Why does this assertion fail when A and B uncommented?

Hi all,

Can someone help me to find out why the code assertion below fails when A and B are uncommented?

Best regards,
Daniel

thanks for ``` hint

#![allow(unused)]

static mut TABLE: [u16; 256] = [0; 256];
static mut INIT_DONE: bool = false;
const CRC_POLY: u16 = 0xA001;
const CRC_START_MODBUS: u16 = 0xFFFF;

unsafe fn init_table() {
    println!("!!! init table");
    let (mut crc, mut c): (u16, u16);
    for i in 0..256usize {
        c = i as u16;
        crc = 0;
        for j in 0..=7 {
            if (crc ^ c) & 0x0001 == 0x0001 {
                crc = (crc >> 1) ^ CRC_POLY;
            } else {
                crc >>= 1;
            }
            c >>= 1;
        }
        TABLE[i] = crc;
    }
    INIT_DONE = true;
}

fn print_table() {
    unsafe {
        if INIT_DONE {
            for i in 0..256 {
                if i % 16 == 0 {
                    println!();
                }
                print!("{:04X} ", TABLE[i]);
                TABLE[i] = 1;
            }
            println!();
        }
    }
}

fn checksum(vec: &Vec<u8>) -> u16 {
    let mut crc: u16 = CRC_START_MODBUS;
    unsafe {
        if !INIT_DONE {
            init_table();
        }
        let (mut tmp, mut c): (u16, u16);
        for v in vec {
            c = 0x00FF & (*v as u16);
            tmp = crc ^ c;
            crc = (crc >> 8) ^ TABLE[(tmp & 0xff) as usize];
        }
    }
    crc
}

fn test_checksum() {
    unsafe {
        // init_table(); // A
    }
    print_table(); // B
    let vec: Vec<u8> = vec![0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
    let crc: u16 = checksum(&vec);
    assert!(crc == 0x4574); // FAILS when A and B both uncommented, otherwise PASS
}

fn main() {
    test_checksum();
}
1 Like

@yadaniel Please surround your code with triple backticks (```). It will be then formatted as code and can be read proplery

1 Like

I found the “problem”.

Thread closed :slight_smile: