Skip to main content

protocrap/
descriptor_pool.rs

1//! Dynamic message pool for runtime schema handling.
2//!
3//! The [`DescriptorPool`] allows decoding and encoding protobuf messages when the
4//! schema is only known at runtime. It builds lookup tables from `FileDescriptorProto`
5//! messages, enabling dynamic operations without generated code.
6//!
7//! # Use Cases
8//!
9//! - Generic protobuf processors (proxies, loggers, transformers)
10//! - Schema-driven tools that load `.proto` definitions at runtime
11//! - Testing and debugging tools
12//!
13//! # Example
14//!
15//! ```
16//! use protocrap::{ProtobufRef, ProtobufMut, arena::Arena, descriptor_pool::DescriptorPool};
17//! use protocrap::google::protobuf::FileDescriptorProto;
18//! use allocator_api2::alloc::Global;
19//!
20//! // Build pool from file descriptors
21//! let mut pool = DescriptorPool::new(&Global);
22//! let file_desc = FileDescriptorProto::ProtoType::file_descriptor();
23//! pool.add_file(file_desc);
24//!
25//! // Decode a message dynamically
26//! let bytes = file_desc.encode_vec::<32>().unwrap();
27//! let mut arena = Arena::new(&Global);
28//! let mut msg = pool.create_message(
29//!     "google.protobuf.FileDescriptorProto",
30//!     &mut arena,
31//! ).unwrap();
32//! msg.decode_flat::<32>(&mut arena, &bytes);
33//!
34//! // Inspect fields
35//! println!("{:?}", msg);
36//! ```
37
38use crate::{
39    arena::Arena,
40    base::{Message, Object},
41    google::protobuf::{
42        DescriptorProto::ProtoType as DescriptorProto,
43        FieldDescriptorProto::ProtoType as FieldDescriptorProto,
44        FileDescriptorProto::ProtoType as FileDescriptorProto,
45    },
46    reflection::{
47        DynamicMessage, field_kind_tokens, is_in_oneof, is_message, is_repeated, needs_has_bit,
48    },
49    tables::Table,
50};
51
52/// A registry of message types for dynamic protobuf operations.
53///
54/// Maintains an internal arena for table storage and a map from fully-qualified
55/// message names to their encoding/decoding tables.
56pub struct DescriptorPool<'alloc> {
57    /// Arena used for allocating message data during decode operations.
58    pub arena: Arena<'alloc>,
59    tables: std::collections::HashMap<std::string::String, &'alloc mut Table>,
60}
61
62impl<'alloc> DescriptorPool<'alloc> {
63    /// Create a new empty descriptor pool with the given allocator.
64    pub fn new(alloc: &'alloc dyn crate::Allocator) -> Self {
65        DescriptorPool {
66            arena: Arena::new(alloc),
67            tables: std::collections::HashMap::new(),
68        }
69    }
70
71    /// Strip leading dot from type name (protobuf returns ".package.Type", we store "package.Type")
72    fn normalize_type_name(type_name: &str) -> &str {
73        type_name.strip_prefix('.').unwrap_or(type_name)
74    }
75
76    /// Add a FileDescriptorProto to the pool
77    pub fn add_file(&mut self, file: &'alloc FileDescriptorProto) -> Result<(), crate::Error<core::alloc::LayoutError>> {
78        let package = if file.has_package() {
79            file.package()
80        } else {
81            ""
82        };
83
84        // First pass: build all tables (child table pointers may be null)
85        for message in file.message_type() {
86            let full_name = if package.is_empty() {
87                message.name().to_string()
88            } else {
89                format!("{}.{}", package, message.name())
90            };
91            self.add_message(message, &full_name, file.get_syntax())?;
92        }
93
94        // Second pass: patch aux entries with correct child table pointers
95        for message in file.message_type() {
96            let full_name = if package.is_empty() {
97                message.name().to_string()
98            } else {
99                format!("{}.{}", package, message.name())
100            };
101            self.patch_message_aux_entries(&full_name)?;
102        }
103        Ok(())
104    }
105
106    fn add_message(
107        &mut self,
108        message: &'alloc DescriptorProto,
109        full_name: &str,
110        syntax: Option<&str>,
111    ) -> Result<(), crate::Error<core::alloc::LayoutError>> {
112        // Build table from descriptor
113        let table = self.build_table_from_descriptor(message, syntax)?;
114        self.tables.insert(full_name.to_string(), table);
115
116        // Add nested types
117        for nested in message.nested_type() {
118            let nested_full_name = format!("{}.{}", full_name, nested.name());
119            self.add_message(nested, &nested_full_name, syntax)?;
120        }
121        Ok(())
122    }
123
124    fn patch_message_aux_entries(&mut self, full_name: &str) -> Result<(), crate::Error<core::alloc::LayoutError>> {
125        use crate::tables::AuxTableEntry;
126
127        let table = match self.tables.get_mut(full_name) {
128            Some(t) => &mut **t,
129            None => return Ok(()),
130        };
131
132        let descriptor = table.descriptor;
133
134        // Count aux entries (message fields)
135        let num_aux_entries = descriptor.field().iter().filter(|f| is_message(f)).count();
136        if num_aux_entries == 0 {
137            return Ok(());
138        }
139
140        // Get aux entry pointer - must use same Layout::extend logic as build_table_from_descriptor
141        unsafe {
142            // Recalculate aux offset using Layout::extend (accounts for padding)
143            let table_layout = core::alloc::Layout::new::<Table>();
144            let (_, aux_offset_from_table) = table_layout
145                .extend(
146                    core::alloc::Layout::array::<crate::decoding::TableEntry>(
147                        table.num_decode_entries as usize,
148                    )?,
149                )?
150                .0
151                .extend(core::alloc::Layout::array::<AuxTableEntry>(num_aux_entries)?)?;
152
153            let aux_ptr =
154                (table as *mut Table as *mut u8).add(aux_offset_from_table) as *mut AuxTableEntry;
155
156            // Patch each aux entry with the correct child table pointer
157            let mut aux_idx = 0;
158            for field in descriptor.field() {
159                if is_message(field) {
160                    let child_type_name = Self::normalize_type_name(field.type_name());
161                    let child_table_ptr = self
162                        .tables
163                        .get_mut(child_type_name)
164                        .map(|t| *t as *mut Table)
165                        .unwrap_or(core::ptr::null_mut());
166
167                    if !child_table_ptr.is_null() {
168                        (*aux_ptr.add(aux_idx)).child_table = child_table_ptr;
169                    }
170                    aux_idx += 1;
171                }
172            }
173        }
174
175        // Patch nested types
176        for nested in descriptor.nested_type() {
177            let nested_full_name = format!("{}.{}", full_name, nested.name());
178            self.patch_message_aux_entries(&nested_full_name)?;
179        }
180        Ok(())
181    }
182
183    /// Get a table by message type name
184    pub fn get_table(&self, message_type: &str) -> Option<&Table> {
185        self.tables.get(message_type).map(|t| &**t)
186    }
187
188    /// Create an empty message of the given type, allocated in the arena.
189    pub fn create_message<'pool, 'msg>(
190        &'pool self,
191        message_type: &str,
192        arena: &mut Arena<'msg>,
193    ) -> Result<DynamicMessage<'pool, 'msg>, crate::Error<core::alloc::LayoutError>> {
194        let table = &**self
195            .tables
196            .get(message_type)
197            .ok_or(crate::Error::MessageNotFound)?;
198
199        // Allocate object with proper alignment (8 bytes for all protobuf types)
200        let layout = core::alloc::Layout::from_size_align(table.size as usize, 8)?;
201        let ptr = arena.alloc_raw(layout)?.as_ptr() as *mut Object;
202        assert!((ptr as usize) & 7 == 0);
203        let object = unsafe {
204            // Zero-initialize the object
205            core::ptr::write_bytes(ptr as *mut u8, 0, table.size as usize);
206            &mut *ptr
207        };
208
209        Ok(DynamicMessage { object, table })
210    }
211
212    // TODO: improve lifetime annotations
213    #[allow(clippy::mut_from_ref)]
214    fn build_table_from_descriptor(
215        &mut self,
216        descriptor: &'alloc DescriptorProto,
217        syntax: Option<&str>,
218    ) -> Result<&'alloc mut Table, crate::Error<core::alloc::LayoutError>> {
219        use crate::{
220            decoding, encoding, reflection::calculate_tag_with_syntax, tables::AuxTableEntry,
221        };
222
223        // Calculate sizes
224        let num_fields = descriptor.field().len();
225        let num_has_bits = descriptor
226            .field()
227            .iter()
228            .filter(|f| needs_has_bit(f))
229            .count();
230        let has_bits_words = num_has_bits.div_ceil(32);
231        let oneof_count = descriptor.oneof_decl().len();
232        let metadata_words = has_bits_words + oneof_count;
233        let metadata_size = (metadata_words * 4) as u32;
234
235        // Calculate max field number for sparse decode table
236        let max_field_number = descriptor
237            .field()
238            .iter()
239            .map(|f| f.number())
240            .max()
241            .unwrap_or(0);
242
243        if max_field_number > 2047 {
244            panic!("Field numbers > 2047 not supported yet");
245        }
246
247        let num_decode_entries = (max_field_number + 1) as usize;
248
249        // Group fields by oneof_index and calculate union sizes
250        let mut oneof_sizes: std::vec::Vec<(usize, usize)> = vec![(0, 1); oneof_count]; // (size, align)
251        for field in descriptor.field() {
252            if is_in_oneof(field) {
253                let oneof_idx = field.oneof_index() as usize;
254                let field_size = self.field_size(field) as usize;
255                let field_align = self.field_align(field) as usize;
256                if field_size > oneof_sizes[oneof_idx].0 {
257                    oneof_sizes[oneof_idx].0 = field_size;
258                }
259                if field_align > oneof_sizes[oneof_idx].1 {
260                    oneof_sizes[oneof_idx].1 = field_align;
261                }
262            }
263        }
264
265        // Calculate field offsets and total size using Layout::extend for proper padding
266        // Start with metadata layout (always u32 array, so alignment is 4)
267        let mut layout = core::alloc::Layout::from_size_align(metadata_size as usize, 4)?;
268
269        // First pass: calculate offsets for regular fields (not in oneof)
270        // Store in a map by field number
271        let mut regular_field_offsets = std::collections::HashMap::<i32, u32>::new();
272        for field in descriptor.field() {
273            if is_in_oneof(field) {
274                continue; // Skip oneof fields, handled separately
275            }
276            let field_size = self.field_size(field);
277            let field_align = self.field_align(field);
278            let field_layout =
279                core::alloc::Layout::from_size_align(field_size as usize, field_align as usize)
280                    .unwrap();
281
282            let (new_layout, offset) = layout.extend(field_layout)?;
283            regular_field_offsets.insert(field.number(), offset as u32);
284            layout = new_layout;
285        }
286
287        // Then add unions for each oneof
288        let mut oneof_offsets = std::vec::Vec::new();
289        for (oneof_idx, &(size, align)) in oneof_sizes.iter().enumerate() {
290            if size > 0 {
291                let union_layout = core::alloc::Layout::from_size_align(size, align)?;
292                let (new_layout, offset) = layout.extend(union_layout)?;
293                oneof_offsets.push((oneof_idx, offset as u32));
294                layout = new_layout;
295            }
296        }
297
298        // Build field_offsets in proto definition order (matching codegen)
299        let mut field_offsets = std::vec::Vec::new();
300        for field in descriptor.field() {
301            let offset = if is_in_oneof(field) {
302                let oneof_idx = field.oneof_index() as usize;
303                oneof_offsets
304                    .iter()
305                    .find(|(idx, _)| *idx == oneof_idx)
306                    .map(|(_, off)| *off)
307                    .unwrap_or(0)
308            } else {
309                regular_field_offsets[&field.number()]
310            };
311            field_offsets.push((field, offset));
312        }
313
314        // Pad to struct alignment
315        let layout = layout.pad_to_align();
316        let total_size = layout.size() as u32;
317
318        // Count message fields for aux entries
319        let num_aux_entries = descriptor
320            .field()
321            .iter()
322            .filter(|f| is_message(&**f))
323            .count();
324
325        // Allocate table with entries - use Layout::extend to handle padding correctly
326        let encode_layout = core::alloc::Layout::array::<encoding::TableEntry>(num_fields)?;
327        let (layout, table_offset) = encode_layout
328            .extend(core::alloc::Layout::new::<Table>())?;
329        let (layout, decode_offset) = layout
330            .extend(core::alloc::Layout::array::<decoding::TableEntry>(num_decode_entries)?)?;
331        let (layout, aux_offset) = layout
332            .extend(core::alloc::Layout::array::<AuxTableEntry>(num_aux_entries)?)?;
333
334        let base_ptr = self.arena.alloc_raw(layout)?.as_ptr();
335
336        unsafe {
337            let encode_ptr = base_ptr as *mut encoding::TableEntry;
338            let table_ptr = base_ptr.add(table_offset) as *mut Table;
339            let decode_ptr = base_ptr.add(decode_offset) as *mut decoding::TableEntry;
340            let aux_ptr = base_ptr.add(aux_offset) as *mut AuxTableEntry;
341
342            // Initialize Table header
343            (*table_ptr).num_encode_entries = num_fields as u16;
344            (*table_ptr).num_decode_entries = num_decode_entries as u16;
345            (*table_ptr).size = total_size as u16;
346            // SAFETY: descriptor lives in arena with 'alloc lifetime, which outlives the table usage
347            (*table_ptr).descriptor = core::mem::transmute::<
348                &'alloc DescriptorProto,
349                &'static DescriptorProto,
350            >(descriptor);
351
352            // Build aux index map for message fields and has_bit index map
353            let mut aux_index_map = std::collections::HashMap::<i32, usize>::new();
354            let mut has_bit_index_map = std::collections::HashMap::<i32, u32>::new();
355            let mut aux_idx = 0;
356            let mut has_bit_idx = 0u32;
357            for field in descriptor.field() {
358                if is_message(field) {
359                    aux_index_map.insert(field.number(), aux_idx);
360                    aux_idx += 1;
361                }
362                if needs_has_bit(field) {
363                    has_bit_index_map.insert(field.number(), has_bit_idx);
364                    has_bit_idx += 1;
365                }
366            }
367
368            // Build encode entries
369            let mut has_bit_idx = 0u8;
370            for (i, &(field, offset)) in field_offsets.iter().enumerate() {
371                let has_bit = if is_in_oneof(&field) {
372                    // Oneof field: has_bit = 0x80 | discriminant_word_idx
373                    let oneof_idx = field.oneof_index() as usize;
374                    (0x80 | (has_bits_words + oneof_idx)) as u8
375                } else if needs_has_bit(&field) {
376                    let bit = has_bit_idx;
377                    has_bit_idx += 1;
378                    bit
379                } else {
380                    0
381                };
382
383                let entry_offset = if is_message(&field) {
384                    // For message fields, offset points to aux entry
385                    let aux_index = aux_index_map[&field.number()];
386                    let aux_offset =
387                        (aux_ptr as usize) + aux_index * core::mem::size_of::<AuxTableEntry>();
388                    let table_addr = table_ptr as usize;
389                    (aux_offset - table_addr) as u16
390                } else {
391                    offset as u16
392                };
393
394                encode_ptr.add(i).write(encoding::TableEntry {
395                    has_bit,
396                    kind: field_kind_tokens(&field),
397                    offset: entry_offset,
398                    encoded_tag: calculate_tag_with_syntax(&field, syntax),
399                });
400            }
401
402            // Build decode entries - sparse array indexed by field number
403            for field_number in 0..=max_field_number {
404                if let Some(field) = descriptor
405                    .field()
406                    .iter()
407                    .find(|f| f.number() == field_number)
408                {
409                    let offset = field_offsets
410                        .iter()
411                        .find(|(f, _)| f.number() == field_number)
412                        .map(|(_, o)| *o)
413                        .unwrap_or(0);
414
415                    // Check oneof first (applies to all field types including message)
416                    let entry = if is_in_oneof(&**field) {
417                        // Oneof field: has_bit = 0x80 | discriminant_word_idx
418                        let oneof_idx = field.oneof_index() as usize;
419                        let has_bit = (0x80 | (has_bits_words + oneof_idx)) as u32;
420
421                        if is_message(&**field) {
422                            // Oneof message field - offset points to aux entry
423                            let aux_index = aux_index_map[&field_number];
424                            let aux_offset = (aux_ptr as usize)
425                                + aux_index * core::mem::size_of::<AuxTableEntry>();
426                            let table_addr = table_ptr as usize;
427                            decoding::TableEntry::new(
428                                field_kind_tokens(field),
429                                has_bit,
430                                aux_offset - table_addr,
431                            )
432                        } else {
433                            decoding::TableEntry::new(
434                                field_kind_tokens(field),
435                                has_bit,
436                                offset as usize,
437                            )
438                        }
439                    } else if is_message(&**field) {
440                        // Regular message field - offset points to aux entry
441                        let aux_index = aux_index_map[&field_number];
442                        let aux_offset =
443                            (aux_ptr as usize) + aux_index * core::mem::size_of::<AuxTableEntry>();
444                        let table_addr = table_ptr as usize;
445                        decoding::TableEntry::new(
446                            field_kind_tokens(field),
447                            0, // has_bit not used for message fields
448                            aux_offset - table_addr,
449                        )
450                    } else {
451                        let has_bit = if needs_has_bit(&**field) {
452                            has_bit_index_map[&field_number]
453                        } else {
454                            0
455                        };
456                        decoding::TableEntry::new(
457                            field_kind_tokens(field),
458                            has_bit,
459                            offset as usize,
460                        )
461                    };
462                    decode_ptr.add(field_number as usize).write(entry);
463                } else {
464                    // Empty entry for unused field number
465                    decode_ptr
466                        .add(field_number as usize)
467                        .write(decoding::TableEntry(0));
468                }
469            }
470
471            // Build aux entries for message fields
472            for (aux_index, (field, offset)) in field_offsets
473                .iter()
474                .filter(|(f, _)| is_message(&**f))
475                .enumerate()
476            {
477                let child_type_name = Self::normalize_type_name(field.type_name());
478                let child_table_ptr = self
479                    .tables
480                    .get_mut(child_type_name)
481                    .map(|t| *t as *mut Table)
482                    .unwrap_or(core::ptr::null_mut());
483
484                aux_ptr.add(aux_index).write(AuxTableEntry {
485                    offset: *offset,
486                    child_table: child_table_ptr,
487                });
488            }
489
490            Ok(&mut *table_ptr)
491        }
492    }
493
494    fn field_size(&self, field: &FieldDescriptorProto) -> u32 {
495        use crate::google::protobuf::FieldDescriptorProto::Type::*;
496
497        if is_repeated(field) {
498            return core::mem::size_of::<crate::containers::RepeatedField<u8>>() as u32;
499        }
500
501        match field.r#type().unwrap() {
502            TYPE_BOOL => 1,
503            TYPE_INT32 | TYPE_UINT32 | TYPE_SINT32 | TYPE_FIXED32 | TYPE_SFIXED32 | TYPE_FLOAT
504            | TYPE_ENUM => 4,
505            TYPE_INT64 | TYPE_UINT64 | TYPE_SINT64 | TYPE_FIXED64 | TYPE_SFIXED64 | TYPE_DOUBLE => {
506                8
507            }
508            TYPE_STRING | TYPE_BYTES => core::mem::size_of::<crate::containers::String>() as u32,
509            TYPE_MESSAGE | TYPE_GROUP => core::mem::size_of::<Message>() as u32,
510        }
511    }
512
513    fn field_align(&self, field: &FieldDescriptorProto) -> u32 {
514        use crate::google::protobuf::FieldDescriptorProto::Type::*;
515
516        if is_repeated(field) {
517            return core::mem::align_of::<crate::containers::RepeatedField<u8>>() as u32;
518        }
519
520        match field.r#type().unwrap() {
521            TYPE_BOOL => 1,
522            TYPE_INT32 | TYPE_UINT32 | TYPE_SINT32 | TYPE_FIXED32 | TYPE_SFIXED32 | TYPE_FLOAT
523            | TYPE_ENUM => 4,
524            TYPE_INT64 | TYPE_UINT64 | TYPE_SINT64 | TYPE_FIXED64 | TYPE_SFIXED64 | TYPE_DOUBLE => {
525                8
526            }
527            TYPE_STRING | TYPE_BYTES => core::mem::align_of::<crate::containers::String>() as u32,
528            TYPE_MESSAGE | TYPE_GROUP => core::mem::align_of::<Message>() as u32,
529        }
530    }
531}
532
533#[cfg(test)]
534mod tests {
535    use super::*;
536    use crate::generated_code_only::Protobuf;
537    use crate::test_utils::compare_tables_rec;
538    use allocator_api2::alloc::Global;
539    use std::collections::HashSet;
540
541    #[test]
542    fn test_static_vs_dynamic_tables() {
543        let mut pool = DescriptorPool::new(&Global);
544        let file_descriptor =
545            crate::google::protobuf::FileDescriptorProto::ProtoType::file_descriptor();
546        pool.add_file(file_descriptor).unwrap();
547
548        let static_table =
549            <crate::google::protobuf::FileDescriptorSet::ProtoType as Protobuf>::table();
550        let dynamic_table = pool
551            .get_table("google.protobuf.FileDescriptorSet")
552            .expect("FileDescriptorSet not found in pool");
553
554        let mut seen = HashSet::new();
555        compare_tables_rec(static_table, dynamic_table, &mut seen);
556    }
557}