1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
mod error;
mod service;
mod ty;

pub use self::{
    error::DescriptorError,
    service::{MethodDescriptor, ServiceDescriptor},
    ty::{
        Cardinality, EnumDescriptor, EnumValueDescriptor, ExtensionDescriptor, FieldDescriptor,
        Kind, MessageDescriptor, OneofDescriptor,
    },
};

use std::{fmt, iter, sync::Arc};

use prost::{bytes::Buf, Message};
use prost_types::{FileDescriptorProto, FileDescriptorSet};

use self::service::ServiceDescriptorInner;

pub(crate) const MAP_ENTRY_KEY_NUMBER: u32 = 1;
pub(crate) const MAP_ENTRY_VALUE_NUMBER: u32 = 2;

/// A `DescriptorPool` is a collection of related descriptors. Typically it will be created from
/// a `FileDescriptorSet` output by the protobuf compiler (see `DescriptorPool::from_file_descriptor_set`)
/// but it may also be built up manually by adding individual files.
///
/// Methods like [`MessageDescriptor::extensions`] will be scoped to just the files contained within the parent
/// `DescriptorPool`.
///
/// This type is uses reference counting internally so it is cheap to clone. Modifying an instance of a
/// pool will not update any existing clones of the instance.
#[derive(Clone, Default)]
pub struct DescriptorPool {
    inner: Arc<DescriptorPoolInner>,
}

#[derive(Clone, Default)]
struct DescriptorPoolInner {
    raw: Vec<FileDescriptorProto>,
    type_map: ty::TypeMap,
    services: Vec<ServiceDescriptorInner>,
}

type FileIndex = u32;
type ServiceIndex = u32;
type MethodIndex = u32;
type MessageIndex = u32;
type OneofIndex = u32;
type ExtensionIndex = u32;
type EnumIndex = u32;
type EnumValueIndex = u32;

impl DescriptorPool {
    /// Creates a new, empty [`DescriptorPool`].
    ///
    /// For the common case of creating a `DescriptorPool` from a single [`FileDescriptorSet`], see
    /// [`DescriptorPool::from_file_descriptor_set`] or [`DescriptorPool::decode`].
    pub fn new() -> Self {
        DescriptorPool::default()
    }

    /// Creates a [`DescriptorPool`] from a [`FileDescriptorSet`].
    ///
    /// This is equivalent to calling [`DescriptorPool::add_file_descriptor_set`] on an empty `DescriptorPool`
    /// instance. See that method's documentation for details.
    pub fn from_file_descriptor_set(
        file_descriptor_set: FileDescriptorSet,
    ) -> Result<Self, DescriptorError> {
        let mut pool = DescriptorPool::new();
        pool.add_file_descriptor_set(file_descriptor_set)?;
        Ok(pool)
    }

    /// Decodes a [`FileDescriptorSet`] from its protobuf byte representation and
    /// creates a new [`DescriptorPool`] wrapping it.
    pub fn decode<B>(bytes: B) -> Result<Self, DescriptorError>
    where
        B: Buf,
    {
        DescriptorPool::from_file_descriptor_set(
            FileDescriptorSet::decode(bytes)
                .map_err(DescriptorError::decode_file_descriptor_set)?,
        )
    }

    /// Adds a new [`FileDescriptorSet`] to this [`DescriptorPool`].
    ///
    /// A file descriptor set may be generated by running the protobuf compiler with the
    /// `--descriptor_set_out` flag. If you are using [`prost-build`](https://crates.io/crates/prost-build),
    /// then [`Config::file_descriptor_set_path`](https://docs.rs/prost-build/latest/prost_build/struct.Config.html#method..file_descriptor_set_path)
    /// is a convenient way to generated it as part of your build.
    ///
    /// This method may return an error if `file_descriptor_set` is invalid, for example
    /// it contains references to types not in the set. If `file_descriptor_set` was created by
    /// the protobuf compiler, these error cases should never occur since it performs its own
    /// validation.
    pub fn add_file_descriptor_set(
        &mut self,
        file_descriptor_set: FileDescriptorSet,
    ) -> Result<(), DescriptorError> {
        self.add_file_descriptor_protos(file_descriptor_set.file)
    }

    /// Adds a collection of file descriptors to this pool.
    ///
    /// The file descriptors may be provided in any order, however all types referenced must be defined
    /// either in one of the files provided, or in a file previously added to the pool.
    ///
    /// Duplicate file descriptors are ignored, however adding two different files with the same name
    /// will return an error.
    pub fn add_file_descriptor_protos<I>(&mut self, files: I) -> Result<(), DescriptorError>
    where
        I: IntoIterator<Item = FileDescriptorProto>,
    {
        // Note we could use `Arc::make_mut` here but by always cloning we
        // avoid putting the pool into an inconsistent state on error.
        let mut inner = (*self.inner).clone();

        let start = inner.raw.len();
        for file in files {
            match inner.raw.iter().find(|f| f.name() == file.name()) {
                None => inner.raw.push(file),
                // Skip duplicate files only if they match exactly
                Some(existing_file) if *existing_file == file => continue,
                Some(_) => return Err(DescriptorError::file_already_exists(file.name())),
            }
        }
        let files = &inner.raw[start..];

        inner.type_map.add_files(files)?;
        inner.type_map.shrink_to_fit();

        for file in files {
            for service in &file.service {
                inner.services.push(ServiceDescriptorInner::from_raw(
                    file,
                    service,
                    &inner.type_map,
                )?);
            }
        }

        self.inner = Arc::new(inner);
        Ok(())
    }

    /// Add a single file descriptor to the pool.
    ///
    /// All types referenced by the file must be defined either in the file itself, or in a file
    /// previously added to the pool.
    pub fn add_file_descriptor_proto(
        &mut self,
        file: FileDescriptorProto,
    ) -> Result<(), DescriptorError> {
        self.add_file_descriptor_protos(iter::once(file))
    }

    /// Gets a iterator over the raw [`FileDescriptorProto`] instances wrapped by this [`DescriptorPool`].
    pub fn file_descriptor_protos(
        &self,
    ) -> impl ExactSizeIterator<Item = &FileDescriptorProto> + '_ {
        self.inner.raw.iter()
    }

    /// Gets an iterator over the services defined in these protobuf files.
    pub fn services(&self) -> impl ExactSizeIterator<Item = ServiceDescriptor> + '_ {
        (0..self.inner.services.len()).map(move |index| ServiceDescriptor::new(self.clone(), index))
    }

    /// Gets an iterator over all messages defined in these protobuf files.
    ///
    /// The iterator includes nested messages defined in another message.
    pub fn all_messages(&self) -> impl ExactSizeIterator<Item = MessageDescriptor> + '_ {
        MessageDescriptor::iter(self)
    }

    /// Gets an iterator over all enums defined in these protobuf files.
    ///
    /// The iterator includes nested enums defined in another message.
    pub fn all_enums(&self) -> impl ExactSizeIterator<Item = EnumDescriptor> + '_ {
        EnumDescriptor::iter(self)
    }

    /// Gets an iterator over all extension fields defined in these protobuf files.
    ///
    /// The iterator includes nested extension fields defined in another message.
    pub fn all_extensions(&self) -> impl ExactSizeIterator<Item = ExtensionDescriptor> + '_ {
        ExtensionDescriptor::iter(self)
    }

    /// Gets a [`MessageDescriptor`] by its fully qualified name, for example `my.package.MessageName`.
    pub fn get_message_by_name(&self, name: &str) -> Option<MessageDescriptor> {
        MessageDescriptor::try_get_by_name(self, name)
    }

    /// Gets an [`EnumDescriptor`] by its fully qualified name, for example `my.package.EnumName`.
    pub fn get_enum_by_name(&self, name: &str) -> Option<EnumDescriptor> {
        EnumDescriptor::try_get_by_name(self, name)
    }
}

impl fmt::Debug for DescriptorPool {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("DescriptorPool")
            .field("services", &debug_fmt_iter(self.services()))
            .field("all_messages", &debug_fmt_iter(self.all_messages()))
            .field("all_enums", &debug_fmt_iter(self.all_enums()))
            .field("all_extensions", &debug_fmt_iter(self.all_extensions()))
            .finish()
    }
}

impl PartialEq for DescriptorPool {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.inner, &other.inner)
    }
}

impl Eq for DescriptorPool {}

fn make_full_name(namespace: &str, name: &str) -> Box<str> {
    let namespace = namespace.trim_start_matches('.');
    if namespace.is_empty() {
        name.into()
    } else {
        let mut full_name = String::with_capacity(namespace.len() + 1 + name.len());
        full_name.push_str(namespace);
        full_name.push('.');
        full_name.push_str(name);
        full_name.into_boxed_str()
    }
}

fn parse_namespace(full_name: &str) -> &str {
    match full_name.rsplit_once('.') {
        Some((namespace, _)) => namespace,
        None => "",
    }
}

fn parse_name(full_name: &str) -> &str {
    match full_name.rsplit_once('.') {
        Some((_, name)) => name,
        None => full_name,
    }
}

fn debug_fmt_iter<I>(i: I) -> impl fmt::Debug
where
    I: Iterator,
    I::Item: fmt::Debug,
{
    struct Wrapper<T>(Vec<T>);

    impl<T> fmt::Debug for Wrapper<T>
    where
        T: fmt::Debug,
    {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.debug_list().entries(&self.0).finish()
        }
    }

    Wrapper(i.collect())
}

#[test]
fn assert_descriptor_send_sync() {
    fn foo<T: Send + Sync>() {}

    foo::<DescriptorPool>();
}