Skip to content

Commit

Permalink
fix: string slice decoding (#1483)
Browse files Browse the repository at this point in the history
decoding string slices now reports correct amount of bytes read
  • Loading branch information
segfault-magnet authored Aug 16, 2024
1 parent a5bdbd3 commit 138d687
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
34 changes: 33 additions & 1 deletion packages/fuels-core/src/codec.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ mod tests {
use super::*;
use crate::{
constants::WORD_SIZE,
types::{Address, AssetId, ContractId},
types::{Address, AsciiString, AssetId, ContractId},
};

#[test]
Expand Down Expand Up @@ -80,4 +80,36 @@ mod tests {

Ok(())
}

#[test]
fn string_slice_is_read_in_total() {
// This was a bug where the decoder read more bytes than it reported, causing the next
// element to be read incorrectly.

// given
#[derive(
fuels_macros::Tokenizable, fuels_macros::Parameterize, Clone, PartialEq, Debug,
)]
#[FuelsCorePath = "crate"]
#[FuelsTypesPath = "crate::types"]
struct Test {
name: AsciiString,
age: u64,
}

let input = Test {
name: AsciiString::new("Alice".to_owned()).unwrap(),
age: 42,
};

let encoded = ABIEncoder::default()
.encode(&[input.clone().into_token()])
.unwrap();

// when
let decoded = try_from_bytes::<Test>(&encoded, DecoderConfig::default()).unwrap();

// then
assert_eq!(decoded, input);
}
}
8 changes: 5 additions & 3 deletions packages/fuels-core/src/codec/abi_decoder/bounded_decoder.rs
Original file line number Diff line number Diff line change
Expand Up @@ -210,12 +210,14 @@ impl BoundedDecoder {

fn decode_string_slice(bytes: &[u8]) -> Result<Decoded> {
let length = peek_length(bytes)?;
let bytes = peek(skip(bytes, LENGTH_BYTES_SIZE)?, length)?;
let decoded = str::from_utf8(bytes)?.to_string();
// skipping over the previously read length
let content_bytes = skip(bytes, LENGTH_BYTES_SIZE)?;
let string_bytes = peek(content_bytes, length)?;
let decoded = str::from_utf8(string_bytes)?.to_string();

Ok(Decoded {
token: Token::StringSlice(StaticStringToken::new(decoded, None)),
bytes_read: bytes.len(),
bytes_read: string_bytes.len() + LENGTH_BYTES_SIZE,
})
}

Expand Down

0 comments on commit 138d687

Please sign in to comment.