#[derive(Variant)]
{
// Attributes available to this derive:
#[variant_enum]
}
Expand description
Derive macro for serializing/deserializing custom structs/enums as glib::Variant
s.
Example
use glib::prelude::*;
#[derive(Debug, PartialEq, Eq, glib::Variant)]
struct Foo {
some_string: String,
some_int: i32,
}
let v = Foo { some_string: String::from("bar"), some_int: 1 };
let var = v.to_variant();
assert_eq!(var.get::<Foo>(), Some(v));
When storing Vec
s of fixed size types it is a good idea to wrap these in
glib::FixedSizeVariantArray
as serialization/deserialization will be more efficient.
Example
use glib::prelude::*;
#[derive(Debug, PartialEq, Eq, glib::Variant)]
struct Foo {
some_vec: glib::FixedSizeVariantArray<Vec<u32>, u32>,
some_int: i32,
}
let v = Foo { some_vec: vec![1u32, 2u32].into(), some_int: 1 };
let var = v.to_variant();
assert_eq!(var.get::<Foo>(), Some(v));
Enums are serialized as a tuple (sv)
with the first value as a kebab case string for the
enum variant, or just s
if this is a C-style enum. Some additional attributes are supported
for enums:
#[variant_enum(repr)]
to serialize the enum variant as an integer type instead ofs
. The#[repr]
attribute must also be specified on the enum with a sized integer type, and the type must implementCopy
.#[variant_enum(enum)]
usesEnumClass
to serialize/deserialize as nicks. Meant for use withglib::Enum
.#[variant_enum(flags)]
usesFlagsClass
to serialize/deserialize as nicks. Meant for use withglib::flags
.#[variant_enum(enum, repr)]
serializes asi32
. Meant for use withglib::Enum
. The type must also implementCopy
.#[variant_enum(flags, repr)]
serializes asu32
. Meant for use withglib::flags
.
Example
use glib::prelude::*;
#[derive(Debug, PartialEq, Eq, glib::Variant)]
enum Foo {
MyA,
MyB(i32),
MyC { some_int: u32, some_string: String }
}
let v = Foo::MyC { some_int: 1, some_string: String::from("bar") };
let var = v.to_variant();
assert_eq!(var.child_value(0).str(), Some("my-c"));
assert_eq!(var.get::<Foo>(), Some(v));
#[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Variant)]
#[variant_enum(repr)]
#[repr(u8)]
enum Bar {
A,
B = 3,
C = 7
}
let v = Bar::B;
let var = v.to_variant();
assert_eq!(var.get::<u8>(), Some(3));
assert_eq!(var.get::<Bar>(), Some(v));
#[derive(Debug, Copy, Clone, PartialEq, Eq, glib::Enum, glib::Variant)]
#[variant_enum(enum)]
#[enum_type(name = "MyEnum")]
enum MyEnum {
Val,
#[enum_value(name = "My Val")]
ValWithCustomName,
#[enum_value(name = "My Other Val", nick = "other")]
ValWithCustomNameAndNick,
}
let v = MyEnum::ValWithCustomNameAndNick;
let var = v.to_variant();
assert_eq!(var.str(), Some("other"));
assert_eq!(var.get::<MyEnum>(), Some(v));