• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * Copyright 2017, The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *     http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #ifndef ENTITY_H
18 #define ENTITY_H
19 
20 #include <memory>
21 #include <vector>
22 
23 #include "word_stream.h"
24 
25 namespace android {
26 namespace spirit {
27 
28 class Builder;
29 class IVisitor;
30 
31 class Entity {
32 public:
Entity()33   Entity() {}
Entity(Builder * b)34   Entity(Builder *b) : mBuilder(b) {}
35 
~Entity()36   virtual ~Entity() {}
37 
38   virtual void accept(IVisitor *visitor) = 0;
39   virtual bool DeserializeInternal(InputWordStream &IS) = 0;
40   virtual void Serialize(OutputWordStream &OS) const;
dump()41   virtual void dump() const {}
42 
setBuilder(Builder * builder)43   void setBuilder(Builder *builder) { mBuilder = builder; }
44 
45 protected:
46   Builder *mBuilder;
47 };
48 
Deserialize(InputWordStream & IS)49 template <typename T> T *Deserialize(InputWordStream &IS) {
50   std::unique_ptr<T> entity(new T());
51   if (!entity->DeserializeInternal(IS)) {
52     return nullptr;
53   }
54   return entity.release();
55 }
56 
Deserialize(const std::vector<uint32_t> & words)57 template <typename T> T *Deserialize(const std::vector<uint32_t> &words) {
58   std::unique_ptr<InputWordStream> IS(InputWordStream::Create(words));
59   return Deserialize<T>(*IS);
60 }
61 
62 template <class T>
DeserializeZeroOrMore(InputWordStream & IS,std::vector<T * > & all)63 void DeserializeZeroOrMore(InputWordStream &IS, std::vector<T *> &all) {
64   while (auto entity = Deserialize<T>(IS)) {
65     all.push_back(entity);
66   }
67 }
68 
69 template <class T>
Serialize(T * e)70 std::vector<uint32_t> Serialize(T* e) {
71   std::unique_ptr<OutputWordStream> OS(OutputWordStream::Create());
72   e->Serialize(*OS);
73   return OS->getWords();
74 }
75 
76 } // namespace spirit
77 } // namespace android
78 
79 #endif // ENTITY_H
80