Function lexical_core::write_with_options

source ·
pub fn write_with_options<'a, N: ToLexicalWithOptions, const FORMAT: u128>(
    n: N,
    bytes: &'a mut [u8],
    options: &N::Options,
) -> &'a mut [u8]
Expand description

Write number to string with custom options.

Returns a subslice of the input buffer containing the written bytes, starting from the same address in memory as the input slice.

  • FORMAT - Packed struct containing the number format.
  • value - Number to serialize.
  • bytes - Buffer to write number to.
  • options - Options to customize number parsing.

§Panics

Panics if the buffer may not be large enough to hold the serialized number. In order to ensure the function will not panic, provide a buffer with at least {integer}::FORMATTED_SIZE elements. If you are using custom digit precision control or exponent break points for writing floats, these constants may be insufficient to store the serialized number, and up to 1200 bytes may be required with radix support.

If the provided FORMAT is not valid, the function may panic. Please ensure is_valid() is called prior to using the format, or checking its validity using a static assertion.

§Example

#[cfg(feature = "write-floats")] {
// import `BUFFER_SIZE` to get the maximum bytes written by the number.
use lexical_core::BUFFER_SIZE;

let mut buffer = [0u8; BUFFER_SIZE];
let float = 3.14159265359_f32;

const FORMAT: u128 = lexical_core::format::STANDARD;
let options = lexical_core::WriteFloatOptions::new();
lexical_core::write_with_options::<_, FORMAT>(float, &mut buffer, &options);

assert_eq!(&buffer[0..9], b"3.1415927");

This will panic, because the buffer is not large enough:

// note: the buffer is only one byte large
let mut buffer = [0u8; 1];
let float = 3.14159265359_f32;

const FORMAT: u128 = lexical_core::format::STANDARD;
let options = lexical_core::WriteFloatOptions::new();
lexical_core::write_with_options::<_, FORMAT>(float, &mut buffer, &options);