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
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, sync::Arc};

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

use self::service::ServiceDescriptorInner;

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

/// A wrapper around a [`FileDescriptorSet`], which provides convenient APIs for the
/// protobuf message definitions.
///
/// This type is immutable once constructed, and uses reference counting internally so it is
/// cheap to clone.
#[derive(Clone)]
pub struct FileDescriptor {
    inner: Arc<FileDescriptorInner>,
}

struct FileDescriptorInner {
    raw: FileDescriptorSet,
    type_map: ty::TypeMap,
    services: Box<[ServiceDescriptorInner]>,
}

impl FileDescriptor {
    /// Create a [`FileDescriptor`] from a [`FileDescriptorSet`].
    ///
    /// 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 new(file_descriptor_set: FileDescriptorSet) -> Result<Self, DescriptorError> {
        let inner = FileDescriptor::from_raw(file_descriptor_set)?;
        Ok(FileDescriptor {
            inner: Arc::new(inner),
        })
    }

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

    fn from_raw(raw: FileDescriptorSet) -> Result<FileDescriptorInner, DescriptorError> {
        let mut type_map = ty::TypeMap::new();
        type_map.add_files(&raw)?;
        type_map.shrink_to_fit();
        let type_map_ref = &type_map;

        let services = raw
            .file
            .iter()
            .flat_map(|raw_file| {
                raw_file.service.iter().map(move |raw_service| {
                    ServiceDescriptorInner::from_raw(raw_file, raw_service, type_map_ref)
                })
            })
            .collect::<Result<_, _>>()?;

        Ok(FileDescriptorInner {
            raw,
            type_map,
            services,
        })
    }

    /// Gets a reference to the [`FileDescriptorSet`] wrapped by this [`FileDescriptor`].
    pub fn file_descriptor_set(&self) -> &FileDescriptorSet {
        &self.inner.raw
    }

    /// 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 FileDescriptor {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.debug_struct("FileDescriptor")
            .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 FileDescriptor {
    fn eq(&self, other: &Self) -> bool {
        Arc::ptr_eq(&self.inner, &other.inner)
    }
}

impl Eq for FileDescriptor {}

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::<FileDescriptor>();
}