Debian Codegraph @

src/bstr.rs

raw symbols SCIP
1 use std::borrow::Cow;
2
3 use ::bstr::{BStr, BString};
4
5 /// Provide a borrowed byte-string view of common string and byte containers.
6 ///
7 /// Unlike [`AsRef`], this conversion deliberately bridges representations such
8 /// as [`String`] and [`Vec<u8>`] to [`BStr`] without allocating.
9 pub trait AsBStr {
10 /// Return this value as a borrowed byte string.
11 fn as_bstr(&self) -> &BStr;
12 }
13
14 /// Provide an optional borrowed byte-string view of common string and byte containers.
15 pub trait AsBStrOpt {
16 /// Return this value as a borrowed byte string, or `None` if it is absent.
17 fn as_bstr_opt(&self) -> Option<&BStr>;
18 }
19
20 impl<T: AsBStr + ?Sized> AsBStrOpt for T {
21 fn as_bstr_opt(&self) -> Option<&BStr> {
22 Some(self.as_bstr())
23 }
24 }
25
26 impl AsBStrOpt for Option<&BStr> {
27 fn as_bstr_opt(&self) -> Option<&BStr> {
28 *self
29 }
30 }
31
32 impl<T: AsBStr + ?Sized> AsBStr for &T {
33 fn as_bstr(&self) -> &BStr {
34 T::as_bstr(self)
35 }
36 }
37
38 impl<T: AsBStr + ?Sized> AsBStr for &mut T {
39 fn as_bstr(&self) -> &BStr {
40 T::as_bstr(self)
41 }
42 }
43
44 impl AsBStr for BStr {
45 fn as_bstr(&self) -> &BStr {
46 self
47 }
48 }
49
50 impl AsBStr for BString {
51 fn as_bstr(&self) -> &BStr {
52 BStr::new(self.as_slice())
53 }
54 }
55
56 impl AsBStr for str {
57 fn as_bstr(&self) -> &BStr {
58 BStr::new(self)
59 }
60 }
61
62 impl AsBStr for String {
63 fn as_bstr(&self) -> &BStr {
64 BStr::new(self)
65 }
66 }
67
68 impl AsBStr for [u8] {
69 fn as_bstr(&self) -> &BStr {
70 BStr::new(self)
71 }
72 }
73
74 impl AsBStr for Vec<u8> {
75 fn as_bstr(&self) -> &BStr {
76 BStr::new(self)
77 }
78 }
79
80 impl<const N: usize> AsBStr for [u8; N] {
81 fn as_bstr(&self) -> &BStr {
82 BStr::new(self)
83 }
84 }
85
86 impl<T> AsBStr for Cow<'_, T>
87 where
88 T: AsBStr + ToOwned + ?Sized,
89 {
90 fn as_bstr(&self) -> &BStr {
91 self.as_ref().as_bstr()
92 }
93 }