-
Notifications
You must be signed in to change notification settings - Fork 14
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: create custom class to verify bitstring position more precisely. (…
- Loading branch information
1 parent
38de286
commit efb771d
Showing
2 changed files
with
60 additions
and
2 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,56 @@ | ||
|
||
export class Bitstring { | ||
bits: Uint8Array; | ||
length: number; | ||
leftToRightIndexing: boolean; | ||
|
||
constructor({ | ||
buffer, | ||
leftToRightIndexing | ||
}: { | ||
buffer: Uint8Array; | ||
leftToRightIndexing?: boolean; | ||
}) { | ||
if (!buffer) { | ||
throw new Error('Only one of "length" or "buffer" must be given.'); | ||
} | ||
this.bits = new Uint8Array(buffer.buffer); | ||
this.length = buffer.length * 8; | ||
this.leftToRightIndexing = leftToRightIndexing ?? false; | ||
} | ||
|
||
set(position: number, on: boolean): void { | ||
const { length, leftToRightIndexing } = this; | ||
const { index, bit } = _parsePosition(position, length, leftToRightIndexing); | ||
if (on) { | ||
this.bits[index] |= bit; | ||
} else { | ||
this.bits[index] &= 0xff ^ bit; | ||
} | ||
} | ||
|
||
get(position: number): boolean { | ||
const { length, leftToRightIndexing } = this; | ||
const { index, bit } = _parsePosition(position, length, leftToRightIndexing); | ||
return !!(this.bits[index] & bit); | ||
} | ||
|
||
|
||
} | ||
|
||
function _parsePosition( | ||
position: number, | ||
length: number, | ||
leftToRightIndexing: boolean | ||
): { index: number; bit: number } { | ||
if (position >= length) { | ||
throw new Error( | ||
`Position "${position}" is out of range "0-${length - 1}".` | ||
); | ||
} | ||
const index = Math.floor(position / 8); | ||
const rem = position % 8; | ||
const shift = leftToRightIndexing ? 7 - rem : rem; | ||
const bit = 1 << shift; | ||
return { index, bit }; | ||
} |
efb771d
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
JUnit