aboutsummaryrefslogtreecommitdiff
path: root/src/common/query.rs
blob: 00d79b21f1bc8fbdf223ec7697b5ddc53f2a6971 (plain)
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
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
use crate::common::db::Database;
use crate::common::expr::Expr;
use crate::common::ip;
use std::fmt;

#[derive(Debug)]
pub enum Error {
    Empty,
    Invalid,
    IP(ip::Error),
    ExpectedArray(Expr),
    ExpectedBlob(Expr),
    InvalidArgsCount {
        cmd: String,
        expected: usize,
        actual: usize,
    },
}

#[derive(Debug)]
pub enum Query {
    Children { ip_block: ip::Block },
    Del { ip_block: ip::Block },
    Echo { msg: Vec<u8> },
    Exists { ip_block: ip::Block },
    Get { ip_block: ip::Block },
    Info { ip_block: ip::Block },
    Parent { ip_block: ip::Block },
    Set { ip_block: ip::Block, value: Expr },
}

impl Query {
    pub fn from_expr(expr: Expr) -> Result<Self, Error> {
        let mut xs = if let Expr::Array(xs) = expr {
            xs
        } else {
            return Err(Error::ExpectedArray(expr));
        };

        if xs.is_empty() {
            return Err(Error::Empty);
        }
        let cmd_expr = xs.remove(0);
        let cmd = if let Expr::Blob(cmd) = cmd_expr {
            cmd
        } else {
            return Err(Error::ExpectedBlob(cmd_expr));
        };

        match &*cmd {
            b"ECHO" => build_echo(xs),         // ECHO str
            b"SET" => build_set(xs),           // SET ::/32 Expr
            b"GET" => build_get(xs),           // GET ::/32
            b"DEL" => build_del(xs),           // DEL ::/32
            b"EXISTS" => build_exists(xs),     // EXISTS ::/32
            b"INFO" => build_info(xs),         // EXISTS ::/32
            b"PARENT" => build_parent(xs),     // SUP ::/32
            b"CHILDREN" => build_children(xs), // SUB ::/32
            _ => Err(Error::Invalid),
        }
    }

    pub fn exec(&self, db: &mut Database) -> Expr {
        match self {
            Self::Echo { msg } => Expr::Blob(msg.clone()),
            Self::Set { ip_block, value: _ } => {
                db.set(*ip_block, std::collections::HashMap::new());
                Expr::Blob(b"OK".to_vec())
            }
            Self::Get { ip_block } => db.get(ip_block).map(|x| x.into()).unwrap_or(Expr::Null),
            Self::Del { ip_block } => db
                .del(ip_block)
                .map_or(Expr::Null, |_| Expr::Blob(b"OK".to_vec())),
            Self::Exists { ip_block } => Expr::Bool(db.exists(ip_block)),
            Self::Info { ip_block } => {
                let info: Vec<(&str, String)> = db.info(ip_block).into();
                info.into()
            }
            Self::Parent { ip_block } => {
                db.parent(ip_block).map(|x| x.into()).unwrap_or(Expr::Null)
            }
            Self::Children { ip_block } => db.children(ip_block).into(),
        }
    }
}

// Display

impl fmt::Display for Query {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let res = match self {
            Query::Set { ip_block, value } => {
                format!("SET {} {}", ip_block, value)
            }
            Query::Get { ip_block } => {
                format!("GET {}", ip_block)
            }
            Query::Echo { msg } => {
                format!("ECHO {:?}", String::from_utf8_lossy(msg).into_owned())
            }
            Query::Del { ip_block } => {
                format!("DEL {}", ip_block)
            }
            Query::Exists { ip_block } => {
                format!("EXISTS {}", ip_block)
            }
            Query::Info { ip_block } => {
                format!("INFO {}", ip_block)
            }
            Query::Parent { ip_block } => {
                format!("PARENT {}", ip_block)
            }
            Query::Children { ip_block } => {
                format!("CHILDREN {}", ip_block)
            }
        };

        write!(f, "{}", res)
    }
}

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        let res = match self {
            Error::Empty => "Received an empty query.".to_string(),
            Error::ExpectedArray(got) => format!("Expected an ARRAY, got: {:?}.", got),
            Error::ExpectedBlob(got) => format!("Expected a BLOB, got: {:?}.", got),
            Error::IP(e) => format!("IP error: {e:?}"),
            Error::Invalid => "Received an invalid query.".to_string(),
            Error::InvalidArgsCount {
                cmd,
                expected,
                actual,
            } => format!(
                "Invalid number of arguments for {:?}. Expected {} but got {}.",
                cmd, expected, actual
            ),
        };

        write!(f, "{}", res)
    }
}

// Builders

fn build_echo(mut args: Vec<Expr>) -> Result<Query, Error> {
    count_args("ECHO", &args, 1)?;

    let expr = args.remove(0);
    let msg = if let Expr::Blob(k) = expr {
        k
    } else {
        return Err(Error::ExpectedBlob(expr));
    };
    Ok(Query::Echo { msg })
}

fn build_get(mut args: Vec<Expr>) -> Result<Query, Error> {
    count_args("GET", &args, 1)?;

    let expr = args.remove(0);
    let ip_block = if let Expr::Blob(ref addr) = expr {
        ip::Block::from_bytestring(addr).map_err(Error::IP)?
    } else {
        return Err(Error::ExpectedBlob(expr));
    };
    Ok(Query::Get { ip_block })
}
fn build_set(mut args: Vec<Expr>) -> Result<Query, Error> {
    count_args("SET", &args, 2)?;

    let expr = args.remove(0);
    let ip_block = if let Expr::Blob(ref addr) = expr {
        ip::Block::from_bytestring(addr).map_err(Error::IP)?
    } else {
        return Err(Error::ExpectedBlob(expr));
    };
    Ok(Query::Set {
        ip_block,
        value: args.remove(0),
    })
}
fn build_del(mut args: Vec<Expr>) -> Result<Query, Error> {
    count_args("DEL", &args, 1)?;

    let expr = args.remove(0);
    let ip_block = if let Expr::Blob(ref addr) = expr {
        ip::Block::from_bytestring(addr).map_err(Error::IP)?
    } else {
        return Err(Error::ExpectedBlob(expr));
    };
    Ok(Query::Del { ip_block })
}
fn build_exists(mut args: Vec<Expr>) -> Result<Query, Error> {
    count_args("EXISTS", &args, 1)?;

    let expr = args.remove(0);
    let ip_block = if let Expr::Blob(ref addr) = expr {
        ip::Block::from_bytestring(addr).map_err(Error::IP)?
    } else {
        return Err(Error::ExpectedBlob(expr));
    };
    Ok(Query::Exists { ip_block })
}
fn build_info(mut args: Vec<Expr>) -> Result<Query, Error> {
    count_args("INFO", &args, 1)?;

    let expr = args.remove(0);
    let ip_block = if let Expr::Blob(ref addr) = expr {
        ip::Block::from_bytestring(addr).map_err(Error::IP)?
    } else {
        return Err(Error::ExpectedBlob(expr));
    };
    Ok(Query::Info { ip_block })
}
fn build_parent(mut args: Vec<Expr>) -> Result<Query, Error> {
    count_args("PARENT", &args, 1)?;

    let expr = args.remove(0);
    let ip_block = if let Expr::Blob(ref addr) = expr {
        ip::Block::from_bytestring(addr).map_err(Error::IP)?
    } else {
        return Err(Error::ExpectedBlob(expr));
    };
    Ok(Query::Parent { ip_block })
}
fn build_children(mut args: Vec<Expr>) -> Result<Query, Error> {
    count_args("CHILDREN", &args, 1)?;

    let expr = args.remove(0);
    let ip_block = if let Expr::Blob(ref addr) = expr {
        ip::Block::from_bytestring(addr).map_err(Error::IP)?
    } else {
        return Err(Error::ExpectedBlob(expr));
    };
    Ok(Query::Children { ip_block })
}

// Helpers

fn count_args<T>(cmd: &str, args: &Vec<T>, expected_count: usize) -> Result<(), Error> {
    let args_count = args.len();
    if args_count != expected_count {
        return Err(Error::InvalidArgsCount {
            cmd: cmd.to_string(),
            expected: expected_count,
            actual: args_count,
        });
    }

    Ok(())
}