[go: up one dir, main page]

gtk4/
constant_expression.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use glib::{translate::*, value::FromValue};
4
5use crate::{ffi, prelude::*, ConstantExpression};
6
7define_expression!(ConstantExpression, ffi::GtkConstantExpression);
8
9impl ConstantExpression {
10    #[doc(alias = "gtk_constant_expression_new")]
11    #[doc(alias = "gtk_constant_expression_new_for_value")]
12    pub fn new(value: impl Into<glib::Value>) -> Self {
13        assert_initialized_main_thread!();
14        unsafe {
15            from_glib_full(ffi::gtk_constant_expression_new_for_value(
16                value.into().to_glib_none().0,
17            ))
18        }
19    }
20
21    // rustdoc-stripper-ignore-next
22    /// Similar to [`Self::value`] but panics if the value is of a different
23    /// type.
24    #[doc(alias = "gtk_constant_expression_get_value")]
25    #[doc(alias = "get_value")]
26    pub fn value_as<V: for<'b> FromValue<'b> + 'static>(&self) -> V {
27        let value = self.value();
28        value
29            .get_owned::<V>()
30            .expect("Failed to get ConstantExpression value")
31    }
32}
33
34impl std::fmt::Debug for ConstantExpression {
35    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
36        f.debug_struct("ConstantExpression")
37            .field("value_type", &self.value_type())
38            .field("is_static", &self.is_static())
39            .field("value", &self.value())
40            .finish()
41    }
42}
43
44#[cfg(test)]
45mod tests {
46    use super::*;
47    use crate as gtk4;
48
49    #[test]
50    fn test_expressions() {
51        let expr1 = ConstantExpression::new(23);
52        assert_eq!(expr1.value().get::<i32>().unwrap(), 23);
53        let expr2 = ConstantExpression::for_value(&"hello".to_value());
54        assert_eq!(expr2.value().get::<String>().unwrap(), "hello");
55        let expr1 = ConstantExpression::new(23);
56        assert_eq!(expr1.value().get::<i32>().unwrap(), 23);
57        assert_eq!(expr1.value_as::<i32>(), 23);
58        let expr2 = ConstantExpression::for_value(&"hello".to_value());
59        assert_eq!(expr2.value().get::<String>().unwrap(), "hello");
60        assert_eq!(expr2.value_as::<String>(), "hello");
61
62        assert!(expr1.is::<ConstantExpression>());
63    }
64}