use crate::build::prost_reflect::ReflectMessage;
use anyhow::Context as _;
pub trait ProtoRepr: ReflectMessage + Default {
type Type;
fn read(&self) -> anyhow::Result<Self::Type>;
fn build(this: &Self::Type) -> Self;
}
pub fn read_required_repr<P: ProtoRepr>(field: &Option<P>) -> anyhow::Result<P::Type> {
field.as_ref().context("missing field")?.read()
}
pub fn read_optional_repr<P: ProtoRepr>(field: &Option<P>) -> anyhow::Result<Option<P::Type>> {
field.as_ref().map(ProtoRepr::read).transpose()
}
pub fn encode<P: ProtoRepr>(msg: &P::Type) -> Vec<u8> {
let msg = P::build(msg);
super::canonical_raw(&msg.encode_to_vec(), &msg.descriptor()).unwrap()
}
pub fn decode<P: ProtoRepr>(bytes: &[u8]) -> anyhow::Result<P::Type> {
P::read(&P::decode(bytes)?)
}