1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316
// Take a look at the license at the top of the repository in the LICENSE file. //! `Variant` binding and helper traits. //! //! [`Variant`](struct.Variant.html) is an immutable dynamically-typed generic //! container. Its type and value are defined at construction and never change. //! //! `Variant` types are described by [`VariantType`](../struct.VariantType.html) //! "type strings". //! //! Although `GVariant` supports arbitrarily complex types, this binding is //! currently limited to the basic ones: `bool`, `u8`, `i16`, `u16`, `i32`, //! `u32`, `i64`, `u64`, `f64`, `&str`/`String`, and [`VariantDict`](../struct.VariantDict.html). //! //! # Examples //! //! ``` //! use glib::prelude::*; // or `use gtk::prelude::*;` //! use glib::{Variant, FromVariant, ToVariant}; //! use std::collections::HashMap; //! //! // Using the `ToVariant` trait. //! let num = 10.to_variant(); //! //! // `is` tests the type of the value. //! assert!(num.is::<i32>()); //! //! // `get` tries to extract the value. //! assert_eq!(num.get::<i32>(), Some(10)); //! assert_eq!(num.get::<u32>(), None); //! //! // `get_str` tries to borrow a string slice. //! let hello = "Hello!".to_variant(); //! assert_eq!(hello.str(), Some("Hello!")); //! assert_eq!(num.str(), None); //! //! // Variant carrying a Variant //! let variant = Variant::from_variant(&hello); //! let variant = variant.as_variant().unwrap(); //! assert_eq!(variant.str(), Some("Hello!")); //! //! // Variant carrying an array //! let array = ["Hello".to_variant(), "there!".to_variant()]; //! let variant = Variant::from_array::<&str>(&array); //! assert_eq!(variant.n_children(), 2); //! assert_eq!(variant.child_value(0).str(), Some("Hello")); //! assert_eq!(variant.child_value(1).str(), Some("there!")); //! //! // You can also convert from and to a Vec //! let array = vec!["Hello", "there!"].to_variant(); //! assert_eq!(variant.n_children(), 2); //! let vec = <Vec<String>>::from_variant(&array).unwrap(); //! assert_eq!(vec[0], "Hello"); //! //! // Conversion to and from HashMap is also possible //! let mut map: HashMap<u16, &str> = HashMap::new(); //! map.insert(1, "hi"); //! map.insert(2, "there"); //! let variant = map.to_variant(); //! assert_eq!(variant.n_children(), 2); //! let map: HashMap<u16, String> = HashMap::from_variant(&variant).unwrap(); //! assert_eq!(map[&1], "hi"); //! assert_eq!(map[&2], "there"); //! //! // And conversion to and from tuples. //! let variant = ("hello", 42u16, vec![ "there", "you" ],).to_variant(); //! assert_eq!(variant.n_children(), 3); //! assert_eq!(variant.type_().to_str(), "(sqas)"); //! let tuple = <(String, u16, Vec<String>)>::from_variant(&variant).unwrap(); //! assert_eq!(tuple.0, "hello"); //! assert_eq!(tuple.1, 42); //! assert_eq!(tuple.2, &[ "there", "you"]); //! //! // `Option` is supported as well, through maybe types //! let variant = Some("hello").to_variant(); //! assert_eq!(variant.n_children(), 1); //! let mut s = <Option<String>>::from_variant(&variant).unwrap(); //! assert_eq!(s.unwrap(), "hello"); //! s = None; //! let variant = s.to_variant(); //! assert_eq!(variant.n_children(), 0); //! let s = <Option<String>>::from_variant(&variant).unwrap(); //! assert!(s.is_none()); //! ``` use crate::bytes::Bytes; use crate::gstring::GString; use crate::translate::*; use crate::StaticType; use crate::Type; use crate::VariantIter; use crate::VariantTy; use crate::VariantType; use std::borrow::Cow; use std::cmp::{Eq, Ordering, PartialEq, PartialOrd}; use std::collections::HashMap; use std::fmt; use std::hash::{BuildHasher, Hash, Hasher}; use std::slice; use std::str; wrapper! { /// A generic immutable value capable of carrying various types. /// /// See the [module documentation](index.html) for more details. // rustdoc-stripper-ignore-next-stop /// [`Variant`][crate::Variant] is a variant datatype; it can contain one or more values /// along with information about the type of the values. /// /// A [`Variant`][crate::Variant] may contain simple types, like an integer, or a boolean value; /// or complex types, like an array of two strings, or a dictionary of key /// value pairs. A [`Variant`][crate::Variant] is also immutable: once it's been created neither /// its type nor its content can be modified further. /// /// GVariant is useful whenever data needs to be serialized, for example when /// sending method parameters in D-Bus, or when saving settings using GSettings. /// /// When creating a new [`Variant`][crate::Variant], you pass the data you want to store in it /// along with a string representing the type of data you wish to pass to it. /// /// For instance, if you want to create a [`Variant`][crate::Variant] holding an integer value you /// can use: /// /// /// /// **⚠️ The following code is in C ⚠️** /// /// ```C /// GVariant *v = g_variant_new ("u", 40); /// ``` /// /// The string "u" in the first argument tells [`Variant`][crate::Variant] that the data passed to /// the constructor (40) is going to be an unsigned integer. /// /// More advanced examples of [`Variant`][crate::Variant] in use can be found in documentation for /// [GVariant format strings][gvariant-format-strings-pointers]. /// /// The range of possible values is determined by the type. /// /// The type system used by [`Variant`][crate::Variant] is [`VariantType`][crate::VariantType]. /// /// [`Variant`][crate::Variant] instances always have a type and a value (which are given /// at construction time). The type and value of a [`Variant`][crate::Variant] instance /// can never change other than by the [`Variant`][crate::Variant] itself being /// destroyed. A [`Variant`][crate::Variant] cannot contain a pointer. /// /// [`Variant`][crate::Variant] is reference counted using `g_variant_ref()` and /// `g_variant_unref()`. [`Variant`][crate::Variant] also has floating reference counts -- /// see [`ref_sink()`][Self::ref_sink()]. /// /// [`Variant`][crate::Variant] is completely threadsafe. A [`Variant`][crate::Variant] instance can be /// concurrently accessed in any way from any number of threads without /// problems. /// /// [`Variant`][crate::Variant] is heavily optimised for dealing with data in serialised /// form. It works particularly well with data located in memory-mapped /// files. It can perform nearly all deserialisation operations in a /// small constant time, usually touching only a single memory page. /// Serialised [`Variant`][crate::Variant] data can also be sent over the network. /// /// [`Variant`][crate::Variant] is largely compatible with D-Bus. Almost all types of /// [`Variant`][crate::Variant] instances can be sent over D-Bus. See [`VariantType`][crate::VariantType] for /// exceptions. (However, [`Variant`][crate::Variant]'s serialisation format is not the same /// as the serialisation format of a D-Bus message body: use `GDBusMessage`, /// in the gio library, for those.) /// /// For space-efficiency, the [`Variant`][crate::Variant] serialisation format does not /// automatically include the variant's length, type or endianness, /// which must either be implied from context (such as knowledge that a /// particular file format always contains a little-endian /// `G_VARIANT_TYPE_VARIANT` which occupies the whole length of the file) /// or supplied out-of-band (for instance, a length, type and/or endianness /// indicator could be placed at the beginning of a file, network message /// or network stream). /// /// A [`Variant`][crate::Variant]'s size is limited mainly by any lower level operating /// system constraints, such as the number of bits in `gsize`. For /// example, it is reasonable to have a 2GB file mapped into memory /// with `GMappedFile`, and call [`from_data()`][Self::from_data()] on it. /// /// For convenience to C programmers, [`Variant`][crate::Variant] features powerful /// varargs-based value construction and destruction. This feature is /// designed to be embedded in other libraries. /// /// There is a Python-inspired text language for describing [`Variant`][crate::Variant] /// values. [`Variant`][crate::Variant] includes a printer for this language and a parser /// with type inferencing. /// /// ## Memory Use /// /// [`Variant`][crate::Variant] tries to be quite efficient with respect to memory use. /// This section gives a rough idea of how much memory is used by the /// current implementation. The information here is subject to change /// in the future. /// /// The memory allocated by [`Variant`][crate::Variant] can be grouped into 4 broad /// purposes: memory for serialised data, memory for the type /// information cache, buffer management memory and memory for the /// [`Variant`][crate::Variant] structure itself. /// /// ## Serialised Data Memory /// /// This is the memory that is used for storing GVariant data in /// serialised form. This is what would be sent over the network or /// what would end up on disk, not counting any indicator of the /// endianness, or of the length or type of the top-level variant. /// /// The amount of memory required to store a boolean is 1 byte. 16, /// 32 and 64 bit integers and double precision floating point numbers /// use their "natural" size. Strings (including object path and /// signature strings) are stored with a nul terminator, and as such /// use the length of the string plus 1 byte. /// /// Maybe types use no space at all to represent the null value and /// use the same amount of space (sometimes plus one byte) as the /// equivalent non-maybe-typed value to represent the non-null case. /// /// Arrays use the amount of space required to store each of their /// members, concatenated. Additionally, if the items stored in an /// array are not of a fixed-size (ie: strings, other arrays, etc) /// then an additional framing offset is stored for each item. The /// size of this offset is either 1, 2 or 4 bytes depending on the /// overall size of the container. Additionally, extra padding bytes /// are added as required for alignment of child values. /// /// Tuples (including dictionary entries) use the amount of space /// required to store each of their members, concatenated, plus one /// framing offset (as per arrays) for each non-fixed-sized item in /// the tuple, except for the last one. Additionally, extra padding /// bytes are added as required for alignment of child values. /// /// Variants use the same amount of space as the item inside of the /// variant, plus 1 byte, plus the length of the type string for the /// item inside the variant. /// /// As an example, consider a dictionary mapping strings to variants. /// In the case that the dictionary is empty, 0 bytes are required for /// the serialisation. /// /// If we add an item "width" that maps to the int32 value of 500 then /// we will use 4 byte to store the int32 (so 6 for the variant /// containing it) and 6 bytes for the string. The variant must be /// aligned to 8 after the 6 bytes of the string, so that's 2 extra /// bytes. 6 (string) + 2 (padding) + 6 (variant) is 14 bytes used /// for the dictionary entry. An additional 1 byte is added to the /// array as a framing offset making a total of 15 bytes. /// /// If we add another entry, "title" that maps to a nullable string /// that happens to have a value of null, then we use 0 bytes for the /// null value (and 3 bytes for the variant to contain it along with /// its type string) plus 6 bytes for the string. Again, we need 2 /// padding bytes. That makes a total of 6 + 2 + 3 = 11 bytes. /// /// We now require extra padding between the two items in the array. /// After the 14 bytes of the first item, that's 2 bytes required. /// We now require 2 framing offsets for an extra two /// bytes. 14 + 2 + 11 + 2 = 29 bytes to encode the entire two-item /// dictionary. /// /// ## Type Information Cache /// /// For each GVariant type that currently exists in the program a type /// information structure is kept in the type information cache. The /// type information structure is required for rapid deserialisation. /// /// Continuing with the above example, if a [`Variant`][crate::Variant] exists with the /// type "a{sv}" then a type information struct will exist for /// "a{sv}", "{sv}", "s", and "v". Multiple uses of the same type /// will share the same type information. Additionally, all /// single-digit types are stored in read-only static memory and do /// not contribute to the writable memory footprint of a program using /// [`Variant`][crate::Variant]. /// /// Aside from the type information structures stored in read-only /// memory, there are two forms of type information. One is used for /// container types where there is a single element type: arrays and /// maybe types. The other is used for container types where there /// are multiple element types: tuples and dictionary entries. /// /// Array type info structures are 6 * sizeof (void *), plus the /// memory required to store the type string itself. This means that /// on 32-bit systems, the cache entry for "a{sv}" would require 30 /// bytes of memory (plus malloc overhead). /// /// Tuple type info structures are 6 * sizeof (void *), plus 4 * /// sizeof (void *) for each item in the tuple, plus the memory /// required to store the type string itself. A 2-item tuple, for /// example, would have a type information structure that consumed /// writable memory in the size of 14 * sizeof (void *) (plus type /// string) This means that on 32-bit systems, the cache entry for /// "{sv}" would require 61 bytes of memory (plus malloc overhead). /// /// This means that in total, for our "a{sv}" example, 91 bytes of /// type information would be allocated. /// /// The type information cache, additionally, uses a `GHashTable` to /// store and look up the cached items and stores a pointer to this /// hash table in static storage. The hash table is freed when there /// are zero items in the type cache. /// /// Although these sizes may seem large it is important to remember /// that a program will probably only have a very small number of /// different types of values in it and that only one type information /// structure is required for many different values of the same type. /// /// ## Buffer Management Memory /// /// [`Variant`][crate::Variant] uses an internal buffer management structure to deal /// with the various different possible sources of serialised data /// that it uses. The buffer is responsible for ensuring that the /// correct call is made when the data is no longer in use by /// [`Variant`][crate::Variant]. This may involve a `g_free()` or a `g_slice_free()` or /// even `g_mapped_file_unref()`. /// /// One buffer management structure is used for each chunk of /// serialised data. The size of the buffer management structure /// is 4 * (void *). On 32-bit systems, that's 16 bytes. /// /// ## GVariant structure /// /// The size of a [`Variant`][crate::Variant] structure is 6 * (void *). On 32-bit /// systems, that's 24 bytes. /// /// [`Variant`][crate::Variant] structures only exist if they are explicitly created /// with API calls. For example, if a [`Variant`][crate::Variant] is constructed out of /// serialised data for the example given above (with the dictionary) /// then although there are 9 individual values that comprise the /// entire dictionary (two keys, two values, two variants containing /// the values, two dictionary entries, plus the dictionary itself), /// only 1 [`Variant`][crate::Variant] instance exists -- the one referring to the /// dictionary. /// /// If calls are made to start accessing the other values then /// [`Variant`][crate::Variant] instances will exist for those values only for as long /// as they are in use (ie: until you call `g_variant_unref()`). The /// type information is shared. The serialised data and the buffer /// management structure for that serialised data is shared by the /// child. /// /// ## Summary /// /// To put the entire example together, for our dictionary mapping /// strings to variants (with two entries, as given above), we are /// using 91 bytes of memory for type information, 29 bytes of memory /// for the serialised data, 16 bytes for buffer management and 24 /// bytes for the [`Variant`][crate::Variant] instance, or a total of 160 bytes, plus /// malloc overhead. If we were to use [`child_value()`][Self::child_value()] to /// access the two dictionary entries, we would use an additional 48 /// bytes. If we were to have other dictionaries of the same type, we /// would use more memory for the serialised data and buffer /// management for those dictionaries, but the type information would /// be shared. #[doc(alias = "GVariant")] pub struct Variant(Shared<ffi::GVariant>); match fn { ref => |ptr| ffi::g_variant_ref_sink(ptr), unref => |ptr| ffi::g_variant_unref(ptr), } } impl StaticType for Variant { fn static_type() -> Type { Type::VARIANT } } #[doc(hidden)] impl crate::value::ValueType for Variant { type Type = Variant; } #[doc(hidden)] unsafe impl<'a> crate::value::FromValue<'a> for Variant { type Checker = crate::value::GenericValueTypeOrNoneChecker<Self>; unsafe fn from_value(value: &'a crate::Value) -> Self { let ptr = gobject_ffi::g_value_dup_variant(value.to_glib_none().0); assert!(!ptr.is_null()); from_glib_full(ptr) } } #[doc(hidden)] impl crate::value::ToValue for Variant { fn to_value(&self) -> crate::Value { unsafe { let mut value = crate::Value::from_type(Variant::static_type()); gobject_ffi::g_value_take_variant( value.to_glib_none_mut().0, self.to_glib_full() as *mut _, ); value } } fn value_type(&self) -> crate::Type { Variant::static_type() } } #[doc(hidden)] impl crate::value::ToValueOptional for Variant { fn to_value_optional(s: Option<&Self>) -> crate::Value { let mut value = crate::Value::for_value_type::<Self>(); unsafe { gobject_ffi::g_value_take_variant( value.to_glib_none_mut().0, s.to_glib_full() as *mut _, ); } value } } impl Variant { /// Returns the type of the value. // rustdoc-stripper-ignore-next-stop /// Determines the type of `self`. /// /// The return value is valid for the lifetime of `self` and must not /// be freed. /// /// # Returns /// /// a [`VariantType`][crate::VariantType] pub fn type_(&self) -> &VariantTy { unsafe { VariantTy::from_ptr(ffi::g_variant_get_type(self.to_glib_none().0)) } } /// Returns `true` if the type of the value corresponds to `T`. #[inline] pub fn is<T: StaticVariantType>(&self) -> bool { self.type_() == T::static_variant_type() } /// Tries to extract a value of type `T`. /// /// Returns `Some` if `T` matches the variant's type. // rustdoc-stripper-ignore-next-stop /// Deconstructs a [`Variant`][crate::Variant] instance. /// /// Think of this function as an analogue to `scanf()`. /// /// The arguments that are expected by this function are entirely /// determined by `format_string`. `format_string` also restricts the /// permissible types of `self`. It is an error to give a value with /// an incompatible type. See the section on /// [GVariant format strings][gvariant-format-strings]. /// Please note that the syntax of the format string is very likely to be /// extended in the future. /// /// `format_string` determines the C types that are used for unpacking /// the values and also determines if the values are copied or borrowed, /// see the section on /// [GVariant format strings][gvariant-format-strings-pointers]. /// ## `format_string` /// a [`Variant`][crate::Variant] format string #[inline] pub fn get<T: FromVariant>(&self) -> Option<T> { T::from_variant(self) } /// Boxes value. #[inline] pub fn from_variant(value: &Variant) -> Self { unsafe { from_glib_none(ffi::g_variant_new_variant(value.to_glib_none().0)) } } /// Unboxes self. /// /// Returns `Some` if self contains a `Variant`. #[inline] #[doc(alias = "get_variant")] pub fn as_variant(&self) -> Option<Variant> { unsafe { from_glib_full(ffi::g_variant_get_variant(self.to_glib_none().0)) } } /// Reads a child item out of a container `Variant` instance. /// /// # Panics /// /// * if `self` is not a container type. /// * if given `index` is larger than number of children. // rustdoc-stripper-ignore-next-stop /// Reads a child item out of a container [`Variant`][crate::Variant] instance. This /// includes variants, maybes, arrays, tuples and dictionary /// entries. It is an error to call this function on any other type of /// [`Variant`][crate::Variant]. /// /// It is an error if `index_` is greater than the number of child items /// in the container. See [`n_children()`][Self::n_children()]. /// /// The returned value is never floating. You should free it with /// `g_variant_unref()` when you're done with it. /// /// Note that values borrowed from the returned child are not guaranteed to /// still be valid after the child is freed even if you still hold a reference /// to `self`, if `self` has not been serialised at the time this function is /// called. To avoid this, you can serialize `self` by calling /// [`data()`][Self::data()] and optionally ignoring the return value. /// /// There may be implementation specific restrictions on deeply nested values, /// which would result in the unit tuple being returned as the child value, /// instead of further nested children. [`Variant`][crate::Variant] is guaranteed to handle /// nesting up to at least 64 levels. /// /// This function is O(1). /// ## `index_` /// the index of the child to fetch /// /// # Returns /// /// the child at the specified index #[doc(alias = "get_child_value")] #[doc(alias = "g_variant_get_child_value")] pub fn child_value(&self, index: usize) -> Variant { assert!(index < self.n_children()); assert!(self.is_container()); unsafe { from_glib_full(ffi::g_variant_get_child_value(self.to_glib_none().0, index)) } } /// Tries to extract a `&str`. /// /// Returns `Some` if the variant has a string type (`s`, `o` or `g` type /// strings). #[doc(alias = "get_str")] #[doc(alias = "g_variant_get_string")] pub fn str(&self) -> Option<&str> { unsafe { match self.type_().to_str() { "s" | "o" | "g" => { let mut len = 0; let ptr = ffi::g_variant_get_string(self.to_glib_none().0, &mut len); let ret = str::from_utf8_unchecked(slice::from_raw_parts( ptr as *const u8, len as usize, )); Some(ret) } _ => None, } } } /// Creates a new GVariant array from children. /// /// All children must be of type `T`. pub fn from_array<T: StaticVariantType>(children: &[Variant]) -> Self { let type_ = T::static_variant_type(); for child in children { assert_eq!(type_, child.type_()); } unsafe { from_glib_none(ffi::g_variant_new_array( type_.as_ptr() as *const _, children.to_glib_none().0, children.len(), )) } } /// Creates a new GVariant tuple from children. pub fn from_tuple(children: &[Variant]) -> Self { unsafe { from_glib_none(ffi::g_variant_new_tuple( children.to_glib_none().0, children.len(), )) } } /// Creates a new maybe Variant. pub fn from_maybe<T: StaticVariantType>(child: Option<&Variant>) -> Self { let type_ = T::static_variant_type(); let ptr = match child { Some(child) => { assert_eq!(type_, child.type_()); child.to_glib_none().0 } None => std::ptr::null(), }; unsafe { from_glib_none(ffi::g_variant_new_maybe( type_.as_ptr() as *const _, ptr as *mut ffi::GVariant, )) } } /// Constructs a new serialised-mode GVariant instance. // rustdoc-stripper-ignore-next-stop /// Constructs a new serialised-mode [`Variant`][crate::Variant] instance. This is the /// inner interface for creation of new serialised values that gets /// called from various functions in gvariant.c. /// /// A reference is taken on `bytes`. /// /// The data in `bytes` must be aligned appropriately for the `type_` being loaded. /// Otherwise this function will internally create a copy of the memory (since /// GLib 2.60) or (in older versions) fail and exit the process. /// ## `type_` /// a [`VariantType`][crate::VariantType] /// ## `bytes` /// a [`Bytes`][crate::Bytes] /// ## `trusted` /// if the contents of `bytes` are trusted /// /// # Returns /// /// a new [`Variant`][crate::Variant] with a floating reference #[doc(alias = "g_variant_new_from_bytes")] pub fn from_bytes<T: StaticVariantType>(bytes: &Bytes) -> Self { unsafe { from_glib_none(ffi::g_variant_new_from_bytes( T::static_variant_type().as_ptr() as *const _, bytes.to_glib_none().0, false.into_glib(), )) } } /// Constructs a new serialised-mode GVariant instance. /// /// This is the same as `from_bytes`, except that checks on the passed /// data are skipped. /// /// You should not use this function on data from external sources. /// /// # Safety /// /// Since the data is not validated, this is potentially dangerous if called /// on bytes which are not guaranteed to have come from serialising another /// Variant. The caller is responsible for ensuring bad data is not passed in. pub unsafe fn from_bytes_trusted<T: StaticVariantType>(bytes: &Bytes) -> Self { from_glib_none(ffi::g_variant_new_from_bytes( T::static_variant_type().as_ptr() as *const _, bytes.to_glib_none().0, true.into_glib(), )) } /// Returns the serialised form of a GVariant instance. // rustdoc-stripper-ignore-next-stop /// Returns a pointer to the serialised form of a [`Variant`][crate::Variant] instance. /// The semantics of this function are exactly the same as /// [`data()`][Self::data()], except that the returned [`Bytes`][crate::Bytes] holds /// a reference to the variant data. /// /// # Returns /// /// A new [`Bytes`][crate::Bytes] representing the variant data #[doc(alias = "get_data_as_bytes")] #[doc(alias = "g_variant_get_data_as_bytes")] pub fn data_as_bytes(&self) -> Bytes { unsafe { from_glib_full(ffi::g_variant_get_data_as_bytes(self.to_glib_none().0)) } } /// Determines the number of children in a container GVariant instance. // rustdoc-stripper-ignore-next-stop /// Determines the number of children in a container [`Variant`][crate::Variant] instance. /// This includes variants, maybes, arrays, tuples and dictionary /// entries. It is an error to call this function on any other type of /// [`Variant`][crate::Variant]. /// /// For variants, the return value is always 1. For values with maybe /// types, it is always zero or one. For arrays, it is the length of the /// array. For tuples it is the number of tuple items (which depends /// only on the type). For dictionary entries, it is always 2 /// /// This function is O(1). /// /// # Returns /// /// the number of children in the container #[doc(alias = "g_variant_n_children")] pub fn n_children(&self) -> usize { assert!(self.is_container()); unsafe { ffi::g_variant_n_children(self.to_glib_none().0) } } /// Create an iterator over items in the variant. pub fn iter(&self) -> VariantIter { assert!(self.is_container()); VariantIter::new(self.clone()) } /// Variant has a container type. // rustdoc-stripper-ignore-next-stop /// Checks if `self` is a container. /// /// # Returns /// /// [`true`] if `self` is a container #[doc(alias = "g_variant_is_container")] pub fn is_container(&self) -> bool { unsafe { ffi::g_variant_is_container(self.to_glib_none().0) != ffi::GFALSE } } } unsafe impl Send for Variant {} unsafe impl Sync for Variant {} impl fmt::Debug for Variant { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { f.debug_struct("Variant") .field("ptr", &self.to_glib_none().0) .field("type", &self.type_()) .field("value", &self.to_string()) .finish() } } impl fmt::Display for Variant { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let serialized: GString = unsafe { from_glib_full(ffi::g_variant_print( self.to_glib_none().0, false.into_glib(), )) }; f.write_str(&serialized) } } impl PartialEq for Variant { #[doc(alias = "g_variant_equal")] fn eq(&self, other: &Self) -> bool { unsafe { from_glib(ffi::g_variant_equal( self.to_glib_none().0 as *const _, other.to_glib_none().0 as *const _, )) } } } impl Eq for Variant {} impl PartialOrd for Variant { fn partial_cmp(&self, other: &Self) -> Option<Ordering> { unsafe { if ffi::g_variant_classify(self.to_glib_none().0) != ffi::g_variant_classify(other.to_glib_none().0) { return None; } if self.is_container() { return None; } let res = ffi::g_variant_compare( self.to_glib_none().0 as *const _, other.to_glib_none().0 as *const _, ); Some(res.cmp(&0)) } } } impl Hash for Variant { #[doc(alias = "g_variant_hash")] fn hash<H: Hasher>(&self, state: &mut H) { unsafe { state.write_u32(ffi::g_variant_hash(self.to_glib_none().0 as *const _)) } } } /// Converts to `Variant`. pub trait ToVariant { /// Returns a `Variant` clone of `self`. fn to_variant(&self) -> Variant; } /// Extracts a value. pub trait FromVariant: Sized + StaticVariantType { /// Tries to extract a value. /// /// Returns `Some` if the variant's type matches `Self`. fn from_variant(variant: &Variant) -> Option<Self>; } /// Returns `VariantType` of `Self`. pub trait StaticVariantType { /// Returns the `VariantType` corresponding to `Self`. fn static_variant_type() -> Cow<'static, VariantTy>; } impl StaticVariantType for Variant { fn static_variant_type() -> Cow<'static, VariantTy> { unsafe { VariantTy::from_str_unchecked("v").into() } } } impl<'a, T: ?Sized + ToVariant> ToVariant for &'a T { fn to_variant(&self) -> Variant { <T as ToVariant>::to_variant(self) } } impl<'a, T: ?Sized + StaticVariantType> StaticVariantType for &'a T { fn static_variant_type() -> Cow<'static, VariantTy> { <T as StaticVariantType>::static_variant_type() } } macro_rules! impl_numeric { ($name:ty, $type_str:expr, $new_fn:ident, $get_fn:ident) => { impl StaticVariantType for $name { fn static_variant_type() -> Cow<'static, VariantTy> { unsafe { VariantTy::from_str_unchecked($type_str).into() } } } impl ToVariant for $name { fn to_variant(&self) -> Variant { unsafe { from_glib_none(ffi::$new_fn(*self)) } } } impl FromVariant for $name { fn from_variant(variant: &Variant) -> Option<Self> { unsafe { if variant.is::<Self>() { Some(ffi::$get_fn(variant.to_glib_none().0)) } else { None } } } } }; } impl_numeric!(u8, "y", g_variant_new_byte, g_variant_get_byte); impl_numeric!(i16, "n", g_variant_new_int16, g_variant_get_int16); impl_numeric!(u16, "q", g_variant_new_uint16, g_variant_get_uint16); impl_numeric!(i32, "i", g_variant_new_int32, g_variant_get_int32); impl_numeric!(u32, "u", g_variant_new_uint32, g_variant_get_uint32); impl_numeric!(i64, "x", g_variant_new_int64, g_variant_get_int64); impl_numeric!(u64, "t", g_variant_new_uint64, g_variant_get_uint64); impl_numeric!(f64, "d", g_variant_new_double, g_variant_get_double); impl StaticVariantType for bool { fn static_variant_type() -> Cow<'static, VariantTy> { unsafe { VariantTy::from_str_unchecked("b").into() } } } impl ToVariant for bool { fn to_variant(&self) -> Variant { unsafe { from_glib_none(ffi::g_variant_new_boolean(self.into_glib())) } } } impl FromVariant for bool { fn from_variant(variant: &Variant) -> Option<Self> { unsafe { if variant.is::<Self>() { Some(from_glib(ffi::g_variant_get_boolean( variant.to_glib_none().0, ))) } else { None } } } } impl StaticVariantType for String { fn static_variant_type() -> Cow<'static, VariantTy> { unsafe { VariantTy::from_str_unchecked("s").into() } } } impl ToVariant for String { fn to_variant(&self) -> Variant { self[..].to_variant() } } impl FromVariant for String { fn from_variant(variant: &Variant) -> Option<Self> { variant.str().map(String::from) } } impl StaticVariantType for str { fn static_variant_type() -> Cow<'static, VariantTy> { unsafe { VariantTy::from_str_unchecked("s").into() } } } impl ToVariant for str { fn to_variant(&self) -> Variant { unsafe { from_glib_none(ffi::g_variant_new_take_string(self.to_glib_full())) } } } impl<T: StaticVariantType> StaticVariantType for Option<T> { fn static_variant_type() -> Cow<'static, VariantTy> { let child_type = T::static_variant_type(); let signature = format!("m{}", child_type.to_str()); VariantType::new(&signature) .expect("incorrect signature") .into() } } impl<T: StaticVariantType + ToVariant> ToVariant for Option<T> { fn to_variant(&self) -> Variant { Variant::from_maybe::<T>(self.as_ref().map(|m| m.to_variant()).as_ref()) } } impl<T: StaticVariantType + FromVariant> FromVariant for Option<T> { fn from_variant(variant: &Variant) -> Option<Self> { unsafe { if variant.is::<Self>() { let c_child = ffi::g_variant_get_maybe(variant.to_glib_none().0); if !c_child.is_null() { let child: Variant = from_glib_full(c_child); Some(T::from_variant(&child)) } else { Some(None) } } else { None } } } } impl<T: StaticVariantType> StaticVariantType for [T] { fn static_variant_type() -> Cow<'static, VariantTy> { let child_type = T::static_variant_type(); let signature = format!("a{}", child_type.to_str()); VariantType::new(&signature) .expect("incorrect signature") .into() } } impl<T: StaticVariantType + ToVariant> ToVariant for [T] { fn to_variant(&self) -> Variant { let mut vec = Vec::with_capacity(self.len()); for child in self { vec.push(child.to_variant()); } Variant::from_array::<T>(&vec) } } impl<T: FromVariant> FromVariant for Vec<T> { fn from_variant(variant: &Variant) -> Option<Self> { let mut vec = Vec::with_capacity(variant.n_children()); for i in 0..variant.n_children() { match variant.child_value(i).get() { Some(child) => vec.push(child), None => return None, } } Some(vec) } } impl<T: StaticVariantType + ToVariant> ToVariant for Vec<T> { fn to_variant(&self) -> Variant { let mut vec = Vec::with_capacity(self.len()); for child in self { vec.push(child.to_variant()); } Variant::from_array::<T>(&vec) } } impl<T: StaticVariantType> StaticVariantType for Vec<T> { fn static_variant_type() -> Cow<'static, VariantTy> { <[T]>::static_variant_type() } } impl<K, V, H> FromVariant for HashMap<K, V, H> where K: FromVariant + Eq + Hash, V: FromVariant, H: BuildHasher + Default, { fn from_variant(variant: &Variant) -> Option<Self> { let mut map = HashMap::default(); for i in 0..variant.n_children() { let entry = variant.child_value(i); let key = match entry.child_value(0).get() { Some(key) => key, None => return None, }; let val = match entry.child_value(1).get() { Some(val) => val, None => return None, }; map.insert(key, val); } Some(map) } } impl<K, V> ToVariant for HashMap<K, V> where K: StaticVariantType + ToVariant + Eq + Hash, V: StaticVariantType + ToVariant, { fn to_variant(&self) -> Variant { let mut vec = Vec::with_capacity(self.len()); for (key, value) in self { let entry = DictEntry::new(key, value).to_variant(); vec.push(entry); } Variant::from_array::<DictEntry<K, V>>(&vec) } } /// A Dictionary entry. /// /// While GVariant format allows a dictionary entry to be an independent type, typically you'll need /// to use this in a dictionary, which is simply an array of dictionary entries. The following code /// creates a dictionary: /// /// ``` ///# use glib::prelude::*; // or `use gtk::prelude::*;` /// use glib::{Variant, FromVariant, ToVariant}; /// use glib::variant::DictEntry; /// /// let entries = vec![ /// DictEntry::new("uuid", 1000u32).to_variant(), /// DictEntry::new("guid", 1001u32).to_variant(), /// ]; /// let dict = Variant::from_array::<DictEntry<&str, u32>>(&entries); /// assert_eq!(dict.n_children(), 2); /// assert_eq!(dict.type_().to_str(), "a{su}"); /// ``` pub struct DictEntry<K, V> { key: K, value: V, } impl<K, V> DictEntry<K, V> where K: StaticVariantType + ToVariant + Eq + Hash, V: StaticVariantType + ToVariant, { pub fn new(key: K, value: V) -> Self { Self { key, value } } pub fn key(&self) -> &K { &self.key } pub fn value(&self) -> &V { &self.value } } impl<K, V> FromVariant for DictEntry<K, V> where K: FromVariant + Eq + Hash, V: FromVariant, { fn from_variant(variant: &Variant) -> Option<Self> { let key = match variant.child_value(0).get() { Some(key) => key, None => return None, }; let value = match variant.child_value(1).get() { Some(value) => value, None => return None, }; Some(Self { key, value }) } } impl<K, V> ToVariant for DictEntry<K, V> where K: StaticVariantType + ToVariant + Eq + Hash, V: StaticVariantType + ToVariant, { fn to_variant(&self) -> Variant { unsafe { from_glib_none(ffi::g_variant_new_dict_entry( self.key.to_variant().to_glib_none().0, self.value.to_variant().to_glib_none().0, )) } } } impl ToVariant for Variant { fn to_variant(&self) -> Variant { Variant::from_variant(self) } } impl FromVariant for Variant { fn from_variant(variant: &Variant) -> Option<Self> { variant.as_variant() } } impl<K: StaticVariantType, V: StaticVariantType> StaticVariantType for DictEntry<K, V> { fn static_variant_type() -> Cow<'static, VariantTy> { let key_type = K::static_variant_type(); let value_type = V::static_variant_type(); let signature = format!("{{{}{}}}", key_type.to_str(), value_type.to_str()); VariantType::new(&signature) .expect("incorrect signature") .into() } } impl<K, V, H> StaticVariantType for HashMap<K, V, H> where K: StaticVariantType, V: StaticVariantType, H: BuildHasher + Default, { fn static_variant_type() -> Cow<'static, VariantTy> { let key_type = K::static_variant_type(); let value_type = V::static_variant_type(); let signature = format!("a{{{}{}}}", key_type.to_str(), value_type.to_str()); VariantType::new(&signature) .expect("incorrect signature") .into() } } macro_rules! tuple_impls { ($($len:expr => ($($n:tt $name:ident)+))+) => { $( impl<$($name),+> StaticVariantType for ($($name,)+) where $($name: StaticVariantType,)+ { fn static_variant_type() -> Cow<'static, VariantTy> { let mut signature = String::with_capacity(255); signature.push('('); $( signature.push_str($name::static_variant_type().to_str()); )+ signature.push(')'); VariantType::new(&signature).expect("incorrect signature").into() } } impl<$($name),+> FromVariant for ($($name,)+) where $($name: FromVariant,)+ { fn from_variant(variant: &Variant) -> Option<Self> { Some(( $( match $name::from_variant(&variant.child_value($n)) { Some(field) => field, None => return None, }, )+ )) } } impl<$($name),+> ToVariant for ($($name,)+) where $($name: ToVariant,)+ { fn to_variant(&self) -> Variant { let mut fields = Vec::with_capacity($len); $( let field = self.$n.to_variant(); fields.push(field); )+ Variant::from_tuple(&fields) } } )+ } } tuple_impls! { 1 => (0 T0) 2 => (0 T0 1 T1) 3 => (0 T0 1 T1 2 T2) 4 => (0 T0 1 T1 2 T2 3 T3) 5 => (0 T0 1 T1 2 T2 3 T3 4 T4) 6 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5) 7 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6) 8 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7) 9 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8) 10 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9) 11 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10) 12 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11) 13 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12) 14 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13) 15 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14) 16 => (0 T0 1 T1 2 T2 3 T3 4 T4 5 T5 6 T6 7 T7 8 T8 9 T9 10 T10 11 T11 12 T12 13 T13 14 T14 15 T15) } #[cfg(test)] mod tests { use super::*; use std::collections::{HashMap, HashSet}; macro_rules! unsigned { ($name:ident, $ty:ident) => { #[test] fn $name() { let mut n = $ty::max_value(); while n > 0 { let v = n.to_variant(); assert_eq!(v.get(), Some(n)); n /= 2; } } }; } macro_rules! signed { ($name:ident, $ty:ident) => { #[test] fn $name() { let mut n = $ty::max_value(); while n > 0 { let v = n.to_variant(); assert_eq!(v.get(), Some(n)); let v = (-n).to_variant(); assert_eq!(v.get(), Some(-n)); n /= 2; } } }; } unsigned!(test_u8, u8); unsigned!(test_u16, u16); unsigned!(test_u32, u32); unsigned!(test_u64, u64); signed!(test_i16, i16); signed!(test_i32, i32); signed!(test_i64, i64); #[test] fn test_str() { let s = "this is a test"; let v = s.to_variant(); assert_eq!(v.str(), Some(s)); } #[test] fn test_string() { let s = String::from("this is a test"); let v = s.to_variant(); assert_eq!(v.get(), Some(s)); } #[test] fn test_eq() { let v1 = "this is a test".to_variant(); let v2 = "this is a test".to_variant(); let v3 = "test".to_variant(); assert_eq!(v1, v2); assert!(v1 != v3); } #[test] fn test_hash() { let v1 = "this is a test".to_variant(); let v2 = "this is a test".to_variant(); let v3 = "test".to_variant(); let mut set = HashSet::new(); set.insert(v1); assert!(set.contains(&v2)); assert!(!set.contains(&v3)); assert_eq!( <HashMap<&str, (&str, u8, u32)>>::static_variant_type().to_str(), "a{s(syu)}" ); } #[test] fn test_array() { // Test just the signature for now. assert_eq!(<Vec<&str>>::static_variant_type().to_str(), "as"); assert_eq!( <Vec<(&str, u8, u32)>>::static_variant_type().to_str(), "a(syu)" ); } }