perspective_viewer/utils/number_format.rs
1// ┏━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┓
2// ┃ ██████ ██████ ██████ █ █ █ █ █ █▄ ▀███ █ ┃
3// ┃ ▄▄▄▄▄█ █▄▄▄▄▄ ▄▄▄▄▄█ ▀▀▀▀▀█▀▀▀▀▀ █ ▀▀▀▀▀█ ████████▌▐███ ███▄ ▀█ █ ▀▀▀▀▀ ┃
4// ┃ █▀▀▀▀▀ █▀▀▀▀▀ █▀██▀▀ ▄▄▄▄▄ █ ▄▄▄▄▄█ ▄▄▄▄▄█ ████████▌▐███ █████▄ █ ▄▄▄▄▄ ┃
5// ┃ █ ██████ █ ▀█▄ █ ██████ █ ███▌▐███ ███████▄ █ ┃
6// ┣━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┫
7// ┃ Copyright (c) 2017, the Perspective Authors. ┃
8// ┃ ╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌╌ ┃
9// ┃ This file is part of the Perspective library, distributed under the terms ┃
10// ┃ of the [Apache License 2.0](https://www.apache.org/licenses/LICENSE-2.0). ┃
11// ┗━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━┛
12
13use std::sync::LazyLock;
14
15use js_sys::Intl;
16use perspective_js::json;
17use perspective_js::utils::global::navigator;
18use wasm_bindgen::JsValue;
19
20pub trait ToFormattedString {
21 fn to_formatted_string(&self) -> String;
22}
23
24struct UnsafeNumberFormat(Intl::NumberFormat);
25
26unsafe impl Send for UnsafeNumberFormat {}
27unsafe impl Sync for UnsafeNumberFormat {}
28
29static NUMBER_FORMAT: LazyLock<UnsafeNumberFormat> = LazyLock::new(|| {
30 let locale = navigator().languages();
31 let opts = json!({});
32 let number_format = Intl::NumberFormat::new(&locale, &opts);
33 UnsafeNumberFormat(number_format)
34});
35
36impl UnsafeNumberFormat {}
37
38impl ToFormattedString for u32 {
39 fn to_formatted_string(&self) -> String {
40 NUMBER_FORMAT
41 .0
42 .format()
43 .call1(&NUMBER_FORMAT.0, &JsValue::from_f64(*self as f64))
44 .unwrap()
45 .as_string()
46 .unwrap()
47 }
48}