protobuf/reflect/file/
dynamic.rs

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
use std::collections::HashMap;
use std::sync::Arc;

use crate::descriptor::FileDescriptorProto;
use crate::owning_ref::OwningRef;
use crate::reflect::error::ReflectError;
use crate::reflect::file::index::FileDescriptorCommon;
use crate::reflect::FileDescriptor;

#[derive(Debug)]
pub(crate) struct DynamicFileDescriptor {
    pub(crate) proto: Arc<FileDescriptorProto>,
    pub(crate) common: FileDescriptorCommon,
}

impl DynamicFileDescriptor {
    pub(crate) fn new(
        proto: FileDescriptorProto,
        dependencies: &[FileDescriptor],
    ) -> crate::Result<DynamicFileDescriptor> {
        // Remove undeclared dependencies.
        let dependencies_index: HashMap<_, &FileDescriptor> =
            dependencies.iter().map(|d| (d.proto().name(), d)).collect();

        if dependencies_index.len() != dependencies.len() {
            return Err(ReflectError::NonUniqueDependencies(
                dependencies
                    .iter()
                    .map(|d| d.proto().name())
                    .collect::<Vec<_>>()
                    .join(", "),
            )
            .into());
        }

        let dependencies: Vec<FileDescriptor> = proto
            .dependency
            .iter()
            .map(|d| {
                let dep = dependencies_index.get(d.as_str());
                match dep {
                    Some(dep) => Ok((*dep).clone()),
                    None => Err(ReflectError::DependencyNotFound(
                        d.clone(),
                        proto.name().to_owned(),
                        dependencies
                            .iter()
                            .map(|d| d.proto().name())
                            .collect::<Vec<_>>()
                            .join(", "),
                    )
                    .into()),
                }
            })
            .collect::<crate::Result<Vec<_>>>()?;

        let proto = Arc::new(proto);

        let common = FileDescriptorCommon::new(OwningRef::new_arc(proto.clone()), dependencies)?;

        Ok(DynamicFileDescriptor { proto, common })
    }
}