print unprintable characters as \u escapes

This commit is contained in:
Daniel Barlow 2022-09-16 15:50:45 +01:00
parent a78cba0a3f
commit 429a661346
1 changed files with 10 additions and 7 deletions

17
sms.fnl
View File

@ -20,12 +20,12 @@
(test= (+ 5 4) 9)
(fn escape-for-logging [s]
(s:gsub "%c" (fn [x] (.. "{" (string.byte x) "}"))))
(fn escape-readably [s]
(s:gsub "%c" (fn [x] (string.format "\\u{%.3x}" (string.byte x)))))
(fn tx [fd s]
(write fd s)
(print (.. ">>> " (escape-for-logging s)))
(print (.. ">>> " (escape-readably s)))
(nanosleep {:tv_sec 0 :tv_nsec (* 10 1000 1000)}))
(fn chars [i]
@ -38,18 +38,21 @@
(fn unicode->gsm [s]
(s:gsub "." (fn [c] (chars (. gsm-char (string.byte c))))))
;(print (escape-for-logging (unicode-to-gsm "hello")))
;(print (escape-for-logging (unicode-to-gsm "{he@llo}€")))
(test= (unicode->gsm "abc123") "abc123")
(test= (unicode->gsm "abc{123}") "abc\x1b(123\x1b)")
;(print (escape-readably(unicode-to-gsm "hello")))
;(print (escape-readably(unicode-to-gsm "{he@llo}€")))
(fn expect [fd pattern fail-pattern]
(let [b (read fd 1024)]
(if (> (# b) 0)
(do
(print (.. "<<< " (escape-for-logging b)))
(print (.. "<<< " (escape-readably b)))
(if (string.find b pattern)
(do (print "found" pattern) true)
(and fail-pattern (string.find b fail-pattern))
(error (.. "Expected " pattern ", got " (escape-for-logging b)))
(error (.. "Expected " pattern ", got " (escape-readably b)))
(expect fd pattern)))
nil)))