aboutsummaryrefslogtreecommitdiffstats
path: root/contrib/libs/apache/avro/impl/Resolver.cc
blob: 43467c028ddb3b001667538d81914e96972ba264 (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
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
/**
 * 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.
 */

#include <memory>
#include "Resolver.hh"
#include "Layout.hh"
#include "NodeImpl.hh"
#include "ValidSchema.hh"
#include "Reader.hh"
#include "AvroTraits.hh"

namespace avro {
using std::unique_ptr;

class ResolverFactory;
typedef std::shared_ptr<Resolver> ResolverPtr;
typedef std::vector<std::unique_ptr<Resolver> > ResolverPtrVector;

// #define DEBUG_VERBOSE

#ifdef DEBUG_VERBOSE
#define DEBUG_OUT(str) std::cout << str << '\n'
#else
class NoOp {};
template<typename T> NoOp& operator<<(NoOp &noOp, const T&) {
    return noOp;
}
NoOp noop;
#define DEBUG_OUT(str) noop << str
#endif

template<typename T>
class PrimitiveSkipper : public Resolver
{
  public:

    PrimitiveSkipper() :
        Resolver()
    {}

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        T val;
        reader.readValue(val);
        DEBUG_OUT("Skipping " << val);
    }
};

template<typename T>
class PrimitiveParser : public Resolver
{
  public:

    PrimitiveParser(const PrimitiveLayout &offset) :
        Resolver(),
        offset_(offset.offset())
    {}

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        T* location = reinterpret_cast<T *> (address + offset_);
        reader.readValue(*location);
        DEBUG_OUT("Reading " << *location);
    }

  private:

    size_t offset_;
};

template<typename WT, typename RT>
class PrimitivePromoter : public Resolver
{
  public:

    PrimitivePromoter(const PrimitiveLayout &offset) :
        Resolver(),
        offset_(offset.offset())
    {}

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        parseIt<WT>(reader, address);
    }

  private:

    void parseIt(Reader &reader, uint8_t *address, const std::true_type &) const
    {
        WT val;
        reader.readValue(val);
        RT *location = reinterpret_cast<RT *> (address + offset_);
        *location = static_cast<RT>(val);
        DEBUG_OUT("Promoting " << val);
    }

    void parseIt(Reader &reader, uint8_t *address, const std::false_type &) const
    { }

    template<typename T>
    void parseIt(Reader &reader, uint8_t *address) const
    {
        parseIt(reader, address, is_promotable<T>());
    }

    size_t offset_;
};

template <>
class PrimitiveSkipper<std::vector<uint8_t> > : public Resolver
{
  public:

    PrimitiveSkipper() :
        Resolver()
    {}

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        std::vector<uint8_t> val;
        reader.readBytes(val);
        DEBUG_OUT("Skipping bytes");
    }
};

template <>
class PrimitiveParser<std::vector<uint8_t> > : public Resolver
{
  public:

    PrimitiveParser(const PrimitiveLayout &offset) :
        Resolver(),
        offset_(offset.offset())
    {}

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        std::vector<uint8_t> *location = reinterpret_cast<std::vector<uint8_t> *> (address + offset_);
        reader.readBytes(*location);
        DEBUG_OUT("Reading bytes");
    }

  private:

    size_t offset_;
};

class RecordSkipper : public Resolver
{
  public:

    RecordSkipper(ResolverFactory &factory, const NodePtr &writer);

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        DEBUG_OUT("Skipping record");

        reader.readRecord();
        size_t steps = resolvers_.size();
        for(size_t i = 0; i < steps; ++i) {
            resolvers_[i]->parse(reader, address);
        }
    }

  protected:

    ResolverPtrVector resolvers_;

};

class RecordParser : public Resolver
{
  public:

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        DEBUG_OUT("Reading record");

        reader.readRecord();
        size_t steps = resolvers_.size();
        for(size_t i = 0; i < steps; ++i) {
            resolvers_[i]->parse(reader, address);
        }
    }

    RecordParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const CompoundLayout &offsets);

  protected:

    ResolverPtrVector resolvers_;

};


class MapSkipper : public Resolver
{
  public:

    MapSkipper(ResolverFactory &factory, const NodePtr &writer);

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        DEBUG_OUT("Skipping map");

        std::string key;
        int64_t size = 0;
        do {
            size = reader.readMapBlockSize();
            for(int64_t i = 0; i < size; ++i) {
                reader.readValue(key);
                resolver_->parse(reader, address);
            }
        } while (size != 0);
    }

  protected:

    ResolverPtr resolver_;
};


class MapParser : public Resolver
{
  public:

    typedef uint8_t *(*GenericMapSetter)(uint8_t *map, const std::string &key);

    MapParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const CompoundLayout &offsets);

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        DEBUG_OUT("Reading map");

        uint8_t *mapAddress = address + offset_;

        std::string key;
        GenericMapSetter* setter = reinterpret_cast<GenericMapSetter *> (address + setFuncOffset_);

        int64_t size = 0;
        do {
            size = reader.readMapBlockSize();
            for(int64_t i = 0; i < size; ++i) {
                reader.readValue(key);

                // create a new map entry and get the address
                uint8_t *location = (*setter)(mapAddress, key);
                resolver_->parse(reader, location);
            }
        } while (size != 0);
    }

  protected:

    ResolverPtr  resolver_;
    size_t          offset_;
    size_t          setFuncOffset_;
};

class ArraySkipper : public Resolver
{
  public:

    ArraySkipper(ResolverFactory &factory, const NodePtr &writer);

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        DEBUG_OUT("Skipping array");

        int64_t size = 0;
        do {
            size = reader.readArrayBlockSize();
            for(int64_t i = 0; i < size; ++i) {
                resolver_->parse(reader, address);
            }
        } while (size != 0);
    }

  protected:

    ResolverPtr resolver_;
};

typedef uint8_t *(*GenericArraySetter)(uint8_t *array);

class ArrayParser : public Resolver
{
  public:

    ArrayParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const CompoundLayout &offsets);

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        DEBUG_OUT("Reading array");

        uint8_t *arrayAddress = address + offset_;

        GenericArraySetter* setter = reinterpret_cast<GenericArraySetter *> (address + setFuncOffset_);

        int64_t size = 0;
        do {
            size = reader.readArrayBlockSize();
            for(int64_t i = 0; i < size; ++i) {
                // create a new map entry and get the address
                uint8_t *location = (*setter)(arrayAddress);
                resolver_->parse(reader, location);
            }
        } while (size != 0);
    }

  protected:

    ArrayParser() :
        Resolver()
    {}

    ResolverPtr resolver_;
    size_t         offset_;
    size_t         setFuncOffset_;
};

class EnumSkipper : public Resolver
{
  public:

    EnumSkipper(ResolverFactory &factory, const NodePtr &writer) :
        Resolver()
    { }

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        int64_t val = reader.readEnum();
        DEBUG_OUT("Skipping enum" << val);
    }
};

class EnumParser : public Resolver
{
  public:

    enum EnumRepresentation {
        VAL
    };

    EnumParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const CompoundLayout &offsets) :
        Resolver(),
        offset_(offsets.at(0).offset()),
        readerSize_(reader->names())
    {
        const size_t writerSize = writer->names();

        mapping_.reserve(writerSize);

        for(size_t i = 0; i < writerSize; ++i) {
            const std::string &name = writer->nameAt(i);
            size_t readerIndex = readerSize_;
            reader->nameIndex(name, readerIndex);
            mapping_.push_back(readerIndex);
        }
    }

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        size_t val = static_cast<size_t>(reader.readEnum());
        assert(static_cast<size_t>(val) < mapping_.size());

        if(mapping_[val] < readerSize_) {
            EnumRepresentation* location = reinterpret_cast<EnumRepresentation *> (address + offset_);
            *location = static_cast<EnumRepresentation>(mapping_[val]);
            DEBUG_OUT("Setting enum" << *location);
        }
    }

protected:

    size_t offset_;
    size_t readerSize_;
    std::vector<size_t> mapping_;

};

class UnionSkipper : public Resolver
{
  public:

    UnionSkipper(ResolverFactory &factory, const NodePtr &writer);

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        DEBUG_OUT("Skipping union");
        size_t choice = static_cast<size_t>(reader.readUnion());
        resolvers_[choice]->parse(reader, address);
    }

  protected:

    ResolverPtrVector resolvers_;
};


class UnionParser : public Resolver
{
  public:

    typedef uint8_t *(*GenericUnionSetter)(uint8_t *, int64_t);

    UnionParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const CompoundLayout &offsets);

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        DEBUG_OUT("Reading union");
        size_t writerChoice = static_cast<size_t>(reader.readUnion());
        int64_t *readerChoice = reinterpret_cast<int64_t *>(address + choiceOffset_);

        *readerChoice = choiceMapping_[writerChoice];
        GenericUnionSetter* setter = reinterpret_cast<GenericUnionSetter *> (address + setFuncOffset_);
        uint8_t *value = reinterpret_cast<uint8_t *> (address + offset_);
        uint8_t *location = (*setter)(value, *readerChoice);

        resolvers_[writerChoice]->parse(reader, location);
    }

  protected:

    ResolverPtrVector resolvers_;
    std::vector<int64_t> choiceMapping_;
    size_t offset_;
    size_t choiceOffset_;
    size_t setFuncOffset_;
};

class UnionToNonUnionParser : public Resolver
{
  public:

    typedef uint8_t *(*GenericUnionSetter)(uint8_t *, int64_t);

    UnionToNonUnionParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const Layout &offsets);

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        DEBUG_OUT("Reading union to non-union");
        size_t choice = static_cast<size_t>(reader.readUnion());
        resolvers_[choice]->parse(reader, address);
    }

  protected:

    ResolverPtrVector resolvers_;
};

class NonUnionToUnionParser : public Resolver
{
  public:

    typedef uint8_t *(*GenericUnionSetter)(uint8_t *, int64_t);

    NonUnionToUnionParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const CompoundLayout &offsets);

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        DEBUG_OUT("Reading non-union to union");

        int64_t *choice = reinterpret_cast<int64_t *>(address + choiceOffset_);
        *choice = choice_;
        GenericUnionSetter* setter = reinterpret_cast<GenericUnionSetter *> (address + setFuncOffset_);
        uint8_t *value = reinterpret_cast<uint8_t *> (address + offset_);
        uint8_t *location = (*setter)(value, choice_);

        resolver_->parse(reader, location);
    }

  protected:

    ResolverPtr resolver_;
    size_t choice_;
    size_t offset_;
    size_t choiceOffset_;
    size_t setFuncOffset_;
};

class FixedSkipper : public Resolver
{
  public:

    FixedSkipper(ResolverFactory &factory, const NodePtr &writer) :
        Resolver()
    {
        size_ = writer->fixedSize();
    }

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        DEBUG_OUT("Skipping fixed");
        std::unique_ptr<uint8_t[]> val(new uint8_t[size_]);
        reader.readFixed(&val[0], size_);
    }

  protected:

    int size_;

};

class FixedParser : public Resolver
{
  public:

    FixedParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const CompoundLayout &offsets) :
        Resolver()
    {
        size_ = writer->fixedSize();
        offset_ = offsets.at(0).offset();
    }

    virtual void parse(Reader &reader, uint8_t *address) const
    {
        DEBUG_OUT("Reading fixed");
        uint8_t *location = reinterpret_cast<uint8_t *> (address + offset_);
        reader.readFixed(location, size_);
    }

  protected:

    int size_;
    size_t offset_;

};


class ResolverFactory : private boost::noncopyable {

    template<typename T>
    unique_ptr<Resolver>
    constructPrimitiveSkipper(const NodePtr &writer)
    {
        return unique_ptr<Resolver>(new PrimitiveSkipper<T>());
    }

    template<typename T>
    unique_ptr<Resolver>
    constructPrimitive(const NodePtr &writer, const NodePtr &reader, const Layout &offset)
    {
        unique_ptr<Resolver> instruction;

        SchemaResolution match = writer->resolve(*reader);

        if (match == RESOLVE_NO_MATCH) {
            instruction = unique_ptr<Resolver>(new PrimitiveSkipper<T>());
        }
        else if (reader->type() == AVRO_UNION) {
            const CompoundLayout &compoundLayout = static_cast<const CompoundLayout &>(offset);
            instruction = unique_ptr<Resolver>(new NonUnionToUnionParser(*this, writer, reader, compoundLayout));
        }
        else if (match == RESOLVE_MATCH) {
            const PrimitiveLayout &primitiveLayout = static_cast<const PrimitiveLayout &>(offset);
            instruction = unique_ptr<Resolver>(new PrimitiveParser<T>(primitiveLayout));
        }
        else if(match == RESOLVE_PROMOTABLE_TO_LONG) {
            const PrimitiveLayout &primitiveLayout = static_cast<const PrimitiveLayout &>(offset);
            instruction = unique_ptr<Resolver>(new PrimitivePromoter<T, int64_t>(primitiveLayout));
        }
        else if(match == RESOLVE_PROMOTABLE_TO_FLOAT) {
            const PrimitiveLayout &primitiveLayout = static_cast<const PrimitiveLayout &>(offset);
            instruction = unique_ptr<Resolver>(new PrimitivePromoter<T, float>(primitiveLayout));
        }
        else if(match == RESOLVE_PROMOTABLE_TO_DOUBLE) {
            const PrimitiveLayout &primitiveLayout = static_cast<const PrimitiveLayout &>(offset);
            instruction = unique_ptr<Resolver>(new PrimitivePromoter<T, double>(primitiveLayout));
        }
        else {
            assert(0);
        }
        return instruction;
    }

    template<typename Skipper>
    unique_ptr<Resolver>
    constructCompoundSkipper(const NodePtr &writer)
    {
        return unique_ptr<Resolver>(new Skipper(*this, writer));
    }


    template<typename Parser, typename Skipper>
    unique_ptr<Resolver>
    constructCompound(const NodePtr &writer, const NodePtr &reader, const Layout &offset)
    {
        unique_ptr<Resolver> instruction;

        SchemaResolution match = RESOLVE_NO_MATCH;

        match = writer->resolve(*reader);

        if (match == RESOLVE_NO_MATCH) {
            instruction = unique_ptr<Resolver>(new Skipper(*this, writer));
        }
        else if(writer->type() != AVRO_UNION && reader->type() == AVRO_UNION) {
            const CompoundLayout &compoundLayout = dynamic_cast<const CompoundLayout &>(offset);
            instruction = unique_ptr<Resolver>(new NonUnionToUnionParser(*this, writer, reader, compoundLayout));
        }
        else if(writer->type() == AVRO_UNION && reader->type() != AVRO_UNION) {
            instruction = unique_ptr<Resolver>(new UnionToNonUnionParser(*this, writer, reader, offset));
        }
        else {
            const CompoundLayout &compoundLayout = dynamic_cast<const CompoundLayout &>(offset);
            instruction = unique_ptr<Resolver>(new Parser(*this, writer, reader, compoundLayout));
        }

        return instruction;
    }

  public:

    unique_ptr<Resolver>
    construct(const NodePtr &writer, const NodePtr &reader, const Layout &offset)
    {

        typedef unique_ptr<Resolver> (ResolverFactory::*BuilderFunc)(const NodePtr &writer, const NodePtr &reader, const Layout &offset);

        NodePtr currentWriter = (writer->type() == AVRO_SYMBOLIC) ?
            resolveSymbol(writer) : writer;

        NodePtr currentReader = (reader->type() == AVRO_SYMBOLIC) ?
            resolveSymbol(reader) : reader;

        static const BuilderFunc funcs[] = {
            &ResolverFactory::constructPrimitive<std::string>,
            &ResolverFactory::constructPrimitive<std::vector<uint8_t> >,
            &ResolverFactory::constructPrimitive<int32_t>,
            &ResolverFactory::constructPrimitive<int64_t>,
            &ResolverFactory::constructPrimitive<float>,
            &ResolverFactory::constructPrimitive<double>,
            &ResolverFactory::constructPrimitive<bool>,
            &ResolverFactory::constructPrimitive<Null>,
            &ResolverFactory::constructCompound<RecordParser, RecordSkipper>,
            &ResolverFactory::constructCompound<EnumParser, EnumSkipper>,
            &ResolverFactory::constructCompound<ArrayParser, ArraySkipper>,
            &ResolverFactory::constructCompound<MapParser, MapSkipper>,
            &ResolverFactory::constructCompound<UnionParser, UnionSkipper>,
            &ResolverFactory::constructCompound<FixedParser, FixedSkipper>
        };

        static_assert((sizeof(funcs)/sizeof(BuilderFunc)) == (AVRO_NUM_TYPES),
                "Invalid number of builder functions");

        BuilderFunc func = funcs[currentWriter->type()];
        assert(func);

        return  ((this)->*(func))(currentWriter, currentReader, offset);
    }

    unique_ptr<Resolver>
    skipper(const NodePtr &writer)
    {

        typedef unique_ptr<Resolver> (ResolverFactory::*BuilderFunc)(const NodePtr &writer);

        NodePtr currentWriter = (writer->type() == AVRO_SYMBOLIC) ?
            writer->leafAt(0) : writer;

        static const BuilderFunc funcs[] = {
            &ResolverFactory::constructPrimitiveSkipper<std::string>,
            &ResolverFactory::constructPrimitiveSkipper<std::vector<uint8_t> >,
            &ResolverFactory::constructPrimitiveSkipper<int32_t>,
            &ResolverFactory::constructPrimitiveSkipper<int64_t>,
            &ResolverFactory::constructPrimitiveSkipper<float>,
            &ResolverFactory::constructPrimitiveSkipper<double>,
            &ResolverFactory::constructPrimitiveSkipper<bool>,
            &ResolverFactory::constructPrimitiveSkipper<Null>,
            &ResolverFactory::constructCompoundSkipper<RecordSkipper>,
            &ResolverFactory::constructCompoundSkipper<EnumSkipper>,
            &ResolverFactory::constructCompoundSkipper<ArraySkipper>,
            &ResolverFactory::constructCompoundSkipper<MapSkipper>,
            &ResolverFactory::constructCompoundSkipper<UnionSkipper>,
            &ResolverFactory::constructCompoundSkipper<FixedSkipper>
        };

        static_assert((sizeof(funcs)/sizeof(BuilderFunc)) == (AVRO_NUM_TYPES),
            "Invalid number of builder functions");

        BuilderFunc func = funcs[currentWriter->type()];
        assert(func);

        return  ((this)->*(func))(currentWriter);
    }
};


RecordSkipper::RecordSkipper(ResolverFactory &factory, const NodePtr &writer) :
    Resolver()
{
    size_t leaves = writer->leaves();
    resolvers_.reserve(leaves);
    for(size_t i = 0; i < leaves; ++i) {
        const NodePtr &w = writer->leafAt(i);
        resolvers_.push_back(factory.skipper(w));
    }
}

RecordParser::RecordParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const CompoundLayout &offsets) :
    Resolver()
{
    size_t leaves = writer->leaves();
    resolvers_.reserve(leaves);
    for(size_t i = 0; i < leaves; ++i) {

        const NodePtr &w = writer->leafAt(i);

        const std::string &name = writer->nameAt(i);

        size_t readerIndex = 0;
        bool found = reader->nameIndex(name, readerIndex);

        if(found) {
            const NodePtr &r = reader->leafAt(readerIndex);
            resolvers_.push_back(factory.construct(w, r, offsets.at(readerIndex)));
        }
        else {
            resolvers_.push_back(factory.skipper(w));
        }
    }
}

MapSkipper::MapSkipper(ResolverFactory &factory, const NodePtr &writer) :
    Resolver(),
    resolver_(factory.skipper(writer->leafAt(1)))
{ }

MapParser::MapParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const CompoundLayout &offsets) :
    Resolver(),
    resolver_(factory.construct(writer->leafAt(1), reader->leafAt(1), offsets.at(1))),
    offset_(offsets.offset()),
    setFuncOffset_( offsets.at(0).offset())
{ }

ArraySkipper::ArraySkipper(ResolverFactory &factory, const NodePtr &writer) :
    Resolver(),
    resolver_(factory.skipper(writer->leafAt(0)))
{ }

ArrayParser::ArrayParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const CompoundLayout &offsets) :
    Resolver(),
    resolver_(factory.construct(writer->leafAt(0), reader->leafAt(0), offsets.at(1))),
    offset_(offsets.offset()),
    setFuncOffset_(offsets.at(0).offset())
{ }

UnionSkipper::UnionSkipper(ResolverFactory &factory, const NodePtr &writer) :
    Resolver()
{
    size_t leaves = writer->leaves();
    resolvers_.reserve(leaves);
    for(size_t i = 0; i < leaves; ++i) {
    const NodePtr &w = writer->leafAt(i);
        resolvers_.push_back(factory.skipper(w));
    }
}

namespace {

// asumes the writer is NOT a union, and the reader IS a union

SchemaResolution
checkUnionMatch(const NodePtr &writer, const NodePtr &reader, size_t &index)
{
    SchemaResolution bestMatch = RESOLVE_NO_MATCH;

    index = 0;
    size_t leaves = reader->leaves();

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

        const NodePtr &leaf = reader->leafAt(i);
        SchemaResolution newMatch = writer->resolve(*leaf);

        if(newMatch == RESOLVE_MATCH) {
            bestMatch = newMatch;
            index = i;
            break;
        }
        if(bestMatch == RESOLVE_NO_MATCH) {
            bestMatch = newMatch;
            index = i;
        }
    }

    return bestMatch;
}

};

UnionParser::UnionParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const CompoundLayout &offsets) :
    Resolver(),
    offset_(offsets.offset()),
    choiceOffset_(offsets.at(0).offset()),
    setFuncOffset_(offsets.at(1).offset())
{

    size_t leaves = writer->leaves();
    resolvers_.reserve(leaves);
    choiceMapping_.reserve(leaves);
    for(size_t i = 0; i < leaves; ++i) {

        // for each writer, we need a schema match for the reader
        const NodePtr &w = writer->leafAt(i);
        size_t index = 0;

        SchemaResolution match = checkUnionMatch(w, reader, index);

        if(match == RESOLVE_NO_MATCH) {
            resolvers_.push_back(factory.skipper(w));
            // push back a non-sensical number
            choiceMapping_.push_back(reader->leaves());
        }
        else {
            const NodePtr &r = reader->leafAt(index);
            resolvers_.push_back(factory.construct(w, r, offsets.at(index+2)));
            choiceMapping_.push_back(index);
        }
    }
}

NonUnionToUnionParser::NonUnionToUnionParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const CompoundLayout &offsets) :
    Resolver(),
    offset_(offsets.offset()),
    choiceOffset_(offsets.at(0).offset()),
    setFuncOffset_(offsets.at(1).offset())
{
#ifndef NDEBUG
    SchemaResolution bestMatch =
#endif
    checkUnionMatch(writer, reader, choice_);
    assert(bestMatch != RESOLVE_NO_MATCH);
    resolver_ = factory.construct(writer, reader->leafAt(choice_), offsets.at(choice_+2));
}

UnionToNonUnionParser::UnionToNonUnionParser(ResolverFactory &factory, const NodePtr &writer, const NodePtr &reader, const Layout &offsets) :
    Resolver()
{
    size_t leaves = writer->leaves();
    resolvers_.reserve(leaves);
    for(size_t i = 0; i < leaves; ++i) {
        const NodePtr &w = writer->leafAt(i);
        resolvers_.push_back(factory.construct(w, reader, offsets));
    }
}

unique_ptr<Resolver> constructResolver(const ValidSchema &writerSchema,
                                    const ValidSchema &readerSchema,
                                    const Layout &readerLayout)
{
    ResolverFactory factory;
    return factory.construct(writerSchema.root(), readerSchema.root(), readerLayout);
}

} // namespace avro