in uniffi_meta/src/reader.rs [502:576]
fn read_default(&mut self, name: &str, ty: &Type) -> Result<LiteralMetadata> {
let literal_kind = self.read_u8()?;
Ok(match literal_kind {
codes::LIT_STR => {
ensure!(
matches!(ty, Type::String),
"field {name} of type {ty:?} can't have a default value of type string"
);
LiteralMetadata::String(self.read_string()?)
}
codes::LIT_INT => {
let base10_digits = self.read_string()?;
// procmacros emit the type for discriminant values based purely on whether the constant
// is positive or negative.
let ty = if !base10_digits.is_empty()
&& base10_digits.as_bytes()[0] == b'-'
&& ty == &Type::UInt64
{
&Type::Int64
} else {
ty
};
macro_rules! parse_int {
($ty:ident, $variant:ident) => {
LiteralMetadata::$variant(
base10_digits
.parse::<$ty>()
.with_context(|| {
format!("parsing default for field {name}: {base10_digits}")
})?
.into(),
Radix::Decimal,
ty.to_owned(),
)
};
}
match ty {
Type::UInt8 => parse_int!(u8, UInt),
Type::Int8 => parse_int!(i8, Int),
Type::UInt16 => parse_int!(u16, UInt),
Type::Int16 => parse_int!(i16, Int),
Type::UInt32 => parse_int!(u32, UInt),
Type::Int32 => parse_int!(i32, Int),
Type::UInt64 => parse_int!(u64, UInt),
Type::Int64 => parse_int!(i64, Int),
_ => {
bail!("field {name} of type {ty:?} can't have a default value of type integer");
}
}
}
codes::LIT_FLOAT => match ty {
Type::Float32 | Type::Float64 => {
LiteralMetadata::Float(self.read_string()?, ty.to_owned())
}
_ => {
bail!("field {name} of type {ty:?} can't have a default value of type float");
}
},
codes::LIT_BOOL => LiteralMetadata::Boolean(self.read_bool()?),
codes::LIT_NONE => match ty {
Type::Optional { .. } => LiteralMetadata::None,
_ => bail!("field {name} of type {ty:?} can't have a default value of None"),
},
codes::LIT_SOME => match ty {
Type::Optional { inner_type, .. } => LiteralMetadata::Some {
inner: Box::new(self.read_default(name, inner_type)?),
},
_ => bail!("field {name} of type {ty:?} can't have a default value of None"),
},
codes::LIT_EMPTY_SEQ => LiteralMetadata::EmptySequence,
_ => bail!("Unexpected literal kind code: {literal_kind:?}"),
})
}