1use std::cmp::Ordering;
19
20use crate::common::Error;
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
29#[doc(alias = "org.apache.kafka.common.Uuid")]
30pub struct Uuid {
31 most_sig_bits: u64,
33 least_sig_bits: u64,
35}
36
37impl Uuid {
38 pub const ZERO_UUID: Uuid = Uuid { most_sig_bits: 0, least_sig_bits: 0 };
40
41 pub const ONE_UUID: Uuid = Uuid { most_sig_bits: 0, least_sig_bits: 1 };
43
44 pub const METADATA_TOPIC_ID: Uuid = Self::ONE_UUID;
46
47 #[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 pub(crate) const fn zero() -> Self {
61 Self::ZERO_UUID
62 }
63
64 #[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 #[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 #[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 #[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 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 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 #[doc(alias = "org.apache.kafka.common.Uuid#fromString")]
138 pub fn from_string(s: &str) -> Result<Self, Error> {
139 if s.encode_utf16().count() > 24 {
141 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 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 pub(crate) fn to_base64_string(self) -> String {
169 let bytes = self.to_bytes();
170 base64_url_encode(&bytes)
171 }
172}
173
174fn 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 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
211fn base64_url_decode(s: &str) -> Result<Vec<u8>, String> {
216 let bytes: Vec<u8> = s.chars().map(|c| u8::try_from(u32::from(c)).unwrap_or(b'?')).collect();
219 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 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 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 _ => {
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 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 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 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 let uuid = Uuid::ZERO_UUID;
382 assert_eq!(uuid.to_string(), "AAAAAAAAAAAAAAAAAAAAAA");
383
384 let uuid = Uuid::ONE_UUID;
386 assert_eq!(uuid.to_string(), "AAAAAAAAAAAAAAAAAAAAAQ");
387
388 let uuid = Uuid::new(0x0123456789ABCDEF, 0xFEDCBA9876543210);
390 let s = uuid.to_string();
391 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 let uuid = Uuid::from_string("AAAAAAAAAAAAAAAAAAAAAA").unwrap();
400 assert_eq!(uuid, Uuid::ZERO_UUID);
401
402 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 #[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 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 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 #[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 #[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 #[test]
510 fn test_compare_uuids_signed() {
511 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 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 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 #[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 #[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 #[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 #[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 #[test]
596 fn test_from_string_illegal_base64_character() {
597 assert_eq!("Illegal base64 character 2b", from_string_message("+AAAAAAAAAAAAAAAAAAAAA"));
598 }
599
600 #[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 #[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 #[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 #[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 #[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}