Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: string slice decoding #1483

Merged
merged 1 commit into from
Aug 16, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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);
}
}
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
Loading