css_lexer/
cow.rs

1use allocator_api2::alloc::{Allocator, Global};
2use allocator_api2::boxed::Box;
3
4/// A Cow-like string that supports custom allocators
5pub enum CowStr<'a, A: Allocator = Global> {
6	Borrowed(&'a str),
7	Owned(Box<str, A>),
8}
9
10impl<'a, A: Allocator> CowStr<'a, A> {
11	pub fn as_str(&self) -> &str {
12		match self {
13			CowStr::Borrowed(s) => s,
14			CowStr::Owned(b) => b,
15		}
16	}
17}
18
19impl<'a, A: Allocator> core::ops::Deref for CowStr<'a, A> {
20	type Target = str;
21	fn deref(&self) -> &Self::Target {
22		self.as_str()
23	}
24}
25
26impl<'a, A: Allocator> AsRef<str> for CowStr<'a, A> {
27	fn as_ref(&self) -> &str {
28		self.as_str()
29	}
30}
31
32impl<'a, A: Allocator> PartialEq<&str> for CowStr<'a, A> {
33	fn eq(&self, other: &&str) -> bool {
34		self.as_str() == *other
35	}
36}
37
38impl<'a, A: Allocator> PartialEq<CowStr<'a, A>> for &str {
39	fn eq(&self, other: &CowStr<'a, A>) -> bool {
40		*self == other.as_str()
41	}
42}
43
44impl<'a, A: Allocator> PartialEq<String> for CowStr<'a, A> {
45	fn eq(&self, other: &String) -> bool {
46		self.as_str() == other
47	}
48}
49
50impl<'a, A: Allocator> PartialEq<CowStr<'a, A>> for String {
51	fn eq(&self, other: &CowStr<'a, A>) -> bool {
52		self == other.as_str()
53	}
54}
55
56impl<'a, A: Allocator> core::fmt::Debug for CowStr<'a, A> {
57	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
58		core::fmt::Debug::fmt(self.as_str(), f)
59	}
60}
61
62impl<'a, A: Allocator> core::fmt::Display for CowStr<'a, A> {
63	fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
64		core::fmt::Display::fmt(self.as_str(), f)
65	}
66}
67
68impl<'a, A: Allocator> From<&'a str> for CowStr<'a, A> {
69	fn from(s: &'a str) -> Self {
70		CowStr::Borrowed(s)
71	}
72}
73
74impl<'a, A: Allocator> From<Box<str, A>> for CowStr<'a, A> {
75	fn from(b: Box<str, A>) -> Self {
76		CowStr::Owned(b)
77	}
78}