yang-db 0.2.0

个人使用数据库操作
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
/// Redis 值类型
///
/// 表示 Redis 中的各种数据类型,提供类型安全的值表示
#[derive(Debug, Clone, PartialEq)]
#[non_exhaustive]
pub enum RedisValue {
    /// 空值
    Nil,
    /// 整数
    Int(i64),
    /// 浮点数
    Float(f64),
    /// 字符串
    String(String),
    /// 字节数组
    Bytes(Vec<u8>),
    /// 数组
    Array(Vec<RedisValue>),
    /// 布尔值
    Bool(bool),
}

impl RedisValue {
    /// 借用字符串切片(零拷贝)
    ///
    /// 对 `String` 变体返回 `&str`,无需堆分配。
    /// `Bytes` 变体不自动解码为 UTF-8,返回 `None`。
    ///
    /// # 返回
    /// - `Some(&str)`: 如果值是字符串类型
    /// - `None`: 如果值不是字符串类型
    ///
    /// # 示例
    /// ```
    /// use yang_db::RedisValue;
    ///
    /// let value = RedisValue::String("hello".to_string());
    /// assert_eq!(value.as_str(), Some("hello"));
    ///
    /// let nil = RedisValue::Nil;
    /// assert_eq!(nil.as_str(), None);
    /// ```
    pub fn as_str(&self) -> Option<&str> {
        match self {
            RedisValue::String(s) => Some(s.as_str()),
            _ => None,
        }
    }

    /// 转换为字符串(需要堆分配)
    ///
    /// 内部委托 [`as_str`](Self::as_str),仅在确实需要 `String` 时使用;
    /// 若只需借用,请优先使用 `as_str()`。
    ///
    /// # 返回
    /// - `Some(String)`: 如果值是字符串类型
    /// - `None`: 如果值不是字符串类型
    ///
    /// # 示例
    /// ```
    /// use yang_db::RedisValue;
    ///
    /// let value = RedisValue::String("hello".to_string());
    /// assert_eq!(value.as_string(), Some("hello".to_string()));
    ///
    /// let nil = RedisValue::Nil;
    /// assert_eq!(nil.as_string(), None);
    /// ```
    pub fn as_string(&self) -> Option<String> {
        self.as_str().map(|s| s.to_owned())
    }

    /// 转换为整数
    ///
    /// # 返回
    /// - `Some(i64)`: 如果值是整数类型
    /// - `None`: 如果值不是整数类型
    pub fn as_i64(&self) -> Option<i64> {
        match self {
            RedisValue::Int(i) => Some(*i),
            _ => None,
        }
    }

    /// 转换为浮点数
    ///
    /// # 返回
    /// - `Some(f64)`: 如果值是浮点数类型
    /// - `None`: 如果值不是浮点数类型
    pub fn as_f64(&self) -> Option<f64> {
        match self {
            RedisValue::Float(f) => Some(*f),
            _ => None,
        }
    }

    /// 转换为布尔值
    ///
    /// # 返回
    /// - `Some(bool)`: 如果值是布尔类型
    /// - `None`: 如果值不是布尔类型
    pub fn as_bool(&self) -> Option<bool> {
        match self {
            RedisValue::Bool(b) => Some(*b),
            _ => None,
        }
    }

    /// 转换为字节数组引用
    ///
    /// # 返回
    /// - `Some(&[u8])`: 如果值是字节数组类型
    /// - `None`: 如果值不是字节数组类型
    pub fn as_bytes(&self) -> Option<&[u8]> {
        match self {
            RedisValue::Bytes(b) => Some(b.as_slice()),
            _ => None,
        }
    }

    /// 转换为数组引用
    ///
    /// # 返回
    /// - `Some(&[RedisValue])`: 如果值是数组类型
    /// - `None`: 如果值不是数组类型
    pub fn as_array(&self) -> Option<&[RedisValue]> {
        match self {
            RedisValue::Array(arr) => Some(arr.as_slice()),
            _ => None,
        }
    }

    /// 检查是否为 Nil
    ///
    /// # 返回
    /// - `true`: 如果值是 Nil
    /// - `false`: 如果值不是 Nil
    pub fn is_nil(&self) -> bool {
        matches!(self, RedisValue::Nil)
    }
}

// 实现 From trait 支持自动转换
impl From<String> for RedisValue {
    fn from(s: String) -> Self {
        RedisValue::String(s)
    }
}

impl From<&str> for RedisValue {
    fn from(s: &str) -> Self {
        RedisValue::String(s.to_string())
    }
}

impl From<i64> for RedisValue {
    fn from(i: i64) -> Self {
        RedisValue::Int(i)
    }
}

impl From<i32> for RedisValue {
    fn from(i: i32) -> Self {
        RedisValue::Int(i as i64)
    }
}

impl From<f64> for RedisValue {
    fn from(f: f64) -> Self {
        RedisValue::Float(f)
    }
}

impl From<bool> for RedisValue {
    fn from(b: bool) -> Self {
        RedisValue::Bool(b)
    }
}

impl From<Vec<u8>> for RedisValue {
    fn from(bytes: Vec<u8>) -> Self {
        RedisValue::Bytes(bytes)
    }
}

// 实现 redis::Value 到 RedisValue 的转换
impl From<redis::Value> for RedisValue {
    fn from(value: redis::Value) -> Self {
        match value {
            redis::Value::Nil => RedisValue::Nil,
            redis::Value::Int(i) => RedisValue::Int(i),
            redis::Value::BulkString(bytes) => {
                // 尝试转换为 UTF-8 字符串:from_utf8 按值消费 bytes,
                // 失败时通过 into_bytes() 取回原始字节,避免多余 clone
                match String::from_utf8(bytes) {
                    Ok(s) => RedisValue::String(s),
                    Err(e) => RedisValue::Bytes(e.into_bytes()),
                }
            }
            redis::Value::Array(values) => {
                RedisValue::Array(values.into_iter().map(RedisValue::from).collect())
            }
            redis::Value::SimpleString(s) => RedisValue::String(s),
            redis::Value::Okay => RedisValue::Bool(true),
            redis::Value::Map(_) => {
                // Map 类型转换为字符串表示
                RedisValue::String(format!("{:?}", value))
            }
            redis::Value::Attribute { .. } => {
                // Attribute 类型转换为字符串表示
                RedisValue::String(format!("{:?}", value))
            }
            redis::Value::Set(_) => {
                // Set 类型转换为字符串表示
                RedisValue::String(format!("{:?}", value))
            }
            redis::Value::Double(f) => RedisValue::Float(f),
            redis::Value::Boolean(b) => RedisValue::Bool(b),
            redis::Value::VerbatimString { .. } => {
                // VerbatimString 转换为字符串表示
                RedisValue::String(format!("{:?}", value))
            }
            redis::Value::BigNumber(_) => {
                // BigNumber 转换为字符串表示
                RedisValue::String(format!("{:?}", value))
            }
            redis::Value::Push { .. } => {
                // Push 类型转换为字符串表示
                RedisValue::String(format!("{:?}", value))
            }
            // 其他未知类型
            _ => RedisValue::String(format!("{:?}", value)),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_redis_value_nil() {
        let value = RedisValue::Nil;
        assert!(value.is_nil());
        assert_eq!(value.as_string(), None);
        assert_eq!(value.as_i64(), None);
    }

    #[test]
    fn test_redis_value_int() {
        let value = RedisValue::Int(42);
        assert!(!value.is_nil());
        assert_eq!(value.as_i64(), Some(42));
        assert_eq!(value.as_string(), None);
    }

    #[test]
    fn test_redis_value_float() {
        let value = RedisValue::Float(123.456);
        assert_eq!(value.as_f64(), Some(123.456));
        assert_eq!(value.as_i64(), None);
    }

    #[test]
    fn test_redis_value_string() {
        let value = RedisValue::String("hello".to_string());
        assert_eq!(value.as_str(), Some("hello"));
        assert_eq!(value.as_string(), Some("hello".to_string()));
        assert_eq!(value.as_i64(), None);
    }

    #[test]
    fn test_redis_value_bool() {
        let value = RedisValue::Bool(true);
        assert_eq!(value.as_bool(), Some(true));
        assert_eq!(value.as_string(), None);
    }

    #[test]
    fn test_redis_value_bytes() {
        let bytes = vec![1, 2, 3, 4];
        let value = RedisValue::Bytes(bytes.clone());
        assert_eq!(value.as_bytes(), Some(bytes.as_slice()));
        assert_eq!(value.as_string(), None);
    }

    #[test]
    fn test_redis_value_array() {
        let arr = vec![
            RedisValue::Int(1),
            RedisValue::String("test".to_string()),
            RedisValue::Nil,
        ];
        let value = RedisValue::Array(arr.clone());
        assert_eq!(value.as_array(), Some(arr.as_slice()));
        assert_eq!(value.as_string(), None);
    }

    #[test]
    fn test_from_string() {
        let value: RedisValue = "hello".into();
        assert_eq!(value, RedisValue::String("hello".to_string()));

        let value: RedisValue = String::from("world").into();
        assert_eq!(value, RedisValue::String("world".to_string()));
    }

    #[test]
    fn test_from_int() {
        let value: RedisValue = 42i64.into();
        assert_eq!(value, RedisValue::Int(42));

        let value: RedisValue = 100i32.into();
        assert_eq!(value, RedisValue::Int(100));
    }

    #[test]
    fn test_from_float() {
        let value: RedisValue = 123.456f64.into();
        assert_eq!(value, RedisValue::Float(123.456));
    }

    #[test]
    fn test_from_bool() {
        let value: RedisValue = true.into();
        assert_eq!(value, RedisValue::Bool(true));

        let value: RedisValue = false.into();
        assert_eq!(value, RedisValue::Bool(false));
    }

    #[test]
    fn test_from_bytes() {
        let bytes = vec![1, 2, 3];
        let value: RedisValue = bytes.clone().into();
        assert_eq!(value, RedisValue::Bytes(bytes));
    }

    #[test]
    fn test_from_redis_value_nil() {
        let redis_val = redis::Value::Nil;
        let value: RedisValue = redis_val.into();
        assert_eq!(value, RedisValue::Nil);
    }

    #[test]
    fn test_from_redis_value_int() {
        let redis_val = redis::Value::Int(42);
        let value: RedisValue = redis_val.into();
        assert_eq!(value, RedisValue::Int(42));
    }

    #[test]
    fn test_from_redis_value_data_utf8() {
        let redis_val = redis::Value::BulkString(b"hello".to_vec());
        let value: RedisValue = redis_val.into();
        assert_eq!(value, RedisValue::String("hello".to_string()));
    }

    #[test]
    fn test_from_redis_value_data_binary() {
        let bytes = vec![0xFF, 0xFE, 0xFD];
        let redis_val = redis::Value::BulkString(bytes.clone());
        let value: RedisValue = redis_val.into();
        assert_eq!(value, RedisValue::Bytes(bytes));
    }

    #[test]
    fn test_from_redis_value_bulk() {
        let redis_val = redis::Value::Array(vec![
            redis::Value::Int(1),
            redis::Value::BulkString(b"test".to_vec()),
        ]);
        let value: RedisValue = redis_val.into();

        if let RedisValue::Array(arr) = value {
            assert_eq!(arr.len(), 2);
            assert_eq!(arr[0], RedisValue::Int(1));
            assert_eq!(arr[1], RedisValue::String("test".to_string()));
        } else {
            panic!("Expected Array");
        }
    }

    #[test]
    fn test_from_redis_value_status() {
        let redis_val = redis::Value::SimpleString("OK".to_string());
        let value: RedisValue = redis_val.into();
        assert_eq!(value, RedisValue::String("OK".to_string()));
    }

    #[test]
    fn test_from_redis_value_okay() {
        let redis_val = redis::Value::Okay;
        let value: RedisValue = redis_val.into();
        assert_eq!(value, RedisValue::Bool(true));
    }

    #[test]
    fn test_clone() {
        let value = RedisValue::String("test".to_string());
        let cloned = value.clone();
        assert_eq!(value, cloned);
    }

    #[test]
    fn test_debug() {
        let value = RedisValue::Int(42);
        let debug_str = format!("{:?}", value);
        assert!(debug_str.contains("Int"));
        assert!(debug_str.contains("42"));
    }

    #[test]
    fn test_as_str() {
        // String 变体返回借用
        let value = RedisValue::String("hello".to_string());
        assert_eq!(value.as_str(), Some("hello"));

        // Bytes 变体不自动解码,返回 None
        let value = RedisValue::Bytes(vec![0xFF, 0xFE]);
        assert_eq!(value.as_str(), None);

        // 其他变体一律 None
        assert_eq!(RedisValue::Nil.as_str(), None);
        assert_eq!(RedisValue::Int(1).as_str(), None);
        assert_eq!(RedisValue::Float(1.0).as_str(), None);
        assert_eq!(RedisValue::Bool(true).as_str(), None);
        assert_eq!(RedisValue::Array(vec![]).as_str(), None);
    }

    #[test]
    fn test_partial_eq() {
        assert_eq!(RedisValue::Nil, RedisValue::Nil);
        assert_eq!(RedisValue::Int(42), RedisValue::Int(42));
        assert_ne!(RedisValue::Int(42), RedisValue::Int(43));
        assert_ne!(RedisValue::Int(42), RedisValue::String("42".to_string()));
    }
}