Refactor next_i32 method to handle edge case

This commit is contained in:
shenjack-5600u 2024-05-02 12:19:07 +08:00
parent 05b99a609f
commit fe46122537
Signed by: shenjack
GPG Key ID: FDF9864E11C7E79F

View File

@ -165,21 +165,26 @@ impl RC4 {
} }
/// 生成 i32 随机数 /// 生成 i32 随机数
/// ```dart /// ```javascript
/// int nextInt(int max) { /// ax(a) {
/// int round = max ; /// // nextInt
/// int v = nextByte(); /// var n, round
/// if (a === 0) return 0
/// n = this.n()
/// round = a
/// do { /// do {
/// v = v <<8 | nextByte(); /// n = (n << 8 | this.n()) >>> 0
/// if (v >= max) { /// if (n >= a) n = C.JsInt.V(n, a)
/// v %= max; /// round = C.JsInt.am(round, 8)
/// } /// } while (round !== 0)
/// round >>= 6; /// return n
/// } while(round != 0);
/// return v;
/// } /// }
///
/// ``` /// ```
pub fn next_i32(&mut self, max: i32) -> i32 { pub fn next_i32(&mut self, max: i32) -> i32 {
if max == 0 {
return 0;
}
let mut round = max; let mut round = max;
let mut v = self.next_u8() as i32; let mut v = self.next_u8() as i32;
loop { loop {
@ -187,7 +192,8 @@ impl RC4 {
if v >= max { if v >= max {
v %= max; v %= max;
} }
round >>= 6; round >>= 8;
// rc4 lib 里是 6, md5.js( 继承的 R ) 里是 8
if round == 0 { if round == 0 {
break; break;
} }