mrhooray / crc-rs

Rust implementation of CRC(16, 32, 64) with support of various standards

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to upgrade from v1 to v3 API?

soulmachine opened this issue · comments

This is more of a question rather than an issue.

I have one line code written with v1 API:

let checksum = crc32::update(my_u32, &crc32::IEEE_TABLE, mybytes).to_be_bytes();

I tried to translate to V3 API:

let CRC_32_IEEE: Crc<u32> = Crc::<u32>::new(&CRC_32_ISO_HDLC);
let mut digest = CRC_32_IEEE.digest_with_initial(my_u32);
digest.update(mybytes);
let checksum = digest.finalize();

But the result has changed.

Any ideas? Thanks

I'm guessing my_u32 is the result of a previous crc computation. Is it possible to keep it as a Digest (like in #73) and then update it?

If you must start with a raw digest value, then you can undo the finalization on my_u32 to compute the appropriate initial value:

let initial = (my_u32 ^ CRC.algorithm.xorout).reverse_bits();
let mut digest = CRC.digest_with_initial(initial);
digest.update(mybytes);
let checksum = digest.finalize();

That should result in the same checksum. But the first approach is recommended for obvious reasons.

Also, you probably want to initialize Crc as a const so that table generation only happens at compile time:

const CRC_32_IEEE: Crc<u32> = Crc::<u32>::new(&CRC_32_ISO_HDLC);

@akhilles your code works, thanks!