Skip to content

Commit

Permalink
Merge pull request #21 from srdtrk/serdar/20-imp-std-err
Browse files Browse the repository at this point in the history
imp: added "std" feature and implemented `std::error::Error`
  • Loading branch information
webmaster128 committed Jun 4, 2024
2 parents f6fecd5 + b84fb06 commit 8859314
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 3 deletions.
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ repository = "https://github.com/noislabs/anybuf"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[features]
default = ["std"]
std = []

[dependencies]

[dev-dependencies]
Expand Down
37 changes: 37 additions & 0 deletions src/bufany.rs
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,43 @@ pub enum RepeatedStringError {
InvalidUtf8,
}

impl core::fmt::Display for BufanyError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("Error decoding protobuf: ")?;
match self {
BufanyError::InvalidTag => f.write_str("Invalid tag"),
BufanyError::InvalidFieldNumber => {
f.write_str("Invalid field number, must be between 1 and 536,870,911")
}
BufanyError::UnsupportedWireType(wire_type) => {
write!(f, "Unsupported wire type: {}", wire_type)
}
BufanyError::ErrorDecodingVarint => f.write_str("Error decoding varint"),
BufanyError::UnexpectedEndOfData => f.write_str("Unexpected end of data"),
}
}
}

impl core::fmt::Display for RepeatedStringError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str("Error decoding repeated string: ")?;
match self {
RepeatedStringError::TypeMismatch => {
f.write_str("Found a value of the wrong wire type")
}
RepeatedStringError::InvalidUtf8 => {
f.write_str("A variable length field did not contain valid UTF-8")
}
}
}
}

#[cfg(feature = "std")]
impl std::error::Error for BufanyError {}

#[cfg(feature = "std")]
impl std::error::Error for RepeatedStringError {}

impl Bufany<'_> {
/// Creates an empty instance with the given lifetime.
///
Expand Down
4 changes: 1 addition & 3 deletions src/varint.rs
Original file line number Diff line number Diff line change
Expand Up @@ -55,9 +55,7 @@ pub fn read_unsigned_varint(data: &mut SliceReader) -> Option<u64> {
// If byte_counter becomes 10, the `value << (byte_counter * 7)` performs a
// left shift of 70 bits on a u64 which leads to an overflow panic.
for byte_counter in 0..10 {
let Some(byte) = data.read_one() else {
return None;
};
let byte = data.read_one()?;
let value = (byte & 0x7f) as u64;
out += value << (byte_counter * 7);
if byte & 0x80 == 0 {
Expand Down

0 comments on commit 8859314

Please sign in to comment.