This is an automated email from the ASF dual-hosted git repository.

zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/arrow-go.git


The following commit(s) were added to refs/heads/main by this push:
     new 52023100 feat(arrow/compute): support IgnoreCase in starts_with (#1468)
52023100 is described below

commit 520231008bd28b1f525b116d17716cdcdb4681e0
Author: Harrison Crosse <[email protected]>
AuthorDate: Thu Nov 5 16:51:47 2026 -0500

    feat(arrow/compute): support IgnoreCase in starts_with (#1468)
    
    ### Rationale for this change
    
    `starts_with` returns `arrow.ErrNotImplemented` when
    `MatchSubstringOptions.IgnoreCase` is set. Substrait plans with
    `CASE_INSENSITIVE` fail for the same reason. I added support for both,
    following Arrow C++.
    
    ### What changes are included in this PR?
    
    `string` and `large_string` use Unicode simple folding, without full
    folding or Turkish special casing. Input is decoded character by
    character, so folds with different UTF-8 lengths match, such as the
    Kelvin sign and `k`. An invalid input byte never matches a pattern
    character. With `IgnoreCase` on string input, an invalid UTF-8 pattern
    returns `arrow.ErrInvalid`.
    
    `binary` and `large_binary` fold ASCII letters only. The issue proposed
    Latin-1 folds for binary input, but C++ folds only ASCII letters there.
    In pyarrow `26.0.0`, `b"\xc0"` and `b"\xe0"` don't match each other
    under `starts_with`, `match_substring` or a `(?i)` regex. This PR
    follows C++.
    
    Substrait `CASE_INSENSITIVE` maps to `IgnoreCase`.
    `CASE_INSENSITIVE_ASCII` still returns `arrow.ErrNotImplemented`.
    Case-sensitive matching is unchanged.
    
    Folding follows the Go toolchain's `unicode` tables. With Go 1.26, the
    `go.mod` minimum, those tables are Unicode 15.0 and string fold results
    matched pyarrow on every oracle case. Go 1.27 uses Unicode 17.0 and
    differs for 116 characters whose simple folds were added or changed.
    
    This PR also extends `IgnoreCase` to `string_view`, which folds like
    `string`, and `binary_view`, which folds ASCII letters only, like
    `binary`. Case-sensitive view matching from
    https://github.com/apache/arrow-go/pull/1467 behaves as before.
    
    ### Are these changes tested?
    
    I extended two tests:
    
    - `TestStartsWith` covers folds with different UTF-8 lengths, no full
    folding, no Turkish special casing, invalid input bytes versus U+FFFD,
    ASCII-only binary folding, and empty patterns. Each row runs as arrays
    and scalars for its input types, except views, which have no scalars.
    The view rows cover inline and out-of-line values, a fold that changes
    UTF-8 length across the 12-byte inline limit, and invalid UTF-8. Both
    view types have a single-buffer sliced case with a null. The options
    test checks the invalid string pattern error for `string` and
    `string_view`.
    - `TestStartsWithExpr` executes `CASE_INSENSITIVE` and checks that
    `CASE_INSENSITIVE_ASCII` is rejected.
    
    I also ran an uncommitted differential comparison against pyarrow
    `26.0.0`. With Go 1.26, its 224,230 cases had only two differences, both
    surrogate-encoded string patterns that Go rejects and C++ accepts.
    
    An uncommitted randomized comparison of view inputs against the `string`
    and `binary` `IgnoreCase` paths found no differences in 20,000 cases.
    
    Case-sensitive view benchmarks on an Apple M4 Max, 12 interleaved rounds
    over 4,096 rows, showed no difference from
    https://github.com/apache/arrow-go/pull/1467. The time geomean changed
    by +0.12%, with every p-value above 0.2.
    
    On macOS arm64, `go test ./arrow/compute/...` passed, along with `go
    test -race -tags assert,test` on `compute`, `kernels` and `exprs`,
    `gofmt`, `go vet`, `golangci-lint` `2.13.2` on Go 1.26.10 and the
    Release Audit Tool.
    
    ### Are there any user-facing changes?
    
    Yes. `IgnoreCase` now works instead of returning
    `arrow.ErrNotImplemented`, and Substrait `CASE_INSENSITIVE` plans
    execute. Invalid UTF-8 string patterns with `IgnoreCase`, including on
    `string_view`, return `arrow.ErrInvalid`. There is no API change.
    
    Closes https://github.com/apache/arrow-go/issues/1460.
---
 arrow/compute/exprs/exec_test.go                |   9 +-
 arrow/compute/exprs/types.go                    |  17 +--
 arrow/compute/internal/kernels/scalar_string.go | 159 ++++++++++++++++++++----
 arrow/compute/scalar_string.go                  |   8 +-
 arrow/compute/scalar_string_test.go             | 103 +++++++++++++--
 5 files changed, 250 insertions(+), 46 deletions(-)

diff --git a/arrow/compute/exprs/exec_test.go b/arrow/compute/exprs/exec_test.go
index 14ae8d16..d6d9bfdf 100644
--- a/arrow/compute/exprs/exec_test.go
+++ b/arrow/compute/exprs/exec_test.go
@@ -1101,7 +1101,9 @@ func TestStartsWithExpr(t *testing.T) {
        bldr := exprs.NewExprBuilder(extSet)
        require.NoError(t, bldr.SetInputSchema(sc))
        ab := bldr.Literal(expr.NewPrimitiveLiteral("ab", false))
-       caseInsensitive := []*types.FunctionOption{{Name: "case_sensitivity", 
Preference: []string{"CASE_INSENSITIVE"}}}
+       caseSensitivity := func(pref string) []*types.FunctionOption {
+               return []*types.FunctionOption{{Name: "case_sensitivity", 
Preference: []string{pref}}}
+       }
 
        tests := []struct {
                name     string
@@ -1116,7 +1118,10 @@ func TestStartsWithExpr(t *testing.T) {
                        bldr.Must(bldr.Cast(ab, arrow.BinaryTypes.String))), 
""},
                {"null pattern", bldr.MustCallScalar("starts_with", nil, 
bldr.FieldRef("s"),
                        
bldr.Literal(expr.NewNullLiteral(&types.StringType{}))), ""},
-               {"case insensitive", bldr.MustCallScalar("starts_with", 
caseInsensitive, bldr.FieldRef("s"), ab), ""},
+               {"case insensitive", bldr.MustCallScalar("starts_with", 
caseSensitivity("CASE_INSENSITIVE"), bldr.FieldRef("s"),
+                       bldr.Literal(expr.NewPrimitiveLiteral("AB", false))), 
`[true, null, false, false]`},
+               {"case insensitive ascii", bldr.MustCallScalar("starts_with", 
caseSensitivity("CASE_INSENSITIVE_ASCII"),
+                       bldr.FieldRef("s"), ab), ""},
        }
 
        for _, tt := range tests {
diff --git a/arrow/compute/exprs/types.go b/arrow/compute/exprs/types.go
index ecfa4a58..ea179ca3 100644
--- a/arrow/compute/exprs/types.go
+++ b/arrow/compute/exprs/types.go
@@ -264,18 +264,18 @@ func setLookupFuncSubstraitToArrowFunc(sf 
*expr.ScalarFunction, input []compute.
        return
 }
 
-// startsWithSubstraitToArrowFunc supports only CASE_SENSITIVE.
-// A case_sensitivity preference list without CASE_SENSITIVE returns an
-// error wrapping arrow.ErrNotImplemented. Arrow C++ maps
-// CASE_INSENSITIVE to ignore_case=true.
+// startsWithSubstraitToArrowFunc maps CASE_INSENSITIVE to IgnoreCase.
+// A case_sensitivity preference list with only CASE_INSENSITIVE_ASCII
+// returns an error wrapping arrow.ErrNotImplemented.
 func startsWithSubstraitToArrowFunc(sf *expr.ScalarFunction, input 
[]compute.Datum) (fname string, args []compute.Datum, opts 
compute.FunctionOptions, err error) {
        if len(input) != 2 {
                return "", nil, nil, fmt.Errorf("%w: starts_with expects 2 
arguments, got %d",
                        arrow.ErrNotImplemented, len(input))
        }
 
-       if _, err := parseOption(sf, "case_sensitivity", &caseSensitivityParser,
-               []caseSensitivity{caseSensitive}, caseSensitive); err != nil {
+       sensitivity, err := parseOption(sf, "case_sensitivity", 
&caseSensitivityParser,
+               []caseSensitivity{caseSensitive, caseInsensitive}, 
caseSensitive)
+       if err != nil {
                return "", nil, nil, fmt.Errorf("%w: starts_with 
case_sensitivity %v", err, sf.GetOption("case_sensitivity"))
        }
 
@@ -295,7 +295,10 @@ func startsWithSubstraitToArrowFunc(sf 
*expr.ScalarFunction, input []compute.Dat
                return "", nil, nil, fmt.Errorf("%w: starts_with pattern of 
type %s", arrow.ErrNotImplemented, sc.DataType())
        }
 
-       return "starts_with", input[:1], 
&compute.MatchSubstringOptions{Pattern: string(pattern.Data())}, nil
+       return "starts_with", input[:1], &compute.MatchSubstringOptions{
+               Pattern:    string(pattern.Data()),
+               IgnoreCase: sensitivity == caseInsensitive,
+       }, nil
 }
 
 func simpleMapSubstraitToArrowFunc(sf *expr.ScalarFunction, input 
[]compute.Datum) (fname string, args []compute.Datum, opts 
compute.FunctionOptions, err error) {
diff --git a/arrow/compute/internal/kernels/scalar_string.go 
b/arrow/compute/internal/kernels/scalar_string.go
index f485e7cd..ff9e3f9e 100644
--- a/arrow/compute/internal/kernels/scalar_string.go
+++ b/arrow/compute/internal/kernels/scalar_string.go
@@ -20,6 +20,8 @@ import (
        "bytes"
        "fmt"
        "slices"
+       "unicode"
+       "unicode/utf8"
 
        "github.com/apache/arrow-go/v18/arrow"
        "github.com/apache/arrow-go/v18/arrow/bitutil"
@@ -28,7 +30,9 @@ import (
 )
 
 // MatchSubstringOptions controls the substring matching functions such as
-// starts_with, which match Pattern as a literal byte sequence.
+// starts_with, which match Pattern literally, not as a regular
+// expression. With IgnoreCase, string input matches Unicode simple case
+// folds and binary input matches ASCII case folds.
 type MatchSubstringOptions struct {
        Pattern    string `compute:"pattern"`
        IgnoreCase bool   `compute:"ignore_case"`
@@ -40,20 +44,43 @@ type matchSubstringState struct {
        pattern []byte
 }
 
-func initMatchSubstring(_ *exec.KernelCtx, args exec.KernelInitArgs) 
(exec.KernelState, error) {
-       opts, ok := args.Options.(MatchSubstringOptions)
-       if p, isPtr := args.Options.(*MatchSubstringOptions); isPtr && p != nil 
{
-               opts, ok = *p, true
-       }
-       if !ok {
-               return nil, fmt.Errorf("%w: attempted to initialize kernel 
state from invalid function options",
-                       arrow.ErrInvalid)
-       }
+type foldUTF8State struct {
+       pattern []rune
+}
+
+// foldASCIIState holds the pattern with each byte lowered by foldASCII.
+type foldASCIIState struct {
+       pattern []byte
+}
 
-       if opts.IgnoreCase {
-               return nil, fmt.Errorf("%w: case-insensitive substring 
matching", arrow.ErrNotImplemented)
+func initMatchSubstring(utf8Input bool) exec.KernelInitFn {
+       return func(_ *exec.KernelCtx, args exec.KernelInitArgs) 
(exec.KernelState, error) {
+               opts, ok := args.Options.(MatchSubstringOptions)
+               if p, isPtr := args.Options.(*MatchSubstringOptions); isPtr && 
p != nil {
+                       opts, ok = *p, true
+               }
+               if !ok {
+                       return nil, fmt.Errorf("%w: attempted to initialize 
kernel state from invalid function options",
+                               arrow.ErrInvalid)
+               }
+
+               switch {
+               case !opts.IgnoreCase:
+                       return matchSubstringState{pattern: 
[]byte(opts.Pattern)}, nil
+               case utf8Input:
+                       if !utf8.ValidString(opts.Pattern) {
+                               return nil, fmt.Errorf("%w: case-insensitive 
pattern must be valid UTF-8 for string input",
+                                       arrow.ErrInvalid)
+                       }
+                       return foldUTF8State{pattern: []rune(opts.Pattern)}, nil
+               default:
+                       pattern := []byte(opts.Pattern)
+                       for i, b := range pattern {
+                               pattern[i] = foldASCII(b)
+                       }
+                       return foldASCIIState{pattern: pattern}, nil
+               }
        }
-       return matchSubstringState{pattern: []byte(opts.Pattern)}, nil
 }
 
 func startsWith(ctx *exec.KernelCtx, v []byte, _ *error) bool {
@@ -78,28 +105,109 @@ func viewStartsWith(h *arrow.ViewHeader, data, pattern 
[]byte) bool {
        return bytes.Equal(data[off+n:off+len(pattern)], pattern[n:])
 }
 
+func viewBytes(h *arrow.ViewHeader, data []byte) []byte {
+       if h.IsInline() {
+               return h.InlineBytes()
+       }
+       off := int(h.BufferOffset())
+       return data[off : off+h.Len()]
+}
+
 // startsWithView reads out-of-line values from Buffers[2], so inputs with
 // more than one data buffer must be coalesced before execution.
 func startsWithView(ctx *exec.KernelCtx, in *exec.ExecSpan, out 
*exec.ExecResult) error {
        var (
-               arg0    = &in.Values[0].Array
-               pattern = ctx.State.(matchSubstringState).pattern
-               views   = 
arrow.ViewHeaderTraits.CastFromBytes(arg0.Buffers[1].Buf)[arg0.Offset:]
-               data    = arg0.Buffers[2].Buf
-               outData = out.Buffers[1].Buf
-               outPos  = int(out.Offset)
+               arg0       = &in.Values[0].Array
+               views      = 
arrow.ViewHeaderTraits.CastFromBytes(arg0.Buffers[1].Buf)[arg0.Offset:]
+               data       = arg0.Buffers[2].Buf
+               outData    = out.Buffers[1].Buf
+               outPos     = int(out.Offset)
+               visitValid func(pos int64)
        )
-       bitutils.VisitBitBlocks(arg0.Buffers[0].Buf, arg0.Offset, arg0.Len,
-               func(pos int64) {
+       visitFold := func(fold func(*exec.KernelCtx, []byte, *error) bool) 
func(int64) {
+               return func(pos int64) {
+                       bitutil.SetBitTo(outData, outPos, fold(ctx, 
viewBytes(&views[pos], data), nil))
+                       outPos++
+               }
+       }
+       switch st := ctx.State.(type) {
+       case matchSubstringState:
+               pattern := st.pattern
+               visitValid = func(pos int64) {
                        bitutil.SetBitTo(outData, outPos, 
viewStartsWith(&views[pos], data, pattern))
                        outPos++
-               }, func() {
+               }
+       case foldUTF8State:
+               visitValid = visitFold(startsWithFoldUTF8)
+       case foldASCIIState:
+               visitValid = visitFold(startsWithFoldASCII)
+       }
+       bitutils.VisitBitBlocks(arg0.Buffers[0].Buf, arg0.Offset, arg0.Len, 
visitValid,
+               func() {
                        bitutil.ClearBit(outData, outPos)
                        outPos++
                })
        return nil
 }
 
+func startsWithFoldUTF8(ctx *exec.KernelCtx, v []byte, _ *error) bool {
+       for _, p := range ctx.State.(foldUTF8State).pattern {
+               r, size := utf8.DecodeRune(v)
+               if (r == utf8.RuneError && size <= 1) || !equalSimpleFold(r, p) 
{
+                       return false
+               }
+               v = v[size:]
+       }
+       return true
+}
+
+func equalSimpleFold(r, p rune) bool {
+       for f := r; ; {
+               if f == p {
+                       return true
+               }
+               if f = unicode.SimpleFold(f); f == r {
+                       return false
+               }
+       }
+}
+
+func startsWithFoldASCII(ctx *exec.KernelCtx, v []byte, _ *error) bool {
+       pattern := ctx.State.(foldASCIIState).pattern
+       if len(v) < len(pattern) {
+               return false
+       }
+       for i, p := range pattern {
+               if foldASCII(v[i]) != p {
+                       return false
+               }
+       }
+       return true
+}
+
+func foldASCII(b byte) byte {
+       if 'A' <= b && b <= 'Z' {
+               return b + 0x20
+       }
+       return b
+}
+
+func startsWithExec[OffsetT int32 | int64]() exec.ArrayKernelExec {
+       caseSensitive := ScalarUnaryNotNullBinaryArgBoolOut[OffsetT](false, 
startsWith)
+       foldUTF8 := ScalarUnaryNotNullBinaryArgBoolOut[OffsetT](false, 
startsWithFoldUTF8)
+       foldASCII := ScalarUnaryNotNullBinaryArgBoolOut[OffsetT](false, 
startsWithFoldASCII)
+       return func(ctx *exec.KernelCtx, in *exec.ExecSpan, out 
*exec.ExecResult) error {
+               switch ctx.State.(type) {
+               case foldUTF8State:
+                       return foldUTF8(ctx, in, out)
+               case foldASCIIState:
+                       return foldASCII(ctx, in, out)
+               default:
+                       return caseSensitive(ctx, in, out)
+               }
+       }
+}
+
 // GetStartsWithKernels returns the kernels for the starts_with function
 // over the binary, string and view types.
 func GetStartsWithKernels() []exec.ScalarKernel {
@@ -112,11 +220,12 @@ func GetStartsWithKernels() []exec.ScalarKernel {
                case arrow.BINARY_VIEW, arrow.STRING_VIEW:
                        ex = startsWithView
                case arrow.LARGE_BINARY, arrow.LARGE_STRING:
-                       ex = ScalarUnaryNotNullBinaryArgBoolOut[int64](false, 
startsWith)
+                       ex = startsWithExec[int64]()
                default:
-                       ex = ScalarUnaryNotNullBinaryArgBoolOut[int32](false, 
startsWith)
+                       ex = startsWithExec[int32]()
                }
-               k := 
exec.NewScalarKernel([]exec.InputType{exec.NewExactInput(ty)}, out, ex, 
initMatchSubstring)
+               k := 
exec.NewScalarKernel([]exec.InputType{exec.NewExactInput(ty)}, out, ex,
+                       initMatchSubstring(ty.(arrow.BinaryDataType).IsUtf8()))
                k.NullHandling = exec.NullIntersection
                k.MemAlloc = exec.MemPrealloc
                kernels = append(kernels, k)
diff --git a/arrow/compute/scalar_string.go b/arrow/compute/scalar_string.go
index 4b416b70..f37c87ea 100644
--- a/arrow/compute/scalar_string.go
+++ b/arrow/compute/scalar_string.go
@@ -25,8 +25,12 @@ import (
 )
 
 // MatchSubstringOptions controls the substring matching functions such as
-// starts_with, which match Pattern as a literal byte sequence. Setting
-// IgnoreCase makes them return arrow.ErrNotImplemented.
+// starts_with, which match Pattern literally, not as a regular
+// expression. With IgnoreCase, string and string_view input match Unicode
+// simple case folds and require a valid UTF-8 pattern, while binary and
+// binary_view input match ASCII case folds only. String case folding uses
+// the tables of the Go toolchain's unicode package, so results can differ
+// between Go versions.
 type MatchSubstringOptions = kernels.MatchSubstringOptions
 
 var startsWithDoc = FunctionDoc{
diff --git a/arrow/compute/scalar_string_test.go 
b/arrow/compute/scalar_string_test.go
index 45083c5e..335e6e0c 100644
--- a/arrow/compute/scalar_string_test.go
+++ b/arrow/compute/scalar_string_test.go
@@ -29,9 +29,9 @@ import (
        "github.com/stretchr/testify/require"
 )
 
-func checkStartsWith(t *testing.T, ctx context.Context, pattern string, input, 
expected compute.Datum) {
+func checkStartsWith(t *testing.T, ctx context.Context, opts 
compute.MatchSubstringOptions, input, expected compute.Datum) {
        t.Helper()
-       got, err := compute.StartsWith(ctx, 
compute.MatchSubstringOptions{Pattern: pattern}, input)
+       got, err := compute.StartsWith(ctx, opts, input)
        require.NoError(t, err)
        defer got.Release()
        assertDatumsEqual(t, expected, got, nil, nil)
@@ -84,7 +84,7 @@ func TestStartsWith(t *testing.T) {
                                switch dt.ID() {
                                case arrow.BINARY_VIEW, arrow.STRING_VIEW:
                                        // arrow/scalar has no view scalars, so 
only the array path applies.
-                                       checkStartsWith(t, ctx, tt.pattern, in, 
exp)
+                                       checkStartsWith(t, ctx, 
compute.MatchSubstringOptions{Pattern: tt.pattern}, in, exp)
                                default:
                                        checkScalarUnary(t, "starts_with", in, 
exp, &compute.MatchSubstringOptions{Pattern: tt.pattern})
                                }
@@ -99,7 +99,8 @@ func TestStartsWith(t *testing.T) {
                expected := fromJSON(t, mem, arrow.FixedWidthTypes.Boolean, 
`[true, true, false, false]`)
                defer expected.Release()
 
-               checkStartsWith(t, ctx, "\xff", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
+               checkStartsWith(t, ctx, compute.MatchSubstringOptions{Pattern: 
"\xff"},
+                       compute.NewDatumWithoutOwning(input), 
compute.NewDatumWithoutOwning(expected))
        })
 
        for _, dt := range []arrow.DataType{arrow.BinaryTypes.String, 
arrow.BinaryTypes.StringView} {
@@ -113,7 +114,8 @@ func TestStartsWith(t *testing.T) {
                        expected := fromJSON(t, mem, 
arrow.FixedWidthTypes.Boolean, `[true, null, true, false, true, false]`)
                        defer expected.Release()
 
-                       checkStartsWith(t, ctx, "ab", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
+                       checkStartsWith(t, ctx, 
compute.MatchSubstringOptions{Pattern: "ab"},
+                               compute.NewDatumWithoutOwning(input), 
compute.NewDatumWithoutOwning(expected))
                })
        }
 
@@ -134,7 +136,8 @@ func TestStartsWith(t *testing.T) {
                expected := fromJSON(t, mem, arrow.FixedWidthTypes.Boolean, 
`[true, false, true, true, null]`)
                defer expected.Release()
 
-               checkStartsWith(t, ctx, "abcdef", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
+               checkStartsWith(t, ctx, compute.MatchSubstringOptions{Pattern: 
"abcdef"},
+                       compute.NewDatumWithoutOwning(input), 
compute.NewDatumWithoutOwning(expected))
        })
 
        t.Run("chunked", func(t *testing.T) {
@@ -152,7 +155,8 @@ func TestStartsWith(t *testing.T) {
                expected := arrow.NewChunked(arrow.FixedWidthTypes.Boolean, 
[]arrow.Array{want})
                defer expected.Release()
 
-               checkStartsWith(t, ctx, "ab", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
+               checkStartsWith(t, ctx, compute.MatchSubstringOptions{Pattern: 
"ab"},
+                       compute.NewDatumWithoutOwning(input), 
compute.NewDatumWithoutOwning(expected))
        })
 
        for _, dt := range []arrow.DataType{arrow.BinaryTypes.String, 
arrow.BinaryTypes.StringView} {
@@ -168,10 +172,84 @@ func TestStartsWith(t *testing.T) {
                        expected := fromJSON(t, mem, 
arrow.FixedWidthTypes.Boolean, `[true, null, false, null, true]`)
                        defer expected.Release()
 
-                       checkStartsWith(t, ctx, "ab", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
+                       checkStartsWith(t, ctx, 
compute.MatchSubstringOptions{Pattern: "ab"},
+                               compute.NewDatumWithoutOwning(input), 
compute.NewDatumWithoutOwning(expected))
                })
        }
 
+       t.Run("ignore case", func(t *testing.T) {
+               strs := []arrow.DataType{arrow.BinaryTypes.String, 
arrow.BinaryTypes.LargeString, arrow.BinaryTypes.StringView}
+               bins := []arrow.DataType{arrow.BinaryTypes.Binary, 
arrow.BinaryTypes.LargeBinary, arrow.BinaryTypes.BinaryView}
+               tests := []struct {
+                       name, pattern string
+                       types         []arrow.DataType
+                       input         []string
+                       expected      string
+               }{
+                       {"multibyte folds", "\u212a\u017f", strs, 
[]string{"ks", "KSx", "\u212a\u017f", "k"}, `[true, true, true, false]`},
+                       {"no full folding", "\u00df", strs, []string{"SS", 
"\u1e9e", "\u00df"}, `[false, true, true]`},
+                       {"no special casing", "i", strs, []string{"I", 
"\u0130", "\u0131"}, `[true, false, false]`},
+                       {"invalid input", "\ufffd", strs, []string{"\ufffd", 
"\xff", "\xffbcdefghijklm"}, `[true, false, false]`},
+                       {"fold changes length", "abcdefghijk\u212a", strs,
+                               []string{"abcdefghijkxyz", "abcdefghijkK", 
"ABCDEFGHIJKkxyz", "abcdefghijk\u212a\u212a", "abcdefghijkx"},
+                               `[false, true, true, true, false]`},
+                       {"ascii folds only", "\xe0a", bins,
+                               []string{"\xe0A", "\xc0a", "\xe0", 
"\xc0abcdefghijklm", "\xe0Abcdefghijklm"},
+                               `[true, false, false, false, true]`},
+                       {"empty pattern", "", append(strs, bins...), 
[]string{"", "\xff"}, `[true, true]`},
+               }
+
+               for _, tt := range tests {
+                       for _, dt := range tt.types {
+                               t.Run(tt.name+"/"+dt.String(), func(t 
*testing.T) {
+                                       ctx, mem := newCtx(t)
+                                       bldr := array.NewBuilder(mem, dt)
+                                       defer bldr.Release()
+                                       bldr.(interface{ 
AppendStringValues([]string, []bool) }).AppendStringValues(tt.input, nil)
+                                       input := bldr.NewArray()
+                                       defer input.Release()
+                                       expected := fromJSON(t, mem, 
arrow.FixedWidthTypes.Boolean, tt.expected)
+                                       defer expected.Release()
+
+                                       in, exp := 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected)
+                                       opts := 
compute.MatchSubstringOptions{Pattern: tt.pattern, IgnoreCase: true}
+                                       switch dt.ID() {
+                                       case arrow.BINARY_VIEW, 
arrow.STRING_VIEW:
+                                               checkStartsWith(t, ctx, opts, 
in, exp)
+                                       default:
+                                               checkScalarUnary(t, 
"starts_with", in, exp, &opts)
+                                       }
+                               })
+                       }
+               }
+
+               for _, dt := range 
[]arrow.DataType{arrow.BinaryTypes.StringView, arrow.BinaryTypes.BinaryView} {
+                       t.Run("sliced/"+dt.String(), func(t *testing.T) {
+                               ctx, mem := newCtx(t)
+                               bldr := array.NewBuilder(mem, dt).(interface {
+                                       array.Builder
+                                       AppendString(string)
+                               })
+                               defer bldr.Release()
+                               bldr.AppendString("abc")
+                               bldr.AppendString("ABcdefghijklmn")
+                               bldr.AppendNull()
+                               for _, v := range []string{"aBc", 
"abXdefghijklmn", "xbcdefghijklmn"} {
+                                       bldr.AppendString(v)
+                               }
+                               full := bldr.NewArray()
+                               defer full.Release()
+                               input := array.NewSlice(full, 1, 6)
+                               defer input.Release()
+                               expected := fromJSON(t, mem, 
arrow.FixedWidthTypes.Boolean, `[true, null, true, false, false]`)
+                               defer expected.Release()
+
+                               checkStartsWith(t, ctx, 
compute.MatchSubstringOptions{Pattern: "abc", IgnoreCase: true},
+                                       compute.NewDatumWithoutOwning(input), 
compute.NewDatumWithoutOwning(expected))
+                       })
+               }
+       })
+
        t.Run("options", func(t *testing.T) {
                fn, ok := 
compute.GetFunctionRegistry().GetFunction("starts_with")
                require.True(t, ok)
@@ -195,7 +273,12 @@ func TestStartsWith(t *testing.T) {
                assert.ErrorIs(t, err, arrow.ErrInvalid)
                _, err = compute.CallFunction(ctx, "starts_with", 
&compute.ArithmeticOptions{}, input)
                assert.ErrorIs(t, err, arrow.ErrInvalid)
-               _, err = compute.StartsWith(ctx, 
compute.MatchSubstringOptions{Pattern: "a", IgnoreCase: true}, input)
-               assert.ErrorIs(t, err, arrow.ErrNotImplemented)
+               _, err = compute.StartsWith(ctx, 
compute.MatchSubstringOptions{Pattern: "\xff", IgnoreCase: true}, input)
+               assert.ErrorIs(t, err, arrow.ErrInvalid)
+               sv := fromJSON(t, mem, arrow.BinaryTypes.StringView, `["ab"]`)
+               defer sv.Release()
+               _, err = compute.StartsWith(ctx, 
compute.MatchSubstringOptions{Pattern: "\xff", IgnoreCase: true},
+                       compute.NewDatumWithoutOwning(sv))
+               assert.ErrorIs(t, err, arrow.ErrInvalid)
        })
 }

Reply via email to