From 9ef9cae60fe45ad0aff3f4b294d7f4e89266d4d9 Mon Sep 17 00:00:00 2001 From: Doug Coleman Date: Sat, 16 Sep 2017 17:21:31 -0500 Subject: [PATCH] escape-strings: Add a way to find minmal escapes for a lua/magic string. --- basis/escape-strings/authors.txt | 2 ++ .../escape-strings-tests.factor | 12 ++++++++++ basis/escape-strings/escape-strings.factor | 22 +++++++++++++++++++ 3 files changed, 36 insertions(+) create mode 100644 basis/escape-strings/authors.txt create mode 100644 basis/escape-strings/escape-strings-tests.factor create mode 100644 basis/escape-strings/escape-strings.factor diff --git a/basis/escape-strings/authors.txt b/basis/escape-strings/authors.txt new file mode 100644 index 0000000000..dbe8e57c80 --- /dev/null +++ b/basis/escape-strings/authors.txt @@ -0,0 +1,2 @@ +John Benediktsson +Doug Coleman diff --git a/basis/escape-strings/escape-strings-tests.factor b/basis/escape-strings/escape-strings-tests.factor new file mode 100644 index 0000000000..4aa82f8242 --- /dev/null +++ b/basis/escape-strings/escape-strings-tests.factor @@ -0,0 +1,12 @@ +! Copyright (C) 2017 John Benediktsson, Doug Coleman. +! See http://factorcode.org/license.txt for BSD license. +USING: tools.test escape-strings ; +IN: escape-strings.tests + +{ "[[asdf]]" } [ "asdf" escape-string ] unit-test +{ "[[[[]]" } [ "[[" escape-string ] unit-test +{ "[=[]]]=]" } [ "]]" escape-string ] unit-test + +{ "[===[]]]==][=[=]=]]===]" } [ "]]]==][=[=]=]" escape-string ] unit-test +{ "[[[=[=]=]]]" } [ "[=[=]=]" escape-string ] unit-test +{ "[[[a[]]" } [ "[a[" escape-string ] unit-test diff --git a/basis/escape-strings/escape-strings.factor b/basis/escape-strings/escape-strings.factor new file mode 100644 index 0000000000..1140100dbf --- /dev/null +++ b/basis/escape-strings/escape-strings.factor @@ -0,0 +1,22 @@ +! Copyright (C) 2017 John Benediktsson, Doug Coleman. +! See http://factorcode.org/license.txt for BSD license. +USING: combinators kernel math math.order sequences ; +IN: escape-strings + +! TODO: Move the "]]" subseq? check into the each loop logic +: #escapes ( str -- n/f ) + [ f f f ] dip [ + { + { char: = [ [ dup [ 1 + ] when ] bi@ ] } + { char: ] [ [ [ 0 or ] 2dip [ max ] curry dip ] when* 0 ] } + [ 2drop f ] + } case + ] each 2drop ; + +: escape-string ( str -- str' ) + "]]" over subseq? [ + dup #escapes ?1+ char: = + [ "[" dup surround ] [ "]" dup surround ] bi surround + ] [ + "[[" "]]" surround + ] if ; \ No newline at end of file