-
Notifications
You must be signed in to change notification settings - Fork 43
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
fix: prevent infinite loop in readFromRadio function
- Loading branch information
1 parent
715e35d
commit 6c6326f
Showing
2 changed files
with
53 additions
and
28 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 |
---|---|---|
@@ -1,9 +1,34 @@ | ||
/** | ||
* Converts a `Uint8Array` to an `ArrayBuffer` | ||
* Converts a Uint8Array to an ArrayBuffer efficiently, with additional safety checks. | ||
* @param array - The Uint8Array to convert | ||
* @returns A new ArrayBuffer containing the Uint8Array data | ||
* @throws { TypeError } If input is not a Uint8Array | ||
*/ | ||
export const typedArrayToBuffer = (array: Uint8Array): ArrayBuffer => { | ||
if (!(array instanceof Uint8Array)) { | ||
throw new TypeError("Input must be a Uint8Array"); | ||
} | ||
|
||
if (array.byteLength === 0) { | ||
return new ArrayBuffer(0); | ||
} | ||
|
||
// Check if the buffer is shared | ||
if (array.buffer instanceof SharedArrayBuffer) { | ||
// Always create a new buffer for shared memory | ||
const newBuffer = new ArrayBuffer(array.byteLength); | ||
new Uint8Array(newBuffer).set(array); | ||
return newBuffer; | ||
} | ||
|
||
// If array uses the entire buffer and isn't offset, return it directly | ||
if (array.byteOffset === 0 && array.byteLength === array.buffer.byteLength) { | ||
return array.buffer; | ||
} | ||
|
||
// Otherwise, return a slice of the buffer containing just our data | ||
return array.buffer.slice( | ||
array.byteOffset, | ||
array.byteLength + array.byteOffset, | ||
array.byteOffset + array.byteLength, | ||
); | ||
}; |