C memcmp alternative in Rust

I'm doing some pure memory compare stuff, and spuriously found no way to use some function like memcmp in C, for example:

let src : *const u8 = ...
let dst: *const u8 = ...
memcmp(src, dst, len);

so is there any alternative in Rust, doing the same thing? I found keyword memcmp was mentioned in Rust core's doc, but I didn't find a way to use it.

P.S. I'm doing FFI stuff, in this case, I must use pointers for comparing, I can use transmute to force cast my pointer to a slice, but I don't know if it is a good idea (honestly speaking I don't know how to cast a pointer to a slice using transmute either...)

You can just compare two slices.

let abc: &[u8] = b"abc";
let def: &[u8] = b"def";
println!("{}", abc < def)

playground

1 Like

I'm doing some FFI stuff, I must use pointers in my case, sorry I didn't mention it before.

You can not transmutate pointer to slice, because of slice it is pointer + length.
But you can use from_raw_parts in std::slice - Rust

2 Likes

Yeah, I just realize it after I typed it, thanks for the suggestion, it works.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.