@@ -8,7 +8,7 @@ pub struct TxnIndex(u16);
88
99impl TxnIndex {
1010 /// Convert an `<T>` to transaction index (saturate if out of range).
11- pub fn from_saturating <
11+ pub ( crate ) fn from_saturating <
1212 T : Copy
1313 + TryInto < u16 >
1414 + std:: ops:: Sub < Output = T >
@@ -21,3 +21,80 @@ impl TxnIndex {
2121 Self ( value)
2222 }
2323}
24+
25+ impl <
26+ T : Copy
27+ + TryInto < u16 >
28+ + std:: ops:: Sub < Output = T >
29+ + std:: cmp:: PartialOrd < T >
30+ + num_traits:: identities:: Zero ,
31+ > From < T > for TxnIndex
32+ {
33+ fn from ( value : T ) -> Self {
34+ TxnIndex :: from_saturating ( value)
35+ }
36+ }
37+
38+ impl From < TxnIndex > for i16 {
39+ fn from ( val : TxnIndex ) -> Self {
40+ i16:: try_from ( val. 0 ) . unwrap_or ( i16:: MAX )
41+ }
42+ }
43+
44+ #[ cfg( test) ]
45+ mod tests {
46+ use super :: * ;
47+
48+ // Test for `From<T>` conversion to `TxnIndex`
49+ #[ test]
50+ fn test_from_u8_to_txn_index ( ) {
51+ let txn_index: TxnIndex = 100u8 . into ( ) ; // u8 is a valid type for conversion
52+ assert_eq ! ( txn_index. 0 , 100 ) ;
53+ }
54+
55+ #[ test]
56+ fn test_from_u16_to_txn_index ( ) {
57+ let txn_index: TxnIndex = 500u16 . into ( ) ; // u16 is valid and within range for `TxnIndex`
58+ assert_eq ! ( txn_index. 0 , 500 ) ;
59+ }
60+
61+ #[ test]
62+ fn test_from_i32_to_txn_index ( ) {
63+ let txn_index: TxnIndex = 1234i32 . into ( ) ; // i32 can be converted into `TxnIndex`
64+ assert_eq ! ( txn_index. 0 , 1234 ) ;
65+ }
66+
67+ #[ test]
68+ fn test_from_u32_to_txn_index ( ) {
69+ let txn_index: TxnIndex = 500_000u32 . into ( ) ; // u32 is larger but should be saturated to `u16::MAX`
70+ assert_eq ! ( txn_index. 0 , u16 :: MAX ) ;
71+ }
72+
73+ #[ test]
74+ fn test_from_large_i32_to_txn_index ( ) {
75+ let txn_index: TxnIndex = 70000i32 . into ( ) ; // i32 too large for u16, should saturate to `u16::MAX`
76+ assert_eq ! ( txn_index. 0 , u16 :: MAX ) ;
77+ }
78+
79+ // Test for `From<TxnIndex>` conversion to `i16`
80+ #[ test]
81+ fn test_txn_index_to_i16_within_range ( ) {
82+ let txn_index = TxnIndex ( 100 ) ;
83+ let result: i16 = txn_index. into ( ) ; // Should successfully convert to i16
84+ assert_eq ! ( result, 100 ) ;
85+ }
86+
87+ #[ test]
88+ fn test_txn_index_to_i16_with_saturation ( ) {
89+ let txn_index = TxnIndex ( u16:: MAX ) ; // u16::MAX = 65535, which is too large for i16
90+ let result: i16 = txn_index. into ( ) ; // Should saturate to i16::MAX
91+ assert_eq ! ( result, i16 :: MAX ) ;
92+ }
93+
94+ #[ test]
95+ fn test_txn_index_to_i16_with_zero ( ) {
96+ let txn_index = TxnIndex ( 0 ) ; // Should be able to convert to i16 without issue
97+ let result: i16 = txn_index. into ( ) ;
98+ assert_eq ! ( result, 0 ) ;
99+ }
100+ }
0 commit comments