Skip to content

Simplify format_integer_with_underscore_sep #141369

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 17 additions & 36 deletions src/librustdoc/clean/utils.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use std::assert_matches::debug_assert_matches;
use std::fmt::{self, Display, Write as _};
use std::mem;
use std::sync::LazyLock as Lazy;
use std::{ascii, mem};

use rustc_ast::tokenstream::TokenTree;
use rustc_hir::def::{DefKind, Res};
@@ -24,7 +24,7 @@ use crate::clean::{
clean_middle_ty, inline,
};
use crate::core::DocContext;
use crate::display::Joined as _;
use crate::display::{Joined as _, MaybeDisplay as _};

#[cfg(test)]
mod tests;
@@ -254,14 +254,7 @@ pub(crate) fn qpath_to_string(p: &hir::QPath<'_>) -> String {
fmt::from_fn(|f| {
segments
.iter()
.map(|seg| {
fmt::from_fn(|f| {
if seg.ident.name != kw::PathRoot {
write!(f, "{}", seg.ident)?;
}
Ok(())
})
})
.map(|seg| (seg.ident.name != kw::PathRoot).then_some(seg.ident).maybe_display())
.joined("::", f)
})
.to_string()
@@ -391,30 +384,12 @@ pub(crate) fn print_evaluated_const(
})
}

fn format_integer_with_underscore_sep(num: &str) -> String {
let num_chars: Vec<_> = num.chars().collect();
let mut num_start_index = if num_chars.first() == Some(&'-') { 1 } else { 0 };
let chunk_size = match &num.as_bytes()[num_start_index..] {
[b'0', b'b' | b'x', ..] => {
num_start_index += 2;
4
}
[b'0', b'o', ..] => {
num_start_index += 2;
let remaining_chars = num_chars.len() - num_start_index;
if remaining_chars <= 6 {
// don't add underscores to Unix permissions like 0755 or 100755
return num.to_string();
}
3
}
_ => 3,
};

num_chars[..num_start_index]
.iter()
.chain(num_chars[num_start_index..].rchunks(chunk_size).rev().intersperse(&['_']).flatten())
.collect()
fn format_integer_with_underscore_sep(num: u128, is_negative: bool) -> String {
let num = num.to_string();
let chars = num.as_ascii().unwrap();
let mut result = if is_negative { "-".to_string() } else { String::new() };
result.extend(chars.rchunks(3).rev().intersperse(&[ascii::Char::LowLine]).flatten());
result
}

fn print_const_with_custom_print_scalar<'tcx>(
@@ -428,7 +403,10 @@ fn print_const_with_custom_print_scalar<'tcx>(
match (ct, ct.ty().kind()) {
(mir::Const::Val(mir::ConstValue::Scalar(int), _), ty::Uint(ui)) => {
let mut output = if with_underscores {
format_integer_with_underscore_sep(&int.to_string())
format_integer_with_underscore_sep(
int.assert_scalar_int().to_bits_unchecked(),
false,
)
} else {
int.to_string()
};
@@ -445,7 +423,10 @@ fn print_const_with_custom_print_scalar<'tcx>(
.size;
let sign_extended_data = int.assert_scalar_int().to_int(size);
let mut output = if with_underscores {
format_integer_with_underscore_sep(&sign_extended_data.to_string())
format_integer_with_underscore_sep(
sign_extended_data.unsigned_abs(),
sign_extended_data.is_negative(),
)
} else {
sign_extended_data.to_string()
};
42 changes: 6 additions & 36 deletions src/librustdoc/clean/utils/tests.rs
Original file line number Diff line number Diff line change
@@ -2,40 +2,10 @@ use super::*;

#[test]
fn int_format_decimal() {
assert_eq!(format_integer_with_underscore_sep("12345678"), "12_345_678");
assert_eq!(format_integer_with_underscore_sep("123"), "123");
assert_eq!(format_integer_with_underscore_sep("123459"), "123_459");
assert_eq!(format_integer_with_underscore_sep("-12345678"), "-12_345_678");
assert_eq!(format_integer_with_underscore_sep("-123"), "-123");
assert_eq!(format_integer_with_underscore_sep("-123459"), "-123_459");
}

#[test]
fn int_format_hex() {
assert_eq!(format_integer_with_underscore_sep("0xab3"), "0xab3");
assert_eq!(format_integer_with_underscore_sep("0xa2345b"), "0xa2_345b");
assert_eq!(format_integer_with_underscore_sep("0xa2e6345b"), "0xa2e6_345b");
assert_eq!(format_integer_with_underscore_sep("-0xab3"), "-0xab3");
assert_eq!(format_integer_with_underscore_sep("-0xa2345b"), "-0xa2_345b");
assert_eq!(format_integer_with_underscore_sep("-0xa2e6345b"), "-0xa2e6_345b");
}

#[test]
fn int_format_binary() {
assert_eq!(format_integer_with_underscore_sep("0o12345671"), "0o12_345_671");
assert_eq!(format_integer_with_underscore_sep("0o123"), "0o123");
assert_eq!(format_integer_with_underscore_sep("0o123451"), "0o123451");
assert_eq!(format_integer_with_underscore_sep("-0o12345671"), "-0o12_345_671");
assert_eq!(format_integer_with_underscore_sep("-0o123"), "-0o123");
assert_eq!(format_integer_with_underscore_sep("-0o123451"), "-0o123451");
}

#[test]
fn int_format_octal() {
assert_eq!(format_integer_with_underscore_sep("0b101"), "0b101");
assert_eq!(format_integer_with_underscore_sep("0b101101011"), "0b1_0110_1011");
assert_eq!(format_integer_with_underscore_sep("0b01101011"), "0b0110_1011");
assert_eq!(format_integer_with_underscore_sep("-0b101"), "-0b101");
assert_eq!(format_integer_with_underscore_sep("-0b101101011"), "-0b1_0110_1011");
assert_eq!(format_integer_with_underscore_sep("-0b01101011"), "-0b0110_1011");
assert_eq!(format_integer_with_underscore_sep(12345678, false), "12_345_678");
assert_eq!(format_integer_with_underscore_sep(123, false), "123");
assert_eq!(format_integer_with_underscore_sep(123459, false), "123_459");
assert_eq!(format_integer_with_underscore_sep(12345678, true), "-12_345_678");
assert_eq!(format_integer_with_underscore_sep(123, true), "-123");
assert_eq!(format_integer_with_underscore_sep(123459, true), "-123_459");
}
2 changes: 2 additions & 0 deletions src/librustdoc/lib.rs
Original file line number Diff line number Diff line change
@@ -3,6 +3,8 @@
html_playground_url = "https://play.rust-lang.org/"
)]
#![feature(rustc_private)]
#![feature(ascii_char)]
#![feature(ascii_char_variants)]
#![feature(assert_matches)]
#![feature(box_patterns)]
#![feature(debug_closure_helpers)]