prost_reflect/descriptor/
api.rs

1use std::{
2    borrow::Cow,
3    collections::HashMap,
4    fmt, iter,
5    ops::{Range, RangeInclusive},
6    sync::Arc,
7};
8
9use prost::{
10    bytes::{Buf, BufMut, Bytes},
11    encoding::{self, WireType},
12    DecodeError, EncodeError, Message,
13};
14use prost_types::{
15    DescriptorProto, EnumDescriptorProto, EnumValueDescriptorProto, FieldDescriptorProto,
16    FileDescriptorProto, FileDescriptorSet, MethodDescriptorProto, OneofDescriptorProto,
17    ServiceDescriptorProto,
18};
19
20use crate::{
21    descriptor::{
22        error::DescriptorErrorKind,
23        find_enum_proto, find_message_proto, tag, to_index,
24        types::{self, Options},
25        Definition, DefinitionKind, DescriptorIndex, EnumDescriptorInner, EnumValueDescriptorInner,
26        ExtensionDescriptorInner, FieldDescriptorInner, FileDescriptorInner, KindIndex,
27        MessageDescriptorInner, MethodDescriptorInner, OneofDescriptorInner,
28        ServiceDescriptorInner, MAP_ENTRY_KEY_NUMBER, MAP_ENTRY_VALUE_NUMBER,
29    },
30    Cardinality, DescriptorError, DescriptorPool, DynamicMessage, EnumDescriptor,
31    EnumValueDescriptor, ExtensionDescriptor, FieldDescriptor, FileDescriptor, Kind,
32    MessageDescriptor, MethodDescriptor, OneofDescriptor, ServiceDescriptor, Syntax, Value,
33};
34
35impl fmt::Debug for Syntax {
36    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
37        match *self {
38            Syntax::Proto2 => write!(f, "proto2"),
39            Syntax::Proto3 => write!(f, "proto3"),
40        }
41    }
42}
43
44impl Kind {
45    fn new(pool: &DescriptorPool, kind: KindIndex) -> Self {
46        match kind {
47            KindIndex::Double => Kind::Double,
48            KindIndex::Float => Kind::Float,
49            KindIndex::Int64 => Kind::Int64,
50            KindIndex::Uint64 => Kind::Uint64,
51            KindIndex::Int32 => Kind::Int32,
52            KindIndex::Fixed64 => Kind::Fixed64,
53            KindIndex::Fixed32 => Kind::Fixed32,
54            KindIndex::Bool => Kind::Bool,
55            KindIndex::String => Kind::String,
56            KindIndex::Bytes => Kind::Bytes,
57            KindIndex::Uint32 => Kind::Uint32,
58            KindIndex::Sfixed32 => Kind::Sfixed32,
59            KindIndex::Sfixed64 => Kind::Sfixed64,
60            KindIndex::Sint32 => Kind::Sint32,
61            KindIndex::Sint64 => Kind::Sint64,
62            KindIndex::Message(index) | KindIndex::Group(index) => {
63                Kind::Message(MessageDescriptor {
64                    pool: pool.clone(),
65                    index,
66                })
67            }
68            KindIndex::Enum(index) => Kind::Enum(EnumDescriptor {
69                pool: pool.clone(),
70                index,
71            }),
72        }
73    }
74
75    /// Gets a reference to the [`MessageDescriptor`] if this is a message type,
76    /// or `None` otherwise.
77    pub fn as_message(&self) -> Option<&MessageDescriptor> {
78        match self {
79            Kind::Message(desc) => Some(desc),
80            _ => None,
81        }
82    }
83
84    /// Gets a reference to the [`EnumDescriptor`] if this is an enum type,
85    /// or `None` otherwise.
86    pub fn as_enum(&self) -> Option<&EnumDescriptor> {
87        match self {
88            Kind::Enum(desc) => Some(desc),
89            _ => None,
90        }
91    }
92
93    /// Returns the [`WireType`] used to encode this type.
94    ///
95    /// Note: The [`Kind::Message`] returns [` WireType::LengthDelimited`],
96    /// as [groups are deprecated](https://protobuf.dev/programming-guides/encoding/#groups).
97    pub fn wire_type(&self) -> WireType {
98        match self {
99            Kind::Double | Kind::Fixed64 | Kind::Sfixed64 => WireType::SixtyFourBit,
100            Kind::Float | Kind::Fixed32 | Kind::Sfixed32 => WireType::ThirtyTwoBit,
101            Kind::Enum(_)
102            | Kind::Int32
103            | Kind::Int64
104            | Kind::Uint32
105            | Kind::Uint64
106            | Kind::Sint32
107            | Kind::Sint64
108            | Kind::Bool => WireType::Varint,
109            Kind::String | Kind::Bytes | Kind::Message(_) => WireType::LengthDelimited,
110        }
111    }
112
113    /// Returns the default value for the given protobuf type `kind`.
114    ///
115    /// Unlike [`FieldDescriptor::default_value`], this method does not
116    /// look at field cardinality, so it will never return a list or map.
117    pub fn default_value(&self) -> Value {
118        match self {
119            Kind::Message(desc) => Value::Message(DynamicMessage::new(desc.clone())),
120            Kind::Enum(enum_ty) => Value::EnumNumber(enum_ty.default_value().number()),
121            Kind::Double => Value::F64(0.0),
122            Kind::Float => Value::F32(0.0),
123            Kind::Int32 | Kind::Sint32 | Kind::Sfixed32 => Value::I32(0),
124            Kind::Int64 | Kind::Sint64 | Kind::Sfixed64 => Value::I64(0),
125            Kind::Uint32 | Kind::Fixed32 => Value::U32(0),
126            Kind::Uint64 | Kind::Fixed64 => Value::U64(0),
127            Kind::Bool => Value::Bool(false),
128            Kind::String => Value::String(String::default()),
129            Kind::Bytes => Value::Bytes(Bytes::default()),
130        }
131    }
132}
133
134impl fmt::Debug for Kind {
135    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
136        match self {
137            Self::Double => write!(f, "double"),
138            Self::Float => write!(f, "float"),
139            Self::Int32 => write!(f, "int32"),
140            Self::Int64 => write!(f, "int64"),
141            Self::Uint32 => write!(f, "uint32"),
142            Self::Uint64 => write!(f, "uint64"),
143            Self::Sint32 => write!(f, "sint32"),
144            Self::Sint64 => write!(f, "sint64"),
145            Self::Fixed32 => write!(f, "fixed32"),
146            Self::Fixed64 => write!(f, "fixed64"),
147            Self::Sfixed32 => write!(f, "sfixed32"),
148            Self::Sfixed64 => write!(f, "sfixed64"),
149            Self::Bool => write!(f, "bool"),
150            Self::String => write!(f, "string"),
151            Self::Bytes => write!(f, "bytes"),
152            Self::Message(m) => write!(f, "{}", m.full_name()),
153            Self::Enum(e) => write!(f, "{}", e.full_name()),
154        }
155    }
156}
157
158impl DescriptorPool {
159    /// Creates a new, empty [`DescriptorPool`].
160    ///
161    /// For the common case of creating a `DescriptorPool` from a single [`FileDescriptorSet`], see
162    /// [`DescriptorPool::from_file_descriptor_set`] or [`DescriptorPool::decode`].
163    pub fn new() -> Self {
164        DescriptorPool::default()
165    }
166
167    /// Creates a [`DescriptorPool`] from a [`FileDescriptorSet`].
168    ///
169    /// A file descriptor set may be generated by running the protobuf compiler with the
170    /// `--descriptor_set_out` flag. If you are using [`prost-build`](https://crates.io/crates/prost-build),
171    /// then [`Config::file_descriptor_set_path`](https://docs.rs/prost-build/latest/prost_build/struct.Config.html#method..file_descriptor_set_path)
172    /// is a convenient way to generate it as part of your build.
173    pub fn from_file_descriptor_set(
174        file_descriptor_set: FileDescriptorSet,
175    ) -> Result<Self, DescriptorError> {
176        let mut pool = DescriptorPool::new();
177        pool.add_file_descriptor_set(file_descriptor_set)?;
178        Ok(pool)
179    }
180
181    /// Decodes and adds a set of file descriptors to the pool.
182    ///
183    /// A file descriptor set may be generated by running the protobuf compiler with the
184    /// `--descriptor_set_out` flag. If you are using [`prost-build`](https://crates.io/crates/prost-build),
185    /// then [`Config::file_descriptor_set_path`](https://docs.rs/prost-build/latest/prost_build/struct.Config.html#method..file_descriptor_set_path)
186    /// is a convenient way to generate it as part of your build.
187    ///
188    /// Unlike when using [`DescriptorPool::from_file_descriptor_set`], any extension options
189    /// defined in the file descriptors are preserved.
190    ///
191    /// # Errors
192    ///
193    /// Returns an error if the given bytes are not a valid protobuf-encoded file descriptor set, or if the descriptor set itself
194    /// is invalid. When using a file descriptor set generated by the protobuf compiler, this method will always succeed.
195    pub fn decode<B>(bytes: B) -> Result<Self, DescriptorError>
196    where
197        B: Buf,
198    {
199        let file_descriptor_set = types::FileDescriptorSet::decode(bytes).map_err(|err| {
200            DescriptorError::new(vec![DescriptorErrorKind::DecodeFileDescriptorSet { err }])
201        })?;
202
203        let mut pool = DescriptorPool::new();
204        pool.build_files(file_descriptor_set.file.into_iter())?;
205        Ok(pool)
206    }
207
208    /// Adds a new [`FileDescriptorSet`] to this [`DescriptorPool`].
209    ///
210    /// A file descriptor set may be generated by running the protobuf compiler with the
211    /// `--descriptor_set_out` flag. If you are using [`prost-build`](https://crates.io/crates/prost-build),
212    /// then [`Config::file_descriptor_set_path`](https://docs.rs/prost-build/latest/prost_build/struct.Config.html#method..file_descriptor_set_path)
213    /// is a convenient way to generate it as part of your build.
214    ///
215    /// Any duplicates of files already in the pool will be skipped. Note this may cause issues when trying to add two different versions of a file with the same name.
216    ///
217    /// # Errors
218    ///
219    /// Returns an error if the descriptor set is invalid, for example if it references types not yet added
220    /// to the pool. When using a file descriptor set generated by the protobuf compiler, this method will
221    /// always succeed.
222    pub fn add_file_descriptor_set(
223        &mut self,
224        file_descriptor_set: FileDescriptorSet,
225    ) -> Result<(), DescriptorError> {
226        self.add_file_descriptor_protos(file_descriptor_set.file)
227    }
228
229    /// Adds a collection of file descriptors to this pool.
230    ///
231    /// The file descriptors may be provided in any order, however all types referenced must be defined
232    /// either in one of the files provided, or in a file previously added to the pool.
233    ///
234    /// Any duplicates of files already in the pool will be skipped. Note this may cause issues when trying to add two different versions of a file with the same name.
235    ///
236    /// # Errors
237    ///
238    /// Returns an error if any of the given file descriptor is invalid, for example if they reference
239    /// types not yet added to the pool.
240    pub fn add_file_descriptor_protos<I>(&mut self, files: I) -> Result<(), DescriptorError>
241    where
242        I: IntoIterator<Item = FileDescriptorProto>,
243    {
244        self.build_files(
245            files
246                .into_iter()
247                .map(types::FileDescriptorProto::from_prost),
248        )
249    }
250
251    /// Add a single file descriptor to the pool.
252    ///
253    /// All types referenced by the file must be defined either in the file itself, or in a file
254    /// previously added to the pool.
255    ///
256    /// If the file is a duplicate of a file already in the pool, it will be skipped. Note this may cause issues when trying to add two different versions of a file with the same name.
257    ///
258    /// # Errors
259    ///
260    /// Returns an error if the given file descriptor is invalid, for example if it references types not yet added
261    /// to the pool.
262    pub fn add_file_descriptor_proto(
263        &mut self,
264        file: FileDescriptorProto,
265    ) -> Result<(), DescriptorError> {
266        self.add_file_descriptor_protos(iter::once(file))
267    }
268
269    /// Decode and add a single file descriptor to the pool.
270    ///
271    /// All types referenced by the file must be defined either in the file itself, or in a file
272    /// previously added to the pool.
273    ///
274    /// Unlike when using [`add_file_descriptor_proto()`][DescriptorPool::add_file_descriptor_proto], any extension options
275    /// defined in the file descriptor are preserved.
276    ///
277    /// If the file is a duplicate of a file already in the pool, it will be skipped. Note this may cause issues when trying to add two different versions of a file with the same name.
278    ///
279    /// # Errors
280    ///
281    /// Returns an error if the given bytes are not a valid protobuf-encoded file descriptor, or if the file descriptor itself
282    /// is invalid, for example if it references types not yet added to the pool.
283    pub fn decode_file_descriptor_proto<B>(&mut self, bytes: B) -> Result<(), DescriptorError>
284    where
285        B: Buf,
286    {
287        let file = types::FileDescriptorProto::decode(bytes).map_err(|err| {
288            DescriptorError::new(vec![DescriptorErrorKind::DecodeFileDescriptorSet { err }])
289        })?;
290
291        self.build_files(iter::once(file))
292    }
293
294    /// Decode and add a set of file descriptors to the pool.
295    ///
296    /// A file descriptor set may be generated by running the protobuf compiler with the
297    /// `--descriptor_set_out` flag. If you are using [`prost-build`](https://crates.io/crates/prost-build),
298    /// then [`Config::file_descriptor_set_path`](https://docs.rs/prost-build/latest/prost_build/struct.Config.html#method..file_descriptor_set_path)
299    /// is a convenient way to generate it as part of your build.
300    ///
301    /// Unlike when using [`add_file_descriptor_set()`][DescriptorPool::add_file_descriptor_set], any extension options
302    /// defined in the file descriptors are preserved.
303    ///
304    /// Any duplicates of files already in the pool will be skipped. Note this may cause issues when trying to add two different versions of a file with the same name.
305    ///
306    /// # Errors
307    ///
308    /// Returns an error if the given bytes are not a valid protobuf-encoded file descriptor set, or if the descriptor set itself
309    /// is invalid. When using a file descriptor set generated by the protobuf compiler, this method will always succeed.
310    pub fn decode_file_descriptor_set<B>(&mut self, bytes: B) -> Result<(), DescriptorError>
311    where
312        B: Buf,
313    {
314        let file = types::FileDescriptorSet::decode(bytes).map_err(|err| {
315            DescriptorError::new(vec![DescriptorErrorKind::DecodeFileDescriptorSet { err }])
316        })?;
317
318        self.build_files(file.file)
319    }
320
321    /// Gets an iterator over the file descriptors added to this pool.
322    pub fn files(&self) -> impl ExactSizeIterator<Item = FileDescriptor> + '_ {
323        indices(&self.inner.files).map(|index| FileDescriptor {
324            pool: self.clone(),
325            index,
326        })
327    }
328
329    /// Gets a file descriptor by its name, or `None` if no such file has been added.
330    pub fn get_file_by_name(&self, name: &str) -> Option<FileDescriptor> {
331        if let Some(&index) = self.inner.file_names.get(name) {
332            Some(FileDescriptor {
333                pool: self.clone(),
334                index,
335            })
336        } else {
337            None
338        }
339    }
340
341    /// Gets a iterator over the raw [`FileDescriptorProto`] instances wrapped by this [`DescriptorPool`].
342    pub fn file_descriptor_protos(
343        &self,
344    ) -> impl ExactSizeIterator<Item = &FileDescriptorProto> + '_ {
345        indices(&self.inner.files).map(|index| &self.inner.files[index as usize].prost)
346    }
347
348    /// Encodes the files contained within this [`DescriptorPool`] to their byte representation.
349    ///
350    /// The encoded message is equivalent to a [`FileDescriptorSet`], however also includes
351    /// any extension options that were defined.
352    pub fn encode<B>(&self, buf: B) -> Result<(), EncodeError>
353    where
354        B: BufMut,
355    {
356        use prost::encoding::{encoded_len_varint, DecodeContext};
357
358        struct FileDescriptorSet<'a> {
359            files: &'a [FileDescriptorInner],
360        }
361
362        impl fmt::Debug for FileDescriptorSet<'_> {
363            fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
364                f.debug_struct("FileDescriptorSet").finish_non_exhaustive()
365            }
366        }
367
368        impl Message for FileDescriptorSet<'_> {
369            fn encode_raw(&self, buf: &mut impl BufMut)
370            where
371                Self: Sized,
372            {
373                for file in self.files {
374                    encoding::message::encode(
375                        tag::file_descriptor_set::FILE as u32,
376                        &file.raw,
377                        buf,
378                    );
379                }
380            }
381
382            fn encoded_len(&self) -> usize {
383                encoding::key_len(tag::file_descriptor_set::FILE as u32) * self.files.len()
384                    + self
385                        .files
386                        .iter()
387                        .map(|f| &f.raw)
388                        .map(Message::encoded_len)
389                        .map(|len| len + encoded_len_varint(len as u64))
390                        .sum::<usize>()
391            }
392
393            fn merge_field(
394                &mut self,
395                _: u32,
396                _: WireType,
397                _: &mut impl Buf,
398                _: DecodeContext,
399            ) -> Result<(), DecodeError>
400            where
401                Self: Sized,
402            {
403                unimplemented!()
404            }
405
406            fn clear(&mut self) {
407                unimplemented!()
408            }
409        }
410
411        let mut buf = buf;
412        FileDescriptorSet {
413            files: &self.inner.files,
414        }
415        .encode(&mut buf)
416    }
417
418    /// Encodes the files contained within this [`DescriptorPool`] to a newly allocated buffer.
419    ///
420    /// The encoded message is equivalent to a [`FileDescriptorSet`], however also includes
421    /// any extension options that were defined.
422    pub fn encode_to_vec(&self) -> Vec<u8> {
423        let mut buf = Vec::new();
424        self.encode(&mut buf).expect("vec should have capacity");
425        buf
426    }
427
428    /// Gets an iterator over the services defined in these protobuf files.
429    pub fn services(&self) -> impl ExactSizeIterator<Item = ServiceDescriptor> + '_ {
430        indices(&self.inner.services).map(|index| ServiceDescriptor {
431            pool: self.clone(),
432            index,
433        })
434    }
435
436    /// Gets an iterator over all message types defined in these protobuf files.
437    ///
438    /// The iterator includes nested messages defined in another message.
439    pub fn all_messages(&self) -> impl ExactSizeIterator<Item = MessageDescriptor> + '_ {
440        indices(&self.inner.messages).map(|index| MessageDescriptor {
441            pool: self.clone(),
442            index,
443        })
444    }
445
446    /// Gets an iterator over all enum types defined in these protobuf files.
447    ///
448    /// The iterator includes nested enums defined in another message.
449    pub fn all_enums(&self) -> impl ExactSizeIterator<Item = EnumDescriptor> + '_ {
450        indices(&self.inner.enums).map(|index| EnumDescriptor {
451            pool: self.clone(),
452            index,
453        })
454    }
455
456    /// Gets an iterator over all extension fields defined in these protobuf files.
457    ///
458    /// The iterator includes nested extension fields defined in another message.
459    pub fn all_extensions(&self) -> impl ExactSizeIterator<Item = ExtensionDescriptor> + '_ {
460        indices(&self.inner.extensions).map(|index| ExtensionDescriptor {
461            pool: self.clone(),
462            index,
463        })
464    }
465
466    /// Gets a [`MessageDescriptor`] by its fully qualified name, for example `my.package.MessageName`.
467    pub fn get_message_by_name(&self, name: &str) -> Option<MessageDescriptor> {
468        match self.inner.get_by_name(name) {
469            Some(&Definition {
470                kind: DefinitionKind::Message(index),
471                ..
472            }) => Some(MessageDescriptor {
473                pool: self.clone(),
474                index,
475            }),
476            _ => None,
477        }
478    }
479
480    /// Gets an [`EnumDescriptor`] by its fully qualified name, for example `my.package.EnumName`.
481    pub fn get_enum_by_name(&self, name: &str) -> Option<EnumDescriptor> {
482        match self.inner.get_by_name(name) {
483            Some(&Definition {
484                kind: DefinitionKind::Enum(index),
485                ..
486            }) => Some(EnumDescriptor {
487                pool: self.clone(),
488                index,
489            }),
490            _ => None,
491        }
492    }
493
494    /// Gets an [`ExtensionDescriptor`] by its fully qualified name, for example `my.package.my_extension`.
495    pub fn get_extension_by_name(&self, name: &str) -> Option<ExtensionDescriptor> {
496        match self.inner.get_by_name(name) {
497            Some(&Definition {
498                kind: DefinitionKind::Extension(index),
499                ..
500            }) => Some(ExtensionDescriptor {
501                pool: self.clone(),
502                index,
503            }),
504            _ => None,
505        }
506    }
507
508    /// Gets an [`ServiceDescriptor`] by its fully qualified name, for example `my.package.MyService`.
509    pub fn get_service_by_name(&self, name: &str) -> Option<ServiceDescriptor> {
510        match self.inner.get_by_name(name) {
511            Some(&Definition {
512                kind: DefinitionKind::Service(index),
513                ..
514            }) => Some(ServiceDescriptor {
515                pool: self.clone(),
516                index,
517            }),
518            _ => None,
519        }
520    }
521}
522
523impl fmt::Debug for DescriptorPool {
524    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
525        f.debug_struct("DescriptorPool")
526            .field("files", &debug_fmt_iter(self.files()))
527            .field("services", &debug_fmt_iter(self.services()))
528            .field("all_messages", &debug_fmt_iter(self.all_messages()))
529            .field("all_enums", &debug_fmt_iter(self.all_enums()))
530            .field("all_extensions", &debug_fmt_iter(self.all_extensions()))
531            .finish()
532    }
533}
534
535impl PartialEq for DescriptorPool {
536    fn eq(&self, other: &Self) -> bool {
537        Arc::ptr_eq(&self.inner, &other.inner)
538    }
539}
540
541impl Eq for DescriptorPool {}
542
543impl FileDescriptor {
544    /// Create a new [`FileDescriptor`] referencing the file at `index` within the given [`DescriptorPool`].
545    ///
546    /// # Panics
547    ///
548    /// Panics if `index` is out-of-bounds.
549    pub fn new(descriptor_pool: DescriptorPool, index: usize) -> Self {
550        debug_assert!(index < descriptor_pool.files().len());
551        FileDescriptor {
552            pool: descriptor_pool,
553            index: to_index(index),
554        }
555    }
556
557    /// Gets a reference to the [`DescriptorPool`] this file is included in.
558    pub fn parent_pool(&self) -> &DescriptorPool {
559        &self.pool
560    }
561
562    /// Gets the unique name of this file relative to the root of the source tree,
563    /// e.g. `path/to/my_package.proto`.
564    pub fn name(&self) -> &str {
565        self.inner().prost.name()
566    }
567
568    /// Gets the name of the package specifier for a file, e.g. `my.package`.
569    ///
570    /// If no package name is set, an empty string is returned.
571    pub fn package_name(&self) -> &str {
572        self.inner().prost.package()
573    }
574
575    /// Gets the index of this file within the parent [`DescriptorPool`].
576    pub fn index(&self) -> usize {
577        self.index as usize
578    }
579
580    /// Gets the syntax of this protobuf file.
581    pub fn syntax(&self) -> Syntax {
582        self.inner().syntax
583    }
584
585    /// Gets the dependencies of this file.
586    ///
587    /// This corresponds to the [`FileDescriptorProto::dependency`] field.
588    pub fn dependencies(&self) -> impl ExactSizeIterator<Item = FileDescriptor> + '_ {
589        let pool = self.parent_pool();
590        self.file_descriptor_proto()
591            .dependency
592            .iter()
593            .map(|name| pool.get_file_by_name(name).expect("file not found"))
594    }
595
596    /// Gets the public dependencies of this file.
597    ///
598    /// This corresponds to the [`FileDescriptorProto::public_dependency`] field.
599    pub fn public_dependencies(&self) -> impl ExactSizeIterator<Item = FileDescriptor> + '_ {
600        let pool = self.parent_pool();
601        let raw = self.file_descriptor_proto();
602        raw.public_dependency.iter().map(|&index| {
603            pool.get_file_by_name(&raw.dependency[index as usize])
604                .expect("file not found")
605        })
606    }
607
608    /// Gets the top-level message types defined within this file.
609    ///
610    /// This does not include nested messages defined within another message.
611    pub fn messages(&self) -> impl ExactSizeIterator<Item = MessageDescriptor> + '_ {
612        let pool = self.parent_pool();
613        let raw_file = self.file_descriptor_proto();
614        raw_file.message_type.iter().map(move |raw_message| {
615            pool.get_message_by_name(join_name(raw_file.package(), raw_message.name()).as_ref())
616                .expect("message not found")
617        })
618    }
619
620    /// Gets the top-level enum types defined within this file.
621    ///
622    /// This does not include nested enums defined within another message.
623    pub fn enums(&self) -> impl ExactSizeIterator<Item = EnumDescriptor> + '_ {
624        let pool = self.parent_pool();
625        let raw_file = self.file_descriptor_proto();
626        raw_file.enum_type.iter().map(move |raw_enum| {
627            pool.get_enum_by_name(join_name(raw_file.package(), raw_enum.name()).as_ref())
628                .expect("enum not found")
629        })
630    }
631
632    /// Gets the top-level extension fields defined within this file.
633    ///
634    /// This does not include nested extensions defined within another message.
635    pub fn extensions(&self) -> impl ExactSizeIterator<Item = ExtensionDescriptor> + '_ {
636        let pool = self.parent_pool();
637        let raw_file = self.file_descriptor_proto();
638        raw_file.extension.iter().map(move |raw_extension| {
639            pool.get_extension_by_name(join_name(raw_file.package(), raw_extension.name()).as_ref())
640                .expect("extension not found")
641        })
642    }
643
644    /// Gets the services defined within this file.
645    pub fn services(&self) -> impl ExactSizeIterator<Item = ServiceDescriptor> + '_ {
646        let pool = self.parent_pool();
647        let raw_file = self.file_descriptor_proto();
648        raw_file.service.iter().map(move |raw_service| {
649            pool.get_service_by_name(join_name(raw_file.package(), raw_service.name()).as_ref())
650                .expect("service not found")
651        })
652    }
653
654    /// Gets a reference to the raw [`FileDescriptorProto`] wrapped by this [`FileDescriptor`].
655    pub fn file_descriptor_proto(&self) -> &FileDescriptorProto {
656        &self.inner().prost
657    }
658
659    /// Encodes this file descriptor to its byte representation.
660    ///
661    /// The encoded message is equivalent to a [`FileDescriptorProto`], however also includes
662    /// any extension options that were defined.
663    pub fn encode<B>(&self, buf: B) -> Result<(), EncodeError>
664    where
665        B: BufMut,
666    {
667        let mut buf = buf;
668        self.inner().raw.encode(&mut buf)
669    }
670
671    /// Encodes this file descriptor to a newly allocated buffer.
672    ///
673    /// The encoded message is equivalent to a [`FileDescriptorProto`], however also includes
674    /// any extension options that were defined.
675    pub fn encode_to_vec(&self) -> Vec<u8> {
676        let mut buf = Vec::new();
677        self.encode(&mut buf).expect("vec should have capacity");
678        buf
679    }
680
681    /// Decodes the options defined for this [`FileDescriptor`], including any extension options.
682    pub fn options(&self) -> DynamicMessage {
683        decode_options(
684            self.parent_pool(),
685            "google.protobuf.FileOptions",
686            &self.inner().raw.options,
687        )
688    }
689
690    fn inner(&self) -> &FileDescriptorInner {
691        &self.pool.inner.files[self.index as usize]
692    }
693}
694
695impl fmt::Debug for FileDescriptor {
696    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
697        f.debug_struct("FileDescriptor")
698            .field("name", &self.name())
699            .field("package_name", &self.package_name())
700            .finish()
701    }
702}
703
704impl MessageDescriptor {
705    /// Gets a reference to the [`DescriptorPool`] this message is defined in.
706    pub fn parent_pool(&self) -> &DescriptorPool {
707        &self.pool
708    }
709
710    /// Gets the [`FileDescriptor`] this message is defined in.
711    pub fn parent_file(&self) -> FileDescriptor {
712        FileDescriptor {
713            pool: self.pool.clone(),
714            index: self.inner().id.file,
715        }
716    }
717
718    /// Gets the parent message type if this message type is nested inside a another message, or `None` otherwise
719    pub fn parent_message(&self) -> Option<MessageDescriptor> {
720        self.inner().parent.map(|index| MessageDescriptor {
721            pool: self.pool.clone(),
722            index,
723        })
724    }
725
726    /// Gets the short name of the message type, e.g. `MyMessage`.
727    pub fn name(&self) -> &str {
728        self.inner().id.name()
729    }
730
731    /// Gets the full name of the message type, e.g. `my.package.MyMessage`.
732    pub fn full_name(&self) -> &str {
733        self.inner().id.full_name()
734    }
735
736    /// Gets the name of the package this message type is defined in, e.g. `my.package`.
737    ///
738    /// If no package name is set, an empty string is returned.
739    pub fn package_name(&self) -> &str {
740        self.raw_file().package()
741    }
742
743    /// Gets the path where this message is defined within the [`FileDescriptorProto`][FileDescriptorProto], e.g. `[4, 0]`.
744    ///
745    /// See [`path`][prost_types::source_code_info::Location::path] for more details on the structure of the path.
746    pub fn path(&self) -> &[i32] {
747        &self.inner().id.path
748    }
749
750    /// Gets a reference to the [`FileDescriptorProto`] in which this message is defined.
751    pub fn parent_file_descriptor_proto(&self) -> &FileDescriptorProto {
752        &self.pool.inner.files[self.inner().id.file as usize].prost
753    }
754
755    /// Gets a reference to the raw [`DescriptorProto`] wrapped by this [`MessageDescriptor`].
756    pub fn descriptor_proto(&self) -> &DescriptorProto {
757        find_message_proto_prost(self.parent_file_descriptor_proto(), self.path())
758    }
759
760    /// Decodes the options defined for this [`MessageDescriptor`], including any extension options.
761    pub fn options(&self) -> DynamicMessage {
762        decode_options(
763            self.parent_pool(),
764            "google.protobuf.MessageOptions",
765            &self.raw().options,
766        )
767    }
768
769    /// Gets an iterator yielding a [`FieldDescriptor`] for each field defined in this message.
770    pub fn fields(&self) -> impl ExactSizeIterator<Item = FieldDescriptor> + '_ {
771        self.inner()
772            .field_numbers
773            .values()
774            .map(|&index| FieldDescriptor {
775                message: self.clone(),
776                index,
777            })
778    }
779
780    pub(crate) fn fields_in_index_order(
781        &self,
782    ) -> impl ExactSizeIterator<Item = FieldDescriptor> + '_ {
783        self.inner()
784            .fields
785            .iter()
786            .enumerate()
787            .map(|(index, _)| FieldDescriptor {
788                message: self.clone(),
789                index: index as u32,
790            })
791    }
792
793    /// Gets an iterator yielding a [`OneofDescriptor`] for each oneof field defined in this message.
794    pub fn oneofs(&self) -> impl ExactSizeIterator<Item = OneofDescriptor> + '_ {
795        indices(&self.inner().oneofs).map(|index| OneofDescriptor {
796            message: self.clone(),
797            index,
798        })
799    }
800
801    /// Gets the nested message types defined within this message.
802    pub fn child_messages(&self) -> impl ExactSizeIterator<Item = MessageDescriptor> + '_ {
803        let pool = self.parent_pool();
804        let namespace = self.full_name();
805        let raw_message = self.descriptor_proto();
806        raw_message.nested_type.iter().map(move |raw_message| {
807            pool.get_message_by_name(join_name(namespace, raw_message.name()).as_ref())
808                .expect("message not found")
809        })
810    }
811
812    /// Gets the nested enum types defined within this message.
813    pub fn child_enums(&self) -> impl ExactSizeIterator<Item = EnumDescriptor> + '_ {
814        let pool = self.parent_pool();
815        let namespace = self.full_name();
816        let raw_message = self.descriptor_proto();
817        raw_message.enum_type.iter().map(move |raw_enum| {
818            pool.get_enum_by_name(join_name(namespace, raw_enum.name()).as_ref())
819                .expect("enum not found")
820        })
821    }
822
823    /// Gets the nested extension fields defined within this message.
824    ///
825    /// Note this only returns extensions defined nested within this message. See
826    /// [`MessageDescriptor::extensions`] to get fields defined anywhere that extend this message.
827    pub fn child_extensions(&self) -> impl ExactSizeIterator<Item = ExtensionDescriptor> + '_ {
828        let pool = self.parent_pool();
829        let namespace = self.full_name();
830        let raw_message = self.descriptor_proto();
831        raw_message.extension.iter().map(move |raw_extension| {
832            pool.get_extension_by_name(join_name(namespace, raw_extension.name()).as_ref())
833                .expect("extension not found")
834        })
835    }
836
837    /// Gets an iterator over all extensions to this message defined in the parent [`DescriptorPool`].
838    ///
839    /// Note this iterates over extension fields defined anywhere which extend this message. See
840    /// [`MessageDescriptor::child_extensions`] to just get extensions defined nested within this message.
841    pub fn extensions(&self) -> impl ExactSizeIterator<Item = ExtensionDescriptor> + '_ {
842        self.inner()
843            .extensions
844            .iter()
845            .map(|&index| ExtensionDescriptor {
846                pool: self.parent_pool().clone(),
847                index,
848            })
849    }
850
851    /// Gets a [`FieldDescriptor`] with the given number, or `None` if no such field exists.
852    pub fn get_field(&self, number: u32) -> Option<FieldDescriptor> {
853        self.inner()
854            .field_numbers
855            .get(&number)
856            .map(|&index| FieldDescriptor {
857                message: self.clone(),
858                index,
859            })
860    }
861
862    /// Gets a [`FieldDescriptor`] with the given name, or `None` if no such field exists.
863    pub fn get_field_by_name(&self, name: &str) -> Option<FieldDescriptor> {
864        self.inner()
865            .field_names
866            .get(name)
867            .map(|&index| FieldDescriptor {
868                message: self.clone(),
869                index,
870            })
871    }
872
873    /// Gets a [`FieldDescriptor`] with the given JSON name, or `None` if no such field exists.
874    pub fn get_field_by_json_name(&self, json_name: &str) -> Option<FieldDescriptor> {
875        self.inner()
876            .field_json_names
877            .get(json_name)
878            .map(|&index| FieldDescriptor {
879                message: self.clone(),
880                index,
881            })
882    }
883
884    /// Returns `true` if this is an auto-generated message type to
885    /// represent the entry type for a map field.
886    //
887    /// If this method returns `true`, [`fields`][Self::fields] is guaranteed to
888    /// yield the following two fields:
889    ///
890    /// * A "key" field with a field number of 1
891    /// * A "value" field with a field number of 2
892    ///
893    /// See [`map_entry_key_field`][MessageDescriptor::map_entry_key_field] and
894    /// [`map_entry_value_field`][MessageDescriptor::map_entry_value_field] for more a convenient way
895    /// to get these fields.
896    pub fn is_map_entry(&self) -> bool {
897        self.raw()
898            .options
899            .as_ref()
900            .map(|o| o.value.map_entry())
901            .unwrap_or(false)
902    }
903
904    /// If this is a [map entry](MessageDescriptor::is_map_entry), returns a [`FieldDescriptor`] for the key.
905    ///
906    /// # Panics
907    ///
908    /// This method may panic if [`is_map_entry`][MessageDescriptor::is_map_entry] returns `false`.
909    pub fn map_entry_key_field(&self) -> FieldDescriptor {
910        debug_assert!(self.is_map_entry());
911        self.get_field(MAP_ENTRY_KEY_NUMBER)
912            .expect("map entry should have key field")
913    }
914
915    /// If this is a [map entry](MessageDescriptor::is_map_entry), returns a [`FieldDescriptor`] for the value.
916    ///
917    /// # Panics
918    ///
919    /// This method may panic if [`is_map_entry`][MessageDescriptor::is_map_entry] returns `false`.
920    pub fn map_entry_value_field(&self) -> FieldDescriptor {
921        debug_assert!(self.is_map_entry());
922        self.get_field(MAP_ENTRY_VALUE_NUMBER)
923            .expect("map entry should have value field")
924    }
925
926    /// Gets an iterator over reserved field number ranges in this message.
927    pub fn reserved_ranges(&self) -> impl ExactSizeIterator<Item = Range<u32>> + '_ {
928        self.raw()
929            .reserved_range
930            .iter()
931            .map(|n| (n.start() as u32)..(n.end() as u32))
932    }
933
934    /// Gets an iterator over reserved field names in this message.
935    pub fn reserved_names(&self) -> impl ExactSizeIterator<Item = &str> + '_ {
936        self.raw().reserved_name.iter().map(|n| n.as_ref())
937    }
938
939    /// Gets an iterator over extension field number ranges in this message.
940    pub fn extension_ranges(&self) -> impl ExactSizeIterator<Item = Range<u32>> + '_ {
941        self.raw()
942            .extension_range
943            .iter()
944            .map(|n| (n.start() as u32)..(n.end() as u32))
945    }
946
947    /// Gets an extension to this message by its number, or `None` if no such extension exists.
948    pub fn get_extension(&self, number: u32) -> Option<ExtensionDescriptor> {
949        self.extensions().find(|ext| ext.number() == number)
950    }
951
952    /// Gets an extension to this message by its full name (e.g. `my.package.my_extension`), or `None` if no such extension exists.
953    pub fn get_extension_by_full_name(&self, name: &str) -> Option<ExtensionDescriptor> {
954        self.extensions().find(|ext| ext.full_name() == name)
955    }
956
957    /// Gets an extension to this message by its JSON name (e.g. `[my.package.my_extension]`), or `None` if no such extension exists.
958    pub fn get_extension_by_json_name(&self, name: &str) -> Option<ExtensionDescriptor> {
959        self.extensions().find(|ext| ext.json_name() == name)
960    }
961
962    fn inner(&self) -> &MessageDescriptorInner {
963        &self.pool.inner.messages[self.index as usize]
964    }
965
966    fn raw(&self) -> &types::DescriptorProto {
967        find_message_proto(self.raw_file(), self.path())
968    }
969
970    fn raw_file(&self) -> &types::FileDescriptorProto {
971        &self.pool.inner.files[self.inner().id.file as usize].raw
972    }
973}
974
975impl fmt::Debug for MessageDescriptor {
976    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
977        f.debug_struct("MessageDescriptor")
978            .field("name", &self.name())
979            .field("full_name", &self.full_name())
980            .field("is_map_entry", &self.is_map_entry())
981            .field("fields", &debug_fmt_iter(self.fields()))
982            .field("oneofs", &debug_fmt_iter(self.oneofs()))
983            .finish()
984    }
985}
986
987impl FieldDescriptor {
988    /// Gets a reference to the [`DescriptorPool`] this field is defined in.
989    pub fn parent_pool(&self) -> &DescriptorPool {
990        self.message.parent_pool()
991    }
992
993    /// Gets the [`FileDescriptor`] this field is defined in.
994    pub fn parent_file(&self) -> FileDescriptor {
995        self.message.parent_file()
996    }
997
998    /// Gets a reference to the [`MessageDescriptor`] this field is defined in.
999    pub fn parent_message(&self) -> &MessageDescriptor {
1000        &self.message
1001    }
1002
1003    /// Gets the short name of the message type, e.g. `my_field`.
1004    pub fn name(&self) -> &str {
1005        self.inner().id.name()
1006    }
1007
1008    /// Gets the full name of the message field, e.g. `my.package.MyMessage.my_field`.
1009    pub fn full_name(&self) -> &str {
1010        self.inner().id.full_name()
1011    }
1012
1013    /// Gets the path where this message field is defined within the [`FileDescriptorProto`][FileDescriptorProto], e.g. `[4, 0, 2, 0]`.
1014    ///
1015    /// See [`path`][prost_types::source_code_info::Location::path] for more details on the structure of the path.
1016    pub fn path(&self) -> &[i32] {
1017        &self.inner().id.path
1018    }
1019
1020    /// Gets a reference to the raw [`FieldDescriptorProto`] wrapped by this [`FieldDescriptor`].
1021    pub fn field_descriptor_proto(&self) -> &FieldDescriptorProto {
1022        &self.parent_message().descriptor_proto().field[*self.path().last().unwrap() as usize]
1023    }
1024
1025    /// Decodes the options defined for this [`FieldDescriptor`], including any extension options.
1026    pub fn options(&self) -> DynamicMessage {
1027        decode_options(
1028            self.parent_pool(),
1029            "google.protobuf.FieldOptions",
1030            &self.raw().options,
1031        )
1032    }
1033
1034    /// Gets the unique number for this message field.
1035    pub fn number(&self) -> u32 {
1036        self.inner().number
1037    }
1038
1039    /// Gets the name used for JSON serialization.
1040    ///
1041    /// This is usually the camel-cased form of the field name, unless
1042    /// another value is set in the proto file.
1043    pub fn json_name(&self) -> &str {
1044        &self.inner().json_name
1045    }
1046
1047    /// Whether this field is encoded using the proto2 group encoding.
1048    pub fn is_group(&self) -> bool {
1049        matches!(self.inner().kind, KindIndex::Group(_))
1050    }
1051
1052    /// Whether this field is a list type.
1053    ///
1054    /// Equivalent to checking that the cardinality is `Repeated` and that
1055    /// [`is_map`][Self::is_map] returns `false`.
1056    pub fn is_list(&self) -> bool {
1057        self.cardinality() == Cardinality::Repeated && !self.is_map()
1058    }
1059
1060    /// Whether this field is a map type.
1061    ///
1062    /// Equivalent to checking that the cardinality is `Repeated` and that
1063    /// the field type is a message where [`is_map_entry`][MessageDescriptor::is_map_entry]
1064    /// returns `true`.
1065    pub fn is_map(&self) -> bool {
1066        self.cardinality() == Cardinality::Repeated
1067            && match self.kind() {
1068                Kind::Message(message) => message.is_map_entry(),
1069                _ => false,
1070            }
1071    }
1072
1073    /// Whether this field is a list encoded using [packed encoding](https://developers.google.com/protocol-buffers/docs/encoding#packed).
1074    pub fn is_packed(&self) -> bool {
1075        self.inner().is_packed
1076    }
1077
1078    /// Whether this field is required.
1079    ///
1080    /// For proto3 this always returns `false`.
1081    pub fn is_required(&self) -> bool {
1082        self.cardinality() == Cardinality::Required
1083    }
1084
1085    /// The cardinality of this field.
1086    pub fn cardinality(&self) -> Cardinality {
1087        self.inner().cardinality
1088    }
1089
1090    /// Whether this field supports distinguishing between an unpopulated field and
1091    /// the default value.
1092    ///
1093    /// For proto2 messages this returns `true` for all non-repeated fields.
1094    /// For proto3 this returns `true` for message fields, and fields contained
1095    /// in a `oneof`.
1096    pub fn supports_presence(&self) -> bool {
1097        self.inner().supports_presence
1098    }
1099
1100    /// Gets the [`Kind`] of this field.
1101    pub fn kind(&self) -> Kind {
1102        Kind::new(self.parent_pool(), self.inner().kind)
1103    }
1104
1105    /// Gets a [`OneofDescriptor`] representing the oneof containing this field,
1106    /// or `None` if this field is not contained in a oneof.
1107    pub fn containing_oneof(&self) -> Option<OneofDescriptor> {
1108        self.inner().oneof.map(|index| OneofDescriptor {
1109            message: self.message.clone(),
1110            index,
1111        })
1112    }
1113
1114    /// Returns the default value for this field.
1115    ///
1116    /// This is equivalent to `kind().default_value()` except for the following cases:
1117    ///
1118    /// * If the field is a map, an empty map is returned.
1119    /// * If the field is `repeated`, an empty list is returned.
1120    /// * If the field has a custom default value specified, that is returned (proto2 only).
1121    pub fn default_value(&self) -> Value {
1122        if self.is_list() {
1123            Value::List(Vec::default())
1124        } else if self.is_map() {
1125            Value::Map(HashMap::default())
1126        } else if let Some(default_value) = &self.inner().default {
1127            default_value.clone()
1128        } else {
1129            self.kind().default_value()
1130        }
1131    }
1132
1133    pub(crate) fn is_packable(&self) -> bool {
1134        self.inner().kind.is_packable()
1135    }
1136
1137    fn inner(&self) -> &FieldDescriptorInner {
1138        &self.message.inner().fields[self.index as usize]
1139    }
1140
1141    fn raw(&self) -> &types::FieldDescriptorProto {
1142        &self.message.raw().field[self.index as usize]
1143    }
1144}
1145
1146impl fmt::Debug for FieldDescriptor {
1147    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1148        f.debug_struct("FieldDescriptor")
1149            .field("name", &self.name())
1150            .field("full_name", &self.full_name())
1151            .field("json_name", &self.json_name())
1152            .field("number", &self.number())
1153            .field("kind", &self.kind())
1154            .field("cardinality", &self.cardinality())
1155            .field(
1156                "containing_oneof",
1157                &self.containing_oneof().map(|o| o.name().to_owned()),
1158            )
1159            .field("default_value", &self.default_value())
1160            .field("is_group", &self.is_group())
1161            .field("is_list", &self.is_list())
1162            .field("is_map", &self.is_map())
1163            .field("is_packed", &self.is_packed())
1164            .field("supports_presence", &self.supports_presence())
1165            .finish()
1166    }
1167}
1168
1169impl ExtensionDescriptor {
1170    /// Gets a reference to the [`DescriptorPool`] this extension field is defined in.
1171    pub fn parent_pool(&self) -> &DescriptorPool {
1172        &self.pool
1173    }
1174
1175    /// Gets the [`FileDescriptor`] this extension field is defined in.
1176    pub fn parent_file(&self) -> FileDescriptor {
1177        FileDescriptor {
1178            pool: self.pool.clone(),
1179            index: self.inner().id.file,
1180        }
1181    }
1182
1183    /// Gets the parent message type if this extension is defined within another message, or `None` otherwise.
1184    ///
1185    /// Note this just corresponds to where the extension is defined in the proto file. See [`containing_message`][ExtensionDescriptor::containing_message]
1186    /// for the message this field extends.
1187    pub fn parent_message(&self) -> Option<MessageDescriptor> {
1188        self.inner().parent.map(|index| MessageDescriptor {
1189            pool: self.pool.clone(),
1190            index,
1191        })
1192    }
1193
1194    /// Gets the short name of the extension field type, e.g. `my_extension`.
1195    pub fn name(&self) -> &str {
1196        self.inner().id.name()
1197    }
1198
1199    /// Gets the full name of the extension field, e.g. `my.package.ParentMessage.my_extension`.
1200    ///
1201    /// Note this includes the name of the parent message if any, not the message this field extends.
1202    pub fn full_name(&self) -> &str {
1203        self.inner().id.full_name()
1204    }
1205
1206    /// Gets the name of the package this extension field is defined in, e.g. `my.package`.
1207    ///
1208    /// If no package name is set, an empty string is returned.
1209    pub fn package_name(&self) -> &str {
1210        self.raw_file().package()
1211    }
1212
1213    /// Gets the path where this extension field is defined within the [`FileDescriptorProto`][FileDescriptorProto], e.g. `[7, 0]`.
1214    ///
1215    /// See [`path`][prost_types::source_code_info::Location::path] for more details on the structure of the path.
1216    pub fn path(&self) -> &[i32] {
1217        &self.inner().id.path
1218    }
1219
1220    /// Gets a reference to the [`FileDescriptorProto`] in which this extension is defined.
1221    pub fn parent_file_descriptor_proto(&self) -> &FileDescriptorProto {
1222        &self.pool.inner.files[self.inner().id.file as usize].prost
1223    }
1224
1225    /// Gets a reference to the raw [`FieldDescriptorProto`] wrapped by this [`ExtensionDescriptor`].
1226    pub fn field_descriptor_proto(&self) -> &FieldDescriptorProto {
1227        let file = self.parent_file_descriptor_proto();
1228        let path = self.path();
1229        debug_assert_ne!(path.len(), 0);
1230        debug_assert_eq!(path.len() % 2, 0);
1231        if path.len() == 2 {
1232            debug_assert_eq!(path[0], tag::file::EXTENSION);
1233            &file.extension[path[1] as usize]
1234        } else {
1235            let message = find_message_proto_prost(file, &path[..path.len() - 2]);
1236            debug_assert_eq!(path[path.len() - 2], tag::message::EXTENSION);
1237            &message.extension[path[path.len() - 1] as usize]
1238        }
1239    }
1240
1241    /// Decodes the options defined for this [`ExtensionDescriptor`], including any extension options.
1242    pub fn options(&self) -> DynamicMessage {
1243        decode_options(
1244            self.parent_pool(),
1245            "google.protobuf.FieldOptions",
1246            &self.raw().options,
1247        )
1248    }
1249
1250    /// Gets the number for this extension field.
1251    pub fn number(&self) -> u32 {
1252        self.inner().number
1253    }
1254
1255    /// Gets the name used for JSON serialization of this extension field, e.g. `[my.package.ParentMessage.my_field]`.
1256    pub fn json_name(&self) -> &str {
1257        &self.inner().json_name
1258    }
1259
1260    /// Whether this field is encoded using the proto2 group encoding.
1261    pub fn is_group(&self) -> bool {
1262        matches!(self.inner().kind, KindIndex::Group(_))
1263    }
1264
1265    /// Whether this field is a list type.
1266    ///
1267    /// Equivalent to checking that the cardinality is `Repeated` and that
1268    /// [`is_map`][Self::is_map] returns `false`.
1269    pub fn is_list(&self) -> bool {
1270        self.cardinality() == Cardinality::Repeated && !self.is_map()
1271    }
1272
1273    /// Whether this field is a map type.
1274    ///
1275    /// Protobuf does not allow map fields to be extensions, so this will always return `false`.
1276    pub fn is_map(&self) -> bool {
1277        self.cardinality() == Cardinality::Repeated
1278            && match self.kind() {
1279                Kind::Message(message) => message.is_map_entry(),
1280                _ => false,
1281            }
1282    }
1283
1284    /// Whether this field is a list encoded using [packed encoding](https://developers.google.com/protocol-buffers/docs/encoding#packed).
1285    pub fn is_packed(&self) -> bool {
1286        self.inner().is_packed
1287    }
1288
1289    /// The cardinality of this field.
1290    pub fn cardinality(&self) -> Cardinality {
1291        self.inner().cardinality
1292    }
1293
1294    /// Whether this extension supports distinguishing between an unpopulated field and
1295    /// the default value.
1296    ///
1297    /// This is equivalent to `cardinality() != Cardinality::Repeated`
1298    pub fn supports_presence(&self) -> bool {
1299        self.cardinality() != Cardinality::Repeated
1300    }
1301
1302    /// Gets the [`Kind`] of this field.
1303    pub fn kind(&self) -> Kind {
1304        Kind::new(&self.pool, self.inner().kind)
1305    }
1306
1307    /// Gets the containing message that this field extends.
1308    pub fn containing_message(&self) -> MessageDescriptor {
1309        MessageDescriptor {
1310            pool: self.pool.clone(),
1311            index: self.inner().extendee,
1312        }
1313    }
1314
1315    /// Returns the default value for this extension.
1316    ///
1317    /// This is equivalent to `kind().default_value()`, unless the field is `repeated`,
1318    /// in which case an empty list is returned.
1319    pub fn default_value(&self) -> Value {
1320        if self.is_list() {
1321            Value::List(Vec::default())
1322        } else if self.is_map() {
1323            Value::Map(HashMap::default())
1324        } else if let Some(default_value) = &self.inner().default {
1325            default_value.clone()
1326        } else {
1327            self.kind().default_value()
1328        }
1329    }
1330
1331    pub(crate) fn is_packable(&self) -> bool {
1332        self.inner().kind.is_packable()
1333    }
1334
1335    fn inner(&self) -> &ExtensionDescriptorInner {
1336        &self.pool.inner.extensions[self.index as usize]
1337    }
1338
1339    fn raw(&self) -> &types::FieldDescriptorProto {
1340        let file = self.raw_file();
1341        let path = self.path();
1342        debug_assert_ne!(path.len(), 0);
1343        debug_assert_eq!(path.len() % 2, 0);
1344        if path.len() == 2 {
1345            debug_assert_eq!(path[0], tag::file::EXTENSION);
1346            &file.extension[path[1] as usize]
1347        } else {
1348            let message = find_message_proto(file, &path[..path.len() - 2]);
1349            debug_assert_eq!(path[path.len() - 2], tag::message::EXTENSION);
1350            &message.extension[path[path.len() - 1] as usize]
1351        }
1352    }
1353
1354    fn raw_file(&self) -> &types::FileDescriptorProto {
1355        &self.pool.inner.files[self.inner().id.file as usize].raw
1356    }
1357}
1358
1359impl fmt::Debug for ExtensionDescriptor {
1360    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1361        f.debug_struct("ExtensionDescriptor")
1362            .field("name", &self.name())
1363            .field("full_name", &self.full_name())
1364            .field("json_name", &self.json_name())
1365            .field("number", &self.number())
1366            .field("kind", &self.kind())
1367            .field("cardinality", &self.cardinality())
1368            .field(
1369                "containing_message",
1370                &self.containing_message().name().to_owned(),
1371            )
1372            .field("default_value", &self.default_value())
1373            .field("is_group", &self.is_group())
1374            .field("is_list", &self.is_list())
1375            .field("is_map", &self.is_map())
1376            .field("is_packed", &self.is_packed())
1377            .field("supports_presence", &self.supports_presence())
1378            .finish()
1379    }
1380}
1381
1382impl EnumDescriptor {
1383    /// Gets a reference to the [`DescriptorPool`] this enum type is defined in.
1384    pub fn parent_pool(&self) -> &DescriptorPool {
1385        &self.pool
1386    }
1387
1388    /// Gets the [`FileDescriptor`] this enum type is defined in.
1389    pub fn parent_file(&self) -> FileDescriptor {
1390        FileDescriptor {
1391            pool: self.pool.clone(),
1392            index: self.inner().id.file,
1393        }
1394    }
1395
1396    /// Gets the parent message type if this enum type is nested inside a another message, or `None` otherwise
1397    pub fn parent_message(&self) -> Option<MessageDescriptor> {
1398        self.inner().parent.map(|index| MessageDescriptor {
1399            pool: self.pool.clone(),
1400            index,
1401        })
1402    }
1403
1404    /// Gets the short name of the enum type, e.g. `MyEnum`.
1405    pub fn name(&self) -> &str {
1406        self.inner().id.name()
1407    }
1408
1409    /// Gets the full name of the enum, e.g. `my.package.MyEnum`.
1410    pub fn full_name(&self) -> &str {
1411        self.inner().id.full_name()
1412    }
1413
1414    /// Gets the name of the package this enum type is defined in, e.g. `my.package`.
1415    ///
1416    /// If no package name is set, an empty string is returned.
1417    pub fn package_name(&self) -> &str {
1418        self.raw_file().package()
1419    }
1420
1421    /// Gets the path where this enum type is defined within the [`FileDescriptorProto`][FileDescriptorProto], e.g. `[5, 0]`.
1422    ///
1423    /// See [`path`][prost_types::source_code_info::Location::path] for more details on the structure of the path.
1424    pub fn path(&self) -> &[i32] {
1425        &self.inner().id.path
1426    }
1427
1428    /// Gets a reference to the [`FileDescriptorProto`] in which this enum is defined.
1429    pub fn parent_file_descriptor_proto(&self) -> &FileDescriptorProto {
1430        &self.pool.inner.files[self.inner().id.file as usize].prost
1431    }
1432
1433    /// Gets a reference to the raw [`EnumDescriptorProto`] wrapped by this [`EnumDescriptor`].
1434    pub fn enum_descriptor_proto(&self) -> &EnumDescriptorProto {
1435        let file = self.parent_file_descriptor_proto();
1436        let path = self.path();
1437        debug_assert_ne!(path.len(), 0);
1438        debug_assert_eq!(path.len() % 2, 0);
1439        if path.len() == 2 {
1440            debug_assert_eq!(path[0], tag::file::ENUM_TYPE);
1441            &file.enum_type[path[1] as usize]
1442        } else {
1443            let message = find_message_proto_prost(file, &path[..path.len() - 2]);
1444            debug_assert_eq!(path[path.len() - 2], tag::message::ENUM_TYPE);
1445            &message.enum_type[path[path.len() - 1] as usize]
1446        }
1447    }
1448
1449    /// Decodes the options defined for this [`EnumDescriptor`], including any extension options.
1450    pub fn options(&self) -> DynamicMessage {
1451        decode_options(
1452            self.parent_pool(),
1453            "google.protobuf.EnumOptions",
1454            &self.raw().options,
1455        )
1456    }
1457
1458    /// Gets the default value for the enum type.
1459    pub fn default_value(&self) -> EnumValueDescriptor {
1460        EnumValueDescriptor {
1461            parent: self.clone(),
1462            index: 0,
1463        }
1464    }
1465
1466    /// Gets a [`EnumValueDescriptor`] for the enum value with the given name, or `None` if no such value exists.
1467    pub fn get_value_by_name(&self, name: &str) -> Option<EnumValueDescriptor> {
1468        self.inner()
1469            .value_names
1470            .get(name)
1471            .map(|&index| EnumValueDescriptor {
1472                parent: self.clone(),
1473                index,
1474            })
1475    }
1476
1477    /// Gets a [`EnumValueDescriptor`] for the enum value with the given number, or `None` if no such value exists.
1478    ///
1479    /// If the enum is defined with the `allow_alias` option and has multiple values with the given number, it is
1480    /// unspecified which one will be returned.
1481    pub fn get_value(&self, number: i32) -> Option<EnumValueDescriptor> {
1482        self.inner()
1483            .value_numbers
1484            .binary_search_by(|(l, _)| l.cmp(&number))
1485            .ok()
1486            .map(|index| EnumValueDescriptor {
1487                parent: self.clone(),
1488                index: self.inner().value_numbers[index].1,
1489            })
1490    }
1491
1492    /// Gets an iterator yielding a [`EnumValueDescriptor`] for each value in this enum.
1493    pub fn values(&self) -> impl ExactSizeIterator<Item = EnumValueDescriptor> + '_ {
1494        self.inner()
1495            .value_numbers
1496            .iter()
1497            .map(|&(_, index)| EnumValueDescriptor {
1498                parent: self.clone(),
1499                index,
1500            })
1501    }
1502
1503    /// Gets an iterator over reserved value number ranges in this enum.
1504    pub fn reserved_ranges(&self) -> impl ExactSizeIterator<Item = RangeInclusive<i32>> + '_ {
1505        self.raw()
1506            .reserved_range
1507            .iter()
1508            .map(|n| n.start()..=n.end())
1509    }
1510
1511    /// Gets an iterator over reserved value names in this enum.
1512    pub fn reserved_names(&self) -> impl ExactSizeIterator<Item = &str> + '_ {
1513        self.raw().reserved_name.iter().map(|n| n.as_ref())
1514    }
1515
1516    fn inner(&self) -> &EnumDescriptorInner {
1517        &self.pool.inner.enums[self.index as usize]
1518    }
1519
1520    fn raw(&self) -> &types::EnumDescriptorProto {
1521        find_enum_proto(self.raw_file(), self.path())
1522    }
1523
1524    fn raw_file(&self) -> &types::FileDescriptorProto {
1525        &self.pool.inner.files[self.inner().id.file as usize].raw
1526    }
1527}
1528
1529impl fmt::Debug for EnumDescriptor {
1530    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1531        f.debug_struct("EnumDescriptor")
1532            .field("name", &self.name())
1533            .field("full_name", &self.full_name())
1534            .field("default_value", &self.default_value())
1535            .field("values", &debug_fmt_iter(self.values()))
1536            .finish()
1537    }
1538}
1539
1540impl EnumValueDescriptor {
1541    /// Gets a reference to the [`DescriptorPool`] this enum value is defined in.
1542    pub fn parent_pool(&self) -> &DescriptorPool {
1543        self.parent.parent_pool()
1544    }
1545
1546    /// Gets the [`FileDescriptor`] this enum value is defined in.
1547    pub fn parent_file(&self) -> FileDescriptor {
1548        self.parent.parent_file()
1549    }
1550
1551    /// Gets a reference to the [`EnumDescriptor`] this enum value is defined in.
1552    pub fn parent_enum(&self) -> &EnumDescriptor {
1553        &self.parent
1554    }
1555
1556    /// Gets the short name of the enum value, e.g. `MY_VALUE`.
1557    pub fn name(&self) -> &str {
1558        self.inner().id.name()
1559    }
1560
1561    /// Gets the full name of the enum value, e.g. `my.package.MY_VALUE`.
1562    pub fn full_name(&self) -> &str {
1563        self.inner().id.full_name()
1564    }
1565
1566    /// Gets the path where this enum value is defined within the [`FileDescriptorProto`][FileDescriptorProto], e.g. `[5, 0, 2, 0]`.
1567    ///
1568    /// See [`path`][prost_types::source_code_info::Location::path] for more details on the structure of the path.
1569    pub fn path(&self) -> &[i32] {
1570        &self.inner().id.path
1571    }
1572
1573    /// Gets a reference to the raw [`EnumValueDescriptorProto`] wrapped by this [`EnumValueDescriptor`].
1574    pub fn enum_value_descriptor_proto(&self) -> &EnumValueDescriptorProto {
1575        &self.parent.enum_descriptor_proto().value[self.index as usize]
1576    }
1577
1578    /// Decodes the options defined for this [`EnumValueDescriptor`], including any extension options.
1579    pub fn options(&self) -> DynamicMessage {
1580        decode_options(
1581            self.parent_pool(),
1582            "google.protobuf.EnumValueOptions",
1583            &self.raw().options,
1584        )
1585    }
1586
1587    /// Gets the number representing this enum value.
1588    pub fn number(&self) -> i32 {
1589        self.inner().number
1590    }
1591
1592    fn inner(&self) -> &EnumValueDescriptorInner {
1593        &self.parent.inner().values[self.index as usize]
1594    }
1595
1596    fn raw(&self) -> &types::EnumValueDescriptorProto {
1597        &self.parent.raw().value[self.index as usize]
1598    }
1599}
1600
1601impl fmt::Debug for EnumValueDescriptor {
1602    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1603        f.debug_struct("EnumValueDescriptor")
1604            .field("name", &self.number())
1605            .field("full_name", &self.full_name())
1606            .field("number", &self.number())
1607            .finish()
1608    }
1609}
1610
1611impl OneofDescriptor {
1612    /// Gets a reference to the [`DescriptorPool`] this oneof is defined in.
1613    pub fn parent_pool(&self) -> &DescriptorPool {
1614        self.message.parent_pool()
1615    }
1616
1617    /// Gets the [`FileDescriptor`] this oneof is defined in.
1618    pub fn parent_file(&self) -> FileDescriptor {
1619        self.message.parent_file()
1620    }
1621
1622    /// Gets a reference to the [`MessageDescriptor`] this oneof is defined in.
1623    pub fn parent_message(&self) -> &MessageDescriptor {
1624        &self.message
1625    }
1626
1627    /// Gets the short name of the oneof, e.g. `my_oneof`.
1628    pub fn name(&self) -> &str {
1629        self.inner().id.name()
1630    }
1631
1632    /// Gets the full name of the oneof, e.g. `my.package.MyMessage.my_oneof`.
1633    pub fn full_name(&self) -> &str {
1634        self.inner().id.full_name()
1635    }
1636
1637    /// Gets the path where this oneof is defined within the [`FileDescriptorProto`][FileDescriptorProto], e.g. `[4, 0, 8, 0]`.
1638    ///
1639    /// See [`path`][prost_types::source_code_info::Location::path] for more details on the structure of the path.
1640    pub fn path(&self) -> &[i32] {
1641        &self.inner().id.path
1642    }
1643
1644    /// Gets a reference to the raw [`OneofDescriptorProto`] wrapped by this [`OneofDescriptor`].
1645    pub fn oneof_descriptor_proto(&self) -> &OneofDescriptorProto {
1646        &self.message.descriptor_proto().oneof_decl[self.index as usize]
1647    }
1648
1649    /// Decodes the options defined for this [`OneofDescriptorProto`], including any extension options.
1650    pub fn options(&self) -> DynamicMessage {
1651        decode_options(
1652            self.parent_pool(),
1653            "google.protobuf.OneofOptions",
1654            &self.raw().options,
1655        )
1656    }
1657
1658    /// Gets an iterator yielding a [`FieldDescriptor`] for each field of the parent message this oneof contains.
1659    pub fn fields(&self) -> impl ExactSizeIterator<Item = FieldDescriptor> + '_ {
1660        self.inner().fields.iter().map(|&index| FieldDescriptor {
1661            message: self.parent_message().clone(),
1662            index,
1663        })
1664    }
1665
1666    /// Returns `true` if this is a synthetic oneof generated to support proto3 optional semantics.
1667    ///
1668    /// If `true`, then [`fields`](OneofDescriptor::fields) will yield exactly one field, for which [`FieldDescriptorProto::proto3_optional`] returns true.
1669    pub fn is_synthetic(&self) -> bool {
1670        self.fields().len() == 1
1671            && self
1672                .fields()
1673                .all(|f| f.field_descriptor_proto().proto3_optional())
1674    }
1675
1676    fn inner(&self) -> &OneofDescriptorInner {
1677        &self.message.inner().oneofs[self.index as usize]
1678    }
1679
1680    fn raw(&self) -> &types::OneofDescriptorProto {
1681        &self.message.raw().oneof_decl[self.index as usize]
1682    }
1683}
1684
1685impl fmt::Debug for OneofDescriptor {
1686    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1687        f.debug_struct("OneofDescriptor")
1688            .field("name", &self.name())
1689            .field("full_name", &self.full_name())
1690            .field("fields", &debug_fmt_iter(self.fields()))
1691            .finish()
1692    }
1693}
1694
1695impl ServiceDescriptor {
1696    /// Create a new [`ServiceDescriptor`] referencing the service at `index` within the given [`DescriptorPool`].
1697    ///
1698    /// # Panics
1699    ///
1700    /// Panics if `index` is out-of-bounds.
1701    pub fn new(pool: DescriptorPool, index: usize) -> Self {
1702        debug_assert!(index < pool.services().len());
1703        ServiceDescriptor {
1704            pool,
1705            index: to_index(index),
1706        }
1707    }
1708
1709    /// Returns the index of this [`ServiceDescriptor`] within the parent [`DescriptorPool`].
1710    pub fn index(&self) -> usize {
1711        self.index as usize
1712    }
1713
1714    /// Gets a reference to the [`DescriptorPool`] this service is defined in.
1715    pub fn parent_pool(&self) -> &DescriptorPool {
1716        &self.pool
1717    }
1718
1719    /// Gets the [`FileDescriptor`] this service is defined in.
1720    pub fn parent_file(&self) -> FileDescriptor {
1721        FileDescriptor {
1722            pool: self.pool.clone(),
1723            index: self.inner().id.file,
1724        }
1725    }
1726
1727    /// Gets the short name of the service, e.g. `MyService`.
1728    pub fn name(&self) -> &str {
1729        self.inner().id.name()
1730    }
1731
1732    /// Gets the full name of the service, e.g. `my.package.Service`.
1733    pub fn full_name(&self) -> &str {
1734        self.inner().id.full_name()
1735    }
1736
1737    /// Gets the name of the package this service is defined in, e.g. `my.package`.
1738    ///
1739    /// If no package name is set, an empty string is returned.
1740    pub fn package_name(&self) -> &str {
1741        self.raw_file().package()
1742    }
1743
1744    /// Gets the path where this service is defined within the [`FileDescriptorProto`][FileDescriptorProto], e.g. `[6, 0]`.
1745    ///
1746    /// See [`path`][prost_types::source_code_info::Location::path] for more details on the structure of the path.
1747    pub fn path(&self) -> &[i32] {
1748        &self.inner().id.path
1749    }
1750
1751    /// Gets a reference to the [`FileDescriptorProto`] in which this service is defined.
1752    pub fn parent_file_descriptor_proto(&self) -> &FileDescriptorProto {
1753        &self.pool.inner.files[self.inner().id.file as usize].prost
1754    }
1755
1756    /// Gets a reference to the raw [`ServiceDescriptorProto`] wrapped by this [`ServiceDescriptor`].
1757    pub fn service_descriptor_proto(&self) -> &ServiceDescriptorProto {
1758        let path = self.path();
1759        debug_assert!(!path.is_empty());
1760        &self.parent_file_descriptor_proto().service[*path.last().unwrap() as usize]
1761    }
1762
1763    /// Decodes the options defined for this [`ServiceDescriptorProto`], including any extension options.
1764    pub fn options(&self) -> DynamicMessage {
1765        decode_options(
1766            self.parent_pool(),
1767            "google.protobuf.ServiceOptions",
1768            &self.raw().options,
1769        )
1770    }
1771
1772    /// Gets an iterator yielding a [`MethodDescriptor`] for each method defined in this service.
1773    pub fn methods(&self) -> impl ExactSizeIterator<Item = MethodDescriptor> + '_ {
1774        indices(&self.inner().methods).map(|index| MethodDescriptor {
1775            service: self.clone(),
1776            index,
1777        })
1778    }
1779
1780    fn inner(&self) -> &ServiceDescriptorInner {
1781        &self.pool.inner.services[self.index as usize]
1782    }
1783
1784    fn raw(&self) -> &types::ServiceDescriptorProto {
1785        let path = self.path();
1786        debug_assert!(!path.is_empty());
1787        &self.raw_file().service[*path.last().unwrap() as usize]
1788    }
1789
1790    fn raw_file(&self) -> &types::FileDescriptorProto {
1791        &self.pool.inner.files[self.inner().id.file as usize].raw
1792    }
1793}
1794
1795impl fmt::Debug for ServiceDescriptor {
1796    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1797        f.debug_struct("ServiceDescriptor")
1798            .field("name", &self.name())
1799            .field("full_name", &self.full_name())
1800            .field("index", &self.index())
1801            .field("methods", &debug_fmt_iter(self.methods()))
1802            .finish()
1803    }
1804}
1805
1806impl MethodDescriptor {
1807    /// Create a new [`MethodDescriptor`] referencing the method at `index` within the [`ServiceDescriptor`].
1808    ///
1809    /// # Panics
1810    ///
1811    /// Panics if `index` is out-of-bounds.
1812    pub fn new(service: ServiceDescriptor, index: usize) -> Self {
1813        debug_assert!(index < service.methods().len());
1814        MethodDescriptor {
1815            service,
1816            index: to_index(index),
1817        }
1818    }
1819
1820    /// Gets the index of the method within the parent [`ServiceDescriptor`].
1821    pub fn index(&self) -> usize {
1822        self.index as usize
1823    }
1824
1825    /// Gets a reference to the [`ServiceDescriptor`] this method is defined in.
1826    pub fn parent_service(&self) -> &ServiceDescriptor {
1827        &self.service
1828    }
1829
1830    /// Gets a reference to the [`DescriptorPool`] this method is defined in.
1831    pub fn parent_pool(&self) -> &DescriptorPool {
1832        self.service.parent_pool()
1833    }
1834
1835    /// Gets the [`FileDescriptor`] this method is defined in.
1836    pub fn parent_file(&self) -> FileDescriptor {
1837        self.service.parent_file()
1838    }
1839
1840    /// Gets the short name of the method, e.g. `method`.
1841    pub fn name(&self) -> &str {
1842        self.inner().id.name()
1843    }
1844
1845    /// Gets the full name of the method, e.g. `my.package.MyService.my_method`.
1846    pub fn full_name(&self) -> &str {
1847        self.inner().id.full_name()
1848    }
1849
1850    /// Gets the path where this method is defined within the [`FileDescriptorProto`][FileDescriptorProto], e.g. `[6, 0, 2, 0]`.
1851    ///
1852    /// See [`path`][prost_types::source_code_info::Location::path] for more details on the structure of the path.
1853    pub fn path(&self) -> &[i32] {
1854        &self.inner().id.path
1855    }
1856
1857    /// Gets a reference to the raw [`MethodDescriptorProto`] wrapped by this [`MethodDescriptor`].
1858    pub fn method_descriptor_proto(&self) -> &MethodDescriptorProto {
1859        &self.service.service_descriptor_proto().method[self.index as usize]
1860    }
1861
1862    /// Decodes the options defined for this [`MethodDescriptorProto`], including any extension options.
1863    pub fn options(&self) -> DynamicMessage {
1864        decode_options(
1865            self.parent_pool(),
1866            "google.protobuf.MethodOptions",
1867            &self.raw().options,
1868        )
1869    }
1870
1871    /// Gets the [`MessageDescriptor`] for the input type of this method.
1872    pub fn input(&self) -> MessageDescriptor {
1873        MessageDescriptor {
1874            pool: self.parent_pool().clone(),
1875            index: self.inner().input,
1876        }
1877    }
1878
1879    /// Gets the [`MessageDescriptor`] for the output type of this method.
1880    pub fn output(&self) -> MessageDescriptor {
1881        MessageDescriptor {
1882            pool: self.parent_pool().clone(),
1883            index: self.inner().output,
1884        }
1885    }
1886
1887    /// Returns `true` if the client streams multiple messages.
1888    pub fn is_client_streaming(&self) -> bool {
1889        self.raw().client_streaming()
1890    }
1891
1892    /// Returns `true` if the server streams multiple messages.
1893    pub fn is_server_streaming(&self) -> bool {
1894        self.raw().server_streaming()
1895    }
1896
1897    fn inner(&self) -> &MethodDescriptorInner {
1898        &self.service.inner().methods[self.index as usize]
1899    }
1900
1901    fn raw(&self) -> &types::MethodDescriptorProto {
1902        &self.service.raw().method[self.index as usize]
1903    }
1904}
1905
1906impl fmt::Debug for MethodDescriptor {
1907    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1908        f.debug_struct("MethodDescriptor")
1909            .field("name", &self.name())
1910            .field("full_name", &self.full_name())
1911            .field("index", &self.index())
1912            .field("input", &self.input())
1913            .field("output", &self.output())
1914            .field("is_client_streaming", &self.is_client_streaming())
1915            .field("is_server_streaming", &self.is_server_streaming())
1916            .finish()
1917    }
1918}
1919
1920fn debug_fmt_iter<I>(i: I) -> impl fmt::Debug
1921where
1922    I: Iterator,
1923    I::Item: fmt::Debug,
1924{
1925    struct Wrapper<T>(Vec<T>);
1926
1927    impl<T> fmt::Debug for Wrapper<T>
1928    where
1929        T: fmt::Debug,
1930    {
1931        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
1932            f.debug_list().entries(&self.0).finish()
1933        }
1934    }
1935
1936    Wrapper(i.collect())
1937}
1938
1939#[allow(clippy::ptr_arg)]
1940fn indices<T>(f: &Vec<T>) -> Range<DescriptorIndex> {
1941    0..to_index(f.len())
1942}
1943
1944fn join_name<'a>(namespace: &str, name: &'a str) -> Cow<'a, str> {
1945    if namespace.is_empty() {
1946        Cow::Borrowed(name)
1947    } else {
1948        Cow::Owned(format!("{namespace}.{name}"))
1949    }
1950}
1951
1952fn decode_options<T>(
1953    pool: &DescriptorPool,
1954    name: &str,
1955    option: &Option<Options<T>>,
1956) -> DynamicMessage {
1957    let message_desc = pool
1958        .get_message_by_name(name)
1959        .unwrap_or_else(|| DescriptorPool::global().get_message_by_name(name).unwrap());
1960
1961    let bytes = option
1962        .as_ref()
1963        .map(|o| o.encoded.as_slice())
1964        .unwrap_or_default();
1965    DynamicMessage::decode(message_desc, bytes).unwrap()
1966}
1967
1968fn find_message_proto_prost<'a>(
1969    file: &'a FileDescriptorProto,
1970    path: &[i32],
1971) -> &'a DescriptorProto {
1972    debug_assert_ne!(path.len(), 0);
1973    debug_assert_eq!(path.len() % 2, 0);
1974
1975    let mut message: Option<&'a DescriptorProto> = None;
1976    for part in path.chunks(2) {
1977        match part[0] {
1978            tag::file::MESSAGE_TYPE => message = Some(&file.message_type[part[1] as usize]),
1979            tag::message::NESTED_TYPE => {
1980                message = Some(&message.unwrap().nested_type[part[1] as usize])
1981            }
1982            _ => panic!("invalid message path"),
1983        }
1984    }
1985
1986    message.unwrap()
1987}