NiceLeeのBlog 用爱发电 bilibili~

Rust 比较时差大小犯的错误😳

2022-11-24
nIceLee

阅读:


时间戳是u128类型,unsigned无符号,这个问题卡了我很久,就很郁闷。

详情

程序放在本地测试没问题,到了生产环境就出了问题。。。
问题在于服务器时间和本地时间戳没有同步,那边更早一点,导致time_now小于time_local
time_now - time_local理论上应该小于0,但rust推断它是一个无符号u128,于是这个数读成了一个超大的数。
于是time_now - time_local > 600000为真,程序会走进报错的逻辑分支。

let time_local_str = "1669298051752";
let time_local = u128::from_str_radix(time_local_str, 10).map_err(|_x| {
    io::Error::new(io::ErrorKind::Other, "Timestamp in header is not correct!!")
})?;

let time_now = SystemTime::now()
    .duration_since(SystemTime::UNIX_EPOCH)
    .unwrap()
    .as_millis();
if time_now - time_local > 600000 {
    return Err(io::Error::new(
        io::ErrorKind::Other,
        "Timestamp or type in header is not valid!!",
    ));
}

改为:

let time_local_str = "1669298051752";
let time_local = u128::from_str_radix(time_local_str, 10).map_err(|_x| {
    io::Error::new(io::ErrorKind::Other, "Timestamp in header is not correct!!")
})?;

let time_now = SystemTime::now()
    .duration_since(SystemTime::UNIX_EPOCH)
    .unwrap()
    .as_millis();
if time_now > time_local + 600000 {
    return Err(io::Error::new(
        io::ErrorKind::Other,
        "Timestamp or type in header is not valid!!",
    ));
}

相似文章

上一篇 Rust 交叉编译

内容
隐藏