-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPreferences.cpp
94 lines (77 loc) · 2.07 KB
/
Preferences.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
//
// Preferences.cpp
// Chip-8 Emu
//
// Created by Daniel Hauser on 30.12.14.
// Copyright (c) 2014 Daniel Hauser. All rights reserved.
//
#include "Preferences.hpp"
#include <memory>
#include <cstdio>
#include <cstdint>
static uint8_t HexChToNibble(char hex)
{
return (hex >= '0' && hex <= '9') ? hex - '0'
: (hex >= 'a' && hex <= 'f') ? hex - 'a' + 10
: (hex >= 'A' && hex <= 'F') ? hex - 'A' + 10
: 0;
}
static uint8_t HexStrToByte(const std::string &str)
{
return HexChToNibble(str[0]) << 4 | HexChToNibble(str[1]);
}
static unsigned int ParseColorStr(const std::string &str)
{
unsigned int color = 0;
for(int i = 0; i < str.length(); i += 2)
{
auto byte = HexStrToByte(str.substr(i, 2));
color |= byte;
if(i < str.length() - 2)
color <<= 8;
}
return color;
}
namespace Preferences
{
static rapidjson::Document doc;
bool Load(const std::string &file)
{
FILE *fp = fopen(file.c_str(), "rb");
if(!fp) return false;
fseek(fp, 0, SEEK_END);
auto fileSize = ftell(fp);
fseek(fp, 0, SEEK_SET);
std::unique_ptr<char[]> fileContent(new char[fileSize]);
fread(fileContent.get(), 1, fileSize, fp);
fclose(fp);
doc.Parse(fileContent.get());
return doc.IsObject();
}
rapidjson::Value &Get(const std::string &name)
{
return doc[name.c_str()];
}
// Helpers
unsigned int AsHex(const char *name, unsigned int defaultHex)
{
if(!doc.IsObject()) return defaultHex;
auto iter = doc.FindMember(name);
if(iter == doc.MemberEnd()) return defaultHex;
return ParseColorStr(iter->value.GetString());
}
double AsNumber(const char *name, double defaultNumber)
{
if(!doc.IsObject()) return defaultNumber;
auto iter = doc.FindMember(name);
if(iter == doc.MemberEnd()) return defaultNumber;
return iter->value.GetDouble();
}
bool AsBool(const char *name, bool defaultBool)
{
if(!doc.IsObject()) return defaultBool;
auto iter = doc.FindMember(name);
if(iter == doc.MemberEnd()) return defaultBool;
return iter->value.GetBool();
}
}