use core::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6};
use smol_bytes::Utf8Bytes;
use super::CursorValue;
use crate::{BeI128, BeU64, BeU128};
fn round_trip<V: CursorValue + PartialEq + core::fmt::Debug>(value: V) -> Vec<u8> {
let mut bytes = Vec::new();
value.write_cursor(&mut bytes);
assert_eq!(V::read_cursor(&bytes).as_ref(), Some(&value));
bytes
}
#[test]
fn the_integers_round_trip_big_endian() {
assert_eq!(round_trip(0i8), [0]);
assert_eq!(round_trip(i8::MIN), [0x80]);
assert_eq!(round_trip(-1i64), [0xff; 8]);
assert_eq!(round_trip(1i64), [0, 0, 0, 0, 0, 0, 0, 1]);
assert_eq!(round_trip(u64::MAX), [0xff; 8]);
assert_eq!(round_trip(u128::MAX), [0xff; 16]);
assert_eq!(round_trip(i128::MIN).len(), 16);
assert_eq!(round_trip(u16::MAX), [0xff, 0xff]);
assert_eq!(round_trip(0u32), [0, 0, 0, 0]);
assert_eq!(round_trip(i16::MAX), [0x7f, 0xff]);
assert_eq!(round_trip(u8::MAX), [0xff]);
assert_eq!(round_trip(i32::MIN), [0x80, 0, 0, 0]);
}
#[test]
fn an_integer_of_the_wrong_width_is_refused() {
assert_eq!(<i64 as CursorValue>::read_cursor(&[0; 4]), None);
assert_eq!(<i64 as CursorValue>::read_cursor(&[0; 9]), None);
assert_eq!(<u8 as CursorValue>::read_cursor(&[]), None);
}
#[test]
fn the_floats_round_trip_bit_for_bit() {
assert_eq!(round_trip(1.5f64), 1.5f64.to_be_bytes());
assert_ne!(round_trip(0.0f64), round_trip(-0.0f64));
assert_eq!(round_trip(f32::MAX), f32::MAX.to_be_bytes());
let mut bytes = Vec::new();
f64::NAN.write_cursor(&mut bytes);
let read = <f64 as CursorValue>::read_cursor(&bytes).expect("a NaN's bytes are eight");
assert!(read.is_nan());
assert_eq!(read.to_bits(), f64::NAN.to_bits());
}
#[test]
fn a_boolean_is_one_byte_and_two_values() {
assert_eq!(round_trip(true), [1]);
assert_eq!(round_trip(false), [0]);
assert_eq!(<bool as CursorValue>::read_cursor(&[2]), None);
assert_eq!(<bool as CursorValue>::read_cursor(&[0, 0]), None);
assert_eq!(<bool as CursorValue>::read_cursor(&[]), None);
}
#[test]
fn the_storage_forms_use_their_own_codec() {
assert_eq!(round_trip(BeU64(1)), BeU64(1).to_blob());
assert_eq!(round_trip(BeU128(1)), BeU128(1).to_blob());
assert_eq!(round_trip(BeI128(-1)), BeI128(-1).to_blob());
assert_ne!(
BeI128(-1).to_blob(),
(-1i128).to_be_bytes(),
"the sign flip is what a second encoding here would lose"
);
assert_eq!(<BeU64 as CursorValue>::read_cursor(&[0; 7]), None);
}
#[test]
fn a_uuid_is_its_sixteen_bytes() {
let id = uuid::Uuid::from_bytes([
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,
]);
assert_eq!(round_trip(id), *id.as_bytes());
assert_eq!(<uuid::Uuid as CursorValue>::read_cursor(&[0; 15]), None);
}
#[test]
fn text_round_trips_and_invalid_utf8_is_refused() {
assert_eq!(round_trip("médià".to_owned()), "médià".as_bytes());
assert_eq!(round_trip(String::new()), [] as [u8; 0]);
assert_eq!(<String as CursorValue>::read_cursor(&[0x80]), None);
assert_eq!(round_trip(Utf8Bytes::from("médià")), "médià".as_bytes());
assert_eq!(<Utf8Bytes as CursorValue>::read_cursor(&[0x80]), None);
}
#[test]
fn the_two_text_types_are_one_encoding() {
let mut owned = Vec::new();
"a red car".to_owned().write_cursor(&mut owned);
let mut shared = Vec::new();
Utf8Bytes::from("a red car").write_cursor(&mut shared);
assert_eq!(owned, shared);
}
#[test]
fn the_two_text_types_agree_on_order_not_only_on_one_encoding() {
let words = ["", "\0", "a", "cafe", "café", "cafétéria", "café ", "zoo"];
let mut by_string: Vec<&str> = words.to_vec();
by_string.sort_by(|a, b| round_trip(String::from(*a)).cmp(&round_trip(String::from(*b))));
let mut by_utf8bytes: Vec<&str> = words.to_vec();
by_utf8bytes
.sort_by(|a, b| round_trip(Utf8Bytes::from(*a)).cmp(&round_trip(Utf8Bytes::from(*b))));
assert_eq!(
by_string, by_utf8bytes,
"a page cursor built over either type must walk the same sequence"
);
let mut by_str_ord = words.to_vec();
by_str_ord.sort_unstable();
assert_eq!(by_string, by_str_ord);
}
#[test]
fn a_byte_column_is_verbatim() {
assert_eq!(round_trip(vec![0u8, 0xff, 0x80]), [0, 0xff, 0x80]);
assert_eq!(round_trip(Vec::<u8>::new()), [] as [u8; 0]);
}
#[test]
fn a_fixed_width_collection_is_the_count_and_the_elements_raw() {
assert_eq!(
round_trip(vec![1i32, -1]),
[0, 0, 0, 2, 0, 0, 0, 1, 0xff, 0xff, 0xff, 0xff]
);
assert_eq!(round_trip(vec![true, false]), [0, 0, 0, 2, 1, 0]);
assert_eq!(round_trip(vec![i16::MIN]), [0, 0, 0, 1, 0x80, 0]);
assert_eq!(round_trip(vec![1.5f64]), {
let mut expected = vec![0, 0, 0, 1];
expected.extend_from_slice(&1.5f64.to_be_bytes());
expected
});
}
#[test]
fn a_variable_width_collection_length_prefixes_each_element() {
assert_eq!(
round_trip(vec!["hd".to_owned(), String::new()]),
[0, 0, 0, 2, 0, 0, 0, 2, b'h', b'd', 0, 0, 0, 0]
);
assert_eq!(
round_trip(vec![vec![0xffu8], Vec::new(), vec![1, 2]]),
[0, 0, 0, 3, 0, 0, 0, 1, 0xff, 0, 0, 0, 0, 0, 0, 0, 2, 1, 2]
);
}
#[test]
fn the_empty_collection_is_a_value_and_not_an_absence() {
assert_eq!(round_trip(Vec::<i64>::new()), [0, 0, 0, 0]);
assert_eq!(round_trip(Vec::<String>::new()), [0, 0, 0, 0]);
assert_eq!(round_trip(Vec::<Vec<u8>>::new()), [0, 0, 0, 0]);
}
#[test]
fn a_list_of_byte_strings_is_not_a_byte_column() {
let mut column = Vec::new();
vec![1u8, 2].write_cursor(&mut column);
let mut list = Vec::new();
vec![vec![1u8, 2]].write_cursor(&mut list);
assert_eq!(column, [1, 2]);
assert_ne!(column, list);
}
#[test]
fn a_malformed_inner_frame_is_refused() {
type Fixed = Vec<i32>;
type Varying = Vec<String>;
assert_eq!(<Fixed as CursorValue>::read_cursor(&[]), None);
assert_eq!(<Fixed as CursorValue>::read_cursor(&[0, 0, 0]), None);
assert_eq!(<Varying as CursorValue>::read_cursor(&[0, 0]), None);
assert_eq!(<Fixed as CursorValue>::read_cursor(&[0, 0, 0, 1]), None);
assert_eq!(
<Fixed as CursorValue>::read_cursor(&[0, 0, 0, 2, 0, 0, 0, 1, 0, 0]),
None,
"six payload bytes are not two `i32`s"
);
assert_eq!(
<Varying as CursorValue>::read_cursor(&[0, 0, 0, 1]),
None,
"a claimed element has not even a length"
);
assert_eq!(
<Varying as CursorValue>::read_cursor(&[0, 0, 0, 1, 0, 0, 0, 4, b'h', b'd']),
None,
"and a length longer than the bytes behind it is the same refusal"
);
assert_eq!(
<Fixed as CursorValue>::read_cursor(&[0, 0, 0, 0, 1]),
None,
"an empty list owns no bytes at all"
);
assert_eq!(
<Varying as CursorValue>::read_cursor(&[0, 0, 0, 0, 0, 0, 0, 1, b'h']),
None
);
assert_eq!(
<Varying as CursorValue>::read_cursor(&[0, 0, 0, 1, 0, 0, 0, 1, b'h', b'd']),
None,
"one element read, one byte nobody owns"
);
assert_eq!(
<Fixed as CursorValue>::read_cursor(&[0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0]),
None,
"four chunks of three bytes are not four `i32`s"
);
assert_eq!(
<Vec<bool> as CursorValue>::read_cursor(&[0, 0, 0, 2, 1, 2]),
None,
"and a byte that is not a boolean is refused inside a list exactly as it is alone"
);
assert_eq!(
<Varying as CursorValue>::read_cursor(&[0, 0, 0, 1, 0, 0, 0, 1, 0x80]),
None,
"an element's own domain check still runs — a lone continuation byte is no `String`"
);
}
#[test]
fn an_instant_round_trips_as_its_two_columns() {
use crate::Timestamp;
let at: Timestamp = "2026-08-09T21:14:03.123456789Z".parse().unwrap();
let before: Timestamp = "1969-12-31T23:59:58.5Z".parse().unwrap();
assert_eq!(round_trip(at).len(), 12);
assert_eq!(round_trip(before).len(), 12);
assert_eq!(round_trip(Timestamp::MIN).len(), 12);
assert_eq!(round_trip(Timestamp::MAX).len(), 12);
assert_eq!(round_trip(Timestamp::UNIX_EPOCH), [0; 12]);
let mut expected = at.as_second().to_be_bytes().to_vec();
expected.extend_from_slice(&at.subsec_nanosecond().to_be_bytes());
assert_eq!(round_trip(at), expected);
}
#[test]
fn a_forged_instant_cursor_is_refused() {
use crate::Timestamp;
assert!(<Timestamp as CursorValue>::read_cursor(&[0; 11]).is_none());
assert!(<Timestamp as CursorValue>::read_cursor(&[0; 13]).is_none());
let mut forged = 2i64.to_be_bytes().to_vec();
forged.extend_from_slice(&(-999_999_999i32).to_be_bytes());
assert_eq!(forged.len(), 12);
assert!(<Timestamp as CursorValue>::read_cursor(&forged).is_none());
let mut written = 1i64.to_be_bytes().to_vec();
written.extend_from_slice(&1i32.to_be_bytes());
assert_eq!(
<Timestamp as CursorValue>::read_cursor(&written),
Some("1970-01-01T00:00:01.000000001Z".parse().unwrap())
);
}
#[test]
fn an_instants_twelve_bytes_are_its_two_scalar_slots() {
use crate::Timestamp;
for instant in [
"2026-08-09T21:14:03.123456789Z"
.parse::<Timestamp>()
.unwrap(),
"1969-12-31T23:59:58.5Z".parse().unwrap(),
Timestamp::UNIX_EPOCH,
Timestamp::MIN,
Timestamp::MAX,
] {
let mut whole = Vec::new();
instant.write_cursor(&mut whole);
let mut halves = Vec::new();
instant.as_second().write_cursor(&mut halves);
instant.subsec_nanosecond().write_cursor(&mut halves);
assert_eq!(whole, halves, "{instant}");
assert_eq!(whole.len(), size_of::<i64>() + size_of::<i32>());
}
}
#[test]
fn an_ipv4_address_is_its_four_octets() {
assert_eq!(round_trip(Ipv4Addr::new(10, 0, 0, 1)), [10, 0, 0, 1]);
assert_eq!(round_trip(Ipv4Addr::UNSPECIFIED), [0, 0, 0, 0]);
assert_eq!(round_trip(Ipv4Addr::BROADCAST), [0xff, 0xff, 0xff, 0xff]);
assert!(Ipv4Addr::new(9, 255, 255, 255) < Ipv4Addr::new(10, 0, 0, 0));
assert_eq!(<Ipv4Addr as CursorValue>::read_cursor(&[0; 3]), None);
assert_eq!(<Ipv4Addr as CursorValue>::read_cursor(&[0; 5]), None);
}
#[test]
fn an_ipv6_address_is_its_sixteen_octets() {
let addr: Ipv6Addr = "2001:db8::1".parse().unwrap();
assert_eq!(round_trip(addr), addr.octets());
assert_eq!(round_trip(Ipv6Addr::UNSPECIFIED), [0; 16]);
assert_eq!(<Ipv6Addr as CursorValue>::read_cursor(&[0; 15]), None);
}
#[test]
fn an_ip_address_is_a_tag_then_the_inner() {
let v4 = IpAddr::V4(Ipv4Addr::new(10, 0, 0, 1));
assert_eq!(round_trip(v4), [0, 10, 0, 0, 1]);
let addr: Ipv6Addr = "2001:db8::1".parse().unwrap();
let mut expected = vec![1];
expected.extend_from_slice(&addr.octets());
assert_eq!(round_trip(IpAddr::V6(addr)), expected);
assert!(
round_trip(IpAddr::V4(Ipv4Addr::BROADCAST)) < round_trip(IpAddr::V6(Ipv6Addr::UNSPECIFIED)),
"every V4 sorts below every V6, regardless of either address",
);
assert_eq!(<IpAddr as CursorValue>::read_cursor(&[2, 0, 0, 0, 0]), None);
assert_eq!(<IpAddr as CursorValue>::read_cursor(&[]), None);
}
#[test]
fn a_socket_v4_is_the_address_then_the_port_big_endian() {
let socket = SocketAddrV4::new(Ipv4Addr::new(10, 0, 0, 1), 8080);
assert_eq!(round_trip(socket), [10, 0, 0, 1, 0x1f, 0x90]);
assert!(
SocketAddrV4::new(Ipv4Addr::new(1, 0, 0, 0), 1)
< SocketAddrV4::new(Ipv4Addr::new(1, 0, 0, 1), 0),
"the address outweighs the port",
);
assert_eq!(<SocketAddrV4 as CursorValue>::read_cursor(&[0; 5]), None);
}
#[test]
fn a_socket_v6_is_the_address_the_port_the_flowinfo_and_the_scope_id() {
let ip: Ipv6Addr = "2001:db8::1".parse().unwrap();
let socket = SocketAddrV6::new(ip, 443, 7, 9);
let mut expected = ip.octets().to_vec();
expected.extend_from_slice(&443u16.to_be_bytes());
expected.extend_from_slice(&7u32.to_be_bytes());
expected.extend_from_slice(&9u32.to_be_bytes());
assert_eq!(round_trip(socket), expected);
assert!(SocketAddrV6::new(ip, 443, 0, 9) < SocketAddrV6::new(ip, 443, 1, 0));
assert!(SocketAddrV6::new(ip, 443, 7, 0) < SocketAddrV6::new(ip, 443, 7, 1));
assert_eq!(<SocketAddrV6 as CursorValue>::read_cursor(&[0; 25]), None);
}
#[test]
fn a_socket_address_is_a_tag_then_the_inner() {
let v4 = SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 80));
let v6 = SocketAddr::V6(SocketAddrV6::new("::1".parse().unwrap(), 80, 0, 0));
let (a, b) = (round_trip(v4), round_trip(v6));
assert_eq!(a[0], 0);
assert_eq!(b[0], 1);
assert!(a < b, "every V4 sorts below every V6, discriminant-first");
assert_eq!(<SocketAddr as CursorValue>::read_cursor(&[2]), None);
}
#[cfg(feature = "smol_str")]
#[test]
fn a_smol_str_mirrors_strings_own_encoding() {
use smol_str::SmolStr;
assert_eq!(round_trip(SmolStr::new("médià")), "médià".as_bytes());
assert_eq!(round_trip(SmolStr::new("")), [] as [u8; 0]);
assert_eq!(<SmolStr as CursorValue>::read_cursor(&[0x80]), None);
let mut smol = Vec::new();
SmolStr::new("a red car").write_cursor(&mut smol);
let mut owned = Vec::new();
"a red car".to_owned().write_cursor(&mut owned);
assert_eq!(smol, owned);
}
#[cfg(feature = "mongo")]
#[test]
fn a_bson_uuid_is_its_sixteen_bytes_mirroring_uuids_row() {
let raw = [
0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32, 0x10,
];
let id = bson::Uuid::from_bytes(raw);
assert_eq!(round_trip(id), raw);
assert_eq!(<bson::Uuid as CursorValue>::read_cursor(&[0; 15]), None);
let mut mirrored = Vec::new();
uuid::Uuid::from_bytes(raw).write_cursor(&mut mirrored);
assert_eq!(round_trip(id), mirrored);
}
#[cfg(feature = "mongo")]
#[test]
fn a_bson_object_id_is_its_twelve_bytes() {
let raw = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];
let id = bson::oid::ObjectId::from_bytes(raw);
assert_eq!(round_trip(id), raw);
assert_eq!(
<bson::oid::ObjectId as CursorValue>::read_cursor(&[0; 11]),
None
);
}
struct SplitMix64(u64);
impl SplitMix64 {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9E37_79B9_7F4A_7C15);
let mut z = self.0;
z = (z ^ (z >> 30)).wrapping_mul(0xBF58_476D_1CE4_E5B9);
z = (z ^ (z >> 27)).wrapping_mul(0x94D0_49BB_1331_11EB);
z ^ (z >> 31)
}
fn next_u16(&mut self) -> u16 {
self.next() as u16
}
fn next_u32(&mut self) -> u32 {
self.next() as u32
}
fn next_u128(&mut self) -> u128 {
(u128::from(self.next()) << 64) | u128::from(self.next())
}
fn next_bool(&mut self) -> bool {
self.next() & 1 == 1
}
}
#[track_caller]
fn assert_byte_order_matches_ord<V: CursorValue + Ord + Clone + core::fmt::Debug>(values: &[V]) {
let mut by_ord = values.to_vec();
by_ord.sort();
let mut by_bytes = values.to_vec();
by_bytes.sort_by_cached_key(|value| {
let mut bytes = Vec::new();
value.write_cursor(&mut bytes);
bytes
});
assert_eq!(
by_bytes, by_ord,
"sorting by cursor bytes must reproduce the type's own Ord"
);
}
const SEED: u64 = 0x1D5C_0DE0_1D5C_0DE0;
const SAMPLES: usize = 256;
#[test]
fn ipv4_addresses_cursor_bytes_agree_with_ord() {
let mut rng = SplitMix64(SEED);
let values: Vec<Ipv4Addr> = (0..SAMPLES)
.map(|_| Ipv4Addr::from(rng.next_u32()))
.collect();
assert_byte_order_matches_ord(&values);
}
#[test]
fn ipv6_addresses_cursor_bytes_agree_with_ord() {
let mut rng = SplitMix64(SEED ^ 1);
let values: Vec<Ipv6Addr> = (0..SAMPLES)
.map(|_| Ipv6Addr::from(rng.next_u128()))
.collect();
assert_byte_order_matches_ord(&values);
}
#[test]
fn ip_addresses_cursor_bytes_agree_with_ord() {
let mut rng = SplitMix64(SEED ^ 2);
let values: Vec<IpAddr> = (0..SAMPLES)
.map(|_| {
if rng.next_bool() {
IpAddr::V4(Ipv4Addr::from(rng.next_u32()))
} else {
IpAddr::V6(Ipv6Addr::from(rng.next_u128()))
}
})
.collect();
assert_byte_order_matches_ord(&values);
}
#[test]
fn socket_v4_cursor_bytes_agree_with_ord() {
let mut rng = SplitMix64(SEED ^ 3);
let values: Vec<SocketAddrV4> = (0..SAMPLES)
.map(|_| SocketAddrV4::new(Ipv4Addr::from(rng.next_u32()), rng.next_u16()))
.collect();
assert_byte_order_matches_ord(&values);
}
#[test]
fn socket_v6_cursor_bytes_agree_with_ord() {
let mut rng = SplitMix64(SEED ^ 4);
let values: Vec<SocketAddrV6> = (0..SAMPLES)
.map(|_| {
SocketAddrV6::new(
Ipv6Addr::from(rng.next_u128()),
rng.next_u16(),
rng.next_u32(),
rng.next_u32(),
)
})
.collect();
assert_byte_order_matches_ord(&values);
}
#[test]
fn socket_address_cursor_bytes_agree_with_ord() {
let mut rng = SplitMix64(SEED ^ 5);
let values: Vec<SocketAddr> = (0..SAMPLES)
.map(|_| {
if rng.next_bool() {
SocketAddr::V4(SocketAddrV4::new(
Ipv4Addr::from(rng.next_u32()),
rng.next_u16(),
))
} else {
SocketAddr::V6(SocketAddrV6::new(
Ipv6Addr::from(rng.next_u128()),
rng.next_u16(),
rng.next_u32(),
rng.next_u32(),
))
}
})
.collect();
assert_byte_order_matches_ord(&values);
}
#[cfg(feature = "smol_str")]
#[test]
fn smol_str_cursor_bytes_agree_with_ord() {
use smol_str::SmolStr;
let mut rng = SplitMix64(SEED ^ 6);
const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789 _-.";
let values: Vec<SmolStr> = (0..SAMPLES)
.map(|_| {
let len = (rng.next() % 24) as usize;
let text: String = (0..len)
.map(|_| ALPHABET[(rng.next() as usize) % ALPHABET.len()] as char)
.collect();
SmolStr::new(text)
})
.collect();
assert_byte_order_matches_ord(&values);
}
#[cfg(feature = "mongo")]
#[test]
fn bson_uuid_cursor_bytes_agree_with_ord() {
let mut rng = SplitMix64(SEED ^ 7);
let values: Vec<bson::Uuid> = (0..SAMPLES)
.map(|_| {
let mut bytes = [0u8; 16];
bytes[..8].copy_from_slice(&rng.next().to_be_bytes());
bytes[8..].copy_from_slice(&rng.next().to_be_bytes());
bson::Uuid::from_bytes(bytes)
})
.collect();
assert_byte_order_matches_ord(&values);
}
#[cfg(feature = "mongo")]
#[test]
fn bson_object_id_cursor_bytes_agree_with_ord() {
let mut rng = SplitMix64(SEED ^ 8);
let values: Vec<bson::oid::ObjectId> = (0..SAMPLES)
.map(|_| {
let mut bytes = [0u8; 12];
bytes[..8].copy_from_slice(&rng.next().to_be_bytes());
bytes[8..].copy_from_slice(&rng.next().to_be_bytes()[..4]);
bson::oid::ObjectId::from_bytes(bytes)
})
.collect();
assert_byte_order_matches_ord(&values);
}