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 884b44bd feat(arrow/compute): add utf8_length, utf8_upper and 
utf8_lower kernels (#1671)
884b44bd is described below

commit 884b44bdeee283dc6a8164b0d6686aa5f9f1af8e
Author: Edward Shen <[email protected]>
AuthorDate: Thu Nov 26 02:36:33 2026 +0800

    feat(arrow/compute): add utf8_length, utf8_upper and utf8_lower kernels 
(#1671)
    
    Adds utf8_length, utf8_upper and utf8_lower over utf8, large_utf8 and
    string_view, matching the C++ kernels: utf8_length counts Unicode code
    points with the output width following the offset width (utf8 -> int32,
    large_utf8 -> int64), and utf8_upper/utf8_lower map each code point with
    Go's simple Unicode case mappings (the unicode.ToUpper/ToLower
    equivalent of the C++ utf8proc calls), return the input type, and fail
    on invalid UTF-8. The string_view kernels are a Go addition: the C++
    registry registers these functions for utf8 and large_utf8 only.
    
    Fixes #1475
    AI-assisted, reviewed by a human.
---
 arrow/compute/doc.go                               |   3 +-
 arrow/compute/internal/kernels/scalar_string.go    | 290 ++++++++++++++++
 .../compute/internal/kernels/scalar_string_test.go | 381 +++++++++++++++++++++
 arrow/compute/internal/kernels/string_casts.go     |   2 +-
 arrow/compute/scalar_string.go                     |  79 ++++-
 arrow/compute/scalar_string_test.go                | 342 ++++++++++++++++++
 6 files changed, 1090 insertions(+), 7 deletions(-)

diff --git a/arrow/compute/doc.go b/arrow/compute/doc.go
index 8271c311..5888e130 100644
--- a/arrow/compute/doc.go
+++ b/arrow/compute/doc.go
@@ -27,7 +27,8 @@
 //
 // The function registry holds scalar functions (element-wise arithmetic,
 // comparisons, boolean logic, bit-wise operations, rounding, set lookup with
-// is_in, prefix matching with starts_with, list_element and the null
+// is_in, prefix matching with starts_with, string length and case mapping
+// with utf8_length, utf8_upper and utf8_lower, list_element and the null
 // checks), vector functions (array_filter, array_take, unique,
 // dictionary_encode, cumulative_sum and the run-end encode/decode
 // functions) and the meta functions cast, filter, take, sort
diff --git a/arrow/compute/internal/kernels/scalar_string.go 
b/arrow/compute/internal/kernels/scalar_string.go
index ff9e3f9e..ece562fe 100644
--- a/arrow/compute/internal/kernels/scalar_string.go
+++ b/arrow/compute/internal/kernels/scalar_string.go
@@ -24,6 +24,7 @@ import (
        "unicode/utf8"
 
        "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/array"
        "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"
@@ -232,3 +233,292 @@ func GetStartsWithKernels() []exec.ScalarKernel {
        }
        return kernels
 }
+
+// utf8Length returns the number of Unicode code points in v by counting
+// the bytes that are not UTF-8 continuation bytes. This matches the C++
+// kernels, which count the same way and only assume valid UTF-8.
+func utf8Length(v []byte) int {
+       var n int
+       for _, b := range v {
+               if b&0xc0 != 0x80 {
+                       n++
+               }
+       }
+       return n
+}
+
+func utf8Length32(_ *exec.KernelCtx, v []byte, _ *error) int32 {
+       return int32(utf8Length(v))
+}
+
+func utf8Length64(_ *exec.KernelCtx, v []byte, _ *error) int64 {
+       return int64(utf8Length(v))
+}
+
+// utf8LengthView is the string_view kernel of the utf8_length function. It
+// reads out-of-line values from Buffers[2], so inputs with more than one
+// data buffer must be coalesced before execution.
+func utf8LengthView(_ *exec.KernelCtx, in *exec.ExecSpan, out 
*exec.ExecResult) error {
+       var (
+               arg0    = &in.Values[0].Array
+               views   = 
arrow.ViewHeaderTraits.CastFromBytes(arg0.Buffers[1].Buf)[arg0.Offset:]
+               data    = arg0.Buffers[2].Buf
+               outVals = exec.GetSpanValues[int32](out, 1)
+               outPos  int
+       )
+
+       bitutils.VisitBitBlocks(arg0.Buffers[0].Buf, arg0.Offset, arg0.Len,
+               func(pos int64) {
+                       outVals[outPos] = 
int32(utf8Length(viewBytes(&views[pos], data)))
+                       outPos++
+               }, func() { outPos++ })
+       return nil
+}
+
+// GetUtf8LengthKernels returns the kernels for the utf8_length function
+// over the string types. The output width follows the offset width of the
+// input type, matching the C++ kernels (utf8 -> int32, large_utf8 ->
+// int64). The string_view kernel is a Go addition; the C++ registry
+// registers utf8_length for utf8 and large_utf8 only.
+func GetUtf8LengthKernels() []exec.ScalarKernel {
+       mk := func(inType, outType arrow.DataType, ex exec.ArrayKernelExec) 
exec.ScalarKernel {
+               k := 
exec.NewScalarKernel([]exec.InputType{exec.NewExactInput(inType)},
+                       exec.NewOutputType(outType), ex, nil)
+               k.NullHandling = exec.NullIntersection
+               k.MemAlloc = exec.MemPrealloc
+               return k
+       }
+       return []exec.ScalarKernel{
+               mk(arrow.BinaryTypes.String, arrow.PrimitiveTypes.Int32,
+                       ScalarUnaryNotNullBinaryArg[int32, 
int32](utf8Length32)),
+               mk(arrow.BinaryTypes.LargeString, arrow.PrimitiveTypes.Int64,
+                       ScalarUnaryNotNullBinaryArg[int64, 
int64](utf8Length64)),
+               mk(arrow.BinaryTypes.StringView, arrow.PrimitiveTypes.Int32, 
utf8LengthView),
+       }
+}
+
+// utf8CodePointMapper is a per-code-point case mapping such as
+// unicode.ToUpper or unicode.ToLower. Like the utf8proc calls used by the
+// C++ kernels, these are simple one-to-one Unicode case mappings.
+type utf8CodePointMapper func(rune) rune
+
+// appendMapped appends v to dst with each of its code points mapped
+// through mapRune. ASCII bytes are mapped without decoding, which relies
+// on mapRune keeping ASCII closed, as unicode.ToUpper and unicode.ToLower
+// do for simple Unicode case mappings. Returns an error wrapping
+// arrow.ErrInvalid when v is not valid UTF-8, matching the C++ kernels
+// which fail on invalid UTF-8 input.
+func appendMapped(dst, v []byte, mapRune utf8CodePointMapper) ([]byte, error) {
+       for len(v) > 0 {
+               if v[0] < utf8.RuneSelf {
+                       dst = append(dst, byte(mapRune(rune(v[0]))))
+                       v = v[1:]
+                       continue
+               }
+               r, size := utf8.DecodeRune(v)
+               if r == utf8.RuneError && size == 1 {
+                       return nil, fmt.Errorf("%w: Invalid UTF8 sequence in 
input", arrow.ErrInvalid)
+               }
+               if u := mapRune(r); u != r {
+                       dst = utf8.AppendRune(dst, u)
+               } else {
+                       dst = append(dst, v[:size]...)
+               }
+               v = v[size:]
+       }
+       return dst, nil
+}
+
+// visitStringValues calls visit for each valid value of the utf8 or
+// large_utf8 array arg0, and nullFn for each null value.
+func visitStringValues[OffsetT int32 | int64](arg0 *exec.ArraySpan,
+       visit func([]byte), nullFn func()) {
+       offsets := exec.GetSpanOffsets[OffsetT](arg0, 1)
+       data := arg0.Buffers[2].Buf
+       bitutils.VisitBitBlocks(arg0.Buffers[0].Buf, arg0.Offset, arg0.Len,
+               func(pos int64) { visit(data[offsets[pos]:offsets[pos+1]]) }, 
nullFn)
+}
+
+// dataReservation tracks the bytes reserved on a string builder so a
+// kernel can append with UnsafeAppend and still grow safely. The initial
+// reservation is a size hint rather than a bound: UnsafeAppend does not
+// grow the data buffer itself, so append grows the reservation before
+// writing a value that would outgrow it, and fails with arrow.ErrInvalid
+// once the output would exceed what the builder can address. A string_view
+// output has to stay in one data buffer, so for a view builder the hint
+// must bound the output: append fails rather than grow it.
+type dataReservation struct {
+       bldr     array.StringLikeBuilder
+       limit    int64 // most data bytes bldr can address
+       reserved int64 // bytes reserved on bldr in total
+       written  int64 // bytes appended so far
+       view     bool  // view builder: no data for inline values, and no growth
+}
+
+// newDataReservation reserves hint bytes of out-of-line data on bldr. A
+// view builder's output has to fit its reservation, so its hint is taken
+// as is and one over the builder's single data buffer limit returns
+// reserveFormattedDataExact's arrow.ErrInvalid. An offset builder's buffer
+// grows in place, so its hint is only capped at the limit: an output that
+// fits the limit is not rejected for its hint, and append enforces the
+// limit on the actual output.
+func newDataReservation(bldr array.StringLikeBuilder, hint int64) 
(*dataReservation, error) {
+       r := &dataReservation{bldr: bldr, limit: formattedDataLimit(bldr), 
view: isViewBuilder(bldr)}
+       if !r.view {
+               hint = min(hint, r.limit)
+       }
+       if err := reserveFormattedDataExact(bldr, hint); err != nil {
+               return nil, err
+       }
+       r.reserved = hint
+       return r, nil
+}
+
+// append appends v with UnsafeAppend, growing the reservation first if v
+// would outgrow it. Inline view values live in their headers and consume
+// no reserved data, so they count against neither the reservation nor the
+// limit. Past the hint there is no basis for a tighter estimate, so the
+// reservation doubles up to the limit; growing by one value at a time
+// would reallocate the data buffer on every value. A view builder's data
+// buffer cannot grow in place, so for it an output that outgrows the hint
+// fails instead of spilling into a second buffer. The limit only comes
+// into play for utf8 and string_view: large_utf8's is MaxInt64, more
+// bytes than an output can hold.
+func (r *dataReservation) append(v []byte) error {
+       if r.view && arrow.IsViewInline(len(v)) {
+               r.bldr.UnsafeAppend(v)
+               return nil
+       }
+       end := r.written + int64(len(v))
+       if end > r.limit {
+               return fmt.Errorf("%w: output (%d bytes) exceeds single data 
buffer limit (%d bytes) for %s",
+                       arrow.ErrInvalid, end, r.limit, r.bldr.Type())
+       }
+       if end > r.reserved {
+               if r.view {
+                       return fmt.Errorf("%w: string_view output (%d bytes) 
outgrew its %d byte reservation",
+                               arrow.ErrInvalid, end, r.reserved)
+               }
+               r.reserved = min(max(2*r.reserved, end), r.limit)
+               r.bldr.ReserveData(int(r.reserved - r.written))
+       }
+       r.bldr.UnsafeAppend(v)
+       r.written = end
+       return nil
+}
+
+// utf8CaseExecOffset is the utf8 or large_utf8 kernel of the utf8_upper
+// and utf8_lower functions.
+func utf8CaseExecOffset[OffsetT int32 | int64](mapRune utf8CodePointMapper) 
exec.ArrayKernelExec {
+       return func(ctx *exec.KernelCtx, in *exec.ExecSpan, out 
*exec.ExecResult) error {
+               arg0 := &in.Values[0].Array
+               bldr := array.NewBuilder(exec.GetAllocator(ctx.Ctx), 
out.Type).(array.StringLikeBuilder)
+               defer bldr.Release()
+
+               // Half again the input bytes fits the output under today's
+               // Unicode tables, where a simple case mapping grows a code 
point
+               // by at most one byte (two to three).
+               var total int64
+               visitStringValues[OffsetT](arg0, func(v []byte) { total += 
int64(len(v)) }, func() {})
+               bldr.Reserve(int(arg0.Len))
+               resv, err := newDataReservation(bldr, total*3/2)
+               if err != nil {
+                       return err
+               }
+
+               var scratch []byte
+               visitStringValues[OffsetT](arg0, func(v []byte) {
+                       if err != nil {
+                               return
+                       }
+                       if scratch, err = appendMapped(scratch[:0], v, 
mapRune); err == nil {
+                               err = resv.append(scratch)
+                       }
+               }, bldr.AppendNull)
+               if err != nil {
+                       return err
+               }
+
+               arr := bldr.NewArray()
+               out.TakeOwnership(arr.Data())
+               arr.Release()
+               return nil
+       }
+}
+
+// utf8CaseExecView is the string_view kernel of the utf8_upper and
+// utf8_lower functions. It reads out-of-line values from Buffers[2], so
+// inputs with more than one data buffer must be coalesced before
+// execution.
+func utf8CaseExecView(mapRune utf8CodePointMapper) exec.ArrayKernelExec {
+       return func(ctx *exec.KernelCtx, in *exec.ExecSpan, out 
*exec.ExecResult) error {
+               arg0 := &in.Values[0].Array
+               views := 
arrow.ViewHeaderTraits.CastFromBytes(arg0.Buffers[1].Buf)[arg0.Offset:]
+               data := arg0.Buffers[2].Buf
+               bldr := array.NewBuilder(exec.GetAllocator(ctx.Ctx), 
out.Type).(array.StringLikeBuilder)
+               defer bldr.Release()
+
+               // Half again the input bytes bounds the output under today's
+               // Unicode tables, where a simple case mapping grows a code 
point
+               // by at most one byte (two to three). The bound has to hold: a
+               // string_view data buffer cannot grow in place, and an inline
+               // value can grow out of line (12 bytes to 18), so every value
+               // counts toward it.
+               var total int64
+               bitutils.VisitBitBlocks(arg0.Buffers[0].Buf, arg0.Offset, 
arg0.Len,
+                       func(pos int64) { total += int64(views[pos].Len()) }, 
func() {})
+               bldr.Reserve(int(arg0.Len))
+               resv, err := newDataReservation(bldr, total*3/2)
+               if err != nil {
+                       return err
+               }
+
+               var scratch []byte
+               bitutils.VisitBitBlocks(arg0.Buffers[0].Buf, arg0.Offset, 
arg0.Len,
+                       func(pos int64) {
+                               if err != nil {
+                                       return
+                               }
+                               if scratch, err = appendMapped(scratch[:0], 
viewBytes(&views[pos], data), mapRune); err == nil {
+                                       err = resv.append(scratch)
+                               }
+                       }, bldr.AppendNull)
+               if err != nil {
+                       return err
+               }
+
+               arr := bldr.NewArray()
+               out.TakeOwnership(arr.Data())
+               arr.Release()
+               return nil
+       }
+}
+
+// GetUtf8CaseKernels returns the kernels for the utf8_upper and utf8_lower
+// functions over the string types. The output type of each kernel matches
+// its input type, like the C++ kernels, which register utf8_upper and
+// utf8_lower for utf8 and large_utf8 only; the string_view kernels are a
+// Go addition.
+func GetUtf8CaseKernels(mapRune utf8CodePointMapper) []exec.ScalarKernel {
+       types := []arrow.DataType{
+               arrow.BinaryTypes.String, arrow.BinaryTypes.LargeString, 
arrow.BinaryTypes.StringView,
+       }
+       kernels := make([]exec.ScalarKernel, 0, len(types))
+       for _, ty := range types {
+               var ex exec.ArrayKernelExec
+               switch ty.ID() {
+               case arrow.STRING_VIEW:
+                       ex = utf8CaseExecView(mapRune)
+               case arrow.LARGE_STRING:
+                       ex = utf8CaseExecOffset[int64](mapRune)
+               default:
+                       ex = utf8CaseExecOffset[int32](mapRune)
+               }
+               k := 
exec.NewScalarKernel([]exec.InputType{exec.NewExactInput(ty)},
+                       exec.NewOutputType(ty), ex, nil)
+               k.NullHandling = exec.NullComputedNoPrealloc
+               k.MemAlloc = exec.MemNoPrealloc
+               kernels = append(kernels, k)
+       }
+       return kernels
+}
diff --git a/arrow/compute/internal/kernels/scalar_string_test.go 
b/arrow/compute/internal/kernels/scalar_string_test.go
new file mode 100644
index 00000000..b8dd8427
--- /dev/null
+++ b/arrow/compute/internal/kernels/scalar_string_test.go
@@ -0,0 +1,381 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+// http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing, software
+// distributed under the License is distributed on an "AS IS" BASIS,
+// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+// See the License for the specific language governing permissions and
+// limitations under the License.
+
+//go:build go1.18
+
+package kernels
+
+import (
+       "bytes"
+       "errors"
+       "fmt"
+       "testing"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/array"
+       "github.com/apache/arrow-go/v18/arrow/memory"
+)
+
+var dataReservationTypes = []struct {
+       name string
+       typ  arrow.DataType
+}{
+       {"utf8", arrow.BinaryTypes.String},
+       {"large_utf8", arrow.BinaryTypes.LargeString},
+       {"string_view", arrow.BinaryTypes.StringView},
+}
+
+// offsetReservationTypes lists the offset builders, which grow their data
+// buffer in place; a view builder's data buffer cannot grow.
+var offsetReservationTypes = []struct {
+       name string
+       typ  arrow.DataType
+}{
+       {"utf8", arrow.BinaryTypes.String},
+       {"large_utf8", arrow.BinaryTypes.LargeString},
+}
+
+// TestDataReservationOutgrowsHint verifies that a dataReservation on an
+// offset builder appends correctly when the output is larger than its
+// hint, the path the utf8 case kernels would take if a future Go version's
+// Unicode tables grew a code point by more than the hint assumes. Without
+// the growth, the append would silently truncate the value.
+func TestDataReservationOutgrowsHint(t *testing.T) {
+       // A nil entry is appended as null; nulls consume no reservation.
+       values := [][]byte{
+               []byte("ab"),
+               nil,
+               bytes.Repeat([]byte("x"), 12),
+               bytes.Repeat([]byte("y"), 70000),
+               nil,
+               {},
+               bytes.Repeat([]byte("z"), 100000),
+       }
+       var total int64
+       for _, v := range values {
+               total += int64(len(v))
+       }
+       // The output size right before the last value.
+       boundary := int64(len(values[0]) + len(values[2]) + len(values[3]))
+
+       for _, tc := range offsetReservationTypes {
+               // Hints below total exercise growth at different points: before
+               // the first value, mid-array, exactly at a value boundary; the
+               // last one fits the whole output.
+               for _, hint := range []int64{0, 3, 1 << 10, boundary, total} {
+                       t.Run(fmt.Sprintf("%s/hint=%d", tc.name, hint), func(t 
*testing.T) {
+                               mem := 
memory.NewCheckedAllocator(memory.NewGoAllocator())
+                               defer mem.AssertSize(t, 0)
+
+                               bldr := array.NewBuilder(mem, 
tc.typ).(array.StringLikeBuilder)
+                               defer bldr.Release()
+                               bldr.Reserve(len(values))
+                               resv, err := newDataReservation(bldr, hint)
+                               if err != nil {
+                                       t.Fatal(err)
+                               }
+                               for _, v := range values {
+                                       if v == nil {
+                                               bldr.AppendNull()
+                                               continue
+                                       }
+                                       if err := resv.append(v); err != nil {
+                                               t.Fatal(err)
+                                       }
+                               }
+
+                               arr := bldr.NewArray().(array.StringLike)
+                               defer arr.Release()
+                               if arr.Len() != len(values) {
+                                       t.Fatalf("length: got %d, want %d", 
arr.Len(), len(values))
+                               }
+                               for i, v := range values {
+                                       if v == nil {
+                                               if arr.IsValid(i) {
+                                                       t.Errorf("value %d: got 
%q, want null", i, arr.Value(i))
+                                               }
+                                               continue
+                                       }
+                                       if got := arr.Value(i); got != 
string(v) {
+                                               t.Errorf("value %d: got %d 
bytes, want %d bytes", i, len(got), len(v))
+                                       }
+                               }
+                       })
+               }
+       }
+}
+
+// TestDataReservationViewOutgrowsHint verifies that a string_view output
+// which outgrows its hint fails with arrow.ErrInvalid instead of spilling
+// into a second data buffer, which a kernel could not return.
+func TestDataReservationViewOutgrowsHint(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.NewGoAllocator())
+       defer mem.AssertSize(t, 0)
+
+       bldr := array.NewStringViewBuilder(mem)
+       defer bldr.Release()
+       bldr.Reserve(3)
+       // Room for the first value only.
+       v := bytes.Repeat([]byte("y"), 70000)
+       resv, err := newDataReservation(bldr, int64(len(v)))
+       if err != nil {
+               t.Fatal(err)
+       }
+       if err := resv.append(v); err != nil {
+               t.Fatal(err)
+       }
+       if err := resv.append(bytes.Repeat([]byte("z"), 100000)); 
!errors.Is(err, arrow.ErrInvalid) {
+               t.Fatalf("second value: got %v, want arrow.ErrInvalid", err)
+       }
+       // An inline value still fits.
+       if err := resv.append([]byte("ab")); err != nil {
+               t.Fatal(err)
+       }
+
+       arr := bldr.NewArray().(array.StringLike)
+       defer arr.Release()
+       if arr.Len() != 2 || arr.Value(0) != string(v) || arr.Value(1) != "ab" {
+               t.Fatalf("got %d values %q, %q; want the first value and %q", 
arr.Len(), arr.Value(0), arr.Value(1), "ab")
+       }
+       if n := len(arr.Data().Buffers()) - 2; n != 1 {
+               t.Errorf("got %d data buffers, want 1", n)
+       }
+}
+
+// countingBuilder counts the data reservations asked of a builder.
+type countingBuilder struct {
+       array.StringLikeBuilder
+       reserves int
+}
+
+func (b *countingBuilder) ReserveData(n int) {
+       b.reserves++
+       b.StringLikeBuilder.ReserveData(n)
+}
+
+// TestDataReservationGrowsGeometrically verifies that an output past its
+// hint doubles the reservation per growth rather than reserving room for
+// one value at a time, which would reallocate the data buffer per value.
+func TestDataReservationGrowsGeometrically(t *testing.T) {
+       const (
+               values = 1000
+               size   = 16
+       )
+       v := bytes.Repeat([]byte("a"), size)
+
+       for _, tc := range offsetReservationTypes {
+               t.Run(tc.name, func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(memory.NewGoAllocator())
+                       defer mem.AssertSize(t, 0)
+
+                       bldr := &countingBuilder{StringLikeBuilder: 
array.NewBuilder(mem, tc.typ).(array.StringLikeBuilder)}
+                       defer bldr.Release()
+                       bldr.Reserve(values)
+                       // A hint for a single value; the output is values 
times that.
+                       resv, err := newDataReservation(bldr, size)
+                       if err != nil {
+                               t.Fatal(err)
+                       }
+                       for i := 0; i < values; i++ {
+                               if err := resv.append(v); err != nil {
+                                       t.Fatal(err)
+                               }
+                       }
+
+                       // Doubling from size to values*size takes log2(values) 
growths.
+                       if grows := bldr.reserves - 1; grows > 12 {
+                               t.Errorf("got %d data reservations for %d 
values, want at most 12", bldr.reserves, values)
+                       }
+                       if resv.written != values*size || resv.reserved < 
resv.written {
+                               t.Errorf("written %d, reserved %d, want 
reserved >= written == %d", resv.written, resv.reserved, values*size)
+                       }
+
+                       arr := bldr.NewArray().(array.StringLike)
+                       defer arr.Release()
+                       for i := 0; i < values; i++ {
+                               if got := arr.Value(i); got != string(v) {
+                                       t.Fatalf("value %d: got %d bytes, want 
%d bytes", i, len(got), size)
+                               }
+                       }
+               })
+       }
+}
+
+// TestDataReservationGrowthCappedAtLimit verifies that growth stops at the
+// builder's limit: the reservation never exceeds it, and the next value
+// that does not fit returns arrow.ErrInvalid.
+func TestDataReservationGrowthCappedAtLimit(t *testing.T) {
+       v := []byte("abcdefghijklmnop")
+
+       for _, tc := range offsetReservationTypes {
+               t.Run(tc.name, func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(memory.NewGoAllocator())
+                       defer mem.AssertSize(t, 0)
+
+                       bldr := array.NewBuilder(mem, 
tc.typ).(array.StringLikeBuilder)
+                       defer bldr.Release()
+                       bldr.Reserve(4)
+                       // Room for one value under the hint and three under 
the limit.
+                       resv, err := newDataReservation(bldr, int64(len(v)))
+                       if err != nil {
+                               t.Fatal(err)
+                       }
+                       resv.limit = 3 * int64(len(v))
+                       for i := 0; i < 3; i++ {
+                               if err := resv.append(v); err != nil {
+                                       t.Fatalf("value %d: %v", i, err)
+                               }
+                       }
+                       if resv.reserved != resv.limit {
+                               t.Errorf("reserved %d bytes, want the %d byte 
limit", resv.reserved, resv.limit)
+                       }
+                       if err := resv.append(v); !errors.Is(err, 
arrow.ErrInvalid) {
+                               t.Fatalf("fourth value: got %v, want 
arrow.ErrInvalid", err)
+                       }
+               })
+       }
+}
+
+// TestDataReservationLimit verifies that append returns arrow.ErrInvalid
+// instead of letting the output exceed what the builder can address, and
+// leaves the values appended before the failure intact.
+func TestDataReservationLimit(t *testing.T) {
+       // Long enough to be out-of-line for string_view.
+       v := []byte("abcdefghijklmnop")
+
+       for _, tc := range dataReservationTypes {
+               t.Run(tc.name, func(t *testing.T) {
+                       mem := 
memory.NewCheckedAllocator(memory.NewGoAllocator())
+                       defer mem.AssertSize(t, 0)
+
+                       bldr := array.NewBuilder(mem, 
tc.typ).(array.StringLikeBuilder)
+                       defer bldr.Release()
+                       bldr.Reserve(5)
+                       // Room for three values only.
+                       resv, err := newDataReservation(bldr, 3*int64(len(v)))
+                       if err != nil {
+                               t.Fatal(err)
+                       }
+                       resv.limit = 3 * int64(len(v))
+
+                       var appended int
+                       for err == nil && appended < 5 {
+                               err = resv.append(v)
+                               if err == nil {
+                                       appended++
+                               }
+                       }
+                       if !errors.Is(err, arrow.ErrInvalid) {
+                               t.Fatalf("fourth value: got %v, want 
arrow.ErrInvalid", err)
+                       }
+                       if appended != 3 || resv.written != 3*int64(len(v)) {
+                               t.Errorf("appended %d values, %d bytes; want 3 
values, %d bytes", appended, resv.written, 3*len(v))
+                       }
+
+                       arr := bldr.NewArray().(array.StringLike)
+                       defer arr.Release()
+                       if arr.Len() != 3 {
+                               t.Fatalf("length: got %d, want 3", arr.Len())
+                       }
+                       for i := 0; i < 3; i++ {
+                               if got := arr.Value(i); got != string(v) {
+                                       t.Errorf("value %d: got %q, want %q", 
i, got, v)
+                               }
+                       }
+               })
+       }
+}
+
+// TestDataReservationInlineViews verifies that inline string_view values
+// consume no reservation: they live in their headers, so neither the
+// reservation nor the limit counts them.
+func TestDataReservationInlineViews(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.NewGoAllocator())
+       defer mem.AssertSize(t, 0)
+
+       bldr := array.NewStringViewBuilder(mem)
+       defer bldr.Release()
+       bldr.Reserve(100)
+       // Nothing reserved and no room under the limit.
+       resv, err := newDataReservation(bldr, 0)
+       if err != nil {
+               t.Fatal(err)
+       }
+       resv.limit = 0
+       for i := 0; i < 100; i++ {
+               if err := resv.append([]byte("ab")); err != nil {
+                       t.Fatalf("inline value %d: %v", i, err)
+               }
+       }
+       if resv.written != 0 {
+               t.Errorf("inline values counted %d bytes against the 
reservation, want 0", resv.written)
+       }
+
+       arr := bldr.NewArray().(array.StringLike)
+       defer arr.Release()
+       if arr.Len() != 100 {
+               t.Fatalf("length: got %d, want 100", arr.Len())
+       }
+       for i := 0; i < 100; i++ {
+               if got := arr.Value(i); got != "ab" {
+                       t.Fatalf("value %d: got %q, want %q", i, got, "ab")
+               }
+       }
+}
+
+// requestingBuilder records the data reservation asked of it without
+// making it, so a limit-sized request needs no memory.
+type requestingBuilder struct {
+       array.StringLikeBuilder
+       asked int
+}
+
+func (b *requestingBuilder) ReserveData(n int) { b.asked += n }
+
+// TestDataReservationHintCappedAtLimit verifies how a hint over the
+// builder's limit is handled: an offset builder reserves the limit, since
+// the hint is not a bound and append enforces the limit on the actual
+// output, while a view builder fails up front since its output cannot
+// grow past the reserved buffer.
+func TestDataReservationHintCappedAtLimit(t *testing.T) {
+       t.Run("utf8", func(t *testing.T) {
+               mem := memory.NewCheckedAllocator(memory.NewGoAllocator())
+               defer mem.AssertSize(t, 0)
+
+               bldr := &requestingBuilder{StringLikeBuilder: 
array.NewStringBuilder(mem)}
+               defer bldr.Release()
+               limit := formattedDataLimit(bldr)
+               resv, err := newDataReservation(bldr, limit+1)
+               if err != nil {
+                       t.Fatalf("hint over the limit: got %v, want no error", 
err)
+               }
+               if resv.reserved != limit || bldr.asked != int(limit) {
+                       t.Errorf("reserved %d bytes (asked %d), want the %d 
byte limit", resv.reserved, bldr.asked, limit)
+               }
+       })
+
+       t.Run("string_view", func(t *testing.T) {
+               mem := memory.NewCheckedAllocator(memory.NewGoAllocator())
+               defer mem.AssertSize(t, 0)
+
+               bldr := array.NewStringViewBuilder(mem)
+               defer bldr.Release()
+               _, err := newDataReservation(bldr, formattedDataLimit(bldr)+1)
+               if !errors.Is(err, arrow.ErrInvalid) {
+                       t.Fatalf("hint over the limit: got %v, want 
arrow.ErrInvalid", err)
+               }
+       })
+}
diff --git a/arrow/compute/internal/kernels/string_casts.go 
b/arrow/compute/internal/kernels/string_casts.go
index d5805d4a..3db24bce 100644
--- a/arrow/compute/internal/kernels/string_casts.go
+++ b/arrow/compute/internal/kernels/string_casts.go
@@ -382,7 +382,7 @@ func reserveFormattedData(bldr array.StringLikeBuilder, 
input *exec.ArraySpan, p
 func reserveFormattedDataExact(bldr array.StringLikeBuilder, total int64) 
error {
        limit := formattedDataLimit(bldr)
        if total > limit {
-               return fmt.Errorf("%w: formatted cast payload (%d bytes) 
exceeds single data buffer limit (%d bytes) for destination builder",
+               return fmt.Errorf("%w: payload (%d bytes) exceeds single data 
buffer limit (%d bytes) for destination builder",
                        arrow.ErrInvalid, total, limit)
        }
        if total > 0 {
diff --git a/arrow/compute/scalar_string.go b/arrow/compute/scalar_string.go
index f37c87ea..06c2267f 100644
--- a/arrow/compute/scalar_string.go
+++ b/arrow/compute/scalar_string.go
@@ -18,6 +18,7 @@ package compute
 
 import (
        "context"
+       "unicode"
 
        "github.com/apache/arrow-go/v18/arrow"
        "github.com/apache/arrow-go/v18/arrow/compute/exec"
@@ -44,11 +45,15 @@ var startsWithDoc = FunctionDoc{
        OptionsRequired: true,
 }
 
-type matchSubstringFunc struct {
+// unaryStringFunc is a scalar function over a single string-like argument.
+// View inputs that carry more than one data buffer are coalesced before
+// execution, so kernel implementations can read out-of-line values from
+// Buffers[2].
+type unaryStringFunc struct {
        ScalarFunction
 }
 
-func (fn *matchSubstringFunc) Execute(ctx context.Context, opts 
FunctionOptions, args ...Datum) (Datum, error) {
+func (fn *unaryStringFunc) Execute(ctx context.Context, opts FunctionOptions, 
args ...Datum) (Datum, error) {
        if len(args) == 1 {
                coalesced, err := coalesceMultiBufferViewDatum(ctx, args[0])
                if err != nil {
@@ -62,21 +67,60 @@ func (fn *matchSubstringFunc) Execute(ctx context.Context, 
opts FunctionOptions,
        return execInternal(ctx, fn, opts, -1, args...)
 }
 
-func (fn *matchSubstringFunc) DispatchBest(vals ...arrow.DataType) 
(exec.Kernel, error) {
+func (fn *unaryStringFunc) DispatchBest(vals ...arrow.DataType) (exec.Kernel, 
error) {
        ensureDictionaryDecoded(vals...)
        ensureNoExtensionType(vals...)
        return fn.DispatchExact(vals...)
 }
 
-// RegisterScalarString registers the starts_with function.
+var (
+       utf8LengthDoc = FunctionDoc{
+               Summary:     "Compute UTF8 string lengths",
+               Description: "For each string in \"strings\", emit its length 
in UTF8 characters.\nNull values emit null.",
+               ArgNames:    []string{"strings"},
+       }
+       utf8UpperDoc = FunctionDoc{
+               Summary:     "Transform input to uppercase",
+               Description: "For each string in \"strings\", return an 
uppercase version.",
+               ArgNames:    []string{"strings"},
+       }
+       utf8LowerDoc = FunctionDoc{
+               Summary:     "Transform input to lowercase",
+               Description: "For each string in \"strings\", return a 
lowercase version.",
+               ArgNames:    []string{"strings"},
+       }
+)
+
+// RegisterScalarString registers the starts_with, utf8_length, utf8_upper
+// and utf8_lower functions.
 func RegisterScalarString(reg FunctionRegistry) {
-       fn := &matchSubstringFunc{*NewScalarFunction("starts_with", Unary(), 
startsWithDoc)}
+       fn := &unaryStringFunc{*NewScalarFunction("starts_with", Unary(), 
startsWithDoc)}
        for _, k := range kernels.GetStartsWithKernels() {
                if err := fn.AddKernel(k); err != nil {
                        panic(err)
                }
        }
        reg.AddFunction(fn, false)
+
+       fns := []struct {
+               fn      *unaryStringFunc
+               kernels []exec.ScalarKernel
+       }{
+               {&unaryStringFunc{*NewScalarFunction("utf8_length", Unary(), 
utf8LengthDoc)},
+                       kernels.GetUtf8LengthKernels()},
+               {&unaryStringFunc{*NewScalarFunction("utf8_upper", Unary(), 
utf8UpperDoc)},
+                       kernels.GetUtf8CaseKernels(unicode.ToUpper)},
+               {&unaryStringFunc{*NewScalarFunction("utf8_lower", Unary(), 
utf8LowerDoc)},
+                       kernels.GetUtf8CaseKernels(unicode.ToLower)},
+       }
+       for _, f := range fns {
+               for _, k := range f.kernels {
+                       if err := f.fn.AddKernel(k); err != nil {
+                               panic(err)
+                       }
+               }
+               reg.AddFunction(f.fn, false)
+       }
 }
 
 // StartsWith returns, for each value in input, whether it starts with
@@ -85,3 +129,28 @@ func RegisterScalarString(reg FunctionRegistry) {
 func StartsWith(ctx context.Context, opts MatchSubstringOptions, input Datum) 
(Datum, error) {
        return CallFunction(ctx, "starts_with", &opts, input)
 }
+
+// Utf8Length returns, for each value in input, its length in Unicode code
+// points. Null values produce null. Dictionary inputs are decoded to
+// their value type, and extension inputs use their storage type.
+func Utf8Length(ctx context.Context, input Datum) (Datum, error) {
+       return CallFunction(ctx, "utf8_length", nil, input)
+}
+
+// Utf8Upper returns an uppercase version of each value in input, mapping
+// each Unicode code point with the Go toolchain's unicode tables, so
+// results can differ between Go versions. Null values produce null.
+// Invalid UTF-8 input returns an error. Dictionary inputs are decoded
+// to their value type, and extension inputs use their storage type.
+func Utf8Upper(ctx context.Context, input Datum) (Datum, error) {
+       return CallFunction(ctx, "utf8_upper", nil, input)
+}
+
+// Utf8Lower returns a lowercase version of each value in input, mapping
+// each Unicode code point with the Go toolchain's unicode tables, so
+// results can differ between Go versions. Null values produce null.
+// Invalid UTF-8 input returns an error. Dictionary inputs are decoded
+// to their value type, and extension inputs use their storage type.
+func Utf8Lower(ctx context.Context, input Datum) (Datum, error) {
+       return CallFunction(ctx, "utf8_lower", nil, input)
+}
diff --git a/arrow/compute/scalar_string_test.go 
b/arrow/compute/scalar_string_test.go
index 118f8f17..702693fb 100644
--- a/arrow/compute/scalar_string_test.go
+++ b/arrow/compute/scalar_string_test.go
@@ -20,6 +20,7 @@ import (
        "context"
        "strings"
        "testing"
+       "unicode/utf8"
 
        "github.com/apache/arrow-go/v18/arrow"
        "github.com/apache/arrow-go/v18/arrow/array"
@@ -271,3 +272,344 @@ func TestStartsWith(t *testing.T) {
                assert.ErrorIs(t, err, arrow.ErrInvalid)
        })
 }
+
+func TestUtf8Length(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+       t.Cleanup(func() { mem.AssertSize(t, 0) })
+       ctx := compute.WithAllocator(context.Background(), mem)
+       fromJSON := func(dt arrow.DataType, json string) arrow.Array {
+               arr, _, err := array.FromJSON(mem, dt, strings.NewReader(json))
+               require.NoError(t, err)
+               t.Cleanup(arr.Release)
+               return arr
+       }
+
+       tests := []struct {
+               name, input, expected string
+       }{
+               {"ascii", `["", "a", "abc"]`, `[0, 1, 3]`},
+               {"multibyte", `["", "ábc", "日本語", "🦄", "aá日🦄", null]`, `[0, 3, 
3, 1, 4, null]`},
+               {"all null", `[null, null]`, `[null, null]`},
+               {"empty array", `[]`, `[]`},
+       }
+
+       for _, dt := range []arrow.DataType{
+               arrow.BinaryTypes.String, arrow.BinaryTypes.LargeString, 
arrow.BinaryTypes.StringView,
+       } {
+               for _, tt := range tests {
+                       t.Run(dt.String()+"/"+tt.name, func(t *testing.T) {
+                               strs := fromJSON(arrow.BinaryTypes.String, 
tt.input)
+                               input, err := compute.CastArray(ctx, strs, 
compute.SafeCastOptions(dt))
+                               require.NoError(t, err)
+                               defer input.Release()
+
+                               outType := arrow.PrimitiveTypes.Int32
+                               if dt.ID() == arrow.LARGE_STRING {
+                                       outType = arrow.PrimitiveTypes.Int64
+                               }
+                               expected := fromJSON(outType, tt.expected)
+
+                               in, exp := 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(expected)
+                               defer in.Release()
+                               defer exp.Release()
+                               checkScalarUnary(t, "utf8_length", in, exp, nil)
+                       })
+               }
+       }
+
+       for _, dt := range []arrow.DataType{arrow.BinaryTypes.String, 
arrow.BinaryTypes.StringView} {
+               t.Run("sliced/"+dt.String(), func(t *testing.T) {
+                       full := fromJSON(dt, `["ab", null, "x", "abc", null, 
"ab", "b", "abd", "a", "ab"]`)
+                       input := array.NewSlice(full, 3, 9)
+                       defer input.Release()
+                       expected := fromJSON(arrow.PrimitiveTypes.Int32, `[3, 
null, 2, 1, 3, 1]`)
+
+                       in, exp := compute.NewDatumWithoutOwning(input), 
compute.NewDatumWithoutOwning(expected)
+                       defer in.Release()
+                       defer exp.Release()
+                       checkScalarUnary(t, "utf8_length", in, exp, nil)
+               })
+       }
+
+       for _, dt := range []arrow.DataType{arrow.BinaryTypes.String, 
arrow.BinaryTypes.StringView} {
+               t.Run("dictionary/"+dt.String(), func(t *testing.T) {
+                       dict := fromJSON(dt, `["ab", null, "xab"]`)
+                       indices := fromJSON(arrow.PrimitiveTypes.Int8, `[0, 1, 
2, null, 0]`)
+                       input := array.NewDictionaryArray(&arrow.DictionaryType{
+                               IndexType: arrow.PrimitiveTypes.Int8, 
ValueType: dt}, indices, dict)
+                       defer input.Release()
+                       expected := fromJSON(arrow.PrimitiveTypes.Int32, `[2, 
null, 3, null, 2]`)
+
+                       in, exp := compute.NewDatumWithoutOwning(input), 
compute.NewDatumWithoutOwning(expected)
+                       defer in.Release()
+                       defer exp.Release()
+                       checkScalarUnary(t, "utf8_length", in, exp, nil)
+               })
+       }
+
+       t.Run("invalid utf8 counted by code point headers", func(t *testing.T) {
+               bldr := array.NewStringBuilder(mem)
+               defer bldr.Release()
+               for _, v := range []string{"\xff\x80", "\xff", "\xc3\x28"} {
+                       bldr.Append(v)
+               }
+               input := bldr.NewArray()
+               defer input.Release()
+               expected := fromJSON(arrow.PrimitiveTypes.Int32, `[1, 1, 2]`)
+
+               in, exp := compute.NewDatumWithoutOwning(input), 
compute.NewDatumWithoutOwning(expected)
+               defer in.Release()
+               defer exp.Release()
+               checkScalarUnary(t, "utf8_length", in, exp, nil)
+       })
+}
+
+func TestUtf8CaseConversion(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+       t.Cleanup(func() { mem.AssertSize(t, 0) })
+       ctx := compute.WithAllocator(context.Background(), mem)
+       fromJSON := func(dt arrow.DataType, json string) arrow.Array {
+               arr, _, err := array.FromJSON(mem, dt, strings.NewReader(json))
+               require.NoError(t, err)
+               t.Cleanup(arr.Release)
+               return arr
+       }
+
+       tests := []struct {
+               name, input, upper, lower string
+       }{
+               {"ascii", `["", "abc", "ABC", "aBc"]`, `["", "ABC", "ABC", 
"ABC"]`, `["", "abc", "abc", "abc"]`},
+               {"latin1", `["ábc", "ÁBC"]`, `["ÁBC", "ÁBC"]`, `["ábc", 
"ábc"]`},
+               {"greek", `["ω", "Ω", "ς"]`, `["Ω", "Ω", "Σ"]`, `["ω", "ω", 
"ς"]`},
+               {"cyrillic", `["д", "Д"]`, `["Д", "Д"]`, `["д", "д"]`},
+               {"turkish dotted i and eszett", `["ß", "ı", "İ"]`, `["ß", "I", 
"İ"]`, `["ß", "ı", "i"]`},
+               {"unchanged", `["日本語", "🦄", "42"]`, `["日本語", "🦄", "42"]`, 
`["日本語", "🦄", "42"]`},
+               {"nulls", `["ab", null, "AB"]`, `["AB", null, "AB"]`, `["ab", 
null, "ab"]`},
+               {"all null", `[null, null]`, `[null, null]`, `[null, null]`},
+               {"empty array", `[]`, `[]`, `[]`},
+       }
+
+       for _, dt := range []arrow.DataType{
+               arrow.BinaryTypes.String, arrow.BinaryTypes.LargeString, 
arrow.BinaryTypes.StringView,
+       } {
+               for _, tt := range tests {
+                       for _, fn := range []struct{ name, expected string }{
+                               {"utf8_upper", tt.upper}, {"utf8_lower", 
tt.lower},
+                       } {
+                               t.Run(dt.String()+"/"+fn.name+"/"+tt.name, 
func(t *testing.T) {
+                                       strs := 
fromJSON(arrow.BinaryTypes.String, tt.input)
+                                       input, err := compute.CastArray(ctx, 
strs, compute.SafeCastOptions(dt))
+                                       require.NoError(t, err)
+                                       defer input.Release()
+
+                                       expected := 
fromJSON(arrow.BinaryTypes.String, fn.expected)
+                                       want, err := compute.CastArray(ctx, 
expected, compute.SafeCastOptions(dt))
+                                       require.NoError(t, err)
+                                       defer want.Release()
+
+                                       in, exp := 
compute.NewDatumWithoutOwning(input), compute.NewDatumWithoutOwning(want)
+                                       defer in.Release()
+                                       defer exp.Release()
+                                       checkScalarUnary(t, fn.name, in, exp, 
nil)
+                               })
+                       }
+               }
+       }
+
+       for _, dt := range []arrow.DataType{
+               arrow.BinaryTypes.String, arrow.BinaryTypes.LargeString, 
arrow.BinaryTypes.StringView,
+       } {
+               t.Run("sliced/"+dt.String(), func(t *testing.T) {
+                       full := fromJSON(dt, `["ab", null, "x", "AbC", null, 
"aB", "b", "abD", "a", "ab"]`)
+                       input := array.NewSlice(full, 3, 9)
+                       defer input.Release()
+                       expected := fromJSON(dt, `["ABC", null, "AB", "B", 
"ABD", "A"]`)
+
+                       in, exp := compute.NewDatumWithoutOwning(input), 
compute.NewDatumWithoutOwning(expected)
+                       defer in.Release()
+                       defer exp.Release()
+                       checkScalarUnary(t, "utf8_upper", in, exp, nil)
+               })
+       }
+
+       for _, dt := range []arrow.DataType{arrow.BinaryTypes.String, 
arrow.BinaryTypes.StringView} {
+               t.Run("dictionary/"+dt.String(), func(t *testing.T) {
+                       dict := fromJSON(dt, `["ab", null, "xAB"]`)
+                       indices := fromJSON(arrow.PrimitiveTypes.Int8, `[0, 1, 
2, null, 0]`)
+                       input := array.NewDictionaryArray(&arrow.DictionaryType{
+                               IndexType: arrow.PrimitiveTypes.Int8, 
ValueType: dt}, indices, dict)
+                       defer input.Release()
+                       expected := fromJSON(dt, `["AB", null, "XAB", null, 
"AB"]`)
+
+                       in, exp := compute.NewDatumWithoutOwning(input), 
compute.NewDatumWithoutOwning(expected)
+                       defer in.Release()
+                       defer exp.Release()
+                       checkScalarUnary(t, "utf8_upper", in, exp, nil)
+               })
+       }
+
+       t.Run("multi-buffer view", func(t *testing.T) {
+               long := strings.Repeat("x", 20000)
+               upperLong := strings.Repeat("X", 20000)
+               bldr := array.NewStringViewBuilder(mem)
+               defer bldr.Release()
+               for _, v := range []string{"abcdef" + long, "abcdef" + long, 
"abcdXf" + long, "abcdef", "abcdef" + long} {
+                       bldr.Append(v)
+               }
+               bldr.AppendNull()
+               full := bldr.NewArray()
+               defer full.Release()
+               require.Greater(t, len(full.Data().Buffers()), 3)
+               input := array.NewSlice(full, 1, 6)
+               defer input.Release()
+
+               expBldr := array.NewStringViewBuilder(mem)
+               defer expBldr.Release()
+               expBldr.Append("ABCDEF" + upperLong)
+               expBldr.Append("ABCDXF" + upperLong)
+               expBldr.Append("ABCDEF")
+               expBldr.Append("ABCDEF" + upperLong)
+               expBldr.AppendNull()
+               expected := expBldr.NewArray()
+               defer expected.Release()
+
+               in, exp := compute.NewDatumWithoutOwning(input), 
compute.NewDatumWithoutOwning(expected)
+               defer in.Release()
+               defer exp.Release()
+               checkScalarUnary(t, "utf8_upper", in, exp, nil)
+       })
+
+       for _, dt := range []arrow.DataType{
+               arrow.BinaryTypes.String, arrow.BinaryTypes.LargeString, 
arrow.BinaryTypes.StringView,
+       } {
+               t.Run("invalid utf8/"+dt.String(), func(t *testing.T) {
+                       bldr := array.NewBuilder(mem, dt)
+                       defer bldr.Release()
+                       type appender interface{ AppendString(string) }
+                       ap := bldr.(appender)
+                       ap.AppendString("\xffbcdefghijklm")
+                       ap.AppendString("ab\xff")
+                       input := bldr.NewArray()
+                       defer input.Release()
+
+                       d := compute.NewDatumWithoutOwning(input)
+                       defer d.Release()
+                       _, err := compute.CallFunction(ctx, "utf8_upper", nil, 
d)
+                       assert.ErrorIs(t, err, arrow.ErrInvalid)
+                       _, err = compute.CallFunction(ctx, "utf8_lower", nil, d)
+                       assert.ErrorIs(t, err, arrow.ErrInvalid)
+               })
+       }
+}
+
+// TestUtf8CaseViewSingleBuffer verifies that the string_view kernels
+// return their output in one data buffer. A kernel result cannot carry the
+// second buffer a view builder allocates once its out-of-line values
+// outgrow the reservation, so the reservation has to cover the whole
+// input, inline values included: a 12-byte inline value of two-byte code
+// points maps to 18 bytes. Every code point is checked against
+// strings.ToUpper and strings.ToLower, which apply the same simple case
+// mapping.
+func TestUtf8CaseViewSingleBuffer(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+       t.Cleanup(func() { mem.AssertSize(t, 0) })
+       ctx := compute.WithAllocator(context.Background(), mem)
+
+       fns := []struct {
+               name string
+               call func(context.Context, compute.Datum) (compute.Datum, error)
+               ref  func(string) string
+       }{
+               {"utf8_upper", compute.Utf8Upper, strings.ToUpper},
+               {"utf8_lower", compute.Utf8Lower, strings.ToLower},
+       }
+       check := func(t *testing.T, values []string, input arrow.Array) {
+               in := compute.NewDatumWithoutOwning(input)
+               defer in.Release()
+
+               for _, fn := range fns {
+                       t.Run(fn.name, func(t *testing.T) {
+                               got, err := fn.call(ctx, in)
+                               require.NoError(t, err)
+                               defer got.Release()
+
+                               out := got.(*compute.ArrayDatum).Value
+                               require.Len(t, out.Buffers(), 3, "output must 
fit one data buffer")
+                               arr := 
array.MakeFromData(out).(*array.StringView)
+                               defer arr.Release()
+                               require.Equal(t, len(values), arr.Len())
+                               for i, v := range values {
+                                       require.Equal(t, fn.ref(v), 
arr.Value(i), "value %d: %q", i, v)
+                               }
+                       })
+               }
+       }
+
+       t.Run("inline values that grow out of line", func(t *testing.T) {
+               // 2000 values of 18 bytes need more than one 32 KiB block if 
the
+               // reservation does not cover them.
+               bldr := array.NewStringViewBuilder(mem)
+               v := strings.Repeat("\u0250", 6)
+               values := make([]string, 2000)
+               for i := range values {
+                       values[i] = v
+                       bldr.Append(v)
+               }
+               input := bldr.NewArray()
+               defer input.Release()
+               check(t, values, input)
+       })
+
+       t.Run("all code points", func(t *testing.T) {
+               // Six copies of a two-byte code point make an inline value.
+               var values []string
+               bldr := array.NewStringViewBuilder(mem)
+               for r := rune(0); r <= utf8.MaxRune; r++ {
+                       if !utf8.ValidRune(r) {
+                               continue
+                       }
+                       s := strings.Repeat(string(r), 6)
+                       values = append(values, s)
+                       bldr.Append(s)
+               }
+               input := bldr.NewArray()
+               defer input.Release()
+               check(t, values, input)
+       })
+}
+
+func TestUtf8StringFuncs(t *testing.T) {
+       mem := memory.NewCheckedAllocator(memory.DefaultAllocator)
+       t.Cleanup(func() { mem.AssertSize(t, 0) })
+       ctx := compute.WithAllocator(context.Background(), mem)
+
+       input, _, err := array.FromJSON(mem, arrow.BinaryTypes.String, 
strings.NewReader(`["aBá", null]`))
+       require.NoError(t, err)
+       defer input.Release()
+       in := compute.NewDatumWithoutOwning(input)
+       defer in.Release()
+
+       lengths, err := compute.Utf8Length(ctx, in)
+       require.NoError(t, err)
+       defer lengths.Release()
+       expLen, _, err := array.FromJSON(mem, arrow.PrimitiveTypes.Int32, 
strings.NewReader(`[3, null]`))
+       require.NoError(t, err)
+       defer expLen.Release()
+       assertDatumsEqual(t, compute.NewDatumWithoutOwning(expLen), lengths, 
nil, nil)
+
+       upper, err := compute.Utf8Upper(ctx, in)
+       require.NoError(t, err)
+       defer upper.Release()
+       expUpper, _, err := array.FromJSON(mem, arrow.BinaryTypes.String, 
strings.NewReader(`["ABÁ", null]`))
+       require.NoError(t, err)
+       defer expUpper.Release()
+       assertDatumsEqual(t, compute.NewDatumWithoutOwning(expUpper), upper, 
nil, nil)
+
+       lower, err := compute.Utf8Lower(ctx, in)
+       require.NoError(t, err)
+       defer lower.Release()
+       expLower, _, err := array.FromJSON(mem, arrow.BinaryTypes.String, 
strings.NewReader(`["abá", null]`))
+       require.NoError(t, err)
+       defer expLower.Release()
+       assertDatumsEqual(t, compute.NewDatumWithoutOwning(expLower), lower, 
nil, nil)
+}

Reply via email to