surrealpatch/lib/src/key/index.rs

110 lines
2 KiB
Rust
Raw Normal View History

2022-04-09 09:09:01 +00:00
use crate::sql::array::Array;
2022-06-15 07:41:23 +00:00
use crate::sql::id::Id;
use derive::Key;
use serde::{Deserialize, Serialize};
2022-06-15 07:41:23 +00:00
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Key)]
struct Prefix {
__: u8,
_a: u8,
2022-03-07 12:25:40 +00:00
pub ns: String,
_b: u8,
2022-03-07 12:25:40 +00:00
pub db: String,
_c: u8,
2022-03-07 12:25:40 +00:00
pub tb: String,
_d: u8,
2022-03-07 12:25:40 +00:00
pub ix: String,
}
2022-06-15 07:41:23 +00:00
impl Prefix {
fn new(ns: &str, db: &str, tb: &str, ix: &str) -> Prefix {
Prefix {
__: 0x2f, // /
_a: 0x2a, // *
ns: ns.to_string(),
_b: 0x2a, // *
db: db.to_string(),
_c: 0x2a, // *
tb: tb.to_string(),
_d: 0xa4, // ¤
ix: ix.to_string(),
}
}
}
2022-06-15 07:41:23 +00:00
#[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize, Key)]
pub struct Index {
__: u8,
_a: u8,
pub ns: String,
_b: u8,
pub db: String,
_c: u8,
pub tb: String,
_d: u8,
pub ix: String,
pub fd: Array,
pub id: Option<Id>,
2022-03-25 20:31:45 +00:00
}
pub fn new(ns: &str, db: &str, tb: &str, ix: &str, fd: &Array, id: Option<&Id>) -> Index {
Index::new(
ns.to_string(),
db.to_string(),
tb.to_string(),
ix.to_string(),
fd.to_owned(),
id.cloned(),
)
}
pub fn prefix(ns: &str, db: &str, tb: &str, ix: &str) -> Vec<u8> {
2022-06-15 07:41:23 +00:00
let mut k = Prefix::new(ns, db, tb, ix).encode().unwrap();
k.extend_from_slice(&[0x00]);
k
}
pub fn suffix(ns: &str, db: &str, tb: &str, ix: &str) -> Vec<u8> {
2022-06-15 07:41:23 +00:00
let mut k = Prefix::new(ns, db, tb, ix).encode().unwrap();
k.extend_from_slice(&[0xff]);
k
}
impl Index {
2022-06-15 07:41:23 +00:00
pub fn new(ns: String, db: String, tb: String, ix: String, fd: Array, id: Option<Id>) -> Index {
Index {
__: 0x2f, // /
_a: 0x2a, // *
ns,
_b: 0x2a, // *
db,
_c: 0x2a, // *
tb,
_d: 0xa4, // ¤
ix,
fd,
2022-06-15 07:41:23 +00:00
id,
}
}
}
#[cfg(test)]
mod tests {
#[test]
fn key() {
use super::*;
#[rustfmt::skip]
let val = Index::new(
"test".to_string(),
"test".to_string(),
"test".to_string(),
"test".to_string(),
2022-04-09 09:09:01 +00:00
vec!["test"].into(),
2022-06-15 07:41:23 +00:00
Some("test".into()),
);
let enc = Index::encode(&val).unwrap();
let dec = Index::decode(&enc).unwrap();
assert_eq!(val, dec);
}
}