1use std::{borrow, fmt, hash, ops, slice, str, sync::Arc};
3
4use crate::{Bytes, BytesMut};
5
6#[derive(Clone, Default, Eq, PartialOrd, Ord)]
8pub struct ByteString(Bytes);
9
10impl ByteString {
11 #[inline]
13 #[must_use]
14 pub const fn new() -> Self {
15 ByteString(Bytes::new())
16 }
17
18 #[inline]
20 pub fn as_str(&self) -> &str {
21 self
22 }
23
24 #[inline]
26 pub fn as_slice(&self) -> &[u8] {
27 self.0.as_ref()
28 }
29
30 #[inline]
32 pub fn as_bytes(&self) -> &Bytes {
33 &self.0
34 }
35
36 #[inline]
38 #[must_use]
39 pub fn into_bytes(self) -> Bytes {
40 self.0
41 }
42
43 #[inline]
45 #[must_use]
46 pub const fn from_static(src: &'static str) -> ByteString {
47 Self(Bytes::from_static(src.as_bytes()))
48 }
49
50 #[must_use]
73 pub fn slice(
74 &self,
75 range: impl ops::RangeBounds<usize> + slice::SliceIndex<str> + Clone,
76 ) -> ByteString {
77 ops::Index::index(self.as_ref(), range.clone());
78 ByteString(self.0.slice(range))
79 }
80
81 #[must_use]
105 pub fn split_off(&mut self, at: usize) -> ByteString {
106 let _ = self.split_at(at);
108
109 ByteString(self.0.split_off(at))
110 }
111
112 #[must_use]
136 pub fn split_to(&mut self, at: usize) -> ByteString {
137 let _ = self.split_at(at);
139
140 ByteString(self.0.split_to(at))
141 }
142
143 #[inline]
145 pub fn trimdown(&mut self) {
146 self.0.trimdown();
147 }
148
149 #[inline]
162 pub fn clear(&mut self) {
163 self.0.clear();
164 }
165
166 #[inline]
174 pub const unsafe fn from_bytes_unchecked(src: Bytes) -> ByteString {
175 Self(src)
176 }
177}
178
179impl PartialEq<str> for ByteString {
180 fn eq(&self, other: &str) -> bool {
181 &self[..] == other
182 }
183}
184
185impl<T: AsRef<str>> PartialEq<T> for ByteString {
186 fn eq(&self, other: &T) -> bool {
187 &self[..] == other.as_ref()
188 }
189}
190
191impl PartialEq<ByteString> for &ByteString {
192 fn eq(&self, other: &ByteString) -> bool {
193 self.as_str() == other.as_str()
194 }
195}
196
197impl PartialEq<ByteString> for str {
198 fn eq(&self, other: &ByteString) -> bool {
199 self == other.as_str()
200 }
201}
202
203impl PartialEq<ByteString> for &str {
204 fn eq(&self, other: &ByteString) -> bool {
205 *self == other.as_str()
206 }
207}
208
209impl AsRef<str> for ByteString {
210 #[inline]
211 fn as_ref(&self) -> &str {
212 self
213 }
214}
215
216impl hash::Hash for ByteString {
217 fn hash<H: hash::Hasher>(&self, state: &mut H) {
218 (**self).hash(state);
219 }
220}
221
222impl ops::Deref for ByteString {
223 type Target = str;
224
225 #[inline]
226 fn deref(&self) -> &str {
227 let bytes = self.0.as_ref();
228 unsafe { str::from_utf8_unchecked(bytes) }
231 }
232}
233
234impl borrow::Borrow<str> for ByteString {
235 #[inline]
236 fn borrow(&self) -> &str {
237 self
238 }
239}
240
241impl From<String> for ByteString {
242 #[inline]
243 fn from(value: String) -> Self {
244 Self(Bytes::from(value))
245 }
246}
247
248impl From<&str> for ByteString {
249 #[inline]
250 fn from(value: &str) -> Self {
251 Self(Bytes::copy_from_slice(value.as_ref()))
252 }
253}
254
255impl From<&ByteString> for ByteString {
256 #[inline]
257 fn from(value: &ByteString) -> Self {
258 value.clone()
259 }
260}
261
262impl<'a> From<borrow::Cow<'a, str>> for ByteString {
263 #[inline]
264 fn from(value: borrow::Cow<'a, str>) -> Self {
265 match value {
266 borrow::Cow::Owned(s) => Self::from(s),
267 borrow::Cow::Borrowed(s) => Self::from(s),
268 }
269 }
270}
271
272impl From<Arc<str>> for ByteString {
273 #[inline]
274 fn from(value: Arc<str>) -> Self {
275 ByteString::from_ext(value)
276 }
277}
278
279impl TryFrom<&[u8]> for ByteString {
280 type Error = ();
281
282 #[inline]
283 fn try_from(value: &[u8]) -> Result<Self, Self::Error> {
284 if utf8::is_valid(value) {
285 Ok(ByteString(Bytes::copy_from_slice(value)))
286 } else {
287 Err(())
288 }
289 }
290}
291
292impl TryFrom<Vec<u8>> for ByteString {
293 type Error = ();
294
295 #[inline]
296 fn try_from(value: Vec<u8>) -> Result<Self, Self::Error> {
297 if utf8::is_valid(&value) {
298 Ok(ByteString(Bytes::from(value)))
299 } else {
300 Err(())
301 }
302 }
303}
304
305impl TryFrom<Bytes> for ByteString {
306 type Error = ();
307
308 #[inline]
309 fn try_from(value: Bytes) -> Result<Self, Self::Error> {
310 if utf8::is_valid(&value) {
311 Ok(ByteString(value))
312 } else {
313 Err(())
314 }
315 }
316}
317
318impl TryFrom<&Bytes> for ByteString {
319 type Error = ();
320
321 #[inline]
322 fn try_from(value: &Bytes) -> Result<Self, Self::Error> {
323 if utf8::is_valid(value) {
324 Ok(ByteString(value.clone()))
325 } else {
326 Err(())
327 }
328 }
329}
330
331impl TryFrom<BytesMut> for ByteString {
332 type Error = ();
333
334 #[inline]
335 fn try_from(value: BytesMut) -> Result<Self, Self::Error> {
336 if utf8::is_valid(&value) {
337 Ok(ByteString(value.freeze()))
338 } else {
339 Err(())
340 }
341 }
342}
343
344impl fmt::Debug for ByteString {
345 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
346 (**self).fmt(fmt)
347 }
348}
349
350impl fmt::Display for ByteString {
351 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
352 (**self).fmt(fmt)
353 }
354}
355
356mod serde {
357 use serde::de::{Deserialize, Deserializer};
358 use serde::ser::{Serialize, Serializer};
359
360 use super::ByteString;
361
362 impl Serialize for ByteString {
363 #[inline]
364 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
365 where
366 S: Serializer,
367 {
368 serializer.serialize_str(self.as_ref())
369 }
370 }
371
372 impl<'de> Deserialize<'de> for ByteString {
373 #[inline]
374 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
375 where
376 D: Deserializer<'de>,
377 {
378 String::deserialize(deserializer).map(ByteString::from)
379 }
380 }
381}
382
383#[cfg(feature = "simd")]
384mod utf8 {
385 pub(super) fn is_valid(input: &[u8]) -> bool {
386 simdutf8::basic::from_utf8(input).is_ok()
387 }
388}
389
390#[cfg(not(feature = "simd"))]
391mod utf8 {
392 pub(super) fn is_valid(input: &[u8]) -> bool {
393 std::str::from_utf8(input).is_ok()
394 }
395}
396
397#[cfg(test)]
398mod test {
399 use std::borrow::{Borrow, Cow};
400 use std::collections::hash_map::DefaultHasher;
401 use std::hash::{Hash, Hasher};
402
403 use super::*;
404
405 #[test]
406 fn test_basics() {
407 let mut s = ByteString::from_static("test");
408 s.trimdown();
409 assert_eq!(s, "test");
410 assert_eq!(s, *"test");
411 assert_eq!(s, "test".to_owned());
412 assert_eq!(s.as_str(), "test");
413 assert_eq!(s.as_slice(), b"test");
414 assert_eq!(s.as_bytes(), &Bytes::copy_from_slice(b"test"));
415 assert_eq!(Borrow::<str>::borrow(&s), "test");
416 assert_eq!("test", s);
417 assert_eq!("test", &s);
418
419 assert_eq!(format!("{s}"), "test");
420 assert_eq!(format!("{s:?}"), "\"test\"");
421
422 let b = s.into_bytes();
423 assert_eq!(b, Bytes::copy_from_slice(b"test"));
424
425 let s = unsafe { ByteString::from_bytes_unchecked(b) };
426 assert_eq!(s, "test");
427 assert_eq!(s.slice(0..2), "te");
428
429 let s = ByteString::from(Cow::Borrowed("test"));
430 assert_eq!(s, "test");
431 let mut s = ByteString::from(Cow::Owned("test".to_string()));
432 assert_eq!(s, "test");
433
434 s.clear();
435 assert_eq!(s, "");
436 }
437
438 #[test]
439 fn test_split() {
440 let mut s = ByteString::from_static("helloworld");
441 let s1 = s.split_off(5);
442 assert_eq!(s, "hello");
443 assert_eq!(s1, "world");
444
445 let mut s = ByteString::from_static("helloworld");
446 let s1 = s.split_to(5);
447 assert_eq!(s, "world");
448 assert_eq!(s1, "hello");
449 }
450
451 #[test]
452 fn test_new() {
453 let _: ByteString = ByteString::new();
454 }
455
456 #[test]
457 fn test_hash() {
458 let mut hasher1 = DefaultHasher::default();
459 "str".hash(&mut hasher1);
460
461 let mut hasher2 = DefaultHasher::default();
462 let s = ByteString::from_static("str");
463 s.hash(&mut hasher2);
464 assert_eq!(hasher1.finish(), hasher2.finish());
465 }
466
467 #[test]
468 #[allow(clippy::items_after_statements)]
469 fn test_from() {
470 let s: ByteString = "hello".to_owned().into();
472 assert_eq!(&s, "hello");
473 let t: &str = s.as_ref();
474 assert_eq!(t, "hello");
475
476 let _: ByteString = "str".into();
478
479 static _S: ByteString = ByteString::from_static("hello");
481 let _ = ByteString::from_static("str");
482
483 let s = ByteString::from_static("hello");
484 let s1 = ByteString::from(&s);
485 assert_eq!(s1, "hello");
486 }
487
488 #[test]
489 fn test_try_from() {
490 let _ = ByteString::try_from(&b"nice bytes"[..]).unwrap();
491 assert!(ByteString::try_from(b"\xc3\x28".as_ref()).is_err());
492
493 let _ = ByteString::try_from(b"nice bytes".to_vec()).unwrap();
494 assert!(ByteString::try_from(vec![b'\xc3']).is_err());
495
496 let _ = ByteString::try_from(Bytes::from_static(b"nice bytes")).unwrap();
497 assert!(ByteString::try_from(Bytes::from_static(b"\xc3\x28")).is_err());
498
499 let _ = ByteString::try_from(&Bytes::from_static(b"nice bytes")).unwrap();
500 assert!(ByteString::try_from(&Bytes::from_static(b"\xc3\x28")).is_err());
501
502 let _ =
503 ByteString::try_from(BytesMut::copy_from_slice(&b"nice bytes"[..])).unwrap();
504 assert!(ByteString::try_from(BytesMut::copy_from_slice(b"\xc3\x28")).is_err());
505 }
506
507 #[test]
508 fn test_serialize() {
509 let s: ByteString = serde_json::from_str(r#""nice bytes""#).unwrap();
510 assert_eq!(s, "nice bytes");
511 }
512
513 #[test]
514 fn test_deserialize() {
515 let s = serde_json::to_string(&ByteString::from_static("nice bytes")).unwrap();
516 assert_eq!(s, r#""nice bytes""#);
517 }
518}