WriteFloatOptions

Struct WriteFloatOptions 

Source
pub struct WriteFloatOptions { /* private fields */ }
Available on crate feature write-floats only.
Expand description

Options to customize writing floats.

This enables extensive control over how the float is written, from control characters like the decimal point, to the use of exponent notation, and the number of significant digits.

§Examples

Writing a simple float with custom special strings and formatting integral floats as integers can be done as:

use core::str;

use lexical_write_float::{Options, ToLexical, ToLexicalWithOptions};
use lexical_write_float::format::STANDARD;

const OPTS: Options = Options::builder()
    .trim_floats(true)
    .nan_string(Some(b"NaN"))
    .inf_string(Some(b"Inf"))
    .build_strict();

const SIZE: usize = OPTS.buffer_size_const::<f64, STANDARD>();
let mut buffer = [0u8; SIZE];

// trim floats
let digits = 12345.0f64.to_lexical_with_options::<STANDARD>(&mut buffer, &OPTS);
assert_eq!(str::from_utf8(digits), Ok("12345"));

// don't trim floats
let digits = 12345.0f64.to_lexical(&mut buffer);
assert_eq!(str::from_utf8(digits), Ok("12345.0"));

Implementations§

Source§

impl Options

Source

pub const fn new() -> Options

Create options with default values.

Source

pub const fn from_radix(radix: u8) -> Options

Create the default options for a given radix.

This function will never fail even if the radix is invalid. It is up to the caller to ensure the format is valid using Options::is_valid. Only radixes from 2 to 36 should be used.

Source

pub const fn buffer_size_const<T, const FORMAT: u128>(&self) -> usize
where T: FormattedSize,

Get an upper bound on the required buffer size.

This is used when custom formatting options, such as significant digits specifiers or custom exponent breaks, are used, which can lead to more or less significant digits being written than expected. If using the default formatting options, then this will always be FORMATTED_SIZE or FORMATTED_SIZE_DECIMAL, depending on the radix.

§Examples
use core::{num, str};

use lexical_write_float::{FormattedSize, Options, ToLexicalWithOptions};
use lexical_write_float::format::STANDARD;

const DEFAULT: Options = Options::builder()
    // require at least 3 significant digits, so `0.01` would be `"0.0100"`.
    .min_significant_digits(num::NonZeroUsize::new(3))
    // allow at most 5 significant digits, so `1.23456` would be `"1.2346"`.
    .max_significant_digits(num::NonZeroUsize::new(5))
    // build our format, erroring if it's invalid
    .build_strict();
assert_eq!(DEFAULT.buffer_size_const::<f64, STANDARD>(), f64::FORMATTED_SIZE_DECIMAL);

const CUSTOM: Options = Options::builder()
    // require at least 300 significant digits.
    .min_significant_digits(num::NonZeroUsize::new(300))
    // allow at most 500 significant digits.
    .max_significant_digits(num::NonZeroUsize::new(500))
    // only write values with magnitude above 1e300 in exponent notation
    .positive_exponent_break(num::NonZeroI32::new(300))
    // only write values with magnitude below 1e-300 in exponent notation
    .negative_exponent_break(num::NonZeroI32::new(-300))
    .build_strict();
// 300 for the significant digits (500 is never reachable), 300 extra
// due to the exponent breakoff, 1 for the sign, 1 for the decimal point
// in all cases, this is enough including the exponent character and sign.
assert_eq!(CUSTOM.buffer_size_const::<f64, STANDARD>(), 602);

// now, write out value to bytes
const SIZE: usize = CUSTOM.buffer_size_const::<f64, STANDARD>();
let mut buffer = [0u8; SIZE];
let value = 1.23456e-299f64;
let digits = value.to_lexical_with_options::<STANDARD>(&mut buffer, &CUSTOM);

// validate our printed digits. 600!
assert_eq!(digits.len(), 600);
assert!(!digits.contains(&b'e') && !digits.contains(&b'E'));
assert!(digits.starts_with(b"0.000000000000000000000000"));

// validate the round-trip
assert_eq!(str::from_utf8(digits).unwrap().parse::<f64>(), Ok(value));

// let's serialize a slightly smaller value
let value = 1.23456e-301f64;
let digits = value.to_lexical_with_options::<STANDARD>(&mut buffer, &CUSTOM);
assert_eq!(digits.len(), 306);
let digits = value.to_lexical_with_options::<STANDARD>(&mut buffer, &CUSTOM);
Source

pub const fn is_valid(&self) -> bool

Check if the options state is valid.

Source

pub const fn max_significant_digits(&self) -> Option<NonZero<usize>>

Get the maximum number of significant digits to write.

This limits the total number of written digits, truncating based on the round_mode if more digits would normally be written. If no value is provided, then it writes as many digits as required to create an unambiguous representation of the float.

§Examples
use core::num::NonZeroUsize;

use lexical_write_float::Options;

const MAX_DIGITS: Option<NonZeroUsize> = NonZeroUsize::new(300);
const OPTIONS: Options = Options::builder()
    .max_significant_digits(MAX_DIGITS)
    .build_strict();
assert_eq!(OPTIONS.max_significant_digits(), MAX_DIGITS);
Source

pub const fn min_significant_digits(&self) -> Option<NonZero<usize>>

Get the minimum number of significant digits to write.

If more digits exist, such as writing “1.2” with a minimum of 5 significant digits, then 0s are appended to the end of the digits. If no value is provided, then it writes as few digits as required to create an unambiguous representation of the float.

§Examples
use core::num::NonZeroUsize;

use lexical_write_float::Options;

const MIN_DIGITS: Option<NonZeroUsize> = NonZeroUsize::new(10);
const OPTIONS: Options = Options::builder()
    .min_significant_digits(MIN_DIGITS)
    .build_strict();
assert_eq!(OPTIONS.min_significant_digits(), MIN_DIGITS);
Source

pub const fn positive_exponent_break(&self) -> Option<NonZero<i32>>

Get the maximum exponent prior to using scientific notation.

If the value is set to 300, then any value with magnitude >= 1e300 (for base 10) will be writen in exponent notation, while any lower value will be written in decimal form. If no value is provided, for decimal floats, this defaults to 9.

§Examples
use core::num::NonZeroI32;

use lexical_write_float::Options;

const POS_BREAK: Option<NonZeroI32> = NonZeroI32::new(3);
const OPTIONS: Options = Options::builder()
    .positive_exponent_break(POS_BREAK)
    .build_strict();
assert_eq!(OPTIONS.positive_exponent_break(), POS_BREAK);
Source

pub const fn negative_exponent_break(&self) -> Option<NonZero<i32>>

Get the minimum exponent prior to using scientific notation.

If the value is set to -300, then any value with magnitude < 1e-300 (for base 10) will be writen in exponent notation, while any larger value will be written in decimal form. If no value is provided, for decimal floats, this defaults to -5.

§Examples
use core::num::NonZeroI32;

use lexical_write_float::Options;

const NEG_BREAK: Option<NonZeroI32> = NonZeroI32::new(-3);
const OPTIONS: Options = Options::builder()
    .negative_exponent_break(NEG_BREAK)
    .build_strict();
assert_eq!(OPTIONS.negative_exponent_break(), NEG_BREAK);
Source

pub const fn round_mode(&self) -> RoundMode

Get the rounding mode for writing digits with precision control.

For example, writing 1.23456 with 5 significant digits with RoundMode::Round would produce "1.2346" while RoundMode::Truncate would produce "1.2345". Defaults to RoundMode::Round.

§Examples
use lexical_write_float::{Options, RoundMode};

const OPTIONS: Options = Options::builder()
    .round_mode(RoundMode::Truncate)
    .build_strict();
assert_eq!(OPTIONS.round_mode(), RoundMode::Truncate);
Source

pub const fn trim_floats(&self) -> bool

Get if we should trim a trailing ".0" from integral floats.

If used in conjunction with min_significant_digits, this will still trim all the significant digits if an integral value is provided. Defaults to false.

§Examples
use lexical_write_float::Options;

const OPTIONS: Options = Options::builder()
    .trim_floats(true)
    .build_strict();
assert_eq!(OPTIONS.trim_floats(), true);
Source

pub const fn exponent(&self) -> u8

Get the character to designate the exponent component of a float.

Any non-control character is valid, but \t to \r are also valid. The full range is [0x09, 0x0D] and [0x20, 0x7F]. Defaults to e.

§Examples
use lexical_write_float::Options;

const OPTIONS: Options = Options::builder()
    .exponent(b'^')
    .build_strict();
assert_eq!(OPTIONS.exponent(), b'^');
Source

pub const fn decimal_point(&self) -> u8

Get the character to separate the integer from the fraction components.

Any non-control character is valid, but \t to \r are also valid. The full range is [0x09, 0x0D] and [0x20, 0x7F]. Defaults to ..

§Examples
use lexical_write_float::Options;

const OPTIONS: Options = Options::builder()
    .exponent(b',')
    .build_strict();
assert_eq!(OPTIONS.exponent(), b',');
Source

pub const fn nan_string(&self) -> Option<&'static [u8]>

Get the string representation for NaN.

The first character must start with N or n and all characters must be valid ASCII letters (A-Z or a-z). If set to None, then writing NaN returns an error. Defaults to NaN.

§Examples
use lexical_write_float::Options;

const OPTIONS: Options = Options::builder()
    .nan_string(Some(b"nan"))
    .build_strict();
assert_eq!(OPTIONS.nan_string(), Some(b"nan".as_ref()));
Source

pub const fn inf_string(&self) -> Option<&'static [u8]>

Get the string representation for Infinity.

The first character must start with I or i and all characters must be valid ASCII letters (A-Z or a-z). If set to None, then writing Infinity returns an error. Defaults to inf.

§Examples
use lexical_write_float::Options;

const OPTIONS: Options = Options::builder()
    .inf_string(Some(b"infinity"))
    .build_strict();
assert_eq!(OPTIONS.inf_string(), Some(b"infinity".as_ref()));
Source

pub const fn infinity_string(&self) -> Option<&'static [u8]>

Get the string representation for Infinity. Alias for inf_string.

The first character must start with I or i and all characters must be valid ASCII letters (A-Z or a-z). If set to None, then writing Infinity returns an error. Defaults to inf.

§Examples
use lexical_write_float::Options;

const OPTIONS: Options = Options::builder()
    .infinity_string(Some(b"infinity"))
    .build_strict();
assert_eq!(OPTIONS.infinity_string(), Some(b"infinity".as_ref()));
Source

pub fn set_max_significant_digits( &mut self, max_significant_digits: Option<NonZero<usize>>, )

👎Deprecated: Options should be treated as immutable, use OptionsBuilder instead. Will be removed in 2.0.

Set the maximum number of significant digits to write.

This limits the total number of written digits, truncating based on the round_mode if more digits would normally be written.

§Panics

This will panic when writing the float if the value is smaller than min_significant_digits.

Source

pub fn set_min_significant_digits( &mut self, min_significant_digits: Option<NonZero<usize>>, )

👎Deprecated: Options should be treated as immutable, use OptionsBuilder instead. Will be removed in 2.0.

Set the minimum number of significant digits to write.

If more digits exist, such as writing “1.2” with a minimum of 5 significant digits, then 0s are appended to the end of the digits.

§Panics

This will panic when writing the float if the value is larger than max_significant_digits.

Source

pub fn set_positive_exponent_break( &mut self, positive_exponent_break: Option<NonZero<i32>>, )

👎Deprecated: Options should be treated as immutable, use OptionsBuilder instead. Will be removed in 2.0.

Set the maximum exponent prior to using scientific notation.

If the value is set to 300, then any value with magnitude >= 1e300 (for base 10) will be writen in exponent notation, while any lower value will be written in decimal form.

Source

pub fn set_negative_exponent_break( &mut self, negative_exponent_break: Option<NonZero<i32>>, )

👎Deprecated: Options should be treated as immutable, use OptionsBuilder instead. Will be removed in 2.0.

Set the minimum exponent prior to using scientific notation.

If the value is set to -300, then any value with magnitude < 1e-300 (for base 10) will be writen in exponent notation, while any larger value will be written in decimal form.

Source

pub fn set_round_mode(&mut self, round_mode: RoundMode)

👎Deprecated: Options should be treated as immutable, use OptionsBuilder instead. Will be removed in 2.0.

Set the rounding mode for writing digits with precision control.

For example, writing 1.23456 with 5 significant digits with RoundMode::Round would produce "1.2346" while RoundMode::Truncate would produce "1.2345".

Source

pub fn set_trim_floats(&mut self, trim_floats: bool)

👎Deprecated: Options should be treated as immutable, use OptionsBuilder instead. Will be removed in 2.0.

Set if we should trim a trailing ".0" from integral floats.

If used in conjunction with min_significant_digits, this will still trim all the significant digits if an integral value is provided.

Source

pub fn set_exponent(&mut self, exponent: u8)

👎Deprecated: Options should be treated as immutable, use OptionsBuilder instead. Will be removed in 2.0.

Set the character to designate the exponent component of a float.

§Safety

Always safe, but may produce invalid output if the exponent is not a valid ASCII character.

Source

pub fn set_decimal_point(&mut self, decimal_point: u8)

👎Deprecated: Options should be treated as immutable, use OptionsBuilder instead. Will be removed in 2.0.

Set the character to separate the integer from the fraction components.

§Safety

Always safe, but may produce invalid output if the decimal point is not a valid ASCII character.

Source

pub fn set_nan_string(&mut self, nan_string: Option<&'static [u8]>)

👎Deprecated: Options should be treated as immutable, use OptionsBuilder instead. Will be removed in 2.0.

Set the string representation for NaN.

Panics

Setting a value too large may cause a panic even if FORMATTED_SIZE elements are provided.

Source

pub fn set_inf_string(&mut self, inf_string: Option<&'static [u8]>)

👎Deprecated: Options should be treated as immutable, use OptionsBuilder instead. Will be removed in 2.0.

Set the short string representation for Infinity

Panics

Setting a value too large may cause a panic even if FORMATTED_SIZE elements are provided.

Source

pub const fn builder() -> OptionsBuilder

Get OptionsBuilder as a static function.

Source

pub const fn rebuild(&self) -> OptionsBuilder

Create OptionsBuilder using existing values.

Trait Implementations§

Source§

impl Clone for Options

Source§

fn clone(&self) -> Options

Returns a duplicate of the value. Read more
1.0.0 · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Debug for Options

Source§

fn fmt(&self, f: &mut Formatter<'_>) -> Result<(), Error>

Formats the value using the given formatter. Read more
Source§

impl Default for Options

Source§

fn default() -> Options

Returns the “default value” for a type. Read more
Source§

impl PartialEq for Options

Source§

fn eq(&self, other: &Options) -> bool

Tests for self and other values to be equal, and is used by ==.
1.0.0 · Source§

fn ne(&self, other: &Rhs) -> bool

Tests for !=. The default implementation is almost always sufficient, and should not be overridden without very good reason.
Source§

impl WriteOptions for Options

Source§

fn buffer_size<T, const FORMAT: u128>(&self) -> usize
where T: FormattedSize,

👎Deprecated: Use buffer_size_const instead. Will be removed in 2.0.

Get an upper bound on the required buffer size.

This method is soft-deprecated and meant for internal use. You should always use buffer_size_const so you can get the required buffer size at compile time to determine the buffer size required.

This is used when custom formatting options, such as significant digits specifiers or custom exponent breaks, are used, which can lead to more or less significant digits being written than expected. If using the default formatting options, then this will always be FORMATTED_SIZE or FORMATTED_SIZE_DECIMAL, depending on the radix.

Source§

fn is_valid(&self) -> bool

Determine if the options are valid.
Source§

impl Eq for Options

Source§

impl StructuralPartialEq for Options

Auto Trait Implementations§

Blanket Implementations§

Source§

impl<T> Any for T
where T: 'static + ?Sized,

Source§

fn type_id(&self) -> TypeId

Gets the TypeId of self. Read more
Source§

impl<T> Borrow<T> for T
where T: ?Sized,

Source§

fn borrow(&self) -> &T

Immutably borrows from an owned value. Read more
Source§

impl<T> BorrowMut<T> for T
where T: ?Sized,

Source§

fn borrow_mut(&mut self) -> &mut T

Mutably borrows from an owned value. Read more
Source§

impl<T> CloneToUninit for T
where T: Clone,

Source§

unsafe fn clone_to_uninit(&self, dest: *mut u8)

🔬This is a nightly-only experimental API. (clone_to_uninit)
Performs copy-assignment from self to dest. Read more
Source§

impl<T> From<T> for T

Source§

fn from(t: T) -> T

Returns the argument unchanged.

Source§

impl<T, U> Into<U> for T
where U: From<T>,

Source§

fn into(self) -> U

Calls U::from(self).

That is, this conversion is whatever the implementation of From<T> for U chooses to do.

Source§

impl<T> ToOwned for T
where T: Clone,

Source§

type Owned = T

The resulting type after obtaining ownership.
Source§

fn to_owned(&self) -> T

Creates owned data from borrowed data, usually by cloning. Read more
Source§

fn clone_into(&self, target: &mut T)

Uses borrowed data to replace owned data, usually by cloning. Read more
Source§

impl<T, U> TryFrom<U> for T
where U: Into<T>,

Source§

type Error = Infallible

The type returned in the event of a conversion error.
Source§

fn try_from(value: U) -> Result<T, <T as TryFrom<U>>::Error>

Performs the conversion.
Source§

impl<T, U> TryInto<U> for T
where U: TryFrom<T>,

Source§

type Error = <U as TryFrom<T>>::Error

The type returned in the event of a conversion error.
Source§

fn try_into(self) -> Result<U, <U as TryFrom<T>>::Error>

Performs the conversion.