< 返回版块

noalias 发表于 2020-10-19 14:55

pub fn to_bytes(values: &[u32]) -> Vec<u8> {
    let mut result = values
        .iter()
        .scan(0, |left, &x| {
            let shift = get_highest_effective_bit(*left);
            let byte = x << shift | *left;
            *left = byte >> 28 | (x >> (32 - shift)) << 4; //这里报错:'attempt to shift right with overflow'
            Some(byte & 0x0fffffff)
        })
        .flat_map(|v| (0..4).map(move |n| (v >> n * 7 & 0x7f) as u8))
        .collect::<Vec<u8>>();

    match result.len() {
        0 | 1 => (),
        x => result[x - 1] |= 0x80,
    }
    result
}

右移溢出! 官方手册里找到了: Integer operators will panic when they overflow when compiled in debug mode. The -C debug-assertions and -C overflow-checks compiler flags can be used to control this more directly. The following things are considered to be overflow:

When +, * or - create a value greater than the maximum value, or less than the minimum value that can be stored. This includes unary - on the smallest value of any signed integer type. Using / or %, where the left-hand argument is the smallest integer of a signed integer type and the right-hand argument is -1. Using << or >> where the right-hand argument is greater than or equal to the number of bits in the type of the left-hand argument, or is negative.

评论区

写评论
uno 2020-10-19 15:38

使用 wrapping functions即可

1 共 1 条评论, 1 页