1 /*
2  * Hunt - A redis client library for D programming language.
3  *
4  * Copyright (C) 2018-2019 HuntLabs
5  *
6  * Website: https://www.huntlabs.net/
7  *
8  * Licensed under the Apache-2.0 License.
9  *
10  */
11  
12 module hunt.redis.params.Params;
13 
14 import hunt.collection.ArrayList;
15 import hunt.collection.HashMap;
16 import hunt.collection.Map;
17 import hunt.Exceptions;
18 
19 import hunt.redis.util.SafeEncoder;
20 
21 import hunt.String;
22 import hunt.Byte;
23 import hunt.Integer;
24 
25 import std.array;
26 import std.conv;
27 import std.variant;
28 
29 abstract class Params {
30 
31     private Map!(string, Variant) params;
32 
33     this() {
34         params = new HashMap!(string, Variant)();
35     }
36 
37     T getParam(T)(string name) {
38         if (params is null || params.isEmpty())
39             return T.init;
40         Variant v = params.get(name);
41         return v.get!T();
42     }
43 
44     const(ubyte)[][] getByteParams() {
45         if (params is null)
46             return null;
47         ArrayList!(const(ubyte)[]) byteParams = new ArrayList!(const(ubyte)[])();
48 
49         foreach(string key, Variant value; params) {
50           byteParams.add(SafeEncoder.encode(key));
51 
52           if (value.hasValue()) {
53               
54             //   byteParams.add(value.toString());
55             if (value.type == typeid(byte[]) || value.type == typeid(const(ubyte)[])) {
56               byteParams.add(value.get!(const(ubyte)[])());
57             } else {
58               byteParams.add(SafeEncoder.encode(to!string(value)));
59             }
60           }
61         }
62 
63         return byteParams.toArray();
64 
65         // return byteParams.toArray(new byte[byteParams.size()][]);
66     }
67 
68     protected bool contains(string name) {
69         if (params is null)
70             return false;
71 
72         return params.containsKey(name);
73     }
74 
75     protected void addParam(string name, string value) {
76         params.put(name, Variant(value));
77     }
78 
79     protected void addParam(string name, int value) {
80         params.put(name, Variant(value));
81     }
82 
83     protected void addParam(string name, long value) {
84         params.put(name, Variant(value));
85     }
86 
87     protected void addParam(string name, byte[] value) {
88         params.put(name, Variant(value));
89     }
90 
91     protected void addParam(string name, Object value) {
92         params.put(name, Variant(value));
93     }
94 
95     protected void addParam(string name, Variant value) {
96         params.put(name, value);
97     }
98 
99     protected void addParam(string name) {
100         params.put(name, Variant(null));
101     }
102 
103 }