Skip to content

Commit 4b6c10f

Browse files
authored
Merge pull request #915 from uuid-rs/fix/v7-ordering
Fix ordering of V7 UUIDs created by earlier seconds with later subsec nanos
2 parents a1aa126 + 4639d67 commit 4b6c10f

1 file changed

Lines changed: 24 additions & 2 deletions

File tree

‎src/timestamp.rs‎

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -903,14 +903,22 @@ pub mod context {
903903

904904
if incoming.last_seed > self.last_seed {
905905
// The incoming value is part of a new millisecond
906+
//
907+
// Return it unchanged, signalling that a counter reseed is also necessary
906908
(incoming, true)
907-
} else {
908-
// The incoming value is part of the same or an earlier millisecond
909+
} else if incoming.last_seed == self.last_seed {
910+
// The incoming value is part of the same millisecond
911+
//
909912
// We may still have advanced the subsecond portion, so use the larger value
910913
let mut value = *self;
911914
value.subsec_nanos = cmp::max(self.subsec_nanos, subsec_nanos);
912915

913916
(value, false)
917+
} else {
918+
// The incoming value is part of an earlier millisecond
919+
//
920+
// Return our last seen value, relying entirely on the counter for monotonicity
921+
(*self, false)
914922
}
915923
}
916924

@@ -1234,6 +1242,20 @@ pub mod context {
12341242
Timestamp::from_unix(&context, seconds, subsec_nanos);
12351243
}
12361244
}
1245+
1246+
#[test]
1247+
fn context_subsec_ordering() {
1248+
let context = ContextV7::new();
1249+
1250+
// Wall-clock order of incoming timestamps is b, a, c
1251+
// UUID order is a, b, c
1252+
let a = Timestamp::from_unix(&context, 100, 0);
1253+
let b = Timestamp::from_unix(&context, 99, 2_000_000);
1254+
let c = Timestamp::from_unix(&context, 100, 1_000_000);
1255+
1256+
assert!(Uuid::new_v7(a) < Uuid::new_v7(b), "a: {a:?} < b: {b:?}");
1257+
assert!(Uuid::new_v7(b) < Uuid::new_v7(c), "b: {b:?} < c: {c:?}");
1258+
}
12371259
}
12381260
}
12391261

0 commit comments

Comments
 (0)