-
Notifications
You must be signed in to change notification settings - Fork 141
Expand file tree
/
Copy pathstring.rs
More file actions
150 lines (124 loc) · 3.85 KB
/
string.rs
File metadata and controls
150 lines (124 loc) · 3.85 KB
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
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
// SPDX-License-Identifier: Apache-2.0
// SPDX-FileCopyrightText: Copyright the Vortex contributors
use std::fmt::Debug;
use std::fmt::Formatter;
use std::ops::Deref;
use vortex_error::VortexError;
use vortex_error::vortex_err;
use crate::ByteBuffer;
/// A wrapper around a [`ByteBuffer`] that guarantees that the buffer contains valid UTF-8.
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct BufferString(ByteBuffer);
impl BufferString {
/// Creates a new `BufferString` from a [`ByteBuffer`].
///
/// # Safety
/// Assumes that the buffer contains valid UTF-8.
pub const unsafe fn new_unchecked(buffer: ByteBuffer) -> Self {
Self(buffer)
}
/// Creates an empty `BufferString`.
pub fn empty() -> Self {
Self(ByteBuffer::from(vec![]))
}
/// Return a view of the contents of BufferString as an immutable `&str`.
pub fn as_str(&self) -> &str {
// SAFETY: We have already validated that the buffer is valid UTF-8
unsafe { std::str::from_utf8_unchecked(self.0.as_ref()) }
}
/// Returns the inner [`ByteBuffer`].
pub fn into_inner(self) -> ByteBuffer {
self.0
}
/// Returns reference to the inner [`ByteBuffer`].
pub fn inner(&self) -> &ByteBuffer {
&self.0
}
}
impl Debug for BufferString {
fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
f.debug_struct("BufferString")
.field("string", &self.as_str())
.finish()
}
}
impl From<BufferString> for ByteBuffer {
fn from(value: BufferString) -> Self {
value.0
}
}
impl From<String> for BufferString {
fn from(value: String) -> Self {
Self(ByteBuffer::from(value.into_bytes()))
}
}
impl From<&str> for BufferString {
fn from(value: &str) -> Self {
Self(ByteBuffer::from(String::from(value).into_bytes()))
}
}
impl TryFrom<ByteBuffer> for BufferString {
type Error = VortexError;
fn try_from(value: ByteBuffer) -> Result<Self, Self::Error> {
simdutf8::basic::from_utf8(value.as_ref()).map_err(|_| {
#[expect(
clippy::unwrap_used,
reason = "unwrap is intentional - the error was already detected"
)]
// run validation using `compat` package to get more detailed error message
let err = simdutf8::compat::from_utf8(value.as_ref()).unwrap_err();
vortex_err!("invalid utf-8: {err}")
})?;
Ok(Self(value))
}
}
impl TryFrom<&[u8]> for BufferString {
type Error = VortexError;
fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
simdutf8::basic::from_utf8(value).map_err(|_| {
#[expect(
clippy::unwrap_used,
reason = "unwrap is intentional - the error was already detected"
)]
// run validation using `compat` package to get more detailed error message
let err = simdutf8::compat::from_utf8(value).unwrap_err();
vortex_err!("invalid utf-8: {err}")
})?;
Ok(Self(ByteBuffer::from(value.to_vec())))
}
}
impl Deref for BufferString {
type Target = str;
#[inline]
fn deref(&self) -> &Self::Target {
self.as_str()
}
}
impl AsRef<str> for BufferString {
#[inline]
fn as_ref(&self) -> &str {
self.as_str()
}
}
impl AsRef<[u8]> for BufferString {
#[inline]
fn as_ref(&self) -> &[u8] {
self.as_str().as_bytes()
}
}
#[cfg(test)]
mod test {
use crate::Alignment;
use crate::BufferString;
use crate::buffer;
#[test]
fn buffer_string() {
let buf = BufferString::from("hello");
assert_eq!(buf.len(), 5);
assert_eq!(buf.into_inner().alignment(), Alignment::of::<u8>());
}
#[test]
fn buffer_string_non_ut8() {
assert!(BufferString::try_from(buffer![0u8, 255]).is_err());
}
}