1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
use crate::{AsIs, AsIsMut, Is, IsMut};
use core::borrow::{Borrow, BorrowMut};
use core::cmp::Ordering;
use core::fmt;
use core::hash::{Hash, Hasher};
use core::ops::{Deref, DerefMut};
use core::str::{from_utf8, from_utf8_mut};
#[cfg(not(feature = "alloc"))]
use crate::ToOwned;
#[derive(Default, Clone)]
pub struct StringStub([u8; 0]);
impl Deref for StringStub {
type Target = str;
fn deref(&self) -> &Self::Target {
from_utf8(&self.0).ok().unwrap()
}
}
impl DerefMut for StringStub {
fn deref_mut(&mut self) -> &mut Self::Target {
from_utf8_mut(&mut self.0).ok().unwrap()
}
}
impl Borrow<str> for StringStub {
fn borrow(&self) -> &str {
self
}
}
impl BorrowMut<str> for StringStub {
fn borrow_mut(&mut self) -> &mut str {
self
}
}
impl PartialEq for StringStub {
fn eq(&self, other: &Self) -> bool {
(**self).eq(&**other)
}
}
impl Eq for StringStub {}
impl PartialOrd for StringStub {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
(**self).partial_cmp(&**other)
}
}
impl Ord for StringStub {
fn cmp(&self, other: &Self) -> Ordering {
(**self).cmp(&**other)
}
}
impl Hash for StringStub {
fn hash<H: Hasher>(&self, state: &mut H) {
(**self).hash(state);
}
}
impl fmt::Debug for StringStub {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
(**self).fmt(f)
}
}
#[cfg(not(feature = "alloc"))]
impl ToOwned for str {
type Owned = StringStub;
}
#[cfg(feature = "alloc")]
use alloc::string::String;
#[cfg(not(feature = "alloc"))]
use StringStub as String;
impl AsIs for String {
type Is = String;
fn as_is<'a>(self) -> Is<'a, Self::Is> {
Is::Owned(self)
}
}
impl AsIsMut for String {
fn as_is_mut<'a>(self) -> IsMut<'a, Self::Is> {
IsMut::Owned(self)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn string_stub() {
let s = StringStub::default();
assert_eq!(s.clone(), s);
assert_eq!(s < s, "" < "");
assert_eq!(s.cmp(&s), "".cmp(&""));
}
}