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
/*!
A streamable value.

# The `Value` trait

A [`Value`] is a type that has structure, like a number, string, map, or sequence.

## Deriving `Value`

Use the `derive` Cargo feature to support automatic implementations of the `Value` trait:

```toml,ignore
[dependencies.sval]
features = ["derive"]
```

Then derive the `Value` for struct-like datastructures:

```
# fn main() {}
# #[cfg(all(feature = "std", feature = "derive"))]
# mod test {
use sval::Value;

#[derive(Value)]
pub struct Data {
    id: u32,
    title: String,
}
# }
```

The trait can also be implemented manually:

```
use sval::value::{self, Value};

pub struct Id(u64);

impl Value for Id {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.u64(self.0)
    }
}
```

## Sequences

A sequence can be visited by iterating over its elements:

```
use sval::value::{self, Value};

pub struct Seq(Vec<u64>);

impl Value for Seq {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.seq_begin(Some(self.0.len()))?;

        for v in &self.0 {
            stream.seq_elem(v)?;
        }

        stream.seq_end()
    }
}
```

## Maps

A map can be visited by iterating over its key-value pairs:

```
# fn main() {}
# #[cfg(feature = "std")]
# mod test {
use std::collections::BTreeMap;
use sval::value::{self, Value};

pub struct Map(BTreeMap<String, u64>);

impl Value for Map {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.map_begin(Some(self.0.len()))?;

        for (k, v) in &self.0 {
            stream.map_key(k)?;
            stream.map_value(v)?;
        }

        stream.map_end()
    }
}
# }
```

## Structure that isn't known upfront

Types can stream a structure that's different than what they use internally.
In the following example, the `Map` type doesn't have any keys or values,
but serializes a nested map like `{"nested": {"key": 42}}`:

```
use sval::value::{self, Value};

pub struct Map;

impl Value for Map {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.map_begin(Some(1))?;

        stream.map_key_begin()?.str("nested")?;
        stream.map_value_begin()?.map_begin(Some(1))?;
        stream.map_key_begin()?.str("key")?;
        stream.map_value_begin()?.u64(42)?;
        stream.map_end()?;

        stream.map_end()
    }
}
```
*/

mod impls;

#[cfg(feature = "alloc")]
pub(crate) mod owned;

pub use crate::stream::RefMutStream as Stream;

#[cfg(feature = "alloc")]
pub use self::owned::OwnedValue;

/**
A value with a streamable structure.

# Implementing `Value`

Implementations of `Value` are expected to conform to the following
model:

## Only a single primitive, map or sequence is streamed

The following `Value` is valid:

```
# use sval::value::{self, Value};
# struct MyValue;
impl Value for MyValue {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        // VALID: The stream can take the primitive
        // value 42
        stream.any(42)
    }
}
```

The following `Value` is not valid:

```
# use sval::value::{self, Value};
# struct MyValue;
impl Value for MyValue {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.any(42)?;

        // INVALID: The stream already received the
        // primitive value 42
        stream.any(43)
    }
}
```

## All maps and sequences are completed, and in the right order

The following `Value` is valid:

```
# use sval::value::{self, Value};
# struct MyValue;
impl Value for MyValue {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.map_begin(None)?;
        stream.map_key("a")?;
        stream.map_value_begin()?.seq_begin(None)?;

        // VALID: The sequence is completed, then the map is completed
        stream.seq_end()?;
        stream.map_end()
    }
}
```

The following `Value` is not valid:

```
# use sval::value::{self, Value};
# struct MyValue;
impl Value for MyValue {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.map_begin(None)?;
        stream.map_key("a")?;
        stream.map_value_begin()?.seq_begin(None)?;

        // INVALID: The map is completed before the sequence,
        // even though the sequence was started last.
        stream.map_end()?;
        stream.seq_end()
    }
}
```

The following `Value` is not valid:

```
# use sval::value::{self, Value};
# struct MyValue;
impl Value for MyValue {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.map_begin(None)?;

        // INVALID: The map is never completed
        Ok(())
    }
}
```

## Map keys and values are received before their corresponding structure

The following `Value` is valid:

```
# use sval::value::{self, Value};
# struct MyValue;
impl Value for MyValue {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.map_begin(None)?;

        // VALID: The `map_key` and `map_value` methods
        // always call the underlying stream correctly
        stream.map_key("a")?;
        stream.map_value("b")?;

        // VALID: `map_key` and `map_value` are called before
        // their actual values are given
        stream.map_key_begin()?.any("c")?;
        stream.map_value_begin()?.any("d")?;

        stream.map_end()
    }
}
```

The following `Value` is not valid:

```
# use sval::value::{self, Value};
# struct MyValue;
impl Value for MyValue {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.map_begin(None)?;

        // INVALID: The underlying `map_key` and `map_value` methods
        // aren't being called before their actual values are given
        stream.any("a")?;
        stream.any("b")?;

        stream.map_end()
    }
}
```

## Map keys are received before values

The following `Value` is valid:

```
# use sval::value::{self, Value};
# struct MyValue;
impl Value for MyValue {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.map_begin(None)?;

        // VALID: The key is streamed before the value
        stream.map_key("a")?;
        stream.map_value("b")?;

        stream.map_end()
    }
}
```

The following `Value` is not valid:

```
# use sval::value::{self, Value};
# struct MyValue;
impl Value for MyValue {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.map_begin(None)?;

        // INVALID: The value is streamed before the key
        stream.map_value("b")?;
        stream.map_key("a")?;

        stream.map_end()
    }
}
```

## Sequence elements are received before their corresponding structure

The following `Value` is valid:

```
# use sval::value::{self, Value};
# struct MyValue;
impl Value for MyValue {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.seq_begin(None)?;

        // VALID: The `seq_elem` method
        // always calls the underlying stream correctly
        stream.seq_elem("a")?;

        // VALID: `seq_elem` is called before
        // their actual values are given
        stream.seq_elem_begin()?.any("b")?;

        stream.seq_end()
    }
}
```

The following `Value` is not valid:

```
# use sval::value::{self, Value};
# struct MyValue;
impl Value for MyValue {
    fn stream(&self, stream: &mut value::Stream) -> value::Result {
        stream.seq_begin(None)?;

        // INVALID: The underlying `seq_elem` method
        // isn't being called before the actual value is given
        stream.any("a")?;

        stream.seq_end()
    }
}
```
*/
pub trait Value {
    /**
    Stream this value.

    # Examples

    Use a [`stream::OwnedStream`] to stream a value:

    ```no_run
    # #[cfg(not(feature = "std"))]
    # fn main() {}
    # #[cfg(feature = "std")]
    # fn main() -> Result<(), Box<dyn std::error::Error>> {
    use sval::stream::OwnedStream;

    let mut stream = OwnedStream::new(MyStream);
    stream.any(42)?;
    # Ok(())
    # }
    # use sval::stream::{self, Stream};
    # struct MyStream;
    # impl Stream for MyStream {
    #     fn fmt(&mut self, _: stream::Arguments) -> stream::Result { unimplemented!() }
    # }
    ```

    It's less convenient, but the `stream` method can be called directly
    instead of using `OwnedStream.any`:

    ```no_run
    # #[cfg(not(feature = "std"))]
    # fn main() {}
    # #[cfg(feature = "std")]
    # fn main() -> Result<(), Box<dyn std::error::Error>> {
    use sval::{
        stream::OwnedStream,
        value::Value,
    };

    let mut stream = OwnedStream::new(MyStream);
    42.stream(&mut stream.borrow_mut())?;
    # Ok(())
    # }
    # use sval::stream::{self, Stream};
    # struct MyStream;
    # impl Stream for MyStream {
    #     fn fmt(&mut self, _: stream::Arguments) -> stream::Result { unimplemented!() }
    # }
    ```

    [`sval::stream`]: ../fn.stream.html
    [`stream::OwnedStream`]: ../stream/struct.OwnedStream.html
    */
    fn stream(&self, stream: &mut Stream) -> Result;
}

impl<'a, T: ?Sized> Value for &'a T
where
    T: Value,
{
    #[inline]
    fn stream(&self, stream: &mut Stream) -> Result {
        (**self).stream(stream)
    }
}

/**
The type returned by streaming methods.
*/
pub type Result = crate::std::result::Result<(), crate::Error>;

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

    #[test]
    fn value_is_object_safe() {
        fn _safe(_: &dyn Value) {}
    }
}