compose_spec 0.3.0

Types for (de)serializing from/to the compose-spec
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
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
//! Provides [`Image`] for the `image` field of [`Service`](super::Service) and `tags` field of
//! [`Build`](super::Build).

mod digest;
mod name;
mod tag;

use std::{
    borrow::Borrow,
    cmp::Ordering,
    fmt::{self, Display, Formatter},
    hash::{Hash, Hasher},
    ops::{AddAssign, SubAssign},
};

use compose_spec_macros::{DeserializeTryFromString, SerializeDisplay};
use thiserror::Error;

use crate::impl_from_str;

pub use self::{
    digest::{Digest, InvalidDigestError},
    name::{InvalidNamePartError, Name},
    tag::{InvalidTagError, Tag},
};

/// Container image specification.
///
/// Images contain a name and an optional tag or digest. Each part of the image specification must
/// conform to a specific format. See [`Name`], [`Tag`], and [`Digest`] for details. The general
/// format is `{name}[:{tag}|@{digest}]`.
///
/// [compose-spec](https://github.com/compose-spec/compose-spec/blob/master/05-services.md#image)
#[derive(SerializeDisplay, DeserializeTryFromString, Debug, Clone)]
pub struct Image {
    /// Inner string.
    inner: String,

    /// Byte position of `inner` where the registry ends, if the image has a registry part.
    registry_end: Option<usize>,

    /// Byte position of `inner` where the tag or digest starts, after its separator (: or @),
    /// if the image has a tag or digest.
    tag_or_digest_start: Option<TagOrDigestStart>,
}

impl Image {
    /// Parse an [`Image`] from a string.
    ///
    /// # Errors
    ///
    /// Images are made up of a [`Name`] and an optional [`Tag`] or [`Digest`]. Each part has
    /// specific requirements for that part of the string to conform to. See [`Name::new()`],
    /// [`Tag::new()`], and [`Digest::new()`] for details.
    ///
    /// This function will also error if the string contains both a tag and digest.
    ///
    /// # Examples
    ///
    /// ```
    /// use compose_spec::service::image::{Image, InvalidImageError};
    ///
    /// let image = Image::parse("quay.io/podman/hello:latest").unwrap();
    ///
    /// assert_eq!(image, "quay.io/podman/hello:latest");
    /// assert_eq!(image.registry(), Some("quay.io"));
    /// assert_eq!(image.name(), "quay.io/podman/hello");
    /// assert_eq!(image.tag(), Some("latest"));
    /// assert_eq!(image.digest(), None);
    ///
    /// // Images cannot have a tag and a digest.
    /// let image = "quay.io/podman/hello:latest@sha256:075975296016084fc66b59c35c9d4504765d95aadcd5469f28d2b75750348fc5";
    /// assert_eq!(Image::parse(image), Err(InvalidImageError::TagAndDigest));
    /// ```
    pub fn parse<T>(image: T) -> Result<Self, InvalidImageError>
    where
        T: AsRef<str> + Into<String>,
    {
        let (registry_end, tag_or_digest_start) = Self::parse_impl(image.as_ref())?;

        Ok(Self {
            inner: image.into(),
            registry_end,
            tag_or_digest_start,
        })
    }

    /// Concrete implementation for [`Self::parse()`].
    fn parse_impl(
        image: &str,
    ) -> Result<(Option<usize>, Option<TagOrDigestStart>), InvalidImageError> {
        let (image, digest_start) = image
            .split_once('@')
            .map_or(Ok((image, None)), |(image, digest)| {
                Digest::new(digest).map(|_| (image, Some(image.len() + 1)))
            })?;

        let (image, tag_start) = image
            .rsplit_once(':')
            // If tag contains '/', then image has a registry with a port and no tag.
            .filter(|(_, tag)| !tag.contains('/'))
            .map_or(Ok((image, None)), |(image, tag)| {
                Tag::new(tag).map(|_| (image, Some(image.len() + 1)))
            })?;

        let tag_or_digest = match (digest_start, tag_start) {
            (None, None) => None,
            (None, Some(tag_start)) => Some(TagOrDigestStart::Tag(tag_start)),
            (Some(digest_start), None) => Some(TagOrDigestStart::Digest(digest_start)),
            (Some(_), Some(_)) => return Err(InvalidImageError::TagAndDigest),
        };

        let name = Name::new(image)?;

        Ok((name.registry_end(), tag_or_digest))
    }

    /// Create an [`Image`] from validated parts.
    ///
    /// # Examples
    ///
    /// ```
    /// use compose_spec::service::image::{Image, Name, Tag};
    ///
    /// let name = Name::new("quay.io/podman/hello").unwrap();
    /// let tag = Tag::new("latest").unwrap();
    ///
    /// let image = Image::from_parts(name, Some(tag.into()));
    ///
    /// assert_eq!(image, "quay.io/podman/hello:latest");
    /// ```
    pub fn from_parts(name: Name, tag_or_digest: Option<TagOrDigest>) -> Self {
        let registry_end = name.registry_end();
        let name = name.into_inner();

        let tag_or_digest_len = tag_or_digest
            .as_ref()
            .map(TagOrDigest::len)
            .unwrap_or_default();
        let mut inner = String::with_capacity(name.len() + tag_or_digest_len);

        inner.push_str(name);

        let tag_or_digest_start = tag_or_digest.map(|tag_or_digest| {
            tag_or_digest.push_to_string(&mut inner);
            tag_or_digest.as_start(inner.len())
        });

        Self {
            inner,
            registry_end,
            tag_or_digest_start,
        }
    }

    /// String slice of the entire image.
    #[must_use]
    pub fn as_str(&self) -> &str {
        &self.inner
    }

    /// Registry portion of the image.
    ///
    /// Returns [`None`] if the image name does not have a registry component.
    ///
    /// # Examples
    ///
    /// ```
    /// use compose_spec::service::Image;
    ///
    /// let image = Image::parse("quay.io/podman/hello").unwrap();
    /// assert_eq!(image.registry(), Some("quay.io"));
    ///
    /// let image = Image::parse("library/busybox").unwrap();
    /// assert_eq!(image.registry(), None);
    /// ```
    #[must_use]
    pub fn registry(&self) -> Option<&str> {
        self.registry_end.map(|end| {
            // PANIC_SAFETY:
            // `registry_end` is always within `inner`.
            // `inner` only contains ASCII.
            // Checked with `registry()` test.
            #[allow(clippy::indexing_slicing, clippy::string_slice)]
            &self.inner[..end]
        })
    }

    /// Set the registry portion of the image name, use [`None`] to remove it.
    ///
    /// # Examples
    ///
    /// ```
    /// use compose_spec::service::image::{Image, Name};
    ///
    /// let mut image = Image::parse("quay.io/k9withabone/podlet").unwrap();
    ///
    /// image.set_registry(None);
    /// assert_eq!(image.registry(), None);
    /// assert_eq!(image, "k9withabone/podlet");
    ///
    /// image.set_registry(Some(Name::new("docker.io").unwrap()));
    /// assert_eq!(image.registry(), Some("docker.io"));
    /// assert_eq!(image, "docker.io/k9withabone/podlet");
    ///
    /// image.set_registry(Some(Name::new("quay.io").unwrap()));
    /// assert_eq!(image.registry(), Some("quay.io"));
    /// assert_eq!(image, "quay.io/k9withabone/podlet");
    /// ```
    pub fn set_registry(&mut self, registry: Option<Name>) {
        match (registry, self.registry_end) {
            // Replace registry
            (Some(registry), Some(end)) => {
                let registry = registry.into_inner();
                self.inner.replace_range(..end, registry);
                let new_len = registry.len();
                self.registry_end = Some(new_len);
                self.update_tag_or_digest_start(end, new_len);
            }
            // Add registry
            (Some(registry), None) => {
                let registry = registry.into_inner();
                self.inner = format!("{registry}/{}", &self.inner);
                self.registry_end = Some(registry.len());
                self.update_tag_or_digest_start(0, registry.len() + 1);
            }
            // Remove registry
            (None, Some(mut end)) => {
                // Add one to end for '/' separator.
                end += 1;
                self.inner.replace_range(..end, "");
                self.registry_end = None;
                self.update_tag_or_digest_start(end, 0);
            }
            // Status quo
            (None, None) => {}
        }
    }

    /// The full name portion of the image, including the registry, as a string slice.
    ///
    /// # Examples
    ///
    /// ```
    /// use compose_spec::service::Image;
    ///
    /// let image = Image::parse("quay.io/podman/hello:latest").unwrap();
    /// assert_eq!(image.name(), "quay.io/podman/hello");
    /// ```
    #[must_use]
    pub fn name(&self) -> &str {
        // PANIC_SAFETY:
        // `name_end()` is always within `inner`.
        // `inner` only contains ASCII.
        // Checked with `name()` test.
        #[allow(clippy::indexing_slicing, clippy::string_slice)]
        &self.inner[..self.name_end()]
    }

    /// The [`Name`] portion of the image.
    #[must_use]
    pub fn as_name(&self) -> Name {
        Name::new_unchecked(self.name(), self.registry_end)
    }

    /// Set the name portion of the image.
    ///
    /// # Examples
    ///
    /// ```
    /// use compose_spec::service::image::{Image, Name};
    ///
    /// let mut image = Image::parse("quay.io/podman/hello:latest").unwrap();
    /// assert_eq!(image.name(), "quay.io/podman/hello");
    ///
    /// image.set_name(Name::new("docker.io/library/busybox").unwrap());
    /// assert_eq!(image.name(), "docker.io/library/busybox");
    /// ```
    pub fn set_name(&mut self, name: Name) {
        let end = self.name_end();
        self.inner.replace_range(..end, name.as_ref());

        self.registry_end = name.registry_end();

        self.update_tag_or_digest_start(end, name.into_inner().len());
    }

    /// Return the byte positions where the image name ends.
    fn name_end(&self) -> usize {
        // Subtract one from tag or digest start for separator.
        self.tag_or_digest_start
            .map_or_else(|| self.inner.len(), |start| start.into_inner() - 1)
    }

    /// Returns a string slice of the image's tag if it has one.
    ///
    /// # Examples
    ///
    /// ```
    /// use compose_spec::service::Image;
    ///
    /// let image = Image::parse("quay.io/podman/hello:latest").unwrap();
    /// assert_eq!(image.tag(), Some("latest"));
    /// ```
    #[must_use]
    pub fn tag(&self) -> Option<&str> {
        if let Some(TagOrDigestStart::Tag(start)) = self.tag_or_digest_start {
            // PANIC_SAFETY:
            // `start` is always within `inner`.
            // `inner` only contains ASCII.
            // Checked with `tag_and_digest()` test.
            #[allow(clippy::indexing_slicing, clippy::string_slice)]
            Some(&self.inner[start..])
        } else {
            None
        }
    }

    /// The [`Tag`] portion of the image, if it has one.
    #[must_use]
    pub fn as_tag(&self) -> Option<Tag> {
        self.tag().map(Tag::new_unchecked)
    }

    /// Set or remove the image's tag.
    ///
    /// If the image has a digest it is removed.
    ///
    /// # Examples
    ///
    /// ```
    /// use compose_spec::service::image::{Image, Tag};
    ///
    /// let digest = "sha256:075975296016084fc66b59c35c9d4504765d95aadcd5469f28d2b75750348fc5";
    /// let mut image = Image::parse(format!("quay.io/podman/hello@{digest}")).unwrap();
    ///
    /// image.set_tag(Some(Tag::new("latest").unwrap()));
    /// assert_eq!(image.tag(), Some("latest"));
    /// ```
    pub fn set_tag(&mut self, tag: Option<Tag>) {
        self.set_tag_or_digest(tag.map(Into::into));
    }

    /// Returns a string slice of the image's digest if it has one.
    ///
    /// # Examples
    ///
    /// ```
    /// use compose_spec::service::Image;
    ///
    /// let digest = "sha256:075975296016084fc66b59c35c9d4504765d95aadcd5469f28d2b75750348fc5";
    /// let image = Image::parse(format!("quay.io/podman/hello@{digest}")).unwrap();
    ///
    /// assert_eq!(image.digest(), Some(digest));
    /// ```
    #[must_use]
    pub fn digest(&self) -> Option<&str> {
        if let Some(TagOrDigestStart::Digest(start)) = self.tag_or_digest_start {
            // PANIC_SAFETY:
            // `start` is always within `inner`.
            // `inner` only contains ASCII.
            // Checked with `tag_and_digest()` test.
            #[allow(clippy::indexing_slicing, clippy::string_slice)]
            Some(&self.inner[start..])
        } else {
            None
        }
    }

    /// The [`Digest`] portion of the image, if it has one.
    #[must_use]
    pub fn as_digest(&self) -> Option<Digest> {
        self.digest().map(Digest::new_unchecked)
    }

    /// Set or remove the image's digest.
    ///
    /// If the image has a tag it is removed.
    ///
    /// # Examples
    ///
    /// ```
    /// use compose_spec::service::image::{Image, Digest};
    ///
    /// let mut image = Image::parse(format!("quay.io/podman/hello:latest")).unwrap();
    ///
    /// let digest = "sha256:075975296016084fc66b59c35c9d4504765d95aadcd5469f28d2b75750348fc5";
    /// image.set_digest(Some(Digest::new(digest).unwrap()));
    /// assert_eq!(image.digest(), Some(digest));
    /// ```
    pub fn set_digest(&mut self, digest: Option<Digest>) {
        self.set_tag_or_digest(digest.map(Into::into));
    }

    /// The [`TagOrDigest`] portion of the image, if it has one.
    #[must_use]
    pub fn as_tag_or_digest(&self) -> Option<TagOrDigest> {
        match self.tag_or_digest_start {
            Some(TagOrDigestStart::Tag(start)) => {
                // PANIC_SAFETY:
                // `start` is always within `inner`.
                // `inner` only contains ASCII.
                // Checked with `tag_and_digest()` test.
                #[allow(clippy::indexing_slicing, clippy::string_slice)]
                let tag = Tag::new_unchecked(&self.inner[start..]);
                Some(TagOrDigest::Tag(tag))
            }
            Some(TagOrDigestStart::Digest(start)) => {
                // PANIC_SAFETY:
                // `start` is always within `inner`.
                // `inner` only contains ASCII.
                // Checked with `tag_and_digest()` test.
                #[allow(clippy::indexing_slicing, clippy::string_slice)]
                let digest = Digest::new_unchecked(&self.inner[start..]);
                Some(TagOrDigest::Digest(digest))
            }
            None => None,
        }
    }

    /// Set or remove the image's tag or digest.
    pub fn set_tag_or_digest(&mut self, tag_or_digest: Option<TagOrDigest>) {
        match (tag_or_digest, self.tag_or_digest_start) {
            // Replace tag
            (Some(TagOrDigest::Tag(tag)), Some(TagOrDigestStart::Tag(start))) => {
                self.inner.replace_range(start.., tag.into_inner());
            }
            // Replace digest
            (Some(TagOrDigest::Digest(digest)), Some(TagOrDigestStart::Digest(start))) => {
                self.inner.replace_range(start.., digest.into_inner());
            }
            // Set tag or digest / replace one with the other
            (Some(tag_or_digest), Some(_) | None) => {
                self.inner.truncate(self.name_end());
                // Add one for separator
                self.tag_or_digest_start = Some(tag_or_digest.as_start(self.inner.len()));
                tag_or_digest.push_to_string(&mut self.inner);
            }
            // Remove tag or digest
            (None, Some(start)) => {
                // Subtract one from tag or digest start for separator
                let new_end = start.into_inner() - 1;
                self.tag_or_digest_start = None;
                self.inner.truncate(new_end);
            }
            // Status quo
            (None, None) => {}
        }
    }

    /// Update the start position of the tag or digest, if it exists.
    ///
    /// The absolute sizes of `old_len` and `new_len` do not matter, only their relative size.
    fn update_tag_or_digest_start(&mut self, old_len: usize, new_len: usize) {
        if let Some(tag_or_digest) = &mut self.tag_or_digest_start {
            match old_len.cmp(&new_len) {
                Ordering::Less => *tag_or_digest += new_len - old_len,
                Ordering::Equal => {}
                Ordering::Greater => *tag_or_digest -= old_len - new_len,
            }
        }
    }

    /// The [`Name`] and [`TagOrDigest`] parts of the image.
    #[must_use]
    pub fn as_parts(&self) -> (Name, Option<TagOrDigest>) {
        (self.as_name(), self.as_tag_or_digest())
    }

    /// Consume the [`Image`] and return its inner [`String`].
    #[must_use]
    pub fn into_inner(self) -> String {
        self.inner
    }
}

/// Error returned when parsing an [`Image`] from a string.
#[derive(Error, Debug, Clone, PartialEq, Eq)]
pub enum InvalidImageError {
    /// Given digest was invalid.
    #[error("invalid image digest")]
    Digest(#[from] InvalidDigestError),

    /// Given tag was invalid.
    #[error("invalid image tag")]
    Tag(#[from] InvalidTagError),

    /// Both a tag and digest were given.
    #[error("image cannot have a tag and a digest")]
    TagAndDigest,

    /// Part of the given image name was invalid.
    #[error("invalid image name part")]
    NamePart(#[from] InvalidNamePartError),
}

impl PartialEq for Image {
    fn eq(&self, other: &Self) -> bool {
        self.inner.eq(&other.inner)
    }
}

impl Eq for Image {}

impl PartialEq<str> for Image {
    fn eq(&self, other: &str) -> bool {
        self.inner.eq(other)
    }
}

impl PartialEq<&str> for Image {
    fn eq(&self, other: &&str) -> bool {
        self.inner.eq(other)
    }
}

impl PartialOrd for Image {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Image {
    fn cmp(&self, other: &Self) -> Ordering {
        self.inner.cmp(&other.inner)
    }
}

impl Hash for Image {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.inner.hash(state);
    }
}

impl_from_str!(Image => InvalidImageError);

impl<'a> From<&'a Image> for (Name<'a>, Option<TagOrDigest<'a>>) {
    fn from(value: &'a Image) -> Self {
        value.as_parts()
    }
}

impl<'a> From<(Name<'a>, Option<TagOrDigest<'a>>)> for Image {
    fn from((name, tag_or_digest): (Name<'a>, Option<TagOrDigest<'a>>)) -> Self {
        Self::from_parts(name, tag_or_digest)
    }
}

impl<'a> From<(Name<'a>, TagOrDigest<'a>)> for Image {
    fn from((name, tag_or_digest): (Name<'a>, TagOrDigest<'a>)) -> Self {
        (name, Some(tag_or_digest)).into()
    }
}

impl<'a> From<Name<'a>> for Image {
    fn from(value: Name<'a>) -> Self {
        (value, None).into()
    }
}

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

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

impl From<Image> for String {
    fn from(value: Image) -> Self {
        value.into_inner()
    }
}

impl Display for Image {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str(&self.inner)
    }
}

/// Byte position where the tag or digest starts, after the separator (: or @), in an [`Image`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum TagOrDigestStart {
    /// The [`Image`] contains a [`Tag`].
    Tag(usize),
    /// The [`Image`] contains a [`Digest`].
    Digest(usize),
}

impl TagOrDigestStart {
    /// Return the inner start value for either variant.
    const fn into_inner(self) -> usize {
        match self {
            Self::Tag(tag_start) => tag_start,
            Self::Digest(digest_start) => digest_start,
        }
    }
}

impl AsMut<usize> for TagOrDigestStart {
    fn as_mut(&mut self) -> &mut usize {
        match self {
            Self::Tag(tag_start) => tag_start,
            Self::Digest(digest_start) => digest_start,
        }
    }
}

impl AddAssign<usize> for TagOrDigestStart {
    fn add_assign(&mut self, rhs: usize) {
        *self.as_mut() += rhs;
    }
}

impl SubAssign<usize> for TagOrDigestStart {
    fn sub_assign(&mut self, rhs: usize) {
        *self.as_mut() -= rhs;
    }
}

/// Validated [`Image`] [`Tag`] or [`Digest`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum TagOrDigest<'a> {
    /// Validated [`Image`] [`Tag`].
    Tag(Tag<'a>),
    /// Validated [`Image`] [`Digest`].
    Digest(Digest<'a>),
}

impl<'a> TagOrDigest<'a> {
    /// Returns [`Some`] if [`Tag`].
    #[must_use]
    pub const fn into_tag(self) -> Option<Tag<'a>> {
        if let Self::Tag(tag) = self {
            Some(tag)
        } else {
            None
        }
    }

    /// Returns [`Some`] if [`Digest`].
    #[must_use]
    pub const fn into_digest(self) -> Option<Digest<'a>> {
        if let Self::Digest(digest) = self {
            Some(digest)
        } else {
            None
        }
    }

    /// Returns the separator character (':' or '@') to use this tag or digest in an [`Image`].
    #[must_use]
    pub const fn separator(&self) -> char {
        match self {
            Self::Tag(_) => ':',
            Self::Digest(_) => '@',
        }
    }

    /// Length in bytes of the inner string slice, plus one for the beginning separator (':' or '@').
    fn len(&self) -> usize {
        match self {
            Self::Tag(tag) => tag.as_ref().len() + 1,
            Self::Digest(digest) => digest.as_ref().len() + 1,
        }
    }

    /// Create a [`TagOrDigestStart`] based on the [`TagOrDigest`] variant.
    const fn as_start(&self, name_end: usize) -> TagOrDigestStart {
        // Add one for separator.
        let start = name_end + 1;
        match self {
            Self::Tag(_) => TagOrDigestStart::Tag(start),
            Self::Digest(_) => TagOrDigestStart::Digest(start),
        }
    }

    /// Push the correct separator (':' or '@'), then the inner string slice to the given `string`.
    fn push_to_string(&self, string: &mut String) {
        string.push(self.separator());
        string.push_str(self.as_ref());
    }
}

impl<'a> From<Tag<'a>> for TagOrDigest<'a> {
    fn from(value: Tag<'a>) -> Self {
        Self::Tag(value)
    }
}

impl<'a> From<Digest<'a>> for TagOrDigest<'a> {
    fn from(value: Digest<'a>) -> Self {
        Self::Digest(value)
    }
}

impl<'a> AsRef<str> for TagOrDigest<'a> {
    fn as_ref(&self) -> &str {
        match self {
            Self::Tag(tag) => tag.as_ref(),
            Self::Digest(digest) => digest.as_ref(),
        }
    }
}

/// Returns `true` if `char` is a lowercase ASCII alphanumeric character.
const fn char_is_alnum(char: char) -> bool {
    matches!(char, 'a'..='z' | '0'..='9')
}

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

    fn assert_parts_eq(
        image: &Image,
        registry: Option<&str>,
        name: &str,
        tag_or_digest: Option<&str>,
    ) {
        assert_eq!(image.registry(), registry);
        assert_eq!(image.name(), name);
        assert_eq!(
            image.as_tag_or_digest().as_ref().map(AsRef::as_ref),
            tag_or_digest,
        );
    }

    #[test]
    fn registry() -> Result<(), InvalidImageError> {
        let mut image = Image::parse("quay.io/podman/hello:latest")?;
        assert_parts_eq(
            &image,
            Some("quay.io"),
            "quay.io/podman/hello",
            Some("latest"),
        );

        // Replace registry
        image.set_registry(Some(Name::new("docker.io")?));
        assert_parts_eq(
            &image,
            Some("docker.io"),
            "docker.io/podman/hello",
            Some("latest"),
        );

        // Remove registry
        image.set_registry(None);
        assert_parts_eq(&image, None, "podman/hello", Some("latest"));

        // Add registry
        image.set_registry(Some(Name::new("quay.io")?));
        assert_parts_eq(
            &image,
            Some("quay.io"),
            "quay.io/podman/hello",
            Some("latest"),
        );

        // Registry with port
        let image = Image::parse("quay.io:443/podman/hello")?;
        assert_parts_eq(
            &image,
            Some("quay.io:443"),
            "quay.io:443/podman/hello",
            None,
        );

        // Registry with port and tag
        let image = Image::parse("quay.io:443/podman/hello:latest")?;
        assert_parts_eq(
            &image,
            Some("quay.io:443"),
            "quay.io:443/podman/hello",
            Some("latest"),
        );

        Ok(())
    }

    #[test]
    fn name() -> Result<(), InvalidImageError> {
        let mut image = Image::parse("quay.io/podman/hello:latest")?;
        assert_parts_eq(
            &image,
            Some("quay.io"),
            "quay.io/podman/hello",
            Some("latest"),
        );
        assert_eq!(image.as_name(), "quay.io/podman/hello");

        image.set_name(Name::new("docker.io/library/busybox")?);
        assert_parts_eq(
            &image,
            Some("docker.io"),
            "docker.io/library/busybox",
            Some("latest"),
        );
        assert_eq!(image.as_name(), "docker.io/library/busybox");

        Ok(())
    }

    #[test]
    fn tag_and_digest() -> Result<(), InvalidImageError> {
        let mut image = Image::parse("quay.io/podman/hello:latest")?;
        assert_parts_eq(
            &image,
            Some("quay.io"),
            "quay.io/podman/hello",
            Some("latest"),
        );
        assert_eq!(image.as_tag().map(Tag::into_inner), Some("latest"));

        // Replace tag
        image.set_tag(Some(Tag::new("test")?));
        assert_parts_eq(
            &image,
            Some("quay.io"),
            "quay.io/podman/hello",
            Some("test"),
        );

        // Replace tag with digest
        let digest = "sha256:075975296016084fc66b59c35c9d4504765d95aadcd5469f28d2b75750348fc5";
        image.set_digest(Some(Digest::new(digest)?));
        assert_parts_eq(
            &image,
            Some("quay.io"),
            "quay.io/podman/hello",
            Some(digest),
        );
        assert_eq!(image.as_digest().map(Digest::into_inner), Some(digest));
        assert_eq!(image, format!("quay.io/podman/hello@{digest}").as_str());

        // Replace digest
        image.set_digest(Some(Digest::new("algo:data")?));
        assert_parts_eq(
            &image,
            Some("quay.io"),
            "quay.io/podman/hello",
            Some("algo:data"),
        );

        // Remove tag or digest
        image.set_tag_or_digest(None);
        assert_parts_eq(&image, Some("quay.io"), "quay.io/podman/hello", None);

        // Add tag back
        image.set_tag(Some(Tag::new("latest")?));
        assert_parts_eq(
            &image,
            Some("quay.io"),
            "quay.io/podman/hello",
            Some("latest"),
        );

        Ok(())
    }
}