buffa-descriptor 0.7.0

Protobuf descriptor types (FileDescriptorProto, DescriptorProto, ...) for buffa
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
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
//! Reflective container access for vtable-mode reflection.
//!
//! This module bridges the reflection value model ([`ValueRef`],
//! [`ReflectList`], [`ReflectMap`]) to the concrete containers generated code
//! holds, so a vtable-mode `impl ReflectMessage` can return
//! `ValueRef::List(&self.tags)` / `ValueRef::Map(&self.labels)` directly:
//!
//! - **View types** — [`RepeatedView`](buffa::RepeatedView) /
//!   [`MapView`](buffa::MapView), borrowing `&str` / `&[u8]` elements.
//! - **Owned types** — `Vec<T>` / `std::collections::HashMap<K, V>`, with owned
//!   `String` / `Vec<u8>` / [`Bytes`](buffa::bytes::Bytes) elements.
//!
//! The generic `ReflectList for Vec<T>` impl also subsumes the bridge
//! [`DynamicMessage`](super::DynamicMessage)'s `Vec<Value>` storage (via
//! `impl ReflectElement for Value`), so there is a single list impl rather than
//! a bespoke one per backing type. [`MapValue`](super::MapValue) keeps its own
//! [`ReflectMap`] impl in `value.rs` (it is a distinct sorted-vec type).
//!
//! ## Why a per-element helper trait, and why it is not a blanket
//!
//! The container impls are fully generic over the element type via
//! [`ReflectElement`] (and [`ReflectMapKey`] for map keys). The tempting shape
//! is a single blanket `impl<M: ReflectMessage> ReflectElement for M` that lets
//! repeated-of-message fall out for free. Rust rejects it (E0119): a
//! trait-bound blanket overlaps with every concrete impl — `impl ReflectElement
//! for i32` included — because the compiler cannot prove `i32: !ReflectMessage`.
//! So the closed set of element types (scalars, `&str`, `&[u8]`,
//! [`EnumValue`](buffa::EnumValue)) gets concrete impls here, and the
//! open-ended cases — message views and bare closed enums — get a one-line
//! `impl ReflectElement` emitted by codegen (a foreign-trait-for-local-type
//! impl, which the orphan rule permits in the consumer crate). That impl is per
//! *type*, not per *field*: a message used in ten repeated fields gets one impl.
//!
//! See `docs/investigations/reflection-vtable.md` §3 for the full rationale.

use alloc::string::String;
use alloc::vec::Vec;

use buffa::bytes::Bytes;
use buffa::{EnumValue, Enumeration, MapView, RepeatedView};

use super::value::{MapKey, MapKeyRef, ReflectList, ReflectMap, Value, ValueRef};

/// Conversion of a single repeated-field element (or map value) to a borrowed
/// [`ValueRef`].
///
/// Implemented here for the closed set of element types the runtime knows:
/// scalars, `&str` / `&[u8]` (view storage), `String` / `Vec<u8>` /
/// [`Bytes`](buffa::bytes::Bytes) (owned storage), [`EnumValue`], and
/// [`Value`](super::Value) (bridge storage). Codegen emits a one-line impl for
/// each generated message type (view and owned, yielding [`ValueRef::Message`])
/// and each bare closed enum (yielding [`ValueRef::EnumNumber`]) — these cannot
/// be covered by a blanket impl without colliding with the scalar impls under
/// Rust's coherence rules.
///
/// # Contract
///
/// `as_value_ref` must return the **same variant** on every call for a given
/// value — the generic [`ReflectList`] / [`ReflectMap`] impls and their callers
/// assume a `Vec<T>` / `HashMap<_, T>` is homogeneous. An implementer must also
/// derive [`Debug`] (the supertrait lets the generic container impls satisfy
/// *their* `Debug` supertrait through the container's derive).
///
/// The non-default `string_type` representations (`SmolStr`, `EcoString`,
/// `CompactString`) have impls gated behind the matching `buffa-descriptor`
/// feature (`smol_str` / `ecow` / `compact_str`), for reflecting a `repeated`
/// field of that type in vtable mode. A consumer building with both that
/// `string_type` and vtable reflection must enable the corresponding feature.
pub trait ReflectElement: core::fmt::Debug {
    /// Borrow this element as a [`ValueRef`].
    #[must_use]
    fn as_value_ref(&self) -> ValueRef<'_>;
}

/// Conversion of a single map key to a borrowed [`MapKeyRef`].
///
/// Implemented for the spec-valid protobuf map-key types: the integral types,
/// `bool`, and `&str`. The `&[u8]` impl exists only for the editions
/// `utf8_validation = NONE` edge case, where a `string` map key is typed as
/// bytes in the view; it converts via UTF-8 and is documented as best-effort
/// (see the impl).
///
/// The [`PartialEq`] supertrait is required so the generic [`ReflectMap`] impl
/// can deduplicate wire entries via [`MapView::iter_unique`](buffa::MapView::iter_unique),
/// matching the bridge path's distinct-key semantics. The [`Debug`] supertrait
/// plays the same role as it does for [`ReflectElement`].
pub trait ReflectMapKey: core::fmt::Debug + PartialEq {
    /// Borrow this key as a [`MapKeyRef`].
    #[must_use]
    fn as_map_key_ref(&self) -> MapKeyRef<'_>;
}

// ── Element impls (closed set) ──────────────────────────────────────────────

macro_rules! impl_scalar_element {
    ($($t:ty => $variant:ident),* $(,)?) => {$(
        impl ReflectElement for $t {
            fn as_value_ref(&self) -> ValueRef<'_> {
                ValueRef::$variant(*self)
            }
        }
    )*};
}

impl_scalar_element! {
    i32 => I32,
    i64 => I64,
    u32 => U32,
    u64 => U64,
    bool => Bool,
    f32 => F32,
    f64 => F64,
}

impl ReflectElement for &str {
    fn as_value_ref(&self) -> ValueRef<'_> {
        // `self` (a `&&str`) auto-derefs to the inner `&str`; an explicit
        // `*self` would trip `clippy::explicit_auto_deref`.
        ValueRef::String(self)
    }
}

impl ReflectElement for &[u8] {
    fn as_value_ref(&self) -> ValueRef<'_> {
        ValueRef::Bytes(self)
    }
}

impl<E: Enumeration> ReflectElement for EnumValue<E> {
    fn as_value_ref(&self) -> ValueRef<'_> {
        ValueRef::EnumNumber(self.to_i32())
    }
}

// ── Owned element impls ─────────────────────────────────────────────────────
//
// Owned messages hold `String` / `Vec<u8>` / `Bytes` (rather than the view
// path's borrowed `&str` / `&[u8]`) and store repeated/map fields as `Vec` /
// `HashMap`. These impls let the generic container impls below cover owned
// collections too. `Value` is included so the bridge `DynamicMessage`'s
// `Vec<Value>` rides the same generic `ReflectList` impl.

impl ReflectElement for String {
    fn as_value_ref(&self) -> ValueRef<'_> {
        ValueRef::String(self)
    }
}

impl ReflectElement for Vec<u8> {
    fn as_value_ref(&self) -> ValueRef<'_> {
        ValueRef::Bytes(self)
    }
}

impl ReflectElement for Bytes {
    fn as_value_ref(&self) -> ValueRef<'_> {
        ValueRef::Bytes(self)
    }
}

impl ReflectElement for Value {
    fn as_value_ref(&self) -> ValueRef<'_> {
        self.as_ref()
    }
}

// Configurable `string_type` representations, for reflecting a `repeated <repr>`
// field in vtable mode. Each is gated on the matching `buffa-descriptor` feature
// (which forwards to `buffa`'s). Only the repeated case needs these: singular
// fields reflect via `&self.field` (any repr derefs to `str`), and `map` string
// keys/values always stay `String`. All reprs satisfy `AsRef<str>`.

#[cfg(feature = "smol_str")]
impl ReflectElement for buffa::smol_str::SmolStr {
    fn as_value_ref(&self) -> ValueRef<'_> {
        ValueRef::String(self.as_ref())
    }
}

#[cfg(feature = "ecow")]
impl ReflectElement for buffa::ecow::EcoString {
    fn as_value_ref(&self) -> ValueRef<'_> {
        ValueRef::String(self.as_ref())
    }
}

#[cfg(feature = "compact_str")]
impl ReflectElement for buffa::compact_str::CompactString {
    fn as_value_ref(&self) -> ValueRef<'_> {
        ValueRef::String(self.as_ref())
    }
}

// ── Map key impls (spec-valid key set) ──────────────────────────────────────

macro_rules! impl_scalar_key {
    ($($t:ty => $variant:ident),* $(,)?) => {$(
        impl ReflectMapKey for $t {
            fn as_map_key_ref(&self) -> MapKeyRef<'_> {
                MapKeyRef::$variant(*self)
            }
        }
    )*};
}

impl_scalar_key! {
    i32 => I32,
    i64 => I64,
    u32 => U32,
    u64 => U64,
    bool => Bool,
}

impl ReflectMapKey for &str {
    fn as_map_key_ref(&self) -> MapKeyRef<'_> {
        MapKeyRef::String(self)
    }
}

impl ReflectMapKey for String {
    fn as_map_key_ref(&self) -> MapKeyRef<'_> {
        MapKeyRef::String(self)
    }
}

impl ReflectMapKey for &[u8] {
    fn as_map_key_ref(&self) -> MapKeyRef<'_> {
        // Reached only for a `string` map key with editions
        // `utf8_validation = NONE`, which the view types as `&[u8]`. The proto
        // type is `string`, so the bytes are normally valid UTF-8; this is a
        // best-effort conversion, not a hard error.
        //
        // Known limitation: the reflection key model ([`MapKey`] / [`MapKeyRef`])
        // represents string keys as UTF-8, with no bytes variant (bytes are not
        // a spec-valid map key). The bridge path shares this constraint — it
        // also stores string keys as `String`. Non-UTF-8 keys therefore collapse
        // to `""`, which can collide with a genuine empty-string key. This is
        // accepted because the case is exotic (a `string` field is normally
        // UTF-8) and faithful representation is not possible without widening
        // the spec-valid key set.
        MapKeyRef::String(core::str::from_utf8(self).unwrap_or(""))
    }
}

// ── Container impls ─────────────────────────────────────────────────────────

impl<T: ReflectElement> ReflectList for RepeatedView<'_, T> {
    fn len(&self) -> usize {
        let elements: &[T] = self;
        elements.len()
    }

    fn get(&self, idx: usize) -> Option<ValueRef<'_>> {
        let elements: &[T] = self;
        elements.get(idx).map(ReflectElement::as_value_ref)
    }

    fn for_each(&self, f: &mut dyn FnMut(ValueRef<'_>)) {
        for elem in self.iter() {
            f(elem.as_value_ref());
        }
    }
}

impl<K: ReflectMapKey, V: ReflectElement> ReflectMap for MapView<'_, K, V> {
    fn len(&self) -> usize {
        // Distinct-key count, matching the bridge path (`MapValue` dedups at
        // construction). `MapView` preserves duplicate wire entries, so a raw
        // `iter().count()` would over-count and diverge from `MapValue::len`.
        self.len_unique()
    }

    fn get(&self, key: &MapKey) -> Option<ValueRef<'_>> {
        // Reverse scan finds the last occurrence first — last-write-wins,
        // matching protobuf map decode semantics and the documented `O(n)`
        // `MapView` lookup. A consumer needing `O(1)` collects into a `HashMap`.
        let want = key.as_ref();
        self.iter()
            .rev()
            .find(|(k, _)| k.as_map_key_ref() == want)
            .map(|(_, v)| v.as_value_ref())
    }

    fn get_str(&self, key: &str) -> Option<ValueRef<'_>> {
        self.iter()
            .rev()
            .find(|(k, _)| matches!(k.as_map_key_ref(), MapKeyRef::String(s) if s == key))
            .map(|(_, v)| v.as_value_ref())
    }

    fn for_each(&self, f: &mut dyn FnMut(MapKeyRef<'_>, ValueRef<'_>)) {
        // Dedup to distinct keys (last-write-wins), matching the bridge path so
        // both reflection modes visit each logical entry exactly once.
        for (k, v) in self.iter_unique() {
            f(k.as_map_key_ref(), v.as_value_ref());
        }
    }
}

// ── Owned containers ────────────────────────────────────────────────────────

/// Owned repeated storage (`Vec<T>`). Also subsumes the bridge
/// `DynamicMessage`'s `Vec<Value>` (via `impl ReflectElement for Value`), so
/// there is no separate `ReflectList for Vec<Value>`.
impl<T: ReflectElement> ReflectList for Vec<T> {
    fn len(&self) -> usize {
        self.as_slice().len()
    }

    fn get(&self, idx: usize) -> Option<ValueRef<'_>> {
        self.as_slice().get(idx).map(ReflectElement::as_value_ref)
    }

    fn for_each(&self, f: &mut dyn FnMut(ValueRef<'_>)) {
        for elem in self {
            f(elem.as_value_ref());
        }
    }
}

/// Owned map storage. Keys are unique by construction (no dedup needed). Vtable
/// reflection requires `std` (the descriptor pool uses `OnceLock`), so the
/// owned-map impl is `std`-gated and targets `std::collections::HashMap` — the
/// concrete type generated code uses for `map` fields under `std`.
#[cfg(feature = "std")]
impl<K: ReflectMapKey, V: ReflectElement> ReflectMap for std::collections::HashMap<K, V> {
    fn len(&self) -> usize {
        Self::len(self)
    }

    fn get(&self, key: &MapKey) -> Option<ValueRef<'_>> {
        let want = key.as_ref();
        self.iter()
            .find(|(k, _)| k.as_map_key_ref() == want)
            .map(|(_, v)| v.as_value_ref())
    }

    fn get_str(&self, key: &str) -> Option<ValueRef<'_>> {
        self.iter()
            .find(|(k, _)| matches!(k.as_map_key_ref(), MapKeyRef::String(s) if s == key))
            .map(|(_, v)| v.as_value_ref())
    }

    fn for_each(&self, f: &mut dyn FnMut(MapKeyRef<'_>, ValueRef<'_>)) {
        for (k, v) in self {
            f(k.as_map_key_ref(), v.as_value_ref());
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::ToString;
    use alloc::vec;
    use alloc::vec::Vec;

    #[test]
    fn repeated_scalar_list() {
        let view: RepeatedView<'_, i32> = RepeatedView::new(vec![7, 11, 13]);
        let list: &dyn ReflectList = &view;
        assert_eq!(list.len(), 3);
        assert!(!list.is_empty());
        assert!(matches!(list.get(1), Some(ValueRef::I32(11))));
        assert!(list.get(3).is_none());

        let mut sum = 0;
        list.for_each(&mut |v| {
            if let ValueRef::I32(n) = v {
                sum += n;
            }
        });
        assert_eq!(sum, 31);
    }

    #[test]
    fn repeated_string_list_is_borrowed() {
        let view: RepeatedView<'_, &str> = RepeatedView::new(vec!["a", "b"]);
        let list: &dyn ReflectList = &view;
        assert_eq!(list.len(), 2);
        assert!(matches!(list.get(0), Some(ValueRef::String("a"))));
        assert!(matches!(list.get(1), Some(ValueRef::String("b"))));
    }

    #[test]
    fn repeated_bytes_list() {
        let a: &[u8] = &[0xDE, 0xAD];
        let b: &[u8] = &[0xBE, 0xEF];
        let view: RepeatedView<'_, &[u8]> = RepeatedView::new(vec![a, b]);
        let list: &dyn ReflectList = &view;
        match list.get(0) {
            Some(ValueRef::Bytes(bytes)) => assert_eq!(bytes, &[0xDE, 0xAD]),
            other => panic!("expected Bytes, got {other:?}"),
        }
    }

    #[test]
    fn empty_list() {
        let view: RepeatedView<'_, i32> = RepeatedView::default();
        let list: &dyn ReflectList = &view;
        assert_eq!(list.len(), 0);
        assert!(list.is_empty());
        assert!(list.get(0).is_none());
    }

    #[test]
    fn map_string_keyed() {
        let view: MapView<'_, &str, i32> = MapView::new(vec![("apples", 3), ("oranges", 7)]);
        let map: &dyn ReflectMap = &view;
        assert_eq!(map.len(), 2);
        assert!(!map.is_empty());

        // The no-alloc CEL hot path.
        assert!(matches!(map.get_str("apples"), Some(ValueRef::I32(3))));
        assert!(matches!(map.get_str("oranges"), Some(ValueRef::I32(7))));
        assert!(map.get_str("durian").is_none());

        // The descriptor-keyed path.
        assert!(matches!(
            map.get(&MapKey::String("apples".into())),
            Some(ValueRef::I32(3))
        ));
        assert!(map.get(&MapKey::String("missing".into())).is_none());

        let mut total = 0;
        map.for_each(&mut |_k, v| {
            if let ValueRef::I32(n) = v {
                total += n;
            }
        });
        assert_eq!(total, 10);
    }

    #[test]
    fn map_int_keyed_get_str_returns_none() {
        let view: MapView<'_, i32, &str> = MapView::new(vec![(1, "one"), (2, "two")]);
        let map: &dyn ReflectMap = &view;
        // get_str on a non-string-keyed map yields None rather than matching.
        assert!(map.get_str("1").is_none());
        assert!(matches!(
            map.get(&MapKey::I32(2)),
            Some(ValueRef::String("two"))
        ));
    }

    #[test]
    fn map_last_write_wins_on_duplicate_keys() {
        // MapView preserves wire order including duplicates; reflection
        // resolves duplicates last-write-wins and presents distinct keys,
        // matching the bridge path (`MapValue` dedups at construction).
        let view: MapView<'_, &str, i32> = MapView::new(vec![("k", 1), ("k", 2)]);
        let map: &dyn ReflectMap = &view;
        assert!(matches!(map.get_str("k"), Some(ValueRef::I32(2))));
        assert!(matches!(
            map.get(&MapKey::String("k".into())),
            Some(ValueRef::I32(2))
        ));
        // Distinct-key count and single visit, not the 2 raw wire entries.
        assert_eq!(map.len(), 1);
        let mut visits = Vec::new();
        map.for_each(&mut |_k, v| {
            if let ValueRef::I32(n) = v {
                visits.push(n);
            }
        });
        assert_eq!(visits, vec![2]);
    }

    #[test]
    fn map_bytes_keyed_utf8() {
        // The `utf8_validation = NONE` edge case: a `string` map key typed as
        // `&[u8]` in the view. Valid UTF-8 bytes reflect as a string key.
        let apples: &[u8] = b"apples";
        let view: MapView<'_, &[u8], i32> = MapView::new(vec![(apples, 5)]);
        let map: &dyn ReflectMap = &view;
        assert_eq!(map.len(), 1);
        assert!(matches!(map.get_str("apples"), Some(ValueRef::I32(5))));
        let mut keys = Vec::new();
        map.for_each(&mut |k, _v| {
            if let MapKeyRef::String(s) = k {
                keys.push(s.to_string());
            }
        });
        assert_eq!(keys, vec!["apples".to_string()]);
    }

    // ── Owned containers (owned-message vtable path) ─────────────────────────

    #[test]
    fn owned_vec_of_string() {
        let v: Vec<String> = vec!["a".to_string(), "b".to_string()];
        let list: &dyn ReflectList = &v;
        assert_eq!(list.len(), 2);
        assert!(matches!(list.get(0), Some(ValueRef::String("a"))));
        assert!(matches!(list.get(1), Some(ValueRef::String("b"))));
    }

    #[test]
    fn owned_vec_of_value_still_reflects() {
        // The bridge `DynamicMessage` repeated storage rides the generic impl
        // via `impl ReflectElement for Value`.
        let v: Vec<Value> = vec![Value::I32(7), Value::I32(11)];
        let list: &dyn ReflectList = &v;
        assert_eq!(list.len(), 2);
        assert!(matches!(list.get(1), Some(ValueRef::I32(11))));
    }

    #[cfg(feature = "std")]
    #[test]
    fn owned_hashmap() {
        let mut m: std::collections::HashMap<String, i32> = std::collections::HashMap::new();
        m.insert("apples".to_string(), 3);
        m.insert("oranges".to_string(), 7);
        let map: &dyn ReflectMap = &m;
        assert_eq!(map.len(), 2);
        assert!(matches!(map.get_str("apples"), Some(ValueRef::I32(3))));
        assert!(matches!(
            map.get(&MapKey::String("oranges".into())),
            Some(ValueRef::I32(7))
        ));
        assert!(map.get_str("durian").is_none());
        let mut total = 0;
        map.for_each(&mut |_k, v| {
            if let ValueRef::I32(n) = v {
                total += n;
            }
        });
        assert_eq!(total, 10);
    }
}