1
1
import { fromUtf8 } from "@smithy/util-utf8" ;
2
2
3
+ import { alloc } from "./cbor-types" ;
4
+
3
5
const USE_BUFFER = typeof Buffer !== "undefined" ;
4
6
const USE_TEXT_ENCODER = typeof TextEncoder !== "undefined" ;
5
7
@@ -13,8 +15,8 @@ type BufferWithUtf8Write = Buffer & {
13
15
*
14
16
*/
15
17
export class ByteVector {
16
- private data : Uint8Array = new Uint8Array ( ) ;
17
- private dataView : DataView = new DataView ( this . data . buffer , 0 , 0 ) ;
18
+ private data : Uint8Array = alloc ( 0 ) ;
19
+ private dataView : DataView = new DataView ( this . data . buffer , this . data . byteOffset , this . data . byteLength ) ;
18
20
private cursor : number = 0 ;
19
21
private textEncoder : TextEncoder | null = USE_TEXT_ENCODER ? new TextEncoder ( ) : null ;
20
22
@@ -88,12 +90,13 @@ export class ByteVector {
88
90
}
89
91
90
92
public toUint8Array ( ) : Uint8Array {
91
- const out = new Uint8Array ( this . cursor ) ;
93
+ const out = alloc ( this . cursor ) ;
92
94
out . set ( this . data . subarray ( 0 , this . cursor ) , 0 ) ;
93
95
this . cursor = 0 ;
94
96
if ( this . data . length > this . initialSize ) {
95
- this . data = new Uint8Array ( this . initialSize ) ;
96
- this . dataView = new DataView ( this . data . buffer , 0 , this . initialSize ) ;
97
+ this . data = alloc ( this . initialSize ) ;
98
+ const { buffer, byteOffset, byteLength } = this . data ;
99
+ this . dataView = new DataView ( buffer , byteOffset , byteLength ) ;
97
100
}
98
101
return out ;
99
102
}
@@ -109,11 +112,12 @@ export class ByteVector {
109
112
// eslint-disable-next-line @typescript-eslint/no-unused-vars
110
113
private resize ( size : number ) {
111
114
const data = this . data ;
112
- this . data = USE_BUFFER ? Buffer . allocUnsafeSlow ( size ) : new Uint8Array ( size ) ;
115
+ this . data = alloc ( size ) ;
113
116
if ( data ) {
114
117
this . data . set ( data , 0 ) ;
115
118
}
116
- this . dataView = new DataView ( this . data . buffer , 0 , size ) ;
119
+ const { buffer, byteOffset, byteLength } = this . data ;
120
+ this . dataView = new DataView ( buffer , byteOffset , byteLength ) ;
117
121
}
118
122
}
119
123
0 commit comments