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
716
717
718
719
720
721
722
723
724
725
726
727
728
729
//! [](https://github.com/nik-rev/serde-cursor)
//!
//! This crate allows you to declaratively specify how to fetch the desired parts of a serde-compatible data format (such as JSON)
//! efficiently, without loading it all into memory, using a jq-like language.
//!
//! ```toml
//! ```
//!
//! # Examples
//!
//! The `Cursor!` macro makes it extremely easy to extract nested fields from data.
//!
//! ## Get version from `Cargo.toml`
//!
//! ```
//! use serde_cursor::Cursor;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let data = r#"
//! [workspace.package]
//! version = "0.1"
//! "#;
//!
//! let version: String = toml::from_str::<Cursor!(workspace.package.version)>(data)?.0;
//! assert_eq!(version, "0.1");
//! # Ok(()) }
//! ```
//!
//! `Cursor!(workspace.package.version)` is the magic juice - this type-macro expands to a type that implements [`serde::Deserialize`](serde_core::Deserialize).
//!
//! **Without `serde_cursor`**:
//!
//! *Pain and suffering...*
//!
//! ```
//! use serde::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct CargoToml {
//! workspace: Workspace
//! }
//!
//! #[derive(Deserialize)]
//! struct Workspace {
//! package: Package
//! }
//!
//! #[derive(Deserialize)]
//! struct Package {
//! version: String
//! }
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let data = r#"
//! [workspace.package]
//! version = "0.1"
//! "#;
//!
//! let version = toml::from_str::<CargoToml>(data)?.workspace.package.version;
//! # Ok(()) }
//! ```
//!
//! ## Get names of all dependencies from `Cargo.lock`
//!
//! The index-all `[]` accesses every element in an array:
//!
//! ```
//! use serde_cursor::Cursor;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let file = r#"
//! [[package]]
//! name = "serde"
//!
//! [[package]]
//! name = "rand"
//! "#;
//!
//! let packages: Vec<String> = toml::from_str::<Cursor!(package[].name)>(file)?.0;
//!
//! assert_eq!(packages, vec!["serde", "rand"]);
//! # Ok(()) }
//! ```
//!
//! # Syntax
//!
//! Specify the type `Vec<String>` after the path `package[].name`:
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let file = r#"
//! # [[package]]
//! # name = "serde"
//! #
//! # [[package]]
//! # name = "rand"
//! # "#;
//! # use serde_cursor::Cursor;
//! let packages = toml::from_str::<Cursor!(package[].name: Vec<String>)>(file)?.0;
//! # Ok(()) }
//! ```
//!
//! The type can be omitted, in which case it will be inferred:
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let file = r#"
//! # [[package]]
//! # name = "serde"
//! #
//! # [[package]]
//! # name = "rand"
//! # "#;
//! # use serde_cursor::Cursor;
//! let packages: Vec<String> = toml::from_str::<Cursor!(package[].name)>(file)?.0;
//! # Ok(()) }
//! ```
//!
//! Fields that consist of identifiers and `-`s can be used without quotes:
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let file = r#"
//! # [dev-dependencies.serde]
//! # version = "1.0"
//! # "#;
//! # use serde_cursor::Cursor;
//! # let version: String = toml::from_str::<
//! Cursor!(dev-dependencies.serde.version)
//! # >(file)?.0;
//! # Ok(()) }
//! ```
//!
//! Fields that contain spaces or other special characters must be quoted:
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let file = r#"
//! # [ferris."🦀::<>"]
//! # "\"" = true
//! # "#;
//! # use serde_cursor::Cursor;
//! # let ferris: bool = toml::from_str::<
//! Cursor!(ferris."🦀::<>".r#"""#)
//! # >(file)?.0;
//! # Ok(()) }
//! ```
//!
//! You can access specific elements of an array:
//!
//! ```
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let file = r#"
//! # [[package]]
//! # name = "serde"
//! # "#;
//! # use serde_cursor::Cursor;
//! # let ferris: String = toml::from_str::<
//! Cursor!(package[0].name)
//! # >(file)?.0;
//! # Ok(()) }
//! ```
//!
//! # `serde_cursor` + `monostate` = 🧡💛💚💙💜
//!
//! The [`monostate`](https://github.com/dtolnay/monostate) crate provides the `MustBe!` macro, which returns a type that implements
//! [`serde::Deserialize`](serde_core::Deserialize), and can only ever deserialize from one specific value.
//!
//! Together, these 2 crates provide an almost jq-like experience of data processing in Rust:
//!
//! ```
//! # /*
//! // early exit if the `reason` field is not equal to `"compiler-message"`
//! get!(reason: MustBe!("compiler-message"))?;
//! get!(message.message: MustBe!("trace_macro"))?;
//!
//! Ok(Expansion {
//! messages: get!(message.children[].message)?,
//! byte_start: get!(message.spans[0].byte_start)?,
//! byte_end: get!(message.spans[0].byte_end)?,
//! })
//! # */
//! ```
//!
//! The jq version of the above processing looks like this:
//!
//! ```jq
//! select(.reason == "compiler-message")
//! | select(.message.message == "trace_macro")
//! | {
//! messages: [.message.children[].message],
//! byte_start: .message.spans[0].byte_start,
//! byte_end: .message.spans[0].byte_end
//! }
//! ```
//!
//! The full code for the above example looks like this:
//!
//! ```
//! use monostate::MustBe;
//! use serde_cursor::Cursor;
//!
//! struct Expansion {
//! messages: Vec<String>,
//! byte_start: u32,
//! byte_end: u32,
//! }
//!
//! impl Expansion {
//! fn parse(value: &[u8]) -> serde_json::Result<Self> {
//! macro_rules! get {
//! ($($cursor:tt)*) => {
//! serde_json::from_slice::<
//! Cursor!($($cursor)*)
//! >(value).map(|it| it.0)
//! };
//! }
//!
//! get!(reason: MustBe!("compiler-message"))?;
//! get!(message.message: MustBe!("trace_macro"))?;
//!
//! Ok(Expansion {
//! messages: get!(message.children[].message)?,
//! byte_start: get!(message.spans[0].byte_start)?,
//! byte_end: get!(message.spans[0].byte_end)?,
//! })
//! }
//! }
//! ```
//!
//! <details>
//!
//! <summary>
//!
//! For reference, the same logic without `serde_cursor` or `monostate`
//!
//! </summary>
//!
//! ```
//! use serde::Deserialize;
//!
//! struct Expansion {
//! messages: Vec<String>,
//! byte_start: u32,
//! byte_end: u32,
//! }
//!
//! impl Expansion {
//! fn from_slice(value: &[u8]) -> serde_json::Result<Self> {
//! #[derive(Deserialize)]
//! struct RawDiagnostic {
//! reason: String,
//! message: DiagnosticMessage,
//! }
//!
//! #[derive(Deserialize)]
//! struct DiagnosticMessage {
//! message: String,
//! children: Vec<DiagnosticChild>,
//! spans: Vec<DiagnosticSpan>,
//! }
//!
//! #[derive(Deserialize)]
//! struct DiagnosticChild {
//! message: String,
//! }
//!
//! #[derive(Deserialize)]
//! struct DiagnosticSpan {
//! byte_start: u32,
//! byte_end: u32,
//! }
//!
//! let raw: RawDiagnostic = serde_json::from_slice(value)?;
//!
//! if raw.reason != "compiler-message" || raw.message.message != "trace_macro" {
//! return Err(serde::de::Error::custom("..."));
//! }
//!
//! let primary_span = raw.message.spans.get(0)
//! .ok_or_else(|| serde::de::Error::custom("..."))?;
//!
//! Ok(Expansion {
//! messages: raw.message.children.into_iter().map(|c| c.message).collect(),
//! byte_start: primary_span.byte_start,
//! byte_end: primary_span.byte_end,
//! })
//! }
//! }
//! ```
//!
//! </details>
//!
//! # Ranges
//!
//! Ranges are like `[]` but for only for elements with an index that falls in the range:
//!
//! ```
//! # /*
//! Cursor!(package[4..]);
//! Cursor!(package[..8]);
//! Cursor!(package[4..8]);
//! Cursor!(package[4..=8]);
//! # */
//! ```
//!
//! # Interpolations
//!
//! It's not uncommon for multiple queries to get quite repetitive:
//!
//! ```
//! # use serde_json::from_str;
//! # use serde_cursor::Cursor;
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let france = "france = { properties = { timeseries = [{ data = { instant = { details = { air_pressure_at_sea_level = 1.0, relative_humidity = 2.0, air_temperature = 3.0 } } } }] } }";
//! # let japan = "japan = { properties = { timeseries = [{ data = { instant = { details = { air_pressure_at_sea_level = 4.0, relative_humidity = 5.0, air_temperature = 6.0 } } } }] } }";
//! let pressure: Vec<f64> = toml::from_str::<Cursor!(france.properties.timeseries[].data.instant.details.air_pressure_at_sea_level)>(france)?.0;
//! let humidity: Vec<f64> = toml::from_str::<Cursor!(japan.properties.timeseries[].data.instant.details.relative_humidity)>(japan)?.0;
//! let temperature: Vec<f64> = toml::from_str::<Cursor!(japan.properties.timeseries[].data.instant.details.air_temperature)>(japan)?.0;
//! # Ok(()) }
//! ```
//!
//! `serde_cursor` supports **interpolations**. You can factor out a common path into a type `Details`, and then interpolate it with `$Details` in the path inside `Cursor!`:
//!
//! ```
//! # use serde_json::from_str;
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! # let france = "france = { properties = { timeseries = [{ data = { instant = { details = { air_pressure_at_sea_level = 1.0, relative_humidity = 2.0, air_temperature = 3.0 } } } }] } }";
//! # let japan = "japan = { properties = { timeseries = [{ data = { instant = { details = { air_pressure_at_sea_level = 4.0, relative_humidity = 5.0, air_temperature = 6.0 } } } }] } }";
//! # use serde_cursor::Cursor;
//! type Details<RestOfPath> = serde_cursor::Path!(properties.timeseries[].data.instant.details + RestOfPath);
//!
//! let pressure: Vec<f64> = toml::from_str::<Cursor!(france.$Details.air_pressure_at_sea_level)>(france)?.0;
//! let humidity: Vec<f64> = toml::from_str::<Cursor!(japan.$Details.relative_humidity)>(japan)?.0;
//! let temperature: Vec<f64> = toml::from_str::<Cursor!(japan.$Details.air_temperature)>(japan)?.0;
//! # Ok(()) }
//! ```
//!
//! # `serde_cursor` vs [`serde_query`](https://github.com/pandaman64/serde-query)
//!
//! `serde_query` also implements jq-like queries, but more verbosely.
//!
//! ## Single query
//!
//! `serde_cursor`:
//!
//! ```
//! use serde_cursor::Cursor;
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let data = r#"{ "commits": [{"author": "Ferris"}] }"#;
//!
//! let authors: Vec<String> = serde_json::from_str::<Cursor!(commits[].author)>(data)?.0;
//! # Ok(()) }
//! ```
//!
//! `serde_query`:
//!
//! ```
//! use serde_query::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct Data {
//! #[query(".commits.[].author")]
//! authors: Vec<String>,
//! }
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let data = r#"{ "commits": [{"author": "Ferris"}] }"#;
//! let data: Data = serde_json::from_str(data)?;
//!
//! let authors = data.authors;
//! # Ok(()) }
//! ```
//!
//! ## Storing queries in a `struct`
//!
//! `serde_cursor`:
//!
//! ```
//! use serde::Deserialize;
//! use serde_cursor::Cursor;
//!
//! #[derive(Deserialize)]
//! struct Data {
//! #[serde(rename = "commits")]
//! authors: Cursor!([].author: Vec<String>),
//! count: usize,
//! }
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let data = r#"{ "count": 1, "commits": [{"author": "Ferris"}] }"#;
//!
//! let data: Data = serde_json::from_str(data)?;
//! # Ok(()) }
//! ```
//!
//! `serde_query`:
//!
//! ```
//! use serde_query::Deserialize;
//!
//! #[derive(Deserialize)]
//! struct Data {
//! #[query(".commits.[].author")]
//! authors: Vec<String>,
//! #[query(".count")]
//! count: usize,
//! }
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let data = r#"{ "count": 1, "commits": [{"author": "Ferris"}] }"#;
//!
//! let data: Data = serde_json::from_str(data)?;
//! # Ok(()) }
//! ```
//!
//! # Great error messages
//!
//! When deserialization fails, you get the exact path of where the failure occurred:
//!
//! ```
//! use serde_cursor::Cursor;
//!
//! let data = serde_json::json!({ "author": { "id": "not-a-number" } });
//! let result = serde_json::from_value::<Cursor!(author.id: i32)>(data);
//! let err = result.unwrap_err().to_string();
//! assert_eq!(err, r#".author.id: invalid type: string "not-a-number", expected i32"#);
//! ```
//!
//! # `serde_with` integration
//!
//! If `feature = "serde_with"` is enabled, the type returned by `Cursor!` will implement [`serde_with::DeserializeAs`](https://docs.rs/serde_with/latest/serde_with/trait.DeserializeAs.html) and [`serde_with::SerializeAs`](https://docs.rs/serde_with/latest/serde_with/trait.SerializeAs.html),
//! meaning you can use it with the `#[serde_as]` attribute:
//!
//! ```
//! # use serde_with::serde_as;
//! use serde::{Serialize, Deserialize};
//! use serde_cursor::Cursor;
//!
//! #[serde_as]
//! #[derive(Serialize, Deserialize)]
//! struct CargoToml {
//! #[serde(rename = "workspace")]
//! #[serde_as(as = "Cursor!(package.version)")]
//! version: String,
//! }
//!
//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
//! let toml: CargoToml = toml::from_str("workspace = { package = { version = '0.1.0' } }")?;
//! assert_eq!(toml.version, "0.1.0");
//! assert_eq!(serde_json::to_string(&toml)?, r#"{"workspace":{"package":{"version":"0.1.0"}}}"#);
//! # Ok(()) }
//! ```
//!
//! # How does it work?
//!
//! The `Cursor!` macro expands to a recursive type that implements [`serde::Deserialize`](serde_core::Deserialize).
//! Information on how to access the nested fields is stored entirely inside the type system.
//!
//! Consider this query, which gets the first dependency of every dependency in `Cargo.toml`:
//!
//! ```rust
//! # /*
//! Cursor!(package[].dependencies[0]: String)
//! # */
//! ```
//!
//! For this `Cargo.lock`, it would extract `["libc", "find-msvc-tools"]`:
//!
//! ```toml
//! [[package]]
//! name = "android_system_properties"
//! dependencies = ["libc"]
//!
//! [[package]]
//! name = "cc"
//! dependencies = ["find-msvc-tools", "shlex"]
//! ```
//!
//! That macro is expanded into a `Cursor` type, which implements [`serde::Deserialize`](serde_core::Deserialize) and [`serde::Serialize`](serde_core::Serialize):
//!
//! ```rust
//! # /*
//! Cursor<
//! String, // : String
//! Path<
//! Field<"package">, // .package
//! Path<
//! IndexAll, // []
//! Path<
//! Field<"dependencies">, // .dependencies
//! Path<
//! Index<0>, // [0]
//! PathEnd
//! >,
//! >,
//! >,
//! >,
//! >
//! # */
//! ```
//!
//! The above is essentially an equivalent to:
//!
//! ```rust
//! # /*
//! vec![
//! Segment::Field("package"), // .package
//! Segment::IndexAll, // []
//! Segment::Field("dependencies"), // .dependencies
//! Segment::Index(0) // [0]
//! ]
//! # */
//! ```
//!
//! Except it exists entirely in the type system.
//!
//! Each time the [`serde::Deserialize::deserialize()`](https://docs.rs/serde/latest/serde/trait.Deserialize.html#tymethod.deserialize) function is called,
//! the first segment of the path (`.package`) is processed, and the rest of the path (`[].dependencies[0]`) is passed to the
//! [`serde::Deserialize`](serde_core::Deserialize) trait, again, and again - until the path is empty.
//!
//! Once the path is empty, we finally get to the type of the field - the `String` in the above example,
//! and finally call [`serde::Deserialize::deserialize()`](https://docs.rs/serde/latest/serde/trait.Deserialize.html#tymethod.deserialize) on that, to finish things off -
//! this `String` is then bubbled up the stack and returned from `<Cursor<String, _> as serde::Deserialize>::deserialize`.
extern crate alloc;
pub
pub
pub use Cursor;
pub use DeserializePath;
pub use Range;
pub use RangeFrom;
pub use RangeFull;
pub use RangeInclusive;
pub use RangeTo;
pub use RangeToInclusive;
pub use ConstPathSegment;
pub use Field;
pub use Index;
pub use PathSegment;
pub use SerializePath;
pub use Cursor;
pub use Path;
/// Available if you need to implement a trait for the type returned by `Cursor!`,
/// or implement the `Sequence` trait to have the index-all `[]` syntax work with
/// more collections.
///
/// This module only shows up in the generated documentation to group items that are
/// implementation details together, but it doesn't actually exist.
///
/// All of these items are exported from the crate root, but hidden.
// This only exists to make the generated macro output
// slightly more sane
pub use Char1Byte as C1;
pub use Char2Byte as C2;
pub use Char3Byte as C3;
pub use Char4Byte as C4;
pub use StrLen;
pub use Path;
pub use PathEnd;
pub use Sequence;