-
Notifications
You must be signed in to change notification settings - Fork 2
/
properties.d
84 lines (70 loc) · 2.39 KB
/
properties.d
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
// Written in the D programming language
module dranges.properties;
// TODO: suppressProperty?
import std.conv: to;
public import std.variant;
template addProperties() {
Variant[] propertiesValues;
int[string] propertiesNames;
bool hasProperty(string propertyName) {
if (propertyName in propertiesNames) return true;
return false;
}
bool hasProperties() {
return (propertiesValues.length == 0 ? false : true);
}
void addProperty(T)(string propertyName, T val) {
if (hasProperty(propertyName)) {
throw new Exception("Property " ~ propertyName ~ " already existing.");
} else {
propertiesNames[propertyName] = propertiesValues.length; // index in the 'propertiesValues' array
propertiesValues ~= Variant(val);
}
}
void addProperties(T, R...)(string propertyName, T val, R rest) {
addProperty(propertyName, val);
static if (rest.length>1)
addProperties(rest);
static if (rest.length == 1)
throw new Exception("addProperties: the arguments list has not a ('name', value) form.");
}
void changeProperty(T)(string propertyName, T newVal) {
if (hasProperty(propertyName)) {
propertiesValues[propertiesNames[propertyName]] = newVal;
}
else {
addProperty(propertyName, newVal);
}
}
T getProperty(T)(string propertyName) {
if (hasProperty(propertyName)) {
return propertiesValues[propertiesNames[propertyName]].get!(T);
}
else {
throw new Exception(propertyName ~ ": no such property.");
}
}
string name() {
return hasProperty("name") ? getProperty!string("name")
: "anonymous " ~ typeof(this).stringof;
}
/// todo : change this function's name
string[] getPropertiesNames() {
return propertiesNames.keys;
}
/// To be tested!
void copyProperties(T)(T source) {
if (source.hasProperties) {
propertiesValues = source.propertiesValues;
propertiesNames = source.propertiesNames;
}
}
void writeProperties() {
string ts;
foreach(string name; propertiesNames.keys) {
// int p =
ts ~= name ~ ": " ~ std.conv.to!string(propertiesNames[name]) ~ " ";
}
writeln(ts);
}
}