ion/format/
boxed.rs

1/*
2 * This Source Code Form is subject to the terms of the Mozilla Public
3 * License, v. 2.0. If a copy of the MPL was not distributed with this
4 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
5 */
6
7use std::fmt;
8use std::fmt::{Display, Formatter};
9
10use crate::format::Config;
11use crate::format::primitive::format_primitive;
12use crate::{Context, Object};
13
14/// Formats a boxed primitive ([Object]) using the given [configuration](Config).
15/// The supported boxed types are `Boolean`, `Number`, `String` and `BigInt`.
16pub fn format_boxed_primitive<'cx>(
17	cx: &'cx Context, cfg: Config, object: &'cx Object<'cx>,
18) -> BoxedPrimitiveDisplay<'cx> {
19	BoxedPrimitiveDisplay { cx, object, cfg }
20}
21
22#[must_use]
23pub struct BoxedPrimitiveDisplay<'cx> {
24	cx: &'cx Context,
25	object: &'cx Object<'cx>,
26	cfg: Config,
27}
28
29impl Display for BoxedPrimitiveDisplay<'_> {
30	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
31		if let Some(primitive) = self.object.unbox_primitive(self.cx) {
32			format_primitive(self.cx, self.cfg, &primitive).fmt(f)
33		} else {
34			unreachable!("Object is not boxed")
35		}
36	}
37}