Skip to main content

kind2sql/
sql_field.rs

1use bytes::buf::Buf;
2
3use crate::Kind;
4
5fn sql_field(
6  blob: impl Fn(&[u8]) -> String,
7  kind: Kind,
8  mut buf: impl Buf,
9  out: &mut Vec<String>,
10) -> vb::Result<()> {
11  use Kind::*;
12  out.push(match kind {
13    Bool => if buf.get_u8() == 0 { 0 } else { 1 }.to_string(),
14    U8 => buf.get_u8().to_string(),
15    I8 => buf.get_i8().to_string(),
16    U16 => buf.get_u16_le().to_string(),
17    I16 => buf.get_i16_le().to_string(),
18    U32 | U64 => {
19      // U32 和 U64 使用 vbyte 编码
20      let (value, consumed) = vb::d(buf.chunk())?;
21      buf.advance(consumed);
22      value.to_string()
23    }
24    I32 => buf.get_i32_le().to_string(),
25    I64 => buf.get_i64_le().to_string(),
26    String | Bytes => {
27      // Bytes , String 编码 = vbyte编码的长度, 内容
28      let (len, consumed) = vb::d(buf.chunk())?;
29      buf.advance(consumed);
30      let len = len as usize;
31      let chunk = buf.chunk();
32      let data = &chunk[..len];
33      let result = match kind {
34        String => sqle::string(data),
35        Bytes => blob(data),
36        _ => unreachable!(),
37      };
38      buf.advance(len);
39      result
40    }
41  });
42  Ok(())
43}
44
45pub trait SqlField {
46  fn blob(data: &[u8]) -> String;
47
48  fn sql_field(kind_li: &[Kind], mut buf: impl Buf) -> vb::Result<Vec<String>> {
49    let mut out = Vec::with_capacity(kind_li.len());
50    for &kind in kind_li {
51      sql_field(Self::blob, kind, &mut buf, &mut out)?;
52    }
53    Ok(out)
54  }
55}