#[macro_export]
macro_rules! sub_unsigned {
($arg_lhs: expr, $arg_rhs: expr) => {
if $arg_lhs > $arg_rhs {
$arg_lhs - $arg_rhs
} else {
0
}
};
}
#[macro_export]
macro_rules! add_unsigned {
($arg_lhs: expr, $arg_rhs: expr) => {{
type BigInt = u64;
let lhs_big: BigInt = $arg_lhs as BigInt;
let rhs_big: BigInt = $arg_rhs as BigInt;
let sum_big: BigInt = lhs_big + rhs_big;
if sum_big > ChUnitPrimitiveType::MAX as BigInt {
ChUnitPrimitiveType::MAX
} else {
$arg_lhs + $arg_rhs
}
}};
}
#[macro_export]
macro_rules! mul_unsigned {
($arg_lhs: expr, $arg_rhs: expr) => {{
type BigInt = u64;
let lhs_big: BigInt = $arg_lhs as BigInt;
let rhs_big: BigInt = $arg_rhs as BigInt;
let mul_big: BigInt = lhs_big + rhs_big;
if mul_big > ChUnitPrimitiveType::MAX as BigInt {
ChUnitPrimitiveType::MAX
} else {
$arg_lhs * $arg_rhs
}
}};
}
#[macro_export]
macro_rules! inc_unsigned {
($arg_lhs: expr) => {
$arg_lhs = add_unsigned!($arg_lhs, 1);
};
($arg_lhs: expr, by: $arg_amount: expr) => {
$arg_lhs = add_unsigned!($arg_lhs, $arg_amount);
};
($arg_lhs: expr, max: $arg_max: expr) => {
if $arg_lhs >= $arg_max {
$arg_lhs = $arg_max;
} else {
$arg_lhs = add_unsigned!($arg_lhs, 1);
}
};
($arg_lhs: expr, by: $arg_amount:expr, max: $arg_max: expr) => {
if add_unsigned!($arg_lhs, $arg_amount) >= $arg_max {
$arg_lhs = $arg_max;
} else {
$arg_lhs = add_unsigned!($arg_lhs, $arg_amount);
}
};
}
#[macro_export]
macro_rules! dec_unsigned {
($arg_lhs: expr) => {
if $arg_lhs > 1 {
$arg_lhs = sub_unsigned!($arg_lhs, 1);
} else {
$arg_lhs = 0;
}
};
($arg_lhs: expr, by: $arg_amount: expr) => {
$arg_lhs = sub_unsigned!($arg_lhs, $arg_amount);
};
}
pub fn format_with_commas(num: usize) -> String {
let num_str = num.to_string();
let mut result = String::new();
for (count, c) in num_str.chars().rev().enumerate() {
if count % 3 == 0 && count != 0 {
result.push(',');
}
result.push(c);
}
result.chars().rev().collect()
}
#[test]
fn test_format_with_commas() {
{
let num = 5;
let result = format_with_commas(num);
assert_eq!(result, "5");
}
{
let num = 12;
let result = format_with_commas(num);
assert_eq!(result, "12");
}
{
let num = 123;
let result = format_with_commas(num);
assert_eq!(result, "123");
}
{
let num = 987654;
let result = format_with_commas(num);
assert_eq!(result, "987,654");
}
{
let num = 123456789;
let result = format_with_commas(num);
assert_eq!(result, "123,456,789");
}
}