Comparisons between Arrays static mut

I would to compare two array static mutable defined in this way:

static mut rdbuf: [u64; SZ_BUF / 8] = [0; SZ_BUF / 8];
static mut wrbuf: [u64; SZ_BUF / 8] = [0; SZ_BUF / 8];

i tried to use Memcmp but returns me the error as follows:

error[E0277]: the trait bound `u64: Memcmp` is not satisfied
   --> src\main.rs:176:23
    |
176 |     let mem_compare = Memcmp::memcmp(&rdbf[0], &wrbuf[0] );
    |                       ^^^^^^^^^^^^^^ the trait `Memcmp` is not implemented for `u64`
    |
    = help: the following other types implement trait `Memcmp`:
              [i16]
              [i32]
              [i64]
              [i8]
              [u16]
              [u32]
              [u64]
              [u8]

How can i avoid this error and to compare these arrays?

This works on my machine:

use memcmp::Memcmp;

const SZ_BUF: usize = 16;

static mut RDBUF: [u64; SZ_BUF / 8] = [0; SZ_BUF / 8];
static mut WRBUF: [u64; SZ_BUF / 8] = [0; SZ_BUF / 8];

fn main() {
    assert!(unsafe { RDBUF.memcmp(&WRBUF) });
}

Edit: didn't read your error message well enough, didn't realize you only want to compare the first element. You can generate one-element slices using a range index like this:

use memcmp::Memcmp;

const SZ_BUF: usize = 16;

static mut RDBUF: [u64; SZ_BUF / 8] = [0; SZ_BUF / 8];
static mut WRBUF: [u64; SZ_BUF / 8] = [0; SZ_BUF / 8];

fn main() {
    assert!(unsafe { RDBUF[..1].memcmp(&WRBUF[..1]) });
}

This will only compare the first element.

1 Like

You are calling memcmp in a single &u64 because you index the first element. It is only implemented for slices as the help message tells you.

Is there a reason for you to use the memcmp crate?

i have to replay the same behaviour of memcmp() in c. But in c i have:

fn memcmp(cx: *const c_void, ct: *const c_void, n: size_t) -> c_int

but my arguments are static mut arrays and are not c_void types

1 Like

The memcmp crate gives you a boolean.if you need a boolean you just can use the == operator. The memcmp crate was created over 8 years ago because the comparison of slices was not properly optimized yet.

If you want to know which of the two buffers is smaller if interpreted as native endian u8 you can use the bytemuck crate

use core::cmp::Ordering;

fn rust_memcmp_64(x: &[u8], y: &[u64]) -> Ordering {
    let x: &[u8] = bytemuck::cast_slice(x);
    let y: &[u8] = bytemuck::cast_slice(y);
   x.cmp(y)
}

This will compile to a call of memcmp or more efficient code if the lenght is known at compile time.

3 Likes

In C, you can (and are supposed to) refer to (a part of) an array with a pointer to its first element, but that certainly does not fly in Rust because it’s terribly unsafe. Rust has slices for that purpose.

Does this do what you want?

    let mem_compare = unsafe { &rdbuf == &wrbuf };

yes, it does

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.