Skip to content
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

Fix negative BigInt formatting #4082

Merged
merged 4 commits into from
Aug 21, 2024
Merged
Changes from 1 commit
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
31 changes: 26 additions & 5 deletions crates/js-sys/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1387,6 +1387,15 @@ impl BigInt {
.pow(JsValue::as_ref(rhs))
.unchecked_into()
}

/// Returns the absolute value of this BigInt value.
fn abs(&self) -> Self {
if self >= &BigInt::from(0) {
self.clone()
} else {
-self
}
}
}

macro_rules! bigint_from {
Expand Down Expand Up @@ -1493,21 +1502,33 @@ impl fmt::Debug for BigInt {
impl fmt::Display for BigInt {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad_integral(self >= &BigInt::from(0), "", &self.to_string_unchecked(10))
f.pad_integral(
self >= &BigInt::from(0),
"",
&self.abs().to_string_unchecked(10),
)
ryangoree marked this conversation as resolved.
Show resolved Hide resolved
}
}

impl fmt::Binary for BigInt {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad_integral(self >= &BigInt::from(0), "0b", &self.to_string_unchecked(2))
f.pad_integral(
self >= &BigInt::from(0),
"0b",
&self.abs().to_string_unchecked(2),
)
}
}

impl fmt::Octal for BigInt {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.pad_integral(self >= &BigInt::from(0), "0o", &self.to_string_unchecked(8))
f.pad_integral(
self >= &BigInt::from(0),
"0o",
&self.abs().to_string_unchecked(8),
)
}
}

Expand All @@ -1517,15 +1538,15 @@ impl fmt::LowerHex for BigInt {
f.pad_integral(
self >= &BigInt::from(0),
"0x",
&self.to_string_unchecked(16),
&self.abs().to_string_unchecked(16),
)
}
}

impl fmt::UpperHex for BigInt {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut s: String = self.to_string_unchecked(16);
let mut s: String = self.abs().to_string_unchecked(16);
s.make_ascii_uppercase();
f.pad_integral(self >= &BigInt::from(0), "0x", &s)
}
Expand Down
Loading