#![allow(dead_code)]
use std::collections::HashMap;
use crate::document::SearchDocument;
pub const CMD_USE: u8 = 1;
pub const CMD_INDEX_SET_DB: u8 = 32; pub const CMD_INDEX_SUBMIT: u8 = 34;
pub const CMD_INDEX_REMOVE: u8 = 35;
pub const CMD_INDEX_EXDATA: u8 = 36; pub const CMD_INDEX_CLEAN_DB: u8 = 37; pub const CMD_DELETE_PROJECT: u8 = 38; pub const CMD_INDEX_COMMIT: u8 = 39;
pub const CMD_SEARCH_GET_RESULT: u8 = 66;
pub const CMD_OK: u8 = 128;
pub const CMD_ERR: u8 = 129;
pub const CMD_SEARCH_RESULT_DOC: u8 = 140;
pub const CMD_SEARCH_RESULT_FIELD: u8 = 141;
pub const CMD_SEARCH_RESULT_FACETS: u8 = 142;
pub const CMD_SEARCH_RESULT_MATCHED: u8 = 143;
pub const CMD_DOC_VALUE: u8 = 161;
pub const CMD_DOC_INDEX: u8 = 162;
pub const CMD_INDEX_REQUEST: u8 = 163;
pub const CMD_SEARCH_SET_SORT: u8 = 192; pub const CMD_SEARCH_SET_NUMERIC: u8 = 194; pub const CMD_QUERY_INIT: u8 = 224; pub const CMD_QUERY_PARSE: u8 = 225; pub const CMD_QUERY_RANGE: u8 = 228;
pub const OK_PROJECT: u16 = 201;
pub const OK_RESULT_BEGIN: u16 = 206;
pub const OK_RESULT_END: u16 = 207;
pub const OK_RQST_FINISHED: u16 = 250;
pub const OK_DB_CHANGED: u16 = 251;
pub const OK_DB_CLEAN: u16 = 253;
pub const OK_PROJECT_DEL: u16 = 255;
pub const OK_DB_COMMITED: u16 = 256;
pub const MIXED_VNO: u8 = 255; pub const WITHPOS: u8 = 0x40; pub const SAVEVALUE: u8 = 0x80; pub const NUMERIC_FLAG: u8 = 0x80; pub const SORT_ASCENDING: u8 = 0x80; pub const SORT_TYPE_VALUE: u8 = 2;
pub fn pack_cmd(cmd: u8, arg1: u8, arg2: u8, buf: &[u8], buf1: &[u8]) -> Vec<u8> {
debug_assert!(buf1.len() <= 255, "buf1 exceeds 255 bytes");
let mut out = Vec::with_capacity(8 + buf.len() + buf1.len());
out.push(cmd);
out.push(arg1);
out.push(arg2);
out.push(buf1.len() as u8);
out.extend_from_slice(&(buf.len() as u32).to_le_bytes());
out.extend_from_slice(buf);
out.extend_from_slice(buf1);
out
}
pub fn parse_packet(data: &[u8]) -> Option<(u8, u16, &[u8], &[u8])> {
if data.len() < 8 {
return None;
}
let blen1 = data[3] as usize;
let blen = u32::from_le_bytes(data[4..8].try_into().unwrap()) as usize;
if 8 + blen + blen1 > data.len() {
return None;
}
Some((
data[0],
(u16::from(data[1]) << 8) | u16::from(data[2]),
&data[8..8 + blen],
&data[8 + blen..8 + blen + blen1],
))
}
pub fn value_bytes(value: &serde_json::Value) -> Vec<u8> {
match value {
serde_json::Value::String(s) => s.as_bytes().to_vec(),
serde_json::Value::Number(n) => n.to_string().into_bytes(),
serde_json::Value::Bool(b) => vec![if *b { b'1' } else { b'0' }],
_ => Vec::new(),
}
}
pub fn doc_commands(
scheme: &mut FieldScheme,
doc: &SearchDocument,
update: bool,
) -> crate::Result<Vec<u8>> {
let id_vno = scheme.id_vno();
let id_name = scheme.id_name().to_string();
let mut out = Vec::new();
if update {
out.extend_from_slice(&pack_cmd(
CMD_INDEX_REQUEST,
1,
id_vno,
doc.id.to_lowercase().as_bytes(),
&[],
));
} else {
out.extend_from_slice(&pack_cmd(CMD_INDEX_REQUEST, 0, 0, &[], &[]));
}
out.extend_from_slice(&index_field(
scheme.field(scheme.id_name()).expect("id field missing from scheme"),
doc.id.as_bytes(),
));
for (name, value) in &doc.fields {
if name == &id_name {
continue; }
let bytes = value_bytes(value);
if bytes.is_empty() {
continue; }
scheme.add_dynamic(name)?;
if let Some(field) = scheme.field(name) {
out.extend_from_slice(&index_field(field, &bytes));
}
}
Ok(out)
}
pub fn index_field(field: &FieldDef, value: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
if !field.custom_tokenizer() {
let base = field.weight | if field.with_pos { WITHPOS } else { 0 };
if field.index_mixed {
out.extend_from_slice(&pack_cmd(CMD_DOC_INDEX, base, MIXED_VNO, value, &[]));
}
if field.index_self {
let save = if field.is_numeric() { 0 } else { SAVEVALUE };
out.extend_from_slice(&pack_cmd(CMD_DOC_INDEX, base | save, field.vno, value, &[]));
}
if !field.index_self || field.is_numeric() {
let flag = if field.is_numeric() { NUMERIC_FLAG } else { 0 };
out.extend_from_slice(&pack_cmd(CMD_DOC_VALUE, flag, field.vno, value, &[]));
}
} else {
out.extend_from_slice(&pack_cmd(CMD_DOC_VALUE, 0, field.vno, value, &[]));
}
out
}
#[derive(Clone, Copy, PartialEq, Debug)]
pub enum FieldKind {
Id,
Title,
Body,
String,
Numeric,
Date,
}
#[derive(Clone, Debug)]
pub struct FieldDef {
pub name: String,
pub vno: u8,
pub kind: FieldKind,
pub index_self: bool, pub index_mixed: bool, pub with_pos: bool, pub weight: u8,
pub tokenizer: Option<String>,
}
impl FieldDef {
pub fn custom_tokenizer(&self) -> bool {
self.tokenizer.as_deref().is_some_and(|t| t != "full")
}
pub fn is_numeric(&self) -> bool {
matches!(self.kind, FieldKind::Numeric | FieldKind::Date)
}
}
pub struct FieldScheme {
fields: Vec<FieldDef>,
by_name: HashMap<String, usize>,
dynamic: bool,
}
struct Section {
name: String,
kind: FieldKind,
index: String,
weight: u8, tokenizer: Option<String>,
}
impl Default for Section {
fn default() -> Self {
Self { name: String::new(), kind: FieldKind::String, index: String::new(), weight: 0, tokenizer: None }
}
}
fn parse_kind(value: &str) -> Option<FieldKind> {
match value {
"id" => Some(FieldKind::Id),
"title" => Some(FieldKind::Title),
"body" => Some(FieldKind::Body),
"string" => Some(FieldKind::String),
"numeric" => Some(FieldKind::Numeric),
"date" => Some(FieldKind::Date),
_ => None,
}
}
fn unquote(value: &str) -> String {
let value = value.trim();
value
.strip_prefix('"')
.and_then(|v| v.strip_suffix('"'))
.or_else(|| value.strip_prefix('\'').and_then(|v| v.strip_suffix('\'')))
.unwrap_or(value)
.to_string()
}
impl FieldScheme {
pub fn default() -> Self {
let mut scheme = Self { fields: Vec::new(), by_name: HashMap::new(), dynamic: true };
scheme.push(FieldDef {
name: "id".to_string(),
vno: 0,
kind: FieldKind::Id,
index_self: true,
index_mixed: false,
with_pos: false,
weight: 1,
tokenizer: None,
});
scheme
}
pub fn from_ini(ini: &str) -> Option<Self> {
let mut scheme = Self { fields: Vec::new(), by_name: HashMap::new(), dynamic: false };
let mut section: Option<Section> = None;
for raw in ini.lines() {
let line = raw.trim();
if line.is_empty() || line.starts_with('#') || line.starts_with(';') {
continue;
}
if let Some(name) = line.strip_prefix('[').and_then(|l| l.strip_suffix(']')) {
if let Some(sec) = section.take() {
scheme.add_section(sec).ok()?;
}
section = Some(Section { name: name.trim().to_string(), ..Section::default() });
} else if let Some((key, value)) = line.split_once('=') {
if let Some(sec) = section.as_mut() {
match key.trim() {
"type" => sec.kind = parse_kind(&unquote(value)).unwrap_or(FieldKind::String),
"index" => sec.index = unquote(value),
"weight" => sec.weight = unquote(value).parse().unwrap_or(0),
"tokenizer" => sec.tokenizer = Some(unquote(value)),
_ => {} }
}
}
}
if let Some(sec) = section {
scheme.add_section(sec).ok()?;
}
if !scheme.fields.iter().any(|f| f.kind == FieldKind::Id) {
return None;
}
Some(scheme)
}
fn push(&mut self, field: FieldDef) {
self.by_name.insert(field.name.clone(), self.fields.len());
self.fields.push(field);
}
pub fn add_dynamic(&mut self, name: &str) -> crate::Result<()> {
if !self.dynamic || self.has_field(name) || name == self.id_name() {
return Ok(());
}
let vno = (1..=254)
.find(|v| !self.fields.iter().any(|f| f.vno == *v))
.ok_or_else(|| vno_exhausted(name))?;
self.push(FieldDef {
name: name.to_string(),
vno,
kind: FieldKind::String,
index_self: true,
index_mixed: true,
with_pos: false,
weight: 1,
tokenizer: None,
});
Ok(())
}
pub fn has_field(&self, name: &str) -> bool {
self.by_name.contains_key(name)
}
pub fn field(&self, name: &str) -> Option<&FieldDef> {
self.by_name.get(name).map(|&i| &self.fields[i])
}
pub fn id_vno(&self) -> u8 {
self.fields.iter().find(|f| f.kind == FieldKind::Id).map(|f| f.vno).unwrap_or(0)
}
pub fn id_name(&self) -> &str {
self.fields.iter().find(|f| f.kind == FieldKind::Id).map(|f| f.name.as_str()).unwrap_or("id")
}
pub fn numeric_vnos(&self) -> Vec<u8> {
self.fields.iter().filter(|f| f.is_numeric()).map(|f| f.vno).collect()
}
pub fn name_for_vno(&self, vno: u8) -> Option<&str> {
self.fields.iter().find(|f| f.vno == vno).map(|f| f.name.as_str())
}
fn add_section(&mut self, sec: Section) -> crate::Result<()> {
let index = if sec.index.is_empty() {
match sec.kind {
FieldKind::Id => "self",
FieldKind::Title | FieldKind::Body => "both",
_ => "none",
}
} else {
sec.index.as_str()
};
let (index_self, index_mixed, with_pos) = match index {
"both" => (true, true, true),
"self" => (true, false, false),
_ => (false, false, false),
};
let weight = if sec.weight > 0 {
sec.weight
} else if sec.kind == FieldKind::Title {
5 } else {
1
};
let vno = if sec.kind == FieldKind::Id {
0
} else if sec.kind == FieldKind::Body {
MIXED_VNO
} else {
(1..=254)
.find(|v| !self.fields.iter().any(|f| f.vno == *v))
.ok_or_else(|| vno_exhausted(&sec.name))?
};
if sec.kind == FieldKind::Id && self.fields.iter().any(|f| f.kind == FieldKind::Id) {
return Ok(());
}
self.push(FieldDef {
name: sec.name,
vno,
kind: sec.kind,
index_self,
index_mixed,
with_pos,
weight,
tokenizer: sec.tokenizer,
});
Ok(())
}
}
fn vno_exhausted(field: &str) -> crate::ScoutError {
crate::ScoutError::XunSearch(format!(
"xunsearch: field vno exhausted (1..=254 all in use), cannot register `{field}`"
))
}
#[cfg(test)]
#[path = "xunsearch_query_tests.rs"]
mod tests;