conduit/src/utils.rs

42 lines
1010 B
Rust
Raw Normal View History

use rand::prelude::*;
use std::{
convert::TryInto,
time::{SystemTime, UNIX_EPOCH},
};
2020-03-29 11:48:44 +00:00
2020-04-12 19:12:50 +00:00
pub fn millis_since_unix_epoch() -> u64 {
SystemTime::now()
2020-03-29 11:48:44 +00:00
.duration_since(UNIX_EPOCH)
.unwrap()
2020-04-12 19:12:50 +00:00
.as_millis() as u64
2020-03-29 11:48:44 +00:00
}
2020-03-29 19:05:20 +00:00
pub fn increment(old: Option<&[u8]>) -> Option<Vec<u8>> {
let number = match old {
Some(bytes) => {
let array: [u8; 8] = bytes.try_into().unwrap();
let number = u64::from_be_bytes(array);
number + 1
}
None => 0,
};
2020-03-29 19:05:20 +00:00
Some(number.to_be_bytes().to_vec())
2020-03-29 19:05:20 +00:00
}
pub fn u64_from_bytes(bytes: &[u8]) -> u64 {
let array: [u8; 8] = bytes.try_into().expect("bytes are valid u64");
u64::from_be_bytes(array)
}
pub fn string_from_bytes(bytes: &[u8]) -> String {
String::from_utf8(bytes.to_vec()).expect("bytes are valid utf8")
2020-03-29 19:05:20 +00:00
}
pub fn random_string(length: usize) -> String {
thread_rng()
.sample_iter(&rand::distributions::Alphanumeric)
.take(length)
.collect()
}