diff --git a/src/libyml/parser.rs b/src/libyml/parser.rs index c330fb56..960bd4c5 100644 --- a/src/libyml/parser.rs +++ b/src/libyml/parser.rs @@ -111,7 +111,7 @@ pub struct MappingStart { } /// Represents an anchor in a YAML document. -#[derive(Ord, PartialOrd, Eq, PartialEq)] +#[derive(Clone, Default, Eq, Ord, PartialEq, PartialOrd)] pub struct Anchor(Box<[u8]>); /// Represents the style of a scalar value in a YAML document. @@ -282,8 +282,7 @@ unsafe fn convert_event<'input>( }) } sys::YamlMappingEndEvent => Event::MappingEnd, - sys::YamlNoEvent => unreachable!(), - _ => unreachable!(), + sys::YamlNoEvent | _ => unreachable!(), } } @@ -303,8 +302,8 @@ unsafe fn optional_repr<'input>( sys: &sys::YamlEventT, input: &'input Cow<'input, [u8]>, ) -> Option<&'input [u8]> { - let start = sys.start_mark.index as usize; - let end = sys.end_mark.index as usize; + let start = usize::try_from(sys.start_mark.index).ok()?; + let end = usize::try_from(sys.end_mark.index).ok()?; Some(&input[start..end]) } diff --git a/src/libyml/safe_cstr.rs b/src/libyml/safe_cstr.rs index f983a266..d491ccbf 100644 --- a/src/libyml/safe_cstr.rs +++ b/src/libyml/safe_cstr.rs @@ -6,9 +6,9 @@ use std::{ }; #[derive(Copy, Clone, Debug, PartialEq, Eq)] -/// A custom error type for CStr operations. +/// A custom error type for `CStr` operations. /// -/// This struct represents an error that occurs during CStr operations. +/// This struct represents an error that occurs during `CStr` operations. /// /// # Implementations /// @@ -73,7 +73,8 @@ impl<'a> CStr<'a> { /// # Returns /// /// A new `CStr` instance representing the input pointer. - pub fn from_ptr(ptr: NonNull) -> Self { + #[must_use] + pub const fn from_ptr(ptr: NonNull) -> Self { CStr { // Cast the input pointer to a `NonNull` pointer ptr: ptr.cast(), @@ -97,11 +98,18 @@ impl<'a> CStr<'a> { end = unsafe { end.add(1) }; } - // Calculate the length of the C-style string, but only if the input is not empty - if end != start { - unsafe { end.offset_from(start) as usize } - } else { + // If the string is empty, return 0. Otherwise, compute the offset safely. + if end == start { 0 + } else { + let offset = unsafe { end.offset_from(start) }; + usize::try_from(offset).unwrap_or_else(|_| { + debug_assert!( + false, + "offset_from returned a negative value, which shouldn't happen in a forward scan" + ); + 0 + }) } } diff --git a/src/modules/error.rs b/src/modules/error.rs index 55d2c523..a923d0fa 100644 --- a/src/modules/error.rs +++ b/src/modules/error.rs @@ -32,16 +32,19 @@ pub struct Location { impl Location { /// Returns the byte index where the error occurred. + #[must_use] pub const fn index(&self) -> usize { self.index } /// Returns the line number where the error occurred. + #[must_use] pub const fn line(&self) -> usize { self.line } /// Returns the column number where the error occurred. + #[must_use] pub const fn column(&self) -> usize { self.column }