qubit-metadata 0.7.1

Type-safe metadata model with schemas and composable filters
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
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
// =============================================================================
//    Copyright (c) 2025 - 2026 Haixing Hu.
//
//    SPDX-License-Identifier: Apache-2.0
//
//    Licensed under the Apache License, Version 2.0.
// =============================================================================
//! Provides the [`Metadata`] type — a structured, key-sorted, typed key-value
//! store.

#[cfg(feature = "json")]
use std::cell::RefCell;
use std::collections::BTreeMap;
use std::fmt;
#[cfg(feature = "json")]
use std::io::Write;
#[cfg(feature = "json")]
use std::rc::Rc;

#[cfg(feature = "json")]
use qubit_budget::json::JsonDecodeSession;
#[cfg(feature = "json")]
use qubit_budget::json::JsonEncodeLimits;
#[cfg(feature = "json")]
use qubit_budget::json::JsonEncodeSession;
use qubit_datatype::ConversionLimits;
use qubit_datatype::ConversionPolicy;
use qubit_datatype::DataConversionTarget;
use qubit_datatype::DataType;
#[cfg(feature = "json")]
use qubit_json::decode::JsonDecoder;
#[cfg(feature = "json")]
use qubit_json::encode::JsonEncoder;
use qubit_redact::Redact;
use qubit_redact::RedactionWriter;
use qubit_redact::Redactor;
use qubit_value::IntoValueDefault;
use qubit_value::StrictValueRead;
use qubit_value::Value;
use qubit_value::ValueError;
#[cfg(feature = "json")]
use qubit_value::ValueWireEncodePreflight;
use qubit_value::ValueWirePayloadV1;
use qubit_value::ValueWirePayloadV1Seed;
use serde::Deserialize;
use serde::Deserializer;
use serde::Serialize;
use serde::Serializer;
use serde::de;
use serde::de::DeserializeSeed;
#[cfg(feature = "json")]
use serde::de::Error as DeError;
use serde::ser::Error as SerError;

use crate::MetadataError;
use crate::MetadataResult;
#[cfg(feature = "schema")]
use crate::MetadataSchema;
use crate::constants::STRICT_STRING_MAP_MAX_ENTRIES;
use crate::constants::STRICT_STRING_MAP_MAX_KEY_BYTES;
use crate::internal::MetadataValues;
#[cfg(feature = "json")]
use crate::metadata_limits::MetadataLimits;
use crate::wire::METADATA_WIRE_VERSION_V1;
use crate::wire::MetadataWireV1;
use crate::wire::MetadataWireV1Seed;
use crate::wire::MetadataWireValuesRef;
use crate::wire::StrictStringMap;
use crate::wire::StrictStringMapValueSeed;

/// A structured, key-sorted, typed key-value store for metadata fields.
///
/// `Metadata` stores values as [`qubit_value::Value`], preserving concrete Rust
/// scalar types such as `i64`, `u32`, `f64`, `String`, and `bool`.  This avoids
/// the ambiguity of a single JSON number type while still allowing callers to
/// store explicit `Value::Json` values when they really need JSON payloads.
/// [`Value::Unset`] retains a declared type but represents no concrete metadata
/// value: typed reads report [`MetadataError::ValueAccess`]. When the optional
/// `schema` or `filter` features are enabled, their validation and matching
/// APIs treat it as a missing concrete value.
///
/// Use [`Metadata::with`] for fluent construction and [`Metadata::set`] when
/// mutating an existing object. The typed [`Metadata::get`] and
/// [`Metadata::get_ref`] accessors read strictly; [`Metadata::convert`]
/// explicitly converts stored values. Use [`Metadata::get_raw`] when
/// the stored runtime [`qubit_value::Value`] must be inspected without
/// conversion.
///
/// # Examples
///
/// ```
/// use qubit_metadata::Metadata;
///
/// # fn main() -> qubit_metadata::MetadataResult<()> {
/// let metadata = Metadata::new().with("tenant", "acme");
/// assert_eq!(metadata.get_ref::<str>("tenant")?, "acme");
/// # Ok(())
/// # }
/// ```
#[derive(Clone, PartialEq, Default)]
pub struct Metadata(
    /// Stored values indexed by metadata key.
    BTreeMap<String, Value>,
);

impl Metadata {
    /// Creates an empty metadata object.
    ///
    /// # Returns
    ///
    /// An empty metadata object.
    #[inline]
    #[must_use]
    pub fn new() -> Self {
        Self(BTreeMap::new())
    }

    /// Checks the metadata wire contract and all values against JSON limits.
    ///
    /// # Parameters
    ///
    /// * `limits` - Output and JSON-value budgets for this operation.
    ///
    /// # Returns
    ///
    /// `Ok(())` when the wire contract and every value pass preflight.
    ///
    /// # Errors
    ///
    /// Returns the wire-contract error before checking JSON value budgets.
    /// Values are checked in key order with one shared preflight, so value
    /// budgets accumulate across all metadata values.
    #[cfg(feature = "json")]
    fn preflight_json_encoding(&self, limits: JsonEncodeLimits) -> Result<(), crate::MetadataWireEncodeError> {
        self.validate_wire_contract()
            .map_err(crate::MetadataWireEncodeError::Domain)?;
        let mut preflight = ValueWireEncodePreflight::new_value_limits(*limits.value_limits());
        for value in self.0.values() {
            preflight
                .check_value(value)
                .map_err(crate::MetadataWireEncodeError::from)?;
        }
        Ok(())
    }

    /// Decodes a strict metadata JSON envelope using the metadata profile.
    ///
    /// # Parameters
    ///
    /// * `input` - Complete untrusted JSON input.
    ///
    /// # Returns
    ///
    /// The decoded metadata object.
    ///
    /// # Errors
    ///
    /// Returns [`crate::MetadataWireDecodeError::Budget`] or
    /// [`crate::MetadataWireDecodeError::Quantity`] when shared JSON traversal
    /// exceeds a configured limit, [`crate::MetadataWireDecodeError::Syntax`]
    /// for empty input or lexical JSON errors, and
    /// [`crate::MetadataWireDecodeError::Decode`] for shared decoder failures
    /// such as invalid UTF-8, unexpected top-level types, or deserialization
    /// failures. Domain limits return
    /// [`crate::MetadataWireDecodeError::Domain`]; invalid metadata
    /// limit configuration returns
    /// [`crate::MetadataWireDecodeError::InvalidLimits`]; unsupported
    /// versions return
    /// [`crate::MetadataWireDecodeError::UnsupportedVersion`]. A metadata
    /// value conversion failure after wire materialization returns
    /// [`crate::MetadataWireDecodeError::InvalidJson`]; such a failure may no
    /// longer have source coordinates.
    #[cfg(feature = "json")]
    #[inline]
    pub fn decode_json_slice(input: &[u8]) -> Result<Self, crate::MetadataWireDecodeError> {
        Self::decode_json_slice_with_limits(input, MetadataLimits::default())
    }

    /// Decodes a strict metadata JSON envelope after applying `limits`.
    ///
    /// # Parameters
    ///
    /// * `input` - Complete untrusted JSON input.
    /// * `limits` - Shared JSON limits for this decoding session.
    ///
    /// # Returns
    ///
    /// The decoded metadata object.
    ///
    /// # Errors
    ///
    /// Returns `Budget` or `Quantity` when shared JSON traversal exceeds a
    /// configured limit, `Domain` for entry/key limits, `UnsupportedVersion`
    /// for a version mismatch, and `InvalidLimits` for invalid metadata limits.
    /// Empty input and lexical JSON errors return `Syntax`; shared decoder
    /// failures such as invalid UTF-8, unexpected top-level types, or
    /// deserialization failures return `Decode`. A metadata value conversion
    /// failure after wire materialization returns `InvalidJson` and may no
    /// longer have source coordinates.
    #[cfg(feature = "json")]
    pub fn decode_json_slice_with_limits(
        input: &[u8],
        limits: MetadataLimits,
    ) -> Result<Self, crate::MetadataWireDecodeError> {
        limits
            .validate()
            .map_err(crate::MetadataWireDecodeError::InvalidLimits)?;
        let mut decoder = JsonDecoder::new(JsonDecodeSession::from_limits(limits.json_decode()));
        let error_slot = Rc::new(RefCell::new(None));
        let wire = decoder
            .decode_unique_seed_utf8(
                MetadataWireV1Seed::new(
                    StrictStringMapValueSeed::new(
                        limits.max_metadata_entries(),
                        limits.max_key_bytes(),
                        ValueWirePayloadV1Seed::new(),
                    )
                    .with_error_slot(Rc::clone(&error_slot)),
                ),
                input,
            )
            .map_err(|error| {
                error_slot.borrow_mut().take().map_or_else(
                    || Into::<crate::MetadataWireDecodeError>::into(error),
                    crate::MetadataWireDecodeError::Domain,
                )
            })?;
        if wire.version != METADATA_WIRE_VERSION_V1 {
            return Err(crate::MetadataWireDecodeError::UnsupportedVersion {
                expected: METADATA_WIRE_VERSION_V1,
                actual: wire.version,
            });
        }
        let metadata = Self(Self::from_wire(wire).map_err(|error| {
            crate::MetadataWireDecodeError::InvalidJson(<serde_json::Error as DeError>::custom(error))
        })?);
        Ok(metadata)
    }

    /// Encodes this metadata object with the default JSON budget profile.
    ///
    /// # Returns
    ///
    /// Compact JSON bytes accepted by the strict metadata wire format.
    ///
    /// # Errors
    ///
    /// Returns [`crate::MetadataWireEncodeError`] when the JSON value or
    /// metadata wire contract rejects the value, output exceeds a configured
    /// budget, serialization fails, or the destination writer rejects bytes.
    /// Wire-contract failures preserve their
    /// [`MetadataError::WireLimitExceeded`] source in the `Domain` variant.
    #[cfg(feature = "json")]
    pub fn to_json_vec(&self) -> Result<Vec<u8>, crate::MetadataWireEncodeError> {
        self.to_json_vec_with_limits(crate::metadata_limits::default_json_encode_limits())
    }

    /// Encodes this metadata object with caller-provided JSON budgets.
    ///
    /// # Parameters
    ///
    /// * `limits` - Output and JSON-value budgets for this operation.
    ///
    /// # Returns
    ///
    /// Compact JSON bytes accepted by the strict metadata wire format.
    ///
    /// # Errors
    ///
    /// Returns [`crate::MetadataWireEncodeError`] when the metadata wire
    /// contract rejects the value, the JSON value or output exceeds a
    /// configured budget, or serialization fails. Wire-contract failures
    /// preserve their [`MetadataError::WireLimitExceeded`] source in the
    /// `Domain` variant. The outer metadata wire contract is checked before
    /// value budgets.
    #[cfg(feature = "json")]
    pub fn to_json_vec_with_limits(&self, limits: JsonEncodeLimits) -> Result<Vec<u8>, crate::MetadataWireEncodeError> {
        self.preflight_json_encoding(limits)?;
        let session = JsonEncodeSession::from_limits(limits);
        JsonEncoder::new(session).to_vec(self).map_err(Into::into)
    }

    /// Validates that this metadata object can be encoded within
    /// caller-provided JSON budgets.
    ///
    /// This performs the same wire-contract, value-preflight, serialization,
    /// and output-budget checks as [`Self::to_json_vec_with_limits`]
    /// without retaining the encoded JSON bytes. Use it when validating
    /// metadata before another operation encodes it.
    ///
    /// # Parameters
    ///
    /// * `limits` - Output and JSON-value budgets for this operation.
    ///
    /// # Returns
    ///
    /// `Ok(())` when the metadata can be encoded within the supplied budgets.
    ///
    /// # Errors
    ///
    /// Returns [`crate::MetadataWireEncodeError`] with the same structured
    /// error categories and validation ordering as
    /// [`Self::to_json_vec_with_limits`]. The metadata V1 wire contract
    /// is checked before JSON value budgets; output byte limits apply to
    /// compact encoded JSON.
    #[cfg(feature = "json")]
    #[inline]
    pub fn validate_json_with_limits(&self, limits: JsonEncodeLimits) -> Result<(), crate::MetadataWireEncodeError> {
        self.preflight_json_encoding(limits)?;
        JsonEncoder::new(JsonEncodeSession::from_limits(limits))
            .write_incremental(&mut std::io::sink(), self)
            .map_err(Into::into)
    }

    /// Encodes this metadata object to a writer with the default JSON budget
    /// profile ([`crate::default_json_encode_limits`]).
    ///
    /// # Parameters
    ///
    /// * `writer` - Destination receiving the complete compact JSON document.
    ///
    /// The complete compact JSON document is buffered and validated before
    /// the first write to `writer`. A budget or serialization failure leaves
    /// the destination untouched by this operation. A destination I/O error
    /// may leave a written prefix; this method does not provide atomic writes
    /// or rollback. Applications own persistence and retry semantics.
    ///
    /// Output budgets use the default encoding profile. Decode limits do not
    /// affect them; use [`Self::to_json_writer_with_limits`] to provide
    /// explicit output budgets.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the buffered document is written successfully.
    ///
    /// # Errors
    ///
    /// Returns [`crate::MetadataWireEncodeError`] when the metadata wire
    /// contract rejects the value, encoding exceeds a budget, serialization
    /// fails, or `writer` rejects the output. Wire-contract failures
    /// preserve their [`MetadataError::WireLimitExceeded`] source in the
    /// `Domain` variant. The outer metadata wire contract is checked before
    /// value budgets.
    ///
    /// # Type Parameters
    ///
    /// * `W` - Writer that receives the encoded document.
    #[cfg(feature = "json")]
    pub fn to_json_writer<W>(&self, writer: W) -> Result<(), crate::MetadataWireEncodeError>
    where
        W: Write,
    {
        self.to_json_writer_with_limits(writer, crate::metadata_limits::default_json_encode_limits())
    }

    /// Encodes this metadata object to a writer with caller-provided budgets.
    ///
    /// # Parameters
    ///
    /// * `writer` - Destination receiving the complete compact JSON document.
    /// * `limits` - Explicit output and JSON-value budgets for this operation.
    ///
    /// The complete compact JSON document is buffered and validated before
    /// the first write to `writer`. A budget or serialization failure leaves
    /// the destination untouched by this operation. A destination I/O error
    /// may leave a written prefix; this method does not provide atomic writes
    /// or rollback. Applications own persistence and retry semantics. Output
    /// budgets come only from the explicitly supplied `limits`; decode limits
    /// do not affect them.
    ///
    /// # Returns
    ///
    /// `Ok(())` after the buffered document is written successfully.
    ///
    /// # Errors
    ///
    /// Returns [`crate::MetadataWireEncodeError`] when the metadata wire
    /// contract rejects the value, encoding exceeds a budget, serialization
    /// fails, or `writer` rejects the output. Wire-contract failures
    /// preserve their [`MetadataError::WireLimitExceeded`] source in the
    /// `Domain` variant.
    ///
    /// # Type Parameters
    ///
    /// * `W` - Writer that receives the encoded document.
    #[cfg(feature = "json")]
    pub fn to_json_writer_with_limits<W>(
        &self,
        mut writer: W,
        limits: JsonEncodeLimits,
    ) -> Result<(), crate::MetadataWireEncodeError>
    where
        W: Write,
    {
        self.preflight_json_encoding(limits)?;
        let session = JsonEncodeSession::from_limits(limits);
        JsonEncoder::new(session)
            .write_buffered(&mut writer, self)
            .map_err(Into::into)
    }

    /// Returns `true` if there are no entries.
    ///
    /// # Returns
    ///
    /// `true` when this object contains no entries.
    #[inline]
    #[must_use]
    pub fn is_empty(&self) -> bool {
        self.0.is_empty()
    }

    /// Returns the number of key-value pairs.
    ///
    /// # Returns
    ///
    /// The number of stored entries.
    #[inline]
    #[must_use]
    pub fn len(&self) -> usize {
        self.0.len()
    }

    /// Returns `true` if the given key exists, including when it stores
    /// [`Value::Unset`].
    ///
    /// # Parameters
    ///
    /// * `key` - Metadata key to inspect.
    ///
    /// # Returns
    ///
    /// `true` when an entry exists for `key`.
    #[inline]
    #[must_use]
    pub fn contains_key(&self, key: &str) -> bool {
        self.0.contains_key(key)
    }

    /// Strictly reads `key` as `T` without coercing the stored runtime type.
    /// Use [`Self::convert`] when the stored value must be explicitly
    /// converted.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The requested type, which must support strict value reads.
    ///
    /// # Parameters
    ///
    /// * `key` - The metadata key to read.
    ///
    /// # Returns
    ///
    /// The owned value read as `T`.
    ///
    /// # Errors
    ///
    /// Returns [`MetadataError::MissingKey`] when `key` is absent, or
    /// [`MetadataError::ValueAccess`] when the stored value is unset or its
    /// runtime type does not match `T`. The value access error preserves the
    /// underlying type and unset details.
    ///
    /// # Examples
    ///
    /// ```
    /// use qubit_metadata::Metadata;
    /// use qubit_metadata::MetadataError;
    ///
    /// let metadata = Metadata::new().with("port", "8080");
    /// assert!(matches!(metadata.get::<u16>("port"),
    ///     Err(MetadataError::ValueAccess { .. })));
    /// assert_eq!(metadata.convert::<u16>("port").unwrap(), 8080);
    /// assert_eq!(metadata.get_ref::<str>("port").unwrap(), "8080");
    /// ```
    pub fn get<T: StrictValueRead>(&self, key: &str) -> MetadataResult<T> {
        T::read_scalar(self.entry(key)?).map_err(|source| Self::map_access_error(key, source))
    }

    /// Borrows the concrete payload under `key` without copying it.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The borrowed payload type. Its reference conversion must accept
    ///   a borrow of the stored value.
    ///
    /// # Parameters
    ///
    /// * `key` - The metadata key to read.
    ///
    /// # Returns
    ///
    /// A reference to the payload. Its lifetime is tied to the borrow of
    /// `self`, not to `key`.
    ///
    /// # Errors
    ///
    /// Returns [`MetadataError::MissingKey`] when `key` is absent, or
    /// [`MetadataError::ValueAccess`] when the stored value is unset or cannot
    /// be borrowed as `T`.
    pub fn get_ref<'a, T: ?Sized>(&'a self, key: &str) -> MetadataResult<&'a T>
    where
        &'a T: TryFrom<&'a Value, Error = ValueError>,
    {
        self.entry(key)?
            .get_ref::<T>()
            .map_err(|source| Self::map_access_error(key, source))
    }

    /// Strictly reads `key`, returning `None` only for an absent key or unset
    /// storage declared as `T`.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The requested type, which must support strict value reads.
    ///
    /// # Parameters
    ///
    /// * `key` - The metadata key to read.
    ///
    /// # Returns
    ///
    /// `Some(value)` when a concrete value is read as `T`; `None` when the key
    /// is absent or stores an unset value declared as `T`.
    ///
    /// # Errors
    ///
    /// Returns [`MetadataError::ValueAccess`] when the stored concrete value
    /// has a different runtime type, or when unset storage is declared as a
    /// different type than `T`.
    ///
    /// # Examples
    ///
    /// ```
    /// use qubit_datatype::DataType;
    /// use qubit_metadata::Metadata;
    /// use qubit_value::Value;
    ///
    /// let metadata = Metadata::new().with("count", Value::Unset(DataType::Int64));
    /// assert_eq!(metadata.get_optional::<i64>("absent").unwrap(), None);
    /// assert_eq!(metadata.get_optional::<i64>("count").unwrap(), None);
    /// assert!(metadata.get_optional::<i32>("count").is_err());
    /// ```
    pub fn get_optional<T: StrictValueRead>(&self, key: &str) -> MetadataResult<Option<T>> {
        match self.get(key) {
            Ok(value) => Ok(Some(value)),
            Err(error) if Self::is_defaultable(&error, false) => Ok(None),
            Err(error) => Err(error),
        }
    }

    /// Strictly reads `key`, adapting `default` only for an absent key or
    /// unset storage declared as `T`.
    ///
    /// The default adapter is invoked only when this read permits fallback.
    /// Rust still evaluates the argument expression before calling this method.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The requested type, which must support strict value reads.
    ///
    /// # Parameters
    ///
    /// * `key` - The metadata key to read.
    /// * `default` - A value or adapter that can provide a default `T`.
    ///
    /// # Returns
    ///
    /// The stored value read as `T`, or the adapted default when the key is
    /// absent or contains matching unset storage.
    ///
    /// # Errors
    ///
    /// Returns [`MetadataError::ValueAccess`] for a type mismatch, including
    /// unset storage declared as a different type. Such errors are propagated
    /// without using the default.
    ///
    /// # Examples
    ///
    /// ```
    /// use qubit_datatype::DataType;
    /// use qubit_metadata::Metadata;
    /// use qubit_value::Value;
    ///
    /// let metadata = Metadata::new()
    ///     .with("count", Value::Unset(DataType::Int64))
    ///     .with("text", "invalid");
    /// assert_eq!(metadata.get_or::<i64>("count", 7_i64).unwrap(), 7);
    /// assert_eq!(metadata.get_or::<i64>("absent", 7_i64).unwrap(), 7);
    /// assert!(metadata.get_or::<i64>("text", 7_i64).is_err());
    /// ```
    pub fn get_or<T: StrictValueRead>(&self, key: &str, default: impl IntoValueDefault<T>) -> MetadataResult<T> {
        self.get_optional(key)
            .map(|value| value.unwrap_or_else(|| default.into_value_default()))
    }

    /// Converts the stored value under `key` to `T` using the default
    /// conversion policy and limits. For strict reads, see [`Self::get`].
    ///
    /// # Type Parameters
    ///
    /// * `T` - The conversion target type.
    ///
    /// # Parameters
    ///
    /// * `key` - The metadata key to convert.
    ///
    /// # Returns
    ///
    /// The stored value converted to `T`.
    ///
    /// # Errors
    ///
    /// Returns [`MetadataError::MissingKey`] when `key` is absent, or
    /// [`MetadataError::ValueAccess`] when conversion fails. The latter retains
    /// the underlying missing, invalid, unsupported, precision-loss, or
    /// resource-limit error and its source chain.
    pub fn convert<T: DataConversionTarget>(&self, key: &str) -> MetadataResult<T> {
        self.convert_with(key, ConversionPolicy::default_ref(), ConversionLimits::default_ref())
    }

    /// Converts the stored value under `key` to `T` with an explicit
    /// [`ConversionPolicy`] and [`ConversionLimits`]. Each call has an
    /// independent conversion budget and leaves the stored value unchanged.
    /// For default policy and limits, see [`Self::convert`].
    ///
    /// # Type Parameters
    ///
    /// * `T` - The conversion target type.
    ///
    /// # Parameters
    ///
    /// * `key` - The metadata key to convert.
    /// * `policy` - The policy controlling which conversions are allowed.
    /// * `limits` - The per-call resource limits and budget.
    ///
    /// # Returns
    ///
    /// The stored value converted to `T`.
    ///
    /// # Errors
    ///
    /// Returns [`MetadataError::MissingKey`] when `key` is absent, or
    /// [`MetadataError::ValueAccess`] when conversion fails. The latter
    /// preserves the underlying conversion facts and any exceeded limits.
    pub fn convert_with<T: DataConversionTarget>(
        &self,
        key: &str,
        policy: &ConversionPolicy,
        limits: &ConversionLimits,
    ) -> MetadataResult<T> {
        self.entry(key)?
            .to_with(policy, limits)
            .map_err(|source| Self::map_access_error(key, source))
    }

    /// Converts the value under `key`, returning `None` for an absent key,
    /// unset storage, or a scalar classified as missing by `policy`.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The conversion target type.
    ///
    /// # Parameters
    ///
    /// * `key` - The metadata key to convert.
    /// * `policy` - The policy controlling conversion and missing-value
    ///   handling.
    /// * `limits` - The per-call resource limits and budget.
    ///
    /// # Returns
    ///
    /// `Some(value)` when conversion succeeds; `None` for an absent key, unset
    /// storage, or a policy-missing scalar.
    ///
    /// # Errors
    ///
    /// Propagates all other errors as [`MetadataError::ValueAccess`], retaining
    /// the key and the underlying conversion error. See [`Self::convert_with`]
    /// for explicit policy and budget behavior.
    pub fn convert_optional_with<T: DataConversionTarget>(
        &self,
        key: &str,
        policy: &ConversionPolicy,
        limits: &ConversionLimits,
    ) -> MetadataResult<Option<T>> {
        match self.convert_with(key, policy, limits) {
            Ok(value) => Ok(Some(value)),
            Err(error) if Self::is_defaultable(&error, true) => Ok(None),
            Err(error) => Err(error),
        }
    }

    /// Converts the value under `key`, adapting `default` only when the result
    /// is a defaultable missing value. See [`Self::convert_optional_with`] for
    /// the conditions that produce `None`.
    ///
    /// The default adapter is invoked only when this conversion permits
    /// fallback. Rust still evaluates the argument expression before calling
    /// this method.
    ///
    /// # Type Parameters
    ///
    /// * `T` - The conversion target type.
    ///
    /// # Parameters
    ///
    /// * `key` - The metadata key to convert.
    /// * `default` - A value or adapter that can provide a default `T`.
    /// * `policy` - The policy controlling conversion and missing-value
    ///   handling.
    /// * `limits` - The per-call resource limits and budget.
    ///
    /// # Returns
    ///
    /// The converted value, or the adapted default when the conversion result
    /// is a defaultable missing value.
    ///
    /// # Errors
    ///
    /// Errors other than defaultable missing values propagate as
    /// [`MetadataError::ValueAccess`]. Invalid values, unsupported conversions,
    /// precision loss, and resource-limit errors never use the default.
    pub fn convert_or_with<T: DataConversionTarget>(
        &self,
        key: &str,
        default: impl IntoValueDefault<T>,
        policy: &ConversionPolicy,
        limits: &ConversionLimits,
    ) -> MetadataResult<T> {
        self.convert_optional_with(key, policy, limits)
            .map(|value| value.unwrap_or_else(|| default.into_value_default()))
    }

    /// Returns a reference to the stored [`Value`] for `key`, or `None` if
    /// absent.
    ///
    /// # Parameters
    ///
    /// * `key` - Metadata key to retrieve.
    ///
    /// # Returns
    ///
    /// The stored value, or `None` when `key` is absent.
    #[inline]
    pub fn get_raw(&self, key: &str) -> Option<&Value> {
        self.0.get(key)
    }

    /// Returns the concrete data type of the value stored under `key`.
    ///
    /// # Parameters
    ///
    /// * `key` - Metadata key to inspect.
    ///
    /// # Returns
    ///
    /// The stored value's data type, or `None` when `key` is absent.
    #[inline]
    pub fn data_type(&self, key: &str) -> Option<DataType> {
        self.0.get(key).map(Value::data_type)
    }

    /// Inserts a typed value and returns the previous value.
    ///
    /// # Parameters
    ///
    /// * `key` - Metadata key to replace.
    /// * `value` - Typed value to store.
    ///
    /// # Returns
    ///
    /// The previous value when the key was already present, or `None`.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Input type convertible into a stored [`Value`].
    #[inline]
    pub fn insert<T>(&mut self, key: &str, value: T) -> Option<Value>
    where
        T: Into<Value>,
    {
        self.0.insert(key.to_string(), value.into())
    }

    /// Sets a typed value and returns this metadata object for chaining.
    ///
    /// # Parameters
    ///
    /// * `key` - Metadata key to replace.
    /// * `value` - Typed value to store.
    ///
    /// # Returns
    ///
    /// A mutable reference to this metadata object.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Input type convertible into a stored [`Value`].
    #[inline]
    pub fn set<T>(&mut self, key: &str, value: T) -> &mut Self
    where
        T: Into<Value>,
    {
        let _ = self.insert(key, value);
        self
    }

    /// Returns a new metadata object with `key` set to `value`.
    ///
    /// # Parameters
    ///
    /// * `key` - Metadata key to replace.
    /// * `value` - Typed value to store.
    ///
    /// # Returns
    ///
    /// This metadata object after inserting the value.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Input type convertible into a stored [`Value`].
    #[inline]
    #[must_use]
    pub fn with<T>(mut self, key: &str, value: T) -> Self
    where
        T: Into<Value>,
    {
        self.set(key, value);
        self
    }

    /// Inserts a typed value after validating it against `schema` and returns
    /// the previous value.
    ///
    /// # Parameters
    ///
    /// * `schema` - Schema used to validate the entry.
    /// * `key` - Metadata key to replace.
    /// * `value` - Typed value to validate and store.
    ///
    /// # Returns
    ///
    /// The previous value when the key was already present, or `None`.
    ///
    /// # Errors
    ///
    /// Returns [`MetadataError::UnknownField`] when `key` is rejected by the
    /// schema, [`MetadataError::MissingRequiredField`] when a required field is
    /// assigned [`Value::Unset`], or [`MetadataError::TypeMismatch`] when the
    /// constructed value's concrete type does not match the schema field type.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Input type convertible into a stored [`Value`].
    #[cfg(feature = "schema")]
    #[inline]
    pub fn insert_checked<T>(&mut self, schema: &MetadataSchema, key: &str, value: T) -> MetadataResult<Option<Value>>
    where
        T: Into<Value>,
    {
        let value = value.into();
        schema.validate_entry(key, &value)?;
        Ok(self.insert(key, value))
    }

    /// Sets a typed value after schema validation and returns this metadata
    /// object for chaining.
    ///
    /// # Parameters
    ///
    /// * `schema` - Schema used to validate the entry.
    /// * `key` - Metadata key to replace.
    /// * `value` - Typed value to validate and store.
    ///
    /// # Returns
    ///
    /// A mutable reference to this metadata object.
    ///
    /// # Errors
    ///
    /// Returns [`MetadataError::UnknownField`] when `key` is rejected by the
    /// schema, [`MetadataError::MissingRequiredField`] when a required field is
    /// assigned [`Value::Unset`], or [`MetadataError::TypeMismatch`] when the
    /// constructed value's concrete type does not match the schema field type.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Input type convertible into a stored [`Value`].
    #[cfg(feature = "schema")]
    #[inline]
    pub fn set_checked<T>(&mut self, schema: &MetadataSchema, key: &str, value: T) -> MetadataResult<&mut Self>
    where
        T: Into<Value>,
    {
        let _ = self.insert_checked(schema, key, value)?;
        Ok(self)
    }

    /// Returns a new metadata object with a typed value validated and inserted.
    ///
    /// # Parameters
    ///
    /// * `schema` - Schema used to validate the entry.
    /// * `key` - Metadata key to replace.
    /// * `value` - Typed value to validate and store.
    ///
    /// # Returns
    ///
    /// This metadata object after inserting the validated value.
    ///
    /// # Errors
    ///
    /// Returns [`MetadataError::UnknownField`] when `key` is rejected by the
    /// schema, [`MetadataError::MissingRequiredField`] when a required field is
    /// assigned [`Value::Unset`], or [`MetadataError::TypeMismatch`] when the
    /// constructed value's concrete type does not match the schema field type.
    ///
    /// # Type Parameters
    ///
    /// * `T` - Input type convertible into a stored [`Value`].
    #[cfg(feature = "schema")]
    #[inline]
    pub fn with_checked<T>(mut self, schema: &MetadataSchema, key: &str, value: T) -> MetadataResult<Self>
    where
        T: Into<Value>,
    {
        self.set_checked(schema, key, value)?;
        Ok(self)
    }

    /// Removes the entry for `key` and returns the stored [`Value`] if it
    /// existed.
    ///
    /// # Parameters
    ///
    /// * `key` - Metadata key to remove.
    ///
    /// # Returns
    ///
    /// The removed value, or `None` when `key` was absent.
    #[inline]
    pub fn remove(&mut self, key: &str) -> Option<Value> {
        self.0.remove(key)
    }

    /// Removes all entries.
    #[inline]
    pub fn clear(&mut self) {
        self.0.clear();
    }

    /// Returns an iterator over `(&str, &Value)` pairs in key-sorted order.
    ///
    /// # Returns
    ///
    /// A borrowing iterator over entries in key order.
    #[inline]
    #[must_use = "the metadata iterator must be consumed to inspect entries"]
    pub fn iter(&self) -> impl Iterator<Item = (&str, &Value)> {
        self.0.iter().map(|(key, value)| (key.as_str(), value))
    }

    /// Returns an iterator over the keys in sorted order.
    ///
    /// # Returns
    ///
    /// A borrowing iterator over keys in sorted order.
    #[inline]
    #[must_use = "the metadata key iterator must be consumed to inspect keys"]
    pub fn keys(&self) -> impl Iterator<Item = &str> {
        self.0.keys().map(String::as_str)
    }

    /// Returns an iterator over the values in key-sorted order.
    ///
    /// # Returns
    ///
    /// A borrowing iterator over values in key order.
    #[inline]
    #[must_use = "the metadata value iterator must be consumed to inspect values"]
    pub fn values(&self) -> impl Iterator<Item = &Value> {
        self.0.values()
    }

    /// Merges all entries from `other` into `self`, overwriting existing keys.
    ///
    /// # Parameters
    ///
    /// * `other` - Metadata entries to consume and merge.
    pub fn merge(&mut self, mut other: Metadata) {
        self.0.append(&mut other.0);
    }

    /// Returns a new `Metadata` that contains entries from `self` and `other`.
    ///
    /// Entries from `other` take precedence on key conflicts.
    ///
    /// # Parameters
    ///
    /// * `other` - Metadata entries to merge.
    ///
    /// # Returns
    ///
    /// A merged copy without modifying either input.
    #[must_use]
    pub fn merged(&self, other: &Metadata) -> Metadata {
        let mut result = self.clone();
        let mut right = other.0.clone();
        result.0.append(&mut right);
        result
    }

    /// Retains only the entries for which `predicate` returns `true`.
    ///
    /// # Parameters
    ///
    /// * `predicate` - Callback invoked for each key and value; returning
    ///   `false` removes that entry.
    ///
    /// # Type Parameters
    ///
    /// * `F` - Callback type used to decide which entries to retain.
    #[inline]
    pub fn retain<F>(&mut self, mut predicate: F)
    where
        F: FnMut(&str, &Value) -> bool,
    {
        self.0.retain(|key, value| predicate(key.as_str(), value));
    }

    /// Converts this metadata object into its underlying map.
    ///
    /// # Returns
    ///
    /// The owned, key-sorted map of metadata values.
    #[inline]
    #[must_use]
    pub fn into_inner(self) -> BTreeMap<String, Value> {
        self.0
    }

    /// Validates that this metadata object fits the strict V1 wire contract.
    ///
    /// This preflight checks the same entry-count and key-byte limits enforced
    /// by [`Serialize::serialize`], allowing callers to reject invalid metadata
    /// at the write boundary instead of discovering the error during encoding.
    ///
    /// # Returns
    ///
    /// `Ok(())` when every entry can satisfy the metadata map limits.
    ///
    /// # Errors
    ///
    /// Returns [`MetadataError::WireLimitExceeded`] when the entry count or a
    /// key exceeds the strict V1 limit.
    #[inline]
    pub fn validate_wire_contract(&self) -> MetadataResult<()> {
        if self.0.len() > STRICT_STRING_MAP_MAX_ENTRIES {
            return Err(MetadataError::WireLimitExceeded {
                kind: crate::MetadataWireLimitKind::Entries,
                value: self.0.len(),
                maximum: STRICT_STRING_MAP_MAX_ENTRIES,
            });
        }
        if let Some(key) = self.0.keys().find(|key| key.len() > STRICT_STRING_MAP_MAX_KEY_BYTES) {
            return Err(MetadataError::WireLimitExceeded {
                kind: crate::MetadataWireLimitKind::KeyBytes,
                value: key.len(),
                maximum: STRICT_STRING_MAP_MAX_KEY_BYTES,
            });
        }
        Ok(())
    }

    /// Looks up storage, leaving unset and type classification to the value
    /// layer.
    ///
    /// # Parameters
    ///
    /// * `key` - Metadata key to look up.
    ///
    /// # Returns
    ///
    /// The stored value for the key.
    ///
    /// # Errors
    ///
    /// Returns [`MetadataError::MissingKey`] when the key is absent.
    fn entry(&self, key: &str) -> MetadataResult<&Value> {
        self.get_raw(key)
            .ok_or_else(|| MetadataError::MissingKey(key.to_owned()))
    }

    /// Wraps a value access error with its metadata key while retaining the
    /// original error as the source.
    ///
    /// # Parameters
    ///
    /// * `key` - Metadata key associated with the access error.
    /// * `source` - Original value access error.
    ///
    /// # Returns
    ///
    /// A metadata value access error containing `key` and `source`.
    fn map_access_error(key: &str, source: ValueError) -> MetadataError {
        MetadataError::ValueAccess {
            key: key.to_owned(),
            source: Box::new(source),
        }
    }

    /// Determines whether a metadata error represents a defaultable missing
    /// value under the selected read policy.
    ///
    /// # Parameters
    ///
    /// * `error` - Metadata error to classify.
    /// * `conversion` - Whether conversion fallback rules apply.
    ///
    /// # Returns
    ///
    /// `true` when the error represents a missing value eligible for the
    /// selected fallback; otherwise, `false`.
    fn is_defaultable(error: &MetadataError, conversion: bool) -> bool {
        match error {
            MetadataError::MissingKey(_) => true,
            MetadataError::ValueAccess { source, .. } => source.missing().is_some_and(|missing| {
                if conversion {
                    missing.is_defaultable_for_conversion()
                } else {
                    missing.is_defaultable_for_strict_read()
                }
            }),
            _ => false,
        }
    }

    /// Converts a decoded wire envelope into scalar metadata values.
    ///
    /// # Parameters
    ///
    /// * `wire` - Decoded metadata envelope containing scalar value payloads.
    ///
    /// # Returns
    ///
    /// The metadata values indexed by key.
    ///
    /// # Errors
    ///
    /// Returns an error message when an envelope value is not a scalar V1
    /// payload.
    fn from_wire(
        wire: MetadataWireV1<StrictStringMap<ValueWirePayloadV1>>,
    ) -> Result<BTreeMap<String, Value>, &'static str> {
        wire.values
            .into_inner()
            .into_iter()
            .map(|(key, value)| {
                value
                    .into_container()
                    .into_scalar()
                    .map(|value| (key, value))
                    .map_err(|_| "metadata values must use scalar V1 payloads")
            })
            .collect()
    }
}

impl Redact for Metadata {
    /// Writes a policy-redacted metadata representation.
    ///
    /// Metadata is pure domain structure, so this traversal consumes nodes,
    /// collection items, and output bytes but no diagnostic input bytes. The
    /// metadata node and its map field are admitted before the stored map is
    /// accessed. The map writer then enters exactly one map node and admits
    /// each exact remaining entry before iterator advancement. Its admitted-
    /// item path classifies entries without charging duplicate keyed root and
    /// field nodes; pass-through values still enter their legitimate nested
    /// value scopes.
    ///
    /// # Parameters
    ///
    /// * `writer` - Redaction writer receiving the metadata representation.
    ///
    /// # Returns
    ///
    /// Returns `()` after writing through the redaction writer.
    fn write_redacted(&self, writer: &mut RedactionWriter<'_>) {
        writer.record("Metadata", |fields| {
            fields.nested("values", &MetadataValues(&self.0));
        });
    }
}

impl fmt::Debug for Metadata {
    /// Writes the strict-policy redacted representation.
    ///
    /// # Parameters
    ///
    /// * `formatter` - Formatter receiving the redacted representation.
    #[inline]
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let output = Redactor::strict().redact_text(self);
        let text = output.text_or_marker("<redaction incomplete>");
        formatter.write_str(text.as_ref())
    }
}

impl fmt::Display for Metadata {
    /// Writes a bounded, strict-policy redacted representation as
    /// single-line diagnostic text.
    ///
    /// The strict policy redacts values according to the diagnostic policy, but
    /// this output is not a confidentiality boundary for arbitrary user-defined
    /// keys or error text.
    ///
    /// # Parameters
    ///
    /// * `formatter` - Formatter receiving the redacted representation.
    #[inline]
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        let output = Redactor::strict().redact_text(self);
        let text = output.text_or_marker("<redaction incomplete>");
        formatter.write_str(text.as_ref())
    }
}

impl Serialize for Metadata {
    /// Serializes metadata as the strict v1 envelope.
    ///
    /// # Type Parameters
    ///
    /// * `S` - Serializer used to produce the wire envelope.
    ///
    /// # Parameters
    ///
    /// * `serializer` - Serializer receiving the metadata envelope.
    ///
    /// # Returns
    ///
    /// The serializer's result containing the encoded envelope.
    ///
    /// # Errors
    ///
    /// Returns the serializer's error if wire validation or serialization
    /// fails.
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        self.validate_wire_contract().map_err(<S::Error as SerError>::custom)?;
        MetadataWireV1 {
            version: METADATA_WIRE_VERSION_V1,
            values: MetadataWireValuesRef(&self.0),
        }
        .serialize(serializer)
    }
}

impl<'de> Deserialize<'de> for Metadata {
    /// Deserializes only the strict v1 envelope.
    ///
    /// # Type Parameters
    ///
    /// * `D` - Deserializer providing the wire envelope.
    ///
    /// # Parameters
    ///
    /// * `deserializer` - Source of the serialized metadata envelope.
    ///
    /// # Returns
    ///
    /// The decoded metadata object.
    ///
    /// # Errors
    ///
    /// Returns the deserializer's error if the envelope is malformed,
    /// unsupported, or contains invalid metadata values.
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        let wire: MetadataWireV1<StrictStringMap<ValueWirePayloadV1>> =
            MetadataWireV1Seed::new(StrictStringMapValueSeed::new(
                STRICT_STRING_MAP_MAX_ENTRIES,
                STRICT_STRING_MAP_MAX_KEY_BYTES,
                ValueWirePayloadV1Seed::new(),
            ))
            .deserialize(deserializer)?;
        if wire.version != METADATA_WIRE_VERSION_V1 {
            return Err(de::Error::custom("unsupported Metadata wire format version"));
        }
        let values = Self::from_wire(wire).map_err(de::Error::custom)?;
        Ok(Self(values))
    }
}

impl From<BTreeMap<String, Value>> for Metadata {
    /// Takes ownership of a sorted map without validating schema or wire
    /// limits. Wire encoding can still reject keys or entry counts outside
    /// the V1 contract.
    ///
    /// # Parameters
    ///
    /// * `map` - Sorted metadata map to take ownership of.
    ///
    /// # Returns
    ///
    /// Metadata containing the supplied entries.
    #[inline]
    fn from(map: BTreeMap<String, Value>) -> Self {
        Self(map)
    }
}

impl From<Metadata> for BTreeMap<String, Value> {
    /// Consumes metadata and returns its owned sorted map.
    ///
    /// # Parameters
    ///
    /// * `meta` - Metadata object to consume.
    ///
    /// # Returns
    ///
    /// The owned sorted map of metadata values.
    #[inline]
    fn from(meta: Metadata) -> Self {
        meta.0
    }
}

impl FromIterator<(String, Value)> for Metadata {
    /// Collects entries into metadata using `BTreeMap` duplicate-key
    /// replacement. The resulting keys are sorted; collection does not
    /// validate schema or wire limits.
    ///
    /// # Type Parameters
    ///
    /// * `I` - Iterator type yielding owned metadata key-value pairs.
    ///
    /// # Parameters
    ///
    /// * `iter` - Source of metadata key-value pairs.
    ///
    /// # Returns
    ///
    /// Metadata containing the collected entries.
    #[inline]
    fn from_iter<I: IntoIterator<Item = (String, Value)>>(iter: I) -> Self {
        Self(iter.into_iter().collect())
    }
}

impl IntoIterator for Metadata {
    /// Owning B-tree iterator, yielding entries in key order.
    type IntoIter = std::collections::btree_map::IntoIter<String, Value>;
    /// Owned key-value pair moved from the consumed metadata.
    type Item = (String, Value);

    /// Consumes metadata and moves its sorted entries without cloning.
    ///
    /// # Parameters
    ///
    /// * `self` - Metadata object whose entries are moved into the iterator.
    ///
    /// # Returns
    ///
    /// An owning iterator over sorted metadata entries.
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.0.into_iter()
    }
}

impl<'a> IntoIterator for &'a Metadata {
    /// Borrowed B-tree iterator tied to the metadata borrow.
    type IntoIter = std::collections::btree_map::Iter<'a, String, Value>;
    /// References to an entry's key and value; neither is cloned.
    type Item = (&'a String, &'a Value);

    /// Borrows sorted entries for the lifetime of the metadata borrow without
    /// cloning. This yields `(&String, &Value)`, unlike [`Metadata::iter`]
    /// which yields `(&str, &Value)`.
    ///
    /// # Parameters
    ///
    /// * `self` - Borrowed metadata whose entries are exposed by the iterator.
    ///
    /// # Returns
    ///
    /// A borrowed iterator over sorted metadata entries.
    #[inline]
    fn into_iter(self) -> Self::IntoIter {
        self.0.iter()
    }
}

impl Extend<(String, Value)> for Metadata {
    /// Adds entries, replacing duplicate keys according to `BTreeMap` behavior.
    /// The resulting keys remain sorted; no input iteration order is promised.
    ///
    /// # Type Parameters
    ///
    /// * `I` - Iterator type yielding owned metadata key-value pairs.
    ///
    /// # Parameters
    ///
    /// * `iter` - Source of metadata key-value pairs to add.
    #[inline]
    fn extend<I: IntoIterator<Item = (String, Value)>>(&mut self, iter: I) {
        self.0.extend(iter);
    }
}