ion/format/
key.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 colored::Colorize as _;
11use itoa::Buffer;
12
13use crate::format::Config;
14use crate::format::symbol::format_symbol;
15use crate::{Context, OwnedKey};
16
17/// Formats the [key of an object](OwnedKey) with the given [configuration](Config).
18pub fn format_key<'cx>(cx: &'cx Context, cfg: Config, key: &'cx OwnedKey<'cx>) -> KeyDisplay<'cx> {
19	KeyDisplay { cx, cfg, key }
20}
21
22#[must_use]
23pub struct KeyDisplay<'cx> {
24	cx: &'cx Context,
25	cfg: Config,
26	key: &'cx OwnedKey<'cx>,
27}
28
29impl Display for KeyDisplay<'_> {
30	fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
31		let colours = self.cfg.colours;
32		match self.key {
33			OwnedKey::Int(i) => {
34				let mut buffer = Buffer::new();
35				buffer.format(*i).color(colours.number).fmt(f)
36			}
37			OwnedKey::String(str) => write!(f, "{0}{1}{0}", r#"""#.color(colours.string), str.color(colours.string)),
38			OwnedKey::Symbol(sym) => {
39				"[".color(colours.symbol).fmt(f)?;
40				format_symbol(self.cx, self.cfg, sym).fmt(f)?;
41				"]".color(colours.symbol).fmt(f)
42			}
43			OwnedKey::Void => unreachable!("Property key <void> cannot be formatted."),
44		}
45	}
46}