From 487a002c6387b95fc65aeb4a056ef208cba7a72b Mon Sep 17 00:00:00 2001 From: Mikael Voss Date: Fri, 18 Apr 2025 13:41:53 +0200 Subject: [PATCH] =?UTF-8?q?lib/strings:=20Zero=E2=80=90pad=20hex=20digits?= =?UTF-8?q?=20in=20escapeC?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit lib.strings.escapeC produces single‐digit hexadecimal strings for character values ≤ 15, which results in an ambiguity. If the following character is a hex digit, it will be interpreted as being part of the escape sequence. systemd, which also relies on C‐style escape sequences, does not decode single‐digit sequences at all, even if unambiguous. Padding the hexadecimal string with "0" avoids this problem. --- lib/strings.nix | 6 +++++- lib/tests/misc.nix | 4 ++-- 2 files changed, 7 insertions(+), 3 deletions(-) diff --git a/lib/strings.nix b/lib/strings.nix index f8b01ec1ebc5..7142a156e393 100644 --- a/lib/strings.nix +++ b/lib/strings.nix @@ -998,7 +998,11 @@ rec { ::: */ - escapeC = list: replaceStrings list (map (c: "\\x${toLower (lib.toHexString (charToInt c))}") list); + escapeC = + list: + replaceStrings list ( + map (c: "\\x${fixedWidthString 2 "0" (toLower (lib.toHexString (charToInt c)))}") list + ); /** Escape the `string` so it can be safely placed inside a URL diff --git a/lib/tests/misc.nix b/lib/tests/misc.nix index d17231061d69..b072f058d727 100644 --- a/lib/tests/misc.nix +++ b/lib/tests/misc.nix @@ -851,8 +851,8 @@ runTests { }; testEscapeC = { - expr = strings.escapeC [ " " ] "Hello World"; - expected = "Hello\\x20World"; + expr = strings.escapeC [ "\n" " " ] "Hello World\n"; + expected = "Hello\\x20World\\x0a"; }; testEscapeURL = testAllTrue [