WriteFloatOptionsBuilder

Struct WriteFloatOptionsBuilder 

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

Builder for Options.

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

For example, to customize the writing of numbers for new exponent and decimal point characters, you would use:

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

let value = 1.234e45f64;

const CUSTOM: Options = Options::builder()
    // write exponents as "1.2^10" and not "1.2e10"
    .exponent(b'^')
    // use the European decimal point, so "1,2" and not "1.2"
    .decimal_point(b',')
    .build_strict();

const BUFFER_SIZE: usize = CUSTOM.buffer_size_const::<f64, STANDARD>();
let mut buffer = [0u8; BUFFER_SIZE];
let digits = value.to_lexical_with_options::<STANDARD>(&mut buffer, &CUSTOM);
assert_eq!(str::from_utf8(digits), Ok("1,234^45"));

Implementations§

Source§

impl OptionsBuilder

Source

pub const fn new() -> OptionsBuilder

Source

pub const fn get_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 lexical_write_float::Options;

let builder = Options::builder();
assert_eq!(builder.get_max_significant_digits(), None);
Source

pub const fn get_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 lexical_write_float::Options;

let builder = Options::builder();
assert_eq!(builder.get_min_significant_digits(), None);
Source

pub const fn get_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 lexical_write_float::Options;

let builder = Options::builder();
assert_eq!(builder.get_positive_exponent_break(), None);
Source

pub const fn get_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 lexical_write_float::Options;

let builder = Options::builder();
assert_eq!(builder.get_negative_exponent_break(), None);
Source

pub const fn get_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};

let builder = Options::builder();
assert_eq!(builder.get_round_mode(), RoundMode::Round);
Source

pub const fn get_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;

let builder = Options::builder();
assert_eq!(builder.get_trim_floats(), false);
Source

pub const fn get_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;

let builder = Options::builder();
assert_eq!(builder.get_exponent(), b'e');
Source

pub const fn get_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;

let builder = Options::builder();
assert_eq!(builder.get_decimal_point(), b'.');
Source

pub const fn get_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 leads to an error. Defaults to NaN.

§Examples
use lexical_write_float::Options;

let builder = Options::builder();
assert_eq!(builder.get_nan_string(), Some("NaN".as_bytes()));
Source

pub const fn get_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;

let builder = Options::builder();
assert_eq!(builder.get_inf_string(), Some("inf".as_bytes()));
Source

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

Get the string representation for Infinity. Alias for get_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;

let builder = Options::builder();
assert_eq!(builder.get_infinity_string(), Some("inf".as_bytes()));
Source

pub const fn max_significant_digits( self, max_significant_digits: Option<NonZero<usize>>, ) -> OptionsBuilder

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. 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;

let max_digits = NonZeroUsize::new(300);
let builder = Options::builder()
    .max_significant_digits(max_digits);
assert_eq!(builder.get_max_significant_digits(), max_digits);
§Panics

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

Source

pub const fn min_significant_digits( self, min_significant_digits: Option<NonZero<usize>>, ) -> OptionsBuilder

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. 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;

let min_digits = NonZeroUsize::new(10);
let builder = Options::builder()
    .min_significant_digits(min_digits);
assert_eq!(builder.get_min_significant_digits(), min_digits);
§Panics

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

Source

pub const fn positive_exponent_break( self, positive_exponent_break: Option<NonZero<i32>>, ) -> OptionsBuilder

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. If no value is provided, for decimal floats, this defaults to 9.

§Examples
use core::num::NonZeroI32;

use lexical_write_float::Options;

let pos_break = NonZeroI32::new(3);
let builder = Options::builder()
    .positive_exponent_break(pos_break);
assert_eq!(builder.get_positive_exponent_break(), pos_break);
§Panics

Panics if the value is <= 0.

Source

pub const fn negative_exponent_break( self, negative_exponent_break: Option<NonZero<i32>>, ) -> OptionsBuilder

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. If no value is provided, for decimal floats, this defaults to -5.

§Examples
use core::num::NonZeroI32;

use lexical_write_float::Options;

let neg_break = NonZeroI32::new(-3);
let builder = Options::builder()
    .negative_exponent_break(neg_break);
assert_eq!(builder.get_negative_exponent_break(), neg_break);
§Panics

Panics if the value is >= 0.

Source

pub const fn round_mode(self, round_mode: RoundMode) -> OptionsBuilder

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". Defaults to RoundMode::Round.

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

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

 let value = 1.23456f64;

// truncating
const TRUNCATE: Options = Options::builder()
    // truncate numbers when writing less digits than present, rather than round
    .round_mode(RoundMode::Truncate)
    // the maximum number of significant digits to write
    .max_significant_digits(num::NonZeroUsize::new(5))
    // build the options, panicking if they're invalid
    .build_strict();
const TRUNCATE_SIZE: usize = TRUNCATE.buffer_size_const::<f64, STANDARD>();
let mut buffer = [0u8; TRUNCATE_SIZE];
let digits = value.to_lexical_with_options::<STANDARD>(&mut buffer, &TRUNCATE);
assert_eq!(str::from_utf8(digits), Ok("1.2345"));

// rounding
const ROUND: Options = Options::builder()
    // round to the nearest number when writing less digits than present
    .round_mode(RoundMode::Round)
    // the maximum number of significant digits to write
    .max_significant_digits(num::NonZeroUsize::new(5))
    // build the options, panicking if they're invalid
    .build_strict();
const ROUND_SIZE: usize = ROUND.buffer_size_const::<f64, STANDARD>();
let mut buffer = [0u8; ROUND_SIZE];
let digits = value.to_lexical_with_options::<STANDARD>(&mut buffer, &ROUND);
assert_eq!(str::from_utf8(digits), Ok("1.2346"));
Source

pub const fn trim_floats(self, trim_floats: bool) -> OptionsBuilder

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. Defaults to false.

§Examples
use lexical_write_float::Options;

let builder = Options::builder()
    .trim_floats(true);
assert_eq!(builder.get_trim_floats(), true);
Source

pub const fn exponent(self, exponent: u8) -> OptionsBuilder

Set 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;

let builder = Options::builder()
    .exponent(b'^');
assert_eq!(builder.get_exponent(), b'^');
Source

pub const fn decimal_point(self, decimal_point: u8) -> OptionsBuilder

Set 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;

let builder = Options::builder()
    .decimal_point(b'^');
assert_eq!(builder.get_decimal_point(), b'^');
Source

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

Set 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;

let builder = Options::builder()
    .nan_string(Some(b"nan"));
assert_eq!(builder.get_nan_string(), Some(b"nan".as_ref()));

Panics

Setting a value with more than 50 elements will panic at runtime. You should always build the format using build_strict or checking is_valid prior to using the format, to avoid unexpected panics.

Source

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

Set 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;

let builder = Options::builder()
    .inf_string(Some(b"infinity"));
assert_eq!(builder.get_inf_string(), Some(b"infinity".as_ref()));

Panics

Setting a value with more than 50 elements will panic at runtime. You should always build the format using build_strict or checking is_valid prior to using the format, to avoid unexpected panics.

Source

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

Set 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;

let builder = Options::builder()
    .infinity_string(Some(b"infinity"));
assert_eq!(builder.get_infinity_string(), Some(b"infinity".as_ref()));

Panics

Setting a value with more than 50 elements will panic at runtime. You should always build the format using build_strict or checking is_valid prior to using the format, to avoid unexpected panics.

Source

pub const fn is_valid(&self) -> bool

Check if the builder state is valid.

Source

pub const fn build_unchecked(&self) -> Options

Build the Options struct without validation.

This is completely safe, however, misusing this, especially the nan_string and inf_string representations could cause panics at runtime. Always use is_valid prior to using the built options.

Source

pub const fn build_strict(&self) -> Options

Build the Options struct, panicking if the builder is invalid.

§Panics

If the built options are not valid. This should always be used within a const context to avoid panics at runtime.

Source

pub const fn build(&self) -> Result<Options, Error>

Build the Options struct.

If the format is not valid, than an error is returned, otherwise, the successful value is returned.

Trait Implementations§

Source§

impl Clone for OptionsBuilder

Source§

fn clone(&self) -> OptionsBuilder

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 OptionsBuilder

Source§

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

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

impl Default for OptionsBuilder

Source§

fn default() -> OptionsBuilder

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

impl PartialEq for OptionsBuilder

Source§

fn eq(&self, other: &OptionsBuilder) -> 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 Eq for OptionsBuilder

Source§

impl StructuralPartialEq for OptionsBuilder

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.