Skip to content

Commit c154b8f

Browse files
nice thousands separator
1 parent 83ce1a1 commit c154b8f

3 files changed

Lines changed: 42 additions & 1 deletion

File tree

language-server/src/code_action.rs

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13156,8 +13156,10 @@ impl<'a> ConvertIntToDifferentBase<'a> {
1315613156
let converted_number = match base {
1315713157
Base::Binary => format!("{minus}0b{:b}", int),
1315813158
Base::Octal => format!("{minus}0o{:o}", int),
13159-
Base::Decimal => format!("{minus}{}", int),
1316013159
Base::Hexadecimal => format!("{minus}0x{:x}", int),
13160+
Base::Decimal => {
13161+
format!("{minus}{}", format_int_with_thousands_separator(&int))
13162+
}
1316113163
};
1316213164
let title = format!("Convert to `{converted_number}`");
1316313165
self.edits.replace(location, converted_number);
@@ -13175,6 +13177,25 @@ impl<'a> ConvertIntToDifferentBase<'a> {
1317513177
}
1317613178
}
1317713179

13180+
fn format_int_with_thousands_separator(int: &BigInt) -> String {
13181+
if int <= &BigInt::from(9999) {
13182+
return int.to_string();
13183+
}
13184+
13185+
// We get chunks of three digits. If we start from 1234567
13186+
// we will have `765`, `432`, `1`
13187+
(int.to_string().chars().rev().chunks(3).into_iter())
13188+
// Each chunk is turned into a string and those are joined with a
13189+
// separator.
13190+
.map(|chunk| chunk.collect::<EcoString>())
13191+
.join("_")
13192+
// And finally reverse everything to bring it back to normal, the number
13193+
// is spelled in reverse right now!
13194+
.chars()
13195+
.rev()
13196+
.collect()
13197+
}
13198+
1317813199
impl<'ast> ast::visit::Visit<'ast> for ConvertIntToDifferentBase<'ast> {
1317913200
fn visit_typed_function(&mut self, fun: &'ast TypedFunction) {
1318013201
// We skip all the functions the cursor is not inside of.

language-server/src/tests/action.rs

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15816,3 +15816,12 @@ fn convert_negative_int_hexadecimal_to_decimal() {
1581615816
find_position_of("0x6f").to_selection()
1581715817
);
1581815818
}
15819+
15820+
#[test]
15821+
fn convert_to_int_has_nicely_separated_digits() {
15822+
assert_code_action!(
15823+
"Convert to `1_234_567`",
15824+
"pub fn main() { 0b100101101011010000111 }",
15825+
find_position_of("0b100101101011010000111").to_selection()
15826+
);
15827+
}
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
---
2+
source: language-server/src/tests/action.rs
3+
expression: "pub fn main() { 0b100101101011010000111 }"
4+
---
5+
----- BEFORE ACTION
6+
pub fn main() { 0b100101101011010000111 }
7+
8+
9+
10+
----- AFTER ACTION
11+
pub fn main() { 1_234_567 }

0 commit comments

Comments
 (0)