@@ -23,26 +23,36 @@ module.exports = (() => {
23
23
}
24
24
} ) ( ) ;
25
25
26
+ const MAX_U8 = Math . pow ( 2 , 8 ) - 1 ;
27
+ const textEncoder = new TextEncoder ( ) ;
28
+ const toArrayBuffer = ( value ) => {
29
+ if ( typeof value === 'string' ) return textEncoder . encode ( value ) ;
30
+ else if ( ! value ) return new Uint8Array ( 0 ) ;
31
+ else return value ;
32
+ } ;
33
+
26
34
module . exports . DeclarativeResponse = class DeclarativeResponse {
27
35
constructor ( ) {
28
36
this . instructions = [ ] ;
29
37
}
30
38
31
- // Utility method to encode text and append instruction
32
- _appendInstruction ( opcode , ...text ) {
39
+ // Append instruction and 1-byte length values
40
+ _appendInstruction ( opcode , ...values ) {
33
41
this . instructions . push ( opcode ) ;
34
- text . forEach ( str => {
35
- const bytes = ( typeof str === 'string' ) ? new TextEncoder ( ) . encode ( str ) : str ;
36
- this . instructions . push ( bytes . length , ...bytes ) ;
42
+ values . forEach ( value => {
43
+ const arrayBuffer = toArrayBuffer ( value ) ;
44
+ const length = arrayBuffer . length ;
45
+ if ( length > MAX_U8 ) throw new RangeError ( 'Data length exceeds ' + MAX_U8 ) ;
46
+ this . instructions . push ( length , ...arrayBuffer ) ;
37
47
} ) ;
38
48
}
39
49
40
- // Utility method to append 2 -byte length text in little-endian format
41
- _appendInstructionWithLength ( opcode , text ) {
42
- this . instructions . push ( opcode ) ;
43
- const bytes = new TextEncoder ( ) . encode ( text ) ;
44
- const length = bytes . length ;
45
- this . instructions . push ( length & 0xff , ( length >> 8 ) & 0xff , ...bytes ) ;
50
+ // Append instruction and 4 -byte length value
51
+ _appendInstructionWithLength ( opcode , value ) {
52
+ const arrayBuffer = toArrayBuffer ( value ) ;
53
+ const lengthBuffer = new Buffer . alloc ( 4 ) ;
54
+ lengthBuffer . writeUInt32LE ( arrayBuffer . length ) ;
55
+ this . instructions . push ( opcode , ... lengthBuffer , ...arrayBuffer ) ;
46
56
}
47
57
48
58
writeHeader ( key , value ) { return this . _appendInstruction ( 1 , key , value ) , this ; }
@@ -51,11 +61,9 @@ module.exports.DeclarativeResponse = class DeclarativeResponse {
51
61
writeHeaderValue ( key ) { return this . _appendInstruction ( 4 , key ) , this ; }
52
62
write ( value ) { return this . _appendInstructionWithLength ( 5 , value ) , this ; }
53
63
writeParameterValue ( key ) { return this . _appendInstruction ( 6 , key ) , this ; }
54
-
64
+ writeStatus ( status ) { return this . _appendInstruction ( 7 , status ) , this ; }
55
65
end ( value ) {
56
- const bytes = new TextEncoder ( ) . encode ( value ) ;
57
- const length = bytes . length ;
58
- this . instructions . push ( 0 , length & 0xff , ( length >> 8 ) & 0xff , ...bytes ) ;
66
+ this . _appendInstructionWithLength ( 0 , value ) ;
59
67
return new Uint8Array ( this . instructions ) . buffer ;
60
68
}
61
69
}
0 commit comments