git.delta.rocks / jrsonnet / refs/commits / 9a5055138e5b

difftreelog

refactor move yaml implementation to stdlib

Yaroslav Bolyukin2022-11-12parent: #92bd203.patch.diff
in: master

5 files changed

addedcrates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth
after · crates/jrsonnet-evaluator/src/manifest.rs
1use std::{borrow::Cow, fmt::Write};23use crate::{4	error::{ErrorKind::*, Result},5	throw, State, Val,6};78pub trait ManifestFormat {9	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()>;10	fn manifest(&self, val: Val) -> Result<String> {11		let mut out = String::new();12		self.manifest_buf(val, &mut out)?;13		Ok(out)14	}15}16impl<T> ManifestFormat for Box<T>17where18	T: ManifestFormat + ?Sized,19{20	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {21		let inner = &**self;22		inner.manifest_buf(val, buf)23	}24}25impl<T> ManifestFormat for &'_ T26where27	T: ManifestFormat + ?Sized,28{29	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {30		let inner = &**self;31		inner.manifest_buf(val, buf)32	}33}3435#[derive(PartialEq, Eq, Clone, Copy)]36enum JsonFormatting {37	// Applied in manifestification38	Manifest,39	/// Used for std.manifestJson40	/// Empty array/objects extends to "[\n\n]" instead of "[ ]" as in manifest41	Std,42	/// No line breaks, used in `obj+''`43	ToString,44	/// Minified json45	Minify,46}4748pub struct JsonFormat<'s> {49	padding: Cow<'s, str>,50	mtype: JsonFormatting,51	newline: &'s str,52	key_val_sep: &'s str,53	#[cfg(feature = "exp-preserve-order")]54	preserve_order: bool,55}5657impl<'s> JsonFormat<'s> {58	// Minifying format59	pub fn minify(#[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Self {60		Self {61			padding: Cow::Borrowed(""),62			mtype: JsonFormatting::Minify,63			newline: "\n",64			key_val_sep: ":",65			#[cfg(feature = "exp-preserve-order")]66			preserve_order,67		}68	}69	// Same format as std.toString70	pub fn std_to_string() -> Self {71		Self {72			padding: Cow::Borrowed(""),73			mtype: JsonFormatting::ToString,74			newline: "\n",75			key_val_sep: ": ",76			#[cfg(feature = "exp-preserve-order")]77			preserve_order: false,78		}79	}80	pub fn std_to_json(81		padding: String,82		newline: &'s str,83		key_val_sep: &'s str,84		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,85	) -> Self {86		Self {87			padding: Cow::Owned(padding),88			mtype: JsonFormatting::Std,89			newline,90			key_val_sep,91			#[cfg(feature = "exp-preserve-order")]92			preserve_order,93		}94	}95	// Same format as CLI manifestification96	pub fn cli(97		padding: usize,98		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,99	) -> Self {100		if padding == 0 {101			return Self::minify(102				#[cfg(feature = "exp-preserve-order")]103				preserve_order,104			);105		}106		Self {107			padding: Cow::Owned(" ".repeat(padding)),108			mtype: JsonFormatting::Manifest,109			newline: "\n",110			key_val_sep: ": ",111			#[cfg(feature = "exp-preserve-order")]112			preserve_order,113		}114	}115}116impl Default for JsonFormat<'static> {117	fn default() -> Self {118		Self {119			padding: Cow::Borrowed("    "),120			mtype: JsonFormatting::Manifest,121			newline: "\n",122			key_val_sep: ": ",123			#[cfg(feature = "exp-preserve-order")]124			preserve_order: false,125		}126	}127}128129pub fn manifest_json_ex(val: &Val, options: &JsonFormat<'_>) -> Result<String> {130	let mut out = String::new();131	manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;132	Ok(out)133}134fn manifest_json_ex_buf(135	val: &Val,136	buf: &mut String,137	cur_padding: &mut String,138	options: &JsonFormat<'_>,139) -> Result<()> {140	let mtype = options.mtype;141	match val {142		Val::Bool(v) => {143			if *v {144				buf.push_str("true");145			} else {146				buf.push_str("false");147			}148		}149		Val::Null => buf.push_str("null"),150		Val::Str(s) => escape_string_json_buf(s, buf),151		Val::Num(n) => write!(buf, "{n}").unwrap(),152		Val::Arr(items) => {153			buf.push('[');154			if !items.is_empty() {155				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {156					buf.push_str(options.newline);157				}158159				let old_len = cur_padding.len();160				cur_padding.push_str(&options.padding);161				for (i, item) in items.iter().enumerate() {162					if i != 0 {163						buf.push(',');164						if mtype == JsonFormatting::ToString {165							buf.push(' ');166						} else if mtype != JsonFormatting::Minify {167							buf.push_str(options.newline);168						}169					}170					buf.push_str(cur_padding);171					manifest_json_ex_buf(&item?, buf, cur_padding, options)?;172				}173				cur_padding.truncate(old_len);174175				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {176					buf.push_str(options.newline);177					buf.push_str(cur_padding);178				}179			} else if mtype == JsonFormatting::Std {180				buf.push_str("\n\n");181				buf.push_str(cur_padding);182			} else if mtype == JsonFormatting::ToString || mtype == JsonFormatting::Manifest {183				buf.push(' ');184			}185			buf.push(']');186		}187		Val::Obj(obj) => {188			obj.run_assertions()?;189			buf.push('{');190			let fields = obj.fields(191				#[cfg(feature = "exp-preserve-order")]192				options.preserve_order,193			);194			if !fields.is_empty() {195				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {196					buf.push_str(options.newline);197				}198199				let old_len = cur_padding.len();200				cur_padding.push_str(&options.padding);201				for (i, field) in fields.into_iter().enumerate() {202					if i != 0 {203						buf.push(',');204						if mtype == JsonFormatting::ToString {205							buf.push(' ');206						} else if mtype != JsonFormatting::Minify {207							buf.push_str(options.newline);208						}209					}210					buf.push_str(cur_padding);211					escape_string_json_buf(&field, buf);212					buf.push_str(options.key_val_sep);213					State::push_description(214						|| format!("field <{}> manifestification", field.clone()),215						|| {216							let value = obj.get(field.clone())?.unwrap();217							manifest_json_ex_buf(&value, buf, cur_padding, options)?;218							Ok(())219						},220					)?;221				}222				cur_padding.truncate(old_len);223224				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {225					buf.push_str(options.newline);226					buf.push_str(cur_padding);227				}228			} else if mtype == JsonFormatting::Std {229				buf.push_str("\n\n");230				buf.push_str(cur_padding);231			} else if mtype == JsonFormatting::ToString || mtype == JsonFormatting::Manifest {232				buf.push(' ');233			}234			buf.push('}');235		}236		Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),237	};238	Ok(())239}240241impl ManifestFormat for JsonFormat<'_> {242	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {243		manifest_json_ex_buf(&val, buf, &mut String::new(), self)244	}245}246247pub struct ToStringFormat;248impl ManifestFormat for ToStringFormat {249	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {250		JsonFormat::std_to_string().manifest_buf(val, out)251	}252}253pub struct StringFormat;254impl ManifestFormat for StringFormat {255	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {256		let Val::Str(s) = val else {257			throw!("output should be string for string manifest format, got {}", val.value_type())258		};259		out.write_str(&s).unwrap();260		Ok(())261	}262}263264pub struct YamlStreamFormat<I>(pub I);265impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {266	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {267		let Val::Arr(arr) = val else {268			throw!("output should be array for yaml stream format, got {}", val.value_type())269		};270		if !arr.is_empty() {271			for v in arr.iter() {272				let v = v?;273				out.push_str("---\n");274				self.0.manifest_buf(v, out)?;275				out.push('\n');276			}277			out.push_str("...");278		}279		Ok(())280	}281}282283pub fn escape_string_json(s: &str) -> String {284	let mut buf = String::new();285	escape_string_json_buf(s, &mut buf);286	buf287}288289// Json string encoding was borrowed from https://github.com/serde-rs/json290291const BB: u8 = b'b'; // \x08292const TT: u8 = b't'; // \x09293const NN: u8 = b'n'; // \x0A294const FF: u8 = b'f'; // \x0C295const RR: u8 = b'r'; // \x0D296const QU: u8 = b'"'; // \x22297const BS: u8 = b'\\'; // \x5C298const UU: u8 = b'u'; // \x00...\x1F except the ones above299const __: u8 = 0;300301// Lookup table of escape sequences. A value of b'x' at index i means that byte302// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.303static ESCAPE: [u8; 256] = [304	//   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F305	UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0306	UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1307	__, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2308	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3309	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4310	__, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5311	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6312	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7313	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8314	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9315	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A316	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B317	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C318	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D319	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E320	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F321];322323pub fn escape_string_json_buf(value: &str, buf: &mut String) {324	// Safety: we only write correct utf-8 in this function325	let buf: &mut Vec<u8> = unsafe { &mut *(buf as *mut String).cast::<Vec<u8>>() };326	let bytes = value.as_bytes();327328	// Perfect for ascii strings, removes any reallocations329	buf.reserve(value.len() + 2);330331	buf.push(b'"');332333	let mut start = 0;334335	for (i, &byte) in bytes.iter().enumerate() {336		let escape = ESCAPE[byte as usize];337		if escape == __ {338			continue;339		}340341		if start < i {342			buf.extend_from_slice(&bytes[start..i]);343		}344		start = i + 1;345346		match escape {347			self::BB | self::TT | self::NN | self::FF | self::RR | self::QU | self::BS => {348				buf.extend_from_slice(&[b'\\', escape]);349			}350			self::UU => {351				static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";352				let bytes = &[353					b'\\',354					b'u',355					b'0',356					b'0',357					HEX_DIGITS[(byte >> 4) as usize],358					HEX_DIGITS[(byte & 0xF) as usize],359				];360				buf.extend_from_slice(bytes);361			}362			_ => unreachable!(),363		}364	}365366	if start == bytes.len() {367		buf.push(b'"');368		return;369	}370371	buf.extend_from_slice(&bytes[start..]);372	buf.push(b'"');373}
deletedcrates/jrsonnet-evaluator/src/stdlib/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-evaluator/src/stdlib/manifest.rs
+++ /dev/null
@@ -1,557 +0,0 @@
-use std::{borrow::Cow, fmt::Write};
-
-use crate::{
-	error::{Error::*, Result},
-	throw, ManifestFormat, State, Val,
-};
-
-#[derive(PartialEq, Eq, Clone, Copy)]
-pub enum ManifestType {
-	// Applied in manifestification
-	Manifest,
-	/// Used for std.manifestJson
-	/// Empty array/objects extends to "[\n\n]" instead of "[ ]" as in manifest
-	Std,
-	/// No line breaks, used in `obj+''`
-	ToString,
-	/// Minified json
-	Minify,
-}
-
-pub struct JsonFormat<'s> {
-	padding: Cow<'s, str>,
-	mtype: ManifestType,
-	newline: &'s str,
-	key_val_sep: &'s str,
-	#[cfg(feature = "exp-preserve-order")]
-	preserve_order: bool,
-}
-
-impl<'s> JsonFormat<'s> {
-	// Minifying format
-	pub fn minify(#[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Self {
-		Self {
-			padding: Cow::Borrowed(""),
-			mtype: ManifestType::Minify,
-			newline: "\n",
-			key_val_sep: ":",
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order,
-		}
-	}
-	// Same format as std.toString
-	pub fn std_to_string() -> Self {
-		Self {
-			padding: Cow::Borrowed(""),
-			mtype: ManifestType::ToString,
-			newline: "\n",
-			key_val_sep: ": ",
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order: false,
-		}
-	}
-	pub fn std_to_json(
-		padding: String,
-		newline: &'s str,
-		key_val_sep: &'s str,
-		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
-	) -> Self {
-		Self {
-			padding: Cow::Owned(padding),
-			mtype: ManifestType::Std,
-			newline,
-			key_val_sep,
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order,
-		}
-	}
-	// Same format as CLI manifestification
-	pub fn cli(
-		padding: usize,
-		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
-	) -> Self {
-		if padding == 0 {
-			return Self::minify(
-				#[cfg(feature = "exp-preserve-order")]
-				preserve_order,
-			);
-		}
-		Self {
-			padding: Cow::Owned(" ".repeat(padding)),
-			mtype: ManifestType::Manifest,
-			newline: "\n",
-			key_val_sep: ": ",
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order,
-		}
-	}
-}
-impl Default for JsonFormat<'static> {
-	fn default() -> Self {
-		Self {
-			padding: Cow::Borrowed("    "),
-			mtype: ManifestType::Manifest,
-			newline: "\n",
-			key_val_sep: ": ",
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order: false,
-		}
-	}
-}
-
-pub fn manifest_json_ex(val: &Val, options: &JsonFormat<'_>) -> Result<String> {
-	let mut out = String::new();
-	manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;
-	Ok(out)
-}
-fn manifest_json_ex_buf(
-	val: &Val,
-	buf: &mut String,
-	cur_padding: &mut String,
-	options: &JsonFormat<'_>,
-) -> Result<()> {
-	let mtype = options.mtype;
-	match val {
-		Val::Bool(v) => {
-			if *v {
-				buf.push_str("true");
-			} else {
-				buf.push_str("false");
-			}
-		}
-		Val::Null => buf.push_str("null"),
-		Val::Str(s) => escape_string_json_buf(s, buf),
-		Val::Num(n) => write!(buf, "{n}").unwrap(),
-		Val::Arr(items) => {
-			buf.push('[');
-			if !items.is_empty() {
-				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {
-					buf.push_str(options.newline);
-				}
-
-				let old_len = cur_padding.len();
-				cur_padding.push_str(&options.padding);
-				for (i, item) in items.iter().enumerate() {
-					if i != 0 {
-						buf.push(',');
-						if mtype == ManifestType::ToString {
-							buf.push(' ');
-						} else if mtype != ManifestType::Minify {
-							buf.push_str(options.newline);
-						}
-					}
-					buf.push_str(cur_padding);
-					manifest_json_ex_buf(&item?, buf, cur_padding, options)?;
-				}
-				cur_padding.truncate(old_len);
-
-				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {
-					buf.push_str(options.newline);
-					buf.push_str(cur_padding);
-				}
-			} else if mtype == ManifestType::Std {
-				buf.push_str("\n\n");
-				buf.push_str(cur_padding);
-			} else if mtype == ManifestType::ToString || mtype == ManifestType::Manifest {
-				buf.push(' ');
-			}
-			buf.push(']');
-		}
-		Val::Obj(obj) => {
-			obj.run_assertions()?;
-			buf.push('{');
-			let fields = obj.fields(
-				#[cfg(feature = "exp-preserve-order")]
-				options.preserve_order,
-			);
-			if !fields.is_empty() {
-				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {
-					buf.push_str(options.newline);
-				}
-
-				let old_len = cur_padding.len();
-				cur_padding.push_str(&options.padding);
-				for (i, field) in fields.into_iter().enumerate() {
-					if i != 0 {
-						buf.push(',');
-						if mtype == ManifestType::ToString {
-							buf.push(' ');
-						} else if mtype != ManifestType::Minify {
-							buf.push_str(options.newline);
-						}
-					}
-					buf.push_str(cur_padding);
-					escape_string_json_buf(&field, buf);
-					buf.push_str(options.key_val_sep);
-					State::push_description(
-						|| format!("field <{}> manifestification", field.clone()),
-						|| {
-							let value = obj.get(field.clone())?.unwrap();
-							manifest_json_ex_buf(&value, buf, cur_padding, options)?;
-							Ok(())
-						},
-					)?;
-				}
-				cur_padding.truncate(old_len);
-
-				if mtype != ManifestType::ToString && mtype != ManifestType::Minify {
-					buf.push_str(options.newline);
-					buf.push_str(cur_padding);
-				}
-			} else if mtype == ManifestType::Std {
-				buf.push_str("\n\n");
-				buf.push_str(cur_padding);
-			} else if mtype == ManifestType::ToString || mtype == ManifestType::Manifest {
-				buf.push(' ');
-			}
-			buf.push('}');
-		}
-		Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),
-	};
-	Ok(())
-}
-
-impl ManifestFormat for JsonFormat<'_> {
-	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
-		manifest_json_ex_buf(&val, buf, &mut String::new(), &self)
-	}
-}
-
-pub struct ToStringFormat;
-impl ManifestFormat for ToStringFormat {
-	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {
-		JsonFormat::std_to_string().manifest_buf(val, out)
-	}
-}
-pub struct StringFormat;
-impl ManifestFormat for StringFormat {
-	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {
-		let Val::Str(s) = val else {
-			throw!("output should be string for string manifest format, got {}", val.value_type())
-		};
-		out.write_str(&s).unwrap();
-		Ok(())
-	}
-}
-
-pub struct YamlStreamFormat<I>(pub I);
-impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {
-	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {
-		let Val::Arr(arr) = val else {
-			throw!("output should be array for yaml stream format, got {}", val.value_type())
-		};
-		if !arr.is_empty() {
-			for v in arr.iter() {
-				let v = v?;
-				out.push_str("---\n");
-				self.0.manifest_buf(v, out)?;
-				out.push('\n');
-			}
-			out.push_str("...");
-		}
-		Ok(())
-	}
-}
-
-pub fn escape_string_json(s: &str) -> String {
-	let mut buf = String::new();
-	escape_string_json_buf(s, &mut buf);
-	buf
-}
-
-// Json string encoding was borrowed from https://github.com/serde-rs/json
-
-const BB: u8 = b'b'; // \x08
-const TT: u8 = b't'; // \x09
-const NN: u8 = b'n'; // \x0A
-const FF: u8 = b'f'; // \x0C
-const RR: u8 = b'r'; // \x0D
-const QU: u8 = b'"'; // \x22
-const BS: u8 = b'\\'; // \x5C
-const UU: u8 = b'u'; // \x00...\x1F except the ones above
-const __: u8 = 0;
-
-// Lookup table of escape sequences. A value of b'x' at index i means that byte
-// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.
-static ESCAPE: [u8; 256] = [
-	//   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F
-	UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0
-	UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1
-	__, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2
-	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3
-	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4
-	__, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5
-	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6
-	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7
-	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8
-	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9
-	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A
-	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B
-	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C
-	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D
-	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E
-	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F
-];
-
-fn escape_string_json_buf(value: &str, buf: &mut String) {
-	// Safety: we only write correct utf-8 in this function
-	let mut buf: &mut Vec<u8> = unsafe { core::mem::transmute(buf) };
-	let bytes = value.as_bytes();
-
-	// Perfect for ascii strings, removes any reallocations
-	buf.reserve(value.len() + 2);
-
-	buf.push(b'"');
-
-	let mut start = 0;
-
-	for (i, &byte) in bytes.iter().enumerate() {
-		let escape = ESCAPE[byte as usize];
-		if escape == __ {
-			continue;
-		}
-
-		if start < i {
-			buf.extend_from_slice(&bytes[start..i]);
-		}
-		start = i + 1;
-
-		match escape {
-			self::BB | self::TT | self::NN | self::FF | self::RR | self::QU | self::BS => {
-				buf.extend_from_slice(&[b'\\', escape])
-			}
-			self::UU => {
-				static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";
-				let bytes = &[
-					b'\\',
-					b'u',
-					b'0',
-					b'0',
-					HEX_DIGITS[(byte >> 4) as usize],
-					HEX_DIGITS[(byte & 0xF) as usize],
-				];
-				buf.extend_from_slice(bytes)
-			}
-			_ => unreachable!(),
-		}
-	}
-
-	if start == bytes.len() {
-		buf.push(b'"');
-		return;
-	}
-
-	buf.extend_from_slice(&bytes[start..]);
-	buf.push(b'"');
-}
-
-pub struct YamlFormat<'s> {
-	/// Padding before fields, i.e
-	/// ```yaml
-	/// a:
-	///   b:
-	/// ## <- this
-	/// ```
-	padding: Cow<'s, str>,
-	/// Padding before array elements in objects
-	/// ```yaml
-	/// a:
-	///   - 1
-	/// ## <- this
-	/// ```
-	arr_element_padding: Cow<'s, str>,
-	/// Should yaml keys appear unescaped, when possible
-	/// ```yaml
-	/// "safe_key": 1
-	/// # vs
-	/// safe_key: 1
-	/// ```
-	quote_keys: bool,
-	/// If true - then order of fields is preserved as written,
-	/// instead of sorting alphabetically
-	#[cfg(feature = "exp-preserve-order")]
-	preserve_order: bool,
-}
-impl YamlFormat<'_> {
-	pub fn cli(
-		padding: usize,
-		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
-	) -> Self {
-		let padding = " ".repeat(padding);
-		Self {
-			padding: Cow::Owned(padding.clone()),
-			arr_element_padding: Cow::Owned(padding),
-			quote_keys: false,
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order,
-		}
-	}
-	pub fn std_to_yaml(
-		indent_array_in_object: bool,
-		quote_keys: bool,
-		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
-	) -> Self {
-		Self {
-			padding: Cow::Borrowed("  "),
-			arr_element_padding: Cow::Borrowed(if indent_array_in_object { "  " } else { "" }),
-			quote_keys,
-			#[cfg(feature = "exp-preserve-order")]
-			preserve_order,
-		}
-	}
-}
-impl ManifestFormat for YamlFormat<'_> {
-	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
-		manifest_yaml_ex_buf(&val, buf, &mut String::new(), self)
-	}
-}
-
-/// From <https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289>
-/// With added date check
-fn yaml_needs_quotes(string: &str) -> bool {
-	fn need_quotes_spaces(string: &str) -> bool {
-		string.starts_with(' ') || string.ends_with(' ')
-	}
-
-	string.is_empty()
-		|| need_quotes_spaces(string)
-		|| string.starts_with(|c| matches!(c, '&' | '*' | '?' | '|' | '-' | '<' | '>' | '=' | '!' | '%' | '@'))
-		|| string.contains(|c| matches!(c, ':' | '{' | '}' | '[' | ']' | ',' | '#' | '`' | '\"' | '\'' | '\\' | '\0'..='\x06' | '\t' | '\n' | '\r' | '\x0e'..='\x1a' | '\x1c'..='\x1f'))
-		|| [
-			// http://yaml.org/type/bool.html
-			// Note: 'y', 'Y', 'n', 'N', is not quoted deliberately, as in libyaml. PyYAML also parse
-			// them as string, not booleans, although it is violating the YAML 1.1 specification.
-			// See https://github.com/dtolnay/serde-yaml/pull/83#discussion_r152628088.
-			"yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",
-			"on", "On", "ON", "off", "Off", "OFF", // http://yaml.org/type/null.html
-			"null", "Null", "NULL", "~",
-		].contains(&string)
-		|| (string.chars().all(|c| matches!(c, '0'..='9' | '-'))
-			&& string.chars().filter(|c| *c == '-').count() == 2)
-		|| string.starts_with('.')
-		|| string.starts_with("0x")
-		|| string.parse::<i64>().is_ok()
-		|| string.parse::<f64>().is_ok()
-}
-
-pub fn manifest_yaml_ex(val: &Val, options: &YamlFormat<'_>) -> Result<String> {
-	let mut out = String::new();
-	manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;
-	Ok(out)
-}
-
-#[allow(clippy::too_many_lines)]
-fn manifest_yaml_ex_buf(
-	val: &Val,
-	buf: &mut String,
-	cur_padding: &mut String,
-	options: &YamlFormat<'_>,
-) -> Result<()> {
-	match val {
-		Val::Bool(v) => {
-			if *v {
-				buf.push_str("true");
-			} else {
-				buf.push_str("false");
-			}
-		}
-		Val::Null => buf.push_str("null"),
-		Val::Str(s) => {
-			if s.is_empty() {
-				buf.push_str("\"\"");
-			} else if let Some(s) = s.strip_suffix('\n') {
-				buf.push('|');
-				for line in s.split('\n') {
-					buf.push('\n');
-					buf.push_str(cur_padding);
-					buf.push_str(&options.padding);
-					buf.push_str(line);
-				}
-			} else if !options.quote_keys && !yaml_needs_quotes(s) {
-				buf.push_str(s);
-			} else {
-				escape_string_json_buf(s, buf);
-			}
-		}
-		Val::Num(n) => write!(buf, "{}", *n).unwrap(),
-		Val::Arr(a) => {
-			if a.is_empty() {
-				buf.push_str("[]");
-			} else {
-				for (i, item) in a.iter().enumerate() {
-					if i != 0 {
-						buf.push('\n');
-						buf.push_str(cur_padding);
-					}
-					let item = item?;
-					buf.push('-');
-					match &item {
-						Val::Arr(a) if !a.is_empty() => {
-							buf.push('\n');
-							buf.push_str(cur_padding);
-							buf.push_str(&options.padding);
-						}
-						_ => buf.push(' '),
-					}
-					let extra_padding = match &item {
-						Val::Arr(a) => !a.is_empty(),
-						Val::Obj(o) => !o.is_empty(),
-						_ => false,
-					};
-					let prev_len = cur_padding.len();
-					if extra_padding {
-						cur_padding.push_str(&options.padding);
-					}
-					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;
-					cur_padding.truncate(prev_len);
-				}
-			}
-		}
-		Val::Obj(o) => {
-			if o.is_empty() {
-				buf.push_str("{}");
-			} else {
-				for (i, key) in o
-					.fields(
-						#[cfg(feature = "exp-preserve-order")]
-						options.preserve_order,
-					)
-					.iter()
-					.enumerate()
-				{
-					if i != 0 {
-						buf.push('\n');
-						buf.push_str(cur_padding);
-					}
-					if !options.quote_keys && !yaml_needs_quotes(key) {
-						buf.push_str(key);
-					} else {
-						escape_string_json_buf(key, buf);
-					}
-					buf.push(':');
-					let prev_len = cur_padding.len();
-					let item = o.get(key.clone())?.expect("field exists");
-					match &item {
-						Val::Arr(a) if !a.is_empty() => {
-							buf.push('\n');
-							buf.push_str(cur_padding);
-							buf.push_str(&options.arr_element_padding);
-							cur_padding.push_str(&options.arr_element_padding);
-						}
-						Val::Obj(o) if !o.is_empty() => {
-							buf.push('\n');
-							buf.push_str(cur_padding);
-							buf.push_str(&options.padding);
-							cur_padding.push_str(&options.padding);
-						}
-						_ => buf.push(' '),
-					}
-					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;
-					cur_padding.truncate(prev_len);
-				}
-			}
-		}
-		Val::Func(_) => throw!("tried to manifest function"),
-	}
-	Ok(())
-}
deletedcrates/jrsonnet-stdlib/src/manifest.rsdiffbeforeafterboth
--- a/crates/jrsonnet-stdlib/src/manifest.rs
+++ /dev/null
@@ -1,46 +0,0 @@
-use jrsonnet_evaluator::{
-	error::Result,
-	function::builtin,
-	stdlib::manifest::{escape_string_json, JsonFormat, YamlFormat},
-	typed::Any,
-	IStr,
-};
-
-#[builtin]
-pub fn builtin_escape_string_json(str_: IStr) -> Result<String> {
-	Ok(escape_string_json(&str_))
-}
-
-#[builtin]
-pub fn builtin_manifest_json_ex(
-	value: Any,
-	indent: IStr,
-	newline: Option<IStr>,
-	key_val_sep: Option<IStr>,
-	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
-) -> Result<String> {
-	let newline = newline.as_deref().unwrap_or("\n");
-	let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");
-	value.0.manifest(JsonFormat::std_to_json(
-		indent.to_string(),
-		newline,
-		key_val_sep,
-		#[cfg(feature = "exp-preserve-order")]
-		preserve_order.unwrap_or(false),
-	))
-}
-
-#[builtin]
-pub fn builtin_manifest_yaml_doc(
-	value: Any,
-	indent_array_in_object: Option<bool>,
-	quote_keys: Option<bool>,
-	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
-) -> Result<String> {
-	value.0.manifest(YamlFormat::std_to_yaml(
-		indent_array_in_object.unwrap_or(false),
-		quote_keys.unwrap_or(true),
-		#[cfg(feature = "exp-preserve-order")]
-		preserve_order.unwrap_or(false),
-	))
-}
addedcrates/jrsonnet-stdlib/src/manifest/mod.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/manifest/mod.rs
@@ -0,0 +1,49 @@
+mod yaml;
+
+use jrsonnet_evaluator::{
+	error::Result,
+	function::builtin,
+	manifest::{escape_string_json, JsonFormat},
+	typed::Any,
+	IStr,
+};
+pub use yaml::YamlFormat;
+
+#[builtin]
+pub fn builtin_escape_string_json(str_: IStr) -> Result<String> {
+	Ok(escape_string_json(&str_))
+}
+
+#[builtin]
+pub fn builtin_manifest_json_ex(
+	value: Any,
+	indent: IStr,
+	newline: Option<IStr>,
+	key_val_sep: Option<IStr>,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> Result<String> {
+	let newline = newline.as_deref().unwrap_or("\n");
+	let key_val_sep = key_val_sep.as_deref().unwrap_or(": ");
+	value.0.manifest(JsonFormat::std_to_json(
+		indent.to_string(),
+		newline,
+		key_val_sep,
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order.unwrap_or(false),
+	))
+}
+
+#[builtin]
+pub fn builtin_manifest_yaml_doc(
+	value: Any,
+	indent_array_in_object: Option<bool>,
+	quote_keys: Option<bool>,
+	#[cfg(feature = "exp-preserve-order")] preserve_order: Option<bool>,
+) -> Result<String> {
+	value.0.manifest(YamlFormat::std_to_yaml(
+		indent_array_in_object.unwrap_or(false),
+		quote_keys.unwrap_or(true),
+		#[cfg(feature = "exp-preserve-order")]
+		preserve_order.unwrap_or(false),
+	))
+}
addedcrates/jrsonnet-stdlib/src/manifest/yaml.rsdiffbeforeafterboth
--- /dev/null
+++ b/crates/jrsonnet-stdlib/src/manifest/yaml.rs
@@ -0,0 +1,218 @@
+use std::{borrow::Cow, fmt::Write};
+
+use jrsonnet_evaluator::{
+	manifest::{escape_string_json_buf, ManifestFormat},
+	throw, Result, Val,
+};
+
+pub struct YamlFormat<'s> {
+	/// Padding before fields, i.e
+	/// ```yaml
+	/// a:
+	///   b:
+	/// ## <- this
+	/// ```
+	padding: Cow<'s, str>,
+	/// Padding before array elements in objects
+	/// ```yaml
+	/// a:
+	///   - 1
+	/// ## <- this
+	/// ```
+	arr_element_padding: Cow<'s, str>,
+	/// Should yaml keys appear unescaped, when possible
+	/// ```yaml
+	/// "safe_key": 1
+	/// # vs
+	/// safe_key: 1
+	/// ```
+	quote_keys: bool,
+	/// If true - then order of fields is preserved as written,
+	/// instead of sorting alphabetically
+	#[cfg(feature = "exp-preserve-order")]
+	preserve_order: bool,
+}
+impl YamlFormat<'_> {
+	pub fn cli(
+		padding: usize,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> Self {
+		let padding = " ".repeat(padding);
+		Self {
+			padding: Cow::Owned(padding.clone()),
+			arr_element_padding: Cow::Owned(padding),
+			quote_keys: false,
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order,
+		}
+	}
+	pub fn std_to_yaml(
+		indent_array_in_object: bool,
+		quote_keys: bool,
+		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,
+	) -> Self {
+		Self {
+			padding: Cow::Borrowed("  "),
+			arr_element_padding: Cow::Borrowed(if indent_array_in_object { "  " } else { "" }),
+			quote_keys,
+			#[cfg(feature = "exp-preserve-order")]
+			preserve_order,
+		}
+	}
+}
+impl ManifestFormat for YamlFormat<'_> {
+	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {
+		manifest_yaml_ex_buf(&val, buf, &mut String::new(), self)
+	}
+}
+
+/// From <https://github.com/chyh1990/yaml-rust/blob/da52a68615f2ecdd6b7e4567019f280c433c1521/src/emitter.rs#L289>
+/// With added date check
+fn yaml_needs_quotes(string: &str) -> bool {
+	fn need_quotes_spaces(string: &str) -> bool {
+		string.starts_with(' ') || string.ends_with(' ')
+	}
+
+	string.is_empty()
+		|| need_quotes_spaces(string)
+		|| string.starts_with(|c| matches!(c, '&' | '*' | '?' | '|' | '-' | '<' | '>' | '=' | '!' | '%' | '@'))
+		|| string.contains(|c| matches!(c, ':' | '{' | '}' | '[' | ']' | ',' | '#' | '`' | '\"' | '\'' | '\\' | '\0'..='\x06' | '\t' | '\n' | '\r' | '\x0e'..='\x1a' | '\x1c'..='\x1f'))
+		|| [
+			// http://yaml.org/type/bool.html
+			// Note: 'y', 'Y', 'n', 'N', is not quoted deliberately, as in libyaml. PyYAML also parse
+			// them as string, not booleans, although it is violating the YAML 1.1 specification.
+			// See https://github.com/dtolnay/serde-yaml/pull/83#discussion_r152628088.
+			"yes", "Yes", "YES", "no", "No", "NO", "True", "TRUE", "true", "False", "FALSE", "false",
+			"on", "On", "ON", "off", "Off", "OFF", // http://yaml.org/type/null.html
+			"null", "Null", "NULL", "~",
+		].contains(&string)
+		|| (string.chars().all(|c| matches!(c, '0'..='9' | '-'))
+			&& string.chars().filter(|c| *c == '-').count() == 2)
+		|| string.starts_with('.')
+		|| string.starts_with("0x")
+		|| string.parse::<i64>().is_ok()
+		|| string.parse::<f64>().is_ok()
+}
+
+#[allow(dead_code)]
+fn manifest_yaml_ex(val: &Val, options: &YamlFormat<'_>) -> Result<String> {
+	let mut out = String::new();
+	manifest_yaml_ex_buf(val, &mut out, &mut String::new(), options)?;
+	Ok(out)
+}
+
+#[allow(clippy::too_many_lines)]
+fn manifest_yaml_ex_buf(
+	val: &Val,
+	buf: &mut String,
+	cur_padding: &mut String,
+	options: &YamlFormat<'_>,
+) -> Result<()> {
+	match val {
+		Val::Bool(v) => {
+			if *v {
+				buf.push_str("true");
+			} else {
+				buf.push_str("false");
+			}
+		}
+		Val::Null => buf.push_str("null"),
+		Val::Str(s) => {
+			if s.is_empty() {
+				buf.push_str("\"\"");
+			} else if let Some(s) = s.strip_suffix('\n') {
+				buf.push('|');
+				for line in s.split('\n') {
+					buf.push('\n');
+					buf.push_str(cur_padding);
+					buf.push_str(&options.padding);
+					buf.push_str(line);
+				}
+			} else if !options.quote_keys && !yaml_needs_quotes(s) {
+				buf.push_str(s);
+			} else {
+				escape_string_json_buf(s, buf);
+			}
+		}
+		Val::Num(n) => write!(buf, "{}", *n).unwrap(),
+		Val::Arr(a) => {
+			if a.is_empty() {
+				buf.push_str("[]");
+			} else {
+				for (i, item) in a.iter().enumerate() {
+					if i != 0 {
+						buf.push('\n');
+						buf.push_str(cur_padding);
+					}
+					let item = item?;
+					buf.push('-');
+					match &item {
+						Val::Arr(a) if !a.is_empty() => {
+							buf.push('\n');
+							buf.push_str(cur_padding);
+							buf.push_str(&options.padding);
+						}
+						_ => buf.push(' '),
+					}
+					let extra_padding = match &item {
+						Val::Arr(a) => !a.is_empty(),
+						Val::Obj(o) => !o.is_empty(),
+						_ => false,
+					};
+					let prev_len = cur_padding.len();
+					if extra_padding {
+						cur_padding.push_str(&options.padding);
+					}
+					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;
+					cur_padding.truncate(prev_len);
+				}
+			}
+		}
+		Val::Obj(o) => {
+			if o.is_empty() {
+				buf.push_str("{}");
+			} else {
+				for (i, key) in o
+					.fields(
+						#[cfg(feature = "exp-preserve-order")]
+						options.preserve_order,
+					)
+					.iter()
+					.enumerate()
+				{
+					if i != 0 {
+						buf.push('\n');
+						buf.push_str(cur_padding);
+					}
+					if !options.quote_keys && !yaml_needs_quotes(key) {
+						buf.push_str(key);
+					} else {
+						escape_string_json_buf(key, buf);
+					}
+					buf.push(':');
+					let prev_len = cur_padding.len();
+					let item = o.get(key.clone())?.expect("field exists");
+					match &item {
+						Val::Arr(a) if !a.is_empty() => {
+							buf.push('\n');
+							buf.push_str(cur_padding);
+							buf.push_str(&options.arr_element_padding);
+							cur_padding.push_str(&options.arr_element_padding);
+						}
+						Val::Obj(o) if !o.is_empty() => {
+							buf.push('\n');
+							buf.push_str(cur_padding);
+							buf.push_str(&options.padding);
+							cur_padding.push_str(&options.padding);
+						}
+						_ => buf.push(' '),
+					}
+					manifest_yaml_ex_buf(&item, buf, cur_padding, options)?;
+					cur_padding.truncate(prev_len);
+				}
+			}
+		}
+		Val::Func(_) => throw!("tried to manifest function"),
+	}
+	Ok(())
+}