aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/apache/avro/api/NodeImpl.hh
blob: ef1c1dac9b641ec33ee7e793b8e9f0240b936a27 (plain) (blame)
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
/*
 * Licensed to the Apache Software Foundation (ASF) under one
 * or more contributor license agreements.  See the NOTICE file
 * distributed with this work for additional information
 * regarding copyright ownership.  The ASF licenses this file
 * to you 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
 *
 *     https://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.
 */

#ifndef avro_NodeImpl_hh__
#define avro_NodeImpl_hh__

#include "Config.hh"
#include "GenericDatum.hh"

#include <iomanip>
#include <iostream>
#include <limits>
#include <memory>
#include <set>
#include <sstream>
#include <utility>

#include "Node.hh"
#include "NodeConcepts.hh"
#include "CustomAttributes.hh"

namespace avro {

/// Implementation details for Node.  NodeImpl represents all the avro types,
/// whose properties are enabled and disabled by selecting concept classes.

template<
    class NameConcept,
    class LeavesConcept,
    class LeafNamesConcept,
    class MultiAttributesConcept,
    class SizeConcept>
class NodeImpl : public Node {

protected:
    explicit NodeImpl(Type type) : Node(type),
                                   nameAttribute_(),
                                   docAttribute_(),
                                   leafAttributes_(),
                                   leafNameAttributes_(),
                                   customAttributes_(),
                                   sizeAttribute_() {}

    NodeImpl(Type type,
             const NameConcept &name,
             const LeavesConcept &leaves,
             const LeafNamesConcept &leafNames,
             const MultiAttributesConcept &customAttributes,
             const SizeConcept &size) : Node(type),
                                        nameAttribute_(name),
                                        docAttribute_(),
                                        leafAttributes_(leaves),
                                        leafNameAttributes_(leafNames),
                                        customAttributes_(customAttributes),
                                        sizeAttribute_(size) {}

    // Ctor with "doc"
    NodeImpl(Type type,
             const NameConcept &name,
             const concepts::SingleAttribute<std::string> &doc,
             const LeavesConcept &leaves,
             const LeafNamesConcept &leafNames,
             const MultiAttributesConcept &customAttributes,
             const SizeConcept &size) : Node(type),
                                        nameAttribute_(name),
                                        docAttribute_(doc),
                                        leafAttributes_(leaves),
                                        leafNameAttributes_(leafNames),
                                        customAttributes_(customAttributes),
                                        sizeAttribute_(size) {}

    void swap(NodeImpl &impl) {
        std::swap(nameAttribute_, impl.nameAttribute_);
        std::swap(docAttribute_, impl.docAttribute_);
        std::swap(leafAttributes_, impl.leafAttributes_);
        std::swap(leafNameAttributes_, impl.leafNameAttributes_);
        std::swap(sizeAttribute_, impl.sizeAttribute_);
        std::swap(customAttributes_, impl.customAttributes_);
        std::swap(nameIndex_, impl.nameIndex_);
    }

    bool hasName() const override {
        // e.g.: true for single and multi-attributes, false for no-attributes.
        return NameConcept::hasAttribute;
    }

    void doSetName(const Name &name) override {
        nameAttribute_.add(name);
    }

    const Name &name() const override {
        return nameAttribute_.get();
    }

    void doSetDoc(const std::string &doc) override {
        docAttribute_.add(doc);
    }

    const std::string &getDoc() const override {
        return docAttribute_.get();
    }

    void doAddLeaf(const NodePtr &newLeaf) final {
        leafAttributes_.add(newLeaf);
    }

    size_t leaves() const override {
        return leafAttributes_.size();
    }

    const NodePtr &leafAt(size_t index) const override {
        return leafAttributes_.get(index);
    }

    void doAddName(const std::string &name) override {
        if (!nameIndex_.add(name, leafNameAttributes_.size())) {
            throw Exception(boost::format("Cannot add duplicate name: %1%") % name);
        }
        leafNameAttributes_.add(name);
    }

    size_t names() const override {
        return leafNameAttributes_.size();
    }

    const std::string &nameAt(size_t index) const override {
        return leafNameAttributes_.get(index);
    }

    bool nameIndex(const std::string &name, size_t &index) const override {
        return nameIndex_.lookup(name, index);
    }

    void doSetFixedSize(size_t size) override {
        sizeAttribute_.add(size);
    }

    size_t fixedSize() const override {
        return sizeAttribute_.get();
    }

    bool isValid() const override = 0;

    void printBasicInfo(std::ostream &os) const override;

    void setLeafToSymbolic(size_t index, const NodePtr &node) override;

    void doAddCustomAttribute(const CustomAttributes &customAttributes) override {
      customAttributes_.add(customAttributes);
    }

    SchemaResolution furtherResolution(const Node &reader) const {
        SchemaResolution match = RESOLVE_NO_MATCH;

        if (reader.type() == AVRO_SYMBOLIC) {

            // resolve the symbolic type, and check again
            const NodePtr &node = reader.leafAt(0);
            match = resolve(*node);
        } else if (reader.type() == AVRO_UNION) {

            // in this case, need to see if there is an exact match for the
            // writer's type, or if not, the first one that can be promoted to a
            // match

            for (size_t i = 0; i < reader.leaves(); ++i) {

                const NodePtr &node = reader.leafAt(i);
                SchemaResolution thisMatch = resolve(*node);

                // if matched then the search is done
                if (thisMatch == RESOLVE_MATCH) {
                    match = thisMatch;
                    break;
                }

                // thisMatch is either no match, or promotable, this will set match to
                // promotable if it hasn't been set already
                if (match == RESOLVE_NO_MATCH) {
                    match = thisMatch;
                }
            }
        }

        return match;
    }

    NameConcept nameAttribute_;

    // Rem: NameConcept type is HasName (= SingleAttribute<Name>), we use std::string instead
    concepts::SingleAttribute<std::string> docAttribute_; /** Doc used to compare schemas */

    LeavesConcept leafAttributes_;
    LeafNamesConcept leafNameAttributes_;
    MultiAttributesConcept customAttributes_;
    SizeConcept sizeAttribute_;
    concepts::NameIndexConcept<LeafNamesConcept> nameIndex_;
};

using NoName = concepts::NoAttribute<Name>;
using HasName = concepts::SingleAttribute<Name>;

using HasDoc = concepts::SingleAttribute<std::string>;

using NoLeaves = concepts::NoAttribute<NodePtr>;
using SingleLeaf = concepts::SingleAttribute<NodePtr>;
using MultiLeaves = concepts::MultiAttribute<NodePtr>;

using NoLeafNames = concepts::NoAttribute<std::string>;
using LeafNames = concepts::MultiAttribute<std::string>;
using MultiAttributes = concepts::MultiAttribute<CustomAttributes>;
using NoAttributes = concepts::NoAttribute<CustomAttributes>;

using NoSize = concepts::NoAttribute<int>;
using HasSize = concepts::SingleAttribute<int>;

using NodeImplPrimitive = NodeImpl<NoName, NoLeaves, NoLeafNames, MultiAttributes, NoSize>;
using NodeImplSymbolic = NodeImpl<HasName, NoLeaves, NoLeafNames, NoAttributes, NoSize>;

using NodeImplRecord = NodeImpl<HasName, MultiLeaves, LeafNames, MultiAttributes, NoSize>;
using NodeImplEnum = NodeImpl<HasName, NoLeaves, LeafNames, NoAttributes, NoSize>;
using NodeImplArray = NodeImpl<NoName, SingleLeaf, NoLeafNames, NoAttributes, NoSize>;
using NodeImplMap = NodeImpl<NoName, MultiLeaves, NoLeafNames, NoAttributes, NoSize>;
using NodeImplUnion = NodeImpl<NoName, MultiLeaves, NoLeafNames, NoAttributes, NoSize>;
using NodeImplFixed = NodeImpl<HasName, NoLeaves, NoLeafNames, NoAttributes, HasSize>;

class AVRO_DECL NodePrimitive : public NodeImplPrimitive {
public:
    explicit NodePrimitive(Type type) : NodeImplPrimitive(type) {}

    SchemaResolution resolve(const Node &reader) const override;

    void printJson(std::ostream &os, size_t depth) const override;

    bool isValid() const override {
        return true;
    }

    void printDefaultToJson(const GenericDatum &g, std::ostream &os, size_t depth) const override;
};

class AVRO_DECL NodeSymbolic : public NodeImplSymbolic {
    using NodeWeakPtr = std::weak_ptr<Node>;

public:
    NodeSymbolic() : NodeImplSymbolic(AVRO_SYMBOLIC) {}

    explicit NodeSymbolic(const HasName &name) : NodeImplSymbolic(AVRO_SYMBOLIC, name, NoLeaves(), NoLeafNames(), NoAttributes(), NoSize()) {}

    NodeSymbolic(const HasName &name, const NodePtr &n) : NodeImplSymbolic(AVRO_SYMBOLIC, name, NoLeaves(), NoLeafNames(), NoAttributes(), NoSize()), actualNode_(n) {}
    SchemaResolution resolve(const Node &reader) const override;

    void printJson(std::ostream &os, size_t depth) const override;

    bool isValid() const override {
        return (nameAttribute_.size() == 1);
    }

    void printDefaultToJson(const GenericDatum &g, std::ostream &os, size_t depth) const override;

    bool isSet() const {
        return (actualNode_.lock() != nullptr);
    }

    NodePtr getNode() const {
        NodePtr node = actualNode_.lock();
        if (!node) {
            throw Exception(boost::format("Could not follow symbol %1%") % name());
        }
        return node;
    }

    void setNode(const NodePtr &node) {
        actualNode_ = node;
    }

protected:
    NodeWeakPtr actualNode_;
};

class AVRO_DECL NodeRecord : public NodeImplRecord {
    std::vector<GenericDatum> defaultValues;

public:
    NodeRecord() : NodeImplRecord(AVRO_RECORD) {}
    NodeRecord(const HasName &name, const MultiLeaves &fields,
               const LeafNames &fieldsNames,
               std::vector<GenericDatum> dv);

    NodeRecord(const HasName &name, const HasDoc &doc, const MultiLeaves &fields,
               const LeafNames &fieldsNames,
               std::vector<GenericDatum> dv) : NodeImplRecord(AVRO_RECORD, name, doc, fields, fieldsNames, MultiAttributes(), NoSize()),
                                               defaultValues(std::move(dv)) {
        leafNameCheck();
    }

    NodeRecord(const HasName &name, const MultiLeaves &fields,
               const LeafNames &fieldsNames,
               const std::vector<GenericDatum>& dv,
               const MultiAttributes &customAttributes) :
        NodeImplRecord(AVRO_RECORD, name, fields, fieldsNames, customAttributes, NoSize()),
        defaultValues(dv) {
        leafNameCheck();
    }

    NodeRecord(const HasName &name, const HasDoc &doc, const MultiLeaves &fields,
               const LeafNames &fieldsNames,
               const std::vector<GenericDatum>& dv,
               const MultiAttributes &customAttributes) :
        NodeImplRecord(AVRO_RECORD, name, doc, fields, fieldsNames, customAttributes, NoSize()),
        defaultValues(dv) {
        leafNameCheck();
    }

    void swap(NodeRecord &r) {
        NodeImplRecord::swap(r);
        defaultValues.swap(r.defaultValues);
    }

    SchemaResolution resolve(const Node &reader) const override;

    void printJson(std::ostream &os, size_t depth) const override;

    bool isValid() const override {
        return ((nameAttribute_.size() == 1) &&
            (leafAttributes_.size() == leafNameAttributes_.size()) &&
            (customAttributes_.size() == 0 ||
            customAttributes_.size() == leafAttributes_.size()));
    }

    const GenericDatum &defaultValueAt(size_t index) override {
        return defaultValues[index];
    }

    void printDefaultToJson(const GenericDatum &g, std::ostream &os, size_t depth) const override;

private:
    // check if leaf name is valid Name and is not duplicate
    void leafNameCheck() {
        for (size_t i = 0; i < leafNameAttributes_.size(); ++i) {
            if (!nameIndex_.add(leafNameAttributes_.get(i), i)) {
                throw Exception(boost::format(
                                    "Cannot add duplicate field: %1%")
                                % leafNameAttributes_.get(i));
            }
        }
    }
};

class AVRO_DECL NodeEnum : public NodeImplEnum {
public:
    NodeEnum() : NodeImplEnum(AVRO_ENUM) {}

    NodeEnum(const HasName &name, const LeafNames &symbols) : NodeImplEnum(AVRO_ENUM, name, NoLeaves(), symbols, NoAttributes(), NoSize()) {
        for (size_t i = 0; i < leafNameAttributes_.size(); ++i) {
            if (!nameIndex_.add(leafNameAttributes_.get(i), i)) {
                throw Exception(boost::format("Cannot add duplicate enum: %1%") % leafNameAttributes_.get(i));
            }
        }
    }

    SchemaResolution resolve(const Node &reader) const override;

    void printJson(std::ostream &os, size_t depth) const override;

    bool isValid() const override {
        return (
            (nameAttribute_.size() == 1) && (leafNameAttributes_.size() > 0));
    }

    void printDefaultToJson(const GenericDatum &g, std::ostream &os, size_t depth) const override;
};

class AVRO_DECL NodeArray : public NodeImplArray {
public:
    NodeArray() : NodeImplArray(AVRO_ARRAY) {}

    explicit NodeArray(const SingleLeaf &items) : NodeImplArray(AVRO_ARRAY, NoName(), items, NoLeafNames(), NoAttributes(), NoSize()) {}

    SchemaResolution resolve(const Node &reader) const override;

    void printJson(std::ostream &os, size_t depth) const override;

    bool isValid() const override {
        return (leafAttributes_.size() == 1);
    }

    void printDefaultToJson(const GenericDatum &g, std::ostream &os, size_t depth) const override;
};

class AVRO_DECL NodeMap : public NodeImplMap {
public:
    NodeMap();

    explicit NodeMap(const SingleLeaf &values) : NodeImplMap(AVRO_MAP, NoName(), MultiLeaves(values), NoLeafNames(), NoAttributes(), NoSize()) {
        // need to add the key for the map too
        NodePtr key(new NodePrimitive(AVRO_STRING));
        doAddLeaf(key);

        // key goes before value
        std::swap(leafAttributes_.get(0), leafAttributes_.get(1));
    }

    SchemaResolution resolve(const Node &reader) const override;

    void printJson(std::ostream &os, size_t depth) const override;

    bool isValid() const override {
        return (leafAttributes_.size() == 2);
    }

    void printDefaultToJson(const GenericDatum &g, std::ostream &os, size_t depth) const override;
};

class AVRO_DECL NodeUnion : public NodeImplUnion {
public:
    NodeUnion() : NodeImplUnion(AVRO_UNION) {}

    explicit NodeUnion(const MultiLeaves &types) : NodeImplUnion(AVRO_UNION, NoName(), types, NoLeafNames(), NoAttributes(), NoSize()) {}

    SchemaResolution resolve(const Node &reader) const override;

    void printJson(std::ostream &os, size_t depth) const override;

    bool isValid() const override {
        std::set<std::string> seen;
        if (leafAttributes_.size() >= 1) {
            for (size_t i = 0; i < leafAttributes_.size(); ++i) {
                std::string name;
                const NodePtr &n = leafAttributes_.get(i);
                switch (n->type()) {
                    case AVRO_STRING:
                        name = "string";
                        break;
                    case AVRO_BYTES:
                        name = "bytes";
                        break;
                    case AVRO_INT:
                        name = "int";
                        break;
                    case AVRO_LONG:
                        name = "long";
                        break;
                    case AVRO_FLOAT:
                        name = "float";
                        break;
                    case AVRO_DOUBLE:
                        name = "double";
                        break;
                    case AVRO_BOOL:
                        name = "bool";
                        break;
                    case AVRO_NULL:
                        name = "null";
                        break;
                    case AVRO_ARRAY:
                        name = "array";
                        break;
                    case AVRO_MAP:
                        name = "map";
                        break;
                    case AVRO_RECORD:
                    case AVRO_ENUM:
                    case AVRO_UNION:
                    case AVRO_FIXED:
                    case AVRO_SYMBOLIC:
                        name = n->name().fullname();
                        break;
                    default: return false;
                }
                if (seen.find(name) != seen.end()) {
                    return false;
                }
                seen.insert(name);
            }
            return true;
        }
        return false;
    }

    void printDefaultToJson(const GenericDatum &g, std::ostream &os, size_t depth) const override;
};

class AVRO_DECL NodeFixed : public NodeImplFixed {
public:
    NodeFixed() : NodeImplFixed(AVRO_FIXED) {}

    NodeFixed(const HasName &name, const HasSize &size) : NodeImplFixed(AVRO_FIXED, name, NoLeaves(), NoLeafNames(), NoAttributes(), size) {}

    SchemaResolution resolve(const Node &reader) const override;

    void printJson(std::ostream &os, size_t depth) const override;

    bool isValid() const override {
        return (
            (nameAttribute_.size() == 1) && (sizeAttribute_.size() == 1));
    }

    void printDefaultToJson(const GenericDatum &g, std::ostream &os, size_t depth) const override;
};

template<class A, class B, class C, class D, class E>
inline void
NodeImpl<A, B, C, D, E>::setLeafToSymbolic(size_t index, const NodePtr &node) {
    if (!B::hasAttribute) {
        throw Exception("Cannot change leaf node for nonexistent leaf");
    }

    auto &replaceNode = const_cast<NodePtr &>(leafAttributes_.get(index));
    if (replaceNode->name() != node->name()) {
        throw Exception("Symbolic name does not match the name of the schema it references");
    }

    auto symbol = std::make_shared<NodeSymbolic>();
    symbol->setName(node->name());
    symbol->setNode(node);
    replaceNode = symbol;
}

template<class A, class B, class C, class D, class E>
inline void
NodeImpl<A, B, C, D, E>::printBasicInfo(std::ostream &os) const {
    os << type();
    if (hasName()) {
        os << ' ' << nameAttribute_.get();
    }

    if (E::hasAttribute) {
        os << " " << sizeAttribute_.get();
    }
    os << '\n';
    size_t count = leaves();
    count = count ? count : names();
    for (size_t i = 0; i < count; ++i) {
        if (C::hasAttribute) {
            os << "name " << nameAt(i) << '\n';
        }
        if (type() != AVRO_SYMBOLIC && leafAttributes_.hasAttribute) {
            leafAt(i)->printBasicInfo(os);
        }
    }
    if (isCompound(type())) {
        os << "end " << type() << '\n';
    }
}

inline NodePtr resolveSymbol(const NodePtr &node) {
    if (node->type() != AVRO_SYMBOLIC) {
        throw Exception("Only symbolic nodes may be resolved");
    }
    std::shared_ptr<NodeSymbolic> symNode = std::static_pointer_cast<NodeSymbolic>(node);
    return symNode->getNode();
}

template<typename T>
inline std::string intToHex(T i) {
    std::stringstream stream;
    stream << "\\u"
           << std::setfill('0') << std::setw(sizeof(T))
           << std::hex << i;
    return stream.str();
}

} // namespace avro

#endif