mod composite;
use super::{
ArityMismatch, Cursor, CursorError, CursorValue, OrderMismatch, OrderSignature, OrderTerm,
TermName, text,
};
use crate::{FieldName, OrderDirection};
const CREATED: &TermName = TermName::new("created_at");
const TITLE: &TermName = TermName::new("title");
const ID: &TermName = TermName::new("id");
#[derive(Debug, Clone, PartialEq)]
enum MediaValue {
Created(i64),
Title(String),
Id(uuid::Uuid),
}
const CREATED_TAG: u8 = 0;
const TITLE_TAG: u8 = 1;
const ID_TAG: u8 = 2;
impl CursorValue for MediaValue {
fn write_cursor(&self, out: &mut Vec<u8>) {
match self {
Self::Created(value) => {
out.push(CREATED_TAG);
value.write_cursor(out);
}
Self::Title(value) => {
out.push(TITLE_TAG);
value.write_cursor(out);
}
Self::Id(value) => {
out.push(ID_TAG);
value.write_cursor(out);
}
}
}
fn read_cursor(bytes: &[u8]) -> Option<Self> {
let (tag, rest) = bytes.split_first()?;
match *tag {
CREATED_TAG => i64::read_cursor(rest).map(Self::Created),
TITLE_TAG => String::read_cursor(rest).map(Self::Title),
ID_TAG => uuid::Uuid::read_cursor(rest).map(Self::Id),
_ => None,
}
}
}
const KEY: uuid::Uuid = uuid::Uuid::from_bytes([0xab; 16]);
fn order() -> [OrderTerm; 3] {
[
OrderTerm::new(CREATED, FieldName::new("created_at"), OrderDirection::Desc),
OrderTerm::nullable(TITLE, FieldName::new("title"), OrderDirection::Asc),
OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
]
}
fn boundary() -> Cursor<MediaValue> {
Cursor::at(
&order(),
[
Some(MediaValue::Created(1_700_000_000)),
Some(MediaValue::Title("a red car".to_owned())),
Some(MediaValue::Id(KEY)),
],
)
}
#[test]
fn a_cursor_carries_the_signature_of_the_order_it_was_minted_under() {
assert_eq!(boundary().signature(), OrderSignature::of(&order()));
assert_eq!(boundary().values().len(), order().len());
}
#[test]
fn a_cursor_round_trips_through_its_opaque_string() {
let cursor = boundary();
let text = cursor.encode();
assert_eq!(Cursor::<MediaValue>::decode(&text), Ok(cursor));
}
#[test]
fn the_frame_is_a_version_a_signature_and_one_length_prefixed_slot_per_term() {
let cursor = Cursor::at(
&order(),
[
Some(MediaValue::Created(1)),
None,
Some(MediaValue::Id(KEY)),
],
);
let frame = text::decode(&cursor.encode()).expect("what `encode` wrote is base64url");
let mut expected = vec![1u8];
expected.extend_from_slice(&OrderSignature::of(&order()).to_blob());
expected.extend_from_slice(&[1, 0, 0, 0, 9, CREATED_TAG]);
expected.extend_from_slice(&1i64.to_be_bytes());
expected.push(0);
expected.extend_from_slice(&[1, 0, 0, 0, 17, ID_TAG]);
expected.extend_from_slice(KEY.as_bytes());
assert_eq!(frame, expected);
}
#[test]
fn a_null_slot_round_trips_as_a_null_slot() {
let cursor = Cursor::at(
&order(),
[
Some(MediaValue::Created(1)),
None,
Some(MediaValue::Id(KEY)),
],
);
let decoded =
Cursor::<MediaValue>::decode(&cursor.encode()).expect("this cursor was just minted");
assert_eq!(decoded.values()[1], None);
assert_eq!(decoded, cursor);
}
#[test]
fn a_cursor_replayed_under_another_order_is_refused() {
let other = [
OrderTerm::new(TITLE, FieldName::new("title"), OrderDirection::Asc),
OrderTerm::nullable(CREATED, FieldName::new("created_at"), OrderDirection::Desc),
OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
];
assert_eq!(
boundary().resume(&other),
Err(CursorError::Order(OrderMismatch::new(
OrderSignature::of(&order()),
OrderSignature::of(&other),
)))
);
assert_eq!(boundary().resume(&order()).map(<[_]>::len), Ok(3));
}
#[test]
fn a_rename_does_not_refuse_an_outstanding_cursor() {
let renamed = [
OrderTerm::new(CREATED, FieldName::new("created"), OrderDirection::Desc),
OrderTerm::nullable(TITLE, FieldName::new("name"), OrderDirection::Asc),
OrderTerm::new(ID, FieldName::new("pk"), OrderDirection::Asc),
];
assert!(boundary().resume(&renamed).is_ok());
}
#[test]
fn a_tuple_that_is_not_as_wide_as_the_order_is_refused() {
let short = Cursor::at(&order(), [Some(MediaValue::Created(1))]);
assert_eq!(
short.resume(&order()),
Err(CursorError::Arity(ArityMismatch::new(1, 3)))
);
}
#[test]
fn a_null_at_a_not_null_term_is_refused() {
let cursor = Cursor::at(
&order(),
[
None,
Some(MediaValue::Title("a red car".to_owned())),
Some(MediaValue::Id(KEY)),
],
);
assert_eq!(cursor.resume(&order()), Err(CursorError::Null(CREATED)));
}
#[test]
fn a_string_that_is_not_the_opaque_spelling_is_refused() {
assert_eq!(
Cursor::<MediaValue>::decode("not a cursor"),
Err(CursorError::Alphabet)
);
}
#[test]
fn a_version_this_build_does_not_know_is_refused() {
let mut frame = text::decode(&boundary().encode()).expect("what `encode` wrote is base64url");
frame[0] = 2;
assert_eq!(
Cursor::<MediaValue>::decode(&text::encode(&frame)),
Err(CursorError::Version(2))
);
}
#[test]
fn a_truncated_frame_is_refused() {
let frame = text::decode(&boundary().encode()).expect("what `encode` wrote is base64url");
assert_eq!(
Cursor::<MediaValue>::decode(&text::encode(&[])),
Err(CursorError::Truncated),
"a frame with no version byte"
);
assert_eq!(
Cursor::<MediaValue>::decode(&text::encode(&frame[..5])),
Err(CursorError::Truncated),
"a frame whose signature is cut short"
);
assert_eq!(
Cursor::<MediaValue>::decode(&text::encode(&frame[..12])),
Err(CursorError::Truncated),
"a frame whose first slot's length is cut short"
);
assert_eq!(
Cursor::<MediaValue>::decode(&text::encode(&frame[..frame.len() - 1])),
Err(CursorError::Truncated),
"a frame whose last slot's value is cut short"
);
let mut enormous = frame.clone();
enormous[10..14].copy_from_slice(&u32::MAX.to_be_bytes());
assert_eq!(
Cursor::<MediaValue>::decode(&text::encode(&enormous)),
Err(CursorError::Truncated),
"a length no frame this size could hold"
);
}
#[test]
fn a_presence_byte_that_is_neither_is_refused() {
let mut frame = text::decode(&boundary().encode()).expect("what `encode` wrote is base64url");
frame[9] = 2;
assert_eq!(
Cursor::<MediaValue>::decode(&text::encode(&frame)),
Err(CursorError::Truncated)
);
}
#[test]
fn a_slot_that_is_not_a_value_of_this_type_is_refused_at_its_position() {
let mut frame = text::decode(&boundary().encode()).expect("what `encode` wrote is base64url");
let tag = 9 + 14 + 5;
frame[tag] = 9;
assert_eq!(
Cursor::<MediaValue>::decode(&text::encode(&frame)),
Err(CursorError::Value(1))
);
}
#[test]
fn the_refusals_say_which_one_they_are() {
assert_eq!(
CursorError::Order(OrderMismatch::new(
OrderSignature::of(&order()),
OrderSignature::of(&[])
))
.to_string(),
"this cursor was minted under another order (0x0a6c8216b482e628, replayed against \
0xcbf29ce484222325)"
);
assert_eq!(
CursorError::Arity(ArityMismatch::new(1, 3)).to_string(),
"this cursor carries 1 values and the order has 3 terms"
);
assert_eq!(
CursorError::Null(CREATED).to_string(),
"this cursor is null at `created_at`, which is NOT NULL"
);
assert_eq!(
CursorError::Version(2).to_string(),
"this cursor is version 2 and this build reads version 1"
);
assert_eq!(
CursorError::Value(1).to_string(),
"this cursor's value 1 is not a value of that column"
);
assert_eq!(
CursorError::Alphabet.to_string(),
"this cursor is not base64url"
);
assert_eq!(
CursorError::Truncated.to_string(),
"this cursor's frame ends inside a field"
);
}
mod collection {
use super::{Cursor, CursorError, CursorValue, OrderSignature, OrderTerm, TermName, text};
use crate::{FieldName, OrderDirection};
const TAGS: &TermName = TermName::new("tags");
const ID: &TermName = TermName::new("id");
const TAGS_TAG: u8 = 0;
const ID_TAG: u8 = 1;
#[derive(Debug, Clone, PartialEq)]
enum Slot {
Tags(Vec<String>),
Id(i64),
}
impl CursorValue for Slot {
fn write_cursor(&self, out: &mut Vec<u8>) {
match self {
Self::Tags(value) => {
out.push(TAGS_TAG);
value.write_cursor(out);
}
Self::Id(value) => {
out.push(ID_TAG);
value.write_cursor(out);
}
}
}
fn read_cursor(bytes: &[u8]) -> Option<Self> {
let (tag, rest) = bytes.split_first()?;
match *tag {
TAGS_TAG => <Vec<String> as CursorValue>::read_cursor(rest).map(Self::Tags),
ID_TAG => <i64 as CursorValue>::read_cursor(rest).map(Self::Id),
_ => None,
}
}
}
fn order() -> [OrderTerm; 2] {
[
OrderTerm::array(TAGS, FieldName::new("tags"), OrderDirection::Asc),
OrderTerm::new(ID, FieldName::new("id"), OrderDirection::Asc),
]
}
fn boundary() -> Cursor<Slot> {
Cursor::at(
&order(),
[
Some(Slot::Tags(vec!["hdr".to_owned(), "sdr".to_owned()])),
Some(Slot::Id(7)),
],
)
}
#[test]
fn a_collection_slot_is_one_slot_whose_bytes_carry_the_count_and_the_elements() {
let frame = text::decode(&boundary().encode()).expect("what `encode` wrote is base64url");
let mut expected = vec![1u8];
expected.extend_from_slice(&OrderSignature::of(&order()).to_blob());
expected.extend_from_slice(&[1, 0, 0, 0, 19, TAGS_TAG]);
expected.extend_from_slice(&2u32.to_be_bytes());
expected.extend_from_slice(&3u32.to_be_bytes());
expected.extend_from_slice(b"hdr");
expected.extend_from_slice(&3u32.to_be_bytes());
expected.extend_from_slice(b"sdr");
expected.extend_from_slice(&[1, 0, 0, 0, 9, ID_TAG]);
expected.extend_from_slice(&7i64.to_be_bytes());
assert_eq!(frame, expected);
assert_eq!(frame[0], 1, "the frame version does not move for a list");
}
#[test]
fn an_empty_collection_is_a_present_slot_and_not_an_absent_one() {
let cursor = Cursor::at(&order(), [Some(Slot::Tags(Vec::new())), Some(Slot::Id(1))]);
let frame = text::decode(&cursor.encode()).expect("what `encode` wrote is base64url");
assert_eq!(
frame[9..14],
[1, 0, 0, 0, 5],
"PRESENT, and five bytes: the sum's tag and the count"
);
assert_eq!(frame[14..19], [TAGS_TAG, 0, 0, 0, 0]);
assert_eq!(Cursor::<Slot>::decode(&cursor.encode()), Ok(cursor));
}
#[test]
fn a_collection_boundary_round_trips_through_its_opaque_string() {
let cursor = Cursor::at(
&order(),
[
Some(Slot::Tags(vec![
"hdr".to_owned(),
String::new(),
"médià".to_owned(),
])),
Some(Slot::Id(-1)),
],
);
assert_eq!(Cursor::<Slot>::decode(&cursor.encode()), Ok(cursor));
}
#[test]
fn a_malformed_inner_frame_is_refused_as_a_value_at_its_slot() {
let encoded = boundary().encode();
let frame = text::decode(&encoded).expect("what `encode` wrote is base64url");
let count = 1 + 8 + 1 + 4 + 1;
assert_eq!(frame[count..count + 4], [0, 0, 0, 2]);
let overstated = {
let mut frame = frame.clone();
frame[count + 3] = 3;
frame
};
assert_eq!(
Cursor::<Slot>::decode(&text::encode(&overstated)),
Err(CursorError::Value(0)),
"a count larger than the elements behind it"
);
let understated = {
let mut frame = frame.clone();
frame[count + 3] = 1;
frame
};
assert_eq!(
Cursor::<Slot>::decode(&text::encode(&understated)),
Err(CursorError::Value(0)),
"…and one smaller, which leaves bytes no element owns"
);
let short = {
let mut frame = frame.clone();
frame[count + 7] = 4;
frame
};
assert_eq!(
Cursor::<Slot>::decode(&text::encode(&short)),
Err(CursorError::Value(0)),
"an element length longer than the bytes behind it"
);
let invalid = {
let mut frame = frame.clone();
frame[count + 8] = 0x80;
frame
};
assert_eq!(
Cursor::<Slot>::decode(&text::encode(&invalid)),
Err(CursorError::Value(0)),
"and an element the element's own row refuses"
);
assert!(Cursor::<Slot>::decode(&encoded).is_ok());
}
}