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

lib.parse: use TryInto trait to replace peek to make parse not need std #235

Merged
merged 2 commits into from
Aug 18, 2020

Conversation

Evian-Zhang
Copy link
Contributor

This PR is to avoid std for the parse method of Object.

The reason that parse need std is peek needs it, and peek's task is:

  1. take the first 16 bytes of the total bytes;
  2. pass the taken array of 16 bytes to peek_bytes method.

And there is a no-std way to take the first 16 bytes of the total bytes:

fn take_hint_bytes(bytes: &[u8]) -> Option<&[u8; 16]> {
    use core::convert::TryInto;
    bytes.get(0..16)
        .and_then(|hint_bytes_slice| {
            hint_bytes_slice.try_into().ok()
        })
}

The core magic is get (which takes the first 16 elements of the given slice and returns a slice) and the TryInto trait (which converts the slice to array type, see more in How to get a slice as an array in Rust?).

For compatibility reason, I don't delete peek method although it is dead code.

Copy link
Owner

@m4b m4b left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM very much appreciated!!

/// Returns None if bytes's length is less than 16.
fn take_hint_bytes(bytes: &[u8]) -> Option<&[u8; 16]> {
use core::convert::TryInto;
bytes.get(0..16)
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Wow this is great, when did this get merged into rust ? (Do you know offhand which rustc this requires ?)

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

TryInto trait was stabilized in Rust 1.34

@@ -295,18 +305,19 @@ if_everything! {
Unknown(u64),
}

// TODO: this could avoid std using peek_bytes
Copy link
Owner

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Uh this is awesome, this todo has been here a very long time, and I really appreciate you fixing it! Great work :)

@m4b m4b merged commit e94ca6b into m4b:master Aug 18, 2020
@m4b
Copy link
Owner

m4b commented Aug 18, 2020

Thanks so much @Evian-Zhang ! :D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants