1use crate::uint::U256;
4
5impl_from_str! {
6 impl FromStr for U256;
7}
8
9pub const fn const_from_str_prefixed(src: &str) -> U256 {
10 assert!(!src.is_empty(), "empty string");
11
12 let bytes = src.as_bytes();
13 let start = bytes[0] == b'+';
14 crate::parse::const_from_str_prefixed(bytes, start as _)
15}
16
17#[cfg(test)]
18mod tests {
19 use super::*;
20 use crate::parse::from_str_radix;
21 use core::num::IntErrorKind;
22
23 #[test]
24 fn from_str() {
25 assert_eq!("42".parse::<U256>().unwrap(), 42);
26 }
27
28 #[test]
29 fn from_str_prefixed() {
30 assert_eq!(from_str_radix::<U256>("0b101", 2, Some("0b")).unwrap(), 5);
31 assert_eq!(from_str_radix::<U256>("0xf", 16, Some("0x")).unwrap(), 15);
32 }
33
34 #[test]
35 fn from_str_errors() {
36 assert_eq!(
37 from_str_radix::<U256>("", 2, None).unwrap_err().kind(),
38 &IntErrorKind::Empty,
39 );
40 assert_eq!(
41 from_str_radix::<U256>("?", 2, None).unwrap_err().kind(),
42 &IntErrorKind::InvalidDigit,
43 );
44 assert_eq!(
45 from_str_radix::<U256>("1", 16, Some("0x"))
46 .unwrap_err()
47 .kind(),
48 &IntErrorKind::InvalidDigit,
49 );
50 assert_eq!(
51 from_str_radix::<U256>("-1", 10, None).unwrap_err().kind(),
52 &IntErrorKind::InvalidDigit,
53 );
54 assert_eq!(
55 from_str_radix::<U256>(
56 "zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz",
57 36,
58 None
59 )
60 .unwrap_err()
61 .kind(),
62 &IntErrorKind::PosOverflow,
63 );
64 }
65
66 #[test]
67 fn const_parse() {
68 assert_eq!(const_from_str_prefixed("+0b1101"), 0b1101);
69 assert_eq!(const_from_str_prefixed("0o777"), 0o777);
70 assert_eq!(const_from_str_prefixed("+0x1f"), 0x1f);
71 assert_eq!(const_from_str_prefixed("42"), 42);
72
73 assert_eq!(
74 const_from_str_prefixed(
75 "0xffff_ffff_ffff_ffff_ffff_ffff_ffff_fffe\
76 baae_dce6_af48_a03b_bfd2_5e8c_d036_4141"
77 ),
78 U256::from_words(
79 0xffff_ffff_ffff_ffff_ffff_ffff_ffff_fffe,
80 0xbaae_dce6_af48_a03b_bfd2_5e8c_d036_4141,
81 ),
82 );
83
84 assert_eq!(
85 const_from_str_prefixed(
86 "0x0000_0000_0000_0000_0000_0000_0000_0000\
87 0000_0000_0000_0000_0000_0000_0000_0000"
88 ),
89 U256::MIN,
90 );
91 assert_eq!(
92 const_from_str_prefixed(
93 "+0xffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff\
94 ffff_ffff_ffff_ffff_ffff_ffff_ffff_ffff"
95 ),
96 U256::MAX,
97 );
98 }
99
100 #[test]
101 #[should_panic]
102 fn const_parse_overflow() {
103 const_from_str_prefixed(
104 "0x1\
105 0000_0000_0000_0000_0000_0000_0000_0000\
106 0000_0000_0000_0000_0000_0000_0000_0000",
107 );
108 }
109
110 #[test]
111 #[should_panic]
112 fn const_parse_invalid() {
113 const_from_str_prefixed("invalid");
114 }
115}