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
use crate::{
typing::AnyValue,
error::{ Error, Result }
};
use std::{
convert::TryFrom,
fmt::{ self, Display, Formatter },
ops::{ Deref, DerefMut }
};
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
#[repr(transparent)]
pub struct Utf8String {
inner: String
}
impl Utf8String {
pub fn new<T>(value: T) -> Self where T: ToString {
Self { inner: value.to_string() }
}
}
impl From<String> for Utf8String {
fn from(value: String) -> Self {
Self::new(value)
}
}
impl From<&str> for Utf8String {
fn from(value: &str) -> Self {
Self::new(value)
}
}
impl From<char> for Utf8String {
fn from(value: char) -> Self {
Self::new(value)
}
}
impl TryFrom<AnyValue> for Utf8String {
type Error = Error;
fn try_from(value: AnyValue) -> Result<Self> {
match value {
AnyValue::Utf8String(value) => Ok(value),
value => Err(etype!("Cannot convert {:?} to UTF-8 string", value))
}
}
}
impl Deref for Utf8String {
type Target = String;
fn deref(&self) -> &Self::Target {
&self.inner
}
}
impl DerefMut for Utf8String {
fn deref_mut(&mut self) -> &mut Self::Target {
&mut self.inner
}
}
impl Display for Utf8String {
fn fmt(&self, f: &mut Formatter) -> fmt::Result {
write!(f, "{}", self)
}
}
impl AsRef<String> for Utf8String {
fn as_ref(&self) -> &String {
self
}
}
impl AsMut<String> for Utf8String {
fn as_mut(&mut self) -> &mut String {
self
}
}
impl AsRef<str> for Utf8String {
fn as_ref(&self) -> &str {
self
}
}
impl AsMut<str> for Utf8String {
fn as_mut(&mut self) -> &mut str {
self
}
}
impl From<Utf8String> for String {
fn from(value: Utf8String) -> Self {
value.inner
}
}
impl TryFrom<Utf8String> for char {
type Error = Error;
fn try_from(value: Utf8String) -> Result<Self> {
let mut chars = value.chars();
let first = chars.next()
.ok_or(etype!("Cannot convert an empty string to `char`"))?;
if !chars.next().is_none() {
Err(etype!("Cannot convert a multichar string to a single `char`"))?;
}
Ok(first)
}
}
impl From<Utf8String> for AnyValue {
fn from(value: Utf8String) -> Self {
AnyValue::Utf8String(value)
}
}