@@ -2,7 +2,8 @@ import lcm from './lcm'
2
2
import WeakMap from 'weak-map'
3
3
4
4
const propMap = new WeakMap ( )
5
- const bitsPerByte = 8
5
+
6
+ const BITS_PER_BYTE = 8
6
7
7
8
export default class CharSet {
8
9
constructor ( chars ) {
@@ -28,7 +29,7 @@ export default class CharSet {
28
29
bitsPerChar,
29
30
length,
30
31
ndxFn : _ndxFn ( bitsPerChar ) ,
31
- charsPerChunk : lcm ( bitsPerChar , bitsPerByte ) / bitsPerChar
32
+ charsPerChunk : lcm ( bitsPerChar , BITS_PER_BYTE ) / bitsPerChar
32
33
}
33
34
propMap . set ( this , privProps )
34
35
}
@@ -57,38 +58,44 @@ export default class CharSet {
57
58
return propMap . get ( this ) . ndxFn
58
59
}
59
60
61
+ bytesNeeded ( entropyBits ) {
62
+ const count = Math . ceil ( entropyBits / this . bitsPerChar ( ) )
63
+ return Math . ceil ( count * this . bitsPerChar ( ) / BITS_PER_BYTE )
64
+ }
65
+
60
66
// Aliases
61
67
chars ( ) { return this . getChars ( ) }
62
68
ndxFn ( ) { return this . getNdxFn ( ) }
69
+ bitsPerChar ( ) { return this . getBitsPerChar ( ) }
63
70
}
64
71
65
72
const _ndxFn = ( bitsPerChar ) => {
66
- // If bitsPerBytes is a multiple of bitsPerChar, we can slice off an integer number
73
+ // If BITS_PER_BYTEs is a multiple of bitsPerChar, we can slice off an integer number
67
74
// of chars per byte.
68
- if ( lcm ( bitsPerChar , bitsPerByte ) === bitsPerByte ) {
75
+ if ( lcm ( bitsPerChar , BITS_PER_BYTE ) === BITS_PER_BYTE ) {
69
76
return function ( chunk , slice , bytes ) {
70
77
let lShift = bitsPerChar
71
- let rShift = bitsPerByte - bitsPerChar
78
+ let rShift = BITS_PER_BYTE - bitsPerChar
72
79
return ( ( bytes [ chunk ] << ( lShift * slice ) ) & 0xff ) >> rShift
73
80
}
74
81
}
75
82
// Otherwise, while slicing off bits per char, we will possibly straddle a couple
76
83
// of bytes, so a bit more work is involved
77
84
else {
78
85
return function ( chunk , slice , bytes ) {
79
- let slicesPerChunk = lcm ( bitsPerChar , bitsPerByte ) / bitsPerByte
86
+ let slicesPerChunk = lcm ( bitsPerChar , BITS_PER_BYTE ) / BITS_PER_BYTE
80
87
let bNum = chunk * slicesPerChunk
81
88
82
- let offset = ( slice * bitsPerChar ) / bitsPerByte
89
+ let offset = ( slice * bitsPerChar ) / BITS_PER_BYTE
83
90
let lOffset = Math . floor ( offset )
84
91
let rOffset = Math . ceil ( offset )
85
92
86
- let rShift = bitsPerByte - bitsPerChar
87
- let lShift = ( slice * bitsPerChar ) % bitsPerByte
93
+ let rShift = BITS_PER_BYTE - bitsPerChar
94
+ let lShift = ( slice * bitsPerChar ) % BITS_PER_BYTE
88
95
89
96
let ndx = ( ( bytes [ bNum + lOffset ] << lShift ) & 0xff ) >> rShift
90
97
91
- let rShiftIt = ( ( rOffset + 1 ) * bitsPerByte - ( slice + 1 ) * bitsPerChar ) % bitsPerByte
98
+ let rShiftIt = ( ( rOffset + 1 ) * BITS_PER_BYTE - ( slice + 1 ) * bitsPerChar ) % BITS_PER_BYTE
92
99
if ( rShift < rShiftIt ) {
93
100
ndx += bytes [ bNum + rOffset ] >> rShiftIt
94
101
}
0 commit comments