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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
use std::borrow::{Borrow, Cow};
use std::convert::TryFrom;
use std::fmt;
use std::mem;
use std::ops::Deref;
#[repr(transparent)]
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Word(str);
impl Word {
#[must_use]
pub unsafe fn from_str_unchecked(val: &str) -> &Self {
mem::transmute(val)
}
#[must_use]
pub unsafe fn from_string_unchecked(val: String) -> Box<Self> {
let s: Box<str> = val.into_boxed_str();
mem::transmute(s)
}
#[must_use]
pub fn as_str(&self) -> &str {
&self.0
}
#[must_use]
pub fn into_string(self: Box<Self>) -> String {
let s: Box<str> = unsafe { mem::transmute(self) };
String::from(s)
}
}
impl fmt::Display for Word {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.0)
}
}
impl From<Box<Word>> for Cow<'_, Word> {
fn from(word: Box<Word>) -> Self {
Self::Owned(word)
}
}
impl<'a> From<&'a Word> for Cow<'a, Word> {
fn from(word: &'a Word) -> Self {
Self::Borrowed(word)
}
}
impl TryFrom<String> for Box<Word> {
type Error = &'static str;
fn try_from(val: String) -> Result<Self, Self::Error> {
if val.contains(|c| c == '\n' || c == ' ') {
Err("string contains newlines or spaces")
} else {
Ok(unsafe { Word::from_string_unchecked(val) })
}
}
}
impl<'a> TryFrom<&'a str> for &'a Word {
type Error = &'static str;
fn try_from(val: &'a str) -> Result<Self, Self::Error> {
if val.contains(|c| c == '\n' || c == ' ') {
Err("string contains newlines or spaces")
} else {
Ok(unsafe { Word::from_str_unchecked(val) })
}
}
}
impl Borrow<str> for Word {
fn borrow(&self) -> &str {
self.as_str()
}
}
impl Deref for Word {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ToOwned for Word {
type Owned = Box<Word>;
fn to_owned(&self) -> Self::Owned {
unsafe { Self::from_string_unchecked(self.0.to_owned()) }
}
}
impl Clone for Box<Word> {
fn clone(&self) -> Self {
(**self).to_owned()
}
}