stringish/src/impls.rs

116 lines
2.6 KiB
Rust

use std::{
borrow::{Borrow, Cow},
fmt::{Debug, Display},
hash::Hash,
};
use crate::Stringish;
impl Debug for Stringish {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if f.alternate() {
if self.cap == 0 {
f.write_str("Borrowed(")?;
} else {
f.write_str("Owned(")?;
}
}
Debug::fmt(&self[..], f)?;
if f.alternate() {
f.write_str(")")?;
}
Ok(())
}
}
impl Display for Stringish {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Display::fmt(&self[..], f)
}
}
impl PartialEq for Stringish {
fn eq(&self, other: &Self) -> bool {
self[..] == other[..]
}
}
impl Eq for Stringish {}
impl PartialOrd for Stringish {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
self[..].partial_cmp(&other[..])
}
}
impl Ord for Stringish {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self[..].cmp(&other[..])
}
}
impl Hash for Stringish {
fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
self[..].hash(state);
}
}
impl Clone for Stringish {
fn clone(&self) -> Self {
if let Some(true) | None = self.is_borrowed() {
Self { ..*self }
} else {
let mut self_borrowed = Self { cap: 0, ..*self };
self_borrowed.make_owned();
self_borrowed
}
}
}
macro_rules! impl_eq_ord {
($($other:ty),* $(,)?) => {
$(
impl<'a> PartialEq<$other> for Stringish {
fn eq(&self, other: &$other) -> bool {
self[..] == other[..]
}
}
impl<'a> PartialEq<Stringish> for $other {
fn eq(&self, other: &Stringish) -> bool {
self[..] == other[..]
}
}
impl<'a> PartialOrd<$other> for Stringish {
fn partial_cmp(&self, other: &$other) -> Option<std::cmp::Ordering> {
self[..].partial_cmp(&other[..])
}
}
impl<'a> PartialOrd<Stringish> for $other {
fn partial_cmp(&self, other: &Stringish) -> Option<std::cmp::Ordering> {
self[..].partial_cmp(&other[..])
}
}
)*
};
}
impl_eq_ord!(str, &'a str, String, Cow<'a, str>);
impl AsRef<str> for Stringish {
fn as_ref(&self) -> &str {
&self[..]
}
}
impl Borrow<str> for Stringish {
fn borrow(&self) -> &str {
&self[..]
}
}