1#![deny(missing_docs)]
5
6use bytemuck::cast_slice;
9use derive_getters::Dissolve;
10use std::ops::Range;
11
12pub mod blocks;
13mod radix;
14pub use radix::PositionalRadixTree;
15
16pub trait PositionalHash {
18 fn position(&self) -> u64;
20}
21
22pub type Token = u32;
24
25pub type Salt = Vec<u8>;
28
29pub type SaltHash = u64;
35
36pub type BlockHash = u64;
41
42pub type SequenceHash = u64;
47
48pub fn compute_hash_v2(data: &[u8], seed: u64) -> u64 {
53 xxhash_rust::xxh3::xxh3_64_with_seed(data, seed)
54}
55
56pub const CHAIN_XXH3_SEED: u64 = 1337;
62
63#[inline]
77pub fn compute_next_sequence_hash(
78 parent_sequence_hash: SequenceHash,
79 child_block_hash: BlockHash,
80) -> SequenceHash {
81 let combined = [parent_sequence_hash, child_block_hash];
82 compute_hash_v2(cast_slice(&combined), CHAIN_XXH3_SEED)
83}
84
85mod serde_bytes_u128 {
91 use serde::{Deserializer, Serializer};
92
93 pub fn serialize<S>(val: &u128, serializer: S) -> Result<S::Ok, S::Error>
94 where
95 S: Serializer,
96 {
97 serializer.serialize_bytes(&val.to_be_bytes())
98 }
99
100 pub fn deserialize<'de, D>(deserializer: D) -> Result<u128, D::Error>
101 where
102 D: Deserializer<'de>,
103 {
104 use serde::de::{self, SeqAccess, Visitor};
105 use std::fmt;
106
107 struct V;
108 impl<'de> Visitor<'de> for V {
109 type Value = [u8; 16];
110
111 fn expecting(&self, f: &mut fmt::Formatter) -> fmt::Result {
112 f.write_str("16 bytes (msgpack bin) or a sequence of 16 u8 values")
113 }
114
115 fn visit_bytes<E: de::Error>(self, v: &[u8]) -> Result<[u8; 16], E> {
116 v.try_into()
117 .map_err(|_| E::invalid_length(v.len(), &"16 bytes"))
118 }
119
120 fn visit_borrowed_bytes<E: de::Error>(self, v: &'de [u8]) -> Result<[u8; 16], E> {
121 self.visit_bytes(v)
122 }
123
124 fn visit_byte_buf<E: de::Error>(self, v: Vec<u8>) -> Result<[u8; 16], E> {
125 self.visit_bytes(&v)
126 }
127
128 fn visit_seq<A: SeqAccess<'de>>(self, mut seq: A) -> Result<[u8; 16], A::Error> {
129 let mut arr = [0u8; 16];
130 for (i, slot) in arr.iter_mut().enumerate() {
131 *slot = seq
132 .next_element()?
133 .ok_or_else(|| de::Error::invalid_length(i, &"16 u8 elements"))?;
134 }
135 Ok(arr)
136 }
137 }
138
139 let arr = deserializer.deserialize_bytes(V)?;
140 Ok(u128::from_be_bytes(arr))
141 }
142}
143
144#[inline]
148pub fn compute_block_hash(block_bytes: &[u8], salt: SaltHash) -> BlockHash {
149 compute_hash_v2(block_bytes, salt)
150}
151
152#[inline]
158pub fn compute_block_hash_for_tokens(tokens: &[Token], salt: SaltHash) -> BlockHash {
159 compute_block_hash(cast_slice(tokens), salt)
160}
161
162#[inline]
166pub fn compute_salt_hash_from_bytes(payload: &[u8]) -> SaltHash {
167 compute_hash_v2(payload, 0)
168}
169
170#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
178pub struct TokenBlockMmInfo {
179 pub mm_hash: u64,
181 pub offset: usize,
183 pub length: usize,
185}
186
187pub const MM_SLOT_TAG_TOKEN: u8 = 0x00;
190pub const MM_SLOT_TAG_PLACEHOLDER: u8 = 0x01;
192
193impl TokenBlockMmInfo {
194 #[inline]
196 pub fn checked_end(&self) -> Option<usize> {
197 self.offset.checked_add(self.length)
198 }
199
200 #[inline]
206 pub fn end(&self) -> usize {
207 self.checked_end()
208 .expect("TokenBlockMmInfo::end overflowed usize; run was not validated")
209 }
210
211 #[inline]
215 pub fn covers(&self, position: usize) -> bool {
216 match self.checked_end() {
217 Some(end) => position >= self.offset && position < end,
218 None => false,
219 }
220 }
221}
222
223#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
225pub enum MmInfoError {
226 #[error(
228 "mm_info range starting at {offset} (length {length}) exceeds tokens length {tokens_len}"
229 )]
230 OutOfBounds {
231 offset: usize,
233 length: usize,
235 tokens_len: usize,
237 },
238 #[error("mm_info range starting at {offset} (length {length}) overflows usize")]
240 OffsetOverflow {
241 offset: usize,
243 length: usize,
245 },
246 #[error("mm_info ranges overlap at position {position}")]
248 Overlapping {
249 position: usize,
251 },
252 #[error("mm_info length must be greater than zero")]
254 EmptyRun,
255}
256
257pub fn validate_and_sort_mm_info(
265 mm_info: &[TokenBlockMmInfo],
266 tokens_len: usize,
267) -> Result<Vec<TokenBlockMmInfo>, MmInfoError> {
268 let mut sorted: Vec<TokenBlockMmInfo> = mm_info.to_vec();
269 sorted.sort_by_key(|m| m.offset);
270 let mut prev_end = 0usize;
271 for m in &sorted {
272 if m.length == 0 {
273 return Err(MmInfoError::EmptyRun);
274 }
275 let end = m
276 .offset
277 .checked_add(m.length)
278 .ok_or(MmInfoError::OffsetOverflow {
279 offset: m.offset,
280 length: m.length,
281 })?;
282 if end > tokens_len {
283 return Err(MmInfoError::OutOfBounds {
284 offset: m.offset,
285 length: m.length,
286 tokens_len,
287 });
288 }
289 if m.offset < prev_end {
290 return Err(MmInfoError::Overlapping { position: m.offset });
291 }
292 prev_end = end;
293 }
294 Ok(sorted)
295}
296
297fn block_has_mm(block_offset: usize, len: usize, mm_runs: &[TokenBlockMmInfo]) -> bool {
300 let block_end = block_offset.saturating_add(len);
301 mm_runs
302 .iter()
303 .any(|m| m.offset < block_end && m.end() > block_offset)
304}
305
306pub fn compute_block_bytes_with_mm(
337 tokens: &[Token],
338 block_offset: usize,
339 mm_runs: &[TokenBlockMmInfo],
340) -> Vec<u8> {
341 debug_assert!(
347 mm_runs.windows(2).all(|w| w[0].end() <= w[1].offset),
348 "compute_block_bytes_with_mm: mm_runs must be sorted by offset and non-overlapping (use validate_and_sort_mm_info)",
349 );
350 debug_assert!(
351 mm_runs.iter().all(|r| r.length > 0),
352 "compute_block_bytes_with_mm: mm_runs must have non-zero length",
353 );
354
355 if !block_has_mm(block_offset, tokens.len(), mm_runs) {
356 return cast_slice::<Token, u8>(tokens).to_vec();
359 }
360
361 const FRAME: usize = 13;
362 let mut out: Vec<u8> = Vec::with_capacity(tokens.len() * FRAME);
363 let mut run_idx = 0usize;
364 while run_idx < mm_runs.len() && mm_runs[run_idx].end() <= block_offset {
366 run_idx += 1;
367 }
368 for (s, &tok) in tokens.iter().enumerate() {
369 let g = block_offset + s;
370 while run_idx < mm_runs.len() && mm_runs[run_idx].end() <= g {
372 run_idx += 1;
373 }
374 if run_idx < mm_runs.len() && mm_runs[run_idx].covers(g) {
375 let run = &mm_runs[run_idx];
376 let run_offset = (g - run.offset) as u32;
377 out.push(MM_SLOT_TAG_PLACEHOLDER);
378 out.extend_from_slice(&run_offset.to_le_bytes());
379 out.extend_from_slice(&run.mm_hash.to_le_bytes());
380 } else {
381 out.push(MM_SLOT_TAG_TOKEN);
382 out.extend_from_slice(&tok.to_le_bytes());
383 out.extend_from_slice(&0u64.to_le_bytes());
384 }
385 }
386 out
387}
388
389#[derive(Debug, Clone, Copy, PartialEq, Eq)]
394pub struct BlockLineage {
395 pub block_hash: BlockHash,
397 pub sequence_hash: SequenceHash,
399 pub parent_sequence_hash: Option<SequenceHash>,
401 pub positional_lineage_hash: PositionalLineageHash,
403}
404
405pub fn hash_complete_blocks(
422 tokens: &[Token],
423 mm_runs: &[TokenBlockMmInfo],
424 block_size: u32,
425 salt_hash: SaltHash,
426) -> Vec<BlockLineage> {
427 assert!(block_size > 0, "block_size must be greater than 0");
428 debug_assert!(
429 mm_runs.windows(2).all(|w| w[0].end() <= w[1].offset),
430 "hash_complete_blocks: mm_runs must be sorted by offset and non-overlapping",
431 );
432 debug_assert!(
433 mm_runs.iter().all(|r| r.length > 0),
434 "hash_complete_blocks: mm_runs must have non-zero length",
435 );
436
437 let bs = block_size as usize;
438 let n_complete = tokens.len() / bs;
439 let mut lineages = Vec::with_capacity(n_complete);
440 let mut run_cursor = 0usize;
441 let mut parent_sequence_hash: Option<SequenceHash> = None;
442
443 for position in 0..n_complete {
444 let block_offset = position * bs;
445 let block_end = block_offset + bs;
446 let block_tokens = &tokens[block_offset..block_end];
447
448 while run_cursor < mm_runs.len() && mm_runs[run_cursor].end() <= block_offset {
452 run_cursor += 1;
453 }
454 let overlaps = run_cursor < mm_runs.len() && mm_runs[run_cursor].offset < block_end;
455 let block_hash = if overlaps {
456 let block_bytes = compute_block_bytes_with_mm(block_tokens, block_offset, mm_runs);
457 compute_block_hash(&block_bytes, salt_hash)
458 } else {
459 compute_block_hash_for_tokens(block_tokens, salt_hash)
460 };
461
462 let sequence_hash = match parent_sequence_hash {
463 Some(parent) => compute_next_sequence_hash(parent, block_hash),
464 None => block_hash,
465 };
466 let positional_lineage_hash =
467 PositionalLineageHash::new(sequence_hash, parent_sequence_hash, position as u64);
468 lineages.push(BlockLineage {
469 block_hash,
470 sequence_hash,
471 parent_sequence_hash,
472 positional_lineage_hash,
473 });
474 parent_sequence_hash = Some(sequence_hash);
475 }
476
477 lineages
478}
479
480#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
492#[serde(transparent)]
493pub struct PositionalSequenceHash(#[serde(with = "serde_bytes_u128")] u128);
494
495impl PositionalSequenceHash {
496 pub fn new(sequence_hash: SequenceHash, position: u64, local_block_hash: BlockHash) -> Self {
501 let mode = Self::select_mode(position);
502 let upper = Self::encode_upper(mode, position, local_block_hash);
503 let value = ((upper as u128) << 64) | (sequence_hash as u128);
504 PositionalSequenceHash(value)
505 }
506
507 pub fn sequence_hash(&self) -> SequenceHash {
509 (self.0 & 0xFFFF_FFFF_FFFF_FFFF) as u64
510 }
511
512 pub fn position(&self) -> u64 {
514 let (_, position, _) = self.decode_upper();
515 position
516 }
517
518 pub fn local_block_hash(&self) -> BlockHash {
520 let (_, _, lbh) = self.decode_upper();
521 lbh
522 }
523
524 pub fn mode(&self) -> u8 {
526 let (mode, _, _) = self.decode_upper();
527 mode
528 }
529
530 #[inline(always)]
532 pub fn as_u128(&self) -> u128 {
533 self.0
534 }
535
536 fn select_mode(position: u64) -> u8 {
538 if position < (1u64 << 8) {
539 0 } else if position < (1u64 << 16) {
541 1 } else if position < (1u64 << 24) {
543 2 } else if position < (1u64 << 31) {
545 3 } else {
547 panic!(
548 "Position {} exceeds maximum supported value (2^31 - 1)",
549 position
550 );
551 }
552 }
553
554 fn encode_upper(mode: u8, position: u64, local_block_hash: u64) -> u64 {
556 let (position_bits, lbh_bits) = match mode {
557 0 => (8, 54), 1 => (16, 46), 2 => (24, 38), 3 => (31, 31), _ => unreachable!(
562 "Invalid mode {} when encoding PositionalSequenceHash; mode must be 0, 1, 2, or 3",
563 mode
564 ),
565 };
566
567 let position_mask = (1u64 << position_bits) - 1;
569 let lbh_mask = (1u64 << lbh_bits) - 1;
570
571 let position_part = position & position_mask;
573 let lbh_part = local_block_hash & lbh_mask;
574
575 ((mode as u64) << 62) | (position_part << lbh_bits) | lbh_part
577 }
578
579 fn decode_upper(&self) -> (u8, u64, u64) {
581 let upper = (self.0 >> 64) as u64;
582
583 let mode = (upper >> 62) as u8;
585
586 let (position_bits, lbh_bits) = match mode {
587 0 => (8, 54),
588 1 => (16, 46),
589 2 => (24, 38),
590 3 => (31, 31),
591 _ => unreachable!(
592 "Invalid mode {} in PositionalSequenceHash - value may be corrupted",
593 mode
594 ),
595 };
596
597 let lbh_mask = (1u64 << lbh_bits) - 1;
599 let position_mask = (1u64 << position_bits) - 1;
600
601 let lbh = upper & lbh_mask;
603 let position = (upper >> lbh_bits) & position_mask;
604
605 (mode, position, lbh)
606 }
607}
608
609impl std::fmt::Debug for PositionalSequenceHash {
610 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
611 f.debug_struct("PositionalSequenceHash")
612 .field("sequence_hash", &self.sequence_hash())
613 .field("local_block_hash", &self.local_block_hash())
614 .field("position", &self.position())
615 .finish()
616 }
617}
618
619#[derive(Clone, Copy, PartialEq, Eq, Hash, Default, serde::Serialize, serde::Deserialize)]
639#[serde(transparent)]
640pub struct PositionalLineageHash(#[serde(with = "serde_bytes_u128")] u128);
641
642impl PositionalLineageHash {
643 pub fn new(
659 current_seq_hash: SequenceHash,
660 parent_seq_hash: Option<SequenceHash>,
661 position: u64,
662 ) -> Self {
663 if position >= (1u64 << 24) {
664 panic!(
665 "Position {} exceeds maximum supported value (2^24 - 1 = 16,777,215)",
666 position
667 );
668 }
669
670 let mode = Self::select_mode(position);
671 let (position_bits, parent_bits) = Self::bit_layout(mode);
672
673 let position_mask = (1u128 << position_bits) - 1;
674 let parent_mask = (1u128 << parent_bits) - 1;
675
676 let position_part = (position as u128) & position_mask;
677 let current_part = current_seq_hash as u128;
678 let parent_part = (parent_seq_hash.unwrap_or(0) as u128) & parent_mask;
679
680 let value = ((mode as u128) << 126)
682 | (position_part << (64 + parent_bits))
683 | (current_part << parent_bits)
684 | parent_part;
685
686 PositionalLineageHash(value)
687 }
688
689 pub fn root(block_hash: BlockHash) -> Self {
693 Self::new(block_hash, None, 0)
694 }
695
696 pub fn extend(&self, child_block_hash: BlockHash) -> Self {
707 let parent_seq = self.current_sequence_hash();
708 let child_seq = compute_next_sequence_hash(parent_seq, child_block_hash);
709 Self::new(child_seq, Some(parent_seq), self.position() + 1)
710 }
711
712 pub fn position(&self) -> u64 {
714 let mode = self.mode();
715 let (position_bits, parent_bits) = Self::bit_layout(mode);
716 let position_mask = (1u128 << position_bits) - 1;
717 ((self.0 >> (64 + parent_bits)) & position_mask) as u64
718 }
719
720 pub fn current_sequence_hash(&self) -> SequenceHash {
725 let mode = self.mode();
726 let (_, parent_bits) = Self::bit_layout(mode);
727 ((self.0 >> parent_bits) & 0xFFFF_FFFF_FFFF_FFFFu128) as u64
728 }
729
730 pub fn parent_hash_fragment(&self) -> u64 {
735 let mode = self.mode();
736 let (_, parent_bits) = Self::bit_layout(mode);
737 let parent_mask = (1u128 << parent_bits) - 1;
738 (self.0 & parent_mask) as u64
739 }
740
741 pub fn parent_fragment_for_child_position(&self, child_position: u64) -> u64 {
748 let child_mode = Self::select_mode(child_position);
749 let (_, child_parent_bits) = Self::bit_layout(child_mode);
750 let mask = (1u64 << child_parent_bits).wrapping_sub(1);
751 self.current_sequence_hash() & mask
752 }
753
754 pub fn mode(&self) -> u8 {
756 (self.0 >> 126) as u8
757 }
758
759 #[inline(always)]
761 pub fn as_u128(&self) -> u128 {
762 self.0
763 }
764
765 fn select_mode(position: u64) -> u8 {
767 if position < (1u64 << 8) {
768 0 } else if position < (1u64 << 16) {
770 1 } else {
772 2 }
774 }
775
776 fn bit_layout(mode: u8) -> (u32, u32) {
779 match mode {
780 0 => (8, 54), 1 => (16, 46), 2 => (24, 38), _ => unreachable!(
784 "Invalid mode {} in PositionalLineageHash; mode must be 0, 1, or 2",
785 mode
786 ),
787 }
788 }
789}
790
791impl PositionalLineageHash {
792 fn format_impl(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
793 let position = self.position();
794 let current_hash = self.current_sequence_hash();
795 let current_hash_b58 = bs58::encode(current_hash.to_be_bytes()).into_string();
796
797 if position == 0 {
798 write!(f, "{}:{}", position, current_hash_b58)
799 } else {
800 let parent_hash = self.parent_hash_fragment();
801 let parent_hash_b58 = bs58::encode(parent_hash.to_be_bytes()).into_string();
802 write!(f, "{}:{}:{}", position, current_hash_b58, parent_hash_b58)
803 }
804 }
805}
806
807impl std::fmt::Debug for PositionalLineageHash {
808 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
809 self.format_impl(f)
810 }
811}
812
813impl std::fmt::Display for PositionalLineageHash {
814 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
815 self.format_impl(f)
816 }
817}
818
819impl std::cmp::PartialOrd for PositionalLineageHash {
820 fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
821 Some(self.cmp(other))
822 }
823}
824
825impl std::cmp::Ord for PositionalLineageHash {
826 fn cmp(&self, other: &Self) -> std::cmp::Ordering {
829 self.position()
830 .cmp(&other.position())
831 .then_with(|| {
832 self.current_sequence_hash()
833 .cmp(&other.current_sequence_hash())
834 })
835 .then_with(|| self.0.cmp(&other.0))
836 }
837}
838
839#[derive(Debug, Clone, Dissolve, Default, Eq)]
843pub struct Tokens(Vec<Token>);
844
845impl AsRef<[Token]> for Tokens {
846 fn as_ref(&self) -> &[Token] {
847 &self.0
848 }
849}
850
851impl std::ops::Deref for Tokens {
852 type Target = [Token];
853
854 fn deref(&self) -> &Self::Target {
855 &self.0
856 }
857}
858
859impl std::borrow::Borrow<[Token]> for Tokens {
860 fn borrow(&self) -> &[Token] {
861 &self.0
862 }
863}
864
865impl From<Vec<Token>> for Tokens {
866 fn from(tokens: Vec<Token>) -> Self {
867 Tokens(tokens)
868 }
869}
870
871impl From<&[Token]> for Tokens {
872 fn from(tokens: &[Token]) -> Self {
873 Tokens(tokens.to_vec())
874 }
875}
876
877impl From<Vec<usize>> for Tokens {
878 fn from(tokens: Vec<usize>) -> Self {
879 Tokens(
880 tokens
881 .into_iter()
882 .map(|t| t.try_into().expect("Token ID exceeds u32::MAX"))
883 .collect(),
884 )
885 }
886}
887
888impl From<Vec<i32>> for Tokens {
889 fn from(tokens: Vec<i32>) -> Self {
891 Tokens(tokens.into_iter().map(|t| t as u32).collect())
892 }
893}
894
895impl From<&[i32]> for Tokens {
896 fn from(tokens: &[i32]) -> Self {
898 Tokens(tokens.iter().map(|&t| t as u32).collect())
899 }
900}
901
902impl From<Tokens> for Vec<Token> {
903 fn from(tokens: Tokens) -> Self {
904 tokens.0
905 }
906}
907
908impl PartialEq<Vec<Token>> for Tokens {
911 fn eq(&self, other: &Vec<Token>) -> bool {
912 self.0 == *other
913 }
914}
915
916impl PartialEq<Tokens> for Vec<Token> {
917 fn eq(&self, other: &Tokens) -> bool {
918 *self == other.0
919 }
920}
921
922impl PartialEq<[Token]> for Tokens {
923 fn eq(&self, other: &[Token]) -> bool {
924 self.0.as_slice() == other
925 }
926}
927
928impl PartialEq<Tokens> for &[Token] {
929 fn eq(&self, other: &Tokens) -> bool {
930 *self == other.0.as_slice()
931 }
932}
933
934impl PartialEq for Tokens {
935 fn eq(&self, other: &Self) -> bool {
936 self.0 == other.0
937 }
938}
939
940impl PartialEq<&[Token]> for Tokens {
943 fn eq(&self, other: &&[Token]) -> bool {
944 self.0.as_slice() == *other
945 }
946}
947
948impl Tokens {
949 fn with_capacity(capacity: usize) -> Self {
950 Tokens(Vec::with_capacity(capacity))
951 }
952
953 pub fn into_sequence(self, block_size: u32, salt_hash: Option<SaltHash>) -> TokenBlockSequence {
963 TokenBlockSequence::new(self, block_size, salt_hash)
964 }
965}
966
967#[derive(Debug, Clone, Copy, PartialEq, Eq, thiserror::Error)]
969pub enum TokenBlockError {
970 #[error("TokenBlock is full")]
972 Full,
973
974 #[error("TokenBlock is incomplete")]
976 Incomplete,
977
978 #[error("TokenBlock is empty")]
980 Empty,
981
982 #[error("TokenBlock has insufficient tokens")]
984 InsufficientTokens,
985
986 #[error(transparent)]
988 MmInfo(#[from] MmInfoError),
989
990 #[error("operation is not supported on a TokenBlockSequence with multimodal runs")]
992 MmRunsPresent,
993}
994
995#[derive(Debug, PartialEq)] pub struct PartialTokenBlock {
1001 tokens: Tokens,
1002 block_size: u32,
1003 salt_hash: SaltHash,
1004 parent_sequence_hash: Option<SequenceHash>,
1005 position: usize, }
1007
1008impl PartialTokenBlock {
1009 pub(crate) fn create_sequence_root(block_size: u32, salt_hash: SaltHash) -> Self {
1016 Self {
1017 tokens: Tokens::with_capacity(block_size as usize),
1018 block_size,
1019 salt_hash,
1020 parent_sequence_hash: None, position: 0, }
1023 }
1024
1025 pub(crate) fn push_tokens(&mut self, tokens: Tokens) -> Tokens {
1038 let remaining_space = self.remaining();
1039
1040 if remaining_space == 0 {
1041 return tokens; }
1043
1044 if tokens.0.len() <= remaining_space {
1045 self.tokens.0.extend(tokens.0);
1047 Tokens::default() } else {
1049 let (to_add, remaining) = tokens.0.split_at(remaining_space);
1051 self.tokens.0.extend_from_slice(to_add);
1052 Tokens(remaining.to_vec()) }
1054 }
1055
1056 #[cfg(test)]
1063 pub(crate) fn push_token(&mut self, token: Token) -> Result<(), TokenBlockError> {
1064 if self.tokens.0.len() >= self.block_size as usize {
1065 return Err(TokenBlockError::Full);
1066 }
1067 self.tokens.0.push(token);
1068 Ok(())
1069 }
1070
1071 pub(crate) fn pop_tokens(&mut self, count: usize) -> Result<(), TokenBlockError> {
1082 if self.tokens.0.len() < count {
1083 return Err(TokenBlockError::InsufficientTokens);
1084 }
1085 self.tokens.0.truncate(self.tokens.0.len() - count);
1086 Ok(())
1087 }
1088
1089 pub fn commit(&mut self) -> Result<TokenBlock, TokenBlockError> {
1101 if self.tokens.0.len() != self.block_size as usize {
1102 return Err(TokenBlockError::Incomplete);
1104 }
1105
1106 let tokens = std::mem::replace(
1108 &mut self.tokens,
1109 Tokens::with_capacity(self.block_size as usize),
1110 );
1111
1112 let chunk = TokenBlockChunk::new(tokens, self.salt_hash);
1113 let block = TokenBlock::from_chunk(chunk, self.parent_sequence_hash, self.position);
1114
1115 self.parent_sequence_hash = Some(block.sequence_hash());
1117 self.position += 1; Ok(block)
1121 }
1122
1123 pub fn remaining(&self) -> usize {
1125 (self.block_size as usize).saturating_sub(self.tokens.0.len())
1127 }
1128
1129 pub fn len(&self) -> usize {
1131 self.tokens.0.len()
1132 }
1133
1134 pub fn is_empty(&self) -> bool {
1136 self.tokens.0.is_empty()
1137 }
1138
1139 pub fn tokens(&self) -> &Tokens {
1141 &self.tokens
1142 }
1143}
1144
1145impl std::ops::Deref for PartialTokenBlock {
1147 type Target = Tokens;
1148
1149 fn deref(&self) -> &Self::Target {
1150 &self.tokens
1151 }
1152}
1153
1154#[derive(Debug)] struct TokenBlockChunk {
1160 tokens: Tokens,
1161 salt_hash: SaltHash,
1162 block_hash: BlockHash,
1163}
1164
1165impl TokenBlockChunk {
1166 fn new(tokens: Tokens, salt_hash: SaltHash) -> Self {
1168 let block_hash = compute_block_hash_for_tokens(&tokens, salt_hash);
1169 Self {
1170 tokens,
1171 salt_hash,
1172 block_hash,
1173 }
1174 }
1175
1176 fn from_tokens(tokens: &[Token], salt_hash: SaltHash) -> Self {
1178 let block_hash = compute_block_hash_for_tokens(tokens, salt_hash);
1179 Self {
1180 tokens: tokens.into(), salt_hash,
1182 block_hash,
1183 }
1184 }
1185}
1186
1187#[derive(Debug, Clone, Default, PartialEq)] pub struct TokenBlock {
1193 tokens: Tokens,
1194 salt_hash: SaltHash,
1195 block_hash: BlockHash,
1196 sequence_hash: SequenceHash,
1197 parent_sequence_hash: Option<SequenceHash>,
1198 positional_sequence_hash: PositionalSequenceHash,
1199 positional_lineage_hash: PositionalLineageHash,
1200}
1201
1202impl TokenBlock {
1203 pub fn next_block(&self) -> PartialTokenBlock {
1207 PartialTokenBlock {
1208 tokens: Tokens::with_capacity(self.tokens.len()),
1209 block_size: self.tokens.len() as u32, salt_hash: self.salt_hash,
1211 parent_sequence_hash: Some(self.sequence_hash), position: self.position() as usize + 1, }
1214 }
1215
1216 fn from_chunk(
1220 chunk: TokenBlockChunk,
1221 parent_sequence_hash: Option<SequenceHash>,
1222 position: usize,
1223 ) -> Self {
1224 let sequence_hash = match parent_sequence_hash {
1225 Some(parent) => compute_next_sequence_hash(parent, chunk.block_hash),
1226 None => {
1227 chunk.block_hash
1229 }
1230 };
1231
1232 let positional_sequence_hash = PositionalSequenceHash::new(
1233 sequence_hash,
1234 position as u64,
1235 chunk.block_hash, );
1237
1238 let positional_lineage_hash =
1239 PositionalLineageHash::new(sequence_hash, parent_sequence_hash, position as u64);
1240
1241 Self {
1242 tokens: chunk.tokens,
1243 salt_hash: chunk.salt_hash,
1244 block_hash: chunk.block_hash,
1245 sequence_hash,
1246 parent_sequence_hash,
1247 positional_sequence_hash,
1248 positional_lineage_hash,
1249 }
1250 }
1251
1252 pub fn tokens(&self) -> &Tokens {
1254 &self.tokens
1255 }
1256
1257 pub fn salt_hash(&self) -> SaltHash {
1259 self.salt_hash
1260 }
1261
1262 pub fn block_hash(&self) -> BlockHash {
1264 self.block_hash
1265 }
1266
1267 pub fn sequence_hash(&self) -> SequenceHash {
1269 self.sequence_hash
1270 }
1271
1272 pub fn parent_sequence_hash(&self) -> Option<SequenceHash> {
1274 self.parent_sequence_hash
1275 }
1276
1277 pub fn block_size(&self) -> usize {
1279 self.tokens.0.len()
1280 }
1281
1282 pub fn positional_sequence_hash(&self) -> PositionalSequenceHash {
1284 self.positional_sequence_hash
1285 }
1286
1287 pub fn positional_lineage_hash(&self) -> PositionalLineageHash {
1289 self.positional_lineage_hash
1290 }
1291
1292 pub fn position(&self) -> u64 {
1294 self.positional_sequence_hash.position()
1295 }
1296}
1297
1298impl PositionalHash for PositionalSequenceHash {
1299 fn position(&self) -> u64 {
1300 self.position()
1301 }
1302}
1303
1304impl PositionalHash for PositionalLineageHash {
1305 fn position(&self) -> u64 {
1306 self.position()
1307 }
1308}
1309
1310#[derive(Debug, PartialEq)]
1325pub struct TokenBlockSequence {
1326 blocks: Vec<TokenBlock>,
1327 current_block: PartialTokenBlock,
1328 salt_hash: SaltHash,
1329 block_size: usize,
1330 mm_runs: Vec<TokenBlockMmInfo>,
1334}
1335
1336impl TokenBlockSequence {
1337 pub fn new(tokens: Tokens, block_size: u32, salt_hash: Option<SaltHash>) -> Self {
1352 assert!(block_size > 0, "block_size must be greater than 0");
1353 let salt_hash = salt_hash.unwrap_or_default();
1354 let (blocks, current_block) = Self::split_tokens(&tokens, block_size, salt_hash);
1355
1356 Self {
1357 blocks,
1358 current_block,
1359 salt_hash,
1360 block_size: block_size as usize,
1361 mm_runs: Vec::new(),
1362 }
1363 }
1364
1365 pub fn extend(&mut self, tokens: Tokens) -> Result<Option<Range<usize>>, TokenBlockError> {
1382 let start_block_index = self.blocks.len();
1383 let mut tokens_to_append = tokens;
1384
1385 while !tokens_to_append.is_empty() {
1386 let remaining_in_current = self.current_block.remaining();
1387
1388 if remaining_in_current == 0 {
1389 let new_block = self.commit_current()?;
1391 self.blocks.push(new_block);
1392 }
1394
1395 let available_tokens = tokens_to_append;
1397 tokens_to_append = self.current_block.push_tokens(available_tokens);
1398
1399 if self.current_block.remaining() == 0 {
1401 let new_block = self.commit_current()?;
1404 self.blocks.push(new_block);
1405 }
1406 }
1407
1408 let end_block_index = self.blocks.len();
1409 if start_block_index == end_block_index {
1410 Ok(None) } else {
1412 Ok(Some(start_block_index..end_block_index))
1413 }
1414 }
1415
1416 fn commit_current(&mut self) -> Result<TokenBlock, TokenBlockError> {
1421 if self.mm_runs.is_empty() {
1422 return self.current_block.commit();
1423 }
1424 if self.current_block.tokens.0.len() != self.current_block.block_size as usize {
1426 return Err(TokenBlockError::Incomplete);
1427 }
1428 let block_offset = self.blocks.len() * (self.current_block.block_size as usize);
1429 let tokens = std::mem::take(&mut self.current_block.tokens);
1430 let block_hash = if block_has_mm(block_offset, tokens.len(), &self.mm_runs) {
1433 let block_bytes = compute_block_bytes_with_mm(&tokens, block_offset, &self.mm_runs);
1434 compute_block_hash(&block_bytes, self.current_block.salt_hash)
1435 } else {
1436 compute_block_hash_for_tokens(&tokens, self.current_block.salt_hash)
1437 };
1438 let chunk = TokenBlockChunk {
1439 tokens,
1440 salt_hash: self.current_block.salt_hash,
1441 block_hash,
1442 };
1443 let block = TokenBlock::from_chunk(
1444 chunk,
1445 self.current_block.parent_sequence_hash,
1446 self.current_block.position,
1447 );
1448 self.current_block.parent_sequence_hash = Some(block.sequence_hash());
1449 self.current_block.position += 1;
1450 Ok(block)
1451 }
1452
1453 pub fn append(&mut self, token: Token) -> Result<Option<usize>, TokenBlockError> {
1470 let before = self.blocks.len();
1471 self.extend(Tokens::from(vec![token]))?;
1472 Ok(if self.blocks.len() > before {
1473 Some(before)
1474 } else {
1475 None
1476 })
1477 }
1478
1479 pub fn truncate(&mut self, len: usize) -> Result<(), TokenBlockError> {
1498 if !self.mm_runs.is_empty() {
1499 return Err(TokenBlockError::MmRunsPresent);
1500 }
1501 let current_total_len = self.total_tokens();
1502 if len >= current_total_len {
1503 return Ok(()); }
1505
1506 let n = current_total_len - len; {
1510 let current_len = self.current_block.len();
1511 let block_size = self.current_block.block_size.max(1);
1513
1514 if n <= current_len {
1515 self.current_block.pop_tokens(n)?;
1517 } else {
1518 let tokens_to_pop_from_blocks = n - current_len;
1520
1521 let num_blocks_to_affect = tokens_to_pop_from_blocks.div_ceil(block_size as usize);
1523
1524 if num_blocks_to_affect > self.blocks.len() {
1526 debug_assert!(
1528 false,
1529 "Truncate calculation error: trying to pop too many blocks."
1530 );
1531 return Err(TokenBlockError::InsufficientTokens);
1532 }
1533
1534 let source_block_index = self.blocks.len() - num_blocks_to_affect;
1536
1537 let num_full_blocks_completely_popped = num_blocks_to_affect - 1;
1539 let num_tokens_to_pop_from_source_block = tokens_to_pop_from_blocks
1540 - num_full_blocks_completely_popped * block_size as usize;
1541 let num_tokens_to_keep_in_new_partial =
1542 (block_size as usize).saturating_sub(num_tokens_to_pop_from_source_block);
1543
1544 let new_partial_tokens = if num_tokens_to_keep_in_new_partial > 0 {
1546 self.blocks[source_block_index].tokens().as_ref()
1547 [..num_tokens_to_keep_in_new_partial]
1548 .to_vec()
1549 } else {
1550 Vec::new()
1551 };
1552
1553 self.blocks.truncate(source_block_index);
1555
1556 self.current_block.tokens = Tokens(new_partial_tokens);
1558 self.current_block.parent_sequence_hash =
1560 self.blocks.last().map(|b| b.sequence_hash());
1561 self.current_block.position = self.blocks.len();
1563 }
1565 }
1566 Ok(())
1567 }
1568
1569 pub fn unwind(&mut self, count: usize) -> Result<(), TokenBlockError> {
1583 let current_total_len = self.total_tokens();
1584 if count > current_total_len {
1585 return Err(TokenBlockError::InsufficientTokens);
1587 }
1588
1589 let len = current_total_len - count;
1591 self.truncate(len)
1592 }
1593
1594 pub fn reset(&mut self) {
1600 self.blocks.clear();
1601 self.current_block =
1602 PartialTokenBlock::create_sequence_root(self.block_size as u32, self.salt_hash);
1603 self.mm_runs.clear();
1604 }
1605
1606 pub fn pop(&mut self) -> Option<Token> {
1622 if !self.mm_runs.is_empty() {
1623 panic!(
1624 "TokenBlockSequence::pop is not supported on a sequence with multimodal runs; \
1625 use try_pop or reset before pop"
1626 );
1627 }
1628 let current_total_len = self.total_tokens();
1629 if current_total_len == 0 {
1630 return None;
1631 }
1632
1633 let last_token = if !self.current_block.tokens.is_empty() {
1636 *self
1638 .current_block
1639 .tokens
1640 .last()
1641 .expect("Current block checked for non-empty")
1642 } else {
1643 let last_block = self
1645 .blocks
1646 .last()
1647 .expect("Sequence is not empty but has no blocks and empty current block?");
1648 *last_block
1649 .tokens()
1650 .last()
1651 .expect("Last block cannot be empty")
1652 };
1653
1654 match self.truncate(current_total_len - 1) {
1657 Ok(_) => Some(last_token),
1658 Err(_) => {
1659 debug_assert!(
1662 false,
1663 "truncate failed unexpectedly after checking length in pop"
1664 );
1665 None
1666 }
1667 }
1668 }
1669
1670 pub fn try_pop(&mut self) -> Result<Option<Token>, TokenBlockError> {
1677 if !self.mm_runs.is_empty() {
1678 return Err(TokenBlockError::MmRunsPresent);
1679 }
1680 Ok(self.pop())
1681 }
1682
1683 pub fn blocks(&self) -> &[TokenBlock] {
1685 &self.blocks
1686 }
1687
1688 pub fn last_complete_block(&self) -> Option<&TokenBlock> {
1690 self.blocks.last()
1691 }
1692
1693 pub fn current_block(&self) -> &PartialTokenBlock {
1695 &self.current_block
1696 }
1697
1698 pub fn into_parts(self) -> (Vec<TokenBlock>, PartialTokenBlock) {
1700 (self.blocks, self.current_block)
1701 }
1702
1703 pub fn block_size(&self) -> usize {
1705 self.block_size
1706 }
1707
1708 pub fn salt_hash(&self) -> SaltHash {
1710 self.salt_hash
1711 }
1712
1713 pub fn total_tokens(&self) -> usize {
1716 let block_size = self.current_block.block_size as usize;
1717 (self.blocks.len() * block_size) + self.current_block.len()
1718 }
1719
1720 pub fn tokens_at(&self, range: Range<usize>) -> Tokens {
1722 let total = self.total_tokens();
1723
1724 if range.start > range.end || range.end > total {
1726 return Tokens::default();
1727 }
1728
1729 if range.is_empty() {
1731 return Tokens::default();
1732 }
1733
1734 let mut result = Vec::with_capacity(range.len());
1735
1736 for i in range {
1737 if i < self.blocks.len() * self.block_size {
1738 let block_index = i / self.block_size;
1740 let token_index = i % self.block_size;
1741 result.push(self.blocks[block_index].tokens()[token_index]);
1742 } else {
1743 let current_block_index = i - (self.blocks.len() * self.block_size);
1745 result.push(self.current_block.tokens()[current_block_index]);
1746 }
1747 }
1748
1749 Tokens::from(result)
1750 }
1751
1752 pub fn split_tokens(
1770 tokens: &[Token],
1771 block_size: u32,
1772 salt_hash: SaltHash,
1773 ) -> (Vec<TokenBlock>, PartialTokenBlock) {
1774 assert!(block_size > 0, "block_size must be greater than 0");
1775 let chunks: Vec<TokenBlockChunk> = tokens
1776 .as_ref()
1777 .chunks_exact(block_size as usize)
1778 .map(|chunk| TokenBlockChunk::from_tokens(chunk, salt_hash))
1779 .collect();
1780
1781 let mut result_blocks = Vec::with_capacity(chunks.len());
1782 let mut last_sequence_hash: Option<SequenceHash> = None;
1783
1784 for (position, chunk) in chunks.into_iter().enumerate() {
1786 let new_block = TokenBlock::from_chunk(chunk, last_sequence_hash, position);
1787 last_sequence_hash = Some(new_block.sequence_hash());
1788 result_blocks.push(new_block);
1789 }
1790
1791 let remainder = tokens
1793 .as_ref()
1794 .chunks_exact(block_size as usize)
1795 .remainder();
1796
1797 let next_position = result_blocks.len(); let mut partial_tokens = Tokens::with_capacity(block_size as usize);
1800 partial_tokens.0.extend_from_slice(remainder);
1801
1802 let current_block = PartialTokenBlock {
1803 tokens: partial_tokens,
1804 block_size,
1805 salt_hash,
1806 parent_sequence_hash: last_sequence_hash,
1808 position: next_position,
1809 };
1810
1811 (result_blocks, current_block)
1812 }
1813
1814 pub fn from_slice(tokens: &[Token], block_size: u32, salt_hash: Option<SaltHash>) -> Self {
1825 assert!(block_size > 0, "block_size must be greater than 0");
1826 let salt_hash = salt_hash.unwrap_or_default();
1827 let (blocks, current_block) = Self::split_tokens(tokens, block_size, salt_hash);
1828
1829 Self {
1830 blocks,
1831 current_block,
1832 salt_hash,
1833 block_size: block_size as usize,
1834 mm_runs: Vec::new(),
1835 }
1836 }
1837
1838 pub fn new_with_mm(
1854 tokens: Tokens,
1855 mm_info: &[TokenBlockMmInfo],
1856 block_size: u32,
1857 salt_hash: Option<SaltHash>,
1858 ) -> Result<Self, TokenBlockError> {
1859 assert!(block_size > 0, "block_size must be greater than 0");
1860 let salt_hash = salt_hash.unwrap_or_default();
1861 let validated =
1862 validate_and_sort_mm_info(mm_info, tokens.len()).map_err(TokenBlockError::MmInfo)?;
1863 let (blocks, current_block) =
1864 Self::split_tokens_with_mm(&tokens, &validated, block_size, salt_hash);
1865 Ok(Self {
1866 blocks,
1867 current_block,
1868 salt_hash,
1869 block_size: block_size as usize,
1870 mm_runs: validated,
1871 })
1872 }
1873
1874 pub fn split_tokens_with_mm(
1878 tokens: &[Token],
1879 mm_runs: &[TokenBlockMmInfo],
1880 block_size: u32,
1881 salt_hash: SaltHash,
1882 ) -> (Vec<TokenBlock>, PartialTokenBlock) {
1883 assert!(block_size > 0, "block_size must be greater than 0");
1884 let bs = block_size as usize;
1885 let lineages = hash_complete_blocks(tokens, mm_runs, block_size, salt_hash);
1886 let mut result_blocks = Vec::with_capacity(lineages.len());
1887 for (position, lineage) in lineages.into_iter().enumerate() {
1888 let block_offset = position * bs;
1889 let chunk = TokenBlockChunk {
1890 tokens: tokens[block_offset..block_offset + bs].into(),
1891 salt_hash,
1892 block_hash: lineage.block_hash,
1893 };
1894 let new_block = TokenBlock::from_chunk(chunk, lineage.parent_sequence_hash, position);
1895 debug_assert_eq!(new_block.sequence_hash(), lineage.sequence_hash);
1896 debug_assert_eq!(
1897 new_block.positional_lineage_hash(),
1898 lineage.positional_lineage_hash
1899 );
1900 result_blocks.push(new_block);
1901 }
1902 let n_complete = result_blocks.len();
1903 let remainder = &tokens[n_complete * bs..];
1904 let current_block = PartialTokenBlock {
1905 tokens: remainder.into(),
1906 block_size,
1907 salt_hash,
1908 parent_sequence_hash: result_blocks.last().map(|block| block.sequence_hash()),
1909 position: n_complete,
1910 };
1911 (result_blocks, current_block)
1912 }
1913
1914 pub fn mm_runs(&self) -> &[TokenBlockMmInfo] {
1916 &self.mm_runs
1917 }
1918
1919 pub fn push_token(&mut self, token: Token) -> Result<Option<usize>, TokenBlockError> {
1923 self.append(token)
1924 }
1925
1926 pub fn push_mm_run(
1934 &mut self,
1935 mm_hash: u64,
1936 length: usize,
1937 ) -> Result<Option<Range<usize>>, TokenBlockError> {
1938 if length == 0 {
1939 return Err(TokenBlockError::MmInfo(MmInfoError::EmptyRun));
1940 }
1941 let offset = self.total_tokens();
1942 self.mm_runs.push(TokenBlockMmInfo {
1943 mm_hash,
1944 offset,
1945 length,
1946 });
1947 let placeholders = Tokens::from(vec![0u32; length]);
1949 self.extend(placeholders)
1950 }
1951
1952 pub fn extend_with_mm(
1961 &mut self,
1962 tokens: &[Token],
1963 mm_info: &[TokenBlockMmInfo],
1964 ) -> Result<Option<Range<usize>>, TokenBlockError> {
1965 let validated =
1966 validate_and_sort_mm_info(mm_info, tokens.len()).map_err(TokenBlockError::MmInfo)?;
1967 let start_block = self.blocks.len();
1968 let mut cursor = 0usize;
1969 for run in &validated {
1970 if run.offset > cursor {
1971 let real = Tokens::from(tokens[cursor..run.offset].to_vec());
1972 self.extend(real)?;
1973 }
1974 self.push_mm_run(run.mm_hash, run.length)?;
1975 cursor = run.offset + run.length;
1976 }
1977 if cursor < tokens.len() {
1978 let real = Tokens::from(tokens[cursor..].to_vec());
1979 self.extend(real)?;
1980 }
1981 let end_block = self.blocks.len();
1982 if start_block == end_block {
1983 Ok(None)
1984 } else {
1985 Ok(Some(start_block..end_block))
1986 }
1987 }
1988}
1989
1990#[cfg(test)]
1991mod tests {
1992 use super::*;
1993 use bytemuck::cast_slice;
1994
1995 fn create_test_sequence(
1997 initial_tokens: &[Token],
1998 block_size: u32,
1999 salt_hash: Option<SaltHash>,
2000 ) -> TokenBlockSequence {
2001 TokenBlockSequence::new(Tokens::from(initial_tokens), block_size, salt_hash)
2002 }
2003
2004 const TEST_SALT_HASH: SaltHash = 1337;
2006 const HASH_1_4: BlockHash = 14643705804678351452; const SEQ_HASH_1_4: SequenceHash = HASH_1_4;
2008 const HASH_5_8: BlockHash = 16777012769546811212; const SEQ_HASH_5_8: SequenceHash = 4945711292740353085; const HASH_9_12: BlockHash = 483935686894639516; const SEQ_HASH_9_12: SequenceHash = 12583592247330656132; #[test]
2014 fn token_hash_helper_matches_canonical_byte_encoding() {
2015 let tokens = [1u32, 2, 3, 4];
2016 assert_eq!(
2017 compute_block_hash_for_tokens(&tokens, TEST_SALT_HASH),
2018 compute_block_hash(cast_slice(&tokens), TEST_SALT_HASH)
2019 );
2020 assert_eq!(
2021 compute_block_hash_for_tokens(&tokens, TEST_SALT_HASH),
2022 HASH_1_4
2023 );
2024 }
2025
2026 impl PartialTokenBlock {
2027 pub fn pop_token(&mut self) -> Result<(), TokenBlockError> {
2034 if self.tokens.0.is_empty() {
2035 return Err(TokenBlockError::Empty);
2036 }
2037 self.tokens.0.pop();
2038 Ok(())
2039 }
2040 }
2041
2042 #[test]
2043 fn test_validate_hash_constants() {
2044 let salt = TEST_SALT_HASH;
2045
2046 let tokens_1_4 = &[1u32, 2, 3, 4];
2048 let computed_hash_1_4 = compute_block_hash(cast_slice(tokens_1_4), salt);
2049 assert_eq!(computed_hash_1_4, HASH_1_4, "Mismatch for HASH_1_4");
2050 assert_eq!(computed_hash_1_4, SEQ_HASH_1_4, "Mismatch for SEQ_HASH_1_4");
2052
2053 let tokens_5_8 = &[5u32, 6, 7, 8];
2055 let computed_hash_5_8 = compute_block_hash(cast_slice(tokens_5_8), salt);
2056 assert_eq!(computed_hash_5_8, HASH_5_8, "Mismatch for HASH_5_8");
2057 let computed_seq_hash_5_8 = compute_next_sequence_hash(SEQ_HASH_1_4, HASH_5_8);
2059 assert_eq!(
2060 computed_seq_hash_5_8, SEQ_HASH_5_8,
2061 "Mismatch for SEQ_HASH_5_8"
2062 );
2063
2064 let tokens_9_12 = &[9u32, 10, 11, 12];
2066 let computed_hash_9_12 = compute_block_hash(cast_slice(tokens_9_12), salt);
2067 assert_eq!(computed_hash_9_12, HASH_9_12, "Mismatch for HASH_9_12");
2068 let computed_seq_hash_9_12 = compute_next_sequence_hash(SEQ_HASH_5_8, HASH_9_12);
2069 assert_eq!(
2070 computed_seq_hash_9_12, SEQ_HASH_9_12,
2071 "Mismatch for SEQ_HASH_9_12"
2072 );
2073 }
2074
2075 #[test]
2076 fn test_positional_sequence_hash_encoding_decoding() {
2077 let seq_hash_0 = 0x1234567890ABCDEF;
2079 let position_0 = 100;
2080 let lbh_0 = 0xFEDCBA9876543210;
2081 let psh_0 = PositionalSequenceHash::new(seq_hash_0, position_0, lbh_0);
2082
2083 assert_eq!(psh_0.mode(), 0, "Position 100 should use mode 0");
2084 assert_eq!(psh_0.sequence_hash(), seq_hash_0);
2085 assert_eq!(psh_0.position(), position_0);
2086 assert_eq!(
2088 psh_0.local_block_hash(),
2089 lbh_0 & ((1u64 << 54) - 1),
2090 "LBH should be truncated to 54 bits"
2091 );
2092
2093 let position_1 = 1000;
2095 let psh_1 = PositionalSequenceHash::new(seq_hash_0, position_1, lbh_0);
2096
2097 assert_eq!(psh_1.mode(), 1, "Position 1000 should use mode 1");
2098 assert_eq!(psh_1.sequence_hash(), seq_hash_0);
2099 assert_eq!(psh_1.position(), position_1);
2100 assert_eq!(
2102 psh_1.local_block_hash(),
2103 lbh_0 & ((1u64 << 46) - 1),
2104 "LBH should be truncated to 46 bits"
2105 );
2106
2107 let position_2 = 100_000;
2109 let psh_2 = PositionalSequenceHash::new(seq_hash_0, position_2, lbh_0);
2110
2111 assert_eq!(psh_2.mode(), 2, "Position 100,000 should use mode 2");
2112 assert_eq!(psh_2.sequence_hash(), seq_hash_0);
2113 assert_eq!(psh_2.position(), position_2);
2114 assert_eq!(
2116 psh_2.local_block_hash(),
2117 lbh_0 & ((1u64 << 38) - 1),
2118 "LBH should be truncated to 38 bits"
2119 );
2120
2121 let position_3 = 20_000_000;
2123 let psh_3 = PositionalSequenceHash::new(seq_hash_0, position_3, lbh_0);
2124
2125 assert_eq!(psh_3.mode(), 3, "Position 20,000,000 should use mode 3");
2126 assert_eq!(psh_3.sequence_hash(), seq_hash_0);
2127 assert_eq!(psh_3.position(), position_3);
2128 assert_eq!(
2130 psh_3.local_block_hash(),
2131 lbh_0 & ((1u64 << 31) - 1),
2132 "LBH should be truncated to 31 bits"
2133 );
2134
2135 let position_255 = 255;
2137 let psh_255 = PositionalSequenceHash::new(seq_hash_0, position_255, lbh_0);
2138 assert_eq!(psh_255.mode(), 0, "Position 255 should use mode 0");
2139 assert_eq!(psh_255.position(), position_255);
2140
2141 let position_256 = 256;
2142 let psh_256 = PositionalSequenceHash::new(seq_hash_0, position_256, lbh_0);
2143 assert_eq!(psh_256.mode(), 1, "Position 256 should use mode 1");
2144 assert_eq!(psh_256.position(), position_256);
2145 }
2146
2147 #[test]
2148 fn test_positional_lineage_hash() {
2149 let current_hash_0 = 0x1234567890ABCDEF;
2151 let parent_hash_0 = 0xFEDCBA9876543210;
2152 let position_0 = 100;
2153 let plh_0 = PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_0);
2154
2155 assert_eq!(plh_0.mode(), 0, "Position 100 should use mode 0");
2156 assert_eq!(plh_0.position(), position_0);
2157 assert_eq!(
2159 plh_0.current_sequence_hash(),
2160 current_hash_0,
2161 "Current sequence hash should be stored in full"
2162 );
2163 assert_eq!(
2164 plh_0.parent_hash_fragment(),
2165 parent_hash_0 & ((1u64 << 54) - 1),
2166 "Parent fragment should be truncated to 54 bits in mode 0"
2167 );
2168
2169 let position_1 = 1000;
2171 let plh_1 = PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_1);
2172
2173 assert_eq!(plh_1.mode(), 1, "Position 1000 should use mode 1");
2174 assert_eq!(plh_1.position(), position_1);
2175 assert_eq!(plh_1.current_sequence_hash(), current_hash_0);
2176 assert_eq!(
2177 plh_1.parent_hash_fragment(),
2178 parent_hash_0 & ((1u64 << 46) - 1),
2179 "Parent fragment should be truncated to 46 bits in mode 1"
2180 );
2181
2182 let position_2 = 100_000;
2184 let plh_2 = PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_2);
2185
2186 assert_eq!(plh_2.mode(), 2, "Position 100,000 should use mode 2");
2187 assert_eq!(plh_2.position(), position_2);
2188 assert_eq!(plh_2.current_sequence_hash(), current_hash_0);
2189 assert_eq!(
2190 plh_2.parent_hash_fragment(),
2191 parent_hash_0 & ((1u64 << 38) - 1),
2192 "Parent fragment should be truncated to 38 bits in mode 2"
2193 );
2194
2195 let position_255 = 255;
2197 let plh_255 = PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_255);
2198 assert_eq!(plh_255.mode(), 0, "Position 255 should use mode 0");
2199 assert_eq!(plh_255.position(), position_255);
2200
2201 let position_256 = 256;
2202 let plh_256 = PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_256);
2203 assert_eq!(plh_256.mode(), 1, "Position 256 should use mode 1");
2204 assert_eq!(plh_256.position(), position_256);
2205
2206 let position_65535 = 65535;
2207 let plh_65535 =
2208 PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_65535);
2209 assert_eq!(plh_65535.mode(), 1, "Position 65535 should use mode 1");
2210 assert_eq!(plh_65535.position(), position_65535);
2211
2212 let position_65536 = 65536;
2213 let plh_65536 =
2214 PositionalLineageHash::new(current_hash_0, Some(parent_hash_0), position_65536);
2215 assert_eq!(plh_65536.mode(), 2, "Position 65536 should use mode 2");
2216 assert_eq!(plh_65536.position(), position_65536);
2217
2218 let plh_root = PositionalLineageHash::new(current_hash_0, None, 0);
2220 assert_eq!(plh_root.mode(), 0);
2221 assert_eq!(plh_root.position(), 0);
2222 assert_eq!(
2223 plh_root.parent_hash_fragment(),
2224 0,
2225 "Root should have zero parent fragment"
2226 );
2227 assert_eq!(plh_root.current_sequence_hash(), current_hash_0);
2228 }
2229
2230 #[test]
2231 #[should_panic(expected = "Position 16777216 exceeds maximum supported value")]
2232 fn test_positional_lineage_hash_panic_on_large_position() {
2233 let current_hash = 0x1234567890ABCDEF;
2234 let parent_hash = 0xFEDCBA9876543210;
2235 let position = 1u64 << 24; let _ = PositionalLineageHash::new(current_hash, Some(parent_hash), position);
2237 }
2238
2239 #[test]
2240 fn test_positional_lineage_hash_mode_boundary_alignment() {
2241 let parent_hash = 0xFEDCBA9876543210;
2247 let current_hash_255 = 0x1234567890ABCDEF;
2248 let current_hash_256 = 0xABCDEF0123456789;
2249
2250 let plh_255 = PositionalLineageHash::new(current_hash_255, Some(parent_hash), 255);
2252 assert_eq!(plh_255.mode(), 0);
2253 assert_eq!(plh_255.current_sequence_hash(), current_hash_255);
2254
2255 let plh_256 = PositionalLineageHash::new(current_hash_256, Some(current_hash_255), 256);
2257 assert_eq!(plh_256.mode(), 1);
2258
2259 let mask_46 = (1u64 << 46) - 1;
2262 assert_eq!(
2263 plh_256.parent_hash_fragment(),
2264 current_hash_255 & mask_46,
2265 "Mode boundary: position 256's parent fragment matches position 255's current truncated to 46 bits"
2266 );
2267 assert_eq!(
2268 plh_256.parent_hash_fragment(),
2269 plh_255.parent_fragment_for_child_position(256),
2270 "parent_fragment_for_child_position helper should match"
2271 );
2272
2273 let current_hash_65535 = 0x1111222233334444;
2275 let current_hash_65536 = 0x5555666677778888;
2276
2277 let plh_65535 = PositionalLineageHash::new(current_hash_65535, Some(parent_hash), 65535);
2278 assert_eq!(plh_65535.mode(), 1);
2279
2280 let plh_65536 =
2281 PositionalLineageHash::new(current_hash_65536, Some(current_hash_65535), 65536);
2282 assert_eq!(plh_65536.mode(), 2);
2283
2284 let mask_38 = (1u64 << 38) - 1;
2286 assert_eq!(
2287 plh_65536.parent_hash_fragment(),
2288 current_hash_65535 & mask_38,
2289 "Mode boundary: position 65536's parent fragment matches position 65535's current truncated to 38 bits"
2290 );
2291 assert_eq!(
2292 plh_65536.parent_hash_fragment(),
2293 plh_65535.parent_fragment_for_child_position(65536),
2294 );
2295 }
2296
2297 #[test]
2298 fn test_positional_lineage_hash_extend() {
2299 let salt: SaltHash = 1337;
2302 let bh: [BlockHash; 3] = [
2303 compute_block_hash(cast_slice(&[1u32, 2, 3, 4]), salt),
2304 compute_block_hash(cast_slice(&[5u32, 6, 7, 8]), salt),
2305 compute_block_hash(cast_slice(&[9u32, 10, 11, 12]), salt),
2306 ];
2307
2308 let blk0 =
2310 TokenBlock::from_chunk(TokenBlockChunk::from_tokens(&[1, 2, 3, 4], salt), None, 0);
2311 let blk1 = TokenBlock::from_chunk(
2312 TokenBlockChunk::from_tokens(&[5, 6, 7, 8], salt),
2313 Some(blk0.sequence_hash()),
2314 1,
2315 );
2316 let blk2 = TokenBlock::from_chunk(
2317 TokenBlockChunk::from_tokens(&[9, 10, 11, 12], salt),
2318 Some(blk1.sequence_hash()),
2319 2,
2320 );
2321
2322 let plh0 = PositionalLineageHash::root(bh[0]);
2324 let plh1 = plh0.extend(bh[1]);
2325 let plh2 = plh1.extend(bh[2]);
2326
2327 assert_eq!(plh0.as_u128(), blk0.positional_lineage_hash().as_u128());
2328 assert_eq!(plh1.as_u128(), blk1.positional_lineage_hash().as_u128());
2329 assert_eq!(plh2.as_u128(), blk2.positional_lineage_hash().as_u128());
2330
2331 assert_eq!(
2333 plh1.current_sequence_hash(),
2334 compute_next_sequence_hash(plh0.current_sequence_hash(), bh[1]),
2335 );
2336
2337 let alt_salt: SaltHash = 4242;
2340 let alt_bh0 = compute_block_hash(cast_slice(&[1u32, 2, 3, 4]), alt_salt);
2341 assert_ne!(alt_bh0, bh[0]);
2342 let alt_plh0 = PositionalLineageHash::root(alt_bh0);
2343 let alt_plh1 = alt_plh0.extend(compute_block_hash(cast_slice(&[5u32, 6, 7, 8]), alt_salt));
2344 assert_ne!(alt_plh0.as_u128(), plh0.as_u128());
2345 assert_ne!(alt_plh1.as_u128(), plh1.as_u128());
2346 }
2347
2348 #[test]
2349 fn test_tokens_from() {
2350 let vec_u32: Vec<u32> = vec![1, 2, 3];
2351 let tokens_u32: Tokens = vec_u32.clone().into();
2352 assert_eq!(tokens_u32.0, vec_u32);
2353
2354 let slice_u32: &[u32] = &[4, 5];
2355 let tokens_slice_u32: Tokens = slice_u32.into();
2356 assert_eq!(tokens_slice_u32.0, vec![4, 5]);
2357
2358 let vec_i32: Vec<i32> = vec![-1, 0, 1]; let tokens_i32: Tokens = vec_i32.into();
2360 assert_eq!(tokens_i32.0, vec![u32::MAX, 0, 1]);
2361
2362 let slice_i32: &[i32] = &[100, 200];
2363 let tokens_slice_i32: Tokens = slice_i32.into();
2364 assert_eq!(tokens_slice_i32.0, vec![100, 200]);
2365
2366 let into_vec: Vec<u32> = tokens_slice_i32.into();
2367 assert_eq!(into_vec, vec![100, 200]);
2368 }
2369
2370 #[test]
2371 fn test_tokens_equality() {
2372 let tokens = Tokens::from(vec![1, 2, 3]);
2373 assert_eq!(tokens, vec![1, 2, 3]);
2374 assert_eq!(vec![1, 2, 3], tokens);
2375 assert_eq!(tokens, &[1, 2, 3][..]);
2376 assert_eq!(&[1, 2, 3][..], tokens);
2377 assert_eq!(tokens, Tokens::from(vec![1, 2, 3]));
2378 assert_ne!(tokens, Tokens::from(vec![1, 2, 4]));
2379 }
2380
2381 #[test]
2382 fn test_tokens_deref_asref() {
2383 let tokens = Tokens::from(vec![10, 20, 30]);
2384
2385 assert_eq!(tokens.len(), 3);
2387 assert_eq!(tokens[1], 20);
2388 let slice: &[Token] = &tokens;
2389 assert_eq!(slice, &[10, 20, 30]);
2390
2391 let as_ref_slice: &[Token] = tokens.as_ref();
2393 assert_eq!(as_ref_slice, &[10, 20, 30]);
2394
2395 let borrowed_slice: &[Token] = std::borrow::Borrow::borrow(&tokens);
2397 assert_eq!(borrowed_slice, &[10, 20, 30]);
2398 }
2399
2400 #[test]
2401 fn test_tokens_into_sequence() {
2402 let tokens = Tokens::from(vec![1, 2, 3, 4, 5]);
2403 let seq = tokens.into_sequence(3, Some(TEST_SALT_HASH));
2404 assert_eq!(seq.blocks().len(), 1);
2405 assert_eq!(seq.blocks[0].tokens().as_ref(), &[1, 2, 3]);
2406 assert_eq!(seq.current_block().tokens().as_ref(), &[4, 5]);
2407 assert_eq!(seq.salt_hash(), TEST_SALT_HASH);
2408 }
2409
2410 #[test]
2411 fn test_partial_block_ops() {
2412 let mut partial = PartialTokenBlock::create_sequence_root(3, TEST_SALT_HASH);
2413 assert_eq!(partial.len(), 0);
2414 assert_eq!(partial.remaining(), 3);
2415 assert!(partial.is_empty());
2416
2417 assert!(partial.push_token(1).is_ok());
2419 assert_eq!(partial.len(), 1);
2420 assert_eq!(partial.remaining(), 2);
2421 let remaining = partial.push_tokens(Tokens::from(vec![2, 3, 4]));
2422 assert_eq!(partial.len(), 3);
2423 assert_eq!(partial.remaining(), 0);
2424 assert_eq!(remaining.as_ref(), &[4]); assert_eq!(partial.tokens().as_ref(), &[1, 2, 3]);
2426
2427 assert_eq!(partial.push_token(5), Err(TokenBlockError::Full));
2429 let remaining_full = partial.push_tokens(Tokens::from(vec![5]));
2430 assert_eq!(remaining_full.as_ref(), &[5]);
2431
2432 assert!(partial.pop_token().is_ok());
2434 assert_eq!(partial.len(), 2);
2435 assert_eq!(partial.tokens().as_ref(), &[1, 2]);
2436 assert!(partial.pop_tokens(2).is_ok());
2437 assert!(partial.is_empty());
2438
2439 assert_eq!(partial.pop_token(), Err(TokenBlockError::Empty));
2441 assert_eq!(
2442 partial.pop_tokens(1),
2443 Err(TokenBlockError::InsufficientTokens)
2444 );
2445
2446 assert!(partial.push_token(10).is_ok());
2448 assert_eq!(partial.commit(), Err(TokenBlockError::Incomplete));
2449
2450 assert!(partial.push_token(11).is_ok());
2452 assert!(partial.push_token(12).is_ok());
2453 assert_eq!(partial.len(), 3);
2454 let commit_result = partial.commit();
2455 assert!(commit_result.is_ok());
2456 let committed_block = commit_result.unwrap();
2457 assert_eq!(committed_block.tokens().as_ref(), &[10, 11, 12]);
2458
2459 assert!(partial.is_empty());
2461 assert_eq!(
2462 partial.parent_sequence_hash,
2463 Some(committed_block.sequence_hash())
2464 );
2465 assert_eq!(partial.block_size, 3);
2466 }
2467
2468 #[test]
2469 fn test_token_block_creation_and_hashes() {
2470 let salt = TEST_SALT_HASH;
2471 let tokens1 = Tokens::from(vec![1, 2, 3, 4]);
2472 let chunk1 = TokenBlockChunk::new(tokens1.clone(), salt);
2473 let block1 = TokenBlock::from_chunk(chunk1, None, 0);
2474
2475 assert_eq!(block1.tokens(), &tokens1);
2476 assert_eq!(block1.salt_hash(), salt);
2477 assert_eq!(block1.parent_sequence_hash(), None);
2478 assert_eq!(block1.block_hash(), HASH_1_4);
2479 assert_eq!(block1.sequence_hash(), SEQ_HASH_1_4); assert_eq!(block1.position(), 0); let plh1 = block1.positional_lineage_hash();
2484 assert_eq!(plh1.position(), 0);
2485 assert_eq!(plh1.parent_hash_fragment(), 0); assert_eq!(plh1.current_sequence_hash(), SEQ_HASH_1_4);
2487
2488 let tokens2 = Tokens::from(vec![5, 6, 7, 8]);
2489 let chunk2 = TokenBlockChunk::new(tokens2.clone(), salt);
2490 let block2 = TokenBlock::from_chunk(chunk2, block1.parent_sequence_hash(), 1); assert_ne!(block2.sequence_hash(), SEQ_HASH_5_8);
2493
2494 let chunk2_correct = TokenBlockChunk::new(tokens2.clone(), salt);
2495 let block2_correct =
2496 TokenBlock::from_chunk(chunk2_correct, Some(block1.sequence_hash()), 1);
2497
2498 assert_eq!(block2_correct.tokens(), &tokens2);
2499 assert_eq!(block2_correct.salt_hash(), salt);
2500 assert_eq!(
2501 block2_correct.parent_sequence_hash(),
2502 Some(block1.sequence_hash())
2503 );
2504 assert_eq!(block2_correct.block_hash(), HASH_5_8);
2505 assert_eq!(block2_correct.sequence_hash(), SEQ_HASH_5_8);
2506 assert_eq!(block2_correct.position(), 1); let plh2 = block2_correct.positional_lineage_hash();
2510 assert_eq!(plh2.position(), 1);
2511 assert_eq!(
2512 plh2.parent_hash_fragment(),
2513 SEQ_HASH_1_4 & ((1u64 << 54) - 1)
2514 ); assert_eq!(plh2.current_sequence_hash(), SEQ_HASH_5_8);
2516 }
2517
2518 #[test]
2519 fn test_new_sequence() {
2520 let seq_empty = create_test_sequence(&[], 4, Some(TEST_SALT_HASH));
2522 assert!(seq_empty.blocks().is_empty());
2523 assert!(seq_empty.current_block().is_empty());
2524 assert_eq!(seq_empty.total_tokens(), 0);
2525 assert_eq!(seq_empty.salt_hash(), TEST_SALT_HASH);
2526 assert_eq!(seq_empty.current_block().parent_sequence_hash, None);
2527
2528 let seq_partial = create_test_sequence(&[1, 2], 4, Some(TEST_SALT_HASH));
2530 assert!(seq_partial.blocks().is_empty());
2531 assert_eq!(seq_partial.current_block().tokens().as_ref(), &[1, 2]);
2532 assert_eq!(seq_partial.total_tokens(), 2);
2533 assert_eq!(seq_partial.current_block().parent_sequence_hash, None);
2534
2535 let seq_one_block = create_test_sequence(&[1, 2, 3, 4], 4, Some(TEST_SALT_HASH));
2537 assert_eq!(seq_one_block.blocks().len(), 1);
2538 assert!(seq_one_block.current_block().is_empty());
2539 assert_eq!(seq_one_block.total_tokens(), 4);
2540 assert_eq!(seq_one_block.blocks[0].tokens().as_ref(), &[1, 2, 3, 4]);
2541 assert_eq!(seq_one_block.blocks[0].sequence_hash(), SEQ_HASH_1_4);
2542 assert_eq!(
2543 seq_one_block.current_block().parent_sequence_hash,
2544 Some(SEQ_HASH_1_4)
2545 );
2546
2547 let seq_multi = create_test_sequence(&[1, 2, 3, 4, 5, 6, 7, 8, 9], 4, Some(TEST_SALT_HASH));
2549 assert_eq!(seq_multi.blocks().len(), 2);
2550 assert_eq!(seq_multi.current_block().tokens().as_ref(), &[9]);
2551 assert_eq!(seq_multi.total_tokens(), 9);
2552 assert_eq!(seq_multi.blocks[0].sequence_hash(), SEQ_HASH_1_4);
2553 assert_eq!(seq_multi.blocks[1].sequence_hash(), SEQ_HASH_5_8);
2554 assert_eq!(
2555 seq_multi.current_block().parent_sequence_hash,
2556 Some(SEQ_HASH_5_8)
2557 );
2558
2559 assert_eq!(seq_multi.tokens_at(0..4).as_ref(), &[1, 2, 3, 4]); assert_eq!(seq_multi.tokens_at(4..8).as_ref(), &[5, 6, 7, 8]); assert_eq!(seq_multi.tokens_at(8..9).as_ref(), &[9]); assert_eq!(seq_multi.tokens_at(2..6).as_ref(), &[3, 4, 5, 6]); assert_eq!(seq_multi.tokens_at(6..9).as_ref(), &[7, 8, 9]); assert_eq!(seq_multi.tokens_at(5..5).as_ref(), &[0u32; 0]); assert_eq!(seq_multi.tokens_at(10..15).as_ref(), &[0u32; 0]); let seq_no_salt = create_test_sequence(&[1, 2, 3, 4, 5], 4, None);
2570 assert_eq!(seq_no_salt.salt_hash(), 0);
2571 assert_eq!(seq_no_salt.blocks().len(), 1);
2572 assert_ne!(seq_no_salt.blocks[0].block_hash(), HASH_1_4); assert_eq!(seq_no_salt.current_block().tokens().as_ref(), &[5]);
2574 }
2575
2576 #[test]
2577 #[should_panic]
2578 fn test_new_sequence_zero_block_size() {
2579 let _ = create_test_sequence(&[1], 0, None);
2580 }
2581
2582 #[test]
2583 fn test_append_single_token() {
2584 let mut sequence =
2585 create_test_sequence(&[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 4, Some(TEST_SALT_HASH));
2586 assert_eq!(sequence.blocks().len(), 2);
2587 assert_eq!(sequence.current_block().tokens.len(), 2);
2588 assert_eq!(sequence.current_block().tokens, vec![9, 10]);
2589 assert_eq!(
2590 sequence.current_block().parent_sequence_hash,
2591 Some(SEQ_HASH_5_8)
2592 );
2593
2594 let completed_idx = sequence.append(11).unwrap();
2596 assert_eq!(completed_idx, None);
2597 assert_eq!(sequence.blocks().len(), 2);
2598 assert_eq!(sequence.current_block().tokens.as_ref(), &[9, 10, 11]);
2599
2600 let completed_idx = sequence.append(12).unwrap();
2603 assert_eq!(completed_idx, Some(2));
2604 assert_eq!(sequence.blocks().len(), 3);
2605 assert_eq!(sequence.current_block.tokens.as_ref(), &[0u32; 0]);
2606 assert_eq!(sequence.current_block.remaining(), 4);
2607 assert_eq!(
2608 sequence.current_block().parent_sequence_hash,
2609 Some(SEQ_HASH_9_12)
2610 ); let completed_idx_13 = sequence.append(13).unwrap();
2614 assert_eq!(completed_idx_13, None);
2615 assert_eq!(sequence.blocks().len(), 3);
2616 assert_eq!(sequence.blocks[2].tokens().as_ref(), &[9, 10, 11, 12]);
2617 assert_eq!(sequence.blocks[2].sequence_hash(), SEQ_HASH_9_12);
2618 assert_eq!(sequence.current_block.tokens.as_ref(), &[13]); assert_eq!(sequence.current_block.remaining(), 3);
2620 assert_eq!(
2621 sequence.current_block.parent_sequence_hash,
2622 Some(SEQ_HASH_9_12)
2623 ); }
2625
2626 #[test]
2627 fn test_extend() {
2628 let block_size = 4;
2629 let salt_hash = Some(TEST_SALT_HASH);
2630
2631 let mut seq1 = create_test_sequence(&[], block_size, salt_hash);
2633 let tokens1 = Tokens::from(vec![1, 2]);
2634 let completed1 = seq1.extend(tokens1).unwrap();
2635 assert_eq!(completed1, None); assert_eq!(seq1.blocks.len(), 0);
2637 assert_eq!(seq1.current_block.tokens.as_ref(), &[1, 2]);
2638 assert_eq!(seq1.current_block.remaining(), 2);
2639 assert_eq!(seq1.current_block.parent_sequence_hash, None); let mut seq2 = create_test_sequence(&[], block_size, salt_hash);
2643 let tokens2 = Tokens::from(vec![1, 2, 3, 4]);
2644 let completed2 = seq2.extend(tokens2).unwrap();
2645 assert_eq!(completed2, Some(0..1));
2646 assert_eq!(seq2.blocks.len(), 1);
2647 assert_eq!(seq2.current_block.tokens.as_ref(), &[0u32; 0]); assert_eq!(seq2.current_block.remaining(), 4);
2649 assert_eq!(seq2.current_block.parent_sequence_hash, Some(SEQ_HASH_1_4)); let mut seq3 = create_test_sequence(&[], block_size, salt_hash);
2653 let tokens3 = Tokens::from(vec![1, 2, 3, 4, 5, 6]);
2654 let completed3 = seq3.extend(tokens3).unwrap();
2655 assert_eq!(completed3, Some(0..1)); assert_eq!(seq3.blocks.len(), 1);
2657 assert_eq!(seq3.current_block.tokens.as_ref(), &[5, 6]); assert_eq!(seq3.blocks[0].tokens().as_ref(), &[1, 2, 3, 4]);
2659 assert_eq!(seq3.current_block.parent_sequence_hash, Some(SEQ_HASH_1_4));
2660 assert_eq!(seq3.current_block.remaining(), 2);
2661
2662 let mut seq4 = create_test_sequence(&[], block_size, salt_hash);
2664 let tokens4 = Tokens::from(vec![1, 2, 3, 4, 5, 6, 7, 8]);
2665 let completed4 = seq4.extend(tokens4).unwrap();
2666 assert_eq!(completed4, Some(0..2)); assert_eq!(seq4.blocks.len(), 2); assert_eq!(seq4.current_block.tokens.as_ref(), &[0u32; 0]);
2669 assert_eq!(seq4.current_block.remaining(), 4);
2670 assert_eq!(seq4.blocks[0].tokens().as_ref(), &[1, 2, 3, 4]);
2671 assert_eq!(seq4.blocks[0].sequence_hash(), SEQ_HASH_1_4);
2672 assert_eq!(seq4.current_block.parent_sequence_hash, Some(SEQ_HASH_5_8)); let mut seq5 = create_test_sequence(&[], block_size, salt_hash);
2676 let tokens5a = Tokens::from(vec![1, 2]);
2677 let completed5a = seq5.extend(tokens5a).unwrap();
2678 assert_eq!(completed5a, None);
2679 assert_eq!(seq5.blocks.len(), 0);
2680 assert_eq!(seq5.current_block.tokens.as_ref(), &[1, 2]);
2681
2682 let tokens5b = Tokens::from(vec![3, 4, 5]);
2683 let completed5b = seq5.extend(tokens5b).unwrap();
2684 assert_eq!(completed5b, Some(0..1)); assert_eq!(seq5.blocks.len(), 1);
2686 assert_eq!(seq5.current_block.tokens.as_ref(), &[5]);
2687 assert_eq!(seq5.blocks[0].tokens().as_ref(), &[1, 2, 3, 4]);
2688 assert_eq!(seq5.current_block.parent_sequence_hash, Some(SEQ_HASH_1_4));
2689 assert_eq!(seq5.current_block.remaining(), 3);
2690
2691 let tokens5c = Tokens::from(vec![6, 7, 8, 9, 10]);
2692 let completed5c = seq5.extend(tokens5c).unwrap();
2693 assert_eq!(completed5c, Some(1..2)); assert_eq!(seq5.blocks.len(), 2);
2695 assert_eq!(seq5.current_block.tokens.as_ref(), &[9, 10]);
2696 assert_eq!(seq5.blocks[1].tokens().as_ref(), &[5, 6, 7, 8]);
2697 assert_eq!(seq5.current_block.parent_sequence_hash, Some(SEQ_HASH_5_8));
2698 assert_eq!(seq5.current_block.remaining(), 2);
2699
2700 let mut seq6 = create_test_sequence(&[1], block_size, salt_hash);
2702 let completed6 = seq6.extend(Tokens::default()).unwrap();
2703 assert_eq!(completed6, None);
2704 assert_eq!(seq6.blocks.len(), 0);
2705 assert_eq!(seq6.current_block.tokens.as_ref(), &[1]);
2706 assert_eq!(seq6.total_tokens(), 1);
2707
2708 let mut seq7 = create_test_sequence(&[1, 2], block_size, salt_hash);
2710 let tokens7 = Tokens::from(vec![3, 4]);
2711 let completed7 = seq7.extend(tokens7).unwrap();
2712 assert_eq!(completed7, Some(0..1)); assert_eq!(seq7.blocks.len(), 1);
2714 assert_eq!(seq7.current_block.tokens.as_ref(), &[0u32; 0]); assert_eq!(seq7.current_block.remaining(), 4);
2716 assert_eq!(seq7.total_tokens(), 4);
2717 assert_eq!(seq7.current_block.parent_sequence_hash, Some(SEQ_HASH_1_4)); assert_eq!(seq7.tokens_at(0..2).as_ref(), &[1, 2]);
2721 assert_eq!(seq7.tokens_at(1..3).as_ref(), &[2, 3]);
2722 assert_eq!(seq7.tokens_at(0..4).as_ref(), &[1, 2, 3, 4]);
2723 assert_eq!(seq7.tokens_at(2..2).as_ref(), &[0u32; 0]); }
2725
2726 #[test]
2727 fn test_truncate() {
2728 let block_size = 4;
2729 let salt_hash = Some(TEST_SALT_HASH);
2730 let initial_tokens = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let mut seq1 = create_test_sequence(initial_tokens, block_size, salt_hash);
2734 assert!(seq1.truncate(9).is_ok());
2735 assert_eq!(seq1.total_tokens(), 9);
2736 assert_eq!(seq1.blocks().len(), 2);
2737 assert_eq!(seq1.current_block().tokens.as_ref(), &[9]);
2738 assert_eq!(
2739 seq1.current_block().parent_sequence_hash,
2740 Some(SEQ_HASH_5_8)
2741 );
2742
2743 let mut seq2 = create_test_sequence(initial_tokens, block_size, salt_hash);
2745 assert!(seq2.truncate(8).is_ok());
2746 assert_eq!(seq2.total_tokens(), 8);
2747 assert_eq!(seq2.blocks().len(), 2);
2748 assert!(seq2.current_block().tokens.is_empty());
2749 assert_eq!(
2750 seq2.current_block().parent_sequence_hash,
2751 Some(SEQ_HASH_5_8)
2752 );
2753
2754 let mut seq3 = create_test_sequence(initial_tokens, block_size, salt_hash);
2756 assert!(seq3.truncate(7).is_ok());
2757 assert_eq!(seq3.total_tokens(), 7);
2758 assert_eq!(seq3.blocks().len(), 1); assert_eq!(seq3.current_block().tokens.as_ref(), &[5, 6, 7]); assert_eq!(
2761 seq3.current_block().parent_sequence_hash,
2762 Some(SEQ_HASH_1_4)
2763 ); assert_eq!(seq3.blocks()[0].tokens().as_ref(), &[1, 2, 3, 4]);
2765
2766 let mut seq4 = create_test_sequence(initial_tokens, block_size, salt_hash);
2768 assert!(seq4.truncate(4).is_ok());
2769 assert_eq!(seq4.total_tokens(), 4);
2770 assert_eq!(seq4.blocks().len(), 1); assert!(seq4.current_block().tokens.is_empty()); assert_eq!(
2773 seq4.current_block().parent_sequence_hash,
2774 Some(SEQ_HASH_1_4)
2775 );
2776 assert_eq!(seq4.blocks()[0].tokens().as_ref(), &[1, 2, 3, 4]);
2777
2778 let mut seq5 = create_test_sequence(initial_tokens, block_size, salt_hash);
2780 assert!(seq5.truncate(3).is_ok());
2781 assert_eq!(seq5.total_tokens(), 3);
2782 assert!(seq5.blocks().is_empty()); assert_eq!(seq5.current_block().tokens.as_ref(), &[1, 2, 3]); assert_eq!(seq5.current_block().parent_sequence_hash, None); let mut seq6 = create_test_sequence(initial_tokens, block_size, salt_hash);
2788 assert!(seq6.truncate(0).is_ok());
2789 assert_eq!(seq6.total_tokens(), 0);
2790 assert!(seq6.blocks().is_empty());
2791 assert!(seq6.current_block().tokens.is_empty());
2792 assert_eq!(seq6.current_block().parent_sequence_hash, None);
2793
2794 let mut seq7 = create_test_sequence(initial_tokens, block_size, salt_hash);
2796 let original_state = (seq7.blocks.clone(), seq7.current_block.tokens.clone()); assert!(seq7.truncate(11).is_ok()); assert_eq!(seq7.total_tokens(), 10);
2799 assert_eq!(seq7.blocks, original_state.0);
2800 assert_eq!(seq7.current_block.tokens, original_state.1);
2801
2802 let mut seq8 = create_test_sequence(initial_tokens, block_size, salt_hash);
2804 let original_state = (seq8.blocks.clone(), seq8.current_block.tokens.clone());
2805 assert!(seq8.truncate(10).is_ok());
2806 assert_eq!(seq8.total_tokens(), 10);
2807 assert_eq!(seq8.blocks, original_state.0);
2808 assert_eq!(seq8.current_block.tokens, original_state.1);
2809
2810 let mut seq9 = create_test_sequence(&[], block_size, salt_hash);
2812 assert!(seq9.truncate(0).is_ok());
2813 assert_eq!(seq9.total_tokens(), 0);
2814 assert!(seq9.blocks().is_empty());
2815 assert!(seq9.current_block().tokens.is_empty());
2816
2817 let tokens10 = &[1, 2, 3, 4, 5, 6, 7, 8]; let mut seq10 = create_test_sequence(tokens10, block_size, salt_hash);
2820 assert_eq!(seq10.total_tokens(), 8);
2821 assert!(seq10.current_block().is_empty());
2822 assert!(seq10.truncate(4).is_ok()); assert_eq!(seq10.total_tokens(), 4);
2824 assert_eq!(seq10.blocks().len(), 1);
2825 assert!(seq10.current_block().tokens.is_empty());
2826 assert_eq!(
2827 seq10.current_block().parent_sequence_hash,
2828 Some(SEQ_HASH_1_4)
2829 );
2830
2831 let tokens11 = &[1, 2, 3, 4, 5, 6, 7, 8]; let mut seq11 = create_test_sequence(tokens11, block_size, salt_hash);
2834 assert!(seq11.truncate(3).is_ok()); assert_eq!(seq11.total_tokens(), 3);
2836 assert!(seq11.blocks().is_empty());
2837 assert_eq!(seq11.current_block().tokens.as_ref(), &[1, 2, 3]); assert_eq!(seq11.current_block().parent_sequence_hash, None);
2839 }
2840
2841 #[test]
2842 fn test_unwind() {
2843 let block_size = 4;
2844 let salt_hash = Some(TEST_SALT_HASH);
2845 let initial_tokens = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let mut seq = create_test_sequence(initial_tokens, block_size, salt_hash);
2849 assert!(seq.unwind(0).is_ok());
2850 assert_eq!(seq.total_tokens(), 10);
2851
2852 let mut seq = create_test_sequence(initial_tokens, block_size, salt_hash);
2854 assert!(seq.unwind(1).is_ok());
2855 assert_eq!(seq.total_tokens(), 9);
2856 assert_eq!(seq.current_block.tokens.as_ref(), &[9]);
2857
2858 let mut seq = create_test_sequence(initial_tokens, block_size, salt_hash);
2860 assert!(seq.unwind(3).is_ok());
2861 assert_eq!(seq.total_tokens(), 7);
2862 assert_eq!(seq.blocks.len(), 1);
2863 assert_eq!(seq.current_block.tokens.as_ref(), &[5, 6, 7]);
2864
2865 let mut seq = create_test_sequence(initial_tokens, block_size, salt_hash);
2867 assert!(seq.unwind(10).is_ok());
2868 assert_eq!(seq.total_tokens(), 0);
2869 assert!(seq.blocks.is_empty());
2870 assert!(seq.current_block.is_empty());
2871
2872 let mut seq = create_test_sequence(initial_tokens, block_size, salt_hash);
2874 assert_eq!(seq.unwind(11), Err(TokenBlockError::InsufficientTokens));
2875 assert_eq!(seq.total_tokens(), 10); let mut seq_empty = create_test_sequence(&[], block_size, salt_hash);
2879 assert_eq!(
2880 seq_empty.unwind(1),
2881 Err(TokenBlockError::InsufficientTokens)
2882 );
2883 }
2884
2885 #[test]
2886 fn test_pop() {
2887 let block_size = 4;
2888 let salt_hash = Some(TEST_SALT_HASH);
2889 let initial_tokens = &[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; let mut seq = create_test_sequence(initial_tokens, block_size, salt_hash);
2892
2893 assert_eq!(seq.pop(), Some(10));
2895 assert_eq!(seq.total_tokens(), 9);
2896 assert_eq!(seq.current_block.tokens.as_ref(), &[9]);
2897 assert_eq!(seq.blocks.len(), 2);
2898
2899 assert_eq!(seq.pop(), Some(9));
2901 assert_eq!(seq.total_tokens(), 8);
2902 assert!(seq.current_block.is_empty());
2903 assert_eq!(seq.blocks.len(), 2);
2904 assert_eq!(seq.current_block.parent_sequence_hash, Some(SEQ_HASH_5_8));
2905
2906 assert_eq!(seq.pop(), Some(8));
2908 assert_eq!(seq.total_tokens(), 7);
2909 assert_eq!(seq.current_block.tokens.as_ref(), &[5, 6, 7]);
2910 assert_eq!(seq.blocks.len(), 1);
2911 assert_eq!(seq.current_block.parent_sequence_hash, Some(SEQ_HASH_1_4));
2912
2913 assert_eq!(seq.pop(), Some(7));
2915 assert_eq!(seq.pop(), Some(6));
2916 assert_eq!(seq.pop(), Some(5));
2917 assert_eq!(seq.total_tokens(), 4);
2918 assert!(seq.current_block.is_empty());
2919 assert_eq!(seq.blocks.len(), 1);
2920 assert_eq!(seq.current_block.parent_sequence_hash, Some(SEQ_HASH_1_4));
2921
2922 assert_eq!(seq.pop(), Some(4));
2924 assert_eq!(seq.total_tokens(), 3);
2925 assert_eq!(seq.current_block.tokens.as_ref(), &[1, 2, 3]);
2926 assert!(seq.blocks.is_empty());
2927 assert_eq!(seq.current_block.parent_sequence_hash, None);
2928
2929 assert_eq!(seq.pop(), Some(3));
2931 assert_eq!(seq.pop(), Some(2));
2932 assert_eq!(seq.pop(), Some(1));
2933 assert_eq!(seq.total_tokens(), 0);
2934 assert!(seq.current_block.is_empty());
2935 assert!(seq.blocks.is_empty());
2936
2937 assert_eq!(seq.pop(), None);
2939 assert_eq!(seq.total_tokens(), 0);
2940 }
2941
2942 #[test]
2943 fn test_total_tokens() {
2944 let block_size = 3;
2945 let salt_hash = Some(TEST_SALT_HASH);
2946
2947 let mut seq = create_test_sequence(&[], block_size, salt_hash);
2948 assert_eq!(seq.total_tokens(), 0);
2949
2950 seq.extend(Tokens::from(vec![1, 2])).unwrap();
2951 assert_eq!(seq.total_tokens(), 2);
2952
2953 seq.append(3).unwrap(); assert_eq!(seq.total_tokens(), 3);
2955
2956 seq.extend(Tokens::from(vec![4, 5, 6, 7])).unwrap(); assert_eq!(seq.total_tokens(), 7);
2958
2959 seq.pop().unwrap(); assert_eq!(seq.total_tokens(), 6);
2961
2962 seq.truncate(4).unwrap(); assert_eq!(seq.total_tokens(), 4);
2964
2965 seq.unwind(2).unwrap(); assert_eq!(seq.total_tokens(), 2);
2967 }
2968
2969 #[test]
2970 fn test_push_tokens_partial_block() {
2971 let mut partial = PartialTokenBlock::create_sequence_root(4, 1337);
2972
2973 let tokens = Tokens(vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10]);
2974
2975 let remaining = partial.push_tokens(tokens);
2976 assert_eq!(partial.tokens.len(), 4);
2977 assert_eq!(remaining.len(), 6);
2978 }
2979
2980 #[test]
2985 fn test_positional_radix_tree_basic_operations() {
2986 use crate::PositionalRadixTree;
2987
2988 let tree: PositionalRadixTree<String> = PositionalRadixTree::new();
2990 assert!(tree.is_empty());
2991 assert_eq!(tree.len(), 0);
2992
2993 let tree2: PositionalRadixTree<i32> = PositionalRadixTree::default();
2995 assert!(tree2.is_empty());
2996
2997 let psh1 = PositionalSequenceHash::new(0x1234, 0, 0xABCD);
2999 let psh2 = PositionalSequenceHash::new(0x5678, 0, 0xEF01);
3000 let psh3 = PositionalSequenceHash::new(0x9ABC, 1, 0x2345);
3001
3002 tree.prefix(&psh1).insert(psh1, "value1".to_string());
3003 assert!(!tree.is_empty());
3004 assert_eq!(tree.len(), 1);
3005
3006 tree.prefix(&psh2).insert(psh2, "value2".to_string());
3007 assert_eq!(tree.len(), 2);
3008
3009 tree.prefix(&psh3).insert(psh3, "value3".to_string());
3010 assert_eq!(tree.len(), 3);
3011
3012 assert_eq!(
3014 tree.prefix(&psh1).get(&psh1).cloned(),
3015 Some("value1".to_string())
3016 );
3017 }
3018
3019 #[test]
3020 fn test_positional_radix_tree_with_lineage_hash() {
3021 use crate::PositionalRadixTree;
3022
3023 let tree: PositionalRadixTree<u32, PositionalLineageHash> = PositionalRadixTree::new();
3025 assert!(tree.is_empty());
3026
3027 let plh1 = PositionalLineageHash::new(0x1234, None, 0);
3028 let plh2 = PositionalLineageHash::new(0x5678, Some(0x1234), 1);
3029
3030 tree.prefix(&plh1).insert(plh1, 100);
3031 tree.prefix(&plh2).insert(plh2, 200);
3032
3033 assert_eq!(tree.len(), 2);
3034 assert_eq!(tree.prefix(&plh1).get(&plh1).copied(), Some(100));
3035 assert_eq!(tree.prefix(&plh2).get(&plh2).copied(), Some(200));
3036 }
3037
3038 #[test]
3039 fn test_positional_radix_tree_position_lookup() {
3040 use crate::PositionalRadixTree;
3041
3042 let tree: PositionalRadixTree<String> = PositionalRadixTree::new();
3043
3044 let psh0 = PositionalSequenceHash::new(0x1111, 0, 0xAAAA);
3046 let psh1 = PositionalSequenceHash::new(0x2222, 1, 0xBBBB);
3047 let psh2 = PositionalSequenceHash::new(0x3333, 2, 0xCCCC);
3048
3049 tree.prefix(&psh0).insert(psh0, "pos0".to_string());
3050 tree.prefix(&psh1).insert(psh1, "pos1".to_string());
3051 tree.prefix(&psh2).insert(psh2, "pos2".to_string());
3052
3053 assert!(tree.position(0).is_some());
3055 assert!(tree.position(1).is_some());
3056 assert!(tree.position(2).is_some());
3057 assert!(tree.position(3).is_none()); let pos0_map = tree.position(0).unwrap();
3061 assert_eq!(pos0_map.len(), 1);
3062 }
3063
3064 #[test]
3065 fn test_positional_radix_tree_concurrent_same_position() {
3066 use crate::PositionalRadixTree;
3067 use std::sync::Arc;
3068
3069 let tree = Arc::new(PositionalRadixTree::new());
3070 let threads: Vec<_> = (0..8_u64)
3071 .map(|value| {
3072 let tree = Arc::clone(&tree);
3073 std::thread::spawn(move || {
3074 let key = PositionalSequenceHash::new(value, 7, value);
3075 tree.prefix(&key).insert(key, value);
3076 })
3077 })
3078 .collect();
3079
3080 for thread in threads {
3081 thread.join().unwrap();
3082 }
3083
3084 assert_eq!(tree.len(), 8);
3085 assert_eq!(tree.position(7).unwrap().len(), 8);
3086 }
3087
3088 #[test]
3091 fn test_positional_sequence_hash_mode_2_and_3() {
3092 let position_mode2 = 100_000u64;
3094 let seq_hash = 0x1234567890ABCDEF;
3095 let block_hash = 0xFEDCBA9876543210;
3096
3097 let psh_mode2 = PositionalSequenceHash::new(seq_hash, position_mode2, block_hash);
3098 assert_eq!(psh_mode2.mode(), 2, "Position 100,000 should use mode 2");
3099 assert_eq!(psh_mode2.position(), position_mode2);
3100 assert_eq!(psh_mode2.sequence_hash(), seq_hash);
3101 assert_eq!(
3103 psh_mode2.local_block_hash(),
3104 block_hash & ((1u64 << 38) - 1)
3105 );
3106
3107 let position_mode3 = 100_000_000u64;
3109 let psh_mode3 = PositionalSequenceHash::new(seq_hash, position_mode3, block_hash);
3110 assert_eq!(
3111 psh_mode3.mode(),
3112 3,
3113 "Position 100,000,000 should use mode 3"
3114 );
3115 assert_eq!(psh_mode3.position(), position_mode3);
3116 assert_eq!(psh_mode3.sequence_hash(), seq_hash);
3117 assert_eq!(
3119 psh_mode3.local_block_hash(),
3120 block_hash & ((1u64 << 31) - 1)
3121 );
3122 }
3123
3124 #[test]
3125 fn test_positional_sequence_hash_as_u128() {
3126 let psh = PositionalSequenceHash::new(0x1234, 100, 0xABCD);
3127 let raw = psh.as_u128();
3128
3129 assert_eq!(raw & 0xFFFF_FFFF_FFFF_FFFF, 0x1234);
3131 assert!(raw > 0); let psh2 = PositionalSequenceHash::new(0x1234, 100, 0xABCD);
3135 assert_eq!(psh.as_u128(), psh2.as_u128());
3136 }
3137
3138 #[test]
3139 fn test_positional_sequence_hash_debug() {
3140 let psh = PositionalSequenceHash::new(0x1234567890ABCDEF, 42, 0xFEDCBA98);
3141 let debug_str = format!("{:?}", psh);
3142
3143 assert!(debug_str.contains("PositionalSequenceHash"));
3145 assert!(debug_str.contains("sequence_hash"));
3146 assert!(debug_str.contains("local_block_hash"));
3147 assert!(debug_str.contains("position"));
3148 }
3149
3150 #[test]
3153 fn test_positional_lineage_hash_debug_and_display() {
3154 let plh_root = PositionalLineageHash::new(0x123456789ABCDEF0, None, 0);
3156 let debug_root = format!("{:?}", plh_root);
3157 let display_root = format!("{}", plh_root);
3158
3159 assert!(debug_root.starts_with("0:"));
3161 assert!(display_root.starts_with("0:"));
3162 assert_eq!(debug_root.matches(':').count(), 1);
3164 assert_eq!(display_root.matches(':').count(), 1);
3165
3166 let plh_child = PositionalLineageHash::new(0xABCDEF0123456789, Some(0x123456789ABCDEF0), 5);
3168 let debug_child = format!("{:?}", plh_child);
3169 let display_child = format!("{}", plh_child);
3170
3171 assert!(debug_child.starts_with("5:"));
3173 assert!(display_child.starts_with("5:"));
3174 assert_eq!(debug_child.matches(':').count(), 2);
3176 assert_eq!(display_child.matches(':').count(), 2);
3177 }
3178
3179 #[test]
3180 fn test_positional_lineage_hash_as_u128() {
3181 let plh = PositionalLineageHash::new(0x1234, Some(0x5678), 10);
3182 let raw = plh.as_u128();
3183
3184 assert!(raw > 0);
3185
3186 let plh2 = PositionalLineageHash::new(0x1234, Some(0x5678), 10);
3188 assert_eq!(plh.as_u128(), plh2.as_u128());
3189
3190 let plh3 = PositionalLineageHash::new(0x1234, Some(0x5678), 11);
3192 assert_ne!(plh.as_u128(), plh3.as_u128());
3193 }
3194
3195 #[test]
3196 fn test_positional_lineage_hash_ord_by_position_then_current_fragment() {
3197 let at_5_low = PositionalLineageHash::new(0x10, Some(0x1111), 5);
3198 let at_5_high = PositionalLineageHash::new(0x20, Some(0x1111), 5);
3199 assert!(
3200 at_5_low.current_sequence_hash() < at_5_high.current_sequence_hash(),
3201 "test assumes distinct current sequence hashes at the same position"
3202 );
3203 assert!(at_5_low < at_5_high);
3204 assert!(at_5_high > at_5_low);
3205
3206 let at_3 = PositionalLineageHash::new(0x99, Some(0x2222), 3);
3207 assert!(at_3 < at_5_low);
3208 assert!(at_5_high < PositionalLineageHash::new(0x01, Some(0x3333), 6));
3209 }
3210
3211 #[test]
3212 fn test_positional_lineage_hash_ord_tiebreak_parent_via_packed_u128() {
3213 let same_pos_same_current = PositionalLineageHash::new(0x1234, Some(0x100), 10);
3214 let same_pos_same_current_other_parent =
3215 PositionalLineageHash::new(0x1234, Some(0x200), 10);
3216 assert_eq!(same_pos_same_current.position(), 10);
3217 assert_eq!(
3218 same_pos_same_current.position(),
3219 same_pos_same_current_other_parent.position()
3220 );
3221 assert_eq!(
3222 same_pos_same_current.current_sequence_hash(),
3223 same_pos_same_current_other_parent.current_sequence_hash()
3224 );
3225 assert_ne!(same_pos_same_current, same_pos_same_current_other_parent);
3226 assert_ne!(
3227 same_pos_same_current.cmp(&same_pos_same_current_other_parent),
3228 std::cmp::Ordering::Equal
3229 );
3230 }
3231
3232 #[test]
3233 fn test_positional_lineage_hash_vec_sort_matches_ord() {
3234 let a = PositionalLineageHash::new(0x30, None, 0);
3235 let b = PositionalLineageHash::new(0x10, Some(0x30), 2);
3236 let c = PositionalLineageHash::new(0x20, Some(0x30), 2);
3237 let mut v = vec![b, a, c];
3238 v.sort();
3239 assert_eq!(v, vec![a, b, c]);
3240 }
3241
3242 #[test]
3243 fn test_positional_lineage_hash_itertools_sorted() {
3244 use itertools::Itertools;
3245
3246 let a = PositionalLineageHash::new(0x30, None, 0);
3247 let b = PositionalLineageHash::new(0x10, Some(0x30), 2);
3248 let c = PositionalLineageHash::new(0x20, Some(0x30), 2);
3249 let sorted: Vec<_> = vec![b, a, c].into_iter().sorted().collect();
3250 assert_eq!(sorted, vec![a, b, c]);
3251 }
3252
3253 #[test]
3256 fn test_tokens_from_vec_usize() {
3257 let usize_vec: Vec<usize> = vec![1, 2, 3, 4, 5];
3258 let tokens = Tokens::from(usize_vec);
3259
3260 assert_eq!(tokens.as_ref(), &[1u32, 2, 3, 4, 5]);
3261 assert_eq!(tokens.len(), 5);
3262 }
3263
3264 #[test]
3265 fn test_tokens_partial_eq_slice_ref() {
3266 let tokens = Tokens::from(vec![1u32, 2, 3, 4]);
3267 let slice: &[Token] = &[1, 2, 3, 4];
3268
3269 assert!(tokens == slice);
3271
3272 let different_slice: &[Token] = &[1, 2, 3, 5];
3273 assert!(tokens != different_slice);
3274 }
3275
3276 #[test]
3279 fn test_token_block_accessors() {
3280 let tokens = Tokens::from(vec![1u32, 2, 3, 4]);
3281 let seq = TokenBlockSequence::new(tokens, 4, Some(1337));
3282
3283 let block = &seq.blocks()[0];
3284
3285 assert_eq!(block.block_size(), 4);
3287
3288 let psh = block.positional_sequence_hash();
3290 assert_eq!(psh.position(), 0);
3291
3292 let plh = block.positional_lineage_hash();
3294 assert_eq!(plh.position(), 0);
3295 assert_eq!(plh.parent_hash_fragment(), 0); }
3297
3298 #[test]
3299 fn test_positional_hash_trait_impls() {
3300 use crate::PositionalHash;
3301
3302 let psh = PositionalSequenceHash::new(0x1234, 42, 0xABCD);
3304 assert_eq!(PositionalHash::position(&psh), 42);
3305
3306 let plh = PositionalLineageHash::new(0x1234, None, 99);
3308 assert_eq!(PositionalHash::position(&plh), 99);
3309 }
3310
3311 #[test]
3314 fn test_sequence_pop_from_full_block() {
3315 let tokens = Tokens::from(vec![1u32, 2, 3, 4, 5, 6, 7, 8]);
3317 let mut seq = TokenBlockSequence::new(tokens, 4, Some(TEST_SALT_HASH));
3318
3319 assert!(seq.current_block().is_empty());
3321 assert_eq!(seq.blocks().len(), 2);
3322 assert_eq!(seq.total_tokens(), 8);
3323
3324 let popped = seq.pop();
3326 assert_eq!(popped, Some(8));
3327 assert_eq!(seq.total_tokens(), 7);
3328 assert_eq!(seq.blocks().len(), 1);
3329 assert_eq!(seq.current_block().tokens.as_ref(), &[5, 6, 7]);
3330 }
3331
3332 #[test]
3333 #[allow(clippy::reversed_empty_ranges)] fn test_sequence_tokens_at_edge_cases() {
3335 let tokens = Tokens::from(vec![1u32, 2, 3, 4, 5]);
3336 let seq = TokenBlockSequence::new(tokens, 4, Some(TEST_SALT_HASH));
3337
3338 assert!(seq.tokens_at(3..2).is_empty());
3340
3341 assert!(seq.tokens_at(0..10).is_empty());
3343
3344 assert_eq!(seq.tokens_at(0..4).as_ref(), &[1, 2, 3, 4]);
3346 assert_eq!(seq.tokens_at(4..5).as_ref(), &[5]);
3347 }
3348
3349 #[test]
3350 fn test_sequence_next_block() {
3351 let tokens = Tokens::from(vec![1u32, 2, 3, 4]);
3352 let seq = TokenBlockSequence::new(tokens, 4, Some(1337));
3353
3354 let block = &seq.blocks()[0];
3355 let next_partial = block.next_block();
3356
3357 assert!(next_partial.is_empty());
3359 assert_eq!(next_partial.remaining(), 4);
3360 assert_eq!(
3361 next_partial.parent_sequence_hash,
3362 Some(block.sequence_hash())
3363 );
3364 assert_eq!(next_partial.position, 1);
3365 }
3366
3367 #[test]
3368 fn test_sequence_reset() {
3369 let tokens = Tokens::from(vec![1u32, 2, 3, 4, 5, 6, 7, 8, 9]);
3370 let mut seq = TokenBlockSequence::new(tokens, 4, Some(1337));
3371
3372 assert_eq!(seq.blocks().len(), 2);
3373 assert_eq!(seq.total_tokens(), 9);
3374
3375 seq.reset();
3376
3377 assert!(seq.blocks().is_empty());
3378 assert!(seq.current_block().is_empty());
3379 assert_eq!(seq.total_tokens(), 0);
3380 assert_eq!(seq.current_block().parent_sequence_hash, None);
3381 }
3382
3383 #[test]
3384 fn test_sequence_into_parts() {
3385 let tokens = Tokens::from(vec![1u32, 2, 3, 4, 5]);
3386 let seq = TokenBlockSequence::new(tokens, 4, Some(1337));
3387
3388 let (blocks, partial) = seq.into_parts();
3389
3390 assert_eq!(blocks.len(), 1);
3391 assert_eq!(partial.tokens.as_ref(), &[5]);
3392 }
3393
3394 #[test]
3395 fn test_sequence_last_complete_block() {
3396 let seq_empty = TokenBlockSequence::new(Tokens::default(), 4, None);
3398 assert!(seq_empty.last_complete_block().is_none());
3399
3400 let tokens = Tokens::from(vec![1u32, 2, 3, 4, 5, 6, 7, 8]);
3402 let seq = TokenBlockSequence::new(tokens, 4, Some(1337));
3403 let last = seq.last_complete_block();
3404 assert!(last.is_some());
3405 assert_eq!(last.unwrap().tokens().as_ref(), &[5, 6, 7, 8]);
3406 }
3407
3408 #[test]
3409 fn test_positional_hashes_msgpack_roundtrip() {
3410 let psh = PositionalSequenceHash::new(0xDEAD_BEEF_CAFE_BABE, 12345, 0x0123_4567_89AB_CDEF);
3411 let bytes = rmp_serde::to_vec(&psh).expect("psh serialize");
3412 let decoded: PositionalSequenceHash =
3413 rmp_serde::from_slice(&bytes).expect("psh deserialize");
3414 assert_eq!(psh, decoded);
3415 assert_eq!(psh.as_u128(), decoded.as_u128());
3416
3417 let plh =
3418 PositionalLineageHash::new(0x1111_2222_3333_4444, Some(0x5555_6666_7777_8888), 256);
3419 let bytes = rmp_serde::to_vec(&plh).expect("plh serialize");
3420 let decoded: PositionalLineageHash =
3421 rmp_serde::from_slice(&bytes).expect("plh deserialize");
3422 assert_eq!(plh, decoded);
3423 assert_eq!(plh.as_u128(), decoded.as_u128());
3424
3425 let vec = vec![psh, PositionalSequenceHash::default(), psh];
3427 let bytes = rmp_serde::to_vec(&vec).expect("vec serialize");
3428 let decoded: Vec<PositionalSequenceHash> =
3429 rmp_serde::from_slice(&bytes).expect("vec deserialize");
3430 assert_eq!(vec, decoded);
3431 }
3432
3433 #[test]
3434 fn test_positional_hashes_json_roundtrip() {
3435 let psh = PositionalSequenceHash::new(0xAAAA_BBBB_CCCC_DDDD, 7, 0xEEEE_FFFF_0000_1111);
3437 let json = serde_json::to_string(&psh).expect("psh json serialize");
3438 let decoded: PositionalSequenceHash =
3439 serde_json::from_str(&json).expect("psh json deserialize");
3440 assert_eq!(psh, decoded);
3441
3442 let plh = PositionalLineageHash::new(0x1234_5678, Some(0xABCD_EF01), 42);
3443 let json = serde_json::to_string(&plh).expect("plh json serialize");
3444 let decoded: PositionalLineageHash =
3445 serde_json::from_str(&json).expect("plh json deserialize");
3446 assert_eq!(plh, decoded);
3447 }
3448
3449 #[test]
3455 fn tokens_mm_zero_mm_equivalence() {
3456 let tokens = Tokens::from(vec![1u32, 2, 3, 4, 5, 6, 7, 8, 9]);
3457 let baseline = TokenBlockSequence::new(tokens.clone(), 4, Some(TEST_SALT_HASH));
3458 let mm = TokenBlockSequence::new_with_mm(tokens, &[], 4, Some(TEST_SALT_HASH))
3459 .expect("validation should pass for empty mm_info");
3460
3461 assert_eq!(mm.blocks().len(), baseline.blocks().len());
3462 for (a, b) in mm.blocks().iter().zip(baseline.blocks().iter()) {
3463 assert_eq!(a.salt_hash(), b.salt_hash());
3464 assert_eq!(a.block_hash(), b.block_hash());
3465 assert_eq!(a.sequence_hash(), b.sequence_hash());
3466 assert_eq!(a.parent_sequence_hash(), b.parent_sequence_hash());
3467 assert_eq!(a.positional_lineage_hash(), b.positional_lineage_hash());
3468 }
3469 assert!(mm.mm_runs().is_empty());
3470 }
3471
3472 #[test]
3475 fn tokens_mm_byte_layout() {
3476 let tokens = Tokens::from(vec![100u32, 101, 102, 103, 0, 0, 106, 107]);
3480 let mm = vec![TokenBlockMmInfo {
3481 mm_hash: 0xAAu64,
3482 offset: 4,
3483 length: 2,
3484 }];
3485 let salt = TEST_SALT_HASH;
3486
3487 let mut expected = Vec::new();
3489 for &t in &[100u32, 101, 102, 103] {
3490 expected.push(MM_SLOT_TAG_TOKEN);
3491 expected.extend_from_slice(&t.to_le_bytes());
3492 expected.extend_from_slice(&0u64.to_le_bytes());
3493 }
3494 for run_off in 0u32..2 {
3495 expected.push(MM_SLOT_TAG_PLACEHOLDER);
3496 expected.extend_from_slice(&run_off.to_le_bytes());
3497 expected.extend_from_slice(&0xAAu64.to_le_bytes());
3498 }
3499 for &t in &[106u32, 107] {
3500 expected.push(MM_SLOT_TAG_TOKEN);
3501 expected.extend_from_slice(&t.to_le_bytes());
3502 expected.extend_from_slice(&0u64.to_le_bytes());
3503 }
3504 assert_eq!(expected.len(), 8 * 13);
3505
3506 let helper_bytes = compute_block_bytes_with_mm(&tokens, 0, &mm);
3508 assert_eq!(helper_bytes, expected, "MM-aware byte buffer mismatch");
3509
3510 let expected_block_hash = compute_block_hash(&expected, salt);
3512 let seq = TokenBlockSequence::new_with_mm(tokens, &mm, 8, Some(salt)).unwrap();
3513 assert_eq!(seq.blocks().len(), 1);
3514 assert_eq!(seq.blocks()[0].block_hash(), expected_block_hash);
3515 }
3516
3517 #[test]
3522 fn tokens_mm_no_position_collision() {
3523 let salt = TEST_SALT_HASH;
3524 let tokens_a = Tokens::from(vec![0u32, 0xAB]);
3526 let mm_a = vec![TokenBlockMmInfo {
3527 mm_hash: 0x1122_3344_5566_7788,
3528 offset: 0,
3529 length: 1,
3530 }];
3531 let tokens_b = Tokens::from(vec![0xAB, 0u32]);
3533 let mm_b = vec![TokenBlockMmInfo {
3534 mm_hash: 0x1122_3344_5566_7788,
3535 offset: 1,
3536 length: 1,
3537 }];
3538
3539 let bytes_a = compute_block_bytes_with_mm(&tokens_a, 0, &mm_a);
3540 let bytes_b = compute_block_bytes_with_mm(&tokens_b, 0, &mm_b);
3541 assert_ne!(
3542 bytes_a, bytes_b,
3543 "tagged framing must distinguish slot kinds at different positions"
3544 );
3545
3546 let seq_a = TokenBlockSequence::new_with_mm(tokens_a, &mm_a, 2, Some(salt)).unwrap();
3547 let seq_b = TokenBlockSequence::new_with_mm(tokens_b, &mm_b, 2, Some(salt)).unwrap();
3548 assert_ne!(
3549 seq_a.blocks()[0].block_hash(),
3550 seq_b.blocks()[0].block_hash()
3551 );
3552 }
3553
3554 #[test]
3558 fn tokens_mm_legacy_fallback_per_block() {
3559 let block_size: u32 = 4;
3560 let salt = Some(TEST_SALT_HASH);
3561 let raw = vec![1u32, 2, 3, 4, 5, 6, 7, 8];
3562 let mm = vec![TokenBlockMmInfo {
3564 mm_hash: 0xAB,
3565 offset: 4,
3566 length: 3,
3567 }];
3568 let seq_mm =
3569 TokenBlockSequence::new_with_mm(Tokens::from(raw.clone()), &mm, block_size, salt)
3570 .unwrap();
3571 let seq_plain = TokenBlockSequence::new(Tokens::from(raw), block_size, salt);
3572
3573 assert_eq!(
3575 seq_mm.blocks()[0].block_hash(),
3576 seq_plain.blocks()[0].block_hash()
3577 );
3578 assert_eq!(
3579 seq_mm.blocks()[0].sequence_hash(),
3580 seq_plain.blocks()[0].sequence_hash()
3581 );
3582 assert_ne!(
3584 seq_mm.blocks()[1].block_hash(),
3585 seq_plain.blocks()[1].block_hash()
3586 );
3587 }
3588
3589 #[test]
3592 fn hash_complete_blocks_matches_sequence_around_mm_run() {
3593 let block_size: u32 = 4;
3594 let salt = TEST_SALT_HASH;
3595 let raw = vec![1u32, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
3597 let mm = vec![TokenBlockMmInfo {
3598 mm_hash: 0xAB,
3599 offset: 4,
3600 length: 4,
3601 }];
3602
3603 let empty = hash_complete_blocks(&raw, &[], block_size, salt);
3604 let plain = TokenBlockSequence::new(Tokens::from(raw.clone()), block_size, Some(salt));
3605 assert_eq!(empty.len(), plain.blocks().len());
3606 assert_eq!(empty.len(), 3);
3607 for (lineage, block) in empty.iter().zip(plain.blocks().iter()) {
3608 assert_eq!(lineage.block_hash, block.block_hash());
3609 assert_eq!(lineage.sequence_hash, block.sequence_hash());
3610 assert_eq!(lineage.parent_sequence_hash, block.parent_sequence_hash());
3611 assert_eq!(
3612 lineage.positional_lineage_hash,
3613 block.positional_lineage_hash()
3614 );
3615 }
3616
3617 let lineages = hash_complete_blocks(&raw, &mm, block_size, salt);
3618 let seq_mm =
3619 TokenBlockSequence::new_with_mm(Tokens::from(raw.clone()), &mm, block_size, Some(salt))
3620 .unwrap();
3621 for (lineage, block) in lineages.iter().zip(seq_mm.blocks().iter()) {
3622 assert_eq!(lineage.block_hash, block.block_hash());
3623 assert_eq!(lineage.sequence_hash, block.sequence_hash());
3624 assert_eq!(lineage.parent_sequence_hash, block.parent_sequence_hash());
3625 assert_eq!(
3626 lineage.positional_lineage_hash,
3627 block.positional_lineage_hash()
3628 );
3629 }
3630
3631 assert_eq!(
3633 lineages[0].block_hash,
3634 compute_block_hash_for_tokens(&raw[0..4], salt)
3635 );
3636 assert_eq!(
3637 lineages[2].block_hash,
3638 compute_block_hash_for_tokens(&raw[8..12], salt)
3639 );
3640 let mm_bytes = compute_block_bytes_with_mm(&raw[4..8], 4, &mm);
3641 assert_eq!(lineages[1].block_hash, compute_block_hash(&mm_bytes, salt));
3642 assert_ne!(lineages[2].sequence_hash, plain.blocks()[2].sequence_hash());
3644 }
3645
3646 #[test]
3653 fn hash_complete_blocks_cursor_gate_boundaries() {
3654 let block_size: u32 = 4;
3655 let salt = TEST_SALT_HASH;
3656 let bs = block_size as usize;
3657 let tokens: Vec<Token> = (0..24).collect();
3659
3660 let verify_cases = |mm_runs: &[TokenBlockMmInfo]| {
3661 let lineages = hash_complete_blocks(&tokens, mm_runs, block_size, salt);
3662 let n_complete = tokens.len() / bs;
3663 assert_eq!(lineages.len(), n_complete);
3664
3665 for (position, lineage) in lineages.iter().enumerate() {
3666 let block_offset = position * bs;
3667 let block_tokens = &tokens[block_offset..block_offset + bs];
3668 let expected_bytes =
3669 compute_block_bytes_with_mm(block_tokens, block_offset, mm_runs);
3670 let expected_hash = compute_block_hash(&expected_bytes, salt);
3671 assert_eq!(
3672 lineage.block_hash,
3673 expected_hash,
3674 "Cursor gate block hash mismatch at block position {position} [offset {block_offset}..{}) run layout: {:?}",
3675 block_offset + bs,
3676 mm_runs
3677 );
3678 }
3679 };
3680
3681 verify_cases(&[TokenBlockMmInfo {
3683 mm_hash: 0x0A,
3684 offset: 1,
3685 length: 4,
3686 }]);
3687
3688 verify_cases(&[TokenBlockMmInfo {
3690 mm_hash: 0x0B,
3691 offset: 7,
3692 length: 3,
3693 }]);
3694
3695 verify_cases(&[TokenBlockMmInfo {
3697 mm_hash: 0x0C,
3698 offset: 4,
3699 length: 4,
3700 }]);
3701
3702 verify_cases(&[
3704 TokenBlockMmInfo {
3705 mm_hash: 0x0D1,
3706 offset: 4,
3707 length: 4,
3708 },
3709 TokenBlockMmInfo {
3710 mm_hash: 0x0D2,
3711 offset: 8,
3712 length: 4,
3713 },
3714 ]);
3715 }
3716
3717 #[test]
3720 fn tokens_mm_validation_overflow() {
3721 let bad = vec![TokenBlockMmInfo {
3722 mm_hash: 1,
3723 offset: usize::MAX - 2,
3724 length: 10,
3725 }];
3726 let err = validate_and_sort_mm_info(&bad, usize::MAX).expect_err("must reject overflow");
3727 assert!(matches!(err, MmInfoError::OffsetOverflow { .. }));
3728 }
3729
3730 #[test]
3733 fn tokens_mm_streaming_equals_batch() {
3734 let tokens = Tokens::from(vec![1u32, 2, 3, 0, 0, 0, 0, 6, 7]);
3736 let mm = vec![TokenBlockMmInfo {
3737 mm_hash: 0xAAu64,
3738 offset: 3,
3739 length: 4,
3740 }];
3741 let salt = Some(TEST_SALT_HASH);
3742 let batch = TokenBlockSequence::new_with_mm(tokens, &mm, 4, salt).unwrap();
3743
3744 let mut streamed = TokenBlockSequence::new(Tokens::default(), 4, salt);
3745 streamed.push_token(1).unwrap();
3746 streamed.push_token(2).unwrap();
3747 streamed.push_token(3).unwrap();
3748 streamed.push_mm_run(0xAAu64, 4).unwrap();
3749 streamed.push_token(6).unwrap();
3750 streamed.push_token(7).unwrap();
3751
3752 assert_eq!(streamed.blocks().len(), batch.blocks().len());
3753 for (a, b) in streamed.blocks().iter().zip(batch.blocks().iter()) {
3754 assert_eq!(a.block_hash(), b.block_hash(), "block_hash mismatch");
3755 assert_eq!(a.sequence_hash(), b.sequence_hash(), "seq_hash mismatch");
3756 assert_eq!(
3757 a.positional_lineage_hash(),
3758 b.positional_lineage_hash(),
3759 "PLH mismatch"
3760 );
3761 }
3762 assert_eq!(streamed.mm_runs(), batch.mm_runs());
3763 }
3764
3765 #[test]
3769 fn tokens_mm_multi_block_run() {
3770 let block_size: u32 = 8;
3771 let bs = block_size as usize;
3772 let mut tokens_a: Vec<Token> = vec![0u32; 2 * bs]; tokens_a.extend_from_slice(&[0u32, 0, 0, 0, 100, 101, 102, 103]); let tokens_a = Tokens::from(tokens_a);
3777 let mm = vec![TokenBlockMmInfo {
3778 mm_hash: 0xCAFEBABEu64,
3779 offset: 0,
3780 length: 20,
3781 }];
3782 let seq_a = TokenBlockSequence::new_with_mm(
3783 tokens_a.clone(),
3784 &mm,
3785 block_size,
3786 Some(TEST_SALT_HASH),
3787 )
3788 .unwrap();
3789 assert_eq!(seq_a.blocks().len(), 3);
3790
3791 let bh0 = seq_a.blocks()[0].block_hash();
3794 let bh1 = seq_a.blocks()[1].block_hash();
3795 assert_ne!(
3796 bh0, bh1,
3797 "fully-placeholder blocks at different run_offsets must hash differently"
3798 );
3799
3800 let seq_b =
3802 TokenBlockSequence::new_with_mm(tokens_a, &mm, block_size, Some(TEST_SALT_HASH))
3803 .unwrap();
3804 assert_eq!(
3805 seq_a.blocks()[0].block_hash(),
3806 seq_b.blocks()[0].block_hash()
3807 );
3808 assert_eq!(
3809 seq_a.blocks()[1].block_hash(),
3810 seq_b.blocks()[1].block_hash()
3811 );
3812 assert_eq!(
3813 seq_a.blocks()[2].block_hash(),
3814 seq_b.blocks()[2].block_hash()
3815 );
3816
3817 let mm_diff = vec![TokenBlockMmInfo {
3819 mm_hash: 0xDEADBEEFu64,
3820 offset: 0,
3821 length: 20,
3822 }];
3823 let mut tokens_c: Vec<Token> = vec![0u32; 2 * bs];
3824 tokens_c.extend_from_slice(&[0u32, 0, 0, 0, 100, 101, 102, 103]);
3825 let seq_c = TokenBlockSequence::new_with_mm(
3826 Tokens::from(tokens_c),
3827 &mm_diff,
3828 block_size,
3829 Some(TEST_SALT_HASH),
3830 )
3831 .unwrap();
3832 assert_ne!(
3833 seq_a.blocks()[0].block_hash(),
3834 seq_c.blocks()[0].block_hash()
3835 );
3836 }
3837
3838 #[test]
3840 fn tokens_mm_validation() {
3841 let tokens = Tokens::from(vec![0u32; 32]);
3842 let overlap = vec![
3844 TokenBlockMmInfo {
3845 mm_hash: 1,
3846 offset: 0,
3847 length: 5,
3848 },
3849 TokenBlockMmInfo {
3850 mm_hash: 2,
3851 offset: 4,
3852 length: 5,
3853 },
3854 ];
3855 let err = TokenBlockSequence::new_with_mm(tokens.clone(), &overlap, 4, None).unwrap_err();
3856 assert!(matches!(
3857 err,
3858 TokenBlockError::MmInfo(MmInfoError::Overlapping { .. })
3859 ));
3860
3861 let oob = vec![TokenBlockMmInfo {
3863 mm_hash: 1,
3864 offset: 30,
3865 length: 10,
3866 }];
3867 let err = TokenBlockSequence::new_with_mm(tokens.clone(), &oob, 4, None).unwrap_err();
3868 assert!(matches!(
3869 err,
3870 TokenBlockError::MmInfo(MmInfoError::OutOfBounds { .. })
3871 ));
3872
3873 let empty = vec![TokenBlockMmInfo {
3875 mm_hash: 1,
3876 offset: 0,
3877 length: 0,
3878 }];
3879 let err = TokenBlockSequence::new_with_mm(tokens, &empty, 4, None).unwrap_err();
3880 assert!(matches!(
3881 err,
3882 TokenBlockError::MmInfo(MmInfoError::EmptyRun)
3883 ));
3884
3885 let mut seq = TokenBlockSequence::new(Tokens::default(), 4, None);
3887 let err = seq.push_mm_run(0xAB, 0).unwrap_err();
3888 assert!(matches!(
3889 err,
3890 TokenBlockError::MmInfo(MmInfoError::EmptyRun)
3891 ));
3892
3893 let mut seq = TokenBlockSequence::new(Tokens::from(vec![1u32, 2, 3]), 4, None);
3895 seq.push_mm_run(0xAB, 2).unwrap();
3896 assert!(matches!(
3897 seq.truncate(0).unwrap_err(),
3898 TokenBlockError::MmRunsPresent
3899 ));
3900 assert!(matches!(
3901 seq.unwind(1).unwrap_err(),
3902 TokenBlockError::MmRunsPresent
3903 ));
3904 }
3905}