escape-strings: Add a way to find minmal escapes for a lua/magic

string.
modern-harvey2
Doug Coleman 2017-09-16 17:21:31 -05:00
parent 722a335b68
commit 9ef9cae60f
3 changed files with 36 additions and 0 deletions

View File

@ -0,0 +1,2 @@
John Benediktsson
Doug Coleman

View File

@ -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

View File

@ -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: = <repetition>
[ "[" dup surround ] [ "]" dup surround ] bi surround
] [
"[[" "]]" surround
] if ;