Last active
January 17, 2022 02:47
-
-
Save ivan/b8011be402f506d40e82372a82f6768e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* 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); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Improvements or rewrites welcome