refactor(span): make Atom a newtype

This commit is contained in:
Boshen 2023-05-12 13:54:48 +08:00
parent ec092eab01
commit af1cd1c520
No known key found for this signature in database
GPG key ID: 6AC90C77AAAA6ABC
3 changed files with 84 additions and 5 deletions

View file

@ -83,7 +83,7 @@ impl Rule for BadArrayMethodOnArguments {
&& ARRAY_METHODS.binary_search(&name).is_ok()
{
ctx.diagnostic(BadArrayMethodOnArgumentsDiagnostic(
Atom::new(name),
Atom::from(name),
expr.span,
));
}

View file

@ -0,0 +1,81 @@
use std::{borrow::Borrow, fmt, ops::Deref};
use compact_str::CompactString;
#[cfg(feature = "serde")]
use serde::Serialize;
/// Newtype for [`CompactString`]
#[derive(Clone, Eq, Hash)]
#[cfg_attr(feature = "serde", derive(Serialize))]
pub struct Atom(CompactString);
impl Atom {
#[inline]
pub fn as_str(&self) -> &str {
self.0.as_str()
}
}
impl Deref for Atom {
type Target = str;
fn deref(&self) -> &Self::Target {
self.0.as_str()
}
}
impl<'a> From<&'a str> for Atom {
fn from(s: &'a str) -> Self {
Self(s.into())
}
}
impl From<String> for Atom {
fn from(s: String) -> Self {
Self(s.into())
}
}
impl AsRef<str> for Atom {
#[inline]
fn as_ref(&self) -> &str {
self.0.as_str()
}
}
impl Borrow<str> for Atom {
#[inline]
fn borrow(&self) -> &str {
self.0.as_str()
}
}
impl<T: AsRef<str>> PartialEq<T> for Atom {
fn eq(&self, other: &T) -> bool {
self.0.as_str() == other.as_ref()
}
}
impl PartialEq<Atom> for String {
fn eq(&self, other: &Atom) -> bool {
self.as_str() == other.0.as_str()
}
}
impl PartialEq<Atom> for &str {
fn eq(&self, other: &Atom) -> bool {
*self == other.0.as_str()
}
}
impl fmt::Debug for Atom {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.0.as_str(), f)
}
}
impl fmt::Display for Atom {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(self.0.as_str(), f)
}
}

View file

@ -1,13 +1,11 @@
mod atom;
use std::hash::{Hash, Hasher};
use compact_str::CompactString;
pub use atom::Atom;
use miette::{SourceOffset, SourceSpan};
#[cfg(feature = "serde")]
use serde::Serialize;
/// Type alias for [`CompactString`]
pub type Atom = CompactString;
/// Newtype for working with text ranges
///
/// See the [`text-size`](https://docs.rs/text-size) crate for details.