Expand description
§azalea-codec
A port of Mojang’s serialization library but with really cool macros.
The library comes with optional support for NBT (through simdnbt) and JSON (through serde_json or simd-json). More serialization formats can be implemented through the Ops trait.
§Example
//! A showcase of some of what azalea-codec can do.
use azalea_codec::Codec;
#[derive(Codec, PartialEq, Clone, Debug)]
enum FormattedText {
Text {
text: String,
#[codec(flatten)]
base: BaseComponent,
},
Translatable(TranslatableComponent),
}
#[derive(Codec, PartialEq, Clone, Debug)]
struct TranslatableComponent {
#[codec(rename = "translate")]
key: String,
#[codec(flatten)]
base: BaseComponent,
}
#[derive(Codec, PartialEq, Clone, Debug)]
#[codec(allow_unknown_keys)]
struct BaseComponent {
#[codec(optional, flatten)]
style: Box<Style>,
#[codec(optional)]
extra: Vec<FormattedText>,
}
#[derive(Codec, PartialEq, Clone, Debug)]
struct Style {
#[codec(optional, default = "white".to_string())]
color: String,
}
fn main() {
// Reading JSON
let json = serde_json::json!({
"text": "Hello, ",
"extra": [{
"translate": "entity.minecraft.cat",
"color": "yellow",
"unknown field!!!": "asdf"
}]
});
let formatted_text = FormattedText::codec_read(&json).unwrap();
assert_eq!(
formatted_text,
FormattedText::Text {
text: "Hello, ".to_string(),
base: BaseComponent {
style: Box::new(Style {
color: "white".into()
}),
extra: vec![FormattedText::Translatable(TranslatableComponent {
key: "entity.minecraft.cat".into(),
base: BaseComponent {
style: Box::new(Style {
color: "yellow".into()
}),
extra: vec![]
}
})]
}
}
);
// Writing NBT
use simdnbt::owned::*;
let nbt: NbtTag = formatted_text.codec_write().unwrap();
assert_eq!(
nbt,
NbtTag::Compound(NbtCompound::from_values(vec![
("text".into(), "Hello, ".into()),
(
"extra".into(),
[NbtCompound::from_values(vec![
("translate".into(), "entity.minecraft.cat".into()),
("color".into(), "yellow".into())
])]
.into()
)
]))
);
}Modules§
Macros§
- impl_
codec_ from - Implement
Codecfor a type that’sInto<T>andFrom<T>for another type that’s already aCodec. - impl_
defaultable - Automatically implements
Defaultableon the given type, allowing it to be supported by#[codec(optional)]fields. - impl_
mapcodec - impl_
mapcodec_ from - See
impl_codec_from. - impl_
serde
Traits§
- Codec
- A data structure that can be written and read.
- Defaultable
- A trait that represents a subset of types with
Default. - Incomplete
- Interchangeable
- Into
Resolvable Item - MapCodec
- MapLike
- NewOk
- Ops
- A data serialization format.
- Resolvable
Item
Derive Macros§
- Codec
- Automatically implement the
Codectrait for arbitrary structs or enums.