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
//! Structured values.
//!
//! This crate contains the [`ValueBag`] type, a container for an anonymous structured value.
//! `ValueBag`s can be captured in various ways and then formatted, inspected, and serialized
//! without losing their original structure.
//!
//! The producer of a [`ValueBag`] may use a different strategy for capturing than the eventual
//! consumer. They don't need to coordinate directly.

#![doc(html_root_url = "https://docs.rs/value-bag/1.7.0")]
#![no_std]

/*
# Crate design

This library internally ties several frameworks together. The details of how
this is done are hidden from end-users. It looks roughly like this:

            ┌─────┐     ┌──────┐
            │sval2│     │serde1│  1. libs on crates.io
            └──┬──┘     └─┬─┬──┘
               ├──────────┘ │
       ┌───────▼──┐     ┌───▼───────┐
       │meta/sval2│     │meta/serde1│  2. meta crates with features
       └───────┬──┘     └───┬───────┘
               │            │
 ┌─────────────▼──┐     ┌───▼─────────────┐
 │internal/sval/v2◄─────┤internal/serde/v1│  3. internal modules with `InternalVisitor`
 └─────────────┬──┘     └───┬─────────────┘
               │            │
        ┌──────▼────────┬───▼────────────┐
        │Internal::Sval2│Internal::Serde1│  4. variants in `Internal` enum
        └───────────────┼────────────────┘
                        │
┌───────────────────────▼────────────────────────┐
│ValueBag::capture_sval2│ValueBag::capture_serde1│  5. ctors on `ValueBag`
└───────────────────────┼────────────────────────┘
                        │
┌───────────────────────▼───────────────────────────┐
│impl Value for ValueBag│impl Serialize for ValueBag│  6. trait impls on `ValueBag`
└───────────────────────┴───────────────────────────┘

## 1. libs on crates.io

These are the frameworks like `serde` or `sval`.

## 2. meta crates with features

These are crates that are internal to `value-bag`. They depend on the public
framework and any utility crates that come along with it. They also expose
features for any other framework. This is done this way so `value-bag` can use
Cargo's `crate?/feature` syntax to conditionally add framework support.

## 3. internal modules with `InternalVisitor`

These are modules in `value-bag` that integrate the framework using the
`InternalVisitor` trait. This makes it possible for that framework to cast
primitive values and pass-through any other framework.

## 4. variants in `Internal` enum

These are individual variants on the `Internal` enum that the `ValueBag`
type wraps. Each framework has one or more variants in this enum.

## 5. ctors on `ValueBag`

These are constructors for producers of `ValueBag`s that accept a value
implementing a serialization trait from a specific framework, like
`serde::Serialize` or `sval::Value`.

## 7. trait impls on `ValueBag`

These are trait impls for consumers of `ValueBag`s that serialize the
underlying value, bridging it if it was produced for a different framework.
*/

#[cfg(any(feature = "std", test))]
#[macro_use]
#[allow(unused_imports)]
extern crate std;

#[cfg(all(not(test), feature = "alloc", not(feature = "std")))]
#[macro_use]
#[allow(unused_imports)]
extern crate core;

#[cfg(all(not(test), feature = "alloc", not(feature = "std")))]
#[macro_use]
#[allow(unused_imports)]
extern crate alloc;

#[cfg(all(not(test), feature = "alloc", not(feature = "std")))]
#[allow(unused_imports)]
mod std {
    pub use crate::{
        alloc::{borrow, boxed, string},
        core::*,
    };
}

#[cfg(not(any(feature = "alloc", feature = "std", test)))]
#[macro_use]
#[allow(unused_imports)]
extern crate core as std;

mod error;
pub mod fill;
mod impls;
mod internal;
pub mod visit;

#[cfg(any(test, feature = "test"))]
pub mod test;

#[cfg(feature = "owned")]
mod owned;
#[cfg(feature = "owned")]
pub use self::owned::*;

#[cfg(feature = "seq")]
mod seq;

pub use self::error::Error;

/// A dynamic structured value.
///
/// # Capturing values
///
/// There are a few ways to capture a value:
///
/// - Using the `ValueBag::capture_*` and `ValueBag::from_*` methods.
/// - Using the standard `From` trait.
/// - Using the `Fill` API.
///
/// ## Using the `ValueBag::capture_*` methods
///
/// `ValueBag` offers a few constructor methods that capture values of different kinds.
/// These methods require a `T: 'static` to support downcasting.
///
/// ```
/// use value_bag::ValueBag;
///
/// let value = ValueBag::capture_debug(&42i32);
///
/// assert_eq!(Some(42), value.to_i64());
/// ```
///
/// Capturing a value using these methods will retain type information so that
/// the contents of the bag can be serialized using an appropriate type.
///
/// For cases where the `'static` bound can't be satisfied, there's also a few
/// constructors that exclude it.
///
/// ```
/// # use std::fmt::Debug;
/// use value_bag::ValueBag;
///
/// let value = ValueBag::from_debug(&42i32);
///
/// assert_eq!(None, value.to_i64());
/// ```
///
/// These `ValueBag::from_*` methods are lossy though and `ValueBag::capture_*` should be preferred.
///
/// ## Using the standard `From` trait
///
/// Primitive types can be converted into a `ValueBag` using the standard `From` trait.
///
/// ```
/// use value_bag::ValueBag;
///
/// let value = ValueBag::from(42i32);
///
/// assert_eq!(Some(42), value.to_i64());
/// ```
///
/// ## Using the `Fill` API
///
/// The [`fill`] module provides a way to bridge APIs that may not be directly
/// compatible with other constructor methods.
///
/// The `Fill` trait is automatically implemented for closures, so can usually
/// be used in libraries that can't implement the trait themselves.
///
/// ```
/// use value_bag::{ValueBag, fill::Slot};
///
/// let value = ValueBag::from_fill(&|slot: Slot| {
///     #[derive(Debug)]
///     struct MyShortLivedValue;
///
///     slot.fill_debug(&MyShortLivedValue)
/// });
///
/// assert_eq!("MyShortLivedValue", format!("{:?}", value));
/// ```
///
/// The trait can also be implemented manually:
///
/// ```
/// # use std::fmt::Debug;
/// use value_bag::{ValueBag, Error, fill::{Slot, Fill}};
///
/// struct FillDebug;
///
/// impl Fill for FillDebug {
///     fn fill(&self, slot: Slot) -> Result<(), Error> {
///         slot.fill_debug(&42i32 as &dyn Debug)
///     }
/// }
///
/// let value = ValueBag::from_fill(&FillDebug);
///
/// assert_eq!(None, value.to_i64());
/// ```
///
/// # Inspecting values
///
/// Once you have a `ValueBag` there are also a few ways to inspect it:
///
/// - Using `std::fmt`
/// - Using `sval`
/// - Using `serde`
/// - Using the `ValueBag::visit` method.
/// - Using the `ValueBag::to_*` methods.
/// - Using the `ValueBag::downcast_ref` method.
///
/// ## Using the `ValueBag::visit` method
///
/// The [`visit`] module provides a simple visitor API that can be used to inspect
/// the structure of primitives stored in a `ValueBag`.
/// More complex datatypes can then be handled using `std::fmt`, `sval`, or `serde`.
///
/// ```
/// #[cfg(not(feature = "std"))] fn main() {}
/// #[cfg(feature = "std")]
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # fn escape(buf: &[u8]) -> &[u8] { buf }
/// # fn itoa_fmt<T>(num: T) -> Vec<u8> { vec![] }
/// # fn ryu_fmt<T>(num: T) -> Vec<u8> { vec![] }
/// # use std::io::Write;
/// use value_bag::{ValueBag, Error, visit::Visit};
///
/// // Implement some simple custom serialization
/// struct MyVisit(Vec<u8>);
/// impl<'v> Visit<'v> for MyVisit {
///     fn visit_any(&mut self, v: ValueBag) -> Result<(), Error> {
///         // Fallback to `Debug` if we didn't visit the value specially
///         write!(&mut self.0, "{:?}", v).map_err(|_| Error::msg("failed to write value"))
///     }
///
///     fn visit_u64(&mut self, v: u64) -> Result<(), Error> {
///         self.0.extend_from_slice(itoa_fmt(v).as_slice());
///         Ok(())
///     }
///
///     fn visit_i64(&mut self, v: i64) -> Result<(), Error> {
///         self.0.extend_from_slice(itoa_fmt(v).as_slice());
///         Ok(())
///     }
///
///     fn visit_f64(&mut self, v: f64) -> Result<(), Error> {
///         self.0.extend_from_slice(ryu_fmt(v).as_slice());
///         Ok(())
///     }
///
///     fn visit_str(&mut self, v: &str) -> Result<(), Error> {
///         self.0.push(b'\"');
///         self.0.extend_from_slice(escape(v.as_bytes()));
///         self.0.push(b'\"');
///         Ok(())
///     }
///
///     fn visit_bool(&mut self, v: bool) -> Result<(), Error> {
///         self.0.extend_from_slice(if v { b"true" } else { b"false" });
///         Ok(())
///     }
/// }
///
/// let value = ValueBag::from(42i64);
///
/// let mut visitor = MyVisit(vec![]);
/// value.visit(&mut visitor)?;
/// # Ok(())
/// # }
/// ```
///
/// ## Using `std::fmt`
///
/// Any `ValueBag` can be formatted using the `std::fmt` machinery as either `Debug`
/// or `Display`.
///
/// ```
/// use value_bag::ValueBag;
///
/// let value = ValueBag::from(true);
///
/// assert_eq!("true", format!("{:?}", value));
/// ```
///
/// ## Using `sval`
///
/// When the `sval2` feature is enabled, any `ValueBag` can be serialized using `sval`.
/// This makes it possible to visit any typed structure captured in the `ValueBag`,
/// including complex datatypes like maps and sequences.
///
/// `sval` doesn't need to allocate so can be used in no-std environments.
///
/// First, enable the `sval2` feature in your `Cargo.toml`:
///
/// ```toml
/// [dependencies.value-bag]
/// features = ["sval2"]
/// ```
///
/// Then stream the contents of the `ValueBag` using `sval`.
///
/// ```
/// # #[cfg(not(all(feature = "std", feature = "sval2")))] fn main() {}
/// # #[cfg(all(feature = "std", feature = "sval2"))]
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # use value_bag_sval2::json as sval_json;
/// use value_bag::ValueBag;
///
/// let value = ValueBag::from(42i64);
/// let json = sval_json::stream_to_string(value)?;
/// # Ok(())
/// # }
/// ```
///
/// ## Using `serde`
///
/// When the `serde1` feature is enabled, any `ValueBag` can be serialized using `serde`.
/// This makes it possible to visit any typed structure captured in the `ValueBag`,
/// including complex datatypes like maps and sequences.
///
/// `serde` needs a few temporary allocations, so also brings in the `std` feature.
///
/// First, enable the `serde1` feature in your `Cargo.toml`:
///
/// ```toml
/// [dependencies.value-bag]
/// features = ["serde1"]
/// ```
///
/// Then stream the contents of the `ValueBag` using `serde`.
///
/// ```
/// # #[cfg(not(all(feature = "std", feature = "serde1")))] fn main() {}
/// # #[cfg(all(feature = "std", feature = "serde1"))]
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # use value_bag_serde1::json as serde_json;
/// use value_bag::ValueBag;
///
/// let value = ValueBag::from(42i64);
/// let json = serde_json::to_string(&value)?;
/// # Ok(())
/// # }
/// ```
///
/// Also see [`serde.rs`](https://serde.rs) for more examples of writing your own serializers.
///
/// ## Using the `ValueBag::to_*` methods
///
/// `ValueBag` provides a set of methods for attempting to pull a concrete value out.
/// These are useful for ad-hoc analysis but aren't intended for exhaustively serializing
/// the contents of a `ValueBag`.
///
/// ```
/// use value_bag::ValueBag;
///
/// let value = ValueBag::capture_display(&42u64);
///
/// assert_eq!(Some(42u64), value.to_u64());
/// ```
///
/// ## Using the `ValueBag::downcast_ref` method
///
/// When a `ValueBag` is created using one of the `capture_*` constructors, it can be downcast
/// back to its original value.
/// This can also be useful for ad-hoc analysis where there's a common possible non-primitive
/// type that could be captured.
///
/// ```
/// # #[derive(Debug)] struct SystemTime;
/// # fn now() -> SystemTime { SystemTime }
/// use value_bag::ValueBag;
///
/// let timestamp = now();
/// let value = ValueBag::capture_debug(&timestamp);
///
/// assert!(value.downcast_ref::<SystemTime>().is_some());
/// ```
///
/// # Working with sequences
///
/// The `seq` feature of `value-bag` enables utilities for working with values that are sequences.
/// First, enable the `seq` feature in your `Cargo.toml`:
///
/// ```toml
/// [dependencies.value-bag]
/// features = ["seq"]
/// ```
///
/// A sequence captured with either `sval` or `serde` can have its elements extracted:
///
/// ```
/// # #[cfg(not(all(feature = "serde1", feature = "seq")))] fn main() {}
/// # #[cfg(all(feature = "serde1", feature = "seq"))]
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// # use value_bag_serde1::json as serde_json;
/// use value_bag::ValueBag;
///
/// let value = ValueBag::from_serde1(&[1.0, 2.0, 3.0]);
///
/// let seq = value.to_f64_seq::<Vec<Option<f64>>>().ok_or("not a sequence")?;
///
/// assert_eq!(vec![Some(1.0), Some(2.0), Some(3.0)], seq);
/// # Ok(())
/// # }
/// ```
#[derive(Clone)]
pub struct ValueBag<'v> {
    inner: internal::Internal<'v>,
}

impl<'v> ValueBag<'v> {
    /// Get an empty `ValueBag`.
    #[inline]
    pub const fn empty() -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::None,
        }
    }

    /// Get a `ValueBag` from an `Option`.
    /// 
    /// This method will return `ValueBag::empty` if the value is `None`.
    #[inline]
    pub fn from_option(v: Option<impl Into<ValueBag<'v>>>) -> ValueBag<'v> {
        match v {
            Some(v) => v.into(),
            None => ValueBag::empty(),
        }
    }

    /// Get a `ValueBag` from a `u8`.
    #[inline]
    pub const fn from_u8(v: u8) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Unsigned(v as u64)
        }
    }

    /// Get a `ValueBag` from a `u16`.
    #[inline]
    pub const fn from_u16(v: u16) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Unsigned(v as u64)
        }
    }

    /// Get a `ValueBag` from a `u32`.
    #[inline]
    pub const fn from_u32(v: u32) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Unsigned(v as u64)
        }
    }

    /// Get a `ValueBag` from a `u64`.
    #[inline]
    pub const fn from_u64(v: u64) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Unsigned(v)
        }
    }

    /// Get a `ValueBag` from a `usize`.
    #[inline]
    pub const fn from_usize(v: usize) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Unsigned(v as u64)
        }
    }

    /// Get a `ValueBag` from a `u128`.
    #[inline]
    pub const fn from_u128_ref(v: &'v u128) -> ValueBag<'v> {
        ValueBag {
            #[cfg(not(feature = "inline-i128"))]
            inner: internal::Internal::BigUnsigned(v),
            #[cfg(feature = "inline-i128")]
            inner: internal::Internal::BigUnsigned(*v),
        }
    }

    /// Get a `ValueBag` from a `u128`.
    #[inline]
    #[cfg(feature = "inline-i128")]
    pub const fn from_u128(v: u128) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::BigUnsigned(v),
        }
    }

    /// Get a `ValueBag` from a `i8`.
    #[inline]
    pub const fn from_i8(v: i8) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Signed(v as i64)
        }
    }

    /// Get a `ValueBag` from a `i16`.
    #[inline]
    pub const fn from_i16(v: i16) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Signed(v as i64)
        }
    }

    /// Get a `ValueBag` from a `i32`.
    #[inline]
    pub const fn from_i32(v: i32) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Signed(v as i64)
        }
    }

    /// Get a `ValueBag` from a `i64`.
    #[inline]
    pub const fn from_i64(v: i64) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Signed(v)
        }
    }

    /// Get a `ValueBag` from a `isize`.
    #[inline]
    pub const fn from_isize(v: isize) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Signed(v as i64)
        }
    }

    /// Get a `ValueBag` from a `i128`.
    #[inline]
    pub const fn from_i128_ref(v: &'v i128) -> ValueBag<'v> {
        ValueBag {
            #[cfg(not(feature = "inline-i128"))]
            inner: internal::Internal::BigSigned(v),
            #[cfg(feature = "inline-i128")]
            inner: internal::Internal::BigSigned(*v),
        }
    }

    /// Get a `ValueBag` from a `i128`.
    #[inline]
    #[cfg(feature = "inline-i128")]
    pub const fn from_i128(v: i128) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::BigSigned(v),
        }
    }

    /// Get a `ValueBag` from a `f32`.
    #[inline]
    pub const fn from_f32(v: f32) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Float(v as f64)
        }
    }

    /// Get a `ValueBag` from a `f64`.
    #[inline]
    pub const fn from_f64(v: f64) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Float(v)
        }
    }

    /// Get a `ValueBag` from a `bool`.
    #[inline]
    pub const fn from_bool(v: bool) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Bool(v)
        }
    }

    /// Get a `ValueBag` from a `str`.
    #[inline]
    pub const fn from_str(v: &'v str) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Str(v)
        }
    }

    /// Get a `ValueBag` from a `char`.
    #[inline]
    pub const fn from_char(v: char) -> ValueBag<'v> {
        ValueBag {
            inner: internal::Internal::Char(v)
        }
    }

    /// Get a `ValueBag` from a reference to a `ValueBag`.
    #[inline]
    pub const fn by_ref<'u>(&'u self) -> ValueBag<'u> {
        ValueBag {
            inner: self.inner.by_ref(),
        }
    }
}

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

    #[cfg(feature = "inline-i128")]
    const SIZE_LIMIT_U64: usize = 4;
    #[cfg(not(feature = "inline-i128"))]
    const SIZE_LIMIT_U64: usize = 3;

    #[test]
    fn value_bag_size() {
        let size = mem::size_of::<ValueBag<'_>>();
        let limit = mem::size_of::<u64>() * SIZE_LIMIT_U64;

        if size > limit {
            panic!(
                "`ValueBag` size ({} bytes) is too large (expected up to {} bytes)",
                size, limit,
            );
        }
    }
}