Skip to content

Commit

Permalink
improve pprint of blobs
Browse files Browse the repository at this point in the history
  • Loading branch information
emanueldima committed Mar 8, 2024
1 parent e8745b1 commit c470e23
Show file tree
Hide file tree
Showing 5 changed files with 68 additions and 47 deletions.
21 changes: 10 additions & 11 deletions src/base/value.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,10 @@ use core::{
fmt::{self, Display},
hash::{Hash, Hasher},
};
use std::borrow::{Borrow, Cow};
use std::{
borrow::{Borrow, Cow},
fmt::Write,
};

pub const DISPLAY_VALUE_NONE: &str = "ø"; // ❍•⸰·
pub const DISPLAY_BYTES_VALUE_LEN: usize = 72;
Expand Down Expand Up @@ -175,11 +178,7 @@ impl<'a> Display for Value<'a> {
Value::Float(x) => write!(buf, "{}", x),
Value::Str(x) => write!(buf, "{}", x),
// Value::OsStr(x) => write!(buf, "{}", x.to_string_lossy()),
Value::Bytes(x) => {
write!(buf, "⟨")?;
write_bytes(buf, x)?;
write!(buf, "⟩")
}
Value::Bytes(x) => write!(buf, "{}", String::from_utf8_lossy(x)),
}
}
}
Expand All @@ -202,19 +201,19 @@ impl<'a> fmt::Debug for Value<'a> {
}
}

fn write_bytes(buf: &mut fmt::Formatter, x: &[u8]) -> fmt::Result {
pub(crate) fn write_bytes(buf: &mut impl Write, x: &[u8]) -> fmt::Result {
let sb = String::from_utf8_lossy(x);
let s = sb.as_ref();
let not_ascii = |c| !(' '..='~').contains(&c);
if s.contains(not_ascii) {
let s = s.replace(not_ascii, ".");
if s.len() > DISPLAY_BYTES_VALUE_LEN {
write!(buf, "{}", &s[..DISPLAY_BYTES_VALUE_LEN])
if s.len() >= DISPLAY_BYTES_VALUE_LEN {
write!(buf, "{}", &s[..DISPLAY_BYTES_VALUE_LEN])
} else {
write!(buf, "{}", s)
}
} else if s.len() > DISPLAY_BYTES_VALUE_LEN {
write!(buf, "{}", &s[..DISPLAY_BYTES_VALUE_LEN])
} else if s.len() >= DISPLAY_BYTES_VALUE_LEN {
write!(buf, "{}", &s[..DISPLAY_BYTES_VALUE_LEN])
} else {
write!(buf, "{}", s)
}
Expand Down
4 changes: 2 additions & 2 deletions src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// #![feature(test)]
#![allow(unused_variables, dead_code)]
#![deny(
// warnings, // todo uncomment this
// warnings, // TODO: uncomment this
missing_debug_implementations,
// missing_copy_implementations, // todo uncomment this
// missing_copy_implementations, // TODO: uncomment this
bare_trait_objects,
// missing_docs
)]
Expand Down
69 changes: 42 additions & 27 deletions src/pprint.rs
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
use std::fmt::Error;
use std::fmt::{Error, Write};

use crate::base::*;

Expand Down Expand Up @@ -84,32 +84,7 @@ fn make_indent(indent: usize, buffer: &mut String) -> Result<(), Error> {
Ok(())
}

fn print_value(buffer: &mut String, indent: usize, s: &str) -> Result<(), Error> {
use std::fmt::Write;
if !s.contains('\n') {
return write!(buffer, "{}", s);
}

let mut pre = String::new();
make_indent(indent, &mut pre)?;
pre.push_str("❝ ");

for (i, l) in s.split('\n').enumerate() {
if i == 0 {
writeln!(buffer, "❝ {}", l)?;
} else {
writeln!(buffer, "{}{}", pre, l)?;
}
}
if buffer.ends_with("\n\n") {
buffer.pop(); // remove last '\n'
}
Ok(())
}

fn print_cell(cell: &Cell, prefix: &str, indent: usize, buffer: &mut String) -> Result<(), Error> {
use std::fmt::Write;

let mut typ = String::new();
write!(buffer, "{} ", cell.interpretation(),)?;

Expand Down Expand Up @@ -163,7 +138,7 @@ fn print_cell(cell: &Cell, prefix: &str, indent: usize, buffer: &mut String) ->
if empty {
empty = v.is_empty();
}
print_value(buffer, indent, v.as_cow_str().as_ref())
print_value(buffer, indent, v)
}
Err(err) => {
if err.kind == HErrKind::None {
Expand All @@ -184,3 +159,43 @@ fn print_cell(cell: &Cell, prefix: &str, indent: usize, buffer: &mut String) ->
buffer.clear();
Ok(())
}

fn print_value(buffer: &mut String, indent: usize, v: Value) -> Result<(), Error> {
match v {
Value::None => write!(buffer, "None"),
Value::Bool(x) => write!(buffer, "{}", x),
Value::Int(x) => write!(buffer, "{}", x),
Value::Float(x) => write!(buffer, "{}", x),
Value::Str(x) => print_string(buffer, indent, x),
Value::Bytes(x) => {
write!(buffer, "⟨")?;
write_bytes(buffer, x)?;
write!(buffer, "⟩")
}
}
}

fn print_string(buffer: &mut String, indent: usize, s: &str) -> Result<(), Error> {
if !s.contains('\n') {
return write!(buffer, "{}", s);
}

let mut pre = String::new();
make_indent(indent, &mut pre)?;
pre.push_str("❝ ");

for (i, l) in s.split('\n').enumerate() {
if i == 0 {
writeln!(buffer, "❝ {}", l)?;
} else {
writeln!(buffer, "{}{}", pre, l)?;
}
}
if buffer.ends_with("\n\n") {
buffer.pop(); // remove last '\n'
}
if buffer.ends_with('\n') {
buffer.pop();
}
Ok(())
}
15 changes: 10 additions & 5 deletions src/tests/fs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ fn test_files() -> Res<()> {
fn test_fs() -> Res<()> {
crate::utils::log::set_verbose(true);
let examples = Cell::from(".").be("path").be("fs").sub().get("examples");
// assert_eq!(std::mem::size_of_val(&examples), 4 * 8); // todo file cell is too large
// assert_eq!(std::mem::size_of_val(&examples), 4 * 8); // TODO: file cell is too large
assert_eq!(
examples.read().label().unwrap_or(Value::None),
Value::Str("examples")
Expand All @@ -37,16 +37,21 @@ fn search_path_with_fs_starter() -> Res<()> {

#[test]
fn fs_write() -> Res<()> {
let t = "Hi there";
let p = "^path^fs/examples/write.txt";
let c = Cell::from(".")
.policy(WritePolicy::NoAutoWrite)
.to(p)
.err()?;
c.write().value(t.into())?;
assert_eq!(Cell::from(".").to(p).read().value()?, t);
c.write().value("Hi there".into())?;
assert_eq!(
Cell::from(".").to(p).read().value()?,
Value::Bytes("Hi there".as_bytes())
);
c.write().value("-".into())?;
assert_eq!(Cell::from(".").to(p).read().value()?, "-");
assert_eq!(
Cell::from(".").to(p).read().value()?,
Value::Bytes("-".as_bytes())
);
Ok(())
}

Expand Down
6 changes: 4 additions & 2 deletions src/tests/ideals.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,9 +16,11 @@ n: nval
fn tree() -> Res<()> {
set_verbose(true);

let cell = Cell::from("./examples/write.json").to("^path^fs[w]^json");
let cell = Cell::from("./examples/write.json");
pprint(&cell, 0, 0);
assert!(cell.clone().err().is_ok());
// let cell = cell.to("^path^fs[w]^json");
// pprint(&cell, 0, 0);
// assert!(cell.clone().err().is_ok());
// assert!(cell.write().value("weak as putty".into()).is_ok());

// let cell = Cell::from(".")
Expand Down

0 comments on commit c470e23

Please sign in to comment.