1- use std:: error:: Error ;
2- use std:: fmt:: Display ;
3-
41/// Ordered index for dynamic trees
52///
63/// ## Encoding
@@ -37,13 +34,13 @@ impl TreeNodeIndex {
3734 }
3835
3936 /// Append tree branch no. `branch_idx` reserving `bits` bits.
40- fn try_bits_branch ( self , branch_idx : u64 , bits : u32 ) -> Result < Self , BranchingError > {
37+ fn try_bits_branch ( self , branch_idx : u64 , bits : u32 ) -> Option < Self > {
4138 let trailing_zeros = self . 0 . trailing_zeros ( ) ;
42- let allocated_shift = trailing_zeros. checked_sub ( bits) . ok_or ( BranchingError ( ( ) ) ) ?;
39+ let allocated_shift = trailing_zeros. checked_sub ( bits) ?;
4340 // Using wrapping operations for optimization, as edge cases are unreachable:
4441 // - `trailing_zeros < 64` as we are guaranteed at least one bit is set
4542 // - `allocated_shift == trailing_zeros - bits <= trailing_zeros < 64`
46- Ok ( TreeNodeIndex (
43+ Some ( TreeNodeIndex (
4744 self . 0 & !u64:: wrapping_shl ( 1 , trailing_zeros)
4845 | u64:: wrapping_shl ( 1 , allocated_shift)
4946 | branch_idx. unbounded_shl ( allocated_shift. wrapping_add ( 1 ) ) ,
@@ -58,7 +55,9 @@ impl TreeNodeIndex {
5855 ) ;
5956 // `branch_num != 0` per debug assertion above
6057 let bits = ceil_ilog2 ( branch_num) ;
61- self . try_bits_branch ( branch_idx, bits) . unwrap ( )
58+ self . try_bits_branch ( branch_idx, bits) . expect (
59+ "TreeNodeIndex's free bits have been exhausted, make sure recursion is used carefully" ,
60+ )
6261 }
6362}
6463
@@ -69,24 +68,5 @@ fn ceil_ilog2(branch_num: u64) -> u32 {
6968 branch_num. wrapping_sub ( 1 ) . checked_ilog2 ( ) . map_or ( 0 , |b| b. wrapping_add ( 1 ) )
7069}
7170
72- /// Error for exhausting free bits
73- #[ derive( Debug ) ]
74- pub struct BranchingError ( ( ) ) ;
75-
76- impl Error for BranchingError { }
77-
78- impl Display for BranchingError {
79- fn fmt ( & self , f : & mut std:: fmt:: Formatter < ' _ > ) -> std:: fmt:: Result {
80- "TreeNodeIndex's free bits have been exhausted, make sure recursion is used carefully"
81- . fmt ( f)
82- }
83- }
84-
85- impl Default for TreeNodeIndex {
86- fn default ( ) -> Self {
87- TreeNodeIndex :: root ( )
88- }
89- }
90-
9171#[ cfg( test) ]
9272mod tests;
0 commit comments