Skip to content

Commit 90cec1e

Browse files
committed
Rename error types to convey their semantics
If a downstream library decodes a hex string into a particular type using a function in this library the returned error type would "leak" which type the library used internally. The specific type shouldn't really concern the callers since it can change anyway. What is relevant though is whether the length is known at compile time or not. We might also add more functions in the future decoding to different types and it'd be better to share error types in such case. This change renames `HexToBytesError` to `DecodeDynSizedBytesError` and `HexToArrayError` to `DecodeFixedSizedBytesError` so that types are not mentioned.
1 parent 2d4bbcf commit 90cec1e

File tree

6 files changed

+42
-42
lines changed

6 files changed

+42
-42
lines changed

examples/hexy.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@
88
use std::fmt;
99
use std::str::FromStr;
1010

11-
use hex_conservative::{fmt_hex_exact, Case, DisplayHex as _, FromHex as _, HexToArrayError};
11+
use hex_conservative::{fmt_hex_exact, Case, DisplayHex as _, FromHex as _, DecodeFixedSizedBytesError};
1212

1313
fn main() {
1414
let s = "deadbeefcafebabedeadbeefcafebabedeadbeefcafebabedeadbeefcafebabe";
@@ -46,7 +46,7 @@ impl fmt::Display for Hexy {
4646
}
4747

4848
impl FromStr for Hexy {
49-
type Err = HexToArrayError;
49+
type Err = DecodeFixedSizedBytesError;
5050

5151
fn from_str(s: &str) -> Result<Self, Self::Err> {
5252
// Errors if the input is invalid

examples/wrap_array.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@
77
use core::fmt;
88
use core::str::FromStr;
99

10-
use hex_conservative::{DisplayHex as _, FromHex as _, HexToArrayError};
10+
use hex_conservative::{DisplayHex as _, FromHex as _, DecodeFixedSizedBytesError};
1111

1212
fn main() {
1313
let hex = "deadbeefcafebabedeadbeefcafebabedeadbeefcafebabedeadbeefcafebabe";
@@ -72,6 +72,6 @@ impl fmt::UpperHex for Wrap {
7272
}
7373

7474
impl FromStr for Wrap {
75-
type Err = HexToArrayError;
75+
type Err = DecodeFixedSizedBytesError;
7676
fn from_str(s: &str) -> Result<Self, Self::Err> { Ok(Self(<[u8; 32]>::from_hex(s)?)) }
7777
}

src/error.rs

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -70,17 +70,17 @@ pub(crate) use write_err;
7070
/// This represents the first error encountered during decoding, however we may add other remaining
7171
/// ones in the future.
7272
///
73-
/// This error differs from `HexToArrayError` in that the number of bytes is only known at run time
73+
/// This error differs from `DecodeFixedSizedBytesError` in that the number of bytes is only known at run time
7474
/// - e.g. when decoding `Vec<u8>`.
7575
#[derive(Debug, Clone, PartialEq, Eq)]
76-
pub enum HexToBytesError {
76+
pub enum DecodeDynSizedBytesError {
7777
/// Non-hexadecimal character.
7878
InvalidChar(InvalidCharError),
7979
/// Purported hex string had odd (not even) length.
8080
OddLengthString(OddLengthStringError),
8181
}
8282

83-
impl HexToBytesError {
83+
impl DecodeDynSizedBytesError {
8484
/// Adds `by_bytes` to all character positions stored inside.
8585
///
8686
/// If you're parsing a larger string that consists of multiple hex sub-strings and want to
@@ -97,7 +97,7 @@ impl HexToBytesError {
9797
#[must_use]
9898
#[inline]
9999
pub fn offset(self, by_bytes: usize) -> Self {
100-
use HexToBytesError as E;
100+
use DecodeDynSizedBytesError as E;
101101

102102
match self {
103103
E::InvalidChar(e) => E::InvalidChar(e.offset(by_bytes)),
@@ -106,15 +106,15 @@ impl HexToBytesError {
106106
}
107107
}
108108

109-
impl From<Infallible> for HexToBytesError {
109+
impl From<Infallible> for DecodeDynSizedBytesError {
110110
#[inline]
111111
fn from(never: Infallible) -> Self { match never {} }
112112
}
113113

114-
impl fmt::Display for HexToBytesError {
114+
impl fmt::Display for DecodeDynSizedBytesError {
115115
#[inline]
116116
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
117-
use HexToBytesError as E;
117+
use DecodeDynSizedBytesError as E;
118118

119119
match *self {
120120
E::InvalidChar(ref e) => write_err!(f, "failed to decode hex"; e),
@@ -124,10 +124,10 @@ impl fmt::Display for HexToBytesError {
124124
}
125125

126126
if_std_error! {{
127-
impl StdError for HexToBytesError {
127+
impl StdError for DecodeDynSizedBytesError {
128128
#[inline]
129129
fn source(&self) -> Option<&(dyn StdError + 'static)> {
130-
use HexToBytesError as E;
130+
use DecodeDynSizedBytesError as E;
131131

132132
match *self {
133133
E::InvalidChar(ref e) => Some(e),
@@ -137,12 +137,12 @@ if_std_error! {{
137137
}
138138
}}
139139

140-
impl From<InvalidCharError> for HexToBytesError {
140+
impl From<InvalidCharError> for DecodeDynSizedBytesError {
141141
#[inline]
142142
fn from(e: InvalidCharError) -> Self { Self::InvalidChar(e) }
143143
}
144144

145-
impl From<OddLengthStringError> for HexToBytesError {
145+
impl From<OddLengthStringError> for DecodeDynSizedBytesError {
146146
#[inline]
147147
fn from(e: OddLengthStringError) -> Self { Self::OddLengthString(e) }
148148
}
@@ -169,7 +169,7 @@ impl InvalidCharError {
169169

170170
/// Adds `by_bytes` to all character positions stored inside.
171171
///
172-
/// **Important**: if you have `HexToBytesError` or `HexToArrayError` you
172+
/// **Important**: if you have `DecodeDynSizedBytesError` or `DecodeFixedSizedBytesError` you
173173
/// should call the method *on them* - do not match them and manually call this method. Doing
174174
/// so may lead to broken behavior in the future.
175175
///
@@ -283,17 +283,17 @@ if_std_error! {{
283283

284284
/// Error returned when hex decoding bytes whose length is known at compile time.
285285
///
286-
/// This error differs from `HexToBytesError` in that the number of bytes is known at compile time
286+
/// This error differs from `DecodeDynSizedBytesError` in that the number of bytes is known at compile time
287287
/// - e.g. when decoding to an array of bytes.
288288
#[derive(Debug, Clone, PartialEq, Eq)]
289-
pub enum HexToArrayError {
289+
pub enum DecodeFixedSizedBytesError {
290290
/// Non-hexadecimal character.
291291
InvalidChar(InvalidCharError),
292292
/// Tried to parse fixed-length hash from a string with the wrong length.
293293
InvalidLength(InvalidLengthError),
294294
}
295295

296-
impl HexToArrayError {
296+
impl DecodeFixedSizedBytesError {
297297
/// Adds `by_bytes` to all character positions stored inside.
298298
///
299299
/// If you're parsing a larger string that consists of multiple hex sub-strings and want to
@@ -310,7 +310,7 @@ impl HexToArrayError {
310310
#[must_use]
311311
#[inline]
312312
pub fn offset(self, by_bytes: usize) -> Self {
313-
use HexToArrayError as E;
313+
use DecodeFixedSizedBytesError as E;
314314

315315
match self {
316316
E::InvalidChar(e) => E::InvalidChar(e.offset(by_bytes)),
@@ -319,15 +319,15 @@ impl HexToArrayError {
319319
}
320320
}
321321

322-
impl From<Infallible> for HexToArrayError {
322+
impl From<Infallible> for DecodeFixedSizedBytesError {
323323
#[inline]
324324
fn from(never: Infallible) -> Self { match never {} }
325325
}
326326

327-
impl fmt::Display for HexToArrayError {
327+
impl fmt::Display for DecodeFixedSizedBytesError {
328328
#[inline]
329329
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
330-
use HexToArrayError as E;
330+
use DecodeFixedSizedBytesError as E;
331331

332332
match *self {
333333
E::InvalidChar(ref e) => write_err!(f, "failed to parse hex"; e),
@@ -337,10 +337,10 @@ impl fmt::Display for HexToArrayError {
337337
}
338338

339339
if_std_error! {{
340-
impl StdError for HexToArrayError {
340+
impl StdError for DecodeFixedSizedBytesError {
341341
#[inline]
342342
fn source(&self) -> Option<&(dyn StdError + 'static)> {
343-
use HexToArrayError as E;
343+
use DecodeFixedSizedBytesError as E;
344344

345345
match *self {
346346
E::InvalidChar(ref e) => Some(e),
@@ -350,12 +350,12 @@ if_std_error! {{
350350
}
351351
}}
352352

353-
impl From<InvalidCharError> for HexToArrayError {
353+
impl From<InvalidCharError> for DecodeFixedSizedBytesError {
354354
#[inline]
355355
fn from(e: InvalidCharError) -> Self { Self::InvalidChar(e) }
356356
}
357357

358-
impl From<InvalidLengthError> for HexToArrayError {
358+
impl From<InvalidLengthError> for DecodeFixedSizedBytesError {
359359
#[inline]
360360
fn from(e: InvalidLengthError) -> Self { Self::InvalidLength(e) }
361361
}
@@ -423,7 +423,7 @@ mod tests {
423423
fn invalid_char_error() {
424424
let result = <Vec<u8> as FromHex>::from_hex("12G4");
425425
let error = result.unwrap_err();
426-
if let HexToBytesError::InvalidChar(e) = error {
426+
if let DecodeDynSizedBytesError::InvalidChar(e) = error {
427427
assert!(!format!("{}", e).is_empty());
428428
assert_eq!(e.invalid_char(), b'G');
429429
assert_eq!(e.pos(), 2);
@@ -439,7 +439,7 @@ mod tests {
439439
let error = result.unwrap_err();
440440
assert!(!format!("{}", error).is_empty());
441441
check_source(&error);
442-
if let HexToBytesError::OddLengthString(e) = error {
442+
if let DecodeDynSizedBytesError::OddLengthString(e) = error {
443443
assert!(!format!("{}", e).is_empty());
444444
assert_eq!(e.length(), 3);
445445
} else {
@@ -453,7 +453,7 @@ mod tests {
453453
let error = result.unwrap_err();
454454
assert!(!format!("{}", error).is_empty());
455455
check_source(&error);
456-
if let HexToArrayError::InvalidLength(e) = error {
456+
if let DecodeFixedSizedBytesError::InvalidLength(e) = error {
457457
assert!(!format!("{}", e).is_empty());
458458
assert_eq!(e.expected_length(), 8);
459459
assert_eq!(e.invalid_length(), 3);
@@ -464,14 +464,14 @@ mod tests {
464464

465465
#[test]
466466
fn to_bytes_error() {
467-
let error = HexToBytesError::OddLengthString(OddLengthStringError { len: 7 });
467+
let error = DecodeDynSizedBytesError::OddLengthString(OddLengthStringError { len: 7 });
468468
assert!(!format!("{}", error).is_empty());
469469
check_source(&error);
470470
}
471471

472472
#[test]
473473
fn to_array_error() {
474-
let error = HexToArrayError::InvalidLength(InvalidLengthError { expected: 8, invalid: 7 });
474+
let error = DecodeFixedSizedBytesError::InvalidLength(InvalidLengthError { expected: 8, invalid: 7 });
475475
assert!(!format!("{}", error).is_empty());
476476
check_source(&error);
477477
}

src/lib.rs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -113,7 +113,7 @@ pub(crate) use table::Table;
113113
pub use self::{
114114
display::DisplayHex,
115115
error::{
116-
HexToArrayError, HexToBytesError, InvalidCharError, InvalidLengthError,
116+
DecodeFixedSizedBytesError, DecodeDynSizedBytesError, InvalidCharError, InvalidLengthError,
117117
OddLengthStringError,
118118
},
119119
iter::{BytesToHexIter, HexToBytesIter, HexSliceToBytesIter},
@@ -130,11 +130,11 @@ pub use self::{
130130
///
131131
/// Returns an error if `hex` contains invalid characters or doesn't have even length.
132132
#[cfg(feature = "alloc")]
133-
pub fn decode_to_vec(hex: &str) -> Result<Vec<u8>, HexToBytesError> {
133+
pub fn decode_to_vec(hex: &str) -> Result<Vec<u8>, DecodeDynSizedBytesError> {
134134
Ok(HexToBytesIter::new(hex)?.drain_to_vec()?)
135135
}
136136

137-
/// Decodes a hex string with an expected length kown at compile time.
137+
/// Decodes a hex string with an expected length known at compile time.
138138
///
139139
/// If you don't know the required length at compile time you need to use [`decode_to_vec`]
140140
/// instead.
@@ -143,7 +143,7 @@ pub fn decode_to_vec(hex: &str) -> Result<Vec<u8>, HexToBytesError> {
143143
///
144144
/// Returns an error if `hex` contains invalid characters or has incorrect length. (Should be
145145
/// `N * 2`.)
146-
pub fn decode_to_array<const N: usize>(hex: &str) -> Result<[u8; N], HexToArrayError> {
146+
pub fn decode_to_array<const N: usize>(hex: &str) -> Result<[u8; N], DecodeFixedSizedBytesError> {
147147
if hex.len() == N * 2 {
148148
let mut ret = [0u8; N];
149149
// checked above

src/parse.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ use core::{fmt, str};
88
use crate::alloc::vec::Vec;
99

1010
#[rustfmt::skip] // Keep public re-exports separate.
11-
pub use crate::error::{HexToBytesError, HexToArrayError};
11+
pub use crate::error::{DecodeDynSizedBytesError, DecodeFixedSizedBytesError};
1212

1313
/// Trait for objects that can be deserialized from hex strings.
1414
pub trait FromHex: Sized + sealed::Sealed {
@@ -25,7 +25,7 @@ pub trait FromHex: Sized + sealed::Sealed {
2525

2626
#[cfg(feature = "alloc")]
2727
impl FromHex for Vec<u8> {
28-
type Error = HexToBytesError;
28+
type Error = DecodeDynSizedBytesError;
2929

3030
#[inline]
3131
fn from_hex(s: &str) -> Result<Self, Self::Error> {
@@ -34,7 +34,7 @@ impl FromHex for Vec<u8> {
3434
}
3535

3636
impl<const LEN: usize> FromHex for [u8; LEN] {
37-
type Error = HexToArrayError;
37+
type Error = DecodeFixedSizedBytesError;
3838

3939
fn from_hex(s: &str) -> Result<Self, Self::Error> {
4040
crate::decode_to_array(s)

tests/api.rs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,7 @@ use core::{fmt, slice};
1717
use hex_conservative::serde;
1818
// These imports test "typical" usage by user code.
1919
use hex_conservative::{
20-
buf_encoder, display, BytesToHexIter, Case, DisplayHex as _, HexToArrayError, HexToBytesError,
20+
buf_encoder, display, BytesToHexIter, Case, DisplayHex as _, DecodeFixedSizedBytesError, DecodeDynSizedBytesError,
2121
InvalidCharError, InvalidLengthError, OddLengthStringError,
2222
};
2323

@@ -86,8 +86,8 @@ impl Structs<'_, slice::Iter<'_, u8>, String> {
8686
// These derives are the policy of `rust-bitcoin` not Rust API guidelines.
8787
#[derive(Debug, Clone, PartialEq, Eq)] // All public types implement Debug (C-DEBUG).
8888
struct Errors {
89-
c: HexToArrayError,
90-
d: HexToBytesError,
89+
c: DecodeFixedSizedBytesError,
90+
d: DecodeDynSizedBytesError,
9191
e: InvalidCharError,
9292
f: InvalidLengthError,
9393
g: OddLengthStringError,

0 commit comments

Comments
 (0)