Skip to content

Commit

Permalink
impl split_at_checked equivalent to respect MSRV
Browse files Browse the repository at this point in the history
  • Loading branch information
RCasatta committed Jan 19, 2025
1 parent 6c3a319 commit e5e8e93
Show file tree
Hide file tree
Showing 3 changed files with 15 additions and 6 deletions.
4 changes: 2 additions & 2 deletions src/bsl/out_point.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use crate::{Error, Parse, ParseResult, SResult};
use crate::{slice::split_at_checked, Error, Parse, ParseResult, SResult};

/// The out point of a transaction input, identifying the previous output being spent
#[derive(Debug, Clone, PartialEq, Eq)]
Expand All @@ -15,7 +15,7 @@ impl<'a> AsRef<[u8]> for OutPoint<'a> {
impl<'a> Parse<'a> for OutPoint<'a> {
/// Parse the out point from the given slice
fn parse(slice: &'a [u8]) -> SResult<Self> {
let (slice, remaining) = slice.split_at_checked(36).ok_or(Error::MoreBytesNeeded)?;
let (slice, remaining) = split_at_checked(slice, 36)?;
Ok(ParseResult::new(remaining, OutPoint { slice }))
}
}
Expand Down
6 changes: 2 additions & 4 deletions src/bsl/script.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
use super::scan_len;
use crate::{Error, Parse, ParseResult, SResult};
use crate::{slice::split_at_checked, Error, Parse, ParseResult, SResult};

/// The Script, this type could be found in transaction outputs as `script_pubkey` or in transaction
/// inputs as `script_sig`.
Expand All @@ -17,9 +17,7 @@ impl<'a> Parse<'a> for Script<'a> {
fn parse(slice: &'a [u8]) -> SResult<Self> {
let mut consumed = 0;
let n = scan_len(slice, &mut consumed)? as usize;
let (script_bytes, remaining) = slice
.split_at_checked(consumed + n)
.ok_or(Error::MoreBytesNeeded)?;
let (script_bytes, remaining) = split_at_checked(slice, consumed + n)?;
Ok(ParseResult::new(
remaining,
Script {
Expand Down
11 changes: 11 additions & 0 deletions src/slice.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,17 @@ pub fn read_slice(from: &[u8], len: usize) -> SResult<&[u8]> {
}
}

/// Split the slice at the given length, returning the remaining slice and the parsed slice.
/// Replace with std split_at_checked when MSRV >= 1.80.0
#[inline(always)]
pub(crate) fn split_at_checked(from: &[u8], len: usize) -> Result<(&[u8], &[u8]), Error> {
if from.len() < len {
Err(Error::MoreBytesNeeded)
} else {
Ok(from.split_at(len))
}
}

#[cfg(test)]
mod test {
use crate::{Error, ParseResult};
Expand Down

0 comments on commit e5e8e93

Please sign in to comment.