use crate::casper_types::bytesrepr::{Bytes, FromBytes};
use crate::error::EventError;
use crate::prelude::*;
use casper_event_standard::casper_types::bytesrepr::ToBytes;
pub fn serialize<T: ToBytes>(value: &T) -> Bytes {
Bytes::from(value.to_bytes().expect("Couldn't serialize"))
}
pub(crate) fn extract_event_name(bytes: &[u8]) -> Result<String, EventError> {
let name: String = FromBytes::from_bytes(bytes)
.map_err(|_| EventError::CouldntExtractName)?
.0;
name.strip_prefix("event_")
.map(|s| s.to_string())
.ok_or(EventError::UnexpectedType(name))
}
pub fn event_absolute_position(len: u32, index: i32) -> Option<u32> {
if index.is_negative() {
let abs_idx = index.wrapping_abs();
if abs_idx > len as i32 {
return None;
}
Some(
len.checked_sub(abs_idx as u32)
.expect("Checked sub failed, it shouldn't happen")
)
} else {
if index >= len as i32 {
return None;
}
Some(index as u32)
}
}
static TABLE: &[u8] = b"0123456789abcdef";
#[inline]
fn hex(byte: u8) -> u8 {
TABLE[byte as usize]
}
pub fn hex_to_slice(src: &[u8], dst: &mut [u8]) {
for (byte, slots) in src.iter().zip(dst.chunks_exact_mut(2)) {
slots[0] = hex((*byte >> 4) & 0xf);
slots[1] = hex(*byte & 0xf);
}
}
#[cfg(test)]
mod tests {
use super::event_absolute_position;
#[test]
fn event_absolute_position_works() {
assert_eq!(event_absolute_position(0, 1), None);
assert_eq!(event_absolute_position(10, 10), None);
assert_eq!(event_absolute_position(10, -11), None);
assert_eq!(event_absolute_position(10, 0), Some(0));
assert_eq!(event_absolute_position(10, 1), Some(1));
assert_eq!(event_absolute_position(10, -1), Some(9));
assert_eq!(event_absolute_position(10, -2), Some(8));
assert_eq!(event_absolute_position(10, -10), Some(0));
}
}