-
Notifications
You must be signed in to change notification settings - Fork 148
/
types.js
3336 lines (3014 loc) · 91.3 KB
/
types.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
// TODO: Make it easier to implement custom types. This will likely require
// exposing the `Tap` object, perhaps under another name. Probably worth a
// major release.
// TODO: Allow configuring when to write the size when writing arrays and maps,
// and customizing their block size.
// TODO: Code-generate `compare` and `clone` record and union methods.
'use strict';
/**
* This module defines all Avro data types and their serialization logic.
*
*/
let utils = require('./utils');
// Convenience imports.
let {Tap, isBufferLike} = utils;
let j = utils.printJSON;
// All non-union concrete (i.e. non-logical) Avro types.
// Defined after all the type classes are defined.
let TYPES;
// Random generator.
let RANDOM = new utils.Lcg();
// Encoding tap (shared for performance).
let TAP = Tap.withCapacity(1024);
// Currently active logical type, used for name redirection.
let LOGICAL_TYPE = null;
// Underlying types of logical types currently being instantiated. This is used
// to be able to reference names (i.e. for branches) during instantiation.
let UNDERLYING_TYPES = [];
/**
* "Abstract" base Avro type.
*
* This class' constructor will register any named types to support recursive
* schemas. All type values are represented in memory similarly to their JSON
* representation, except for:
*
* + `bytes` and `fixed` which are represented as `Uint8Array`s.
* + `union`s which will be "unwrapped" unless the `wrapUnions` option is set.
*
* See individual subclasses for details.
*/
class Type {
constructor (schema, opts) {
let type;
if (LOGICAL_TYPE) {
type = LOGICAL_TYPE;
UNDERLYING_TYPES.push([LOGICAL_TYPE, this]);
LOGICAL_TYPE = null;
} else {
type = this;
}
// Lazily instantiated hash string. It will be generated the first time the
// type's default fingerprint is computed (for example when using `equals`).
// We use a mutable object since types are frozen after instantiation.
this._hash = new Hash();
this.name = undefined;
this.aliases = undefined;
this.doc = (schema && schema.doc) ? '' + schema.doc : undefined;
if (schema) {
// This is a complex (i.e. non-primitive) type.
let name = schema.name;
let namespace = schema.namespace === undefined ?
opts && opts.namespace :
schema.namespace;
if (name !== undefined) {
// This isn't an anonymous type.
name = maybeQualify(name, namespace);
if (isPrimitive(name)) {
// Avro doesn't allow redefining primitive names.
throw new Error(`cannot rename primitive type: ${j(name)}`);
}
let registry = opts && opts.registry;
if (registry) {
if (registry[name] !== undefined) {
throw new Error(`duplicate type name: ${name}`);
}
registry[name] = type;
}
} else if (opts && opts.noAnonymousTypes) {
throw new Error(`missing name property in schema: ${j(schema)}`);
}
this.name = name;
this.aliases = schema.aliases ?
schema.aliases.map((s) => { return maybeQualify(s, namespace); }) :
[];
}
}
static forSchema (schema, opts) {
opts = Object.assign({}, opts);
opts.registry = opts.registry || {};
let UnionType = (function (wrapUnions) {
if (wrapUnions === true) {
wrapUnions = 'always';
} else if (wrapUnions === false) {
wrapUnions = 'never';
} else if (wrapUnions === undefined) {
wrapUnions = 'auto';
} else if (typeof wrapUnions == 'string') {
wrapUnions = wrapUnions.toLowerCase();
} else if (typeof wrapUnions === 'function') {
wrapUnions = 'auto';
}
switch (wrapUnions) {
case 'always':
return WrappedUnionType;
case 'never':
return UnwrappedUnionType;
case 'auto':
return undefined; // Determined dynamically later on.
default:
throw new Error(`invalid wrap unions option: ${j(wrapUnions)}`);
}
})(opts.wrapUnions);
if (schema === null) {
// Let's be helpful for this common error.
throw new Error('invalid type: null (did you mean "null"?)');
}
if (Type.isType(schema)) {
return schema;
}
let type;
if (opts.typeHook && (type = opts.typeHook(schema, opts))) {
if (!Type.isType(type)) {
throw new Error(`invalid typehook return value: ${j(type)}`);
}
return type;
}
if (typeof schema == 'string') { // Type reference.
schema = maybeQualify(schema, opts.namespace);
type = opts.registry[schema];
if (type) {
// Type was already defined, return it.
return type;
}
if (isPrimitive(schema)) {
// Reference to a primitive type. These are also defined names by
// default so we create the appropriate type and it to the registry for
// future reference.
type = Type.forSchema({type: schema}, opts);
opts.registry[schema] = type;
return type;
}
throw new Error(`undefined type name: ${schema}`);
}
if (schema.logicalType && opts.logicalTypes && !LOGICAL_TYPE) {
let DerivedType = opts.logicalTypes[schema.logicalType];
// TODO: check to ensure DerivedType was derived from LogicalType via ES6
// subclassing; otherwise it will not work properly
if (DerivedType) {
let namespace = opts.namespace;
let registry = {};
Object.keys(opts.registry).forEach((key) => {
registry[key] = opts.registry[key];
});
try {
return new DerivedType(schema, opts);
} catch (err) {
if (opts.assertLogicalTypes) {
// The spec mandates that we fall through to the underlying type if
// the logical type is invalid. We provide this option to ease
// debugging.
throw err;
}
LOGICAL_TYPE = null;
opts.namespace = namespace;
opts.registry = registry;
}
}
}
if (Array.isArray(schema)) { // Union.
// We temporarily clear the logical type since we instantiate the branch's
// types before the underlying union's type (necessary to decide whether
// the union is ambiguous or not).
let logicalType = LOGICAL_TYPE;
LOGICAL_TYPE = null;
let types = schema.map((obj) => {
return Type.forSchema(obj, opts);
});
let projectionFn;
if (!UnionType) {
if (typeof opts.wrapUnions === 'function') {
// we have a projection function
projectionFn = opts.wrapUnions(types);
UnionType = typeof projectionFn !== 'undefined'
? UnwrappedUnionType
: WrappedUnionType;
} else {
UnionType = isAmbiguous(types) ? WrappedUnionType : UnwrappedUnionType;
}
}
LOGICAL_TYPE = logicalType;
type = new UnionType(types, opts, projectionFn);
} else { // New type definition.
type = (function (typeName) {
let Type = TYPES[typeName];
if (Type === undefined) {
throw new Error(`unknown type: ${j(typeName)}`);
}
return new Type(schema, opts);
})(schema.type);
}
return type;
}
static forValue (val, opts) {
opts = Object.assign({}, opts);
// Sentinel used when inferring the types of empty arrays.
opts.emptyArrayType = opts.emptyArrayType || Type.forSchema({
type: 'array', items: 'null'
});
// Optional custom inference hook.
if (opts.valueHook) {
let type = opts.valueHook(val, opts);
if (type !== undefined) {
if (!Type.isType(type)) {
throw new Error(`invalid value hook return value: ${j(type)}`);
}
return type;
}
}
// Default inference logic.
switch (typeof val) {
case 'string':
return Type.forSchema('string', opts);
case 'boolean':
return Type.forSchema('boolean', opts);
case 'number':
if ((val | 0) === val) {
return Type.forSchema('int', opts);
} else if (Math.abs(val) < 9007199254740991) {
return Type.forSchema('float', opts);
}
return Type.forSchema('double', opts);
case 'object': {
if (val === null) {
return Type.forSchema('null', opts);
} else if (Array.isArray(val)) {
if (!val.length) {
return opts.emptyArrayType;
}
return Type.forSchema({
type: 'array',
items: Type.forTypes(
val.map((v) => { return Type.forValue(v, opts); }),
opts
)
}, opts);
} else if (isBufferLike(val)) {
return Type.forSchema('bytes', opts);
}
let fieldNames = Object.keys(val);
if (fieldNames.some((s) => { return !utils.isValidName(s); })) {
// We have to fall back to a map.
return Type.forSchema({
type: 'map',
values: Type.forTypes(fieldNames.map((s) => {
return Type.forValue(val[s], opts);
}), opts)
}, opts);
}
return Type.forSchema({
type: 'record',
fields: fieldNames.map((s) => {
return {name: s, type: Type.forValue(val[s], opts)};
})
}, opts);
}
default:
throw new Error(`cannot infer type from: ${j(val)}`);
}
}
static forTypes (types, opts) {
if (!types.length) {
throw new Error('no types to combine');
}
if (types.length === 1) {
return types[0]; // Nothing to do.
}
opts = Object.assign({}, opts);
// Extract any union types, with special care for wrapped unions (see
// below).
let expanded = [];
let numWrappedUnions = 0;
let isValidWrappedUnion = true;
types.forEach((type) => {
switch (type.typeName) {
case 'union:unwrapped':
isValidWrappedUnion = false;
expanded = expanded.concat(type.types);
break;
case 'union:wrapped':
numWrappedUnions++;
expanded = expanded.concat(type.types);
break;
case 'null':
expanded.push(type);
break;
default:
isValidWrappedUnion = false;
expanded.push(type);
}
});
if (numWrappedUnions) {
if (!isValidWrappedUnion) {
// It is only valid to combine wrapped unions when no other type is
// present other than wrapped unions and nulls (otherwise the values of
// others wouldn't be valid in the resulting union).
throw new Error('cannot combine wrapped union');
}
let branchTypes = {};
expanded.forEach((type) => {
let name = type.branchName;
let branchType = branchTypes[name];
if (!branchType) {
branchTypes[name] = type;
} else if (!type.equals(branchType)) {
throw new Error('inconsistent branch type');
}
});
let wrapUnions = opts.wrapUnions;
let unionType;
opts.wrapUnions = true;
try {
unionType = Type.forSchema(Object.keys(branchTypes).map((name) => {
return branchTypes[name];
}), opts);
} catch (err) {
throw err;
} finally {
opts.wrapUnions = wrapUnions;
}
return unionType;
}
// Group types by category, similar to the logic for unwrapped unions.
let bucketized = {};
expanded.forEach((type) => {
let bucket = getTypeBucket(type);
let bucketTypes = bucketized[bucket];
if (!bucketTypes) {
bucketized[bucket] = bucketTypes = [];
}
bucketTypes.push(type);
});
// Generate the "augmented" type for each group.
let buckets = Object.keys(bucketized);
let augmented = buckets.map((bucket) => {
let bucketTypes = bucketized[bucket];
if (bucketTypes.length === 1) {
return bucketTypes[0];
} else {
switch (bucket) {
case 'null':
case 'boolean':
return bucketTypes[0];
case 'number':
return combineNumbers(bucketTypes);
case 'string':
return combineStrings(bucketTypes, opts);
case 'buffer':
return combineBuffers(bucketTypes, opts);
case 'array':
// Remove any sentinel arrays (used when inferring from empty
// arrays) to avoid making things nullable when they shouldn't be.
bucketTypes = bucketTypes.filter((t) => {
return t !== opts.emptyArrayType;
});
if (!bucketTypes.length) {
// We still don't have a real type, just return the sentinel.
return opts.emptyArrayType;
}
return Type.forSchema({
type: 'array',
items: Type.forTypes(bucketTypes.map((t) => {
return t.itemsType;
}), opts)
}, opts);
default:
return combineObjects(bucketTypes, opts);
}
}
});
if (augmented.length === 1) {
return augmented[0];
} else {
// We return an (unwrapped) union of all augmented types.
return Type.forSchema(augmented, opts);
}
}
static isType (/* any, [prefix] ... */) {
let l = arguments.length;
if (!l) {
return false;
}
let any = arguments[0];
if (
!any ||
typeof any._update != 'function' ||
typeof any.fingerprint != 'function'
) {
// Not fool-proof, but most likely good enough.
return false;
}
if (l === 1) {
// No type names specified, we are done.
return true;
}
// We check if at least one of the prefixes matches.
let typeName = any.typeName;
for (let i = 1; i < l; i++) {
if (typeName.indexOf(arguments[i]) === 0) {
return true;
}
}
return false;
}
static __reset (size) {
TAP.reinitialize(size);
}
get branchName () {
let type = Type.isType(this, 'logical') ? this.underlyingType : this;
if (type.name) {
return type.name;
}
if (Type.isType(type, 'abstract')) {
return type._concreteTypeName;
}
return Type.isType(type, 'union') ? undefined : type.typeName;
}
clone (val, opts) {
if (opts) {
opts = {
coerce: !!opts.coerceBuffers | 0, // Coerce JSON to Buffer.
fieldHook: opts.fieldHook,
qualifyNames: !!opts.qualifyNames,
skip: !!opts.skipMissingFields,
wrap: !!opts.wrapUnions | 0 // Wrap first match into union.
};
return this._copy(val, opts);
} else {
// If no modifications are required, we can get by with a serialization
// roundtrip (generally much faster than a standard deep copy).
return this.fromBuffer(this.toBuffer(val));
}
}
compareBuffers (buf1, buf2) {
return this._match(Tap.fromBuffer(buf1), Tap.fromBuffer(buf2));
}
createResolver (type, opts) {
if (!Type.isType(type)) {
// More explicit error message than the "incompatible type" thrown
// otherwise (especially because of the overridden `toJSON` method).
throw new Error(`not a type: ${j(type)}`);
}
if (!Type.isType(this, 'union', 'logical') && Type.isType(type, 'logical')) {
// Trying to read a logical type as a built-in: unwrap the logical type.
// Note that we exclude unions to support resolving into unions containing
// logical types.
return this.createResolver(type.underlyingType, opts);
}
opts = Object.assign({}, opts);
opts.registry = opts.registry || {};
let resolver, key;
if (
Type.isType(this, 'record', 'error') &&
Type.isType(type, 'record', 'error')
) {
// We allow conversions between records and errors.
key = this.name + ':' + type.name; // ':' is illegal in Avro type names.
resolver = opts.registry[key];
if (resolver) {
return resolver;
}
}
resolver = new Resolver(this);
if (key) { // Register resolver early for recursive schemas.
opts.registry[key] = resolver;
}
if (Type.isType(type, 'union')) {
let resolvers = type.types.map(function (t) {
return this.createResolver(t, opts);
}, this);
resolver._read = function (tap) {
let index = tap.readLong();
let resolver = resolvers[index];
if (resolver === undefined) {
throw new Error(`invalid union index: ${index}`);
}
return resolvers[index]._read(tap);
};
} else {
this._update(resolver, type, opts);
}
if (!resolver._read) {
throw new Error(`cannot read ${type} as ${this}`);
}
return Object.freeze(resolver);
}
decode (buf, pos, resolver) {
let tap = Tap.fromBuffer(buf, pos);
let val = readValue(this, tap, resolver);
if (!tap.isValid()) {
return {value: undefined, offset: -1};
}
return {value: val, offset: tap.pos};
}
encode (val, buf, pos) {
let tap = Tap.fromBuffer(buf, pos);
this._write(tap, val);
if (!tap.isValid()) {
// Don't throw as there is no way to predict this. We also return the
// number of missing bytes to ease resizing.
return buf.length - tap.pos;
}
return tap.pos;
}
equals (type, opts) {
let canon = ( // Canonical equality.
Type.isType(type) &&
this._getCachedHash() === type._getCachedHash()
);
if (!canon || !(opts && opts.strict)) {
return canon;
}
return (
JSON.stringify(this.schema({exportAttrs: true})) ===
JSON.stringify(type.schema({exportAttrs: true}))
);
}
/**
* Get this type's schema fingerprint (lazily calculated and cached).
* Differs from {@link fingerprint} in that it returns the string
* representation of the fingerprint as it's stored internally.
* @returns {string}
*/
_getCachedHash() {
if (!this._hash.hash) {
let schemaStr = JSON.stringify(this.schema());
// Cache the hash as a binary string to avoid overhead and also return a
// fresh copy every time
// https://stackoverflow.com/questions/45803829/memory-overhead-of-typed-arrays-vs-strings/45808835#45808835
this._hash.hash = utils.bufferToBinaryString(utils.getHash(schemaStr));
}
return this._hash.hash;
}
fingerprint (algorithm) {
if (!algorithm) {
return utils.binaryStringToBuffer(this._getCachedHash());
}
return utils.getHash(JSON.stringify(this.schema()), algorithm);
}
fromBuffer (buf, resolver, noCheck) {
let tap = Tap.fromBuffer(buf, 0);
let val = readValue(this, tap, resolver, noCheck);
if (!tap.isValid()) {
throw new Error('truncated buffer');
}
if (!noCheck && tap.pos < buf.length) {
throw new Error('trailing data');
}
return val;
}
fromString (str) {
return this._copy(JSON.parse(str), {coerce: 2});
}
inspect () {
let typeName = this.typeName;
let className = getClassName(typeName);
if (isPrimitive(typeName)) {
// The class name is sufficient to identify the type.
return `<${className}>`;
} else {
// We add a little metadata for convenience.
let obj = this.schema({exportAttrs: true, noDeref: true});
if (typeof obj == 'object' && !Type.isType(this, 'logical')) {
obj.type = undefined; // Would be redundant with constructor name.
}
return `<${className} ${j(obj)}>`;
}
}
isValid (val, opts) {
// We only have a single flag for now, so no need to complicate things.
let flags = (opts && opts.noUndeclaredFields) | 0;
let errorHook = opts && opts.errorHook;
let hook, path;
if (errorHook) {
path = [];
hook = function (any, type) {
errorHook.call(this, path.slice(), any, type, val);
};
}
return this._check(val, flags, hook, path);
}
schema (opts) {
// Copy the options to avoid mutating the original options object when we
// add the registry of dereferenced types.
return this._attrs({}, {
exportAttrs: !!(opts && opts.exportAttrs),
noDeref: !!(opts && opts.noDeref)
});
}
toBuffer (val) {
TAP.pos = 0;
this._write(TAP, val);
if (TAP.isValid()) {
return TAP.toBuffer();
}
let buf = new Uint8Array(TAP.pos);
this._write(Tap.fromBuffer(buf), val);
return buf;
}
toJSON () {
// Convenience to allow using `JSON.stringify(type)` to get a type's schema.
return this.schema({exportAttrs: true});
}
toString (val) {
if (val === undefined) {
// Consistent behavior with standard `toString` expectations.
return JSON.stringify(this.schema({noDeref: true}));
}
return JSON.stringify(this._copy(val, {coerce: 3}));
}
wrap (val) {
let Branch = this._branchConstructor;
return Branch === null ? null : new Branch(val);
}
_attrs (derefed, opts) {
// This function handles a lot of the common logic to schema generation
// across types, for example keeping track of which types have already been
// de-referenced (i.e. derefed).
let name = this.name;
if (name !== undefined) {
if (opts.noDeref || derefed[name]) {
return name;
}
derefed[name] = true;
}
let schema = {};
// The order in which we add fields to the `schema` object matters here.
// Since JS objects are unordered, this implementation (unfortunately)
// relies on engines returning properties in the same order that they are
// inserted in. This is not in the JS spec, but can be "somewhat" safely
// assumed (see http://stackoverflow.com/q/5525795/1062617).
if (this.name !== undefined) {
schema.name = name;
}
schema.type = this.typeName;
let derefedSchema = this._deref(schema, derefed, opts);
if (derefedSchema !== undefined) {
// We allow the original schema to be overridden (this will happen for
// primitive types and logical types).
schema = derefedSchema;
}
if (opts.exportAttrs) {
if (this.aliases && this.aliases.length) {
schema.aliases = this.aliases;
}
if (this.doc !== undefined) {
schema.doc = this.doc;
}
}
return schema;
}
_createBranchConstructor () {
let name = this.branchName;
if (name === 'null') {
return null;
}
let attr = ~name.indexOf('.') ? 'this[\'' + name + '\']' : 'this.' + name;
let body = 'return function Branch$(val) { ' + attr + ' = val; };';
// eslint-disable-next-line no-new-func
let Branch = (new Function(body))();
Branch.type = this;
// eslint-disable-next-line no-new-func
Branch.prototype.unwrap = new Function('return ' + attr + ';');
Branch.prototype.unwrapped = Branch.prototype.unwrap; // Deprecated.
return Branch;
}
_peek (tap) {
let pos = tap.pos;
let val = this._read(tap);
tap.pos = pos;
return val;
}
compare () { utils.abstractFunction(); }
random () { utils.abstractFunction(); }
_check () { utils.abstractFunction(); }
_copy () { utils.abstractFunction(); }
_deref () { utils.abstractFunction(); }
_match () { utils.abstractFunction(); }
_read () { utils.abstractFunction(); }
_skip () { utils.abstractFunction(); }
_update () { utils.abstractFunction(); }
_write () { utils.abstractFunction(); }
}
// "Deprecated" getters (will be explicitly deprecated in 5.1).
Type.prototype.getAliases = function () { return this.aliases; };
Type.prototype.getFingerprint = Type.prototype.fingerprint;
Type.prototype.getName = function (asBranch) {
return (this.name || !asBranch) ? this.name : this.branchName;
};
Type.prototype.getSchema = Type.prototype.schema;
Type.prototype.getTypeName = function () { return this.typeName; };
// Implementations.
/**
* Base primitive Avro type.
*
* Most of the primitive types share the same cloning and resolution
* mechanisms, provided by this class. This class also lets us conveniently
* check whether a type is a primitive using `instanceof`.
*/
class PrimitiveType extends Type {
constructor (noFreeze) {
super();
this._branchConstructor = this._createBranchConstructor();
if (!noFreeze) {
// Abstract long types can't be frozen at this stage.
Object.freeze(this);
}
}
_update (resolver, type) {
if (type.typeName === this.typeName) {
resolver._read = this._read;
}
}
_copy (val) {
this._check(val, undefined, throwInvalidError);
return val;
}
_deref () { return this.typeName; }
compare (a, b) {
return utils.compare(a, b);
}
}
/** Nulls. */
class NullType extends PrimitiveType {
_check (val, flags, hook) {
let b = val === null;
if (!b && hook) {
hook(val, this);
}
return b;
}
_read () { return null; }
_skip () {}
_write (tap, val) {
if (val !== null) {
throwInvalidError(val, this);
}
}
_match () { return 0; }
}
NullType.prototype.compare = NullType.prototype._match;
NullType.prototype.typeName = 'null';
NullType.prototype.random = NullType.prototype._read;
/** Booleans. */
class BooleanType extends PrimitiveType {
_check (val, flags, hook) {
let b = typeof val == 'boolean';
if (!b && hook) {
hook(val, this);
}
return b;
}
_read (tap) { return tap.readBoolean(); }
_skip (tap) { tap.skipBoolean(); }
_write (tap, val) {
if (typeof val != 'boolean') {
throwInvalidError(val, this);
}
tap.writeBoolean(val);
}
_match (tap1, tap2) {
return tap1.matchBoolean(tap2);
}
random () { return RANDOM.nextBoolean(); }
}
BooleanType.prototype.typeName = 'boolean';
/** Integers. */
class IntType extends PrimitiveType {
_check (val, flags, hook) {
let b = val === (val | 0);
if (!b && hook) {
hook(val, this);
}
return b;
}
_read (tap) { return tap.readLong(); }
_skip (tap) { tap.skipLong(); }
_write (tap, val) {
if (val !== (val | 0)) {
throwInvalidError(val, this);
}
tap.writeLong(val);
}
_match (tap1, tap2) {
return tap1.matchLong(tap2);
}
random () { return RANDOM.nextInt(1000) | 0; }
}
IntType.prototype.typeName = 'int';
/**
* Longs.
*
* We can't capture all the range unfortunately since JavaScript represents all
* numbers internally as `double`s, so the default implementation plays safe
* and throws rather than potentially silently change the data. See `__with` or
* `AbstractLongType` below for a way to implement a custom long type.
*/
class LongType extends PrimitiveType {
// TODO: rework AbstractLongType so we don't need to accept noFreeze here
constructor (noFreeze) { super(noFreeze); }
_check (val, flags, hook) {
let b = typeof val == 'number' && val % 1 === 0 && isSafeLong(val);
if (!b && hook) {
hook(val, this);
}
return b;
}
_read (tap) {
let n = tap.readLong();
if (!isSafeLong(n)) {
throw new Error('potential precision loss');
}
return n;
}
_skip (tap) { tap.skipLong(); }
_write (tap, val) {
if (typeof val != 'number' || val % 1 || !isSafeLong(val)) {
throwInvalidError(val, this);
}
tap.writeLong(val);
}
_match (tap1, tap2) {
return tap1.matchLong(tap2);
}
_update (resolver, type) {
switch (type.typeName) {
case 'int':
resolver._read = type._read;
break;
case 'abstract:long':
case 'long':
resolver._read = this._read; // In case `type` is an `AbstractLongType`.
}
}
random () { return RANDOM.nextInt(); }
static __with (methods, noUnpack) {
methods = methods || {}; // Will give a more helpful error message.
// We map some of the methods to a different name to be able to intercept
// their input and output (otherwise we wouldn't be able to perform any
// unpacking logic, and the type wouldn't work when nested).
let mapping = {
toBuffer: '_toBuffer',
fromBuffer: '_fromBuffer',
fromJSON: '_fromJSON',
toJSON: '_toJSON',
isValid: '_isValid',
compare: 'compare'
};
let type = new AbstractLongType(noUnpack);
Object.keys(mapping).forEach((name) => {
if (methods[name] === undefined) {
throw new Error(`missing method implementation: ${name}`);
}
type[mapping[name]] = methods[name];
});
return Object.freeze(type);
}
}
LongType.prototype.typeName = 'long';
/** Floats. */
class FloatType extends PrimitiveType {
_check (val, flags, hook) {
let b = typeof val == 'number';
if (!b && hook) {
hook(val, this);
}
return b;
}
_read (tap) { return tap.readFloat(); }
_skip (tap) { tap.skipFloat(); }
_write (tap, val) {
if (typeof val != 'number') {
throwInvalidError(val, this);
}
tap.writeFloat(val);
}
_match (tap1, tap2) {
return tap1.matchFloat(tap2);
}
_update (resolver, type) {