git.delta.rocks / jrsonnet / refs/commits / 4be0ffe86b04

difftreelog

fix do not write trailing newline in --multi for -S

Yaroslav Bolyukin2023-05-04parent: #c2bc5cc.patch.diff
in: master

2 files changed

modifiedcmds/jrsonnet/src/main.rsdiffbeforeafterboth
--- a/cmds/jrsonnet/src/main.rs
+++ b/cmds/jrsonnet/src/main.rs
@@ -200,12 +200,16 @@
 			}
 			println!("{}", path.to_str().expect("path"));
 			let mut file = File::create(path)?;
-			writeln!(
+			write!(
 				file,
 				"{}",
 				data.manifest(&manifest_format)
-					.with_description(|| format!("manifesting {field}"))?
+					.with_description(|| format!("manifesting {field}"))?,
 			)?;
+			if manifest_format.file_trailing_newline() {
+				writeln!(file)?;
+			}
+			file.flush()?;
 		}
 	} else if let Some(path) = opts.output.output_file {
 		if opts.output.create_output_dirs {
modifiedcrates/jrsonnet-evaluator/src/manifest.rsdiffbeforeafterboth
before · 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.clone().into_flat(), buf),151		Val::Num(n) => write!(buf, "{n}").unwrap(),152		#[cfg(feature = "exp-bigint")]153		Val::BigInt(n) => write!(buf, "{n}").unwrap(),154		Val::Arr(items) => {155			buf.push('[');156			if !items.is_empty() {157				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {158					buf.push_str(options.newline);159				}160161				let old_len = cur_padding.len();162				cur_padding.push_str(&options.padding);163				for (i, item) in items.iter().enumerate() {164					if i != 0 {165						buf.push(',');166						if mtype == JsonFormatting::ToString {167							buf.push(' ');168						} else if mtype != JsonFormatting::Minify {169							buf.push_str(options.newline);170						}171					}172					buf.push_str(cur_padding);173					manifest_json_ex_buf(&item?, buf, cur_padding, options)?;174				}175				cur_padding.truncate(old_len);176177				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {178					buf.push_str(options.newline);179					buf.push_str(cur_padding);180				}181			} else if mtype == JsonFormatting::Std {182				buf.push_str(options.newline);183				buf.push_str(options.newline);184				buf.push_str(cur_padding);185			} else if mtype == JsonFormatting::ToString || mtype == JsonFormatting::Manifest {186				buf.push(' ');187			}188			buf.push(']');189		}190		Val::Obj(obj) => {191			obj.run_assertions()?;192			buf.push('{');193			let fields = obj.fields(194				#[cfg(feature = "exp-preserve-order")]195				options.preserve_order,196			);197			if !fields.is_empty() {198				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {199					buf.push_str(options.newline);200				}201202				let old_len = cur_padding.len();203				cur_padding.push_str(&options.padding);204				for (i, field) in fields.into_iter().enumerate() {205					if i != 0 {206						buf.push(',');207						if mtype == JsonFormatting::ToString {208							buf.push(' ');209						} else if mtype != JsonFormatting::Minify {210							buf.push_str(options.newline);211						}212					}213					buf.push_str(cur_padding);214					escape_string_json_buf(&field, buf);215					buf.push_str(options.key_val_sep);216					State::push_description(217						|| format!("field <{}> manifestification", field.clone()),218						|| {219							let value = obj.get(field.clone())?.unwrap();220							manifest_json_ex_buf(&value, buf, cur_padding, options)?;221							Ok(())222						},223					)?;224				}225				cur_padding.truncate(old_len);226227				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {228					buf.push_str(options.newline);229					buf.push_str(cur_padding);230				}231			} else if mtype == JsonFormatting::Std {232				buf.push_str(options.newline);233				buf.push_str(options.newline);234				buf.push_str(cur_padding);235			} else if mtype == JsonFormatting::ToString || mtype == JsonFormatting::Manifest {236				buf.push(' ');237			}238			buf.push('}');239		}240		Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),241	};242	Ok(())243}244245impl ManifestFormat for JsonFormat<'_> {246	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {247		manifest_json_ex_buf(&val, buf, &mut String::new(), self)248	}249}250251pub struct ToStringFormat;252impl ManifestFormat for ToStringFormat {253	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {254		JsonFormat::std_to_string().manifest_buf(val, out)255	}256}257pub struct StringFormat;258impl ManifestFormat for StringFormat {259	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {260		let Val::Str(s) = val else {261			throw!("output should be string for string manifest format, got {}", val.value_type())262		};263		write!(out, "{s}").unwrap();264		Ok(())265	}266}267268pub struct YamlStreamFormat<I>(pub I);269impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {270	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {271		let Val::Arr(arr) = val else {272			throw!("output should be array for yaml stream format, got {}", val.value_type())273		};274		if !arr.is_empty() {275			for v in arr.iter() {276				let v = v?;277				out.push_str("---\n");278				self.0.manifest_buf(v, out)?;279				out.push('\n');280			}281			out.push_str("...");282		}283		Ok(())284	}285}286287pub fn escape_string_json(s: &str) -> String {288	let mut buf = String::new();289	escape_string_json_buf(s, &mut buf);290	buf291}292293// Json string encoding was borrowed from https://github.com/serde-rs/json294295const BB: u8 = b'b'; // \x08296const TT: u8 = b't'; // \x09297const NN: u8 = b'n'; // \x0A298const FF: u8 = b'f'; // \x0C299const RR: u8 = b'r'; // \x0D300const QU: u8 = b'"'; // \x22301const BS: u8 = b'\\'; // \x5C302const UU: u8 = b'u'; // \x00...\x1F except the ones above303const __: u8 = 0;304305// Lookup table of escape sequences. A value of b'x' at index i means that byte306// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.307static ESCAPE: [u8; 256] = [308	//   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F309	UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0310	UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1311	__, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2312	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3313	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4314	__, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5315	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6316	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7317	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8318	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9319	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A320	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B321	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C322	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D323	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E324	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F325];326327pub fn escape_string_json_buf(value: &str, buf: &mut String) {328	// Safety: we only write correct utf-8 in this function329	let buf: &mut Vec<u8> = unsafe { &mut *(buf as *mut String).cast::<Vec<u8>>() };330	let bytes = value.as_bytes();331332	// Perfect for ascii strings, removes any reallocations333	buf.reserve(value.len() + 2);334335	buf.push(b'"');336337	let mut start = 0;338339	for (i, &byte) in bytes.iter().enumerate() {340		let escape = ESCAPE[byte as usize];341		if escape == __ {342			continue;343		}344345		if start < i {346			buf.extend_from_slice(&bytes[start..i]);347		}348		start = i + 1;349350		match escape {351			self::BB | self::TT | self::NN | self::FF | self::RR | self::QU | self::BS => {352				buf.extend_from_slice(&[b'\\', escape]);353			}354			self::UU => {355				static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";356				let bytes = &[357					b'\\',358					b'u',359					b'0',360					b'0',361					HEX_DIGITS[(byte >> 4) as usize],362					HEX_DIGITS[(byte & 0xF) as usize],363				];364				buf.extend_from_slice(bytes);365			}366			_ => unreachable!(),367		}368	}369370	if start == bytes.len() {371		buf.push(b'"');372		return;373	}374375	buf.extend_from_slice(&bytes[start..]);376	buf.push(b'"');377}
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	/// When outputing to file, is it safe to append a trailing newline (I.e newline won't change16	/// the meaning).17	///18	/// Default implementation returns `true`19	fn file_trailing_newline(&self) -> bool {20		true21	}22}23impl<T> ManifestFormat for Box<T>24where25	T: ManifestFormat + ?Sized,26{27	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {28		let inner = &**self;29		inner.manifest_buf(val, buf)30	}31	fn file_trailing_newline(&self) -> bool {32		let inner = &**self;33		inner.file_trailing_newline()34	}35}36impl<T> ManifestFormat for &'_ T37where38	T: ManifestFormat + ?Sized,39{40	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {41		let inner = &**self;42		inner.manifest_buf(val, buf)43	}44	fn file_trailing_newline(&self) -> bool {45		let inner = &**self;46		inner.file_trailing_newline()47	}48}4950#[derive(PartialEq, Eq, Clone, Copy)]51enum JsonFormatting {52	// Applied in manifestification53	Manifest,54	/// Used for std.manifestJson55	/// Empty array/objects extends to "[\n\n]" instead of "[ ]" as in manifest56	Std,57	/// No line breaks, used in `obj+''`58	ToString,59	/// Minified json60	Minify,61}6263pub struct JsonFormat<'s> {64	padding: Cow<'s, str>,65	mtype: JsonFormatting,66	newline: &'s str,67	key_val_sep: &'s str,68	#[cfg(feature = "exp-preserve-order")]69	preserve_order: bool,70}7172impl<'s> JsonFormat<'s> {73	// Minifying format74	pub fn minify(#[cfg(feature = "exp-preserve-order")] preserve_order: bool) -> Self {75		Self {76			padding: Cow::Borrowed(""),77			mtype: JsonFormatting::Minify,78			newline: "\n",79			key_val_sep: ":",80			#[cfg(feature = "exp-preserve-order")]81			preserve_order,82		}83	}84	// Same format as std.toString85	pub fn std_to_string() -> Self {86		Self {87			padding: Cow::Borrowed(""),88			mtype: JsonFormatting::ToString,89			newline: "\n",90			key_val_sep: ": ",91			#[cfg(feature = "exp-preserve-order")]92			preserve_order: false,93		}94	}95	pub fn std_to_json(96		padding: String,97		newline: &'s str,98		key_val_sep: &'s str,99		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,100	) -> Self {101		Self {102			padding: Cow::Owned(padding),103			mtype: JsonFormatting::Std,104			newline,105			key_val_sep,106			#[cfg(feature = "exp-preserve-order")]107			preserve_order,108		}109	}110	// Same format as CLI manifestification111	pub fn cli(112		padding: usize,113		#[cfg(feature = "exp-preserve-order")] preserve_order: bool,114	) -> Self {115		if padding == 0 {116			return Self::minify(117				#[cfg(feature = "exp-preserve-order")]118				preserve_order,119			);120		}121		Self {122			padding: Cow::Owned(" ".repeat(padding)),123			mtype: JsonFormatting::Manifest,124			newline: "\n",125			key_val_sep: ": ",126			#[cfg(feature = "exp-preserve-order")]127			preserve_order,128		}129	}130}131impl Default for JsonFormat<'static> {132	fn default() -> Self {133		Self {134			padding: Cow::Borrowed("    "),135			mtype: JsonFormatting::Manifest,136			newline: "\n",137			key_val_sep: ": ",138			#[cfg(feature = "exp-preserve-order")]139			preserve_order: false,140		}141	}142}143144pub fn manifest_json_ex(val: &Val, options: &JsonFormat<'_>) -> Result<String> {145	let mut out = String::new();146	manifest_json_ex_buf(val, &mut out, &mut String::new(), options)?;147	Ok(out)148}149fn manifest_json_ex_buf(150	val: &Val,151	buf: &mut String,152	cur_padding: &mut String,153	options: &JsonFormat<'_>,154) -> Result<()> {155	let mtype = options.mtype;156	match val {157		Val::Bool(v) => {158			if *v {159				buf.push_str("true");160			} else {161				buf.push_str("false");162			}163		}164		Val::Null => buf.push_str("null"),165		Val::Str(s) => escape_string_json_buf(&s.clone().into_flat(), buf),166		Val::Num(n) => write!(buf, "{n}").unwrap(),167		#[cfg(feature = "exp-bigint")]168		Val::BigInt(n) => write!(buf, "{n}").unwrap(),169		Val::Arr(items) => {170			buf.push('[');171			if !items.is_empty() {172				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {173					buf.push_str(options.newline);174				}175176				let old_len = cur_padding.len();177				cur_padding.push_str(&options.padding);178				for (i, item) in items.iter().enumerate() {179					if i != 0 {180						buf.push(',');181						if mtype == JsonFormatting::ToString {182							buf.push(' ');183						} else if mtype != JsonFormatting::Minify {184							buf.push_str(options.newline);185						}186					}187					buf.push_str(cur_padding);188					manifest_json_ex_buf(&item?, buf, cur_padding, options)?;189				}190				cur_padding.truncate(old_len);191192				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {193					buf.push_str(options.newline);194					buf.push_str(cur_padding);195				}196			} else if mtype == JsonFormatting::Std {197				buf.push_str(options.newline);198				buf.push_str(options.newline);199				buf.push_str(cur_padding);200			} else if mtype == JsonFormatting::ToString || mtype == JsonFormatting::Manifest {201				buf.push(' ');202			}203			buf.push(']');204		}205		Val::Obj(obj) => {206			obj.run_assertions()?;207			buf.push('{');208			let fields = obj.fields(209				#[cfg(feature = "exp-preserve-order")]210				options.preserve_order,211			);212			if !fields.is_empty() {213				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {214					buf.push_str(options.newline);215				}216217				let old_len = cur_padding.len();218				cur_padding.push_str(&options.padding);219				for (i, field) in fields.into_iter().enumerate() {220					if i != 0 {221						buf.push(',');222						if mtype == JsonFormatting::ToString {223							buf.push(' ');224						} else if mtype != JsonFormatting::Minify {225							buf.push_str(options.newline);226						}227					}228					buf.push_str(cur_padding);229					escape_string_json_buf(&field, buf);230					buf.push_str(options.key_val_sep);231					State::push_description(232						|| format!("field <{}> manifestification", field.clone()),233						|| {234							let value = obj.get(field.clone())?.unwrap();235							manifest_json_ex_buf(&value, buf, cur_padding, options)?;236							Ok(())237						},238					)?;239				}240				cur_padding.truncate(old_len);241242				if mtype != JsonFormatting::ToString && mtype != JsonFormatting::Minify {243					buf.push_str(options.newline);244					buf.push_str(cur_padding);245				}246			} else if mtype == JsonFormatting::Std {247				buf.push_str(options.newline);248				buf.push_str(options.newline);249				buf.push_str(cur_padding);250			} else if mtype == JsonFormatting::ToString || mtype == JsonFormatting::Manifest {251				buf.push(' ');252			}253			buf.push('}');254		}255		Val::Func(_) => throw!(RuntimeError("tried to manifest function".into())),256	};257	Ok(())258}259260impl ManifestFormat for JsonFormat<'_> {261	fn manifest_buf(&self, val: Val, buf: &mut String) -> Result<()> {262		manifest_json_ex_buf(&val, buf, &mut String::new(), self)263	}264}265266pub struct ToStringFormat;267impl ManifestFormat for ToStringFormat {268	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {269		JsonFormat::std_to_string().manifest_buf(val, out)270	}271	fn file_trailing_newline(&self) -> bool {272		false273	}274}275pub struct StringFormat;276impl ManifestFormat for StringFormat {277	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {278		let Val::Str(s) = val else {279			throw!("output should be string for string manifest format, got {}", val.value_type())280		};281		write!(out, "{s}").unwrap();282		Ok(())283	}284	fn file_trailing_newline(&self) -> bool {285		false286	}287}288289pub struct YamlStreamFormat<I>(pub I);290impl<I: ManifestFormat> ManifestFormat for YamlStreamFormat<I> {291	fn manifest_buf(&self, val: Val, out: &mut String) -> Result<()> {292		let Val::Arr(arr) = val else {293			throw!("output should be array for yaml stream format, got {}", val.value_type())294		};295		if !arr.is_empty() {296			for v in arr.iter() {297				let v = v?;298				out.push_str("---\n");299				self.0.manifest_buf(v, out)?;300				out.push('\n');301			}302			out.push_str("...");303		}304		Ok(())305	}306}307308pub fn escape_string_json(s: &str) -> String {309	let mut buf = String::new();310	escape_string_json_buf(s, &mut buf);311	buf312}313314// Json string encoding was borrowed from https://github.com/serde-rs/json315316const BB: u8 = b'b'; // \x08317const TT: u8 = b't'; // \x09318const NN: u8 = b'n'; // \x0A319const FF: u8 = b'f'; // \x0C320const RR: u8 = b'r'; // \x0D321const QU: u8 = b'"'; // \x22322const BS: u8 = b'\\'; // \x5C323const UU: u8 = b'u'; // \x00...\x1F except the ones above324const __: u8 = 0;325326// Lookup table of escape sequences. A value of b'x' at index i means that byte327// i is escaped as "\x" in JSON. A value of 0 means that byte i is not escaped.328static ESCAPE: [u8; 256] = [329	//   1   2   3   4   5   6   7   8   9   A   B   C   D   E   F330	UU, UU, UU, UU, UU, UU, UU, UU, BB, TT, NN, UU, FF, RR, UU, UU, // 0331	UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, UU, // 1332	__, __, QU, __, __, __, __, __, __, __, __, __, __, __, __, __, // 2333	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 3334	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 4335	__, __, __, __, __, __, __, __, __, __, __, __, BS, __, __, __, // 5336	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 6337	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 7338	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 8339	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // 9340	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // A341	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // B342	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // C343	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // D344	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // E345	__, __, __, __, __, __, __, __, __, __, __, __, __, __, __, __, // F346];347348pub fn escape_string_json_buf(value: &str, buf: &mut String) {349	// Safety: we only write correct utf-8 in this function350	let buf: &mut Vec<u8> = unsafe { &mut *(buf as *mut String).cast::<Vec<u8>>() };351	let bytes = value.as_bytes();352353	// Perfect for ascii strings, removes any reallocations354	buf.reserve(value.len() + 2);355356	buf.push(b'"');357358	let mut start = 0;359360	for (i, &byte) in bytes.iter().enumerate() {361		let escape = ESCAPE[byte as usize];362		if escape == __ {363			continue;364		}365366		if start < i {367			buf.extend_from_slice(&bytes[start..i]);368		}369		start = i + 1;370371		match escape {372			self::BB | self::TT | self::NN | self::FF | self::RR | self::QU | self::BS => {373				buf.extend_from_slice(&[b'\\', escape]);374			}375			self::UU => {376				static HEX_DIGITS: [u8; 16] = *b"0123456789abcdef";377				let bytes = &[378					b'\\',379					b'u',380					b'0',381					b'0',382					HEX_DIGITS[(byte >> 4) as usize],383					HEX_DIGITS[(byte & 0xF) as usize],384				];385				buf.extend_from_slice(bytes);386			}387			_ => unreachable!(),388		}389	}390391	if start == bytes.len() {392		buf.push(b'"');393		return;394	}395396	buf.extend_from_slice(&bytes[start..]);397	buf.push(b'"');398}