forked from datastax/nodejs-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathencoder.js
2015 lines (1846 loc) · 60.8 KB
/
encoder.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright DataStax, Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
'use strict';
const util = require('util');
const types = require('./types');
const dataTypes = types.dataTypes;
const Long = types.Long;
const Integer = types.Integer;
const BigDecimal = types.BigDecimal;
const MutableLong = require('./types/mutable-long');
const utils = require('./utils');
const token = require('./token');
const { DateRange } = require('./datastax/search');
const geo = require('./geometry');
const Geometry = geo.Geometry;
const LineString = geo.LineString;
const Point = geo.Point;
const Polygon = geo.Polygon;
const uuidRegex = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
const buffers = {
int16Zero: utils.allocBufferFromArray([0, 0]),
int32Zero: utils.allocBufferFromArray([0, 0, 0, 0]),
int8Zero: utils.allocBufferFromArray([0]),
int8One: utils.allocBufferFromArray([1]),
int8MaxValue: utils.allocBufferFromArray([0xff])
};
// BigInt: Avoid using literals (e.g., 32n) as we must be able to compile with older engines
const isBigIntSupported = typeof BigInt !== 'undefined';
const bigInt32 = isBigIntSupported ? BigInt(32) : null;
const bigInt8 = isBigIntSupported ? BigInt(8) : null;
const bigInt0 = isBigIntSupported ? BigInt(0) : null;
const bigIntMinus1 = isBigIntSupported ? BigInt(-1) : null;
const bigInt32BitsOn = isBigIntSupported ? BigInt(0xffffffff) : null;
const bigInt8BitsOn = isBigIntSupported ? BigInt(0xff) : null;
const complexTypeNames = Object.freeze({
list : 'org.apache.cassandra.db.marshal.ListType',
set : 'org.apache.cassandra.db.marshal.SetType',
map : 'org.apache.cassandra.db.marshal.MapType',
udt : 'org.apache.cassandra.db.marshal.UserType',
tuple : 'org.apache.cassandra.db.marshal.TupleType',
frozen : 'org.apache.cassandra.db.marshal.FrozenType',
reversed : 'org.apache.cassandra.db.marshal.ReversedType',
composite : 'org.apache.cassandra.db.marshal.CompositeType',
empty : 'org.apache.cassandra.db.marshal.EmptyType',
collection: 'org.apache.cassandra.db.marshal.ColumnToCollectionType'
});
const cqlNames = Object.freeze({
frozen: 'frozen',
list: 'list',
'set': 'set',
map: 'map',
tuple: 'tuple',
empty: 'empty',
duration: 'duration',
vector: 'vector'
});
const singleTypeNames = Object.freeze({
'org.apache.cassandra.db.marshal.UTF8Type': dataTypes.varchar,
'org.apache.cassandra.db.marshal.AsciiType': dataTypes.ascii,
'org.apache.cassandra.db.marshal.UUIDType': dataTypes.uuid,
'org.apache.cassandra.db.marshal.TimeUUIDType': dataTypes.timeuuid,
'org.apache.cassandra.db.marshal.Int32Type': dataTypes.int,
'org.apache.cassandra.db.marshal.BytesType': dataTypes.blob,
'org.apache.cassandra.db.marshal.FloatType': dataTypes.float,
'org.apache.cassandra.db.marshal.DoubleType': dataTypes.double,
'org.apache.cassandra.db.marshal.BooleanType': dataTypes.boolean,
'org.apache.cassandra.db.marshal.InetAddressType': dataTypes.inet,
'org.apache.cassandra.db.marshal.SimpleDateType': dataTypes.date,
'org.apache.cassandra.db.marshal.TimeType': dataTypes.time,
'org.apache.cassandra.db.marshal.ShortType': dataTypes.smallint,
'org.apache.cassandra.db.marshal.ByteType': dataTypes.tinyint,
'org.apache.cassandra.db.marshal.DateType': dataTypes.timestamp,
'org.apache.cassandra.db.marshal.TimestampType': dataTypes.timestamp,
'org.apache.cassandra.db.marshal.LongType': dataTypes.bigint,
'org.apache.cassandra.db.marshal.DecimalType': dataTypes.decimal,
'org.apache.cassandra.db.marshal.IntegerType': dataTypes.varint,
'org.apache.cassandra.db.marshal.CounterColumnType': dataTypes.counter
});
const singleTypeNamesByDataType = invertObject(singleTypeNames);
const singleFqTypeNamesLength = Object.keys(singleTypeNames).reduce(function (previous, current) {
return current.length > previous ? current.length : previous;
}, 0);
const customTypeNames = Object.freeze({
duration: 'org.apache.cassandra.db.marshal.DurationType',
lineString: 'org.apache.cassandra.db.marshal.LineStringType',
point: 'org.apache.cassandra.db.marshal.PointType',
polygon: 'org.apache.cassandra.db.marshal.PolygonType',
dateRange: 'org.apache.cassandra.db.marshal.DateRangeType',
vector: 'org.apache.cassandra.db.marshal.VectorType'
});
const nullValueBuffer = utils.allocBufferFromArray([255, 255, 255, 255]);
const unsetValueBuffer = utils.allocBufferFromArray([255, 255, 255, 254]);
/**
* For backwards compatibility, empty buffers as text/blob/custom values are supported.
* In the case of other types, they are going to be decoded as a <code>null</code> value.
* @private
* @type {Set}
*/
const zeroLengthTypesSupported = new Set([
dataTypes.text,
dataTypes.ascii,
dataTypes.varchar,
dataTypes.custom,
dataTypes.blob
]);
/**
* Serializes and deserializes to and from a CQL type and a Javascript Type.
* @param {Number} protocolVersion
* @param {ClientOptions} options
* @constructor
*/
function Encoder(protocolVersion, options) {
this.encodingOptions = options.encoding || utils.emptyObject;
defineInstanceMembers.call(this);
this.setProtocolVersion(protocolVersion);
setEncoders.call(this);
if (this.encodingOptions.copyBuffer) {
this.handleBuffer = handleBufferCopy;
}
else {
this.handleBuffer = handleBufferRef;
}
}
/**
* Declares the privileged instance members.
* @private
*/
function defineInstanceMembers() {
/**
* Sets the protocol version and the encoding/decoding methods depending on the protocol version
* @param {Number} value
* @ignore
* @internal
*/
this.setProtocolVersion = function (value) {
this.protocolVersion = value;
//Set the collection serialization based on the protocol version
this.decodeCollectionLength = decodeCollectionLengthV3;
this.getLengthBuffer = getLengthBufferV3;
this.collectionLengthSize = 4;
if (!types.protocolVersion.uses4BytesCollectionLength(this.protocolVersion)) {
this.decodeCollectionLength = decodeCollectionLengthV2;
this.getLengthBuffer = getLengthBufferV2;
this.collectionLengthSize = 2;
}
};
const customDecoders = {
[customTypeNames.duration]: decodeDuration,
[customTypeNames.lineString]: decodeLineString,
[customTypeNames.point]: decodePoint,
[customTypeNames.polygon]: decodePolygon,
[customTypeNames.dateRange]: decodeDateRange
};
const customEncoders = {
[customTypeNames.duration]: encodeDuration,
[customTypeNames.lineString]: encodeLineString,
[customTypeNames.point]: encodePoint,
[customTypeNames.polygon]: encodePolygon,
[customTypeNames.dateRange]: encodeDateRange
};
// Decoding methods
this.decodeBlob = function (bytes) {
return this.handleBuffer(bytes);
};
this.decodeCustom = function (bytes, typeName) {
// Make sure we actually have something to process in typeName before we go any further
if (!typeName || typeName.length === 0) {
return this.handleBuffer(bytes);
}
// Special handling for vector custom types (since they have args)
if (typeName.startsWith(customTypeNames.vector)) {
return this.decodeVector(bytes, this.parseVectorTypeArgs(typeName, customTypeNames.vector, this.parseFqTypeName));
}
const handler = customDecoders[typeName];
if (handler) {
return handler.call(this, bytes);
}
return this.handleBuffer(bytes);
};
this.decodeUtf8String = function (bytes) {
return bytes.toString('utf8');
};
this.decodeAsciiString = function (bytes) {
return bytes.toString('ascii');
};
this.decodeBoolean = function (bytes) {
return !!bytes.readUInt8(0);
};
this.decodeDouble = function (bytes) {
return bytes.readDoubleBE(0);
};
this.decodeFloat = function (bytes) {
return bytes.readFloatBE(0);
};
this.decodeInt = function (bytes) {
return bytes.readInt32BE(0);
};
this.decodeSmallint = function (bytes) {
return bytes.readInt16BE(0);
};
this.decodeTinyint = function (bytes) {
return bytes.readInt8(0);
};
this._decodeCqlLongAsLong = function (bytes) {
return Long.fromBuffer(bytes);
};
this._decodeCqlLongAsBigInt = function (bytes) {
return BigInt.asIntN(64, (BigInt(bytes.readUInt32BE(0)) << bigInt32) | BigInt(bytes.readUInt32BE(4)));
};
this.decodeLong = this.encodingOptions.useBigIntAsLong
? this._decodeCqlLongAsBigInt
: this._decodeCqlLongAsLong;
this._decodeVarintAsInteger = function (bytes) {
return Integer.fromBuffer(bytes);
};
this._decodeVarintAsBigInt = function decodeVarintAsBigInt(bytes) {
let result = bigInt0;
if (bytes[0] <= 0x7f) {
for (let i = 0; i < bytes.length; i++) {
const b = BigInt(bytes[bytes.length - 1 - i]);
result = result | (b << BigInt(i * 8));
}
} else {
for (let i = 0; i < bytes.length; i++) {
const b = BigInt(bytes[bytes.length - 1 - i]);
result = result | ((~b & bigInt8BitsOn) << BigInt(i * 8));
}
result = ~result;
}
return result;
};
this.decodeVarint = this.encodingOptions.useBigIntAsVarint
? this._decodeVarintAsBigInt
: this._decodeVarintAsInteger;
this.decodeDecimal = function(bytes) {
return BigDecimal.fromBuffer(bytes);
};
this.decodeTimestamp = function(bytes) {
return new Date(this._decodeCqlLongAsLong(bytes).toNumber());
};
this.decodeDate = function (bytes) {
return types.LocalDate.fromBuffer(bytes);
};
this.decodeTime = function (bytes) {
return types.LocalTime.fromBuffer(bytes);
};
/*
* Reads a list from bytes
*/
this.decodeList = function (bytes, subtype) {
const totalItems = this.decodeCollectionLength(bytes, 0);
let offset = this.collectionLengthSize;
const list = new Array(totalItems);
for (let i = 0; i < totalItems; i++) {
//bytes length of the item
const length = this.decodeCollectionLength(bytes, offset);
offset += this.collectionLengthSize;
//slice it
list[i] = this.decode(bytes.slice(offset, offset+length), subtype);
offset += length;
}
return list;
};
/*
* Reads a Set from bytes
*/
this.decodeSet = function (bytes, subtype) {
const arr = this.decodeList(bytes, subtype);
if (this.encodingOptions.set) {
const setConstructor = this.encodingOptions.set;
return new setConstructor(arr);
}
return arr;
};
/*
* Reads a map (key / value) from bytes
*/
this.decodeMap = function (bytes, subtypes) {
let map;
const totalItems = this.decodeCollectionLength(bytes, 0);
let offset = this.collectionLengthSize;
const self = this;
function readValues(callback, thisArg) {
for (let i = 0; i < totalItems; i++) {
const keyLength = self.decodeCollectionLength(bytes, offset);
offset += self.collectionLengthSize;
const key = self.decode(bytes.slice(offset, offset + keyLength), subtypes[0]);
offset += keyLength;
const valueLength = self.decodeCollectionLength(bytes, offset);
offset += self.collectionLengthSize;
if (valueLength < 0) {
callback.call(thisArg, key, null);
continue;
}
const value = self.decode(bytes.slice(offset, offset + valueLength), subtypes[1]);
offset += valueLength;
callback.call(thisArg, key, value);
}
}
if (this.encodingOptions.map) {
const mapConstructor = this.encodingOptions.map;
map = new mapConstructor();
readValues(map.set, map);
}
else {
map = {};
readValues(function (key, value) {
map[key] = value;
});
}
return map;
};
this.decodeUuid = function (bytes) {
return new types.Uuid(this.handleBuffer(bytes));
};
this.decodeTimeUuid = function (bytes) {
return new types.TimeUuid(this.handleBuffer(bytes));
};
this.decodeInet = function (bytes) {
return new types.InetAddress(this.handleBuffer(bytes));
};
/**
* Decodes a user defined type into an object
* @param {Buffer} bytes
* @param {{fields: Array}} udtInfo
* @private
*/
this.decodeUdt = function (bytes, udtInfo) {
const result = {};
let offset = 0;
for (let i = 0; i < udtInfo.fields.length && offset < bytes.length; i++) {
//bytes length of the field value
const length = bytes.readInt32BE(offset);
offset += 4;
//slice it
const field = udtInfo.fields[i];
if (length < 0) {
result[field.name] = null;
continue;
}
result[field.name] = this.decode(bytes.slice(offset, offset+length), field.type);
offset += length;
}
return result;
};
this.decodeTuple = function (bytes, tupleInfo) {
const elements = new Array(tupleInfo.length);
let offset = 0;
for (let i = 0; i < tupleInfo.length && offset < bytes.length; i++) {
const length = bytes.readInt32BE(offset);
offset += 4;
if (length < 0) {
elements[i] = null;
continue;
}
elements[i] = this.decode(bytes.slice(offset, offset+length), tupleInfo[i]);
offset += length;
}
return types.Tuple.fromArray(elements);
};
//Encoding methods
this.encodeFloat = function (value) {
if (typeof value === 'string') {
// All numeric types are supported as strings for historical reasons
value = parseFloat(value);
if (Number.isNaN(value)) {
throw new TypeError(`Expected string representation of a number, obtained ${util.inspect(value)}`);
}
}
if (typeof value !== 'number') {
throw new TypeError('Expected Number, obtained ' + util.inspect(value));
}
const buf = utils.allocBufferUnsafe(4);
buf.writeFloatBE(value, 0);
return buf;
};
this.encodeDouble = function (value) {
if (typeof value === 'string') {
// All numeric types are supported as strings for historical reasons
value = parseFloat(value);
if (Number.isNaN(value)) {
throw new TypeError(`Expected string representation of a number, obtained ${util.inspect(value)}`);
}
}
if (typeof value !== 'number') {
throw new TypeError('Expected Number, obtained ' + util.inspect(value));
}
const buf = utils.allocBufferUnsafe(8);
buf.writeDoubleBE(value, 0);
return buf;
};
/**
* @param {Date|String|Long|Number} value
* @private
*/
this.encodeTimestamp = function (value) {
const originalValue = value;
if (typeof value === 'string') {
value = new Date(value);
}
if (value instanceof Date) {
//milliseconds since epoch
value = value.getTime();
if (isNaN(value)) {
throw new TypeError('Invalid date: ' + originalValue);
}
}
if (this.encodingOptions.useBigIntAsLong) {
value = BigInt(value);
}
return this.encodeLong(value);
};
/**
* @param {Date|String|LocalDate} value
* @returns {Buffer}
* @throws {TypeError}
* @private
*/
this.encodeDate = function (value) {
const originalValue = value;
try {
if (typeof value === 'string') {
value = types.LocalDate.fromString(value);
}
if (value instanceof Date) {
value = types.LocalDate.fromDate(value);
}
}
catch (err) {
//Wrap into a TypeError
throw new TypeError('LocalDate could not be parsed ' + err);
}
if (!(value instanceof types.LocalDate)) {
throw new TypeError('Expected Date/String/LocalDate, obtained ' + util.inspect(originalValue));
}
return value.toBuffer();
};
/**
* @param {String|LocalDate} value
* @returns {Buffer}
* @throws {TypeError}
* @private
*/
this.encodeTime = function (value) {
const originalValue = value;
try {
if (typeof value === 'string') {
value = types.LocalTime.fromString(value);
}
}
catch (err) {
//Wrap into a TypeError
throw new TypeError('LocalTime could not be parsed ' + err);
}
if (!(value instanceof types.LocalTime)) {
throw new TypeError('Expected String/LocalTime, obtained ' + util.inspect(originalValue));
}
return value.toBuffer();
};
/**
* @param {Uuid|String|Buffer} value
* @private
*/
this.encodeUuid = function (value) {
if (typeof value === 'string') {
try {
value = types.Uuid.fromString(value).getBuffer();
}
catch (err) {
throw new TypeError(err.message);
}
} else if (value instanceof types.Uuid) {
value = value.getBuffer();
} else {
throw new TypeError('Not a valid Uuid, expected Uuid/String/Buffer, obtained ' + util.inspect(value));
}
return value;
};
/**
* @param {String|InetAddress|Buffer} value
* @returns {Buffer}
* @private
*/
this.encodeInet = function (value) {
if (typeof value === 'string') {
value = types.InetAddress.fromString(value);
}
if (value instanceof types.InetAddress) {
value = value.getBuffer();
}
if (!(value instanceof Buffer)) {
throw new TypeError('Not a valid Inet, expected InetAddress/Buffer, obtained ' + util.inspect(value));
}
return value;
};
/**
* @param {Long|Buffer|String|Number} value
* @private
*/
this._encodeBigIntFromLong = function (value) {
if (typeof value === 'number') {
value = Long.fromNumber(value);
} else if (typeof value === 'string') {
value = Long.fromString(value);
}
let buf = null;
if (value instanceof Long) {
buf = Long.toBuffer(value);
} else if (value instanceof MutableLong) {
buf = Long.toBuffer(value.toImmutable());
}
if (buf === null) {
throw new TypeError('Not a valid bigint, expected Long/Number/String/Buffer, obtained ' + util.inspect(value));
}
return buf;
};
this._encodeBigIntFromBigInt = function (value) {
if (typeof value === 'string') {
// All numeric types are supported as strings for historical reasons
value = BigInt(value);
}
// eslint-disable-next-line valid-typeof
if (typeof value !== 'bigint') {
// Only BigInt values are supported
throw new TypeError('Not a valid BigInt value, obtained ' + util.inspect(value));
}
const buffer = utils.allocBufferUnsafe(8);
buffer.writeUInt32BE(Number(value >> bigInt32) >>> 0, 0);
buffer.writeUInt32BE(Number(value & bigInt32BitsOn), 4);
return buffer;
};
this.encodeLong = this.encodingOptions.useBigIntAsLong
? this._encodeBigIntFromBigInt
: this._encodeBigIntFromLong;
/**
* @param {Integer|Buffer|String|Number} value
* @returns {Buffer}
* @private
*/
this._encodeVarintFromInteger = function (value) {
if (typeof value === 'number') {
value = Integer.fromNumber(value);
}
if (typeof value === 'string') {
value = Integer.fromString(value);
}
let buf = null;
if (value instanceof Buffer) {
buf = value;
}
if (value instanceof Integer) {
buf = Integer.toBuffer(value);
}
if (buf === null) {
throw new TypeError('Not a valid varint, expected Integer/Number/String/Buffer, obtained ' + util.inspect(value));
}
return buf;
};
this._encodeVarintFromBigInt = function (value) {
if (typeof value === 'string') {
// All numeric types are supported as strings for historical reasons
value = BigInt(value);
}
// eslint-disable-next-line valid-typeof
if (typeof value !== 'bigint') {
throw new TypeError('Not a valid varint, expected BigInt, obtained ' + util.inspect(value));
}
if (value === bigInt0) {
return buffers.int8Zero;
}
else if (value === bigIntMinus1) {
return buffers.int8MaxValue;
}
const parts = [];
if (value > bigInt0){
while (value !== bigInt0) {
parts.unshift(Number(value & bigInt8BitsOn));
value = value >> bigInt8;
}
if (parts[0] > 0x7f) {
// Positive value needs a padding
parts.unshift(0);
}
} else {
while (value !== bigIntMinus1) {
parts.unshift(Number(value & bigInt8BitsOn));
value = value >> bigInt8;
}
if (parts[0] <= 0x7f) {
// Negative value needs a padding
parts.unshift(0xff);
}
}
return utils.allocBufferFromArray(parts);
};
this.encodeVarint = this.encodingOptions.useBigIntAsVarint
? this._encodeVarintFromBigInt
: this._encodeVarintFromInteger;
/**
* @param {BigDecimal|Buffer|String|Number} value
* @returns {Buffer}
* @private
*/
this.encodeDecimal = function (value) {
if (typeof value === 'number') {
value = BigDecimal.fromNumber(value);
} else if (typeof value === 'string') {
value = BigDecimal.fromString(value);
}
let buf = null;
if (value instanceof BigDecimal) {
buf = BigDecimal.toBuffer(value);
} else {
throw new TypeError('Not a valid varint, expected BigDecimal/Number/String/Buffer, obtained ' + util.inspect(value));
}
return buf;
};
this.encodeString = function (value, encoding) {
if (typeof value !== 'string') {
throw new TypeError('Not a valid text value, expected String obtained ' + util.inspect(value));
}
return utils.allocBufferFromString(value, encoding);
};
this.encodeUtf8String = function (value) {
return this.encodeString(value, 'utf8');
};
this.encodeAsciiString = function (value) {
return this.encodeString(value, 'ascii');
};
this.encodeBlob = function (value) {
if (!(value instanceof Buffer)) {
throw new TypeError('Not a valid blob, expected Buffer obtained ' + util.inspect(value));
}
return value;
};
this.encodeCustom = function (value, customTypeName) {
// Special handling for vector custom types (since they have args)
if (customTypeName.startsWith(customTypeNames.vector)) {
return this.encodeVector(value, this.parseVectorTypeArgs(customTypeName, customTypeNames.vector, this.parseFqTypeName));
}
const handler = customEncoders[customTypeName];
if (handler) {
return handler.call(this, value);
}
throw new TypeError('No encoding handler found for type ' + customTypeName);
};
/**
* @param {Boolean} value
* @returns {Buffer}
* @private
*/
this.encodeBoolean = function (value) {
return value ? buffers.int8One : buffers.int8Zero;
};
/**
* @param {Number|String} value
* @private
*/
this.encodeInt = function (value) {
if (isNaN(value)) {
throw new TypeError('Expected Number, obtained ' + util.inspect(value));
}
const buf = utils.allocBufferUnsafe(4);
buf.writeInt32BE(value, 0);
return buf;
};
/**
* @param {Number|String} value
* @private
*/
this.encodeSmallint = function (value) {
if (isNaN(value)) {
throw new TypeError('Expected Number, obtained ' + util.inspect(value));
}
const buf = utils.allocBufferUnsafe(2);
buf.writeInt16BE(value, 0);
return buf;
};
/**
* @param {Number|String} value
* @private
*/
this.encodeTinyint = function (value) {
if (isNaN(value)) {
throw new TypeError('Expected Number, obtained ' + util.inspect(value));
}
const buf = utils.allocBufferUnsafe(1);
buf.writeInt8(value, 0);
return buf;
};
this.encodeList = function (value, subtype) {
if (!Array.isArray(value)) {
throw new TypeError('Not a valid list value, expected Array obtained ' + util.inspect(value));
}
if (value.length === 0) {
return null;
}
const parts = [];
parts.push(this.getLengthBuffer(value));
for (let i = 0;i < value.length;i++) {
const val = value[i];
if (val === null || typeof val === 'undefined' || val === types.unset) {
throw new TypeError('A collection can\'t contain null or unset values');
}
const bytes = this.encode(val, subtype);
//include item byte length
parts.push(this.getLengthBuffer(bytes));
//include item
parts.push(bytes);
}
return Buffer.concat(parts);
};
this.encodeSet = function (value, subtype) {
if (this.encodingOptions.set && value instanceof this.encodingOptions.set) {
const arr = [];
value.forEach(function (x) {
arr.push(x);
});
return this.encodeList(arr, subtype);
}
return this.encodeList(value, subtype);
};
/**
* Serializes a map into a Buffer
* @param value
* @param {Array} [subtypes]
* @returns {Buffer}
* @private
*/
this.encodeMap = function (value, subtypes) {
const parts = [];
let propCounter = 0;
let keySubtype = null;
let valueSubtype = null;
const self = this;
if (subtypes) {
keySubtype = subtypes[0];
valueSubtype = subtypes[1];
}
function addItem(val, key) {
if (key === null || typeof key === 'undefined' || key === types.unset) {
throw new TypeError('A map can\'t contain null or unset keys');
}
if (val === null || typeof val === 'undefined' || val === types.unset) {
throw new TypeError('A map can\'t contain null or unset values');
}
const keyBuffer = self.encode(key, keySubtype);
//include item byte length
parts.push(self.getLengthBuffer(keyBuffer));
//include item
parts.push(keyBuffer);
//value
const valueBuffer = self.encode(val, valueSubtype);
//include item byte length
parts.push(self.getLengthBuffer(valueBuffer));
//include item
if (valueBuffer !== null) {
parts.push(valueBuffer);
}
propCounter++;
}
if (this.encodingOptions.map && value instanceof this.encodingOptions.map) {
//Use Map#forEach() method to iterate
value.forEach(addItem);
}
else {
//Use object
for (const key in value) {
if (!value.hasOwnProperty(key)) {
continue;
}
const val = value[key];
addItem(val, key);
}
}
parts.unshift(this.getLengthBuffer(propCounter));
return Buffer.concat(parts);
};
this.encodeUdt = function (value, udtInfo) {
const parts = [];
let totalLength = 0;
for (let i = 0; i < udtInfo.fields.length; i++) {
const field = udtInfo.fields[i];
const item = this.encode(value[field.name], field.type);
if (!item) {
parts.push(nullValueBuffer);
totalLength += 4;
continue;
}
if (item === types.unset) {
parts.push(unsetValueBuffer);
totalLength += 4;
continue;
}
const lengthBuffer = utils.allocBufferUnsafe(4);
lengthBuffer.writeInt32BE(item.length, 0);
parts.push(lengthBuffer);
parts.push(item);
totalLength += item.length + 4;
}
return Buffer.concat(parts, totalLength);
};
this.encodeTuple = function (value, tupleInfo) {
const parts = [];
let totalLength = 0;
const length = Math.min(tupleInfo.length, value.length);
for (let i = 0; i < length; i++) {
const type = tupleInfo[i];
const item = this.encode(value.get(i), type);
if (!item) {
parts.push(nullValueBuffer);
totalLength += 4;
continue;
}
if (item === types.unset) {
parts.push(unsetValueBuffer);
totalLength += 4;
continue;
}
const lengthBuffer = utils.allocBufferUnsafe(4);
lengthBuffer.writeInt32BE(item.length, 0);
parts.push(lengthBuffer);
parts.push(item);
totalLength += item.length + 4;
}
return Buffer.concat(parts, totalLength);
};
this.decodeVector = function(buffer, params) {
const subtype = params["subtype"];
const dimensions = params["dimensions"];
const elemLength = 4; // TODO: figure this out based on the subtype
const expectedLength = buffer.length / elemLength;
if ((elemLength * dimensions) !== buffer.length) {
throw new TypeError(`Expected buffer of subtype ${subtype} with dimensions ${dimensions} to be of size ${expectedLength}, observed size ${buffer.length}`);
}
const rv = [];
let offset = 0;
for (let i = 0; i < dimensions; i++) {
offset = i * elemLength;
rv[i] = this.decode(buffer.slice(offset, offset + elemLength), subtype);
}
return new Float32Array(rv);
};
/**
* @param {CqlVector} value
* @param {Object} params
*/
this.encodeVector = function(value, params) {
// Evaluate params to encodeVector(), returning the computed subtype
function evalParams() {
if (!(value instanceof Float32Array)) {
throw new TypeError("Driver only supports vectors of 4 byte floating point values");
}
// Perform client-side validation iff we were actually supplied with meaningful type info. In practice
// this will only occur when using prepared statements.
if (params.hasOwnProperty("subtype") && params.hasOwnProperty("dimensions")) {
const subtype = params["subtype"];
const dimensions = params["dimensions"];
if (value.length !== dimensions) {
throw new TypeError(`Expected vector with ${dimensions} dimensions, observed size of ${value.length}`);
}
if (subtype.code !== dataTypes.float) {
throw new TypeError("Driver only supports vectors of 4 byte floating point values");
}
return subtype;
}
return { code: dataTypes.float };
}
if (!Encoder.isTypedArray(value)) {
throw new TypeError('Expected TypedArray subclass, obtained ' + util.inspect(value));
}
if (value.length === 0) {
throw new TypeError("Cannot encode empty array as vector");
}
const subtype = evalParams();
// TypedArrays are _not_ JS arrays so explicitly convert them here before trying to write them
// into a buffer
const elems = [];
for (const elem of value) {
elems.push(this.encode(elem, subtype));
}
return Buffer.concat(elems);
};
/**
* Extract the (typed) arguments from a vector type
*
* @param {String} typeName
* @param {String} stringToExclude Leading string indicating this is a vector type (to be excluded when eval'ing args)
* @param {Function} subtypeResolveFn Function used to resolve subtype type; varies depending on type naming convention
* @returns {Object}
* @internal
*/
this.parseVectorTypeArgs = function(typeName, stringToExclude, subtypeResolveFn) {
const argsStartIndex = stringToExclude.length + 1;
const argsLength = typeName.length - (stringToExclude.length + 2);
const params = parseParams(typeName, argsStartIndex, argsLength);
if (params.length === 2) {
return {subtype: subtypeResolveFn(params[0]), dimensions: parseInt(params[1], 10)};
}
throw new TypeError('Not a valid type ' + typeName);
};
/**
* If not provided, it uses the array of buffers or the parameters and hints to build the routingKey
* @param {Array} params
* @param {ExecutionOptions} execOptions