jj_lib/fmt_util.rs
1// Copyright 2023 The Jujutsu Authors
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// https://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Common formatting helpers
16
17/// Find the smallest binary prefix with which the whole part of `x` is at most
18/// three digits, and return the scaled `x`, that prefix, and the associated
19/// base-1024 exponent.
20pub fn binary_prefix(x: f32) -> (f32, &'static str) {
21 /// Binary prefixes in ascending order, starting with the empty prefix. The
22 /// index of each prefix is the base-1024 exponent it represents.
23 const TABLE: [&str; 9] = ["", "Ki", "Mi", "Gi", "Ti", "Pi", "Ei", "Zi", "Yi"];
24
25 let mut i = 0;
26 let mut scaled = x;
27 while scaled.abs() >= 1000.0 && i < TABLE.len() - 1 {
28 i += 1;
29 scaled /= 1024.0;
30 }
31 (scaled, TABLE[i])
32}