firestore 0.61.1

Library provides a simple API for Google Firestore and own Serde serializer based on efficient gRPC API
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
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
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
//! Validated newtypes for Firestore document and collection IDs.
//!
//! See [`FirestoreDocumentId`] for the full rationale; [`FirestoreCollectionId`] is the same
//! shape applied to collection names. This module is private — both types are re-exported at the
//! crate root.

use crate::errors::FirestoreError;
use crate::FirestoreResult;
use serde::{Deserialize, Serialize, Serializer};
use std::borrow::{Borrow, Cow};
use std::fmt::{Display, Formatter};
use std::str::FromStr;

/// The one rule a path segment fails, if any.
///
/// This is the single source of truth for what makes a Firestore path segment valid, shared by
/// the runtime path ([`validate_path_segment`], which turns a violation into an error message)
/// and the compile-time path (`from_static` on both ID types, which turns one into a `panic!` that
/// aborts `const` evaluation). Add or change a rule here, not in either caller.
#[derive(Clone, Copy)]
enum PathSegmentViolation {
    Empty,
    TooLong { len: usize },
    ContainsSlash,
    DotOrDotDot,
}

impl PathSegmentViolation {
    /// The base rule phrase, shared by both callers below.
    ///
    /// [`validate_path_segment`] appends a field name and, for some rules, a dynamic detail on top
    /// of this. `from_static`'s panic uses it bare: `Display::fmt` is not a `const fn` on stable
    /// Rust, so there is no const-compatible way to interpolate a field name or a value into this
    /// message, and `panic!("{}", ...)` with a single `&'static str` argument is the one form of
    /// `panic!` that is const-evaluable. A failing `const` declaration already points `rustc` at
    /// the offending line, so the missing field name costs nothing there.
    const fn rule_message(self) -> &'static str {
        match self {
            Self::Empty => "must not be empty",
            Self::TooLong { .. } => "must be at most 1500 bytes",
            Self::ContainsSlash => "must not contain '/'",
            Self::DotOrDotDot => "must not be \".\" or \"..\"",
        }
    }
}

/// Checks `segment` against Firestore's ID rules without allocating.
///
/// `str::contains` and `str::eq` are not `const fn`, so this cannot reuse the ordinary string
/// methods and instead walks `segment.as_bytes()` by hand. That byte loop is what lets
/// `from_static` run at compile time; do not replace it with the `str`-method equivalent even
/// though it reads simpler; doing so would stop `from_static` from being a `const fn`.
const fn check_path_segment(segment: &str) -> Result<(), PathSegmentViolation> {
    let bytes = segment.as_bytes();
    let len = bytes.len();

    if len == 0 {
        return Err(PathSegmentViolation::Empty);
    }

    // Checked before the '/' and '.'/'..' checks below so that every other rule sees a value
    // already bounded to 1500 bytes.
    if len > 1500 {
        return Err(PathSegmentViolation::TooLong { len });
    }

    let mut i = 0;
    while i < len {
        if bytes[i] == b'/' {
            return Err(PathSegmentViolation::ContainsSlash);
        }
        i += 1;
    }

    if (len == 1 && bytes[0] == b'.') || (len == 2 && bytes[0] == b'.' && bytes[1] == b'.') {
        return Err(PathSegmentViolation::DotOrDotDot);
    }

    Ok(())
}

/// Validates a single Firestore path segment (a document ID or a collection ID).
///
/// `field` is the name reported in the resulting error, `"document_id"` or `"collection_id"`.
/// UTF-8 validity needs no check of its own — `segment: &str` is UTF-8 by construction. The
/// reserved `__*__` namespace is deliberately not checked; see the module docs.
pub(crate) fn validate_path_segment(segment: &str, field: &'static str) -> FirestoreResult<()> {
    let violation = match check_path_segment(segment) {
        Ok(()) => return Ok(()),
        Err(violation) => violation,
    };
    let rule = violation.rule_message();

    match violation {
        PathSegmentViolation::Empty => Err(FirestoreError::invalid_parameters(
            field,
            rule.to_string(),
        )),
        // The value itself is unbounded here, unlike every other violation below, so this
        // message reports the length rather than echoing it.
        PathSegmentViolation::TooLong { len } => Err(FirestoreError::invalid_parameters(
            field,
            format!("{rule}, was {len} bytes"),
        )),
        PathSegmentViolation::ContainsSlash => Err(FirestoreError::invalid_parameters(
            field,
            format!(
                "{rule}: \"{}\" - a slash-delimited path such as \"users/123/posts\" is not a single ID; \
                 build it with `.parent(db.parent_path(\"users\", \"123\")?)` and pass \"posts\" as the {field}",
                segment.escape_debug(),
            ),
        )),
        PathSegmentViolation::DotOrDotDot => Err(FirestoreError::invalid_parameters(
            field,
            format!("{rule}, got \"{segment}\""),
        )),
    }
}

/// A Firestore document ID that has been checked against Firestore's ID rules.
///
/// Construct one with [`FirestoreDocumentId::new`] at the point an ID enters your system, then
/// pass it (by value or by reference) anywhere this crate accepts a document ID, or store it in
/// your own structs.
///
/// ```rust
/// use firestore::FirestoreDocumentId;
///
/// let id = FirestoreDocumentId::new("user-42").expect("valid document id");
/// assert_eq!(id.as_str(), "user-42");
///
/// let err = FirestoreDocumentId::new("a/b").unwrap_err();
/// assert!(err.to_string().contains("document_id"));
///
/// let err = FirestoreDocumentId::new("").unwrap_err();
/// assert!(err.to_string().contains("document_id"));
/// ```
///
/// It implements `AsRef<str>` (and `&FirestoreDocumentId` does too, via the standard library's
/// blanket impl), so it drops into every document-ID parameter in this crate's fluent API without
/// a signature change:
///
/// ```rust,no_run
/// use firestore::{FirestoreDb, FirestoreDocumentId, FirestoreResult};
///
/// # async fn run() -> FirestoreResult<()> {
/// let db = FirestoreDb::new("my-project").await?;
/// let id = FirestoreDocumentId::new("user-42")?;
///
/// let doc = db.fluent().select().by_id_in("users").one(&id).await?;
/// # let _ = doc;
/// # Ok(())
/// # }
/// ```
///
/// A field typed as [`FirestoreDocumentId`] carries the same proof, and validates the same way
/// when deserialized — the usual arrival point for an untrusted ID:
///
/// ```rust
/// use firestore::FirestoreDocumentId;
/// use serde::{Deserialize, Serialize};
///
/// #[derive(Debug, Clone, Deserialize, Serialize)]
/// struct CreateSession {
///     user_id: FirestoreDocumentId,
/// }
///
/// let session = CreateSession {
///     user_id: FirestoreDocumentId::new("user-42")?,
/// };
/// assert_eq!(session.user_id.as_str(), "user-42");
/// # Ok::<(), firestore::errors::FirestoreError>(())
/// ```
///
/// This departs from [`FirestoreReference`](crate::FirestoreReference), which derives
/// `Deserialize` unconditionally and only validates lazily, on `parse()`. If a field must
/// round-trip an ID without validating it (for example, one already known to be safe, or logged
/// verbatim for diagnostics), keep it typed as `String` — that is the documented escape hatch,
/// not a gap in this type.
///
/// Neither this type nor [`FirestoreCollectionId`] implements [`rvstruct::ValueStruct`]. That
/// trait requires an `into_value(self) -> String` alongside `value()`, and a consuming conversion
/// back to a bare `String` is exactly what these types exist to discourage: it launders a
/// validated ID back into a value that can be mutated or concatenated while still looking like it
/// came from a checked source. For the same reason there is no `into_string()` and no
/// `From<FirestoreDocumentId> for String` — only the read-only [`value()`](Self::value) and
/// [`as_str()`](Self::as_str) accessors. An owned `String` is still reachable, deliberately
/// explicitly, via `id.as_str().to_string()`:
///
/// ```compile_fail
/// use firestore::FirestoreDocumentId;
/// let id = FirestoreDocumentId::new("user-42").unwrap();
/// let _owned: String = id.into();
/// ```
///
/// Firestore also exposes Datastore-mode entities with integer IDs as documents literally named
/// `__id7__`, and such documents are read today through the same path-building code these types
/// back. Validation here therefore does not reject the reserved `__*__` namespace: doing so would
/// turn an existing, working read into a client-side error for a case the server only rejects on
/// write. `"__id7__"` and `"__name__"` are accepted by [`FirestoreDocumentId::new`] and
/// [`FirestoreCollectionId::new`] on purpose.
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize)]
#[serde(try_from = "String")]
pub struct FirestoreDocumentId(Cow<'static, str>);

impl FirestoreDocumentId {
    /// Validates `id` and wraps it.
    ///
    /// # Errors
    /// Returns [`FirestoreError::InvalidParametersError`] if `id` is empty, longer than 1500
    /// bytes, contains `/`, or is exactly `"."` or `".."`.
    pub fn new<S: Into<String>>(id: S) -> FirestoreResult<Self> {
        let id = id.into();
        validate_path_segment(&id, "document_id")?;
        Ok(Self(Cow::Owned(id)))
    }

    /// Validates `id` without allocating or constructing a value.
    ///
    /// Useful to check a borrowed `&str` before deciding whether to take ownership of it.
    ///
    /// # Errors
    /// Same conditions as [`FirestoreDocumentId::new`].
    pub fn validate_str(id: &str) -> FirestoreResult<()> {
        validate_path_segment(id, "document_id")
    }

    /// Re-validates an already-constructed ID.
    ///
    /// A valid [`FirestoreDocumentId`] cannot become invalid after construction, so this always
    /// succeeds; it exists to mirror [`FirestoreListenerTarget::validate`](crate::FirestoreListenerTarget::validate)
    /// for callers that validate every ID-like value the same way.
    ///
    /// # Errors
    /// Never fails; returns `FirestoreResult<()>` for symmetry with [`FirestoreDocumentId::validate_str`].
    pub fn validate(&self) -> FirestoreResult<()> {
        validate_path_segment(&self.0, "document_id")
    }

    /// Validates `id` at compile time and wraps it without allocating, for a name known up front.
    ///
    /// Declare validated names the way you would declare `const NAME: &str = "..."` today:
    ///
    /// ```rust
    /// use firestore::FirestoreDocumentId;
    ///
    /// const WELCOME_DOC: FirestoreDocumentId = FirestoreDocumentId::from_static("welcome");
    /// assert_eq!(WELCOME_DOC.as_str(), "welcome");
    /// ```
    ///
    /// Used in a `const` or `static` item, an invalid literal is a compile error: evaluating the
    /// item panics, which `rustc` reports at the definition site rather than letting the invalid
    /// value reach a binary. Called from inside a function body, where the result is only a
    /// runtime value, the same invalid literal panics instead, exactly like an out-of-bounds
    /// `const fn` array index would.
    ///
    /// ```compile_fail
    /// use firestore::FirestoreDocumentId;
    /// const BAD: FirestoreDocumentId = FirestoreDocumentId::from_static("a/b");
    /// ```
    ///
    /// # Panics
    /// Panics if `id` is empty, longer than 1500 bytes, contains `/`, or is exactly `"."` or
    /// `".."`, and the call is not evaluated at compile time.
    pub const fn from_static(id: &'static str) -> Self {
        match check_path_segment(id) {
            Ok(()) => Self(Cow::Borrowed(id)),
            Err(violation) => panic!("{}", violation.rule_message()),
        }
    }

    /// Returns the wrapped ID.
    ///
    /// Equivalent to [`as_str`](Self::as_str); kept as a separate method so a validated ID reads
    /// the same as [`rvstruct::ValueStruct::value`] elsewhere in this crate's API. There is no
    /// consuming equivalent that returns an owned `String` (see the [`FirestoreDocumentId`] type
    /// docs for why). Use `id.as_str().to_string()` when an owned copy is genuinely needed.
    pub fn value(&self) -> &str {
        &self.0
    }

    /// Returns the wrapped ID as a `&str`. Equivalent to [`value`](Self::value).
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for FirestoreDocumentId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Borrow<str> for FirestoreDocumentId {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl Display for FirestoreDocumentId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Display::fmt(self.0.as_ref(), f)
    }
}

impl TryFrom<&str> for FirestoreDocumentId {
    type Error = FirestoreError;

    fn try_from(id: &str) -> Result<Self, Self::Error> {
        Self::new(id)
    }
}

impl TryFrom<String> for FirestoreDocumentId {
    type Error = FirestoreError;

    fn try_from(id: String) -> Result<Self, Self::Error> {
        Self::new(id)
    }
}

impl FromStr for FirestoreDocumentId {
    type Err = FirestoreError;

    fn from_str(id: &str) -> Result<Self, Self::Err> {
        Self::new(id)
    }
}

impl PartialEq<str> for FirestoreDocumentId {
    fn eq(&self, other: &str) -> bool {
        self.0.as_ref() == other
    }
}

impl PartialEq<FirestoreDocumentId> for str {
    fn eq(&self, other: &FirestoreDocumentId) -> bool {
        self == other.0.as_ref()
    }
}

impl PartialEq<&str> for FirestoreDocumentId {
    fn eq(&self, other: &&str) -> bool {
        self.0.as_ref() == *other
    }
}

impl PartialEq<FirestoreDocumentId> for &str {
    fn eq(&self, other: &FirestoreDocumentId) -> bool {
        *self == other.0.as_ref()
    }
}

impl PartialEq<String> for FirestoreDocumentId {
    fn eq(&self, other: &String) -> bool {
        self.0.as_ref() == other.as_str()
    }
}

impl PartialEq<FirestoreDocumentId> for String {
    fn eq(&self, other: &FirestoreDocumentId) -> bool {
        self.as_str() == other.0.as_ref()
    }
}

impl Serialize for FirestoreDocumentId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.0.as_ref())
    }
}

/// A Firestore collection ID that has been checked against Firestore's ID rules.
///
/// Construct one with [`FirestoreCollectionId::new`] at the point a collection name enters your
/// system — the natural case is a collection chosen at runtime, where an unchecked `/` would
/// silently re-target the operation at a different collection. It has the same API shape, and the
/// same design rationale (no consuming unwrap, no reserved-namespace check, the `String` escape
/// hatch), as [`FirestoreDocumentId`]; see that type's docs for the full explanation.
///
/// ```rust
/// use firestore::FirestoreCollectionId;
///
/// let id = FirestoreCollectionId::new("users").expect("valid collection id");
/// assert_eq!(id.as_str(), "users");
///
/// let err = FirestoreCollectionId::new("a/b").unwrap_err();
/// assert!(err.to_string().contains("collection_id"));
/// assert!(err.to_string().contains(".parent("));
///
/// let err = FirestoreCollectionId::new("").unwrap_err();
/// assert!(err.to_string().contains("collection_id"));
/// ```
///
/// Drop-in by reference into the fluent API, exactly like [`FirestoreDocumentId`]:
///
/// ```rust,no_run
/// use firestore::{FirestoreCollectionId, FirestoreDb, FirestoreResult};
///
/// # async fn run() -> FirestoreResult<()> {
/// let db = FirestoreDb::new("my-project").await?;
/// let collection = FirestoreCollectionId::new("users")?;
///
/// let documents = db.fluent().list().from(&collection).stream_all().await?;
/// # let _ = documents;
/// # Ok(())
/// # }
/// ```
///
/// Stored in a caller's own struct:
///
/// ```rust
/// use firestore::FirestoreCollectionId;
///
/// struct DynamicCollectionRequest {
///     collection: FirestoreCollectionId,
/// }
///
/// let request = DynamicCollectionRequest {
///     collection: FirestoreCollectionId::new("users")?,
/// };
/// assert_eq!(request.collection.as_str(), "users");
/// # Ok::<(), firestore::errors::FirestoreError>(())
/// ```
#[derive(Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash, Deserialize)]
#[serde(try_from = "String")]
pub struct FirestoreCollectionId(Cow<'static, str>);

impl FirestoreCollectionId {
    /// Validates `id` and wraps it.
    ///
    /// # Errors
    /// Returns [`FirestoreError::InvalidParametersError`] if `id` is empty, longer than 1500
    /// bytes, contains `/`, or is exactly `"."` or `".."`.
    pub fn new<S: Into<String>>(id: S) -> FirestoreResult<Self> {
        let id = id.into();
        validate_path_segment(&id, "collection_id")?;
        Ok(Self(Cow::Owned(id)))
    }

    /// Validates `id` without allocating or constructing a value.
    ///
    /// # Errors
    /// Same conditions as [`FirestoreCollectionId::new`].
    pub fn validate_str(id: &str) -> FirestoreResult<()> {
        validate_path_segment(id, "collection_id")
    }

    /// Re-validates an already-constructed ID.
    ///
    /// A valid [`FirestoreCollectionId`] cannot become invalid after construction, so this always
    /// succeeds; it exists to mirror [`FirestoreListenerTarget::validate`](crate::FirestoreListenerTarget::validate)
    /// for callers that validate every ID-like value the same way.
    ///
    /// # Errors
    /// Never fails; returns `FirestoreResult<()>` for symmetry with [`FirestoreCollectionId::validate_str`].
    pub fn validate(&self) -> FirestoreResult<()> {
        validate_path_segment(&self.0, "collection_id")
    }

    /// Validates `id` at compile time and wraps it without allocating, for a name known up front.
    ///
    /// Declare validated names the way you would declare `const NAME: &str = "..."` today:
    ///
    /// ```rust
    /// use firestore::FirestoreCollectionId;
    ///
    /// const USERS: FirestoreCollectionId = FirestoreCollectionId::from_static("users");
    /// assert_eq!(USERS.as_str(), "users");
    /// ```
    ///
    /// Used in a `const` or `static` item, an invalid literal is a compile error: evaluating the
    /// item panics, which `rustc` reports at the definition site rather than letting the invalid
    /// value reach a binary. Called from inside a function body, where the result is only a
    /// runtime value, the same invalid literal panics instead, exactly like an out-of-bounds
    /// `const fn` array index would.
    ///
    /// ```compile_fail
    /// use firestore::FirestoreCollectionId;
    /// const BAD: FirestoreCollectionId = FirestoreCollectionId::from_static("a/b");
    /// ```
    ///
    /// # Panics
    /// Panics if `id` is empty, longer than 1500 bytes, contains `/`, or is exactly `"."` or
    /// `".."`, and the call is not evaluated at compile time.
    pub const fn from_static(id: &'static str) -> Self {
        match check_path_segment(id) {
            Ok(()) => Self(Cow::Borrowed(id)),
            Err(violation) => panic!("{}", violation.rule_message()),
        }
    }

    /// Returns the wrapped ID.
    ///
    /// Equivalent to [`as_str`](Self::as_str); kept as a separate method so a validated ID reads
    /// the same as [`rvstruct::ValueStruct::value`] elsewhere in this crate's API. There is no
    /// consuming equivalent that returns an owned `String` (see the [`FirestoreDocumentId`] type
    /// docs for why). Use `id.as_str().to_string()` when an owned copy is genuinely needed.
    pub fn value(&self) -> &str {
        &self.0
    }

    /// Returns the wrapped ID as a `&str`. Equivalent to [`value`](Self::value).
    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl AsRef<str> for FirestoreCollectionId {
    fn as_ref(&self) -> &str {
        &self.0
    }
}

impl Borrow<str> for FirestoreCollectionId {
    fn borrow(&self) -> &str {
        &self.0
    }
}

impl Display for FirestoreCollectionId {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Display::fmt(self.0.as_ref(), f)
    }
}

impl TryFrom<&str> for FirestoreCollectionId {
    type Error = FirestoreError;

    fn try_from(id: &str) -> Result<Self, Self::Error> {
        Self::new(id)
    }
}

impl TryFrom<String> for FirestoreCollectionId {
    type Error = FirestoreError;

    fn try_from(id: String) -> Result<Self, Self::Error> {
        Self::new(id)
    }
}

impl FromStr for FirestoreCollectionId {
    type Err = FirestoreError;

    fn from_str(id: &str) -> Result<Self, Self::Err> {
        Self::new(id)
    }
}

impl PartialEq<str> for FirestoreCollectionId {
    fn eq(&self, other: &str) -> bool {
        self.0.as_ref() == other
    }
}

impl PartialEq<FirestoreCollectionId> for str {
    fn eq(&self, other: &FirestoreCollectionId) -> bool {
        self == other.0.as_ref()
    }
}

impl PartialEq<&str> for FirestoreCollectionId {
    fn eq(&self, other: &&str) -> bool {
        self.0.as_ref() == *other
    }
}

impl PartialEq<FirestoreCollectionId> for &str {
    fn eq(&self, other: &FirestoreCollectionId) -> bool {
        *self == other.0.as_ref()
    }
}

impl PartialEq<String> for FirestoreCollectionId {
    fn eq(&self, other: &String) -> bool {
        self.0.as_ref() == other.as_str()
    }
}

impl PartialEq<FirestoreCollectionId> for String {
    fn eq(&self, other: &FirestoreCollectionId) -> bool {
        self.as_str() == other.0.as_ref()
    }
}

impl Serialize for FirestoreCollectionId {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(self.0.as_ref())
    }
}

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

    #[test]
    fn document_id_accepts_valid_ids() {
        assert!(FirestoreDocumentId::new("user-42").is_ok());
        assert!(FirestoreDocumentId::new("...").is_ok());
        assert!(FirestoreDocumentId::new(".x").is_ok());
        assert!(FirestoreDocumentId::new("__id7__").is_ok());
        assert!(FirestoreDocumentId::new("__name__").is_ok());
    }

    #[test]
    fn collection_id_accepts_valid_ids() {
        assert!(FirestoreCollectionId::new("users").is_ok());
        assert!(FirestoreCollectionId::new("...").is_ok());
        assert!(FirestoreCollectionId::new(".x").is_ok());
        assert!(FirestoreCollectionId::new("__id7__").is_ok());
        assert!(FirestoreCollectionId::new("__name__").is_ok());
    }

    #[test]
    fn rejects_empty_slash_and_dot_segments() {
        for bad in ["", ".", "..", "a/b"] {
            assert!(
                FirestoreDocumentId::new(bad).is_err(),
                "expected {bad:?} to be rejected as a document id"
            );
            assert!(
                FirestoreCollectionId::new(bad).is_err(),
                "expected {bad:?} to be rejected as a collection id"
            );
        }
    }

    #[test]
    fn length_limit_is_measured_in_bytes_not_chars() {
        let at_limit = "é".repeat(750);
        assert_eq!(at_limit.len(), 1500);
        assert!(FirestoreDocumentId::new(at_limit.clone()).is_ok());
        assert!(FirestoreCollectionId::new(at_limit).is_ok());

        let over_limit = "é".repeat(751);
        assert_eq!(over_limit.len(), 1502);
        assert!(FirestoreDocumentId::new(over_limit.clone()).is_err());
        assert!(FirestoreCollectionId::new(over_limit).is_err());
    }

    #[test]
    fn oversized_id_error_reports_byte_count_not_the_value() {
        let huge = "x".repeat(10_000);
        let err = FirestoreDocumentId::new(huge).unwrap_err();
        let message = err.to_string();
        assert!(
            message.len() < 200,
            "message should be short, was {} bytes: {message}",
            message.len()
        );
        assert!(
            !message.contains(&"x".repeat(10)),
            "message must not echo the value"
        );
        assert!(message.contains("10000"));
    }

    #[test]
    fn slash_error_escapes_embedded_newlines() {
        let err = FirestoreCollectionId::new("a\nb/c").unwrap_err();
        let message = err.to_string();
        assert!(
            !message.contains('\n'),
            "message must not contain a raw newline: {message:?}"
        );
        assert!(
            message.contains("\\n"),
            "message should show the escaped newline: {message:?}"
        );
    }

    #[test]
    fn slash_error_names_the_parent_builder() {
        let err = FirestoreCollectionId::new("users/123").unwrap_err();
        let message = err.to_string();
        assert!(
            message.contains(".parent("),
            "message should point at `.parent()`: {message}"
        );
        assert!(message.contains("collection_id"));
    }

    #[test]
    fn value_and_as_str_agree() {
        let id = FirestoreDocumentId::new("user-42").unwrap();
        let v: &str = id.value();
        assert_eq!(v, "user-42");
        assert_eq!(id.value(), id.as_str());
    }

    #[test]
    fn validate_str_and_validate_agree_with_new() {
        assert!(FirestoreDocumentId::validate_str("user-42").is_ok());
        assert!(FirestoreDocumentId::validate_str("a/b").is_err());

        let id = FirestoreCollectionId::new("users").unwrap();
        assert!(id.validate().is_ok());
    }

    #[test]
    fn partial_eq_with_str_and_string_both_directions() {
        let id = FirestoreDocumentId::new("user-42").unwrap();
        assert_eq!(id, *"user-42");
        assert_eq!(*"user-42", id);
        assert_eq!(id, "user-42");
        assert_eq!("user-42", id);
        assert_eq!(id, "user-42".to_string());
        assert_eq!("user-42".to_string(), id);
    }

    #[test]
    fn try_from_and_from_str_round_trip() {
        let via_try_from: FirestoreDocumentId = "user-42".try_into().unwrap();
        let via_from_str: FirestoreDocumentId = "user-42".parse().unwrap();
        assert_eq!(via_try_from, via_from_str);

        assert!(FirestoreDocumentId::try_from("a/b").is_err());
        assert!("a/b".parse::<FirestoreDocumentId>().is_err());
    }

    #[test]
    fn deserialize_validates_via_try_from_string() {
        use serde::de::value::{Error as ValueError, StringDeserializer};
        use serde::de::IntoDeserializer;

        let deserializer: StringDeserializer<ValueError> =
            "user-42".to_string().into_deserializer();
        let id = FirestoreDocumentId::deserialize(deserializer).unwrap();
        assert_eq!(id.as_str(), "user-42");

        let bad_deserializer: StringDeserializer<ValueError> =
            "a/b".to_string().into_deserializer();
        assert!(FirestoreDocumentId::deserialize(bad_deserializer).is_err());
    }

    #[test]
    fn drop_in_via_as_ref_str_send() {
        fn takes<S: AsRef<str> + Send>(_: S) {}

        let doc_id = FirestoreDocumentId::new("doc-1").unwrap();
        takes(doc_id.clone());
        takes(&doc_id);

        let coll_id = FirestoreCollectionId::new("col-1").unwrap();
        takes(coll_id.clone());
        takes(&coll_id);
    }

    const CONST_DOC_ID: FirestoreDocumentId = FirestoreDocumentId::from_static("const-doc");
    static STATIC_COLLECTION_ID: FirestoreCollectionId =
        FirestoreCollectionId::from_static("static-collection");

    #[test]
    fn from_static_builds_const_and_static_items() {
        assert_eq!(CONST_DOC_ID.as_str(), "const-doc");
        assert_eq!(STATIC_COLLECTION_ID.as_str(), "static-collection");
    }

    #[test]
    fn from_static_agrees_with_new_on_valid_input() {
        let via_new = FirestoreDocumentId::new("const-doc").unwrap();
        assert_eq!(CONST_DOC_ID, via_new);

        let via_new = FirestoreCollectionId::new("static-collection").unwrap();
        assert_eq!(STATIC_COLLECTION_ID, via_new);
    }

    #[test]
    fn borrowed_and_owned_are_equal_and_hash_the_same() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        let borrowed = FirestoreDocumentId::from_static("user-42");
        let owned = FirestoreDocumentId::new("user-42").unwrap();
        assert_eq!(borrowed, owned);

        let hash_of = |id: &FirestoreDocumentId| {
            let mut hasher = DefaultHasher::new();
            id.hash(&mut hasher);
            hasher.finish()
        };
        assert_eq!(hash_of(&borrowed), hash_of(&owned));
    }

    #[test]
    fn hashmap_lookup_by_str_finds_a_from_static_key() {
        use std::collections::HashMap;

        const KEY: FirestoreCollectionId = FirestoreCollectionId::from_static("users");
        let mut map: HashMap<FirestoreCollectionId, u32> = HashMap::new();
        map.insert(KEY, 1);

        assert_eq!(map.get("users"), Some(&1));
    }
}