Skip to main content

confluent_kafka/common/
uuid.rs

1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 *    http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17
18use std::cmp::Ordering;
19
20use crate::common::Error;
21
22/// This class defines an immutable universally unique identifier (UUID). It
23/// represents a 128-bit value. More specifically, the random UUIDs generated by
24/// this class are variant 2 (Leach-Salz) version 4 UUIDs. This is the same type
25/// of UUID as the ones generated by `java.util.UUID`. The `Display`
26/// implementation prints using the base64 string encoding. Likewise, the
27/// [`from_string`](Self::from_string) method expects a base64 string encoding.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29#[doc(alias = "org.apache.kafka.common.Uuid")]
30pub struct Uuid {
31    /// The most significant 64 bits of the UUID
32    most_sig_bits: u64,
33    /// The least significant 64 bits of the UUID
34    least_sig_bits: u64,
35}
36
37impl Uuid {
38    /// A UUID that represents a null or empty UUID. Will never be returned by random_uuid.
39    pub const ZERO_UUID: Uuid = Uuid { most_sig_bits: 0, least_sig_bits: 0 };
40
41    /// A reserved UUID. Will never be returned by random_uuid.
42    pub const ONE_UUID: Uuid = Uuid { most_sig_bits: 0, least_sig_bits: 1 };
43
44    /// A UUID for the metadata topic in KRaft mode. Will never be returned by random_uuid.
45    pub const METADATA_TOPIC_ID: Uuid = Self::ONE_UUID;
46
47    /// Constructs a 128-bit type 4 UUID where the first long represents the most significant 64 bits
48    /// and the second long represents the least significant 64 bits.
49    ///
50    /// # Arguments
51    ///
52    /// - `most_sig_bits` - the most significant 64 bits
53    /// - `least_sig_bits` - the least significant 64 bits
54    #[doc(alias = "org.apache.kafka.common.Uuid#Uuid")]
55    pub const fn new(most_sig_bits: u64, least_sig_bits: u64) -> Self {
56        Uuid { most_sig_bits, least_sig_bits }
57    }
58
59    /// Creates a zero UUID (all bits are zero).
60    pub(crate) const fn zero() -> Self {
61        Self::ZERO_UUID
62    }
63
64    /// Static factory to retrieve a type 4 (pseudo randomly generated) UUID.
65    ///
66    /// This will not generate a UUID equal to `ZERO_UUID`, `ONE_UUID`, or one whose
67    /// string representation contains a dash ("-").
68    #[doc(alias = "org.apache.kafka.common.Uuid#randomUuid")]
69    pub fn random_uuid() -> Self {
70        loop {
71            let ju = uuid::Uuid::new_v4();
72            let (most, least) = ju.as_u64_pair();
73            let uuid = Self::new(most, least);
74            if uuid == Self::ZERO_UUID || uuid == Self::ONE_UUID {
75                continue;
76            }
77            if uuid.to_base64_string().contains('-') {
78                continue;
79            }
80            return uuid;
81        }
82    }
83
84    /// Returns the most significant 64 bits of this UUID.
85    #[doc(alias = "org.apache.kafka.common.Uuid#getMostSignificantBits")]
86    pub const fn most_significant_bits(&self) -> u64 {
87        self.most_sig_bits
88    }
89
90    /// Returns the least significant 64 bits of this UUID.
91    #[doc(alias = "org.apache.kafka.common.Uuid#getLeastSignificantBits")]
92    pub const fn least_significant_bits(&self) -> u64 {
93        self.least_sig_bits
94    }
95
96    /// Checks if this is the zero UUID (all bits are zero).
97    #[cfg(test)]
98    pub(crate) const fn is_zero(&self) -> bool {
99        self.most_sig_bits == 0 && self.least_sig_bits == 0
100    }
101
102    /// Creates a UUID from a 16-byte array in big-endian order.
103    ///
104    /// Java has no such constructor (only `Uuid(long, long)`); this decodes
105    /// `fromString`'s bytes, so it is crate-private.
106    pub(crate) fn with_bytes(bytes: [u8; 16]) -> Self {
107        let most_sig_bits = u64::from_be_bytes([
108            bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
109        ]);
110        let least_sig_bits = u64::from_be_bytes([
111            bytes[8], bytes[9], bytes[10], bytes[11], bytes[12], bytes[13], bytes[14], bytes[15],
112        ]);
113        Uuid::new(most_sig_bits, least_sig_bits)
114    }
115
116    /// Converts this UUID to a 16-byte array in big-endian order.
117    pub(crate) fn to_bytes(self) -> [u8; 16] {
118        let mut bytes = [0u8; 16];
119        bytes[0..8].copy_from_slice(&self.most_sig_bits.to_be_bytes());
120        bytes[8..16].copy_from_slice(&self.least_sig_bits.to_be_bytes());
121        bytes
122    }
123
124    /// Creates a UUID based on a base64 string encoding used in the `to_string()` method.
125    ///
126    /// # Arguments
127    ///
128    /// - `s` - the base64 URL encoding, without padding
129    ///
130    /// # Errors
131    ///
132    /// - [`Error::is_local_illegal_argument_error`] if `s` is not the base64 encoding of 16 bytes
133    // As in Java, the length is counted in UTF-16 units and the prefix in the
134    // "too long" message is its first 24 of them. One deviation: when that cut
135    // splits a surrogate pair Java's message ends in a lone surrogate, which a
136    // Rust `String` cannot hold, so it ends in U+FFFD.
137    #[doc(alias = "org.apache.kafka.common.Uuid#fromString")]
138    pub fn from_string(s: &str) -> Result<Self, Error> {
139        // Java's `str.length()` counts UTF-16 units, not the UTF-8 bytes `str::len` counts.
140        if s.encode_utf16().count() > 24 {
141            // `str.substring(0, 24)` takes 24 UTF-16 units, which can cut a surrogate pair in
142            // two; a lone surrogate cannot be held by a Rust `String`, so it becomes U+FFFD.
143            let prefix: Vec<u16> = s.encode_utf16().take(24).collect();
144            return Err(Error::local_illegal_argument(format!(
145                "Input string with prefix `{}` is too long to be decoded as a base64 UUID",
146                String::from_utf16_lossy(&prefix)
147            )));
148        }
149
150        // Decode base64 URL without padding
151        let decoded = base64_url_decode(s).map_err(Error::local_illegal_argument)?;
152
153        if decoded.len() != 16 {
154            return Err(Error::local_illegal_argument(format!(
155                "Input string `{}` decoded as {} bytes, which is not equal to the expected 16 bytes of a base64-encoded UUID",
156                s,
157                decoded.len()
158            )));
159        }
160
161        let mut bytes = [0u8; 16];
162        bytes.copy_from_slice(&decoded);
163        Ok(Self::with_bytes(bytes))
164    }
165
166    /// Returns a base64 URL encoded string (without padding) of the UUID.
167    /// This matches the Java implementation's toString() method.
168    pub(crate) fn to_base64_string(self) -> String {
169        let bytes = self.to_bytes();
170        base64_url_encode(&bytes)
171    }
172}
173
174/// Base64 URL encode without padding (matches Java's Base64.getUrlEncoder().withoutPadding())
175fn base64_url_encode(data: &[u8]) -> String {
176    const CHARSET: &[u8] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
177
178    let mut result = String::new();
179    let mut i = 0;
180
181    while i + 2 < data.len() {
182        let b1 = data[i];
183        let b2 = data[i + 1];
184        let b3 = data[i + 2];
185
186        result.push(CHARSET[(b1 >> 2) as usize] as char);
187        result.push(CHARSET[(((b1 & 0x03) << 4) | (b2 >> 4)) as usize] as char);
188        result.push(CHARSET[(((b2 & 0x0f) << 2) | (b3 >> 6)) as usize] as char);
189        result.push(CHARSET[(b3 & 0x3f) as usize] as char);
190
191        i += 3;
192    }
193
194    // Handle remaining bytes
195    if i < data.len() {
196        let b1 = data[i];
197        result.push(CHARSET[(b1 >> 2) as usize] as char);
198
199        if i + 1 < data.len() {
200            let b2 = data[i + 1];
201            result.push(CHARSET[(((b1 & 0x03) << 4) | (b2 >> 4)) as usize] as char);
202            result.push(CHARSET[((b2 & 0x0f) << 2) as usize] as char);
203        } else {
204            result.push(CHARSET[((b1 & 0x03) << 4) as usize] as char);
205        }
206    }
207
208    result
209}
210
211/// Base64 URL decode (matches Java's Base64.getUrlDecoder().decode(String), errors included)
212///
213/// Padding is optional, but a `=` ends the data and must complete the last 4-character unit:
214/// one `=` after three characters, two after two. Nothing may follow it.
215fn base64_url_decode(s: &str) -> Result<Vec<u8>, String> {
216    // `Base64.Decoder.decode(String)` reads the string as ISO-8859-1 (`src.getBytes(ISO_8859_1)`):
217    // a char it cannot encode, above U+00FF, becomes `?`.
218    let bytes: Vec<u8> = s.chars().map(|c| u8::try_from(u32::from(c)).unwrap_or(b'?')).collect();
219    // Java sizes the output first, and that rejects a single character before any is decoded.
220    if bytes.len() == 1 {
221        return Err("Input byte[] should at least have 2 bytes for base64 bytes".to_string());
222    }
223
224    let mut result = Vec::with_capacity(bytes.len() * 3 / 4);
225    let mut unit = [0u8; 4];
226    // How many characters of the current 4-character unit have been read.
227    let mut unit_len = 0;
228    let mut i = 0;
229
230    while i < bytes.len() {
231        let c = bytes[i];
232        i += 1;
233
234        let val = match c {
235            b'A'..=b'Z' => c - b'A',
236            b'a'..=b'z' => c - b'a' + 26,
237            b'0'..=b'9' => c - b'0' + 52,
238            b'-' => 62,
239            b'_' => 63,
240            b'=' => {
241                // Padding is the end of the data. It may not start a unit, and after two
242                // characters it must be `==`.
243                let complete = match unit_len {
244                    0 => false,
245                    2 => {
246                        let second = bytes.get(i) == Some(&b'=');
247                        i += 1;
248                        second
249                    },
250                    _ => true,
251                };
252                if !complete {
253                    return Err("Input byte array has wrong 4-byte ending unit".to_string());
254                }
255                break;
256            },
257            // Java: `"Illegal base64 character " + Integer.toString(src[sp - 1], 16)`, where
258            // `src[sp - 1]` is a signed `byte`.
259            _ => {
260                let signed = c as i8;
261                return Err(if signed < 0 {
262                    format!("Illegal base64 character -{:x}", -i32::from(signed))
263                } else {
264                    format!("Illegal base64 character {signed:x}")
265                });
266            },
267        };
268
269        unit[unit_len] = val;
270        unit_len += 1;
271        if unit_len == 4 {
272            result.push((unit[0] << 2) | (unit[1] >> 4));
273            result.push((unit[1] << 4) | (unit[2] >> 2));
274            result.push((unit[2] << 6) | unit[3]);
275            unit_len = 0;
276        }
277    }
278
279    // The data ended, at the end of the input or at its padding, inside a unit.
280    match unit_len {
281        1 => return Err("Last unit does not have enough valid bits".to_string()),
282        2 => result.push((unit[0] << 2) | (unit[1] >> 4)),
283        3 => {
284            result.push((unit[0] << 2) | (unit[1] >> 4));
285            result.push((unit[1] << 4) | (unit[2] >> 2));
286        },
287        _ => {},
288    }
289
290    // Only padding ends the loop early, and nothing may follow it.
291    if i < bytes.len() {
292        return Err(format!("Input byte array has incorrect ending byte at {i}"));
293    }
294
295    Ok(result)
296}
297
298impl Default for Uuid {
299    fn default() -> Self {
300        Uuid::zero()
301    }
302}
303
304impl std::fmt::Display for Uuid {
305    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
306        write!(f, "{}", self.to_base64_string())
307    }
308}
309
310impl PartialOrd for Uuid {
311    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
312        Some(self.cmp(other))
313    }
314}
315
316impl Ord for Uuid {
317    // Compares two UUIDs using signed 64-bit comparison to match Java's
318    // `Uuid.compareTo()` which compares `long` (signed) fields.
319    fn cmp(&self, other: &Self) -> Ordering {
320        match (self.most_sig_bits as i64).cmp(&(other.most_sig_bits as i64)) {
321            Ordering::Equal => (self.least_sig_bits as i64).cmp(&(other.least_sig_bits as i64)),
322            ord => ord,
323        }
324    }
325}
326
327#[cfg(test)]
328mod tests {
329    use super::*;
330
331    #[test]
332    fn test_zero_uuid() {
333        let uuid = Uuid::zero();
334        assert_eq!(uuid.most_significant_bits(), 0);
335        assert_eq!(uuid.least_significant_bits(), 0);
336        assert!(uuid.is_zero());
337        assert_eq!(uuid, Uuid::ZERO_UUID);
338    }
339
340    #[test]
341    fn test_one_uuid() {
342        let uuid = Uuid::ONE_UUID;
343        assert_eq!(uuid.most_significant_bits(), 0);
344        assert_eq!(uuid.least_significant_bits(), 1);
345        assert!(!uuid.is_zero());
346    }
347
348    #[test]
349    fn test_new_uuid() {
350        let uuid = Uuid::new(0x0123456789ABCDEF, 0xFEDCBA9876543210);
351        assert_eq!(uuid.most_significant_bits(), 0x0123456789ABCDEF);
352        assert_eq!(uuid.least_significant_bits(), 0xFEDCBA9876543210);
353        assert!(!uuid.is_zero());
354    }
355
356    #[test]
357    fn test_new_bytes() {
358        let bytes = [
359            0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10,
360        ];
361        let uuid = Uuid::with_bytes(bytes);
362        assert_eq!(uuid.most_significant_bits(), 0x0123456789ABCDEF);
363        assert_eq!(uuid.least_significant_bits(), 0xFEDCBA9876543210);
364    }
365
366    #[test]
367    fn test_to_bytes() {
368        let uuid = Uuid::new(0x0123456789ABCDEF, 0xFEDCBA9876543210);
369        let bytes = uuid.to_bytes();
370        assert_eq!(
371            bytes,
372            [
373                0x01, 0x23, 0x45, 0x67, 0x89, 0xAB, 0xCD, 0xEF, 0xFE, 0xDC, 0xBA, 0x98, 0x76, 0x54, 0x32, 0x10,
374            ]
375        );
376    }
377
378    #[test]
379    fn test_to_string_base64() {
380        // Test zero UUID
381        let uuid = Uuid::ZERO_UUID;
382        assert_eq!(uuid.to_string(), "AAAAAAAAAAAAAAAAAAAAAA");
383
384        // Test one UUID - verified against Java implementation
385        let uuid = Uuid::ONE_UUID;
386        assert_eq!(uuid.to_string(), "AAAAAAAAAAAAAAAAAAAAAQ");
387
388        // Test a known UUID
389        let uuid = Uuid::new(0x0123456789ABCDEF, 0xFEDCBA9876543210);
390        let s = uuid.to_string();
391        // Verify it's base64 URL encoded (22 chars for 16 bytes without padding)
392        assert_eq!(s.len(), 22);
393        assert!(s.chars().all(|c| c.is_alphanumeric() || c == '-' || c == '_'));
394    }
395
396    #[test]
397    fn test_from_string_base64() {
398        // Test zero UUID
399        let uuid = Uuid::from_string("AAAAAAAAAAAAAAAAAAAAAA").unwrap();
400        assert_eq!(uuid, Uuid::ZERO_UUID);
401
402        // Test one UUID - verified against Java implementation
403        let uuid = Uuid::from_string("AAAAAAAAAAAAAAAAAAAAAQ").unwrap();
404        assert_eq!(uuid, Uuid::ONE_UUID);
405    }
406
407    #[test]
408    fn test_round_trip() {
409        let original = Uuid::new(0x0123456789ABCDEF, 0xFEDCBA9876543210);
410        let s = original.to_string();
411        let parsed = Uuid::from_string(&s).unwrap();
412        assert_eq!(original, parsed);
413    }
414
415    #[test]
416    fn test_bytes_round_trip() {
417        let original = Uuid::new(0x0123456789ABCDEF, 0xFEDCBA9876543210);
418        let bytes = original.to_bytes();
419        let parsed = Uuid::with_bytes(bytes);
420        assert_eq!(original, parsed);
421    }
422
423    #[test]
424    fn test_default() {
425        let uuid = Uuid::default();
426        assert!(uuid.is_zero());
427        assert_eq!(uuid, Uuid::ZERO_UUID);
428    }
429
430    #[test]
431    fn test_ord() {
432        let uuid1 = Uuid::new(1, 0);
433        let uuid2 = Uuid::new(2, 0);
434        let uuid3 = Uuid::new(1, 1);
435
436        assert!(uuid1 < uuid2);
437        assert!(uuid1 < uuid3);
438        assert!(uuid3 < uuid2);
439    }
440
441    /// Translated from Java UuidTest.testHashCode.
442    /// Java uses a custom hashCode (msb ^ lsb), Rust uses derive(Hash).
443    /// We verify hash consistency: equal UUIDs produce equal hashes,
444    /// different UUIDs produce different hashes.
445    #[test]
446    #[doc(alias = "org.apache.kafka.common.UuidTest#testHashCode")]
447    fn test_hash_code() {
448        use std::collections::hash_map::DefaultHasher;
449        use std::hash::{Hash, Hasher};
450
451        fn hash_uuid(uuid: &Uuid) -> u64 {
452            let mut hasher = DefaultHasher::new();
453            uuid.hash(&mut hasher);
454            hasher.finish()
455        }
456
457        let id1 = Uuid::new(16, 7);
458        let id2 = Uuid::new(1043, 20075);
459        let id3 = Uuid::new(104312423523523, 200732425676585);
460
461        // Equal UUIDs produce equal hashes
462        assert_eq!(hash_uuid(&id1), hash_uuid(&Uuid::new(16, 7)));
463        assert_eq!(hash_uuid(&id2), hash_uuid(&Uuid::new(1043, 20075)));
464        assert_eq!(hash_uuid(&id3), hash_uuid(&Uuid::new(104312423523523, 200732425676585)));
465
466        // Different UUIDs produce different hashes (not guaranteed in general,
467        // but these specific values should differ)
468        assert_ne!(hash_uuid(&id1), hash_uuid(&id2));
469        assert_ne!(hash_uuid(&id1), hash_uuid(&id3));
470        assert_ne!(hash_uuid(&id2), hash_uuid(&id3));
471    }
472
473    /// Translated from Java UuidTest.testRandomUuid (RepeatedTest(100)).
474    /// Verifies that random UUIDs are not ZERO_UUID, not METADATA_TOPIC_ID,
475    /// and contain no dash (KAFKA-20072).
476    #[test]
477    #[doc(alias = "org.apache.kafka.common.UuidTest#testRandomUuid")]
478    fn test_random_uuid() {
479        for _ in 0..100 {
480            let random_id = Uuid::random_uuid();
481            assert_ne!(Uuid::ZERO_UUID, random_id);
482            assert_ne!(Uuid::METADATA_TOPIC_ID, random_id);
483            assert!(!random_id.to_string().contains('-'));
484        }
485    }
486
487    /// Translated from Java UuidTest.testCompareUuids.
488    /// Verifies all 9 comparison combinations of UUIDs (0,0), (0,1), (1,0).
489    #[test]
490    #[doc(alias = "org.apache.kafka.common.UuidTest#testCompareUuids")]
491    fn test_compare_uuids() {
492        let id00 = Uuid::new(0, 0);
493        let id01 = Uuid::new(0, 1);
494        let id10 = Uuid::new(1, 0);
495
496        assert_eq!(Ordering::Equal, id00.cmp(&id00));
497        assert_eq!(Ordering::Equal, id01.cmp(&id01));
498        assert_eq!(Ordering::Equal, id10.cmp(&id10));
499        assert_eq!(Ordering::Less, id00.cmp(&id01));
500        assert_eq!(Ordering::Less, id00.cmp(&id10));
501        assert_eq!(Ordering::Greater, id01.cmp(&id00));
502        assert_eq!(Ordering::Greater, id10.cmp(&id00));
503        assert_eq!(Ordering::Less, id01.cmp(&id10));
504        assert_eq!(Ordering::Greater, id10.cmp(&id01));
505    }
506
507    /// Verifies that signed comparison matches Java behavior for UUIDs
508    /// with high bits set (values that would be negative as Java long).
509    #[test]
510    fn test_compare_uuids_signed() {
511        // 0xFFFFFFFFFFFFFFFF as i64 is -1, which should be less than 1 (signed comparison)
512        let uuid_neg = Uuid::new(0xFFFFFFFFFFFFFFFF, 0);
513        let uuid_pos = Uuid::new(1, 0);
514        assert!(uuid_neg < uuid_pos, "UUID with high MSB bit set should compare less (signed)");
515
516        // Same for least significant bits
517        let uuid_neg_lsb = Uuid::new(0, 0xFFFFFFFFFFFFFFFF);
518        let uuid_pos_lsb = Uuid::new(0, 1);
519        assert!(
520            uuid_neg_lsb < uuid_pos_lsb,
521            "UUID with high LSB bit set should compare less (signed)"
522        );
523    }
524
525    #[test]
526    fn test_from_string_too_long() {
527        let result = Uuid::from_string("AAAAAAAAAAAAAAAAAAAAAA_THIS_IS_TOO_LONG");
528        assert!(result.is_err());
529        let error = result.unwrap_err();
530        assert!(error.is_local_illegal_argument_error());
531        assert!(error.to_string().contains("too long"));
532    }
533
534    #[test]
535    fn test_from_string_invalid_length() {
536        let result = Uuid::from_string("AAAA");
537        assert!(result.is_err());
538        let error = result.unwrap_err();
539        assert!(error.is_local_illegal_argument_error());
540        assert!(error.to_string().contains("not equal to the expected 16 bytes"));
541    }
542
543    /// The expected messages below are what Java's `Uuid.fromString` throws, observed by
544    /// running it (`Base64.getUrlDecoder().decode(String)` reads the string as ISO-8859-1,
545    /// so a char above U+00FF is `?`, 0x3f, and a Latin-1 char is its *signed* byte).
546    fn from_string_message(s: &str) -> String {
547        let error = Uuid::from_string(s).expect_err("not a base64 UUID");
548        assert!(
549            error.is_local_illegal_argument_error(),
550            "Java throws IllegalArgumentException: {error}"
551        );
552        error.message().to_string()
553    }
554
555    /// The length check counted UTF-8 bytes where Java's `String.length()` counts
556    /// UTF-16 units, and `&s[..24]` is a byte slice, so a multi-byte character straddling
557    /// byte 24 panicked instead of throwing `IllegalArgumentException`:
558    /// `Uuid.fromString("a€€€€€€€€")` is 9 chars to Java, which fails to decode them.
559    #[test]
560    fn test_from_string_multibyte_input_is_an_error_not_a_panic() {
561        assert_eq!(
562            "Illegal base64 character 3f",
563            from_string_message("a\u{20ac}\u{20ac}\u{20ac}\u{20ac}\u{20ac}\u{20ac}\u{20ac}\u{20ac}")
564        );
565    }
566
567    /// 8 chars in 24 bytes, and 13 chars in 26 bytes: Java measures chars, so neither is too long.
568    #[test]
569    fn test_from_string_length_is_counted_in_utf16_units_not_bytes() {
570        assert_eq!("Illegal base64 character 3f", from_string_message(&"\u{20ac}".repeat(8)));
571        assert_eq!("Illegal base64 character -17", from_string_message(&"\u{e9}".repeat(13)));
572    }
573
574    /// 25 UTF-16 units are too long, and the prefix of the message is the first 24 of them
575    /// (`str.substring(0, 24)`), here ending in a whole `€`.
576    #[test]
577    fn test_from_string_too_long_prefix_is_24_utf16_units() {
578        assert_eq!(
579            "Input string with prefix `AAAAAAAAAAAAAAAAAAAAAAA\u{20ac}` is too long to be decoded as a base64 UUID",
580            from_string_message(&format!("{}\u{20ac}\u{20ac}", "A".repeat(23)))
581        );
582    }
583
584    /// `substring(0, 24)` can cut a surrogate pair in two, leaving a lone surrogate in the
585    /// message, which a Rust `String` cannot hold: it becomes U+FFFD.
586    #[test]
587    fn test_from_string_too_long_prefix_cutting_a_surrogate_pair() {
588        assert_eq!(
589            "Input string with prefix `AAAAAAAAAAAAAAAAAAAAAAA\u{fffd}` is too long to be decoded as a base64 UUID",
590            from_string_message(&format!("{}\u{1f600}", "A".repeat(23)))
591        );
592    }
593
594    /// An ASCII character that is not in the URL-safe alphabet is reported as Java reports it.
595    #[test]
596    fn test_from_string_illegal_base64_character() {
597        assert_eq!("Illegal base64 character 2b", from_string_message("+AAAAAAAAAAAAAAAAAAAAA"));
598    }
599
600    /// Padding must complete the last 4-character unit, as `Base64.getUrlDecoder()` requires:
601    /// a `=` cannot start a unit, and after two characters it must be `==` (issue #269).
602    #[test]
603    fn test_from_string_padding_with_a_wrong_ending_unit() {
604        let a = |n: usize| "A".repeat(n);
605        for s in [
606            format!("{}=", a(22)),
607            format!("{}=A", a(22)),
608            format!("={}", a(21)),
609            format!("{}=", a(20)),
610            format!("{}==", a(20)),
611            format!("{}=A", a(20)),
612            format!("{}==A", a(20)),
613            format!("{}={}", a(8), a(8)),
614        ] {
615            assert_eq!("Input byte array has wrong 4-byte ending unit", from_string_message(&s), "{s}");
616        }
617    }
618
619    /// A last unit of one character holds 6 bits, less than a byte, with or without padding.
620    #[test]
621    fn test_from_string_last_unit_without_enough_bits() {
622        for s in [
623            "A".repeat(21),
624            format!("{}=", "A".repeat(21)),
625            format!("{}==", "A".repeat(21)),
626        ] {
627            assert_eq!("Last unit does not have enough valid bits", from_string_message(&s), "{s}");
628        }
629    }
630
631    /// Nothing may follow complete padding; Java reports the index of the first byte after it.
632    #[test]
633    fn test_from_string_bytes_after_padding() {
634        assert_eq!(
635            "Input byte array has incorrect ending byte at 20",
636            from_string_message(&format!("{}==AA", "A".repeat(18)))
637        );
638        assert_eq!("Input byte array has incorrect ending byte at 4", from_string_message("AAA=A"));
639    }
640
641    /// Java rejects a single character before decoding it, even an illegal one.
642    #[test]
643    fn test_from_string_single_character() {
644        assert_eq!(
645            "Input byte[] should at least have 2 bytes for base64 bytes",
646            from_string_message("A")
647        );
648        assert_eq!(
649            "Input byte[] should at least have 2 bytes for base64 bytes",
650            from_string_message("+")
651        );
652    }
653
654    /// Padding is optional; the 22 characters of a UUID decode the same with `==`, and a
655    /// well-padded string of the wrong size is still reported by its decoded length.
656    #[test]
657    fn test_from_string_valid_padding() {
658        let uuid = Uuid::new(0x0123_4567_89ab_cdef, 0xfedc_ba98_7654_3210);
659        let s = uuid.to_string();
660        assert_eq!(22, s.len());
661        assert_eq!(uuid, Uuid::from_string(&s).unwrap());
662        assert_eq!(uuid, Uuid::from_string(&format!("{s}==")).unwrap());
663        assert_eq!(Uuid::zero(), Uuid::from_string(&"A".repeat(22)).unwrap());
664        assert_eq!(
665            "Input string `AAAAAAAAAAAAAAAAAAAAAAA=` decoded as 17 bytes, which is not equal to the expected 16 bytes of a base64-encoded UUID",
666            from_string_message(&format!("{}=", "A".repeat(23)))
667        );
668        assert_eq!(
669            "Input string `` decoded as 0 bytes, which is not equal to the expected 16 bytes of a base64-encoded UUID",
670            from_string_message("")
671        );
672    }
673}