conduwuit/src/utils.rs

35 lines
849 B
Rust
Raw Normal View History

use std::{
convert::TryInto,
time::{SystemTime, UNIX_EPOCH},
};
2020-03-29 11:48:44 +00:00
pub fn millis_since_unix_epoch() -> js_int::UInt {
(SystemTime::now()
.duration_since(UNIX_EPOCH)
.unwrap()
.as_millis() as u32)
.into()
}
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
}