1use std::borrow::Cow;
8use std::fmt::{Display, Formatter};
9use std::{fmt, str};
10
11pub use config::Config;
12
13use crate::format::object::format_object;
14use crate::format::primitive::format_primitive;
15use crate::{Context, Value};
16
17pub mod array;
18pub mod boxed;
19mod config;
20pub mod date;
21pub mod descriptor;
22pub mod function;
23pub mod key;
24pub mod object;
25mod prefix;
26pub mod primitive;
27pub mod promise;
28pub mod regexp;
29mod string;
30pub mod symbol;
31pub mod typedarray;
32
33pub const INDENT: &str = " ";
34pub const NEWLINE: &str = "\n";
35
36#[must_use]
37pub fn indent_str(indentation: usize) -> Cow<'static, str> {
38 const MAX_INDENTS: usize = 128;
39 static INDENTS: &str = match str::from_utf8(&[b' '; MAX_INDENTS * 2]) {
40 Ok(indents) => indents,
41 _ => unreachable!(),
42 };
43
44 if indentation <= 128 {
45 Cow::Borrowed(&INDENTS[0..indentation * INDENT.len()])
46 } else {
47 Cow::Owned(INDENT.repeat(indentation))
48 }
49}
50
51pub fn format_value<'cx>(cx: &'cx Context, cfg: Config, value: &'cx Value<'cx>) -> ValueDisplay<'cx> {
53 ValueDisplay { cx, value, cfg }
54}
55
56#[must_use]
57pub struct ValueDisplay<'cx> {
58 cx: &'cx Context,
59 value: &'cx Value<'cx>,
60 cfg: Config,
61}
62
63impl Display for ValueDisplay<'_> {
64 fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
65 if self.value.handle().is_object() {
66 format_object(self.cx, self.cfg, self.value.to_object(self.cx)).fmt(f)
67 } else {
68 format_primitive(self.cx, self.cfg, self.value).fmt(f)
69 }
70 }
71}