harmos-protocol 0.1.15

Harmos v1 plugin protobuf messages and gRPC client and server.
Documentation
/* ***
 *
 * Harmos
 *
 * SPDX-License-Identifier: Apache-2.0
 *
 * ***
 */

//! Render Reflection Implementations for Generated Contract Packages.

/* === Modules === */

/* === Re-Exports === */

/* === Imports === */

// Standard Library Imports
use std::{collections::BTreeMap, error::Error};

// Third Party Imports
use prost_types::FileDescriptorSet;

// Local Imports

/* === Constants === */

/* === Macros === */

/* === Type Aliases === */

/* === Structs === */

/* === Enums === */

/* === Traits === */

/* === Implementations === */

/* === Public Functions === */

pub fn generate(descriptors: &FileDescriptorSet, modules: &BTreeMap<String, String>, inventory: &str) -> Result<String, Box<dyn Error>> {
    let mut source = format!(
        r#"// This file is @generated by the protocol generator.
use std::sync::OnceLock;
use prost_reflect::{{DescriptorPool, MessageDescriptor, ReflectMessage}};

fn pool() -> &'static DescriptorPool {{
    static POOL: OnceLock<DescriptorPool> = OnceLock::new();
    POOL.get_or_init(|| {{
        let bytes = include_bytes!("{inventory}");
        DescriptorPool::decode(bytes.as_slice()).expect("generated protocol descriptors")
    }})
}}
"#
    );
    for (package, module) in modules {
        let messages =
            descriptors.file.iter().filter(|file| file.package.as_deref() == Some(package.as_str())).flat_map(|file| &file.message_type);
        for message in messages {
            let name = message.name.as_deref().ok_or("Generate Reflection: Name Each Message")?;
            source.push_str(&format!(
                r#"
impl ReflectMessage for {module}::{name} {{
    fn descriptor(&self) -> MessageDescriptor {{
        pool().get_message_by_name("{package}.{name}").expect("generated message")
    }}
}}
"#
            ));
        }
    }
    Ok(source)
}

/* === Private Functions === */

/* === Tests === */