glib_macros

Derive Macro ValueDelegate

Source
#[derive(ValueDelegate)]
{
    // Attributes available to this derive:
    #[value_delegate]
}
Expand description

ยงExample

use glib::prelude::*;
use glib::ValueDelegate;

#[derive(ValueDelegate, Debug, PartialEq)]
struct MyInt(i32);

let myv = MyInt(2);
let convertedv = myv.to_value();
assert_eq!(convertedv.get::<MyInt>(), Ok(myv));


#[derive(ValueDelegate, Debug, PartialEq)]
#[value_delegate(from = u32)]
enum MyEnum {
    Zero,
    NotZero(u32)
}

impl From<u32> for MyEnum {
    fn from(v: u32) -> Self {
        match v {
            0 => MyEnum::Zero,
            x => MyEnum::NotZero(x)
        }
    }
}
impl<'a> From<&'a MyEnum> for u32 {
    fn from(v: &'a MyEnum) -> Self {
        match v {
            MyEnum::Zero => 0,
            MyEnum::NotZero(x) => *x
        }
    }
}
impl From<MyEnum> for u32 {
    fn from(v: MyEnum) -> Self {
        match v {
            MyEnum::Zero => 0,
            MyEnum::NotZero(x) => x
        }
    }
}

let myv = MyEnum::NotZero(34);
let convertedv = myv.to_value();
assert_eq!(convertedv.get::<MyEnum>(), Ok(myv));


// If you want your type to be usable inside an `Option`, you can derive `ToValueOptional`
// by adding `nullable` as follows
#[derive(ValueDelegate, Debug, PartialEq)]
#[value_delegate(nullable)]
struct MyString(String);

let myv = Some(MyString("Hello world".to_string()));
let convertedv = myv.to_value();
assert_eq!(convertedv.get::<Option<MyString>>(), Ok(myv));
let convertedv = None::<MyString>.to_value();
assert_eq!(convertedv.get::<Option<MyString>>(), Ok(None::<MyString>));