mbed 0.1.3

Embed and transform assets into your Rust crate.
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
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
#![cfg_attr(docsrs, feature(doc_cfg))]

//! # mbed
//!
//! Embed and transform assets into your Rust crate.
//!
//! [`mbed`](crate) provides macros for turning files and generated outputs into [`Artifact`]
//! values. Artifacts carry their bytes, MIME type, and [`Id`], and can be grouped
//! into a [`Manifest`] for lookup by identifier.
//!
//! ## Basic usage
//!
//! Requires the `macros` feature.
//!
//! ```rust
//! # #[cfg(any())]
//! # fn __no_run() {
//! pub const LOGO: Artifact<[u8]> = mbed::include_bytes!["../assets/logo.svg"];
//! pub const INDEX: Artifact<str> = mbed::include_str!["../pages/index.html"];
//!
//! let id = LOGO.id();
//! assert_eq!(LOGO.mime(), "image/svg+xml");
//! # }
//! ```
//!
//! ## Collections and manifests
//!
//! `collect!` groups artifacts inside a module. `manifest!` can then reference
//! individual artifacts or whole collections with `::*`.
//!
//! Requires the `macros` feature.
//!
//! ```rust
//! # #[cfg(any())]
//! # fn __no_run() {
//! pub mod pages {
//!     pub const INDEX: Artifact<str> = mbed::include_str!["../pages/index.html"];
//!     pub const ABOUT: Artifact<str> = mbed::include_str!["../pages/about.html"];
//!
//!     mbed::collect![INDEX, ABOUT];
//! }
//!
//! pub mod images {
//!     pub const LOGO: Artifact<[u8]> = mbed::include_bytes!["../assets/logo.svg"];
//!
//!     mbed::collect![LOGO];
//! }
//!
//! pub const ASSETS: Manifest = mbed::manifest![pages::*, images::*];
//!
//! let artifact = ASSETS.get(pages::INDEX.id()).unwrap();
//! assert_eq!(artifact.mime(), pages::INDEX.mime());
//! # }
//! ```
//!
//! ## Images
//!
//! Requires the `image` feature.
//!
//! ```rust
//! # #[cfg(any())]
//! # fn __no_run() {
//! pub const LOGO: Artifact<Image> = mbed::image::include! {
//!     resize: Scale(0.5),
//!     path: "../assets/logo.png",
//!     format: WebP,
//! };
//!
//! assert_eq!(LOGO.format(), mbed::image::Format::WebP);
//! let bytes = LOGO.as_bytes();
//! # }
//! ```
//!
//! ## JavaScript bundles
//!
//! Requires the `bundle` feature.
//!
//! ```rust
//! # #[cfg(any())]
//! # fn __no_run() {
//! pub const APP: Artifact<Bundle> = mbed::js::bundle!["../frontend/app.js"];
//!
//! let code = APP.code();
//! let sourcemap = APP.sourcemap();
//! # }
//! ```
//!
//! ## Tailwind CSS
//!
//! Requires the `tailwindcss` feature.
//!
//! ```rust
//! # #[cfg(any())]
//! # fn __no_run() {
//! pub const STYLES: Artifact<str> = mbed::css::tailwindcss!("../tailwind.css");
//! # }
//! ```
//!
//! ## Feature flags
//!
//! - `macros` enables [`include_bytes!`], [`include_str!`], [`collect!`], and
//!   [`manifest!`].
//! - `image` enables [`image::include!`] and image metadata support.
//! - `bundle` enables [`js::bundle!`].
//! - `tailwindcss` enables [`css::tailwindcss!`].
//! - `serde` enables serialization support for public data types.
//! - `cargo-progress` shows bundling progress in Cargo build output. This feature
//!   is only supported on Linux.

use std::{iter::FusedIterator, ops::Deref, str::FromStr};

/// A collection of embedded artifacts indexed by [`Id`].
///
/// Manifests are usually generated with [`manifest!`]. They store artifacts as
/// byte artifacts, regardless of whether the original source artifact was bytes,
/// text, an image, or a JavaScript bundle.
///
/// # Examples
///
/// Requires the `macros` feature.
///
/// ```rust
/// # #[cfg(any())]
/// # fn __no_run() {
/// pub mod assets {
///     pub const ROBOTS: Artifact<str> = mbed::include_str!["../public/robots.txt"];
///     pub const FAVICON: Artifact<[u8]> = mbed::include_bytes!["../public/favicon.ico"];
///
///     mbed::collect![ROBOTS, FAVICON];
/// }
///
/// pub const MANIFEST: Manifest = mbed::manifest![assets::*];
///
/// let robots = MANIFEST.get(assets::ROBOTS.id()).unwrap();
/// assert_eq!(robots.as_bytes(), assets::ROBOTS.as_bytes());
/// # }
/// ```
#[derive(Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Manifest {
    artifacts: &'static [Artifact<[u8]>],
    buckets: &'static [Bucket],
}

impl std::fmt::Debug for Manifest {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("Manifest").field(&self.artifacts).finish()
    }
}

impl Manifest {
    /// Returns the artifact with the given [`Id`].
    ///
    /// Returns `None` when the id is not present in this manifest.
    #[inline]
    pub const fn get(&self, id: Id) -> Option<Artifact> {
        let bucket_index = id.bucket_index(self.buckets.len());

        match self.buckets[bucket_index].find(id) {
            Some(index) => Some(self.artifacts[index]),
            None => None,
        }
    }

    /// Returns all artifacts in this manifest.
    ///
    /// The order matches the order generated by [`manifest!`].
    #[inline]
    pub const fn artifacts(&self) -> &'static [Artifact] {
        self.artifacts
    }
}

impl IntoIterator for Manifest {
    type Item = Artifact;

    type IntoIter = Iter<[u8]>;

    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        Iter {
            artifacts: self.artifacts(),
            index: 0,
        }
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Manifest {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        <[_] as serde::Serialize>::serialize(self.artifacts(), serializer)
    }
}

/// An iterator over embedded artifacts.
#[derive(Debug, Clone)]
pub struct Iter<T>
where
    T: ?Sized + 'static,
{
    artifacts: &'static [Artifact<T>],
    index: usize,
}

impl<T> Iterator for Iter<T>
where
    T: ?Sized + 'static,
{
    type Item = Artifact<T>;

    #[inline]
    fn next(&mut self) -> Option<Self::Item> {
        if self.index < self.artifacts.len() {
            let artifact = self.artifacts[self.index];
            self.index += 1;
            Some(artifact)
        } else {
            None
        }
    }
}

impl<T> FusedIterator for Iter<T> where T: ?Sized + 'static {}

/// An embedded asset and its metadata.
///
/// `Artifact` values are produced by the crate's embedding macros. The default
/// artifact type is `Artifact<[u8]>`, but text artifacts use `Artifact<str>`,
/// image artifacts use `Artifact<image::Image>`, and JavaScript bundles use
/// `Artifact<js::Bundle>`.
///
/// Each artifact has:
///
/// - an [`Id`], generated from the artifact contents;
/// - a MIME type;
/// - a reference to the embedded value.
///
/// # Examples
///
/// Requires the `macros` feature.
///
/// ```rust
/// # #[cfg(any())]
/// # fn __no_run() {
/// pub const CONFIG: Artifact<str> = mbed::include_str!["../config/default.toml"];
///
/// let id = CONFIG.id();
/// let mime = CONFIG.mime();
/// let text = CONFIG.as_str();
/// # }
/// ```
#[derive(Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize))]
pub struct Artifact<T = [u8]>
where
    T: ?Sized + 'static,
{
    mime: &'static str,
    id: Id,
    value: &'static T,
}

impl<T> Clone for Artifact<T>
where
    T: ?Sized,
{
    #[inline]
    fn clone(&self) -> Self {
        *self
    }
}

impl<T> Copy for Artifact<T> where T: ?Sized {}

impl<T> Artifact<T>
where
    T: ?Sized,
{
    /// Returns this artifact's SHA-224 identifier.
    #[inline]
    pub const fn id(&self) -> Id {
        self.id
    }

    /// Returns this artifact's MIME type.
    #[inline]
    pub const fn mime(&self) -> &'static str {
        self.mime
    }
}

impl Artifact<[u8]> {
    /// Returns this artifact's embedded bytes.
    #[inline]
    pub const fn as_bytes(&self) -> &'static [u8] {
        self.value
    }

    #[doc(hidden)]
    #[inline]
    pub const fn __into_bytes_artifact(self) -> Artifact<[u8]> {
        self
    }
}

impl Artifact<str> {
    /// Returns this artifact's UTF-8 contents as bytes.
    #[inline]
    pub const fn as_bytes(&self) -> &'static [u8] {
        self.value.as_bytes()
    }

    /// Returns this artifact's UTF-8 contents.
    #[inline]
    pub const fn as_str(&self) -> &'static str {
        self.value
    }

    /// Converts this text artifact into a byte artifact.
    #[inline]
    pub const fn into_bytes_artifact(self) -> Artifact<[u8]> {
        Artifact {
            id: self.id,
            mime: self.mime,
            value: self.value.as_bytes(),
        }
    }

    #[doc(hidden)]
    #[inline]
    pub const fn __into_bytes_artifact(self) -> Artifact<[u8]> {
        self.into_bytes_artifact()
    }
}

impl AsRef<[u8]> for Artifact<[u8]> {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl AsRef<[u8]> for Artifact<str> {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl AsRef<str> for Artifact<str> {
    #[inline]
    fn as_ref(&self) -> &str {
        self.as_str()
    }
}

impl Deref for Artifact<[u8]> {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_bytes()
    }
}

impl Deref for Artifact<str> {
    type Target = str;

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_str()
    }
}

/// A SHA-224 artifact identifier.
///
/// `Id` is a 28-byte digest. Its [`Display`](std::fmt::Display)
/// representation is lowercase hexadecimal, and [`FromStr`] parses the same
/// representation.
///
/// # Examples
///
/// ```rust
/// # #[cfg(any())]
/// # fn __no_run() {
/// let id = mbed::Id::from_str(
///     "00000000000000000000000000000000000000000000000000000000",
/// ).unwrap();
///
/// assert_eq!(id.to_string().len(), 56);
/// assert_eq!(id.as_bytes().len(), 28);
/// # }
/// ```
#[derive(Default, Clone, Copy, Eq, PartialOrd, Ord, Hash)]
#[repr(transparent)]
#[allow(clippy::derived_hash_with_manual_eq)]
pub struct Id([u8; 28]);

impl std::fmt::Debug for Id {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_tuple("Id")
            .field(&const_hex::Buffer::<_, false>::new().const_format(self.as_bytes()))
            .finish()
    }
}

impl std::fmt::Display for Id {
    #[inline]
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(
            const_hex::Buffer::<_, false>::new()
                .const_format(self.as_bytes())
                .as_str(),
        )
    }
}

impl Id {
    /// The smallest possible identifier.
    pub const MIN: Self = Self([u8::MIN; _]);

    /// The largest possible identifier.
    pub const MAX: Self = Self([u8::MAX; _]);

    /// Compares two identifiers byte by byte.
    #[inline]
    pub const fn eq(&self, other: &Self) -> bool {
        let mut x = true;
        let mut i = 0;

        while i < self.0.len() {
            x = x && self.0[i] == other.0[i];
            i += 1;
        }

        x
    }

    /// Returns this identifier as a 28-byte array reference.
    #[inline]
    pub const fn as_bytes(&self) -> &[u8; 28] {
        &self.0
    }

    /// Returns this identifier as a 28-byte array.
    #[inline]
    pub const fn to_bytes(self) -> [u8; 28] {
        self.0
    }

    /// Creates an identifier from a 28-byte array.
    #[inline]
    pub const fn from_bytes(x: [u8; 28]) -> Self {
        Self(x)
    }

    #[inline]
    const fn bucket_index(&self, n: usize) -> usize {
        usize::from_ne_bytes(*self.0.first_chunk().unwrap()) & !(usize::MAX << n.ilog2())
    }
}

impl PartialEq for Id {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.eq(other)
    }
}

impl AsRef<[u8]> for Id {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl Deref for Id {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_bytes()
    }
}

impl FromStr for Id {
    type Err = const_hex::FromHexError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        const_hex::decode_to_array(s).map(Self::from_bytes)
    }
}

#[cfg(feature = "serde")]
impl serde::Serialize for Id {
    #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: serde::Serializer,
    {
        serializer.serialize_str(
            const_hex::Buffer::<_, false>::new()
                .const_format(self.as_bytes())
                .as_str(),
        )
    }
}

#[cfg(feature = "serde")]
impl<'de> serde::Deserialize<'de> for Id {
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: serde::Deserializer<'de>,
    {
        <&str as serde::Deserialize>::deserialize(deserializer)
            .and_then(|x| Self::from_str(x).map_err(<D::Error as serde::de::Error>::custom))
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[doc(hidden)]
#[repr(transparent)]
pub struct Bucket(&'static [Entry]);

impl Bucket {
    const fn find(&self, id: Id) -> Option<usize> {
        let mut i = 0;

        while i < self.0.len() {
            if self.0[i].id.eq(&id) {
                return Some(self.0[i].index as usize);
            }

            i += 1;
        }

        None
    }
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[doc(hidden)]
pub struct Entry {
    id: Id,
    index: u32,
}

/// Groups artifacts into a module-local collection.
///
/// `collect!` creates a hidden `__ARTIFACTS` item that can be consumed by
/// [`manifest!`] or by another `collect!` invocation using `module::*`.
///
/// This macro accepts artifact names and collection globs.
///
/// Requires the `macros` feature.
///
/// # Examples
///
/// ```rust
/// # #[cfg(any())]
/// # fn __no_run() {
/// pub mod icons {
///     pub const LOGO: Artifact<[u8]> = mbed::include_bytes!["../icons/logo.svg"];
///     pub const MENU: Artifact<[u8]> = mbed::include_bytes!["../icons/menu.svg"];
///
///     mbed::collect![LOGO, MENU];
/// }
///
/// pub mod pages {
///     pub const INDEX: Artifact<str> = mbed::include_str!["../pages/index.html"];
///
///     mbed::collect![INDEX];
/// }
///
/// pub mod public {
///     mbed::collect![super::icons::*, super::pages::*];
/// }
/// # }
/// ```
#[cfg(feature = "macros")]
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
#[macro_export]
macro_rules! collect {
    (@impl $($x:ident)::+ ::*) => {
        &$($x)::+ ::__ARTIFACTS
    };

    (@impl $($x:ident)::+) => {
        &[($($x)::+).__into_bytes_artifact()]
    };


    ($($($tt:tt)::+),* $(,)?) => {
        #[allow(unused)]
        #[doc(hidden)]
        pub const __ARTIFACTS: &'static [$crate::__macro::Artifact]
            = $crate::__macro::concat_slices!([$crate::__macro::Artifact]: $($crate::collect!(@impl $($tt)::+)),*);
    };
}

/// Builds a [`Manifest`] from artifacts and collections.
///
/// `manifest!` accepts the same input shape as [`collect!`]: artifact names and
/// module globs such as `assets::*`.
///
/// Requires the `macros` feature.
///
/// # Examples
///
/// ```rust
/// # #[cfg(any())]
/// # fn __no_run() {
/// pub mod assets {
///     pub const README: Artifact<str> = mbed::include_str!["../README.md"];
///     pub const LOGO: Artifact<[u8]> = mbed::include_bytes!["../assets/logo.svg"];
///
///     mbed::collect![README, LOGO];
/// }
///
/// pub const MANIFEST: Manifest = mbed::manifest![assets::*];
///
/// let artifact = MANIFEST.get(assets::README.id()).unwrap();
/// assert_eq!(artifact.mime(), assets::README.mime());
/// # }
/// ```
#[cfg(feature = "macros")]
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
#[macro_export]
macro_rules! manifest {
    ($($tt:tt)*) => {{
        $crate::collect!($($tt)*);

        const MANIFEST: $crate::__macro::Manifest = {
            const BUCKET_LEN: usize = 1 << __ARTIFACTS.len().ilog2() as usize;

            const ENTRIES_LEN: usize = {
                let mut entries_len = [0usize; BUCKET_LEN];
                let mut entries_max = 0;

                let mut i = 0;

                while i < __ARTIFACTS.len() {
                    let x = &mut entries_len
                        [$crate::__macro::bucket_index(&__ARTIFACTS[i].id(), BUCKET_LEN)];

                    *x += 1;

                    if *x > entries_max {
                        entries_max = *x;
                    }

                    i += 1;
                }

                entries_max
            };

            const BUCKETS_RAW: [([$crate::__macro::Entry; ENTRIES_LEN], usize); BUCKET_LEN] = {
                let mut buckets =
                    [([$crate::__macro::entry($crate::__macro::Id::MIN, 0); ENTRIES_LEN], 0usize); BUCKET_LEN];

                let mut i = 0;

                while i < __ARTIFACTS.len() {
                    let x =
                        &mut buckets[$crate::__macro::bucket_index(&__ARTIFACTS[i].id(), BUCKET_LEN)];

                    let k = x.1;

                    x.0[k] = $crate::__macro::entry(__ARTIFACTS[i].id(), i as u32);
                    x.1 += 1;

                    i += 1;
                }

                buckets
            };

            const BUCKETS: [$crate::__macro::Bucket; BUCKET_LEN] = {
                let mut buckets = [$crate::__macro::bucket(&[]); BUCKET_LEN];

                let mut i = 0;

                while i < BUCKET_LEN {
                    buckets[i] = $crate::__macro::bucket(BUCKETS_RAW[i].0.split_at(BUCKETS_RAW[i].1).0);
                    i += 1;
                }

                buckets
            };

            $crate::__macro::manifest(__ARTIFACTS, &BUCKETS)
        };

        MANIFEST
    }};
}

/// Embeds a file as an [`Artifact<[u8]>`].
///
/// This is the mbed equivalent of Rust's `include_bytes!`, with artifact
/// metadata attached.
///
/// Requires the `macros` feature.
///
/// # Examples
///
/// ```rust
/// # #[cfg(any())]
/// # fn __no_run() {
/// pub const LOGO: Artifact<[u8]> = mbed::include_bytes!["../assets/logo.svg"];
///
/// let bytes = LOGO.as_bytes();
/// let id = LOGO.id();
/// # }
/// ```
#[cfg(feature = "macros")]
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
pub use mbed_core::include_str;

/// Embeds a UTF-8 file as an [`Artifact<str>`].
///
/// This is the mbed equivalent of Rust's `include_str!`, with artifact metadata
/// attached.
///
/// Requires the `macros` feature.
///
/// # Examples
///
/// ```rust
/// # #[cfg(any())]
/// # fn __no_run() {
/// pub const TEMPLATE: Artifact<str> = mbed::include_str!["../templates/page.html"];
///
/// let text = TEMPLATE.as_str();
/// let bytes = TEMPLATE.as_bytes();
/// # }
/// ```
#[cfg(feature = "macros")]
#[cfg_attr(docsrs, doc(cfg(feature = "macros")))]
pub use mbed_core::include_bytes;

/// CSS asset support.
#[cfg(feature = "css")]
#[cfg_attr(docsrs, doc(cfg(feature = "css")))]
pub mod css {
    /// Compiles Tailwind CSS into an embedded text artifact.
    ///
    /// Requires the `tailwindcss` feature.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # #[cfg(any())]
    /// # fn __no_run() {
    /// pub const APP_CSS: Artifact<str> = mbed::css::tailwindcss!("../tailwind.css");
    ///
    /// let css = APP_CSS.as_str();
    /// # }
    /// ```
    #[cfg(feature = "tailwindcss")]
    #[cfg_attr(docsrs, doc(cfg(feature = "tailwindcss")))]
    pub use mbed_css::tailwindcss;
}

/// Image asset support.
///
/// Requires the `image` feature.
///
/// Optional image features:
///
/// - `image-avif` enables AVIF support and requires `libdav1d`.
/// - `image-asm` enables assembly optimizations and requires `nasm`.
#[cfg(feature = "image")]
#[cfg_attr(docsrs, doc(cfg(feature = "image")))]
pub mod image {
    use std::ops::Deref;

    use crate::Artifact;

    /// Embeds an image as an [`Artifact<Image>`].
    ///
    /// The embedded artifact includes the encoded image bytes, image dimensions,
    /// and detected output format.
    ///
    /// Requires the `image` feature.
    ///
    /// Optional image features:
    ///
    /// - `image-avif` enables AVIF support and requires `libdav1d`.
    /// - `image-asm` enables assembly optimizations and requires `nasm`.
    ///
    /// # Syntax
    ///
    /// ```rust
    /// # #[cfg(any())]
    /// # fn __no_run() {
    /// mbed::image::include! {
    ///     path: "../assets/logo.png",
    ///     format: WebP,
    ///     compression: Fast,
    ///     resize: Scale(0.75),
    /// }
    /// # }
    /// ```
    ///
    /// The macro accepts a braced list of named fields. The `path` field is
    /// required; all other fields are optional.
    ///
    /// ## Fields
    ///
    /// - `path`: Path to the source image file.
    /// - `format`: Output image format. If omitted, the original image format is
    ///   preserved.
    /// - `compression`: Best-effort hint for how the image should be re-encoded.
    /// - `resize`: Optional resize operation to apply before embedding.
    ///
    /// ## Supported formats
    ///
    /// `Png`, `Jpeg`, `Gif`, `WebP`, `Pnm`, `Tiff`, `Tga`, `Bmp`, `Ico`, `Hdr`,
    /// `OpenExr`, `Farbfeld`, `Avif`, and `Qoi`.
    ///
    /// AVIF support requires the `image-avif` feature.
    ///
    /// ## Supported compression modes
    ///
    /// `Fast`, `Best`, `Uncompressed`, and `Balanced`.
    ///
    /// Compression is a best-effort hint. Some formats may ignore it or only
    /// support a subset of compression behavior.
    ///
    /// ## Resize syntax
    ///
    /// Images can be resized by scale factor:
    ///
    /// ```rust
    /// # #[cfg(any())]
    /// # fn __no_run() {
    /// # __ {
    /// resize: Scale(0.75)
    /// # }}
    /// ```
    ///
    /// Or to exact dimensions:
    ///
    /// ```rust
    /// # #[cfg(any())]
    /// # fn __no_run() {
    /// # __ {
    /// resize: Exact {
    ///     width: 1024,
    ///     height: 1024,
    ///     keep_aspect_ratio: false,
    /// }
    /// # }}
    /// ```
    ///
    /// When `keep_aspect_ratio` is enabled, the image is resized to fit within the
    /// requested dimensions without changing its aspect ratio.
    ///
    /// # Examples
    ///
    /// Embed an image using its original format:
    ///
    /// ```rust
    /// # #[cfg(any())]
    /// # fn __no_run() {
    /// pub const LOGO: Artifact<Image> = mbed::image::include! {
    ///     path: "../assets/logo.png",
    /// };
    ///
    /// assert_eq!(LOGO.width(), 512);
    /// assert_eq!(LOGO.height(), 512);
    /// let bytes = LOGO.as_bytes();
    /// # }
    /// ```
    ///
    /// Re-encode, compress, and resize an image:
    ///
    /// ```rust
    /// # #[cfg(any())]
    /// # fn __no_run() {
    /// pub const LOGO_WEBP: Artifact<Image> = mbed::image::include! {
    ///     path: "../assets/logo.png",
    ///     format: WebP,
    ///     compression: Fast,
    ///     resize: Scale(0.75),
    /// };
    /// # }
    /// ```
    pub use mbed_image::include;

    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    pub struct Image {
        format: Format,
        width: u32,
        height: u32,
        bytes: &'static [u8],
    }

    impl Artifact<Image> {
        /// Returns the encoded image format.
        #[inline]
        pub const fn format(&self) -> Format {
            self.value.format
        }

        /// Returns the image width in pixels.
        #[inline]
        pub const fn width(&self) -> u32 {
            self.value.width
        }

        /// Returns the image height in pixels.
        #[inline]
        pub const fn height(&self) -> u32 {
            self.value.height
        }

        /// Returns the encoded image bytes.
        #[inline]
        pub const fn as_bytes(&self) -> &'static [u8] {
            self.value.bytes
        }

        #[doc(hidden)]
        #[inline]
        pub const fn __into_bytes_artifact(self) -> Artifact<[u8]> {
            Artifact {
                mime: self.mime(),
                id: self.id(),
                value: self.as_bytes(),
            }
        }
    }

    impl AsRef<[u8]> for Artifact<Image> {
        #[inline]
        fn as_ref(&self) -> &[u8] {
            self.as_bytes()
        }
    }

    impl Deref for Artifact<Image> {
        type Target = [u8];

        #[inline]
        fn deref(&self) -> &Self::Target {
            self.as_bytes()
        }
    }

    /// An encoded image format.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
    pub enum Format {
        /// PNG image data.
        Png,
        /// JPEG image data.
        Jpeg,
        /// GIF image data.
        Gif,
        /// WebP image data.
        WebP,
        /// PNM image data.
        Pnm,
        /// TIFF image data.
        Tiff,
        /// TGA image data.
        Tga,
        /// BMP image data.
        Bmp,
        /// ICO image data.
        Ico,
        /// Radiance HDR image data.
        Hdr,
        /// OpenEXR image data.
        OpenExr,
        /// Farbfeld image data.
        Farbfeld,
        /// AVIF image data.
        #[cfg(any(feature = "image-avif", doc, docsrs))]
        #[cfg_attr(docsrs, doc(cfg(feature = "image-avif")))]
        Avif,
        /// QOI image data.
        Qoi,
    }

    #[cfg(feature = "macros")]
    #[doc(hidden)]
    pub mod __macro {
        pub use super::{Format, Image};

        #[inline]
        pub const fn image(format: Format, width: u32, height: u32, bytes: &'static [u8]) -> Image {
            Image {
                format,
                width,
                height,
                bytes,
            }
        }
    }
}

/// JavaScript asset support.
#[cfg(feature = "js")]
#[cfg_attr(docsrs, doc(cfg(feature = "js")))]
pub mod js {
    use std::ops::Deref;

    use crate::Artifact;

    /// Bundles and minifies JavaScript into an embedded [`Artifact<Bundle>`].
    ///
    /// The embedded artifact includes the bundled JavaScript code and source map.
    ///
    /// Bundling and minification are performed using `oxc`.
    ///
    /// Requires the `bundle` feature.
    ///
    /// # Syntax
    ///
    /// The macro accepts either a single JavaScript file path:
    ///
    /// ```rust
    /// # #[cfg(any())]
    /// # fn __no_run() {
    /// mbed::js::bundle!("../frontend/app.js")
    /// # }
    /// ```
    ///
    /// Or a list of JavaScript file paths:
    ///
    /// ```rust
    /// # #[cfg(any())]
    /// # fn __no_run() {
    /// mbed::js::bundle![
    ///     "../frontend/vendor.js",
    ///     "../frontend/app.js",
    /// ]
    /// # }
    /// ```
    ///
    /// Paths are resolved relative to the source file containing the macro
    /// invocation.
    ///
    /// Only JavaScript files are currently supported. TypeScript files cannot be
    /// bundled by this macro at this time.
    ///
    /// # Examples
    ///
    /// Bundle a single JavaScript entry point:
    ///
    /// ```rust
    /// # #[cfg(any())]
    /// # fn __no_run() {
    /// pub const APP: Artifact<Bundle> = mbed::js::bundle!("../frontend/app.js");
    ///
    /// let code = APP.code();
    /// let sourcemap = APP.sourcemap();
    /// # }
    /// ```
    ///
    /// Bundle multiple JavaScript files:
    ///
    /// ```rust
    /// # #[cfg(any())]
    /// # fn __no_run() {
    /// pub const APP: Artifact<Bundle> = mbed::js::bundle![
    ///     "../frontend/vendor.js",
    ///     "../frontend/app.js",
    /// ];
    ///
    /// let code = APP.code();
    /// let sourcemap = APP.sourcemap();
    /// # }
    /// ```
    #[cfg(feature = "bundle")]
    #[cfg_attr(docsrs, doc(cfg(feature = "bundle")))]
    pub use mbed_js::bundle;

    /// Embedded JavaScript bundle output.
    ///
    /// A bundle contains generated JavaScript code and its source map.
    #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
    #[cfg_attr(feature = "serde", derive(serde::Serialize))]
    pub struct Bundle {
        code: &'static str,
        sourcemap: &'static str,
    }

    impl Artifact<Bundle> {
        /// Returns the bundle code as UTF-8 bytes.
        #[inline]
        pub const fn as_bytes(&self) -> &'static [u8] {
            self.as_str().as_bytes()
        }

        /// Returns the bundle code.
        #[inline]
        pub const fn as_str(&self) -> &'static str {
            self.code()
        }

        /// Returns the generated JavaScript code.
        #[inline]
        pub const fn code(&self) -> &'static str {
            self.value.code
        }

        /// Returns the generated source map.
        #[inline]
        pub const fn sourcemap(&self) -> &'static str {
            self.value.sourcemap
        }

        #[doc(hidden)]
        #[inline]
        pub const fn __into_bytes_artifact(self) -> Artifact<[u8]> {
            Artifact {
                mime: self.mime(),
                id: self.id(),
                value: self.code().as_bytes(),
            }
        }
    }

    impl AsRef<[u8]> for Artifact<Bundle> {
        #[inline]
        fn as_ref(&self) -> &[u8] {
            self.as_bytes()
        }
    }

    impl AsRef<str> for Artifact<Bundle> {
        #[inline]
        fn as_ref(&self) -> &str {
            self.as_str()
        }
    }

    impl Deref for Artifact<Bundle> {
        type Target = str;

        #[inline]
        fn deref(&self) -> &Self::Target {
            self.as_str()
        }
    }

    #[cfg(feature = "macros")]
    #[doc(hidden)]
    pub mod __macro {
        pub use super::Bundle;

        #[inline]
        pub const fn bundle(code: &'static str, sourcemap: &'static str) -> Bundle {
            Bundle { code, sourcemap }
        }
    }
}

#[cfg(feature = "macros")]
#[doc(hidden)]
pub mod __macro {
    pub use crate::{Artifact, Bucket, Entry, Id, Manifest};
    pub use constcat::concat_slices;

    #[inline]
    pub const fn manifest(
        artifacts: &'static [Artifact<[u8]>],
        buckets: &'static [Bucket],
    ) -> Manifest {
        Manifest { artifacts, buckets }
    }

    #[inline]
    pub const fn artifact<T>(mime: &'static str, id: Id, value: &'static T) -> Artifact<T>
    where
        T: ?Sized + 'static,
    {
        Artifact { mime, id, value }
    }

    #[inline]
    pub const fn bucket(x: &'static [Entry]) -> Bucket {
        Bucket(x)
    }

    #[inline]
    pub const fn entry(id: Id, index: u32) -> Entry {
        Entry { id, index }
    }

    #[inline]
    pub const fn bucket_index(x: &Id, n: usize) -> usize {
        x.bucket_index(n)
    }
}