← std

std/float.kur

//! Floating-point numbers from text. They are read through C's `strtod`,
//! which rounds a decimal to the nearest double correctly (ties to even) and to an infinity
//! past the largest one. The view is read through whatever capability
//! permits it (`Exclusive!`, `Shared!`, `StaticRead`).
use package as std;

use alloc::buffer::Buffer!;
use core::fmt::Writer;
use core::ascii::is_space;
use core::mem::alloca;
use core::option::Option;
use core::ptr::offset;
use core::slice::{ReadBytes, byte_or_zero};
use libc::float::strtod;

/// The double that all of `bytes` spells, as `strtod` reads it in the C
/// locale: a decimal such as `-2.5e3` or `.5`, a hexadecimal float such as
/// `0x1p-3`, `inf` or `nan`. Nothing for an empty view, a leading space, or
/// any byte past the number (a NUL among them).
///
/// A process starts in the C locale and the library never changes it, so
/// the decimal point is `.`; foreign code that calls `setlocale` (for
/// `LC_NUMERIC`) changes what `strtod` reads, and calling it while another
/// thread parses here is a data race in C.
forall C, S where ReadBytes[C, S], Copy[S].
fn parse_f64(&cx: C, bytes: S) -> Option[f64] {
    if ReadBytes[C, S]::len(&cx, bytes) == 0usize || is_space(byte_or_zero(&cx, bytes, 0usize)) {
        return Option::None;
    }
    var digits = Buffer!::new().write(&cx, bytes).write_byte(0u8);
    let start = unsafe &digits.as_ptr();
    // The bytes copied, before the NUL: the number must end where they do.
    let n = &digits.len() - 1usize;
    let end = unsafe alloca[*u8]();
    unsafe *end = start;
    let value = unsafe strtod(start, end);
    let whole = unsafe (unsafe *end as usize) == unsafe (unsafe offset(start, n) as usize);
    digits.destroy();
    if whole {
        Option::Some.(value)
    } else {
        Option::None
    }
}