1 | // Take a look at the license at the top of the repository in the LICENSE file. |
2 | |
3 | use crate::translate::*; |
4 | |
5 | // rustdoc-stripper-ignore-next |
6 | /// A `CollationKey` allows ordering strings using the linguistically correct rules for the current locale. |
7 | #[derive (Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] |
8 | pub struct CollationKey(String); |
9 | |
10 | impl<T: AsRef<str>> From<T> for CollationKey { |
11 | // rustdoc-stripper-ignore-next |
12 | /// Converts a string into a `CollationKey` that can be compared with other |
13 | /// collation keys produced by the same function using `std::cmp::Ordering::cmp()`. |
14 | #[doc (alias = "g_utf8_collate_key" )] |
15 | fn from(s: T) -> Self { |
16 | let key: String = |
17 | unsafe { from_glib_full(ptr:ffi::g_utf8_collate_key(str:s.as_ref().to_glib_none().0, len:-1)) }; |
18 | Self(key) |
19 | } |
20 | } |
21 | |
22 | // rustdoc-stripper-ignore-next |
23 | /// A `FilenameCollationKey` allows ordering file names using the linguistically correct rules for the current locale. |
24 | /// Compared to `CollationKey`, filename collation keys take into consideration dots and other characters |
25 | /// commonly found in file names. |
26 | #[derive (Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] |
27 | pub struct FilenameCollationKey(String); |
28 | |
29 | impl<T: AsRef<str>> From<T> for FilenameCollationKey { |
30 | // rustdoc-stripper-ignore-next |
31 | /// Converts a string into a `FilenameCollationKey` that can be compared with other |
32 | /// collation keys produced by the same function using `std::cmp::Ordering::cmp()`. |
33 | #[doc (alias = "g_utf8_collate_key_for_filename" )] |
34 | fn from(s: T) -> Self { |
35 | let key: String = unsafe { |
36 | from_glib_full(ptr:ffi::g_utf8_collate_key_for_filename( |
37 | str:s.as_ref().to_glib_none().0, |
38 | len:-1, |
39 | )) |
40 | }; |
41 | Self(key) |
42 | } |
43 | } |
44 | |
45 | #[cfg (test)] |
46 | mod tests { |
47 | use super::*; |
48 | |
49 | #[test ] |
50 | fn collate() { |
51 | let mut unsorted = vec![ |
52 | String::from("bcd" ), |
53 | String::from("cde" ), |
54 | String::from("abc" ), |
55 | ]; |
56 | |
57 | let sorted = vec![ |
58 | String::from("abc" ), |
59 | String::from("bcd" ), |
60 | String::from("cde" ), |
61 | ]; |
62 | |
63 | unsorted.sort_by(|s1, s2| CollationKey::from(&s1).cmp(&CollationKey::from(&s2))); |
64 | |
65 | assert_eq!(unsorted, sorted); |
66 | } |
67 | |
68 | #[test ] |
69 | fn collate_filenames() { |
70 | let mut unsorted = vec![ |
71 | String::from("bcd.a" ), |
72 | String::from("cde.b" ), |
73 | String::from("abc.c" ), |
74 | ]; |
75 | |
76 | let sorted = vec![ |
77 | String::from("abc.c" ), |
78 | String::from("bcd.a" ), |
79 | String::from("cde.b" ), |
80 | ]; |
81 | |
82 | unsorted.sort_by(|s1, s2| { |
83 | FilenameCollationKey::from(&s1).cmp(&FilenameCollationKey::from(&s2)) |
84 | }); |
85 | |
86 | assert_eq!(unsorted, sorted); |
87 | } |
88 | } |
89 | |