#![deny(unsafe_code)]
use crate::json::index::Shape;
use crate::json::{self, Kind, Value};
use crate::render::{str_width, truncate_width, Line, LineKind, Span};
use crate::theme;
pub const INDENT: usize = 2;
pub const ALL_OPEN: &str = "*";
pub fn child_id(parent: &str, i: usize) -> String {
format!("{parent}/{i}")
}
pub fn top_index(id: &str) -> Option<usize> {
id.strip_prefix('/')?.parse().ok()
}
pub const MAX_VALUE: usize = 4096;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Mark {
Open,
Closed,
Leaf,
}
impl Mark {
pub fn of(shape: Shape, open: bool) -> Mark {
match (shape.is_container(), open) {
(false, _) => Mark::Leaf,
(true, true) => Mark::Open,
(true, false) => Mark::Closed,
}
}
}
pub enum Body<'a> {
Bracket(Shape),
Close(Shape),
Summary(Shape, usize, bool),
Scalar(&'a Value),
Note(String),
}
pub fn spans(depth: usize, mark: Mark, key: Option<&str>, body: Body<'_>) -> Vec<Span> {
let mut out = indent(depth);
out.push(marker(mark));
if let Some(k) = key {
out.push(Span::new(json::write::escape(k), theme::json_key()));
out.push(Span::new(": ", theme::json_punct()));
}
out.extend(body_spans(body));
out
}
pub fn line(spans: Vec<Span>, source_line: usize) -> Line {
Line {
spans,
block: 0,
source_line,
heading: None,
scroll: true,
kind: LineKind::Table,
}
}
pub fn body_spans(body: Body<'_>) -> Vec<Span> {
match body {
Body::Bracket(s) => vec![Span::new(s.brackets().0, theme::json_punct())],
Body::Close(s) => vec![Span::new(s.brackets().1, theme::json_punct())],
Body::Summary(s, n, done) => {
vec![Span::new(summary_text(s, n, done), theme::muted())]
}
Body::Scalar(v) => scalar_spans(v),
Body::Note(t) => vec![Span::new(t, theme::error())],
}
}
pub fn summary_text(shape: Shape, n: usize, done: bool) -> String {
let (l, r) = shape.brackets();
if done && n == 0 {
return format!("{l}{r}");
}
let ge = match done {
true => "",
false => "\u{2265}",
};
format!("{l}\u{2026}{ge}{n} {}{r}", shape.unit(n))
}
pub fn scalar_spans(v: &Value) -> Vec<Span> {
let (text, style) = match v.kind() {
Kind::String => (
cut_literal(&json::write::escape(v.as_str().unwrap_or(""))),
theme::json_string(),
),
Kind::Number => (
cut(v.as_number().map(|n| n.text()).unwrap_or_default()),
theme::json_number(),
),
Kind::Bool => (v.as_bool().unwrap_or(false).to_string(), theme::json_bool()),
Kind::Null => ("null".to_string(), theme::json_null()),
_ => (cut(&v.to_json()), theme::text()),
};
vec![Span::new(text, style)]
}
pub fn shape_of(v: &Value) -> Shape {
match v {
Value::Object(_) => Shape::Object,
Value::Array(_) => Shape::Array,
Value::Str(_) => Shape::Str,
Value::Number(_) => Shape::Number,
Value::Bool(_) => Shape::Bool,
Value::Null => Shape::Null,
}
}
pub fn path_step(key: Option<&str>, index: usize) -> String {
match key {
None => format!("[{index}]"),
Some(k) if plain_key(k) => format!(".{k}"),
Some(k) => format!("[{}]", Value::string(k.to_string()).to_json()),
}
}
fn plain_key(k: &str) -> bool {
!k.is_empty()
&& k.chars()
.all(|c| c.is_ascii_alphanumeric() || c == '_' || c == '-')
&& !k.starts_with(|c: char| c.is_ascii_digit())
}
pub fn size(n: u64) -> String {
const UNITS: [(u64, &str); 3] = [(1 << 30, "GB"), (1 << 20, "MB"), (1 << 10, "KB")];
for (scale, name) in UNITS {
if n >= scale {
return format!("{:.1} {name}", n as f64 / scale as f64);
}
}
format!("{n} bytes")
}
pub const MAX_DEPTH: usize = 256;
pub fn too_deep(limit: usize) -> String {
format!("\u{27e8}nested deeper than {limit} levels \u{2014} not opened\u{27e9}")
}
pub fn oversize(len: u64, cap: u64) -> String {
format!(
"\u{27e8}{} \u{2014} over the {} display limit\u{27e9}",
size(len),
size(cap)
)
}
fn cut_literal(lit: &str) -> String {
if str_width(lit) <= MAX_VALUE {
return lit.to_string();
}
let kept = truncate_width(lit, MAX_VALUE.saturating_sub(2));
let kept = kept.trim_end_matches('\\');
format!("{kept}\u{2026}\"")
}
fn cut(text: &str) -> String {
if str_width(text) <= MAX_VALUE {
return text.to_string();
}
let mut s = truncate_width(text, MAX_VALUE.saturating_sub(1)).to_string();
s.push('\u{2026}');
s
}
pub const MAX_INDENT: usize = 64;
fn indent(depth: usize) -> Vec<Span> {
match depth.min(MAX_INDENT) {
0 => Vec::new(),
d => vec![Span::plain(" ".repeat(d * INDENT))],
}
}
fn marker(mark: Mark) -> Span {
let glyph = match mark {
Mark::Open => theme::MARKER_OPEN,
Mark::Closed => theme::MARKER_CLOSED,
Mark::Leaf => return Span::plain(" "),
};
Span::new(format!("{glyph} "), theme::json_marker())
}
#[cfg(test)]
#[path = "jsonrow_tests.rs"]
mod tests;