Struct latin1str::Latin1Str

source ·
#[repr(transparent)]
pub struct Latin1Str { /* private fields */ }
Expand description

A borrowed latin-1 encoded string (like &str)

Implementations§

Turns some bytes into a Latin1Str slice

Safety

The byte slice may not contain any null bytes

Examples found in repository?
src/lib.rs (line 72)
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
    pub fn encode(string: &str) -> Cow<Latin1Str> {
        let (res, _, _) = WINDOWS_1252.encode(string);
        match res {
            Cow::Owned(o) => Cow::Owned(Self {
                inner: o.into_boxed_slice(),
            }),
            Cow::Borrowed(b) => Cow::Borrowed(unsafe { Latin1Str::from_bytes_unchecked(b) }),
        }
    }

    /// Create a new instance by reading from a [`BufRead`] until a null terminator is found
    /// or the end of the string is reached.
    ///
    /// ```
    /// use std::io::{Read, Cursor};
    /// use latin1str::Latin1String;
    ///
    /// let bytes = b"Hello World!\0";
    /// let mut cur = Cursor::new(bytes);
    /// let s = Latin1String::read_cstring(&mut cur).unwrap();
    /// assert_eq!(s.decode().as_ref(), "Hello World!");
    /// assert_eq!(cur.read(&mut []).ok(), Some(0));
    /// ```
    pub fn read_cstring<R: BufRead>(reader: &mut R) -> Result<Self, io::Error> {
        let mut string: Vec<u8> = Vec::new();
        reader.read_until(0x00, &mut string)?;
        if string.ends_with(&[0x00]) {
            string.pop();
        }
        Ok(Self {
            inner: string.into_boxed_slice(),
        })
    }
}

impl Borrow<Latin1Str> for Latin1String {
    fn borrow(&self) -> &Latin1Str {
        unsafe { Latin1Str::from_bytes_unchecked(&self.inner) }
    }
}

impl Deref for Latin1String {
    type Target = Latin1Str;

    fn deref(&self) -> &Self::Target {
        self.borrow()
    }
}

impl From<Cow<'_, Latin1Str>> for Latin1String {
    fn from(cow: Cow<'_, Latin1Str>) -> Self {
        cow.into_owned()
    }
}

impl From<&Latin1Str> for Latin1String {
    fn from(src: &Latin1Str) -> Latin1String {
        src.to_owned()
    }
}

#[repr(transparent)]
#[derive(PartialEq, PartialOrd, Eq, Ord)]
/// A borrowed latin-1 encoded string (like `&str`)
pub struct Latin1Str {
    #[allow(dead_code)]
    inner: [u8],
}

impl PartialEq<Latin1String> for Latin1Str {
    fn eq(&self, other: &Latin1String) -> bool {
        <Latin1Str as PartialEq>::eq(self, other)
    }
}

impl PartialEq<Latin1String> for &Latin1Str {
    fn eq(&self, other: &Latin1String) -> bool {
        <Latin1Str as PartialEq>::eq(*self, other)
    }
}

impl PartialEq<Latin1Str> for Latin1String {
    fn eq(&self, other: &Latin1Str) -> bool {
        <Latin1Str as PartialEq>::eq(self, other)
    }
}

impl PartialEq<&Latin1Str> for Latin1String {
    fn eq(&self, other: &&Latin1Str) -> bool {
        <Latin1Str as PartialEq>::eq(self, *other)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Latin1String {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        self.deref().serialize(serializer)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Latin1Str {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(self.decode().as_ref())
    }
}

impl fmt::Debug for &'_ Latin1Str {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.decode().fmt(f)
    }
}

impl ToOwned for Latin1Str {
    type Owned = Latin1String;

    fn to_owned(&self) -> Self::Owned {
        Latin1String {
            inner: self.as_bytes().into(),
        }
    }
}

impl Latin1Str {
    /// Turns some bytes into a Latin1Str slice
    ///
    /// ## Safety
    ///
    /// The byte slice may not contain any null bytes
    pub const unsafe fn from_bytes_unchecked(text: &[u8]) -> &Self {
        &*(text as *const [u8] as *const Latin1Str)
    }

    /// Wrap all bytes before the first nul as a [`Latin1Str`]
    ///
    /// This method will never fail
    ///
    /// ```
    /// # use latin1str::Latin1Str;
    /// let s = Latin1Str::from_bytes_until_nul(b"Hello\0World!");
    /// assert_eq!(s.as_bytes(), b"Hello");
    /// let s = Latin1Str::from_bytes_until_nul(b"Hello World!");
    /// assert_eq!(s.as_bytes(), b"Hello World!");
    /// ```
    pub fn from_bytes_until_nul(mut bytes: &[u8]) -> &Self {
        if let Some(nullpos) = memchr(0, bytes) {
            bytes = bytes.split_at(nullpos).0;
        }
        // SAFETY: if there was a nul in here, the if above would have removed it
        unsafe { Self::from_bytes_unchecked(bytes) }
    }

    #[deprecated = "Use `from_bytes_until_nul` instead"]
    /// Alias of [`Latin1Str::from_bytes_until_nul`]
    pub fn new(bytes: &[u8]) -> &Self {
        Self::from_bytes_until_nul(bytes)
    }

    /// Get the bytes of the string
    ///
    /// ```
    /// # use latin1str::Latin1Str;
    /// let s = Latin1Str::from_bytes_until_nul(b"Hello World!");
    /// assert_eq!(s.as_bytes(), b"Hello World!")
    /// ```
    pub const fn as_bytes(&self) -> &[u8] {
        &self.inner
    }

    /// Get the bytes of the string
    pub const fn len(&self) -> usize {
        self.inner.len()
    }

    /// Check whether the str is empty
    ///
    /// ```
    /// # use latin1str::Latin1Str;
    /// assert!(Latin1Str::from_bytes_until_nul(b"").is_empty());
    /// assert!(!Latin1Str::from_bytes_until_nul(b"a").is_empty());
    /// ```
    pub const fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Decode the string
    ///
    /// ```
    /// # use latin1str::Latin1Str;
    /// let s = Latin1Str::from_bytes_until_nul(b"Fr\xFChling");
    /// assert_eq!(s.decode().as_ref(), "Frühling");
    /// ```
    pub fn decode(&self) -> Cow<str> {
        WINDOWS_1252.decode(self.as_bytes()).0
    }
}

impl<'a> From<&'a CStr> for &'a Latin1Str {
    fn from(v: &'a CStr) -> Self {
        // SAFETY: CStr has no internal nul bytes and to_bytes does not expose the trailing one
        unsafe { Latin1Str::from_bytes_unchecked(v.to_bytes()) }
    }

Wrap all bytes before the first nul as a Latin1Str

This method will never fail

let s = Latin1Str::from_bytes_until_nul(b"Hello\0World!");
assert_eq!(s.as_bytes(), b"Hello");
let s = Latin1Str::from_bytes_until_nul(b"Hello World!");
assert_eq!(s.as_bytes(), b"Hello World!");
Examples found in repository?
src/lib.rs (line 227)
226
227
228
    pub fn new(bytes: &[u8]) -> &Self {
        Self::from_bytes_until_nul(bytes)
    }
👎Deprecated: Use from_bytes_until_nul instead

Get the bytes of the string

let s = Latin1Str::from_bytes_until_nul(b"Hello World!");
assert_eq!(s.as_bytes(), b"Hello World!")
Examples found in repository?
src/lib.rs (line 190)
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
    fn to_owned(&self) -> Self::Owned {
        Latin1String {
            inner: self.as_bytes().into(),
        }
    }
}

impl Latin1Str {
    /// Turns some bytes into a Latin1Str slice
    ///
    /// ## Safety
    ///
    /// The byte slice may not contain any null bytes
    pub const unsafe fn from_bytes_unchecked(text: &[u8]) -> &Self {
        &*(text as *const [u8] as *const Latin1Str)
    }

    /// Wrap all bytes before the first nul as a [`Latin1Str`]
    ///
    /// This method will never fail
    ///
    /// ```
    /// # use latin1str::Latin1Str;
    /// let s = Latin1Str::from_bytes_until_nul(b"Hello\0World!");
    /// assert_eq!(s.as_bytes(), b"Hello");
    /// let s = Latin1Str::from_bytes_until_nul(b"Hello World!");
    /// assert_eq!(s.as_bytes(), b"Hello World!");
    /// ```
    pub fn from_bytes_until_nul(mut bytes: &[u8]) -> &Self {
        if let Some(nullpos) = memchr(0, bytes) {
            bytes = bytes.split_at(nullpos).0;
        }
        // SAFETY: if there was a nul in here, the if above would have removed it
        unsafe { Self::from_bytes_unchecked(bytes) }
    }

    #[deprecated = "Use `from_bytes_until_nul` instead"]
    /// Alias of [`Latin1Str::from_bytes_until_nul`]
    pub fn new(bytes: &[u8]) -> &Self {
        Self::from_bytes_until_nul(bytes)
    }

    /// Get the bytes of the string
    ///
    /// ```
    /// # use latin1str::Latin1Str;
    /// let s = Latin1Str::from_bytes_until_nul(b"Hello World!");
    /// assert_eq!(s.as_bytes(), b"Hello World!")
    /// ```
    pub const fn as_bytes(&self) -> &[u8] {
        &self.inner
    }

    /// Get the bytes of the string
    pub const fn len(&self) -> usize {
        self.inner.len()
    }

    /// Check whether the str is empty
    ///
    /// ```
    /// # use latin1str::Latin1Str;
    /// assert!(Latin1Str::from_bytes_until_nul(b"").is_empty());
    /// assert!(!Latin1Str::from_bytes_until_nul(b"a").is_empty());
    /// ```
    pub const fn is_empty(&self) -> bool {
        self.inner.is_empty()
    }

    /// Decode the string
    ///
    /// ```
    /// # use latin1str::Latin1Str;
    /// let s = Latin1Str::from_bytes_until_nul(b"Fr\xFChling");
    /// assert_eq!(s.decode().as_ref(), "Frühling");
    /// ```
    pub fn decode(&self) -> Cow<str> {
        WINDOWS_1252.decode(self.as_bytes()).0
    }

Get the bytes of the string

Check whether the str is empty

assert!(Latin1Str::from_bytes_until_nul(b"").is_empty());
assert!(!Latin1Str::from_bytes_until_nul(b"a").is_empty());

Decode the string

let s = Latin1Str::from_bytes_until_nul(b"Fr\xFChling");
assert_eq!(s.decode().as_ref(), "Frühling");
Examples found in repository?
src/lib.rs (line 181)
180
181
182
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        self.decode().fmt(f)
    }

Trait Implementations§

Immutably borrows from an owned value. Read more
Formats the value using the given formatter. Read more
Converts to this type from the input type.
Converts to this type from the input type.
This method returns an Ordering between self and other. Read more
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method tests for self and other values to be equal, and is used by ==.
This method tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
This method returns an ordering between self and other values if one exists. Read more
This method tests less than (for self and other) and is used by the < operator. Read more
This method tests less than or equal to (for self and other) and is used by the <= operator. Read more
This method tests greater than (for self and other) and is used by the > operator. Read more
This method tests greater than or equal to (for self and other) and is used by the >= operator. Read more
The resulting type after obtaining ownership.
Creates owned data from borrowed data, usually by cloning. Read more
Uses borrowed data to replace owned data, usually by cloning. Read more

Auto Trait Implementations§

Blanket Implementations§

Gets the TypeId of self. Read more
Immutably borrows from an owned value. Read more
Mutably borrows from an owned value. Read more