Skip to content

Commit 3a6ba36

Browse files
committed
nostr: fix support for NIP-44 on no_std env
The `f64::log2` function is available only in the `std` library, so replace it to be compatible with no_std env. Pull-Request: #955 Signed-off-by: Yuki Kishimoto <[email protected]>
1 parent d7b4e22 commit 3a6ba36

File tree

2 files changed

+24
-2
lines changed

2 files changed

+24
-2
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -71,6 +71,7 @@
7171

7272
- keyring: fix keys persistence between OS restarts on Linux (https://github.com/rust-nostr/nostr/pull/942)
7373
- nostr: fix index out of bounds in `Tags::dedup` (https://github.com/rust-nostr/nostr/pull/949)
74+
- nostr: fix support for NIP-44 on no_std env (https://github.com/rust-nostr/nostr/pull/955)
7475

7576
### Removed
7677

crates/nostr/src/nips/nip44/v2.rs

Lines changed: 23 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -339,8 +339,8 @@ fn log2_round_down(x: usize) -> u32 {
339339
if x == 0 {
340340
0
341341
} else {
342-
let x: f64 = x as f64;
343-
x.log2().floor() as u32
342+
// This is equivalent to floor(log2(x))
343+
(usize::BITS - 1) - x.leading_zeros()
344344
}
345345
}
346346

@@ -390,6 +390,27 @@ mod tests {
390390
bytes
391391
}
392392

393+
// Check if out manual implementation work in the same way as the std one.
394+
#[test]
395+
fn test_log2_round_down() {
396+
let f = |x: usize| -> u32 {
397+
let x: f64 = x as f64;
398+
x.log2().floor() as u32
399+
};
400+
401+
assert_eq!(log2_round_down(0), f(0));
402+
assert_eq!(log2_round_down(1), f(1));
403+
assert_eq!(log2_round_down(2), f(2));
404+
assert_eq!(log2_round_down(3), f(3));
405+
assert_eq!(log2_round_down(4), f(4));
406+
assert_eq!(log2_round_down(5), f(5));
407+
assert_eq!(log2_round_down(6), f(6));
408+
assert_eq!(log2_round_down(7), f(7));
409+
assert_eq!(log2_round_down(8), f(8));
410+
assert_eq!(log2_round_down(9), f(9));
411+
assert_eq!(log2_round_down(10), f(10));
412+
}
413+
393414
#[test]
394415
fn test_valid_get_conversation_key() {
395416
let json: serde_json::Value = serde_json::from_str(JSON_VECTORS).unwrap();

0 commit comments

Comments
 (0)