pbrs 0.2.0

Pure-Rust Protocol Buffers kernel with the Google protobuf v4 application API
Documentation
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
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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
//! Owned and borrowed protobuf string/bytes types (`ProtoStr` may be invalid UTF-8).
use crate::internal::SealedInternal;
use crate::proxied::{AsView, IntoProxied, IntoView, Proxied};
use std::fmt;
use std::ops::Deref;

/// The bytes were not valid UTF-8.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Utf8Error;

impl fmt::Display for Utf8Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("invalid utf-8")
    }
}

impl std::error::Error for Utf8Error {}

/// Shared immutable view of a protobuf `string` field. May contain invalid UTF-8.
#[repr(transparent)]
pub struct ProtoStr([u8]);

impl<'msg> From<&'msg str> for &'msg ProtoStr {
    fn from(s: &'msg str) -> &'msg ProtoStr {
        ProtoStr::from_str(s)
    }
}

impl ProtoStr {
    pub fn from_bytes(bytes: &[u8]) -> &Self {
        // SAFETY: transparent over [u8]
        unsafe { &*(bytes as *const [u8] as *const ProtoStr) }
    }

    #[expect(
        clippy::should_implement_trait,
        reason = "from_str is a ProtoStr constructor, not the std FromStr trait"
    )]
    pub fn from_str(s: &str) -> &Self {
        Self::from_bytes(s.as_bytes())
    }

    /// View over bytes that may not be UTF-8 (C++ interop / proto2).
    pub fn from_utf8_unchecked(bytes: &[u8]) -> &Self {
        Self::from_bytes(bytes)
    }

    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    pub fn to_str(&self) -> Result<&str, Utf8Error> {
        std::str::from_utf8(&self.0).map_err(|_| Utf8Error)
    }
}

impl fmt::Debug for ProtoStr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.to_str() {
            Ok(s) => fmt::Debug::fmt(s, f),
            Err(_) => f.debug_tuple("ProtoStr").field(&&self.0).finish(),
        }
    }
}

impl PartialEq for ProtoStr {
    fn eq(&self, other: &Self) -> bool {
        self.0 == other.0
    }
}
impl Eq for ProtoStr {}

impl PartialEq<str> for ProtoStr {
    fn eq(&self, other: &str) -> bool {
        self.as_bytes() == other.as_bytes()
    }
}

impl PartialEq<&str> for ProtoStr {
    fn eq(&self, other: &&str) -> bool {
        self.as_bytes() == other.as_bytes()
    }
}

impl PartialEq<ProtoString> for ProtoStr {
    fn eq(&self, other: &ProtoString) -> bool {
        self.as_bytes() == other.as_bytes()
    }
}

impl fmt::Display for ProtoStr {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Display::fmt(&String::from_utf8_lossy(self.as_bytes()), f)
    }
}

const INLINE_CAP: usize = 23;

#[derive(Clone)]
enum Repr {
    Inline { len: u8, data: [u8; INLINE_CAP] },
    Heap(Vec<u8>),
}

/// Owned protobuf `string`. May contain invalid UTF-8 (C++ interop).
#[derive(Clone)]
pub struct ProtoString(Repr);

impl Default for ProtoString {
    fn default() -> Self {
        Self::new()
    }
}

impl ProtoString {
    pub fn new() -> Self {
        Self(Repr::Inline {
            len: 0,
            data: [0; INLINE_CAP],
        })
    }

    pub fn from_bytes(bytes: &[u8]) -> Self {
        if bytes.len() <= INLINE_CAP {
            let mut data = [0u8; INLINE_CAP];
            data[..bytes.len()].copy_from_slice(bytes);
            Self(Repr::Inline {
                len: bytes.len() as u8,
                data,
            })
        } else {
            Self(Repr::Heap(bytes.to_vec()))
        }
    }

    pub fn as_view(&self) -> &ProtoStr {
        ProtoStr::from_bytes(self.as_bytes())
    }

    pub fn as_bytes(&self) -> &[u8] {
        match &self.0 {
            Repr::Inline { len, data } => &data[..*len as usize],
            Repr::Heap(v) => v,
        }
    }

    pub fn to_str(&self) -> Result<&str, Utf8Error> {
        self.as_view().to_str()
    }

    pub fn clear(&mut self) {
        self.0 = Repr::Inline {
            len: 0,
            data: [0; INLINE_CAP],
        };
    }

    pub fn is_empty(&self) -> bool {
        match &self.0 {
            Repr::Inline { len, .. } => *len == 0,
            Repr::Heap(v) => v.is_empty(),
        }
    }
}

impl PartialEq for ProtoString {
    fn eq(&self, other: &Self) -> bool {
        self.as_bytes() == other.as_bytes()
    }
}
impl PartialEq<str> for ProtoString {
    fn eq(&self, other: &str) -> bool {
        self.as_bytes() == other.as_bytes()
    }
}
impl PartialEq<&str> for ProtoString {
    fn eq(&self, other: &&str) -> bool {
        self.as_bytes() == other.as_bytes()
    }
}
impl Eq for ProtoString {}
impl PartialOrd for ProtoString {
    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
        Some(self.cmp(other))
    }
}
impl Ord for ProtoString {
    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
        self.as_bytes().cmp(other.as_bytes())
    }
}
impl std::hash::Hash for ProtoString {
    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
        self.as_bytes().hash(state);
    }
}

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

impl From<&str> for ProtoString {
    fn from(s: &str) -> Self {
        Self::from_bytes(s.as_bytes())
    }
}

impl From<String> for ProtoString {
    fn from(s: String) -> Self {
        if s.len() <= INLINE_CAP {
            Self::from_bytes(s.as_bytes())
        } else {
            Self(Repr::Heap(s.into_bytes()))
        }
    }
}

impl From<&ProtoStr> for ProtoString {
    fn from(s: &ProtoStr) -> Self {
        Self::from_bytes(s.as_bytes())
    }
}

impl Deref for ProtoString {
    type Target = ProtoStr;
    fn deref(&self) -> &ProtoStr {
        self.as_view()
    }
}

impl SealedInternal for ProtoString {}
impl Proxied for ProtoString {
    type View<'msg> = &'msg ProtoStr;
}
impl AsView for ProtoString {
    type Proxied = Self;
    fn as_view(&self) -> &ProtoStr {
        ProtoString::as_view(self)
    }
}
impl<'msg> IntoView<'msg> for &'msg ProtoStr {
    fn into_view<'shorter>(self) -> &'shorter ProtoStr
    where
        'msg: 'shorter,
    {
        self
    }
}
impl SealedInternal for &ProtoStr {}
impl AsView for &ProtoStr {
    type Proxied = ProtoString;
    fn as_view(&self) -> &ProtoStr {
        self
    }
}

impl IntoProxied<ProtoString> for &str {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoString {
        ProtoString::from(self)
    }
}
impl IntoProxied<ProtoString> for String {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoString {
        ProtoString::from(self)
    }
}
impl IntoProxied<ProtoString> for &String {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoString {
        ProtoString::from(self.as_str())
    }
}
impl IntoProxied<ProtoString> for &ProtoStr {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoString {
        ProtoString::from(self)
    }
}
impl IntoProxied<ProtoString> for std::borrow::Cow<'_, str> {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoString {
        ProtoString::from(self.as_ref())
    }
}
impl IntoProxied<ProtoString> for Box<str> {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoString {
        ProtoString::from(self.as_ref())
    }
}
impl IntoProxied<ProtoString> for std::rc::Rc<str> {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoString {
        ProtoString::from(self.as_ref())
    }
}
impl IntoProxied<ProtoString> for std::sync::Arc<str> {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoString {
        ProtoString::from(self.as_ref())
    }
}
impl IntoProxied<ProtoString> for std::ffi::OsString {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoString {
        ProtoString::from(self.to_string_lossy().as_ref())
    }
}
impl IntoProxied<ProtoString> for &std::ffi::OsStr {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoString {
        ProtoString::from(self.to_string_lossy().as_ref())
    }
}

/// Owned protobuf `bytes`.
///
/// Backed by [`Bytes`](bytes::Bytes) (PK-09): cheap to clone, and convertible
/// to/from shared buffers without copying. The `&[u8]` accessors are
/// unchanged.
#[derive(Clone, Default, PartialEq, Eq, Hash)]
pub struct ProtoBytes(bytes::Bytes);

impl ProtoBytes {
    pub fn new() -> Self {
        Self(bytes::Bytes::new())
    }

    pub fn as_view(&self) -> &[u8] {
        &self.0
    }

    pub fn as_bytes(&self) -> &[u8] {
        &self.0
    }

    /// This value as a shareable buffer: a refcount clone, never a copy.
    pub fn as_shared(&self) -> bytes::Bytes {
        self.0.clone()
    }

    /// Owned copy of the contents. The escape hatch when a value must not
    /// retain a shared buffer (PK-09 `detach`).
    pub fn into_vec(self) -> Vec<u8> {
        self.0.to_vec()
    }

    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    pub fn clear(&mut self) {
        self.0 = bytes::Bytes::new();
    }
}

impl fmt::Debug for ProtoBytes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_tuple("ProtoBytes").field(&self.as_bytes()).finish()
    }
}

impl From<&[u8]> for ProtoBytes {
    fn from(v: &[u8]) -> Self {
        Self(bytes::Bytes::copy_from_slice(v))
    }
}
impl From<Vec<u8>> for ProtoBytes {
    fn from(v: Vec<u8>) -> Self {
        Self(bytes::Bytes::from(v))
    }
}
impl From<bytes::Bytes> for ProtoBytes {
    fn from(v: bytes::Bytes) -> Self {
        Self(v)
    }
}
impl<const N: usize> From<&[u8; N]> for ProtoBytes {
    fn from(v: &[u8; N]) -> Self {
        Self(bytes::Bytes::copy_from_slice(v))
    }
}

impl SealedInternal for ProtoBytes {}
impl Proxied for ProtoBytes {
    type View<'msg> = &'msg [u8];
}
impl AsView for ProtoBytes {
    type Proxied = Self;
    fn as_view(&self) -> &[u8] {
        &self.0
    }
}
impl IntoProxied<ProtoBytes> for &[u8] {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoBytes {
        ProtoBytes::from(self)
    }
}
impl IntoProxied<ProtoBytes> for Vec<u8> {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoBytes {
        ProtoBytes::from(self)
    }
}
impl IntoProxied<ProtoBytes> for bytes::Bytes {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoBytes {
        ProtoBytes::from(self)
    }
}
impl IntoProxied<ProtoBytes> for &Vec<u8> {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoBytes {
        ProtoBytes::from(self.as_slice())
    }
}
impl<const N: usize> IntoProxied<ProtoBytes> for &[u8; N] {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoBytes {
        ProtoBytes::from(self.as_slice())
    }
}
impl IntoProxied<ProtoBytes> for std::borrow::Cow<'_, [u8]> {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoBytes {
        ProtoBytes::from(self.as_ref())
    }
}
impl IntoProxied<ProtoBytes> for Box<[u8]> {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoBytes {
        ProtoBytes::from(self.as_ref())
    }
}
impl IntoProxied<ProtoBytes> for std::rc::Rc<[u8]> {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoBytes {
        ProtoBytes::from(self.as_ref())
    }
}
impl IntoProxied<ProtoBytes> for std::sync::Arc<[u8]> {
    fn into_proxied(self, _private: crate::internal::Private) -> ProtoBytes {
        ProtoBytes::from(self.as_ref())
    }
}

impl SealedInternal for &[u8] {}
impl AsView for &[u8] {
    type Proxied = ProtoBytes;
    fn as_view(&self) -> &[u8] {
        self
    }
}
impl<'msg> IntoView<'msg> for &'msg [u8] {
    fn into_view<'shorter>(self) -> &'shorter [u8]
    where
        'msg: 'shorter,
    {
        self
    }
}