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 Line(str);
impl Line {
#[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 Line {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", &self.0)
}
}
impl From<Box<Line>> for Cow<'_, Line> {
fn from(line: Box<Line>) -> Self {
Self::Owned(line)
}
}
impl<'a> From<&'a Line> for Cow<'a, Line> {
fn from(line: &'a Line) -> Self {
Self::Borrowed(line)
}
}
impl TryFrom<String> for Box<Line> {
type Error = &'static str;
fn try_from(val: String) -> Result<Self, Self::Error> {
if val.contains('\n') {
Err("string contains newlines")
} else {
Ok(unsafe { Line::from_string_unchecked(val) })
}
}
}
impl<'a> TryFrom<&'a str> for &'a Line {
type Error = &'static str;
fn try_from(val: &'a str) -> Result<Self, Self::Error> {
if val.contains('\n') {
Err("string contains newlines")
} else {
Ok(unsafe { Line::from_str_unchecked(val) })
}
}
}
impl Borrow<str> for Line {
fn borrow(&self) -> &str {
self.as_str()
}
}
impl Deref for Line {
type Target = str;
fn deref(&self) -> &Self::Target {
&self.0
}
}
impl ToOwned for Line {
type Owned = Box<Line>;
fn to_owned(&self) -> Self::Owned {
unsafe { Self::from_string_unchecked(self.0.to_owned()) }
}
}
impl Clone for Box<Line> {
fn clone(&self) -> Self {
(**self).to_owned()
}
}