Passwordfile library  4.0.0
C++ library to read/write passwords from/to encrypted files
field.cpp
Go to the documentation of this file.
1 #include "./field.h"
2 #include "./parsingexception.h"
3 
4 #include <c++utilities/io/binaryreader.h>
5 #include <c++utilities/io/binarywriter.h>
6 
7 using namespace std;
8 using namespace IoUtilities;
9 using namespace ConversionUtilities;
10 
11 namespace Io {
12 
23 Field::Field(AccountEntry *tiedAccount, const string &name, const string &value)
24  : m_name(name)
25  , m_value(value)
26  , m_type(FieldType::Normal)
27  , m_tiedAccount(tiedAccount)
28 {
29 }
30 
36 Field::Field(AccountEntry *tiedAccount, istream &stream)
37 {
38  BinaryReader reader(&stream);
39  const int version = reader.readByte();
40  if (version != 0x0 && version != 0x1) {
41  throw ParsingException("Field version is not supported.");
42  }
43  m_name = reader.readLengthPrefixedString();
44  m_value = reader.readLengthPrefixedString();
45  byte type = reader.readByte();
46  if (!isValidType(type)) {
47  throw ParsingException("Field type is not supported.");
48  }
49  m_type = static_cast<FieldType>(type);
50  // read extended header for version 0x1
51  if (version == 0x1) {
52  const uint16 extendedHeaderSize = reader.readUInt16BE();
53  // currently there's nothing to read here
54  m_extendedData = reader.readString(extendedHeaderSize);
55  }
56  m_tiedAccount = tiedAccount;
57 }
58 
62 void Field::make(ostream &stream) const
63 {
64  BinaryWriter writer(&stream);
65  writer.writeByte(m_extendedData.empty() ? 0x0 : 0x1); // version
66  writer.writeLengthPrefixedString(m_name);
67  writer.writeLengthPrefixedString(m_value);
68  writer.writeByte(static_cast<byte>(m_type));
69  if (!m_extendedData.empty()) {
70  writer.writeUInt16BE(m_extendedData.size());
71  writer.writeString(m_extendedData);
72  }
73 }
74 } // namespace Io
static bool isValidType(int number)
Returns whether the specified number is a valid field type.
Definition: field.h:115
STL namespace.
void make(std::ostream &stream) const
Serializes the current instance to the specified stream.
Definition: field.cpp:62
Field()
Definition: field.h:42
Contains all IO related classes.
FieldType type() const
Returns the type.
Definition: field.h:91
The exception that is thrown when a parsing error occurs.
Definition: entry.h:171
std::string m_extendedData
Definition: field.h:39
FieldType
Definition: field.h:11
The exception that is thrown when a parsing error occurs.
AccountEntry * tiedAccount() const
Returns the tied account.
Definition: field.h:107