try_into() is breaking when used on u8

So I don't have a lot of knowledge on this script, compiling as part of a larger project for ARM. This comes from the zksync library which is designed primarily for x86.

I keep running into a conversion error when compiling

        7 |         .try_into()
       |          ^^^^^^^^ the trait       `std::convert::From<std::vec::Vec<u8>>` is not implemented for `[u8; 16]`

I tried using try_from() as many of my searches recommended but wasn't able to get it running, as I am still very new to rust, but open to if anyone can get it working.

I am compiling with the following target and linker below -

target - arm-unknown-linux-musleabi linker - arm-linux-gnueabihf-ld

If anyone can recommend how to to fix this I'd love to hear, I was thinking usize instead of the u64 vars, but couldn't quite figure out if that is the rabbit hole I should try going down.

Full code down here

use serde::{Deserialize, Serialize};
use std::convert::TryInto;

/// Defines time range `[valid_from, valid_until]` for which transaction is valid,
/// time format is the same as Ethereum (UNIX timestamp in seconds)
#[derive(Debug, Clone, Copy, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct TimeRange {
    pub valid_from: u64,
    pub valid_until: u64,
}

impl TimeRange {
    pub fn new(valid_from: u64, valid_until: u64) -> Self {
        Self {
            valid_from,
            valid_until,
        }
    }

    pub fn to_be_bytes(&self) -> [u8; 16] {
        [
            self.valid_from.to_be_bytes(),
            self.valid_until.to_be_bytes(),
        ]
        .concat()
        .try_into()
        .expect("valid_from and valid_until should be u64")
    }

    pub fn check_correctness(&self) -> bool {
        self.valid_from <= self.valid_until
    }

    pub fn is_valid(&self, block_timestamp: u64) -> bool {
        self.valid_from <= block_timestamp && block_timestamp <= self.valid_until
    }
}

impl Default for TimeRange {
    fn default() -> Self {
        Self {
            valid_from: 0,
            valid_until: u64::max_value(),
        }
    }
}

1 answer

  • answered 2021-04-10 05:05 Emoun

    Your code compiles successfully on the current stable release (v1.51). However, TryFrom<Vec<_>> for slices (which is what allows you to use try_into()) was only added in rust 1.48, so maybe you are running a rust version older that 1.48. If so, updating to 1.48+ should fix your problem.