wedb_embed 0.1.2

Embedded database engine providing Redis-like APIs, built on fjall / 嵌入式数据库引擎,提供类似 Redis 的接口,底层基于 fjall 开发
Documentation
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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
use crate::key_composer::{
  ns::is_default_namespace,
  oppv::{
    decode_oppv_u64, encode_oppv_u64, encode_oppv_u64_fixed, encode_oppv_u64_slice, oppv_len_u64,
  },
  small_key::SmallKey,
  tag::{KeyTag, ScopeModeTag},
};

/// 通用子键复用构建器(零堆分配,支持高频循环迭代)
#[derive(Debug, Clone)]
pub struct SubkeyComposer {
  buf: Vec<u8>,
  prefix_len: usize,
}

impl SubkeyComposer {
  #[inline]
  pub fn new(prefix: Vec<u8>) -> Self {
    let prefix_len = prefix.len();
    Self {
      buf: prefix,
      prefix_len,
    }
  }

  #[inline]
  pub fn from_slice(prefix: &[u8]) -> Self {
    let prefix_len = prefix.len();
    let mut buf = Vec::with_capacity(prefix_len + 64);
    buf.extend_from_slice(prefix);
    Self { buf, prefix_len }
  }

  #[inline]
  pub fn compose_sub(&mut self, subkey: &[u8]) -> &[u8] {
    self.buf.truncate(self.prefix_len);
    self.buf.extend_from_slice(subkey);
    &self.buf
  }

  #[inline]
  pub fn compose_sub_u64_be(&mut self, val: u64) -> &[u8] {
    self.buf.truncate(self.prefix_len);
    self.buf.extend_from_slice(&val.to_be_bytes());
    &self.buf
  }

  #[inline]
  pub fn prefix(&self) -> &[u8] {
    &self.buf[..self.prefix_len]
  }
}

/// 统一的物理键编排器(负责多租户隔离、复合数据结构 Key 与子键前缀构造,全面支持纯数字 OPPV 变长保序编码与前缀无关帧化)
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct KeyComposer<'a> {
  ns: &'a str,
  ns_id: u64,
  db: u64,
}

impl<'a> KeyComposer<'a> {
  /// 构造默认命名空间的 KeyComposer(ns_id = 0, db = 0)
  ///
  /// 非默认命名空间必须通过 `new_named()` 传入数据库分配的持久化自增 ID
  #[inline]
  pub fn new(ns: &'a str) -> Self {
    debug_assert!(
      is_default_namespace(ns),
      "KeyComposer::new() only accepts default namespace, use new_named() with a database-allocated ns_id for '{ns}'"
    );
    Self {
      ns,
      ns_id: 0,
      db: 0,
    }
  }

  #[inline]
  pub const fn new_db(db: u64) -> Self {
    Self {
      ns: "default",
      ns_id: 0,
      db,
    }
  }

  #[inline]
  pub const fn new_named(ns: &'a str, ns_id: u64, db: u64) -> Self {
    Self { ns, ns_id, db }
  }

  #[inline(always)]
  pub const fn ns(&self) -> &'a str {
    self.ns
  }

  #[inline(always)]
  pub const fn ns_id(&self) -> u64 {
    self.ns_id
  }

  #[inline(always)]
  pub const fn db(&self) -> u64 {
    self.db
  }

  #[inline(always)]
  pub const fn is_default(&self) -> bool {
    self.ns_id == 0 && self.db == 0
  }

  /// 栈上定长编码作用域前缀到 24 字节数组(零堆分配,零 SmallVec 开销,返回写入字节数)
  ///
  /// 模式 0: 空; 模式 1: \x00\x01[oppv(db)]; 模式 2: \x00\x02[oppv(ns_id)]; 模式 3: \x00\x03[oppv(ns_id)][oppv(db)]
  #[inline(always)]
  pub fn encode_scope_prefix_fixed(&self, buf: &mut [u8; 24]) -> usize {
    if self.is_default() {
      return 0;
    }
    if self.ns_id == 0 {
      buf[0..2].copy_from_slice(ScopeModeTag::DefaultDb.as_prefix_slice());
      let len = encode_oppv_u64_slice(self.db, &mut buf[2..]);
      2 + len
    } else if self.db == 0 {
      buf[0..2].copy_from_slice(ScopeModeTag::Tenant.as_prefix_slice());
      let len = encode_oppv_u64_slice(self.ns_id, &mut buf[2..]);
      2 + len
    } else {
      buf[0..2].copy_from_slice(ScopeModeTag::TenantDb.as_prefix_slice());
      let len1 = encode_oppv_u64_slice(self.ns_id, &mut buf[2..]);
      let len2 = encode_oppv_u64_slice(self.db, &mut buf[2 + len1..]);
      2 + len1 + len2
    }
  }

  /// 编码作用域物理前缀到 Vec<u8>
  #[inline]
  pub fn encode_scope_prefix(&self, buf: &mut Vec<u8>) {
    let mut tmp = [0u8; 24];
    let len = self.encode_scope_prefix_fixed(&mut tmp);
    buf.extend_from_slice(&tmp[..len]);
  }

  /// 编码作用域物理前缀到 SmallKey(栈上零堆分配)
  #[inline]
  pub fn encode_scope_prefix_small(&self, sk: &mut SmallKey) {
    let mut buf = [0u8; 24];
    let len = self.encode_scope_prefix_fixed(&mut buf);
    sk.extend_from_slice(&buf[..len]);
  }

  /// 计算作用域前缀的物理字节长度(纯 CPU 算术判断,零堆内存分配)
  #[inline(always)]
  pub const fn scope_prefix_len(&self) -> usize {
    if self.is_default() {
      0
    } else if self.ns_id == 0 {
      2 + oppv_len_u64(self.db)
    } else if self.db == 0 {
      2 + oppv_len_u64(self.ns_id)
    } else {
      2 + oppv_len_u64(self.ns_id) + oppv_len_u64(self.db)
    }
  }

  /// 构造复合结构元数据存储键(格式:`[scope_prefix][tag][key]`)
  #[inline]
  pub fn compose_meta_key_into(&self, tag: &[u8], key_bytes: &[u8], buf: &mut Vec<u8>) {
    buf.clear();
    buf.reserve(self.scope_prefix_len() + tag.len() + key_bytes.len());
    self.encode_scope_prefix(buf);
    buf.extend_from_slice(tag);
    buf.extend_from_slice(key_bytes);
  }

  #[inline]
  pub fn compose_meta_key_stack(&self, tag: &[u8], key_bytes: &[u8]) -> SmallKey {
    let mut sk = SmallKey::new();
    let mut buf = [0u8; 24];
    let len = self.encode_scope_prefix_fixed(&mut buf);
    sk.extend_from_slice(&buf[..len]);
    sk.extend_from_slice(tag);
    sk.extend_from_slice(key_bytes);
    sk
  }

  /// 构造复合结构子键数据前缀,并额外预留 extra_len 容量(避免二次内存重分配)
  #[inline]
  pub fn compose_prefix_into_with_extra(
    &self,
    tag: &[u8],
    key_bytes: &[u8],
    extra_len: usize,
    buf: &mut Vec<u8>,
  ) {
    buf.clear();
    buf.reserve(
      self.scope_prefix_len()
        + tag.len()
        + oppv_len_u64(key_bytes.len() as u64)
        + key_bytes.len()
        + extra_len,
    );
    self.encode_scope_prefix(buf);
    buf.extend_from_slice(tag);
    encode_oppv_u64(key_bytes.len() as u64, buf);
    buf.extend_from_slice(key_bytes);
  }

  /// 构造复合结构子键数据前缀(前缀无关编码:`[scope_prefix][tag][oppv(len(key))][key]`)
  #[inline]
  pub fn compose_prefix_into(&self, tag: &[u8], key_bytes: &[u8], buf: &mut Vec<u8>) {
    self.compose_prefix_into_with_extra(tag, key_bytes, 0, buf);
  }

  #[inline]
  pub fn compose_prefix(&self, tag: &[u8], key_bytes: &[u8]) -> Vec<u8> {
    let cap =
      self.scope_prefix_len() + tag.len() + oppv_len_u64(key_bytes.len() as u64) + key_bytes.len();
    let mut buf = Vec::with_capacity(cap);
    self.encode_scope_prefix(&mut buf);
    buf.extend_from_slice(tag);
    encode_oppv_u64(key_bytes.len() as u64, &mut buf);
    buf.extend_from_slice(key_bytes);
    buf
  }

  #[inline]
  pub fn compose_prefix_stack(&self, tag: &[u8], key_bytes: &[u8]) -> SmallKey {
    let mut sk = SmallKey::new();
    let mut buf = [0u8; 24];
    let prefix_len = self.encode_scope_prefix_fixed(&mut buf);
    sk.extend_from_slice(&buf[..prefix_len]);
    sk.extend_from_slice(tag);
    let mut tmp = [0u8; 9];
    let len = encode_oppv_u64_fixed(key_bytes.len() as u64, &mut tmp);
    sk.extend_from_slice(&tmp[..len]);
    sk.extend_from_slice(key_bytes);
    sk
  }

  #[inline]
  pub fn compose_subkey_stack(&self, tag: &[u8], key_bytes: &[u8], subkey: &[u8]) -> SmallKey {
    let mut sk = SmallKey::new();
    let mut buf = [0u8; 24];
    let prefix_len = self.encode_scope_prefix_fixed(&mut buf);
    sk.extend_from_slice(&buf[..prefix_len]);
    sk.extend_from_slice(tag);
    let mut tmp = [0u8; 9];
    let len = encode_oppv_u64_fixed(key_bytes.len() as u64, &mut tmp);
    sk.extend_from_slice(&tmp[..len]);
    sk.extend_from_slice(key_bytes);
    sk.extend_from_slice(subkey);
    sk
  }

  /// 栈上定长构造带有两个子键分量的存储键(零堆分配,如 score 索引、时间戳分块、布谷鸟分页)
  #[inline]
  pub fn compose_subkey2_stack(
    &self,
    tag: &[u8],
    key_bytes: &[u8],
    sub1: &[u8],
    sub2: &[u8],
  ) -> SmallKey {
    let mut sk = SmallKey::new();
    let mut buf = [0u8; 24];
    let prefix_len = self.encode_scope_prefix_fixed(&mut buf);
    sk.extend_from_slice(&buf[..prefix_len]);
    sk.extend_from_slice(tag);
    let mut tmp = [0u8; 9];
    let len = encode_oppv_u64_fixed(key_bytes.len() as u64, &mut tmp);
    sk.extend_from_slice(&tmp[..len]);
    sk.extend_from_slice(key_bytes);
    sk.extend_from_slice(sub1);
    sk.extend_from_slice(sub2);
    sk
  }

  /// 栈上定长构造带有 OPPV 长度前缀的层级子键(零堆分配,如 Stream 消费者元数据、PEL 项)
  #[inline]
  pub fn compose_oppv_subkey_stack(
    &self,
    tag: &[u8],
    key_bytes: &[u8],
    mid_bytes: &[u8],
    sub: &[u8],
  ) -> SmallKey {
    let mut sk = SmallKey::new();
    let mut buf = [0u8; 24];
    let prefix_len = self.encode_scope_prefix_fixed(&mut buf);
    sk.extend_from_slice(&buf[..prefix_len]);
    sk.extend_from_slice(tag);
    let mut tmp = [0u8; 9];
    let len1 = encode_oppv_u64_fixed(key_bytes.len() as u64, &mut tmp);
    sk.extend_from_slice(&tmp[..len1]);
    sk.extend_from_slice(key_bytes);
    let len2 = encode_oppv_u64_fixed(mid_bytes.len() as u64, &mut tmp);
    sk.extend_from_slice(&tmp[..len2]);
    sk.extend_from_slice(mid_bytes);
    sk.extend_from_slice(sub);
    sk
  }

  #[inline]
  pub fn compose_meta_prefix_stack(&self, tag: &[u8]) -> SmallKey {
    let mut sk = SmallKey::new();
    let mut buf = [0u8; 24];
    let prefix_len = self.encode_scope_prefix_fixed(&mut buf);
    sk.extend_from_slice(&buf[..prefix_len]);
    sk.extend_from_slice(tag);
    sk
  }

  #[inline]
  pub fn compose_meta_prefix(&self, tag: &[u8]) -> Vec<u8> {
    let mut v = Vec::with_capacity(self.scope_prefix_len() + tag.len());
    self.encode_scope_prefix(&mut v);
    v.extend_from_slice(tag);
    v
  }

  #[inline]
  pub fn namespace_prefix(&self) -> Vec<u8> {
    let mut v = Vec::with_capacity(self.scope_prefix_len());
    self.encode_scope_prefix(&mut v);
    v
  }

  // ==================== 作用域反查与提取 ====================

  /// 从多租户/多库物理键中严格解析作用域前缀(适用于 data_ns / meta_ns 列族中的物理键)
  ///
  /// 返回 `(KeyComposer, prefix_len, remain_slice)`
  #[inline]
  pub fn parse_scoped_prefix(full_key: &[u8]) -> Option<(Self, usize, &[u8])> {
    if full_key.len() < 3 || full_key[0] != 0 {
      return None;
    }
    let scope_tag = ScopeModeTag::from_u8(full_key[1])?;
    match scope_tag {
      ScopeModeTag::DefaultDb => {
        let (db, c) = decode_oppv_u64(&full_key[2..])?;
        let prefix_len = 2 + c;
        if full_key.len() > prefix_len {
          Some((Self::new_db(db), prefix_len, &full_key[prefix_len..]))
        } else {
          None
        }
      }
      ScopeModeTag::Tenant => {
        let (ns_id, c) = decode_oppv_u64(&full_key[2..])?;
        let prefix_len = 2 + c;
        if full_key.len() > prefix_len {
          Some((
            Self::new_named("", ns_id, 0),
            prefix_len,
            &full_key[prefix_len..],
          ))
        } else {
          None
        }
      }
      ScopeModeTag::TenantDb => {
        let (ns_id, c1) = decode_oppv_u64(full_key.get(2..)?)?;
        let (db, c2) = decode_oppv_u64(full_key.get(2 + c1..)?)?;
        let prefix_len = 2 + c1 + c2;
        if full_key.len() > prefix_len {
          Some((
            Self::new_named("", ns_id, db),
            prefix_len,
            &full_key[prefix_len..],
          ))
        } else {
          None
        }
      }
    }
  }

  /// 判断物理键是否属于当前 KeyComposer 所在的作用域
  #[inline(always)]
  pub fn is_key_in_ns(&self, full_key: &[u8]) -> bool {
    if self.is_default() {
      !full_key.is_empty() && KeyTag::from_u8(full_key[0]).is_some()
    } else {
      let mut buf = [0u8; 24];
      let len = self.encode_scope_prefix_fixed(&mut buf);
      let prefix_slice = &buf[..len];
      full_key.starts_with(prefix_slice)
        && full_key.len() > prefix_slice.len()
        && KeyTag::from_u8(full_key[prefix_slice.len()]).is_some()
    }
  }

  /// 高性能零分配提取用户 Key(基于物理类型前缀与 OPPV 长度编码精准分帧,100% 免疫任何特殊字节与冒号)
  #[inline]
  pub fn extract_user_key<'b>(&self, full_key: &'b [u8]) -> Option<&'b [u8]> {
    let remain = if self.is_default() {
      full_key
    } else {
      let mut buf = [0u8; 24];
      let len = self.encode_scope_prefix_fixed(&mut buf);
      let prefix_slice = &buf[..len];
      if !full_key.starts_with(prefix_slice) {
        return None;
      }
      &full_key[len..]
    };

    if remain.is_empty() {
      return None;
    }

    let tag = KeyTag::from_u8(remain[0])?;

    match tag {
      KeyTag::RawString
      | KeyTag::HashMeta
      | KeyTag::ListMeta
      | KeyTag::SetMeta
      | KeyTag::ZSetMeta
      | KeyTag::BloomMeta
      | KeyTag::CuckooMeta
      | KeyTag::BitmapMeta
      | KeyTag::HllMeta
      | KeyTag::HllRaw
      | KeyTag::JsonMeta
      | KeyTag::SortedIntMeta
      | KeyTag::StreamMeta
      | KeyTag::TDigestMeta
      | KeyTag::TimeSeriesMeta
      | KeyTag::FtSchema
      | KeyTag::FtAlias => Some(&remain[1..]),

      KeyTag::HashData
      | KeyTag::ListData
      | KeyTag::SetData
      | KeyTag::ZSetData
      | KeyTag::ZSetScore
      | KeyTag::BloomData
      | KeyTag::CuckooData
      | KeyTag::BitmapData
      | KeyTag::JsonData
      | KeyTag::SortedIntData
      | KeyTag::StreamData
      | KeyTag::StreamGroup
      | KeyTag::StreamConsumer
      | KeyTag::StreamPel
      | KeyTag::TDigestData
      | KeyTag::TimeSeriesData
      | KeyTag::FtIndex
      | KeyTag::FtData => {
        let (key_len, consumed) = decode_oppv_u64(&remain[1..])?;
        let start = 1 + consumed;
        let end = start.checked_add(key_len as usize)?;
        remain.get(start..end)
      }
    }
  }

  /// 将当前命名空间的底层键转换为目标命名空间的底层键(零拷贝/二进制安全)
  #[inline]
  pub fn transform_key_to_target_bytes(
    &self,
    full_key: &[u8],
    target_kc: &KeyComposer<'_>,
  ) -> Option<Vec<u8>> {
    let remain = if self.is_default() {
      if full_key.is_empty() || KeyTag::from_u8(full_key[0]).is_none() {
        return None;
      }
      full_key
    } else {
      let mut buf = [0u8; 24];
      let len = self.encode_scope_prefix_fixed(&mut buf);
      let prefix_slice = &buf[..len];
      if !full_key.starts_with(prefix_slice) {
        return None;
      }
      let rem = &full_key[len..];
      if rem.is_empty() || KeyTag::from_u8(rem[0]).is_none() {
        return None;
      }
      rem
    };

    let mut out = Vec::with_capacity(target_kc.scope_prefix_len() + remain.len());
    target_kc.encode_scope_prefix(&mut out);
    out.extend_from_slice(remain);
    Some(out)
  }
}