SSP21-CPP
SeqStructField.h
1 
2 #ifndef SSP21_SEQSTRUCTFIELD_H
3 #define SSP21_SEQSTRUCTFIELD_H
4 
5 #include "log4cpp/Logger.h"
6 #include "log4cpp/LogMacros.h"
7 
8 #include "ssp21/crypto/IMessagePrinter.h"
9 #include "ssp21/crypto/VLength.h"
10 
11 #include "ssp21/util/ICollection.h"
12 
13 namespace ssp21
14 {
15  template <class StructType, uint32_t MAX_COUNT>
16  class SeqStructField : public ICollection<StructType>
17  {
18 
19  public:
20 
21  uint32_t capacity() const
22  {
23  return MAX_COUNT;
24  }
25 
26  size_t size() const
27  {
28  size_t sum = 0;
29 
30  for (uint32_t i = 0; i < this->count(); ++i)
31  {
32  sum += this->get(i)->size();
33  }
34 
35  return VLength::size_in_bytes(this->count()) + sum;
36  }
37 
38  ParseError read(seq32_t& input)
39  {
40  this->clear();
41 
42  uint32_t count;
43  auto cerr = VLength::read(count, input);
44  if (any(cerr)) return cerr;
45 
46  while (count > 0)
47  {
48  StructType item; ;
49  auto serr = item.read(input);
50  if (any(serr)) return serr;
51 
52  if (!this->push(item))
53  {
55  }
56 
57  --count;
58  }
59 
60  return ParseError::ok;
61  }
62 
63  FormatError write(wseq32_t& output) const
64  {
65  const auto err = VLength::write(this->count(), output);
66  if (any(err)) return err;
67 
68  for (uint32_t i = 0; i < this->count_; ++i)
69  {
70  auto serr = this->items_[i].write(output);
71  if (any(serr)) return serr;
72  }
73 
74  return FormatError::ok;
75  }
76 
77  void print(const char* name, IMessagePrinter& printer) const
78  {
79  char message[log4cpp::max_log_entry_size];
80  SAFE_STRING_FORMAT(message, log4cpp::max_log_entry_size, "%s (count = %u)", name, this->count());
81  printer.print(message);
82 
83  for (uint32_t i = 0; i < this->count_; ++i)
84  {
85  SAFE_STRING_FORMAT(message, log4cpp::max_log_entry_size, "field #%u", i + 1);
86  printer.print(message);
87 
88  this->items_[i].print("test", printer); // TODO
89  }
90  }
91 
92  void clear()
93  {
94  this->count_ = 0;
95  }
96 
97  bool push(const StructType& item)
98  {
99  if (this->count_ == MAX_COUNT)
100  {
101  return false;
102  }
103 
104  this->items_[this->count_++] = item;
105 
106  return true;
107  }
108 
109  StructType const* get(uint32_t i) const
110  {
111  if (i >= this->count_)
112  {
113  return nullptr;
114  }
115 
116  return &this->items_[i];
117  }
118 
119  uint32_t count() const
120  {
121  return this->count_;
122  }
123 
124  private:
125 
126  uint32_t count_ = 0;
127  StructType items_[MAX_COUNT];
128  };
129 
130 }
131 
132 #endif
SSP21-cpp main namespace.
Definition: BufferTypes.h:12
ParseError
Definition: ParseError.h:27
reached an implementation specific capacity limit
FormatError
Definition: FormatError.h:28