ps_uuid/methods/
with_variant.rs1use crate::{Variant, UUID};
2
3impl UUID {
4 #[must_use]
5 pub const fn with_variant(self, variant: Variant) -> Self {
6 let mut uuid = self;
7
8 uuid.bytes[8] &= variant.bitmask();
9 uuid.bytes[8] |= variant.prefix();
10
11 uuid
12 }
13}
14
15#[cfg(test)]
16mod tests {
17 use super::{Variant, UUID};
18
19 const fn make_uuid_with_byte_8(byte: u8) -> UUID {
20 let mut bytes = [0u8; 16];
21 bytes[8] = byte;
22 UUID { bytes }
23 }
24
25 #[test]
26 fn with_variant_ncs() {
27 let uuid = make_uuid_with_byte_8(0xFF);
28 let result = uuid.with_variant(Variant::NCS);
29 assert_eq!(result.get_variant(), Variant::NCS);
30 assert_eq!(result.bytes[8] & 0x80, 0x00);
31 }
32
33 #[test]
34 fn with_variant_osf() {
35 let uuid = make_uuid_with_byte_8(0x00);
36 let result = uuid.with_variant(Variant::OSF);
37 assert_eq!(result.get_variant(), Variant::OSF);
38 assert_eq!(result.bytes[8] & 0xC0, 0x80);
39 }
40
41 #[test]
42 fn with_variant_dcom() {
43 let uuid = make_uuid_with_byte_8(0x3F);
44 let result = uuid.with_variant(Variant::DCOM);
45 assert_eq!(result.get_variant(), Variant::DCOM);
46 assert_eq!(result.bytes[8] & 0xE0, 0xC0);
47 }
48
49 #[test]
50 fn with_variant_reserved() {
51 let uuid = make_uuid_with_byte_8(0x00);
52 let result = uuid.with_variant(Variant::Reserved);
53 assert_eq!(result.get_variant(), Variant::Reserved);
54 assert_eq!(result.bytes[8] & 0xE0, 0xE0);
55 }
56
57 #[test]
58 fn with_variant_preserves_other_bytes() {
59 let original_bytes = [1, 2, 3, 4, 5, 6, 7, 8, 0xFF, 10, 11, 12, 13, 14, 15, 16];
60 let uuid = UUID {
61 bytes: original_bytes,
62 };
63
64 let result = uuid.with_variant(Variant::OSF);
65
66 for (i, &byte) in result.bytes.iter().enumerate() {
67 if i != 8 {
68 assert_eq!(byte, original_bytes[i]);
69 }
70 }
71 }
72
73 #[test]
74 fn with_variant_leaves_original_unchanged() {
75 let original_bytes = [1, 2, 3, 4, 5, 6, 7, 8, 0xFF, 10, 11, 12, 13, 14, 15, 16];
76 let uuid = UUID {
77 bytes: original_bytes,
78 };
79
80 let _result = uuid.with_variant(Variant::OSF);
81
82 assert_eq!(uuid.bytes, original_bytes);
83 }
84
85 #[test]
86 fn with_variant_can_chain_variants() {
87 let uuid = make_uuid_with_byte_8(0x00);
88
89 let result = uuid
90 .with_variant(Variant::NCS)
91 .with_variant(Variant::OSF)
92 .with_variant(Variant::DCOM)
93 .with_variant(Variant::Reserved);
94
95 assert_eq!(result.get_variant(), Variant::Reserved);
96 }
97
98 #[test]
99 fn with_variant_idempotent() {
100 let uuid = make_uuid_with_byte_8(0xA5);
101
102 let first_result = uuid.with_variant(Variant::OSF);
103 let second_result = first_result.with_variant(Variant::OSF);
104
105 assert_eq!(first_result.bytes[8], second_result.bytes[8]);
106 }
107}