Skip to content

Commit

Permalink
Merge pull request #53 from ergochat/multiescape
Browse files Browse the repository at this point in the history
accept multiple hex escapes in the same [[]] block
  • Loading branch information
slingamn authored Sep 15, 2024
2 parents 8329134 + 112722a commit 76abc56
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 6 deletions.
4 changes: 4 additions & 0 deletions lib/strings_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ var replacementTestCases = []stringTestCase{
{`www[[\x0D]]`, "www\x0d"},
{`www[[\xff]]`, "www\xff"},
{`www[[\xFF]]`, "www\xff"},
{`www[[\xFF\x00]]`, "www\xff\x00"},
{`www[[\xFF\x00\x01]]01`, "www\xff\x00\x0101"},
{`www[[\xaa\xBB\xcc\x35]]01`, "www\xaa\xbb\xcc\x3501"},
{`www[[\xzz]]`, "www[[\\xzz]]"}, // invalid hex is not an escape
{`[[notanescape]]`, "[[notanescape]]"},
{`[[[U]]]`, "[\x1f]"},
}
Expand Down
16 changes: 10 additions & 6 deletions lib/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ import (

var (
// e.g., [[\x00]] for \x00, [[\xFF]] or [[\xff]] for \xff
hexEscapeRegex = regexp.MustCompile(`^\[\[\\x[0-9a-fA-F]{2}\]\]`)
// multiple escapes are accepted within the same block, e.g. [[\x00\x01\x03]]
hexEscapeRegex = regexp.MustCompile(`^\[\[(\\x[0-9a-fA-F]{2})+\]\]`)
)

var controlCodeReplacements = []struct {
Expand Down Expand Up @@ -49,12 +50,15 @@ LineLoop:
continue LineLoop
}
}
if hexEscapeRegex.MatchString(line) {
if val, err := strconv.ParseUint(strings.ToLower(line[4:6]), 16, 8); err == nil {
buf.WriteByte(byte(val))
line = line[8:]
continue LineLoop
if matched := hexEscapeRegex.FindString(line); matched != "" {
// [[\x01\x02]]
for i := 2; i < len(matched)-2; i += 4 {
if val, err := strconv.ParseUint(line[i+2:i+4], 16, 8); err == nil {
buf.WriteByte(byte(val))
}
}
line = line[len(matched):]
continue LineLoop
}
}
buf.WriteByte(line[0])
Expand Down

0 comments on commit 76abc56

Please sign in to comment.