1mod declaration;
9#[doc(hidden)]
10pub use declaration::__private;
11mod method;
12
13pub use declaration::Evolve;
14#[cfg(feature = "typescript")]
15pub use declaration::{ExtensionLayout, OpenLayout, SchemaFields};
16pub use declaration::{ExtensionSlot, OpenSlot, RecoverSlot};
17pub use method::{Evolving, Method, decode, encode, encode_into, encode_to_slice, encoded_len};
18#[doc(hidden)]
19pub mod inline;
20
21#[doc(hidden)]
22pub use serde as __serde;
23
24use crate::{
25 Encoding, Error, LimitKind, Limits, decode as reader, encode as writer, framing::HEADER_BYTES,
26 meter::Budget,
27};
28use alloc::vec::Vec;
29use core::fmt;
30use serde::{
31 Deserialize, Deserializer, Serialize, Serializer,
32 de::{self, SeqAccess, Visitor},
33 ser::SerializeTuple,
34};
35use serde_bytes::Bytes;
36
37mod recovery;
38pub use recovery::{Recoverable, RecoveryContext};
39
40pub struct Projected<'a, T> {
42 pub core: T,
44 pub extensions: Extensions<'a>,
46}
47
48impl<'a, T> Projected<'a, T> {
49 pub const fn new(core: T, extensions: Extensions<'a>) -> Self {
51 Self { core, extensions }
52 }
53
54 pub const fn empty(core: T) -> Self {
56 Self::new(core, Extensions::empty())
57 }
58}
59
60impl<T: Serialize> Serialize for Projected<'_, T> {
61 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
62 (&self.core, self.extensions).serialize(serializer)
63 }
64}
65
66impl<'de: 'a, 'a, T: Deserialize<'de>> Deserialize<'de> for Projected<'a, T> {
67 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
68 let (core, extensions) = <(T, Extensions<'a>)>::deserialize(deserializer)?;
69 Ok(Self::new(core, extensions))
70 }
71}
72
73pub fn decode_projected<'de, T: Deserialize<'de>, R>(
83 input: &'de [u8],
84 encoding: Encoding,
85 limits: Limits,
86 project: impl FnOnce(Projected<'de, T>, &ReadContext<'_>) -> Result<R, Error>,
87) -> Result<R, Error> {
88 decode_value(input, encoding, limits, project)
89}
90
91pub(crate) fn decode_value<'de, T: Deserialize<'de>, R>(
92 input: &'de [u8],
93 encoding: Encoding,
94 limits: Limits,
95 project: impl FnOnce(T, &ReadContext<'_>) -> Result<R, Error>,
96) -> Result<R, Error> {
97 let (payload, limits) = reader::admit_input(input, encoding, limits)?;
98 let budget = Budget::new(limits);
99 let dto = reader::decode_payload(payload, &budget, 1);
100 budget.check()?;
101 let result = project(
102 dto?,
103 &ReadContext {
104 budget: &budget,
105 depth: 1,
106 },
107 );
108 budget.check()?;
109 result
110}
111
112pub fn encode_closed_core<T: Serialize + ?Sized>(
117 value: &T,
118 encoding: Encoding,
119 limits: Limits,
120) -> Result<Vec<u8>, Error> {
121 let root = Projected::empty(value);
122 encode_closed_with(&writer::payload_writer(&root), encoding, limits)
123}
124
125#[inline(never)]
126fn encode_closed_with(
127 write: &writer::PayloadWriter<'_>,
128 encoding: Encoding,
129 limits: Limits,
130) -> Result<Vec<u8>, Error> {
131 let mut out = Vec::new();
132 encode_value_into_with(&mut out, encoding, limits, |output, header, context| {
133 writer::write_projected_vec_with(write, context.budget, header, context.byte_limit, output)
134 })?;
135 Ok(out)
136}
137
138pub fn encode_projected_into<'out, 'value, T: Serialize>(
147 output: &'out mut Vec<u8>,
148 encoding: Encoding,
149 limits: Limits,
150 prepare: impl FnOnce(&WriteContext<'_>) -> Result<Projected<'value, T>, Error>,
151) -> Result<&'out [u8], Error> {
152 encode_value_into(output, encoding, limits, prepare)
153}
154
155pub(crate) fn encode_value_into<T: Serialize>(
156 output: &mut Vec<u8>,
157 encoding: Encoding,
158 limits: Limits,
159 prepare: impl FnOnce(&WriteContext<'_>) -> Result<T, Error>,
160) -> Result<&[u8], Error> {
161 encode_value_into_with(output, encoding, limits, |output, header, context| {
162 let value = prepare(context);
163 context.budget.check()?;
164 write_value_into(output, header, context, &value?)
165 })
166}
167
168#[inline(never)]
169fn encode_value_into_with(
170 output: &mut Vec<u8>,
171 encoding: Encoding,
172 limits: Limits,
173 write: impl FnOnce(&mut Vec<u8>, Option<[u8; HEADER_BYTES]>, &WriteContext<'_>) -> Result<(), Error>,
174) -> Result<&[u8], Error> {
175 output.clear();
176 let header = encoding.header();
177 let prefix = encoding.header_len();
178 let limits = limits.without_prefix(prefix)?;
179 let budget = Budget::new(limits);
180 budget.check()?;
181 let context = WriteContext {
182 budget: &budget,
183 depth: 1,
184 byte_limit: limits.bytes,
185 };
186 let result = write(output, header, &context);
187 if let Err(error) = budget.check().and(result) {
188 output.clear();
189 return Err(error);
190 }
191 Ok(output)
192}
193
194fn write_value_into<T: Serialize>(
195 output: &mut Vec<u8>,
196 header: Option<[u8; HEADER_BYTES]>,
197 context: &WriteContext<'_>,
198 value: &T,
199) -> Result<(), Error> {
200 writer::write_projected_vec_with(
201 &writer::payload_writer(value),
202 context.budget,
203 header,
204 context.byte_limit,
205 output,
206 )
207}
208
209pub fn projected_len<T: Serialize>(
215 value: &Projected<'_, T>,
216 encoding: Encoding,
217 limits: Limits,
218) -> Result<usize, Error> {
219 writer::encoded_len(value, encoding, limits)
220}
221
222pub fn encode_projected_to_slice<'out, 'value, T: Serialize>(
233 output: &'out mut [u8],
234 encoding: Encoding,
235 limits: Limits,
236 prepare: impl FnOnce(&WriteContext<'_>) -> Result<Projected<'value, T>, Error>,
237) -> Result<&'out [u8], Error> {
238 encode_value_to_slice(output, encoding, limits, prepare)
239}
240
241pub(crate) fn encode_value_to_slice<T: Serialize>(
242 output: &mut [u8],
243 encoding: Encoding,
244 limits: Limits,
245 prepare: impl FnOnce(&WriteContext<'_>) -> Result<T, Error>,
246) -> Result<&[u8], Error> {
247 encode_projected_to_slice_with(output, encoding, limits, |mut destination| {
248 let context = destination.context();
249 let dto = prepare(&context);
250 context.budget.check()?;
251 destination.write_value(&dto?)
252 })
253}
254
255pub fn encode_projected_to_slice_with(
267 output: &mut [u8],
268 encoding: Encoding,
269 limits: Limits,
270 write: impl FnOnce(ProjectedOutput<'_>) -> Result<(), Error>,
271) -> Result<&[u8], Error> {
272 let header = encoding.header();
273 let prefix = encoding.header_len();
274 let limits = limits.without_prefix(prefix)?;
275 let budget = Budget::new(limits);
276 budget.check()?;
277 let capacity = output
278 .get_mut(prefix..)
279 .ok_or(Error::Limit(LimitKind::Output))?;
280 let capacity_kind = if capacity.len() < limits.bytes {
281 LimitKind::Output
282 } else {
283 LimitKind::Bytes
284 };
285 let cap = capacity.len().min(limits.bytes);
286 let mut written = None;
287 let result = write(ProjectedOutput {
288 output: &mut capacity[..cap],
289 context: WriteContext {
290 budget: &budget,
291 depth: 1,
292 byte_limit: limits.bytes,
293 },
294 capacity_kind,
295 written: &mut written,
296 });
297 budget.check()?;
298 result?;
299 let size = written.ok_or(Error::Malformed)?;
300 if let Some(header) = header {
301 output[..prefix].copy_from_slice(&header);
302 }
303 Ok(&output[..prefix + size])
304}
305
306pub struct ProjectedOutput<'scope> {
308 output: &'scope mut [u8],
309 context: WriteContext<'scope>,
310 capacity_kind: LimitKind,
311 written: &'scope mut Option<usize>,
312}
313
314impl<'scope> ProjectedOutput<'scope> {
315 #[must_use]
317 pub const fn context(&self) -> WriteContext<'scope> {
318 WriteContext {
319 budget: self.context.budget,
320 depth: self.context.depth,
321 byte_limit: self.context.byte_limit,
322 }
323 }
324
325 pub fn write<T: Serialize>(mut self, value: &Projected<'_, T>) -> Result<(), Error> {
331 self.write_value(value)
332 }
333
334 pub(crate) fn write_value<T: Serialize + ?Sized>(&mut self, value: &T) -> Result<(), Error> {
335 let size = writer::write_bounded_slice::<T, false>(
336 value,
337 self.context.budget,
338 self.context.depth,
339 self.output,
340 self.capacity_kind,
341 )?;
342 *self.written = Some(size);
343 Ok(())
344 }
345}
346
347pub struct ReadContext<'a> {
349 budget: &'a Budget,
350 depth: usize,
351}
352
353impl ReadContext<'_> {
354 pub fn nested<R>(
359 &self,
360 project: impl FnOnce(&ReadContext<'_>) -> Result<R, Error>,
361 ) -> Result<R, Error> {
362 let child = self.child();
363 admit_scope(child.budget, child.depth)?;
364 project(&child)
365 }
366
367 pub fn admit_allocation<T>(&self, count: usize) -> Result<(), Error> {
372 admit_materialization::<T>(self.budget, self.depth, count)
373 }
374
375 #[doc(hidden)]
377 #[must_use]
378 pub fn child(&self) -> Self {
379 Self {
380 budget: self.budget,
381 depth: self.depth.saturating_add(1),
382 }
383 }
384}
385
386pub struct WriteContext<'a> {
388 budget: &'a Budget,
389 depth: usize,
390 byte_limit: usize,
391}
392
393impl WriteContext<'_> {
394 pub fn nested<R>(
399 &self,
400 prepare: impl FnOnce(&WriteContext<'_>) -> Result<R, Error>,
401 ) -> Result<R, Error> {
402 let child = self.child();
403 admit_scope(child.budget, child.depth)?;
404 prepare(&child)
405 }
406
407 #[doc(hidden)]
412 pub fn admit_preparation(&self) -> Result<(), Error> {
413 admit_scope(self.budget, self.depth)
414 }
415
416 #[doc(hidden)]
421 pub fn admit_allocation<T>(&self, count: usize) -> Result<(), Error> {
422 admit_materialization::<T>(self.budget, self.depth, count)
423 }
424
425 #[doc(hidden)]
427 #[must_use]
428 pub fn child(&self) -> Self {
429 Self {
430 budget: self.budget,
431 depth: self.depth.saturating_add(1),
432 byte_limit: self.byte_limit,
433 }
434 }
435
436 fn write_once<T: Serialize + ?Sized>(
437 &self,
438 value: &T,
439 scratch: &mut [u8],
440 ) -> Result<usize, Error> {
441 let byte_limit = self.byte_limit.min(u32::MAX as usize);
442 let capacity_kind = if scratch.len() < byte_limit {
443 LimitKind::Scratch
444 } else {
445 LimitKind::Bytes
446 };
447 let cap = scratch.len().min(byte_limit);
448 writer::write_bounded_slice::<_, true>(
449 value,
450 self.budget,
451 self.depth,
452 &mut scratch[..cap],
453 capacity_kind,
454 )
455 }
456}
457
458fn varint_width(value: u32) -> usize {
459 (u32::BITS - value.leading_zeros()).max(1).div_ceil(7) as usize
460}
461
462fn admit(budget: &Budget, depth: usize, units: usize) -> Result<(), Error> {
463 if budget.enter(depth, units) {
464 Ok(())
465 } else {
466 Err(budget.error())
467 }
468}
469
470fn admit_materialization<T>(budget: &Budget, depth: usize, count: usize) -> Result<(), Error> {
471 let units = size_of::<T>().checked_mul(count).ok_or_else(|| {
472 budget.refuse();
473 budget.error()
474 })?;
475 admit(budget, depth, units)
476}
477
478fn admit_scope(budget: &Budget, depth: usize) -> Result<(), Error> {
479 if budget.enter_scope(depth) {
480 Ok(())
481 } else {
482 Err(budget.error())
483 }
484}
485
486pub struct Field<'meter, 'de> {
488 bytes: &'de [u8],
489 context: ReadContext<'meter>,
490}
491
492impl<'de> Field<'_, 'de> {
493 pub fn decode<T: Deserialize<'de>>(self) -> Result<T, Error> {
499 self.project(|value, _| Ok(value))
500 }
501
502 #[doc(hidden)]
507 pub fn project_inline<T: inline::Inline<'de>>(self) -> Result<T, Error> {
508 self.project(T::project)
509 }
510
511 pub fn project<T: Deserialize<'de>, R>(
516 self,
517 project: impl FnOnce(T, &ReadContext<'_>) -> Result<R, Error>,
518 ) -> Result<R, Error> {
519 let value = reader::decode_payload(self.bytes, self.context.budget, self.context.depth)
520 .map_err(|error| {
521 if error == Error::Trailing {
522 Error::Malformed
523 } else {
524 error
525 }
526 });
527 self.context.budget.check()?;
528 let result = project(value?, &self.context);
529 self.context.budget.check()?;
530 result
531 }
532}
533
534#[derive(Clone, Copy, Debug, PartialEq, Eq)]
536pub struct Extensions<'a>(&'a [u8]);
537
538impl<'a> Extensions<'a> {
539 #[must_use]
541 pub const fn empty() -> Self {
542 Self(&[])
543 }
544
545 pub fn visit(
554 self,
555 context: &ReadContext<'_>,
556 mut visit: impl FnMut(u32, Field<'_, 'a>) -> Result<(), Error>,
557 ) -> Result<(), Error> {
558 let block = context.child();
559 admit_scope(block.budget, block.depth)?;
560 let mut rest = self.0;
561 let mut previous = 0;
562 while !rest.is_empty() {
563 let field_context = block.child();
564 admit_scope(field_context.budget, field_context.depth)?;
565 let (id, bytes, remaining) = extension_header(rest)?;
566 if id <= previous {
567 return Err(Error::Malformed);
568 }
569 visit(
570 id,
571 Field {
572 bytes,
573 context: field_context,
574 },
575 )?;
576 block.budget.check()?;
577 rest = remaining;
578 previous = id;
579 }
580 Ok(())
581 }
582}
583
584#[inline(never)]
585fn extension_header(rest: &[u8]) -> Result<(u32, &[u8], &[u8]), Error> {
586 if let Some(([id, length], tail)) = rest.split_first_chunk::<2>()
588 && (id | length) < 128
589 {
590 let (bytes, remaining) = tail
591 .split_at_checked(usize::from(*length))
592 .ok_or(Error::Malformed)?;
593 return Ok((u32::from(*id), bytes, remaining));
594 }
595 postcard_extension_header(rest)
596}
597
598#[inline(never)]
599fn postcard_extension_header(rest: &[u8]) -> Result<(u32, &[u8], &[u8]), Error> {
600 let ((id, bytes), remaining) =
602 postcard::take_from_bytes::<(u32, &Bytes)>(rest).map_err(|_| Error::Malformed)?;
603 Ok((id, bytes.as_ref(), remaining))
604}
605
606impl Serialize for Extensions<'_> {
607 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
608 serializer.serialize_bytes(self.0)
609 }
610}
611
612impl<'de: 'a, 'a> Deserialize<'de> for Extensions<'a> {
613 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
614 <&Bytes>::deserialize(deserializer).map(|bytes| Self(bytes.as_ref()))
615 }
616}
617
618pub struct ExtensionsWriter<'a> {
620 output: &'a mut [u8],
621 used: usize,
622 previous: u32,
623}
624
625impl<'a> ExtensionsWriter<'a> {
626 #[must_use]
628 pub const fn new(output: &'a mut [u8]) -> Self {
629 Self {
630 output,
631 used: 0,
632 previous: 0,
633 }
634 }
635
636 pub fn push<T: Serialize + ?Sized>(
642 &mut self,
643 context: &WriteContext<'_>,
644 id: u32,
645 value: &T,
646 ) -> Result<(), Error> {
647 self.push_with(context, id, |leaf, available| {
648 leaf.write_once(value, available)
649 })
650 }
651
652 #[doc(hidden)]
661 pub fn push_projected<'de, T: inline::Inline<'de>>(
662 &mut self,
663 context: &WriteContext<'_>,
664 id: u32,
665 value: &T,
666 ) -> Result<(), Error> {
667 self.push_with(context, id, |leaf, available| {
668 let capacity = available.len();
669 let (view, tail) = value.prepare(leaf, available)?;
670 let staged = capacity.checked_sub(tail.len()).ok_or(Error::Malformed)?;
671 let len = leaf.write_once(&view, tail)?;
672 drop(view);
673 if staged != 0 {
674 available.copy_within(staged..staged + len, 0);
675 }
676 Ok(len)
677 })
678 }
679
680 fn push_with(
681 &mut self,
682 context: &WriteContext<'_>,
683 id: u32,
684 prepare: impl FnOnce(&WriteContext<'_>, &mut [u8]) -> Result<usize, Error>,
685 ) -> Result<(), Error> {
686 if id <= self.previous {
687 return Err(Error::Malformed);
688 }
689 let mut leaf = context.child().child();
690 admit_scope(leaf.budget, leaf.depth)?;
691 let bound = leaf.byte_limit.min(u32::MAX as usize);
692 let min_prefix = if id < 128 { 2 } else { varint_width(id) + 1 };
693 let body_at = self
694 .used
695 .checked_add(min_prefix)
696 .filter(|start| *start <= bound)
697 .ok_or_else(|| leaf.budget.refuse_with(LimitKind::Bytes))?;
698 let available = self
699 .output
700 .get_mut(body_at..)
701 .ok_or_else(|| leaf.budget.refuse_with(LimitKind::Scratch))?;
702 if !leaf.budget.charge_buffer(min_prefix) {
703 return Err(leaf.budget.error());
704 }
705 leaf.byte_limit = bound - body_at;
708 let len = prepare(&leaf, available)?;
709 self.used = if min_prefix == 2 && len < 128 {
710 self.output[self.used..body_at].copy_from_slice(&[id as u8, len as u8]);
712 body_at + len
713 } else {
714 self.finish_wide_prefix(leaf.budget, bound, id, body_at, len)?
715 };
716 self.previous = id;
717 Ok(())
718 }
719
720 #[cold]
721 #[inline(never)]
722 fn finish_wide_prefix(
723 &mut self,
724 budget: &Budget,
725 bound: usize,
726 id: u32,
727 body_at: usize,
728 len: usize,
729 ) -> Result<usize, Error> {
730 let mut end = body_at + len;
731 if len >= 128 {
732 let extra = varint_width(len as u32) - 1;
733 end = end
734 .checked_add(extra)
735 .filter(|end| *end <= bound)
736 .ok_or_else(|| budget.refuse_with(LimitKind::Bytes))?;
737 if end > self.output.len() {
738 return Err(budget.refuse_with(LimitKind::Scratch));
739 }
740 if !budget.charge_buffer(extra) {
741 return Err(budget.error());
742 }
743 self.output
744 .copy_within(body_at..body_at + len, body_at + extra);
745 }
746 let prefix = &mut self.output[self.used..end - len];
747 postcard::to_slice(&(id, len as u32), prefix).map_err(|_| Error::Malformed)?;
748 Ok(end)
749 }
750
751 #[must_use]
753 pub fn finish(self) -> Extensions<'a> {
754 self.finish_and_tail().0
755 }
756
757 #[must_use]
762 pub fn finish_and_tail(self) -> (Extensions<'a>, &'a mut [u8]) {
763 let (bytes, tail) = self.output.split_at_mut(self.used);
764 (Extensions(bytes), tail)
765 }
766}
767
768#[derive(Clone, Copy, Debug, PartialEq, Eq)]
774pub struct OpaqueOpen<'a> {
775 id: u32,
776 bytes: &'a [u8],
777}
778
779impl<'a> OpaqueOpen<'a> {
780 #[must_use]
782 pub const fn absent() -> Self {
783 Self { id: 0, bytes: &[] }
784 }
785
786 pub const fn unit(id: u32) -> Result<Self, Error> {
791 if id == 0 || id > (u32::MAX >> 1) {
792 return Err(Error::Malformed);
793 }
794 Ok(Self { id, bytes: &[] })
795 }
796
797 pub fn write<T: Serialize + ?Sized>(
802 context: &WriteContext<'_>,
803 id: u32,
804 value: &T,
805 scratch: &'a mut [u8],
806 ) -> Result<Self, Error> {
807 Self::write_in(context, id, value, scratch).map(|(open, _)| open)
808 }
809
810 pub fn write_in<T: Serialize + ?Sized>(
815 context: &WriteContext<'_>,
816 id: u32,
817 value: &T,
818 scratch: &'a mut [u8],
819 ) -> Result<(Self, &'a mut [u8]), Error> {
820 Self::unit(id)?;
821 let leaf = context.child().child();
822 let size = leaf.write_once(value, scratch)?;
823 let (bytes, tail) = scratch.split_at_mut(size);
824 Ok((Self { id, bytes }, tail))
825 }
826
827 pub fn visit<R>(
836 self,
837 context: &ReadContext<'_>,
838 visit: impl FnOnce(u32, Field<'_, 'a>) -> Result<R, Error>,
839 ) -> Result<Option<R>, Error> {
840 let variant = context.child();
841 if self.id == 0 {
842 admit_scope(variant.budget, variant.depth)?;
843 return Ok(None);
844 }
845 let field_context = variant.child();
846 if !variant
849 .budget
850 .enter_nested_scopes(variant.depth, field_context.depth)
851 {
852 return Err(variant.budget.error());
853 }
854 let result = visit(
855 self.id,
856 Field {
857 bytes: self.bytes,
858 context: field_context,
859 },
860 );
861 variant.budget.check()?;
862 result.map(Some)
863 }
864}
865
866impl Serialize for OpaqueOpen<'_> {
867 fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
868 let has_payload = !self.bytes.is_empty();
869 let mut tuple = serializer.serialize_tuple(1 + usize::from(has_payload))?;
870 tuple.serialize_element(&((self.id << 1) | u32::from(has_payload)))?;
871 if has_payload {
872 tuple.serialize_element(Bytes::new(self.bytes))?;
873 }
874 tuple.end()
875 }
876}
877
878impl<'de: 'a, 'a> Deserialize<'de> for OpaqueOpen<'a> {
879 fn deserialize<D: Deserializer<'de>>(deserializer: D) -> Result<Self, D::Error> {
880 struct OpenVisitor;
881 impl<'de> Visitor<'de> for OpenVisitor {
882 type Value = OpaqueOpen<'de>;
883
884 fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
885 formatter.write_str("open variant tag and optional nonempty payload")
886 }
887
888 fn visit_seq<A: SeqAccess<'de>>(self, mut access: A) -> Result<Self::Value, A::Error> {
889 let header: u32 = access
890 .next_element()?
891 .ok_or_else(|| de::Error::invalid_length(0, &self))?;
892 let id = header >> 1;
893 let bytes = if header & 1 == 0 {
894 &[]
895 } else {
896 if id == 0 {
897 return Err(de::Error::custom("absent open variant has a payload"));
898 }
899 let bytes: &Bytes = access
900 .next_element()?
901 .ok_or_else(|| de::Error::invalid_length(1, &self))?;
902 if bytes.is_empty() {
903 return Err(de::Error::custom("empty open variant payload extent"));
904 }
905 bytes.as_ref()
906 };
907 Ok(OpaqueOpen { id, bytes })
908 }
909 }
910 deserializer.deserialize_tuple(2, OpenVisitor)
911 }
912}