wcol 0.1.1

Collection objects (list/set/hash/zset/geo) and BfTree range-index operator layer for wedb
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
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
//! 列表 RESP 语义操作(对标 libs/server/Objects/List/ListObjectImpl.cs,
//! C# 为 ListObject 的 partial 分片;Rust 侧以同 crate 跨模块 impl 承载)
//!
//! RESP 负载经 [`ObjectOutput`] 输出;操作计数经 `result1` 回传。
//! 刻意差异:C# RespMemoryWriter 的 ResetPosition/DecreaseArrayLength
//! (LPOS 预写数组头再回退)以"先收集命中、后统一输出"等价表达。

use wbase::num::strict_i32;

use super::list_object::ListObject;
use crate::types::{ObjectInput, object_output::ObjectOutput};

// ---- CmdStrings 中列表域专用错误串(cmd_strings.rs 不在本周期改动范围) ----

/// ERR index out of range
const RESP_ERR_GENERIC_INDEX_OUT_RANGE: &[u8] = b"ERR index out of range";

use wresp::cmd_strings::{
  RESP_ERR_GENERIC_NOSUCHKEY, RESP_ERR_GENERIC_SYNTAX_ERROR, RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER,
};

/// 取第 i 个参数字节
///
#[inline]
fn arg(input: &ObjectInput, i: usize) -> &[u8] {
  input.arg(i)
}

impl ListObject {
  /// LREM:按计数方向移除元素
  ///
  /// libs/server/Objects/List/ListObjectImpl.cs:ListRemove
  pub(crate) fn list_remove(&mut self, input: &ObjectInput, output: &mut ObjectOutput) {
    let count = input.arg1;

    //indicates partial execution
    output.result1 = i32::MIN as i64;

    // get the source string to remove
    let item_span = arg(input, 0);

    let mut removed_count = 0_i64;
    output.result1 = 0;

    //remove all equals to item
    if count == 0 {
      let mut i = 0;
      while i < self.list.len() {
        if self.list[i].as_slice() == item_span {
          let value = self.list.remove(i).unwrap();
          self.update_size(&value, false);
          removed_count += 1;
        } else {
          i += 1;
        }
      }
    } else {
      let from_head_to_tail = count > 0;
      // |int.MinValue| 不适配 i64 取绝对值路径:钳制为 i32::MAX(迭代上限受
      // 列表长度约束,钳制后移除数与 C# Math.Abs 一致)
      let count = if count == i32::MIN {
        i32::MAX as i64
      } else {
        (count).abs() as i64
      };

      let mut idx = if from_head_to_tail {
        0
      } else {
        self.list.len() as i64 - 1
      };

      while removed_count < count && (0..self.list.len() as i64).contains(&idx) {
        let matches = self.list[idx as usize].as_slice() == item_span;
        if matches {
          let value = self.list.remove(idx as usize).unwrap();
          self.update_size(&value, false);
          removed_count += 1;
          if !from_head_to_tail {
            idx -= 1;
          }
        } else {
          idx += if from_head_to_tail { 1 } else { -1 };
        }
      }
    }
    output.result1 = removed_count;
  }

  /// LINSERT:在首个 pivot 前后插入
  ///
  /// libs/server/Objects/List/ListObjectImpl.cs:ListInsert
  pub(crate) fn list_insert(&mut self, input: &ObjectInput, output: &mut ObjectOutput) {
    //indicates partial execution
    output.result1 = i32::MIN as i64;

    if !self.list.is_empty() {
      // figure out where to insert BEFORE or AFTER
      let position = arg(input, 0);

      // get the source string
      let pivot = arg(input, 1);

      // get the string to INSERT into the list
      let item = arg(input, 2).to_vec();

      let insert_before = position.eq_ignore_ascii_case(b"BEFORE");

      output.result1 = -1;

      // find the first ocurrence of the pivot element
      if let Some(pos) = self.list.iter().position(|v| v.as_slice() == pivot) {
        let at = if insert_before { pos } else { pos + 1 };
        self.list.insert(at, item.clone());
        self.update_size(&item, true);
        output.result1 = self.list.len() as i64;
      }
    }
  }

  /// LINDEX:按下标取元素
  ///
  /// libs/server/Objects/List/ListObjectImpl.cs:ListIndex
  pub(crate) fn list_index(&mut self, input: &ObjectInput, output: &mut ObjectOutput) {
    let index = input.arg1;

    output.result1 = -1;

    let len = self.list.len() as i64;
    let index = if index < 0 {
      len + i64::from(index)
    } else {
      i64::from(index)
    };

    if let Some(item) = self.list.get(index as usize) {
      output.write_bulk_string(item);
      output.result1 = 1;
    }
    // C# ElementAtOrDefault 越界回 null 项(item == default),此处以无负载表达
  }

  /// LRANGE:闭区间取片段
  ///
  /// libs/server/Objects/List/ListObjectImpl.cs:ListRange
  pub(crate) fn list_range(&mut self, input: &ObjectInput, output: &mut ObjectOutput) {
    let start = input.arg1;
    let stop = input.arg2;

    if self.list.is_empty() {
      // write empty list
      output.write_empty_array();
      return;
    }

    let len = self.list.len() as i64;
    let mut start = i64::from(start);
    let mut stop = i64::from(stop);

    start = if start < 0 { len + start } else { start };
    if start < 0 {
      start = 0;
    }

    stop = if stop < 0 { len + stop } else { stop };
    if stop >= len {
      stop = len - 1;
    }

    if start > stop {
      output.write_empty_array();
      return;
    }

    let count = (stop - start + 1) as usize;
    output.write_array_length(count);

    for item in self.list.iter().skip(start as usize).take(count) {
      output.write_bulk_string(item);
    }

    output.result1 = count as i64;
  }

  /// LTRIM:区间裁剪(保留 [start, stop])
  ///
  /// libs/server/Objects/List/ListObjectImpl.cs:ListTrim
  pub(crate) fn list_trim(&mut self, input: &ObjectInput, output: &mut ObjectOutput) {
    let start = input.arg1;
    let end = input.arg2;

    if !self.list.is_empty() {
      let len = self.list.len() as i64;
      let mut start = i64::from(start);
      let mut end = i64::from(end);

      start = if start < 0 { len + start } else { start };
      end = if end < 0 { len + end } else { end };

      if start > end || start >= len || end < 0 {
        let removed: Vec<Vec<u8>> = self.list.drain(..).collect();
        for value in removed {
          self.update_size(&value, false);
        }
      } else {
        start = start.max(0);
        end = if end >= len { len } else { end + 1 };

        // Only the first end elements will remain
        if start == 0 {
          let num_deletes = len - end;
          for _ in 0..num_deletes {
            if let Some(value) = self.list.pop_back() {
              self.update_size(&value, false);
            }
          }
          output.result1 = num_deletes;
        } else {
          // 保留 [start, end):先收集后删除(C# 经只读快照迭代原表删除)
          let doomed: Vec<usize> = (0..len as usize)
            .filter(|i| !(*i >= start as usize && *i < end as usize))
            .collect();
          for (offset, i) in doomed.iter().enumerate() {
            let value = self.list.remove(i - offset).unwrap();
            self.update_size(&value, false);
          }
          output.result1 = len;
        }
      }
    }
  }

  /// LLEN:长度
  ///
  /// libs/server/Objects/List/ListObjectImpl.cs:ListLength
  pub(crate) fn list_length(&mut self, output: &mut ObjectOutput) {
    output.result1 = self.list.len() as i64;
  }

  /// LPUSH / RPUSH / LPUSHX / RPUSHX:批量推入
  ///
  /// libs/server/Objects/List/ListObjectImpl.cs:ListPush
  pub(crate) fn list_push(
    &mut self,
    input: &ObjectInput,
    output: &mut ObjectOutput,
    f_add_at_head: bool,
  ) {
    output.result1 = 0;
    for i in 0..input.parse_state.count {
      let value = arg(input, i).to_vec();

      // Add the value to the top of the list
      if f_add_at_head {
        self.list.push_front(value.clone());
      } else {
        self.list.push_back(value.clone());
      }

      self.update_size(&value, true);
    }
    output.result1 = self.list.len() as i64;
  }

  /// LPOP / RPOP(含 count 形态)
  ///
  /// libs/server/Objects/List/ListObjectImpl.cs:ListPop
  pub(crate) fn list_pop(
    &mut self,
    input: &ObjectInput,
    output: &mut ObjectOutput,
    resp_protocol_version: u8,
    f_del_at_head: bool,
  ) {
    let mut count = i64::from(input.arg1);

    if (self.list.len() as i64) < count {
      count = self.list.len() as i64;
    }

    if self.list.is_empty() {
      output.write_null(resp_protocol_version);
      count = 0;
    } else if count <= 0 {
      // LPOP/RPOP with an explicit count of 0 replies with an empty array.
      output.write_empty_array();
    } else if count > 1 {
      output.write_array_length(count as usize);
    }

    let mut removed = 0_i64;

    while count > 0 && !self.list.is_empty() {
      let value = if f_del_at_head {
        self.list.pop_front()
      } else {
        self.list.pop_back()
      };

      if let Some(value) = value {
        self.update_size(&value, false);
        output.write_bulk_string(&value);
      }

      count -= 1;

      removed += 1;
    }

    output.result1 = removed;
  }

  /// LSET:按下标覆写
  ///
  /// libs/server/Objects/List/ListObjectImpl.cs:ListSet
  pub(crate) fn list_set(&mut self, input: &ObjectInput, output: &mut ObjectOutput) {
    if self.list.is_empty() {
      output.write_error(RESP_ERR_GENERIC_NOSUCHKEY.as_bytes());
      return;
    }

    // index
    let Some(index) = strict_i32(arg(input, 0)) else {
      output.write_error(RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER.as_bytes());
      return;
    };

    let len = self.list.len() as i64;
    let index = if index < 0 {
      len + i64::from(index)
    } else {
      i64::from(index)
    };

    if index > len - 1 || index < 0 {
      output.write_error(RESP_ERR_GENERIC_INDEX_OUT_RANGE);
      return;
    }

    // element
    let element = arg(input, 1).to_vec();

    let old = self.list[index as usize].clone();
    self.update_size(&old, false);
    self.update_size(&element, true);
    self.list[index as usize] = element;

    // C# writer.WriteDirect(CmdStrings.RESP_OK)
    output.payload.extend_from_slice(b"+OK\r\n");
    output.result1 = 1;
  }

  /// LPOS:定位元素第 rank 次出现(count/maxlen 可选)
  ///
  /// libs/server/Objects/List/ListObjectImpl.cs:ListPosition
  pub(crate) fn list_position(&mut self, input: &ObjectInput, output: &mut ObjectOutput) {
    let element = arg(input, 0);

    // 默认形态:rank=1、count=1(缺省)、maxlen=0(不限)
    let mut params = ListPositionParams::default();

    if let Err(error) = read_list_position_input(input, &mut params) {
      output.write_error(error);
      return;
    }

    if params.count < 0 || params.maxlen < 0 || params.rank == 0 {
      output.write_error(RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER.as_bytes());
      return;
    }

    let count = if params.count == 0 {
      self.list.len() as i64
    } else {
      params.count
    };

    let mut found: Vec<i64> = Vec::new();

    if params.rank > 0 {
      let mut rank = params.rank;
      let len = self.list.len() as i64;
      let maxlen_index = if params.maxlen == 0 {
        len
      } else {
        params.maxlen
      };

      for (current_index, item) in self.list.iter().enumerate().take(maxlen_index as usize) {
        if item.as_slice() == element {
          if rank == 1 {
            found.push(current_index as i64);
            if found.len() as i64 == count {
              break;
            }
          } else {
            rank -= 1;
          }
        }
      }
    } else {
      // rank < 0:自尾向头
      let mut rank = params.rank.unsigned_abs() as i64;
      let len = self.list.len() as i64;
      let maxlen_index = if params.maxlen == 0 {
        0
      } else {
        len - params.maxlen
      };

      let mut current_index = len - 1;
      while current_index >= maxlen_index && current_index >= 0 {
        if self.list[current_index as usize].as_slice() == element {
          if rank == 1 {
            found.push(current_index);
            if found.len() as i64 == count {
              break;
            }
          } else {
            rank -= 1;
          }
        }
        current_index -= 1;
      }
    }

    // C# ResetPosition/DecreaseArrayLength 的等价形态:先收集命中,后统一输出
    let found_len = found.len();
    if params.is_default_count {
      if found.is_empty() {
        output.write_null(2);
      } else {
        output.write_int64(found[0]);
      }
    } else if found.is_empty() {
      output.write_empty_array();
    } else {
      output.write_array_length(found_len);
      for index in found {
        output.write_int64(index);
      }
    }

    output.result1 = found_len as i64;
  }
}

/// LPOS 解析产物
///
/// libs/server/Objects/List/ListObjectImpl.cs:ReadListPositionInput 出参束
#[derive(Debug, Clone, Copy)]
struct ListPositionParams {
  rank: i64,
  count: i64,
  is_default_count: bool,
  maxlen: i64,
}

impl Default for ListPositionParams {
  fn default() -> Self {
    // By default, LPOS takes first match element; return 1 element; iterate to all the item
    Self {
      rank: 1,
      count: 1,
      is_default_count: true,
      maxlen: 0,
    }
  }
}

/// 解析 LPOS 的 RANK/COUNT/MAXLEN 词元(忽略 ASCII 大小写)
///
/// libs/server/Objects/List/ListObjectImpl.cs:ReadListPositionInput
fn read_list_position_input(
  input: &ObjectInput,
  params: &mut ListPositionParams,
) -> Result<(), &'static [u8]> {
  let count = input.parse_state.count;
  let mut curr_token_idx = 1;

  let parse_i32_arg = |idx: &mut usize| -> Result<i64, &'static [u8]> {
    if *idx >= count {
      return Err(RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER.as_bytes());
    }
    let val =
      strict_i32(arg(input, *idx)).ok_or(RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER.as_bytes())?;
    *idx += 1;
    Ok(i64::from(val))
  };

  while curr_token_idx < count {
    let sb_param = arg(input, curr_token_idx);
    curr_token_idx += 1;

    if sb_param.eq_ignore_ascii_case(b"RANK") {
      params.rank = parse_i32_arg(&mut curr_token_idx)?;
    } else if sb_param.eq_ignore_ascii_case(b"COUNT") {
      params.count = parse_i32_arg(&mut curr_token_idx)?;
      params.is_default_count = false;
    } else if sb_param.eq_ignore_ascii_case(b"MAXLEN") {
      params.maxlen = parse_i32_arg(&mut curr_token_idx)?;
    } else {
      return Err(RESP_ERR_GENERIC_SYNTAX_ERROR.as_bytes());
    }
  }

  Ok(())
}

#[cfg(test)]
mod tests {
  use wval::GarnetObjectType;

  use super::*;
  use crate::object_store_utils::make_object_input;

  #[test]
  fn test_read_list_position_input() {
    let mut params = ListPositionParams::default();
    let input = make_object_input(
      GarnetObjectType::List,
      0,
      &[
        b"elem".as_slice(),
        b"rAnK",
        b"2",
        b"cOuNt",
        b"5",
        b"mAxLeN",
        b"100",
      ],
      0,
      0,
    );
    assert!(read_list_position_input(&input, &mut params).is_ok());
    assert_eq!(params.rank, 2);
    assert_eq!(params.count, 5);
    assert!(!params.is_default_count);
    assert_eq!(params.maxlen, 100);

    // 缺少参数值边界守卫(防止越界 panic)
    for opt in [b"RANK".as_slice(), b"COUNT", b"MAXLEN"] {
      let mut p = ListPositionParams::default();
      let input = make_object_input(GarnetObjectType::List, 0, &[b"elem".as_slice(), opt], 0, 0);
      assert_eq!(
        read_list_position_input(&input, &mut p),
        Err(RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER.as_bytes())
      );
    }

    // 非整数值
    let mut p = ListPositionParams::default();
    let input = make_object_input(
      GarnetObjectType::List,
      0,
      &[b"elem".as_slice(), b"rank", b"abc"],
      0,
      0,
    );
    assert_eq!(
      read_list_position_input(&input, &mut p),
      Err(RESP_ERR_GENERIC_VALUE_IS_NOT_INTEGER.as_bytes())
    );

    // 未知选项
    let mut p = ListPositionParams::default();
    let input = make_object_input(
      GarnetObjectType::List,
      0,
      &[b"elem".as_slice(), b"UNKNOWN"],
      0,
      0,
    );
    assert_eq!(
      read_list_position_input(&input, &mut p),
      Err(RESP_ERR_GENERIC_SYNTAX_ERROR.as_bytes())
    );
  }
}