Passwordfile library  5.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 CppUtilities;
9 
10 namespace Io {
11 
22 Field::Field(AccountEntry *tiedAccount, const string &name, const string &value)
23  : m_name(name)
24  , m_value(value)
25  , m_type(FieldType::Normal)
26  , m_tiedAccount(tiedAccount)
27 {
28 }
29 
35 Field::Field(AccountEntry *tiedAccount, istream &stream)
36 {
37  BinaryReader reader(&stream);
38  const int version = reader.readByte();
39  if (version != 0x0 && version != 0x1) {
40  throw ParsingException("Field version is not supported.");
41  }
42  m_name = reader.readLengthPrefixedString();
43  m_value = reader.readLengthPrefixedString();
44  std::uint8_t type = reader.readByte();
45  if (!isValidType(type)) {
46  throw ParsingException("Field type is not supported.");
47  }
48  m_type = static_cast<FieldType>(type);
49  // read extended header for version 0x1
50  if (version == 0x1) {
51  const std::uint16_t extendedHeaderSize = reader.readUInt16BE();
52  // currently there's nothing to read here
53  m_extendedData = reader.readString(extendedHeaderSize);
54  }
55  m_tiedAccount = tiedAccount;
56 }
57 
61 void Field::make(ostream &stream) const
62 {
63  BinaryWriter writer(&stream);
64  writer.writeByte(m_extendedData.empty() ? 0x0 : 0x1); // version
65  writer.writeLengthPrefixedString(m_name);
66  writer.writeLengthPrefixedString(m_value);
67  writer.writeByte(static_cast<std::uint8_t>(m_type));
68  if (!m_extendedData.empty()) {
69  writer.writeUInt16BE(m_extendedData.size());
70  writer.writeString(m_extendedData);
71  }
72 }
73 } // namespace Io
Io::ParsingException
The exception that is thrown when a parsing error occurs.
Definition: parsingexception.h:11
Io::FieldType::Normal
Io::Field::make
void make(std::ostream &stream) const
Serializes the current instance to the specified stream.
Definition: field.cpp:61
Io::Field::isValidType
static bool isValidType(int number)
Returns whether the specified number is a valid field type.
Definition: field.h:115
parsingexception.h
Io
Contains all IO related classes.
Definition: cryptoexception.h:9
Io::Field::Field
Field()
Definition: field.h:42
CppUtilities
Definition: utils.h:12
Io::Field::type
FieldType type() const
Returns the type.
Definition: field.h:91
field.h
Io::Field::m_extendedData
std::string m_extendedData
Definition: field.h:39
Io::FieldType
FieldType
Definition: field.h:11
Io::AccountEntry
The exception that is thrown when a parsing error occurs.
Definition: entry.h:170
Io::Field::tiedAccount
AccountEntry * tiedAccount() const
Returns the tied account.
Definition: field.h:107