From 0136a5a38ded76bbdfc70b7dc0bbc25308d5fad2 Mon Sep 17 00:00:00 2001 From: Daniil Gentili Date: Fri, 26 May 2023 23:31:07 +0200 Subject: [PATCH] Fix slice on multiline strings --- filters/standard_filters.go | 12 +++++++----- filters/standard_filters_test.go | 4 ++++ 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/filters/standard_filters.go b/filters/standard_filters.go index b4c4170..8f23282 100644 --- a/filters/standard_filters.go +++ b/filters/standard_filters.go @@ -12,7 +12,6 @@ import ( "strings" "time" "unicode" - "unicode/utf8" "github.com/danog/liquid/values" "github.com/osteele/tuesday" @@ -151,13 +150,16 @@ func AddStandardFilters(fd FilterDictionary) { // nolint: gocyclo }) fd.AddFilter("sort_natural", sortNaturalFilter) fd.AddFilter("slice", func(s string, start int, length func(int) int) string { - // runes aren't bytes; don't use slice + ss := []rune(s) n := length(1) if start < 0 { - start = utf8.RuneCountInString(s) + start + start = len(ss) + start } - p := regexp.MustCompile(fmt.Sprintf(`^.{%d}(.{0,%d}).*$`, start, n)) - return p.ReplaceAllString(s, "$1") + end := start+n + if end > len(ss) { + end = len(ss) + } + return string(ss[start:end]) }) fd.AddFilter("split", splitFilter) fd.AddFilter("strip_html", func(s string) string { diff --git a/filters/standard_filters_test.go b/filters/standard_filters_test.go index 558c84a..1a51904 100644 --- a/filters/standard_filters_test.go +++ b/filters/standard_filters_test.go @@ -98,8 +98,12 @@ var filterTests = []struct { {`"I strained to see the train through the rain" | remove_first: "rain"`, "I sted to see the train through the rain"}, {`"Liquid" | slice: 0`, "L"}, + {`"Liquid +Liquid" | slice: 0`, "L"}, {`"Liquid" | slice: 2`, "q"}, {`"Liquid" | slice: 2, 5`, "quid"}, + {`"Liquid +Liquid" | slice: 2, 4`, "quid"}, {`"Liquid" | slice: -3, 2`, "ui"}, {`"a/b/c" | split: '/' | join: '-'`, "a-b-c"},