#![cfg_attr(not(feature = "std"), no_std)]
extern crate alloc;
#[cfg(not(feature = "std"))]
use alloc::string::String;
#[cfg(feature = "std")]
use convert_case::{Boundary, Case, Casing};
#[cfg(feature = "std")]
pub fn camel_to_snake(text: &str) -> String {
text.from_case(Case::UpperCamel)
.without_boundaries(&[Boundary::UpperDigit, Boundary::LowerDigit])
.to_case(Case::Snake)
}
pub fn event_absolute_position(len: usize, index: i32) -> Option<usize> {
if index.is_negative() {
let abs_idx = index.wrapping_abs() as usize;
if abs_idx > len {
return None;
}
Some(len - abs_idx)
} else {
if index as usize >= len {
return None;
}
Some(index as usize)
}
}
pub static KEY_DELIMITER: &str = "#";
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);
}
}
#[inline]
pub fn create_key(left: &str, right: &str) -> String {
alloc::format!("{}{}{}", left, KEY_DELIMITER, right)
}
#[cfg(test)]
mod tests {
use crate::{camel_to_snake, event_absolute_position};
#[test]
fn camel_to_snake_works() {
assert_eq!("owned_token", camel_to_snake("OwnedToken"));
assert_eq!("ownable", camel_to_snake("Ownable"));
assert_eq!("erc20", camel_to_snake("Erc20"));
assert_eq!(
"erc20_implementation",
camel_to_snake("Erc20Implementation")
);
}
#[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));
}
}