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 a15c5135 feat(arrow/compute): support string_view and binary_view in 
starts_with (#1467)
a15c5135 is described below

commit a15c5135ceb580115608575e2cdd3f6ab19933a8
Author: Harrison Crosse <[email protected]>
AuthorDate: Thu Nov 5 12:58:52 2026 -0500

    feat(arrow/compute): support string_view and binary_view in starts_with 
(#1467)
    
    ### Rationale for this change
    
    `starts_with` rejects `string_view` and `binary_view`, so callers have
    to cast them first. This change accepts view inputs directly. Arrow C++
    also lacks support for these inputs
    (https://github.com/apache/arrow/issues/50478).
    
    ### What changes are included in this PR?
    
    The kernel checks the length in the 16-byte view header first. Inline
    values compare inside the header. For out-of-line values, it checks the
    4-byte prefix before reading the data buffer, and reads only the pattern
    bytes past that prefix.
    
    `ArraySpan` has three buffer slots, so inputs with more than one data
    buffer are coalesced before execution with the existing helper that
    `cast` uses. They share its `math.MaxInt32` limit on out-of-line bytes.
    Dictionaries of views use the existing dictionary decoding, including
    coalescing multi-buffer dictionary values. The `scalar` package has no
    view scalars, so scalar inputs are unchanged.
    
    https://github.com/apache/arrow-go/pull/1468 adds `IgnoreCase` and
    changes the same files. Whichever of the two merges second will merge
    main and add `IgnoreCase` for view inputs. Until then, `IgnoreCase` with
    view input returns `arrow.ErrNotImplemented` here.
    
    ### Are these changes tested?
    
    Yes. I extended `TestStartsWith` to run the shared cases on both view
    types. New rows check inline and out-of-line matches, prefix mismatches,
    mismatches past the prefix and patterns longer than the value. A sliced
    `string_view` checks offsets. The sliced multi-buffer `binary_view` case
    reads past the prefix in a later buffer, checking both a match and a
    mismatch. A dictionary of `string_view` checks decoding, null indices
    and null dictionary values.
    
    I also ran an uncommitted differential test over 20,000 generated cases,
    comparing the view result with cast-then-existing-kernel and
    `bytes.HasPrefix`. It found no differences across multi-buffer, sliced,
    dictionary and chunked inputs.
    
    On macOS arm64 with Go `1.27.3`, `go test ./arrow/compute/...` passed
    with and without `-tags assert,test`, along with `-race` on
    `arrow/compute`, `arrow/compute/internal/kernels` and
    `arrow/compute/exprs`. `gofmt`, `go vet` on compute and kernels, and the
    Release Audit Tool passed. `golangci-lint` `2.13.2`, run with Go
    `1.26.10`, reported no issues in `arrow`, `parquet` and `internal`.
    
    I benchmarked 65,536 synthetic `string_view` values against casting to
    `string` before calling `starts_with`. These results are from a Linux
    amd64 VM with 8 AMD EPYC vCPUs, with 12 runs per case:
    
    | Input | Cast then string | View kernel | Less time |
    | --- | ---: | ---: | ---: |
    | Inline values, 1 to 12 bytes | 3.197 ms | 0.590 ms | 81.6% |
    | 64-byte values, 128 data buffers | 8.214 ms | 5.412 ms | 34.1% |
    | Same 64-byte values, one data buffer | 3.143 ms | 0.895 ms | 71.5% |
    
    The multi-buffer gain is smaller because both paths first copy the
    out-of-line data into one buffer.
    
    ### Are there any user-facing changes?
    
    Yes. `starts_with` accepts `string_view` and `binary_view` inputs,
    including dictionaries of views. There is no API change.
    
    Closes https://github.com/apache/arrow-go/issues/1459.
---
 arrow/compute/internal/kernels/scalar_string.go | 57 ++++++++++++++++--
 arrow/compute/scalar_string.go                  | 10 ++++
 arrow/compute/scalar_string_test.go             | 80 ++++++++++++++++++-------
 3 files changed, 120 insertions(+), 27 deletions(-)

diff --git a/arrow/compute/internal/kernels/scalar_string.go 
b/arrow/compute/internal/kernels/scalar_string.go
index 9ac96bcd..f485e7cd 100644
--- a/arrow/compute/internal/kernels/scalar_string.go
+++ b/arrow/compute/internal/kernels/scalar_string.go
@@ -19,9 +19,12 @@ package kernels
 import (
        "bytes"
        "fmt"
+       "slices"
 
        "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/bitutil"
        "github.com/apache/arrow-go/v18/arrow/compute/exec"
+       "github.com/apache/arrow-go/v18/internal/bitutils"
 )
 
 // MatchSubstringOptions controls the substring matching functions such as
@@ -57,16 +60,60 @@ func startsWith(ctx *exec.KernelCtx, v []byte, _ *error) 
bool {
        return bytes.HasPrefix(v, ctx.State.(matchSubstringState).pattern)
 }
 
+// viewStartsWith decides from the view header alone when it can, and
+// reads the data buffer only for the part of pattern past the prefix.
+func viewStartsWith(h *arrow.ViewHeader, data, pattern []byte) bool {
+       if h.Len() < len(pattern) {
+               return false
+       }
+       if h.IsInline() {
+               return bytes.HasPrefix(h.InlineBytes(), pattern)
+       }
+       prefix := h.Prefix()
+       n := min(len(pattern), arrow.ViewPrefixLen)
+       if !bytes.Equal(prefix[:n], pattern[:n]) {
+               return false
+       }
+       off := int(h.BufferOffset())
+       return bytes.Equal(data[off+n:off+len(pattern)], pattern[n:])
+}
+
+// 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)
+       )
+       bitutils.VisitBitBlocks(arg0.Buffers[0].Buf, arg0.Offset, arg0.Len,
+               func(pos int64) {
+                       bitutil.SetBitTo(outData, outPos, 
viewStartsWith(&views[pos], data, pattern))
+                       outPos++
+               }, func() {
+                       bitutil.ClearBit(outData, outPos)
+                       outPos++
+               })
+       return nil
+}
+
 // GetStartsWithKernels returns the kernels for the starts_with function
-// over the base binary and string types.
+// over the binary, string and view types.
 func GetStartsWithKernels() []exec.ScalarKernel {
        out := exec.NewOutputType(arrow.FixedWidthTypes.Boolean)
-       kernels := make([]exec.ScalarKernel, 0, len(baseBinaryTypes))
-       for _, ty := range baseBinaryTypes {
+       types := append(slices.Clip(baseBinaryTypes), 
arrow.BinaryTypes.BinaryView, arrow.BinaryTypes.StringView)
+       kernels := make([]exec.ScalarKernel, 0, len(types))
+       for _, ty := range types {
                var ex exec.ArrayKernelExec
-               if arrow.IsLargeBinaryLike(ty.ID()) {
+               switch ty.ID() {
+               case arrow.BINARY_VIEW, arrow.STRING_VIEW:
+                       ex = startsWithView
+               case arrow.LARGE_BINARY, arrow.LARGE_STRING:
                        ex = ScalarUnaryNotNullBinaryArgBoolOut[int64](false, 
startsWith)
-               } else {
+               default:
                        ex = ScalarUnaryNotNullBinaryArgBoolOut[int32](false, 
startsWith)
                }
                k := 
exec.NewScalarKernel([]exec.InputType{exec.NewExactInput(ty)}, out, ex, 
initMatchSubstring)
diff --git a/arrow/compute/scalar_string.go b/arrow/compute/scalar_string.go
index 4eca046a..4b416b70 100644
--- a/arrow/compute/scalar_string.go
+++ b/arrow/compute/scalar_string.go
@@ -45,6 +45,16 @@ type matchSubstringFunc struct {
 }
 
 func (fn *matchSubstringFunc) Execute(ctx context.Context, opts 
FunctionOptions, args ...Datum) (Datum, error) {
+       if len(args) == 1 {
+               coalesced, err := coalesceMultiBufferViewDatum(ctx, args[0])
+               if err != nil {
+                       return nil, err
+               }
+               if coalesced != nil {
+                       defer coalesced.Release()
+                       args = []Datum{coalesced}
+               }
+       }
        return execInternal(ctx, fn, opts, -1, args...)
 }
 
diff --git a/arrow/compute/scalar_string_test.go 
b/arrow/compute/scalar_string_test.go
index 744844d7..45083c5e 100644
--- a/arrow/compute/scalar_string_test.go
+++ b/arrow/compute/scalar_string_test.go
@@ -56,11 +56,17 @@ func TestStartsWith(t *testing.T) {
                {"empty pattern", "", `["", "a", null]`, `[true, true, null]`},
                {"all null", "ab", `[null, null]`, `[null, null]`},
                {"empty", "ab", `[]`, `[]`},
+               {"long pattern", "abcdef",
+                       `["abcdefghijklm", "abcdeXghijklm", "abcdefghijkl", 
"Xbcdefghijklm"]`,
+                       `[true, false, true, false]`},
+               {"long values", "ab", `["abcdefghijklm", "aXcdefghijklm"]`, 
`[true, false]`},
+               {"pattern longer than value", "abcdefghijklmn", 
`["abcdefghijklm", "nopqrstuvwxyz"]`, `[false, false]`},
        }
 
        for _, dt := range []arrow.DataType{
                arrow.BinaryTypes.Binary, arrow.BinaryTypes.LargeBinary,
                arrow.BinaryTypes.String, arrow.BinaryTypes.LargeString,
+               arrow.BinaryTypes.BinaryView, arrow.BinaryTypes.StringView,
        } {
                for _, tt := range tests {
                        t.Run(dt.String()+"/"+tt.name, func(t *testing.T) {
@@ -74,8 +80,14 @@ func TestStartsWith(t *testing.T) {
                                expected := fromJSON(t, mem, 
arrow.FixedWidthTypes.Boolean, tt.expected)
                                defer expected.Release()
 
-                               checkScalarUnary(t, "starts_with", 
compute.NewDatumWithoutOwning(input),
-                                       
compute.NewDatumWithoutOwning(expected), 
&compute.MatchSubstringOptions{Pattern: tt.pattern})
+                               in, exp := 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected)
+                               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)
+                               default:
+                                       checkScalarUnary(t, "starts_with", in, 
exp, &compute.MatchSubstringOptions{Pattern: tt.pattern})
+                               }
                        })
                }
        }
@@ -90,17 +102,39 @@ func TestStartsWith(t *testing.T) {
                checkStartsWith(t, ctx, "\xff", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
        })
 
-       t.Run("sliced", func(t *testing.T) {
+       for _, dt := range []arrow.DataType{arrow.BinaryTypes.String, 
arrow.BinaryTypes.StringView} {
+               t.Run("sliced/"+dt.String(), func(t *testing.T) {
+                       ctx, mem := newCtx(t)
+                       full := fromJSON(t, mem, dt,
+                               `["ab", null, "x", "abc", null, "ab", "b", 
"abd", "a", "ab"]`)
+                       defer full.Release()
+                       input := array.NewSlice(full, 3, 9)
+                       defer input.Release()
+                       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))
+               })
+       }
+
+       t.Run("multi-buffer view", func(t *testing.T) {
                ctx, mem := newCtx(t)
-               full := fromJSON(t, mem, arrow.BinaryTypes.String,
-                       `["ab", null, "x", "abc", null, "ab", "b", "abd", "a", 
"ab"]`)
+               long := strings.Repeat("x", 20000)
+               bldr := array.NewBinaryViewBuilder(mem)
+               defer bldr.Release()
+               for _, v := range []string{"abcdef" + long, "abcdef" + long, 
"abcdXf" + long, "abcdef", "abcdef" + long} {
+                       bldr.Append([]byte(v))
+               }
+               bldr.AppendNull()
+               full := bldr.NewArray()
                defer full.Release()
-               input := array.NewSlice(full, 3, 9)
+               require.Greater(t, len(full.Data().Buffers()), 3)
+               input := array.NewSlice(full, 1, 6)
                defer input.Release()
-               expected := fromJSON(t, mem, arrow.FixedWidthTypes.Boolean, 
`[true, null, true, false, true, false]`)
+               expected := fromJSON(t, mem, arrow.FixedWidthTypes.Boolean, 
`[true, false, true, true, null]`)
                defer expected.Release()
 
-               checkStartsWith(t, ctx, "ab", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
+               checkStartsWith(t, ctx, "abcdef", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
        })
 
        t.Run("chunked", func(t *testing.T) {
@@ -121,20 +155,22 @@ func TestStartsWith(t *testing.T) {
                checkStartsWith(t, ctx, "ab", 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected))
        })
 
-       t.Run("dictionary", func(t *testing.T) {
-               ctx, mem := newCtx(t)
-               dict := fromJSON(t, mem, arrow.BinaryTypes.String, `["ab", 
null, "xab"]`)
-               defer dict.Release()
-               indices := fromJSON(t, mem, arrow.PrimitiveTypes.Int8, `[0, 1, 
2, null, 0]`)
-               defer indices.Release()
-               input := array.NewDictionaryArray(&arrow.DictionaryType{
-                       IndexType: arrow.PrimitiveTypes.Int8, ValueType: 
arrow.BinaryTypes.String}, indices, dict)
-               defer input.Release()
-               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))
-       })
+       for _, dt := range []arrow.DataType{arrow.BinaryTypes.String, 
arrow.BinaryTypes.StringView} {
+               t.Run("dictionary/"+dt.String(), func(t *testing.T) {
+                       ctx, mem := newCtx(t)
+                       dict := fromJSON(t, mem, dt, `["ab", null, "xab"]`)
+                       defer dict.Release()
+                       indices := fromJSON(t, mem, arrow.PrimitiveTypes.Int8, 
`[0, 1, 2, null, 0]`)
+                       defer indices.Release()
+                       input := array.NewDictionaryArray(&arrow.DictionaryType{
+                               IndexType: arrow.PrimitiveTypes.Int8, 
ValueType: dt}, indices, dict)
+                       defer input.Release()
+                       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))
+               })
+       }
 
        t.Run("options", func(t *testing.T) {
                fn, ok := 
compute.GetFunctionRegistry().GetFunction("starts_with")

Reply via email to