Convert u64 to String for concatenation

EDIT/SOLUTION: the to_le_bytes() returns 8 bytes for num.to_le_bytes() which is totally fine and thus it might concatenate 8 symbols to the string which is not what we want.
I tried several available built-in methods without any luck and came up with my own solution which works but might be unoptimal/not super efficient:

fn convert_num_to_ascii_bytes(num: u64) -> Bytes {
    let mut bytes = Bytes::new();
    let mut n = num;
    if n == 0 {
        bytes.push(48);
        return bytes;
    }
    while n != 0 {
        // 48 - is an ASCII offset for digits
        bytes.push(((n % 10) + 48).try_as_u8().unwrap());
        n /= 10;
    }
    let mut reversed_bytes = Bytes::with_capacity(bytes.len());
    while !bytes.is_empty() {
        reversed_bytes.push(bytes.pop().unwrap());
    }
    return reversed_bytes;
}

Then we can use it like that:

pub fn concat_str_with_num(s: String, num: u64) -> String {
    let mut result = Bytes::new();
    push_bytes(result, s.as_bytes());
    push_bytes(result, String::from_ascii_str("$").as_bytes()); // an arbitrary delimeter
    push_bytes(result, num.convert_num_to_ascii_bytes()); 
    String::from_ascii(result)
}
2 Likes