bson 6.2.0 → 6.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import { BSONError } from '../error';
2
+ import { tryReadBasicLatin } from './latin';
2
3
 
3
4
  type TextDecoder = {
4
5
  readonly encoding: string;
@@ -108,6 +109,10 @@ export const webByteUtils = {
108
109
  return new Uint8Array(size);
109
110
  },
110
111
 
112
+ allocateUnsafe(size: number): Uint8Array {
113
+ return webByteUtils.allocate(size);
114
+ },
115
+
111
116
  equals(a: Uint8Array, b: Uint8Array): boolean {
112
117
  if (a.byteLength !== b.byteLength) {
113
118
  return false;
@@ -168,21 +173,29 @@ export const webByteUtils = {
168
173
  return Array.from(uint8array, byte => byte.toString(16).padStart(2, '0')).join('');
169
174
  },
170
175
 
171
- fromUTF8(text: string): Uint8Array {
172
- return new TextEncoder().encode(text);
173
- },
176
+ toUTF8(uint8array: Uint8Array, start: number, end: number, fatal: boolean): string {
177
+ const basicLatin = end - start <= 20 ? tryReadBasicLatin(uint8array, start, end) : null;
178
+ if (basicLatin != null) {
179
+ return basicLatin;
180
+ }
174
181
 
175
- toUTF8(uint8array: Uint8Array, start: number, end: number): string {
176
- return new TextDecoder('utf8', { fatal: false }).decode(uint8array.slice(start, end));
182
+ if (fatal) {
183
+ try {
184
+ return new TextDecoder('utf8', { fatal }).decode(uint8array.slice(start, end));
185
+ } catch (cause) {
186
+ throw new BSONError('Invalid UTF-8 string in BSON document', { cause });
187
+ }
188
+ }
189
+ return new TextDecoder('utf8', { fatal }).decode(uint8array.slice(start, end));
177
190
  },
178
191
 
179
192
  utf8ByteLength(input: string): number {
180
- return webByteUtils.fromUTF8(input).byteLength;
193
+ return new TextEncoder().encode(input).byteLength;
181
194
  },
182
195
 
183
- encodeUTF8Into(buffer: Uint8Array, source: string, byteOffset: number): number {
184
- const bytes = webByteUtils.fromUTF8(source);
185
- buffer.set(bytes, byteOffset);
196
+ encodeUTF8Into(uint8array: Uint8Array, source: string, byteOffset: number): number {
197
+ const bytes = new TextEncoder().encode(source);
198
+ uint8array.set(bytes, byteOffset);
186
199
  return bytes.byteLength;
187
200
  },
188
201