Passwordfile library  3.1.2
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 
36 {
37  BinaryReader reader(&stream);
38  int version = reader.readByte();
39  if(version == 0x0 || version == 0x1) {
40  m_name = reader.readLengthPrefixedString();
41  m_value = reader.readLengthPrefixedString();
42  byte type = reader.readByte();
43  if(isValidType(type)) {
44  m_type = static_cast<FieldType>(type);
45  } else {
46  throw ParsingException("Field type is not supported.");
47  }
48  if(version == 0x1) { // version 0x1 has an extended header
49  uint16 extendedHeaderSize = reader.readUInt16BE();
50  // currently there's nothing to read here
51  m_extendedData = reader.readString(extendedHeaderSize);
52  }
53  m_tiedAccount = tiedAccount;
54  } else {
55  throw ParsingException("Field version is not supported.");
56  }
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 
75 }
static bool isValidType(int number)
Returns whether the specified number is a valid field type.
Definition: field.h:114
STL namespace.
Contains all IO related classes.
The exception that is thrown when a parsing error occurs.
Definition: entry.h:147
void make(std::ostream &stream) const
Serializes the current instance to the specified stream.
Definition: field.cpp:62
Field(AccountEntry *tiedAccount, const std::string &name=std::string(), const std::string &value=std::string())
Constructs a new account entry for the specified account with the specified name and value...
Definition: field.cpp:23
std::string m_extendedData
Definition: field.h:43
FieldType type() const
Returns the type.
Definition: field.h:90
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:106