Skip to content

Instantly share code, notes, and snippets.

@ivan
Last active January 17, 2022 02:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivan/b8011be402f506d40e82372a82f6768e to your computer and use it in GitHub Desktop.
Save ivan/b8011be402f506d40e82372a82f6768e to your computer and use it in GitHub Desktop.
/**
* A wrapper to work around otherwise not being able to mutate caller's string.
*/
class WrappedValue {
constructor(public val: any) {}
}
function strip_out_nuls_(wrapped: WrappedValue): number {
let had_nul = 0;
const val = wrapped.val;
if (typeof val === "string" && val.includes("\u0000")) {
wrapped.val = val.replaceAll("\u0000", "");
had_nul = 1;
} else if (typeof val === "object" && val !== null) {
for (const [key, obj_val] of Object.entries(val)) {
const wrapped = new WrappedValue(obj_val);
had_nul |= strip_out_nuls_(wrapped);
(val as any)[key] = wrapped.val;
}
} else if (Array.isArray(val)) {
for (let idx = 0; idx < val.length; idx++) {
const wrapped = new WrappedValue(val[idx]);
had_nul |= strip_out_nuls_(wrapped);
val[idx] = wrapped.val;
}
}
return had_nul;
}
// Recursively walk a deserialized JSON object and replace strings (except object keys)
// to strip out all NUL characters. Returns `true` if any NUL was removed.
function strip_out_nuls(val: any): boolean {
return Boolean(strip_out_nuls_(new WrappedValue(val)));
}
{
let obj = {"hello": 3, "world": ["val\u0000thing", "\u0000", {"hello": "\u0000\u0000"}]};
console.log(obj);
let had_nul = strip_out_nuls(obj);
console.log(had_nul, obj);
}
{
let obj = {"hello": 3};
console.log(obj);
let had_nul = strip_out_nuls(obj);
console.log(had_nul, obj);
}
@ivan
Copy link
Author

ivan commented Jan 17, 2022

Improvements or rewrites welcome

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment