-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathvalue.rs
715 lines (624 loc) · 19.5 KB
/
value.rs
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
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
//! Represents valid Bencode data.
use crate::{error::Error, ByteString};
use core::fmt::Display;
use serde::{
de::{Deserialize, DeserializeOwned, MapAccess, SeqAccess, Visitor},
ser::Serialize,
};
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::{collections::BTreeMap, fmt, str, str::FromStr, string::String, vec::Vec};
#[cfg(feature = "std")]
use std::{collections::BTreeMap, fmt, str, str::FromStr, string::String, vec::Vec};
/// Represents a valid Bencode number.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Number {
/// A signed integer.
Signed(i64),
/// An unsigned integer.
Unsigned(u64),
}
impl Display for Number {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Number::Signed(arg0) => Display::fmt(arg0, f),
Number::Unsigned(arg0) => Display::fmt(arg0, f),
}
}
}
impl From<isize> for Number {
fn from(value: isize) -> Self {
Number::Signed(value as i64)
}
}
impl From<i64> for Number {
fn from(value: i64) -> Self {
Number::Signed(value)
}
}
impl From<i32> for Number {
fn from(value: i32) -> Self {
Number::Signed(i64::from(value))
}
}
impl From<i16> for Number {
fn from(value: i16) -> Self {
Number::Signed(i64::from(value))
}
}
impl From<i8> for Number {
fn from(value: i8) -> Self {
Number::Signed(i64::from(value))
}
}
impl From<usize> for Number {
fn from(value: usize) -> Self {
Number::Unsigned(value as u64)
}
}
impl From<u64> for Number {
fn from(value: u64) -> Self {
Number::Unsigned(value)
}
}
impl From<u32> for Number {
fn from(value: u32) -> Self {
Number::Unsigned(u64::from(value))
}
}
impl From<u16> for Number {
fn from(value: u16) -> Self {
Number::Unsigned(u64::from(value))
}
}
impl From<u8> for Number {
fn from(value: u8) -> Self {
Number::Unsigned(u64::from(value))
}
}
/// Represents a valid Bencode value.
///
/// It is useful when it is unknown what the data may contain (e.g. when different kinds of
/// messages can be received in a network packet).
#[derive(Clone, PartialEq)]
pub enum Value {
/// A byte string.
///
/// Encoded strings can contain non-UTF-8 bytes, so a byte string is used to represent
/// "strings".
ByteStr(ByteString),
/// An integer which can be signed or unsigned.
Int(Number),
/// A list of values.
List(Vec<Value>),
/// A dictionary of values.
Dict(BTreeMap<ByteString, Value>),
}
impl Value {
/// If the value is a byte string, returns a reference to the underlying value.
#[must_use]
pub fn as_byte_str(&self) -> Option<&ByteString> {
match self {
Value::ByteStr(b) => Some(b),
_ => None,
}
}
/// If the value is a byte string, returns a mutable reference to the underlying value.
#[must_use]
pub fn as_byte_str_mut(&mut self) -> Option<&mut ByteString> {
match self {
Value::ByteStr(ref mut b) => Some(b),
_ => None,
}
}
/// If the value is a UTF-8 string, returns a reference to the underlying value.
#[must_use]
pub fn as_str(&self) -> Option<&str> {
match self {
Value::ByteStr(b) => str::from_utf8(b.as_slice()).ok(),
_ => None,
}
}
/// If the value is a UTF-8 string, returns a mutable reference to the underlying value.
#[must_use]
pub fn as_str_mut(&mut self) -> Option<&mut str> {
match self {
Value::ByteStr(ref mut b) => str::from_utf8_mut(b.as_mut_slice()).ok(),
_ => None,
}
}
/// If the value is a number, returns a reference to the underlying value.
#[must_use]
pub fn as_number(&self) -> Option<&Number> {
match self {
Value::Int(n) => Some(n),
_ => None,
}
}
/// If the value is a [u64], returns the underlying value.
#[must_use]
pub fn as_u64(&self) -> Option<u64> {
match self {
Value::Int(Number::Unsigned(n)) => Some(*n),
_ => None,
}
}
/// If the value is a [i64], returns the underlying value.
#[must_use]
pub fn as_i64(&self) -> Option<i64> {
match self {
Value::Int(Number::Signed(n)) => Some(*n),
_ => None,
}
}
/// If the value is an array, returns a reference to the underlying value.
#[must_use]
pub fn as_array(&self) -> Option<&Vec<Value>> {
match self {
Value::List(ref l) => Some(l),
_ => None,
}
}
/// If the value is an array, returns a mutable reference to the underlying value.
#[must_use]
pub fn as_array_mut(&mut self) -> Option<&mut Vec<Value>> {
match self {
Value::List(ref mut l) => Some(l),
_ => None,
}
}
/// If the value is a dictionary, returns a reference to the underlying value.
#[must_use]
pub fn as_dict(&self) -> Option<&BTreeMap<ByteString, Value>> {
match self {
Value::Dict(d) => Some(d),
_ => None,
}
}
/// If the value is a dictionary, returns a mutable reference to the underlying value.
#[must_use]
pub fn as_dict_mut(&mut self) -> Option<&mut BTreeMap<ByteString, Value>> {
match self {
Value::Dict(ref mut d) => Some(d),
_ => None,
}
}
/// Returns true if the value is a byte string.
#[must_use]
pub fn is_byte_str(&self) -> bool {
self.as_byte_str().is_some()
}
/// Returns true if the value is a UTF-8 string.
///
/// Note that the value could be a byte string but not a UTF-8 string.
#[must_use]
pub fn is_string(&self) -> bool {
self.as_str().is_some()
}
/// Returns true if the value is a an [u64].
///
/// Note that the value could be a [i64].
#[must_use]
pub fn is_u64(&self) -> bool {
self.as_u64().is_some()
}
/// Returns true if the value is a an [i64].
///
/// Note that the value could be a [u64].
#[must_use]
pub fn is_i64(&self) -> bool {
self.as_i64().is_some()
}
/// Returns true if the value is an array.
#[must_use]
pub fn is_array(&self) -> bool {
self.as_array().is_some()
}
/// Returns true if the value is a dictionary.
#[must_use]
pub fn is_dict(&self) -> bool {
self.as_dict().is_some()
}
}
impl fmt::Debug for Value {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
struct DebugByteStr<'a>(&'a ByteString);
impl fmt::Debug for DebugByteStr<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match core::str::from_utf8(self.0) {
Ok(key) => f.debug_tuple("ByteStr").field(&key).finish(),
Err(_) => f.debug_tuple("ByteStr").field(&self.0).finish(),
}
}
}
match self {
Value::ByteStr(arg0) => fmt::Debug::fmt(&DebugByteStr(arg0), f),
Value::Int(arg0) => f.debug_tuple("Int").field(arg0).finish(),
Value::List(arg0) => f.debug_tuple("List").field(arg0).finish(),
Value::Dict(arg0) => {
struct DebugDict<'a>(&'a BTreeMap<ByteString, Value>);
impl fmt::Debug for DebugDict<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let mut d = &mut f.debug_map();
for (key, value) in self.0 {
d = d.entry(&DebugByteStr(key), value);
}
d.finish()
}
}
f.debug_tuple("Dict").field(&DebugDict(arg0)).finish()
}
}
}
}
impl From<i8> for Value {
fn from(other: i8) -> Value {
Value::Int(Number::from(other))
}
}
impl From<i16> for Value {
fn from(other: i16) -> Value {
Value::Int(Number::from(other))
}
}
impl From<i32> for Value {
fn from(other: i32) -> Value {
Value::Int(Number::from(other))
}
}
impl From<i64> for Value {
fn from(other: i64) -> Value {
Value::Int(Number::from(other))
}
}
impl From<isize> for Value {
fn from(other: isize) -> Value {
Value::Int(Number::from(other))
}
}
impl From<u8> for Value {
fn from(other: u8) -> Value {
Value::Int(Number::from(other))
}
}
impl From<u16> for Value {
fn from(other: u16) -> Value {
Value::Int(Number::from(other))
}
}
impl From<u32> for Value {
fn from(other: u32) -> Value {
Value::Int(Number::from(other))
}
}
impl From<u64> for Value {
fn from(other: u64) -> Value {
Value::Int(Number::from(other))
}
}
impl From<usize> for Value {
fn from(other: usize) -> Value {
Value::Int(Number::from(other))
}
}
impl FromStr for Value {
type Err = Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Ok(Value::ByteStr(ByteString::from(String::from(s))))
}
}
impl<'a> From<&'a str> for Value {
fn from(other: &'a str) -> Value {
Value::ByteStr(ByteString::from(other))
}
}
impl From<String> for Value {
fn from(other: String) -> Value {
Value::ByteStr(ByteString::from(other))
}
}
impl<V: Into<Value>> From<Vec<V>> for Value {
fn from(other: Vec<V>) -> Value {
Value::List(other.into_iter().map(Into::into).collect())
}
}
impl<K: Into<ByteString>, V: Into<Value>> From<BTreeMap<K, V>> for Value {
fn from(other: BTreeMap<K, V>) -> Value {
Value::Dict(
other
.into_iter()
.map(|(k, v)| (k.into(), v.into()))
.collect(),
)
}
}
impl<'de> Deserialize<'de> for Value {
#[inline]
fn deserialize<T>(deserializer: T) -> Result<Value, T::Error>
where
T: serde::Deserializer<'de>,
{
struct ValueVisitor;
impl<'de> Visitor<'de> for ValueVisitor {
type Value = Value;
#[inline]
fn expecting(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str("any valid Bencode value")
}
#[inline]
fn visit_i64<E>(self, value: i64) -> Result<Self::Value, E> {
Ok(Value::Int(Number::Signed(value)))
}
#[inline]
fn visit_u64<E>(self, value: u64) -> Result<Self::Value, E> {
Ok(Value::Int(Number::Unsigned(value)))
}
#[inline]
fn visit_str<E>(self, value: &str) -> Result<Self::Value, E> {
Ok(Value::ByteStr(ByteString::from(String::from(value))))
}
#[inline]
fn visit_string<E>(self, value: String) -> Result<Self::Value, E> {
Ok(Value::ByteStr(ByteString::from(value)))
}
#[inline]
fn visit_bytes<E>(self, value: &[u8]) -> Result<Self::Value, E> {
Ok(Value::ByteStr(ByteString::from(value)))
}
#[inline]
fn visit_byte_buf<E>(self, value: Vec<u8>) -> Result<Self::Value, E> {
Ok(Value::ByteStr(ByteString::from(value)))
}
#[inline]
fn visit_some<D>(self, deserializer: D) -> Result<Self::Value, D::Error>
where
D: serde::Deserializer<'de>,
{
Deserialize::deserialize(deserializer)
}
fn visit_seq<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
where
V: SeqAccess<'de>,
{
let mut list = Vec::new();
if let Some(size_hint) = visitor.size_hint() {
list.reserve(size_hint);
}
while let Some(elem) = visitor.next_element()? {
list.push(elem);
}
Ok(Value::List(list))
}
fn visit_map<V>(self, mut visitor: V) -> Result<Self::Value, V::Error>
where
V: MapAccess<'de>,
{
let mut dict = BTreeMap::new();
while let Some((key, value)) = visitor.next_entry()? {
dict.insert(key, value);
}
Ok(Value::Dict(dict))
}
}
deserializer.deserialize_any(ValueVisitor)
}
}
impl Serialize for Value {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
match self {
Value::ByteStr(ref b) => b.serialize(serializer),
Value::Int(i) => match i {
Number::Signed(s) => s.serialize(serializer),
Number::Unsigned(u) => u.serialize(serializer),
},
Value::List(l) => l.serialize(serializer),
Value::Dict(d) => d.serialize(serializer),
}
}
}
mod de;
mod index;
mod ser;
pub use index::Index;
impl Value {
/// Used to get a reference to a value with an index.
#[inline]
pub fn get<I: Index>(&self, index: I) -> Option<&Value> {
index.index(self)
}
/// Used to get a mutable reference to a value with an index.
#[inline]
pub fn get_mut<I: Index>(&mut self, index: I) -> Option<&mut Value> {
index.index_mut(self)
}
}
/// Deserializes an instance of `T` from a [Value].
///
/// # Errors
///
/// Deserialization can fail if the data is not valid, if the data cannot cannot be deserialized
/// into an instance of `T`, and other IO errors.
#[allow(clippy::module_name_repetitions)]
#[inline]
pub fn from_value<T>(value: Value) -> Result<T, Error>
where
T: DeserializeOwned,
{
T::deserialize(value)
}
/// Serializes an instance of `T` into a [Value].
///
/// # Errors
///
/// Serialization can fail if `T`'s implementation of
/// [`Serialize`] decides to fail, if `T` contains
/// unsupported types for serialization, or if `T` contains a map with
/// non-string keys.
#[allow(clippy::module_name_repetitions)]
#[inline]
pub fn to_value<T>(value: &T) -> Result<Value, Error>
where
T: ?Sized + Serialize,
{
value.serialize(ser::Serializer)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::error::Result;
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::vec;
#[cfg(feature = "std")]
use std::vec;
#[test]
fn test_deserialize_string() -> Result<()> {
let input = "4:spam";
let v: Value = crate::de::from_slice(input.as_bytes())?;
assert_eq!(v, Value::ByteStr(ByteString::from(String::from("spam"))));
Ok(())
}
#[test]
fn test_deserialize_integer_1() -> Result<()> {
let input = "i3e";
let v: Value = crate::de::from_slice(input.as_bytes())?;
assert_eq!(v, Value::Int(Number::Unsigned(3)));
Ok(())
}
#[test]
fn test_deserialize_integer_2() -> Result<()> {
let input = "i-3e";
let v: Value = crate::de::from_slice(input.as_bytes())?;
assert_eq!(v, Value::Int(Number::Signed(-3)));
Ok(())
}
#[test]
fn test_deserialize_integer_3() -> Result<()> {
let input = "i0e";
let v: Value = crate::de::from_slice(input.as_bytes())?;
assert_eq!(v, Value::Int(Number::Unsigned(0)));
Ok(())
}
#[test]
fn test_deserialize_list() -> Result<()> {
let input = "l4:spam4:eggse";
let v: Value = crate::de::from_slice(input.as_bytes())?;
assert_eq!(
v,
Value::List(vec![
Value::ByteStr(ByteString::from(String::from("spam"))),
Value::ByteStr(ByteString::from(String::from("eggs"))),
])
);
Ok(())
}
#[test]
fn test_deserialize_dict_1() -> Result<()> {
let input = "d3:cow3:moo4:spam4:eggse";
let v: Value = crate::de::from_slice(input.as_bytes())?;
let mut expected = BTreeMap::new();
expected.insert(
ByteString::from(String::from("cow")),
Value::ByteStr(ByteString::from(String::from("moo"))),
);
expected.insert(
ByteString::from(String::from("spam")),
Value::ByteStr(ByteString::from(String::from("eggs"))),
);
assert_eq!(v, Value::Dict(expected));
Ok(())
}
#[test]
fn test_deserialize_dict_2() -> Result<()> {
let input = "d4:spaml1:a1:bee";
let v: Value = crate::de::from_slice(input.as_bytes())?;
let mut expected = BTreeMap::new();
expected.insert(
ByteString::from(String::from("spam")),
Value::List(vec![
Value::ByteStr(ByteString::from(String::from("a"))),
Value::ByteStr(ByteString::from(String::from("b"))),
]),
);
assert_eq!(v, Value::Dict(expected));
Ok(())
}
#[test]
#[cfg(feature = "std")]
fn test_serialize_string() -> Result<()> {
let expected = "4:spam";
let v: Vec<u8> =
crate::ser::to_vec(&Value::ByteStr(ByteString::from(String::from("spam"))))?;
assert_eq!(v, expected.to_string().into_bytes());
Ok(())
}
#[test]
#[cfg(feature = "std")]
fn test_serialize_integer_1() -> Result<()> {
let expected = "i3e";
let v: Vec<u8> = crate::ser::to_vec(&Value::Int(Number::Unsigned(3)))?;
assert_eq!(v, expected.to_string().into_bytes());
Ok(())
}
#[test]
#[cfg(feature = "std")]
fn test_serialize_integer_2() -> Result<()> {
let expected = "i-3e";
let v: Vec<u8> = crate::ser::to_vec(&Value::Int(Number::Signed(-3)))?;
assert_eq!(v, expected.to_string().into_bytes());
Ok(())
}
#[test]
#[cfg(feature = "std")]
fn test_serialize_integer_3() -> Result<()> {
let expected = "i0e";
let v: Vec<u8> = crate::ser::to_vec(&Value::Int(Number::Unsigned(0)))?;
assert_eq!(v, expected.to_string().into_bytes());
Ok(())
}
#[test]
#[cfg(feature = "std")]
fn test_serialize_list() -> Result<()> {
let expected = "l4:spam4:eggse";
let v: Vec<u8> = crate::ser::to_vec(&Value::List(vec![
Value::ByteStr(ByteString::from(String::from("spam"))),
Value::ByteStr(ByteString::from(String::from("eggs"))),
]))?;
assert_eq!(v, expected.to_string().into_bytes());
Ok(())
}
#[test]
#[cfg(feature = "std")]
fn test_serialize_dict_1() -> Result<()> {
let expected = "d3:cow3:moo4:spam4:eggse";
let mut dict = BTreeMap::new();
dict.insert(
ByteString::from(String::from("cow")),
Value::ByteStr(ByteString::from(String::from("moo"))),
);
dict.insert(
ByteString::from(String::from("spam")),
Value::ByteStr(ByteString::from(String::from("eggs"))),
);
let v: Vec<u8> = crate::ser::to_vec(&Value::Dict(dict))?;
assert_eq!(v, expected.to_string().into_bytes());
Ok(())
}
#[test]
#[cfg(feature = "std")]
fn test_serialize_dict_2() -> Result<()> {
let expected = "d4:spaml1:a1:bee";
let mut dict = BTreeMap::new();
dict.insert(
ByteString::from(String::from("spam")),
Value::List(vec![
Value::ByteStr(ByteString::from(String::from("a"))),
Value::ByteStr(ByteString::from(String::from("b"))),
]),
);
let v: Vec<u8> = crate::ser::to_vec(&Value::Dict(dict))?;
assert_eq!(v, expected.to_string().into_bytes());
Ok(())
}
}