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 9d790025 perf(parquet/internal/encoding): speed up ALP decoding (#1552)
9d790025 is described below

commit 9d79002556c4f762717c6518a0e734671990e29c
Author: Matt Topol <[email protected]>
AuthorDate: Wed Nov 18 11:57:00 2026 -0500

    perf(parquet/internal/encoding): speed up ALP decoding (#1552)
    
    ### Rationale for this change
    
    Decoding an ALP vector makes four passes over its values, and copies the
    packed bytes once before the first:
    
    - `BitReader.GetBatch` unpacks the deltas. The vectorized unpackers
    behind it read through an `io.Reader`, so the packed bytes are copied
    into a pooled buffer first, and the unpacked `uint32`s are then widened
    to `uint64`.
    - A loop generic over the float type adds the frame of reference to each
    delta and scales it into the decoder's buffer.
    - The exceptions are patched in through a generic helper that looks the
    type up for every value.
    - The values are copied to the caller.
    
    Deltas wider than 32 bits never reach the vectorized unpackers:
    `GetBatch` reads them one value at a time.
    
    On amd64 the AVX2 unpacker is itself slow at most widths. At any width
    that does not divide 32, it builds each register from scalar inserts
    (`vpinsrd`), which Intel runs on one port: unpacking 1,024 deltas of 14
    bits takes about 0.69µs, against 0.13µs at 8 bits. Scaling them, one
    `CVTSI2SDQ` and two `MULSD` at a time, takes about 1µs more.
    
    ### What changes are included in this PR?
    
    - `utils.Unpack32Vectorized` runs the NEON or AVX2 unpacker on a byte
    slice directly. It unpacks nothing on a platform without one.
    - Deltas of up to 32 bits are unpacked with it straight from the page,
    and scaled in a second pass written for each type. Wider deltas, and
    every delta on a platform without a vectorized unpacker, are unpacked
    and scaled in one pass, with one 8-byte load per delta.
    - On amd64 with AVX2, deltas of up to 25 bits are decoded in one pass by
    a kernel in assembly. A group of 8 deltas spans whole bytes, so the
    kernel loads it with two 16-byte loads, moves the 4 bytes holding each
    delta into its own 32-bit lane with a shuffle, shifts and masks it, adds
    the frame of reference, converts, scales, and stores the 8 values. The
    shuffles, shifts and masks for each width are built once.
    - AVX2 cannot convert an int64 to a double. A `DOUBLE` vector whose
    integers all lie in [-2^51, 2^51) converts with one integer addition and
    one subtraction. Any other converts the upper 48 bits and the lower 16
    apart, both exactly, and rounds once in the final addition. Both give
    the double `CVTSI2SDQ` gives, and the scaling is two multiplications, as
    in Go, so a page decodes to the same bits on every platform.
    - Wider deltas, and every delta on arm64, go through the loops above.
    - A read that starts at a vector and covers all of it is decoded into
    the caller's slice rather than the decoder's buffer.
    - Exceptions are patched by a loop written for each type.
    - A vector of zero bit width is filled with its one value.
    
    The unpacking loops load a few bytes past a vector's packed deltas.
    Those bytes are the vector's exceptions or the next vector. Only the
    last vector of a page can be without them, and it is unpacked from a
    padded copy. The AVX2 kernel loads up to 16 bytes past the middle of a
    group, and decodes only the groups whose loads stay inside the page; the
    loops above decode the rest.
    
    Timings on an Apple M4 (darwin/arm64), which this PR's AVX2 kernel does
    not change. The machine was busy with other work, so `main` and this
    branch were run in alternating short turns, 50 samples each. The spread
    is wide, and the absolute times are slower than on an idle machine, but
    both sides ran under the same conditions:
    
    ```
                                                   │     main      │            
      PR                  │
                                                   │    sec/op     │    sec/op  
   vs base                │
    ALPDecodingFloat32/no_exceptions/len_1024-10     1258.0n ± 12%   599.8n ± 
10%  -52.32% (p=0.000 n=50)
    ALPDecodingFloat32/no_exceptions/len_65536-10     84.73µ ± 16%   35.62µ ± 
17%  -57.96% (p=0.000 n=50)
    ALPDecodingFloat32/10%_exceptions/len_1024-10    1607.0n ± 11%   593.0n ± 
14%  -63.10% (n=50)
    ALPDecodingFloat32/10%_exceptions/len_65536-10   111.59µ ±  6%   40.05µ ± 
11%  -64.12% (p=0.000 n=50)
    ALPDecodingFloat32/all_exceptions/len_1024-10    4287.0n ± 15%   809.5n ± 
12%  -81.12% (p=0.000 n=50)
    ALPDecodingFloat32/all_exceptions/len_65536-10   260.66µ ± 13%   51.08µ ± 
14%  -80.40% (p=0.000 n=50)
    ALPDecodingFloat64/no_exceptions/len_1024-10     1335.5n ± 13%   591.8n ± 
16%  -55.69% (p=0.000 n=50)
    ALPDecodingFloat64/no_exceptions/len_65536-10     93.38µ ±  9%   36.95µ ± 
10%  -60.43% (p=0.000 n=50)
    ALPDecodingFloat64/10%_exceptions/len_1024-10    1741.5n ±  8%   651.2n ± 
17%  -62.61% (n=50)
    ALPDecodingFloat64/10%_exceptions/len_65536-10   103.73µ ± 13%   42.27µ ± 
15%  -59.25% (p=0.000 n=50)
    ALPDecodingFloat64/all_exceptions/len_1024-10    4158.5n ± 14%   736.5n ± 
12%  -82.29% (n=50)
    ALPDecodingFloat64/all_exceptions/len_65536-10   255.89µ ± 21%   52.04µ ± 
14%  -79.66% (p=0.000 n=50)
    ALPDecodingFloat64Batched/len_1024-10            1732.5n ± 16%   857.5n ± 
13%  -50.50% (p=0.000 n=50)
    ALPDecodingFloat64Batched/len_65536-10           109.50µ ± 13%   55.60µ ± 
13%  -49.23% (p=0.000 n=50)
    ALPDecodingFloat64Wide/len_1024-10                8.127µ ± 15%   1.096µ ±  
8%  -86.51% (n=50)
    ALPDecodingFloat64Wide/len_65536-10              519.79µ ±  9%   63.99µ ± 
10%  -87.69% (p=0.000 n=50)
    geomean                                           19.42µ         5.795µ     
   -70.16%
    ```
    
    `Wide` is a benchmark this PR adds, for deltas of about 50 bits.
    
    Timings on an Intel Core Ultra 7 155H (linux/amd64, AVX2), Go 1.27.4.
    `main` is this PR's base, fc5d5ce5, with this PR's benchmark file, and
    `PR` is this PR without the AVX2 kernel. Each binary was pinned to one
    performance core, and the three were run in alternating turns, 30
    samples each. Other work was running on the machine, with a load average
    that ranged from about 2 to 18 on 22 threads, so the spread is wide:
    
    ```
                                                │     main      │               
   PR                   │                 AVX2                 │
                                                │    sec/op     │    sec/op     
 vs base                │    sec/op     vs base                │
    ALPDecodingFloat32/no_exceptions/len_1024     1542.0n ± 19%    892.2n ± 18% 
 -42.14% (p=0.000 n=30)   212.8n ± 15%  -86.20% (p=0.000 n=30)
    ALPDecodingFloat32/no_exceptions/len_65536    101.57µ ± 17%    56.07µ ± 12% 
 -44.80% (p=0.000 n=30)   11.63µ ± 16%  -88.55% (p=0.000 n=30)
    ALPDecodingFloat32/10%_exceptions/len_1024    1989.0n ± 15%    945.0n ± 13% 
 -52.49% (p=0.000 n=30)   227.5n ± 12%  -88.56% (p=0.000 n=30)
    ALPDecodingFloat32/10%_exceptions/len_65536   128.25µ ±  9%    59.54µ ± 12% 
 -53.58% (p=0.000 n=30)   13.82µ ± 19%  -89.22% (p=0.000 n=30)
    ALPDecodingFloat32/all_exceptions/len_1024    4901.0n ± 14%    646.5n ± 11% 
 -86.81% (p=0.000 n=30)   636.9n ± 17%  -87.00% (p=0.000 n=30)
    ALPDecodingFloat32/all_exceptions/len_65536   312.37µ ±  8%    42.89µ ± 13% 
 -86.27% (p=0.000 n=30)   39.93µ ± 20%  -87.22% (p=0.000 n=30)
    ALPDecodingFloat64/no_exceptions/len_1024     1462.0n ± 10%    906.2n ± 13% 
 -38.02% (p=0.000 n=30)   323.6n ± 17%  -77.86% (p=0.000 n=30)
    ALPDecodingFloat64/no_exceptions/len_65536    103.54µ ±  9%    56.68µ ± 13% 
 -45.25% (p=0.000 n=30)   19.08µ ± 18%  -81.57% (p=0.000 n=30)
    ALPDecodingFloat64/10%_exceptions/len_1024    1896.0n ±  8%    958.4n ± 11% 
 -49.45% (p=0.000 n=30)   360.8n ± 17%  -80.97% (p=0.000 n=30)
    ALPDecodingFloat64/10%_exceptions/len_65536   124.38µ ±  8%    59.26µ ± 11% 
 -52.36% (p=0.000 n=30)   22.56µ ± 15%  -81.87% (p=0.000 n=30)
    ALPDecodingFloat64/all_exceptions/len_1024    4784.0n ± 12%    734.0n ± 15% 
 -84.66% (p=0.000 n=30)   685.0n ± 15%  -85.68% (p=0.000 n=30)
    ALPDecodingFloat64/all_exceptions/len_65536   307.59µ ± 14%    48.23µ ± 11% 
 -84.32% (p=0.000 n=30)   45.14µ ± 13%  -85.32% (p=0.000 n=30)
    ALPDecodingFloat64Batched/len_1024            2011.0n ± 11%   1138.5n ± 14% 
 -43.39% (p=0.000 n=30)   551.3n ± 11%  -72.59% (p=0.000 n=30)
    ALPDecodingFloat64Batched/len_65536           130.90µ ± 12%    70.85µ ± 13% 
 -45.87% (p=0.000 n=30)   32.67µ ± 15%  -75.04% (p=0.000 n=30)
    ALPDecodingFloat64Wide/len_1024                8.655µ ±  8%    1.700µ ± 14% 
 -80.37% (p=0.000 n=30)   1.619µ ± 18%  -81.30% (p=0.000 n=30)
    ALPDecodingFloat64Wide/len_65536               589.9µ ± 12%    109.6µ ± 17% 
 -81.42% (p=0.000 n=30)   101.4µ ± 13%  -82.81% (p=0.000 n=30)
    geomean                                        22.50µ          7.589µ       
 -66.27%                  3.630µ        -83.87%
    ```
    
    The benchmarks' `DOUBLE` values take the short conversion. On 1,024
    values the long one took about 0.70µs, against 1.1µs to 1.7µs without
    the kernel, in a separate run.
    
    `all_exceptions` vectors have a bit width of 0, so the kernel does not
    change them, nor `Wide`, whose deltas are about 50 bits.
    
    ### Are these changes tested?
    
    Yes, by new tests of the loops and of the decoder, and by the existing
    ALP tests. `TestALPDecodePacked` compares the decoded bits with Go's own
    conversion at every width, at lengths either side of the groups of 4, 8
    and 32 the loops work in, and with frames of reference either side of
    each end of the range the short `DOUBLE` conversion takes.
    `TestALPDecodePackedGuardPage` decodes deltas placed against a page that
    cannot be read, at every width. Both also pass with `-tags noasm` and on
    386.
    
    ### Are there any user-facing changes?
    
    No.
---
 parquet/internal/encoding/alp_encoding.go          | 132 +++++------
 .../encoding/alp_encoding_benchmark_test.go        |  34 +++
 parquet/internal/encoding/alp_encoding_test.go     |  27 ++-
 parquet/internal/encoding/alp_scaling.go           |  11 -
 parquet/internal/encoding/alp_unpack.go            | 215 ++++++++++++++++++
 parquet/internal/encoding/alp_unpack_amd64.go      | 116 ++++++++++
 parquet/internal/encoding/alp_unpack_avx2_amd64.s  | 195 ++++++++++++++++
 parquet/internal/encoding/alp_unpack_guard_test.go |  73 ++++++
 parquet/internal/encoding/alp_unpack_test.go       | 250 +++++++++++++++++++++
 parquet/internal/utils/bit_packing_amd64.go        |   1 +
 parquet/internal/utils/bit_packing_arm64.go        |   1 +
 parquet/internal/utils/bit_packing_avx2_amd64.go   |   4 +
 parquet/internal/utils/bit_packing_default.go      |  22 ++
 parquet/internal/utils/bit_packing_neon_arm64.go   |   4 +
 parquet/internal/utils/unpack32_vectorized_test.go |  75 +++++++
 15 files changed, 1063 insertions(+), 97 deletions(-)

diff --git a/parquet/internal/encoding/alp_encoding.go 
b/parquet/internal/encoding/alp_encoding.go
index 52dbcafb..fd518b3f 100644
--- a/parquet/internal/encoding/alp_encoding.go
+++ b/parquet/internal/encoding/alp_encoding.go
@@ -37,7 +37,6 @@ package encoding
 // Reference: https://dl.acm.org/doi/10.1145/3626717
 
 import (
-       "bytes"
        "encoding/binary"
        "errors"
        "fmt"
@@ -98,27 +97,6 @@ func alpAppendPackedBits(dst []byte, values []uint64, 
bitWidth int) []byte {
        return dst[:start+size]
 }
 
-// alpUnpackBits reverses alpAppendPackedBits into out, which must hold as many
-// values as were packed. The reader is reset onto packed, so one reader serves
-// every vector of a page.
-func alpUnpackBits(br *utils.BitReader, packed *bytes.Reader, data []byte, out 
[]uint64, bitWidth int) error {
-       if bitWidth == 0 {
-               clear(out)
-               return nil
-       }
-
-       packed.Reset(data)
-       br.Reset(packed)
-       n, err := br.GetBatch(uint(bitWidth), out)
-       if err != nil {
-               return err
-       }
-       if n != len(out) {
-               return fmt.Errorf("parquet: ALP unpacked %d of %d values", n, 
len(out))
-       }
-       return nil
-}
-
 func alpAppendInt[T alpFloat](dst []byte, v uint64) []byte {
        if alpEncodedBytes[T]() == 4 {
                return binary.LittleEndian.AppendUint32(dst, uint32(v))
@@ -133,13 +111,6 @@ func alpReadInt[T alpFloat](src []byte) int64 {
        return int64(binary.LittleEndian.Uint64(src))
 }
 
-func alpReadFloat[T alpFloat](src []byte) T {
-       if alpEncodedBytes[T]() == 4 {
-               return 
alpFloatFromBits[T](uint64(binary.LittleEndian.Uint32(src)))
-       }
-       return alpFloatFromBits[T](binary.LittleEndian.Uint64(src))
-}
-
 // alpEncoder encodes a float column with ALP, a vector at a time. It buffers
 // values until it holds a whole vector, so the values of a page reach the sink
 // only when the caller flushes it.
@@ -476,20 +447,16 @@ type alpDecoder[T alpFloat] struct {
        currentVectorIndex int
        currentIndex       int
        decodedValues      []T
-       deltas             []uint64
 
-       // One reader pair, reset onto each vector's packed deltas in turn.
-       packedReader *bytes.Reader
-       bitReader    *utils.BitReader
+       // Deltas of up to 32 bits, between unpacking and scaling.
+       unpacked []uint32
+       // A padded copy of a vector's packed deltas, for the one vector whose
+       // unpacking would otherwise load past the end of the page.
+       padded []byte
 }
 
 func newALPDecoder[T alpFloat](e format.Encoding, descr *schema.Column) 
*alpDecoder[T] {
-       packed := bytes.NewReader(nil)
-       return &alpDecoder[T]{
-               decoder:      newDecoderBase(e, descr),
-               packedReader: packed,
-               bitReader:    utils.NewBitReader(packed),
-       }
+       return &alpDecoder[T]{decoder: newDecoderBase(e, descr)}
 }
 
 func (dec *alpDecoder[T]) Type() parquet.Type {
@@ -563,7 +530,7 @@ func (dec *alpDecoder[T]) SetData(nvals int, data []byte) 
error {
        // from there rather than from the start of the data.
        dec.bodyData = data[alpHeaderSize:]
        dec.decodedValues = slices.Grow(dec.decodedValues[:0], 
dec.vectorSize)[:dec.vectorSize]
-       dec.deltas = slices.Grow(dec.deltas[:0], 
dec.vectorSize)[:dec.vectorSize]
+       dec.unpacked = slices.Grow(dec.unpacked[:0], 
dec.vectorSize)[:dec.vectorSize]
 
        return nil
 }
@@ -580,10 +547,11 @@ func (dec *alpDecoder[T]) vectorLength(vectorIdx int) int 
{
        return dec.vectorSize
 }
 
-// decodeVector decodes one vector into dec.decodedValues. It checks every size
-// and position it reads, since the page may be truncated or corrupt.
-func (dec *alpDecoder[T]) decodeVector(vectorIdx int) error {
-       vectorLen := dec.vectorLength(vectorIdx)
+// decodeVector decodes one vector into out, which holds exactly the vector's
+// values. It checks every size and position it reads, since the page may be
+// truncated or corrupt.
+func (dec *alpDecoder[T]) decodeVector(vectorIdx int, out []T) error {
+       vectorLen := len(out)
        valueBytes := alpEncodedBytes[T]()
 
        // On 32-bit platforms, converting a large uint32 offset can make pos
@@ -626,39 +594,48 @@ func (dec *alpDecoder[T]) decodeVector(vectorIdx int) 
error {
                        vectorIdx, end, vectorIdx+1, 
dec.vectorOffsets[vectorIdx+1])
        }
 
-       deltas := dec.deltas[:vectorLen]
-       if err := alpUnpackBits(dec.bitReader, dec.packedReader, 
dec.bodyData[pos:pos+packedSize], deltas, bitWidth); err != nil {
-               return err
+       // Positions come first among the exceptions, then the values.
+       packed := dec.bodyData[pos:]
+       positions := dec.bodyData[pos+packedSize : 
pos+packedSize+numExceptions*2]
+       excValues := dec.bodyData[pos+packedSize+numExceptions*2 : end]
+       // Unpacking loads a few bytes past the deltas. Those are the 
exceptions or
+       // the next vector, except at the end of the page, where there may be 
none.
+       if need := alpUnpackSize(vectorLen, bitWidth); bitWidth > 0 && need > 
len(packed) {
+               dec.padded = slices.Grow(dec.padded[:0], need)[:need]
+               clear(dec.padded[copy(dec.padded, packed):])
+               packed = dec.padded
        }
-       pos += packedSize
 
        // The deltas were computed in the encoded integer's width with wrapping
-       // arithmetic, so add the frame of reference back the same way.
-       s := newALPScaling[T](exponent, factor)
-       out := dec.decodedValues[:len(deltas)]
-       if valueBytes == 4 {
-               ref := uint32(frameOfRef)
-               for i, d := range deltas {
-                       out[i] = s.decode(int64(int32(uint32(d) + ref)))
+       // arithmetic, so the frame of reference is added back the same way.
+       bad := -1
+       switch out := any(out).(type) {
+       case []float64:
+               fac, exp := alpDoublePow10[factor], alpDoubleNegPow10[exponent]
+               if bitWidth == 0 {
+                       v := float64(frameOfRef) * fac * exp
+                       for i := range out {
+                               out[i] = v
+                       }
+               } else {
+                       alpDecodePacked64(out, packed, uint(bitWidth), 
uint64(frameOfRef), fac, exp, dec.unpacked)
                }
-       } else {
-               ref := uint64(frameOfRef)
-               for i, d := range deltas {
-                       out[i] = s.decode(int64(d + ref))
+               bad = alpPatch64(out, positions, excValues)
+       case []float32:
+               fac, exp := alpFloatPow10[factor], alpFloatNegPow10[exponent]
+               if bitWidth == 0 {
+                       v := float32(int32(frameOfRef)) * fac * exp
+                       for i := range out {
+                               out[i] = v
+                       }
+               } else {
+                       alpDecodePacked32(out, packed, uint(bitWidth), 
uint32(frameOfRef), fac, exp, dec.unpacked)
                }
+               bad = alpPatch32(out, positions, excValues)
        }
-
-       // Positions come first, then the values, so read both in one pass 
instead
-       // of copying the positions out.
-       valuePos := pos + numExceptions*2
-       for e := range numExceptions {
-               idx := binary.LittleEndian.Uint16(dec.bodyData[pos+e*2:])
-               if int(idx) >= vectorLen {
-                       return fmt.Errorf("parquet: ALP exception position %d 
is outside vector %d", idx, vectorIdx)
-               }
-               dec.decodedValues[idx] = 
alpReadFloat[T](dec.bodyData[valuePos+e*valueBytes:])
+       if bad >= 0 {
+               return fmt.Errorf("parquet: ALP exception position %d is 
outside vector %d", bad, vectorIdx)
        }
-
        return nil
 }
 
@@ -673,8 +650,20 @@ func (dec *alpDecoder[T]) Decode(out []T) (int, error) {
        // vectors.
        for read < toRead && dec.currentIndex < dec.totalCount {
                vectorIdx := dec.currentIndex / dec.vectorSize
+               vectorLen := dec.vectorLength(vectorIdx)
+               if dec.currentIndex%dec.vectorSize == 0 && toRead-read >= 
vectorLen {
+                       // The caller wants the whole vector, so decode it 
where it goes
+                       // rather than into the decoder's buffer and copy it 
across.
+                       if err := dec.decodeVector(vectorIdx, 
out[read:read+vectorLen]); err != nil {
+                               dec.nvals -= read
+                               return read, err
+                       }
+                       read += vectorLen
+                       dec.currentIndex += vectorLen
+                       continue
+               }
                if vectorIdx != dec.currentVectorIndex {
-                       if err := dec.decodeVector(vectorIdx); err != nil {
+                       if err := dec.decodeVector(vectorIdx, 
dec.decodedValues[:vectorLen]); err != nil {
                                dec.nvals -= read
                                return read, err
                        }
@@ -682,7 +671,6 @@ func (dec *alpDecoder[T]) Decode(out []T) (int, error) {
                }
 
                indexInVector := dec.currentIndex % dec.vectorSize
-               vectorLen := dec.vectorLength(vectorIdx)
                n := copy(out[read:toRead], 
dec.decodedValues[indexInVector:vectorLen])
                read += n
                dec.currentIndex += n
diff --git a/parquet/internal/encoding/alp_encoding_benchmark_test.go 
b/parquet/internal/encoding/alp_encoding_benchmark_test.go
index 7c323043..94166990 100644
--- a/parquet/internal/encoding/alp_encoding_benchmark_test.go
+++ b/parquet/internal/encoding/alp_encoding_benchmark_test.go
@@ -198,3 +198,37 @@ func BenchmarkALPDecodingFloat64Batched(b *testing.B) {
                })
        }
 }
+
+// Whole numbers up to 2^50 pack at about 50 bits each with no exceptions,
+// which is wider than the 32 bits the vectorized unpackers handle.
+func BenchmarkALPDecodingFloat64Wide(b *testing.B) {
+       for sz := MINSIZE; sz < MAXSIZE+1; sz *= 2 {
+               b.Run(fmt.Sprintf("len %d", sz), func(b *testing.B) {
+                       values := make([]float64, sz)
+                       for i := range values {
+                               values[i] = float64((uint64(i) * 
0x9E3779B97F4A7C15) >> 14)
+                       }
+                       output := make([]float64, sz)
+                       encoder := encoding.NewEncoder(parquet.Types.Double, 
parquet.Encodings.ALP,
+                               false, nil, 
memory.DefaultAllocator).(encoding.Float64Encoder)
+                       defer encoder.Release()
+                       encoder.Put(values)
+                       buf, _ := encoder.FlushValues()
+                       defer buf.Release()
+
+                       decoder := encoding.NewDecoder(parquet.Types.Double, 
parquet.Encodings.ALP,
+                               nil, 
memory.DefaultAllocator).(encoding.Float64Decoder)
+                       b.ReportAllocs()
+                       b.ResetTimer()
+                       b.SetBytes(int64(len(values) * arrow.Float64SizeBytes))
+                       for b.Loop() {
+                               if err := decoder.SetData(sz, buf.Bytes()); err 
!= nil {
+                                       b.Fatal(err)
+                               }
+                               if _, err := decoder.Decode(output); err != nil 
{
+                                       b.Fatal(err)
+                               }
+                       }
+               })
+       }
+}
diff --git a/parquet/internal/encoding/alp_encoding_test.go 
b/parquet/internal/encoding/alp_encoding_test.go
index 8c77fef5..2dd3f17b 100644
--- a/parquet/internal/encoding/alp_encoding_test.go
+++ b/parquet/internal/encoding/alp_encoding_test.go
@@ -34,11 +34,20 @@ import (
        "github.com/stretchr/testify/require"
 )
 
-// alpTestUnpackBits unpacks with readers of its own, since the decoder's are
-// tied to a page.
+// alpTestUnpackBits reverses alpAppendPackedBits with a plain bit reader.
 func alpTestUnpackBits(packed []byte, out []uint64, bitWidth int) error {
-       reader := bytes.NewReader(nil)
-       return alpUnpackBits(utils.NewBitReader(reader), reader, packed, out, 
bitWidth)
+       if bitWidth == 0 {
+               clear(out)
+               return nil
+       }
+       n, err := 
utils.NewBitReader(bytes.NewReader(packed)).GetBatch(uint(bitWidth), out)
+       if err != nil {
+               return err
+       }
+       if n != len(out) {
+               return fmt.Errorf("unpacked %d of %d values", n, len(out))
+       }
+       return nil
 }
 
 func TestALPPackUnpackBits(t *testing.T) {
@@ -95,16 +104,6 @@ func TestALPPackBitsKnownOutput(t *testing.T) {
        assert.Equal(t, byte(0xE4), packed[0])
 }
 
-// TestALPUnpackBitsShortInput requires truncated packed data to return an 
error.
-// The two lengths cover the scalar path for a partial group of 32 values and 
the
-// vectorized path for a whole group.
-func TestALPUnpackBitsShortInput(t *testing.T) {
-       for _, count := range []int{8, 64} {
-               out := make([]uint64, count)
-               assert.Error(t, alpTestUnpackBits([]byte{0xFF}, out, 8), 
"count=%d", count)
-       }
-}
-
 func newFloat32Column() *schema.Column {
        return schema.NewColumn(schema.NewFloat32Node("float32", 
parquet.Repetitions.Required, -1), 0, 0)
 }
diff --git a/parquet/internal/encoding/alp_scaling.go 
b/parquet/internal/encoding/alp_scaling.go
index 5270ac76..f0b8930b 100644
--- a/parquet/internal/encoding/alp_scaling.go
+++ b/parquet/internal/encoding/alp_scaling.go
@@ -143,17 +143,6 @@ func alpFloatToBits[T alpFloat](v T) uint64 {
        panic("parquet: ALP: unsupported float type")
 }
 
-func alpFloatFromBits[T alpFloat](b uint64) T {
-       var z T
-       switch any(z).(type) {
-       case float32:
-               return T(math.Float32frombits(uint32(b)))
-       case float64:
-               return T(math.Float64frombits(b))
-       }
-       panic("parquet: ALP: unsupported float type")
-}
-
 // alpScaling holds the constants of one exponent and factor pair. Encoding and
 // decoding look them up once per vector rather than once per value.
 type alpScaling[T alpFloat] struct {
diff --git a/parquet/internal/encoding/alp_unpack.go 
b/parquet/internal/encoding/alp_unpack.go
new file mode 100644
index 00000000..dbf075e4
--- /dev/null
+++ b/parquet/internal/encoding/alp_unpack.go
@@ -0,0 +1,215 @@
+// 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.
+
+package encoding
+
+// The loops that turn one ALP vector back into values, written once for each
+// physical type. A loop generic over the type looks the type up for every
+// value; these do not.
+
+import (
+       "encoding/binary"
+       "math"
+
+       "github.com/apache/arrow-go/v18/parquet/internal/utils"
+)
+
+// alpUnpackSlack is how many bytes past the first byte of a vector's last
+// packed delta the unpacking loops may load. A delta starts at most 7 bits
+// into a byte, so up to 57 bits wide it lies inside one 8-byte load, and a
+// wider one takes a ninth byte.
+const alpUnpackSlack = 9
+
+// alpUnpackSize returns how many bytes of packed deltas the unpacking loops
+// load for count values of bitWidth bits. That is more than the deltas occupy:
+// a load takes in whatever follows them, and a mask discards it.
+func alpUnpackSize(count, bitWidth int) int {
+       return (count-1)*bitWidth/8 + alpUnpackSlack
+}
+
+// alpDecodeGroups64 and alpDecodeGroups32 are the platform's kernels that
+// unpack, add the frame of reference and scale in one pass, as many whole
+// groups of 8 deltas as they can from the front of src, and return how many
+// values that was. They are nil where there are none.
+var (
+       alpDecodeGroups64 func(out []float64, src []byte, bitWidth uint, ref 
uint64, fac, exp float64) int
+       alpDecodeGroups32 func(out []float32, src []byte, bitWidth uint, ref 
uint32, fac, exp float32) int
+)
+
+// alpDecodePacked64 unpacks len(out) deltas of bitWidth bits from the front of
+// src, adds the frame of reference to each and scales it. bitWidth is 1 to 64,
+// and src holds alpUnpackSize bytes.
+//
+// The platform's kernel, where there is one, decodes what it can. Of the rest,
+// deltas of up to 32 bits are unpacked 32 at a time into scratch, which holds
+// len(out) values, and scaled in a second pass. Where the unpacking is
+// vectorized, that is faster than doing both in one pass.
+//
+// Wider deltas, the few left of a short vector, and every delta on a platform
+// without a vectorized unpacker are unpacked and scaled one at a time.
+func alpDecodePacked64(out []float64, src []byte, bitWidth uint, ref uint64, 
fac, exp float64, scratch []uint32) {
+       if alpDecodeGroups64 != nil {
+               // A group of 8 values ends on a byte boundary at any width.
+               n := alpDecodeGroups64(out, src, bitWidth, ref, fac, exp)
+               out, src = out[n:], src[n*int(bitWidth)/8:]
+       }
+       if bitWidth <= 32 {
+               n := utils.Unpack32Vectorized(src, scratch[:len(out)], 
int(bitWidth))
+               head := out[:n]
+               for i, d := range scratch[:n] {
+                       head[i] = float64(int64(uint64(d)+ref)) * fac * exp
+               }
+               // A group of 32 values ends on a byte boundary at any width.
+               out, src = out[n:], src[n*int(bitWidth)/8:]
+       }
+
+       mask := ^uint64(0) >> (64 - bitWidth)
+       bitPos := uint(0)
+       if bitWidth > 57 {
+               for i := range out {
+                       offset, shift := bitPos>>3, bitPos&7
+                       lo := binary.LittleEndian.Uint64(src[offset:])
+                       hi := uint64(src[offset+8])
+                       // Shifting by 64 gives zero, which is what a delta 
that starts
+                       // on a byte boundary needs of the ninth byte.
+                       d := (lo>>shift | hi<<(64-shift)) & mask
+                       out[i] = float64(int64(d+ref)) * fac * exp
+                       bitPos += bitWidth
+               }
+               return
+       }
+
+       // Four at a time: the loads do not depend on one another, and the 
loop's
+       // own bookkeeping is otherwise a large share of the work.
+       i := 0
+       for ; i+4 <= len(out); i += 4 {
+               o := out[i : i+4 : i+4]
+               p1, p2, p3 := bitPos+bitWidth, bitPos+2*bitWidth, 
bitPos+3*bitWidth
+               d0 := binary.LittleEndian.Uint64(src[bitPos>>3:]) >> (bitPos & 
7) & mask
+               d1 := binary.LittleEndian.Uint64(src[p1>>3:]) >> (p1 & 7) & mask
+               d2 := binary.LittleEndian.Uint64(src[p2>>3:]) >> (p2 & 7) & mask
+               d3 := binary.LittleEndian.Uint64(src[p3>>3:]) >> (p3 & 7) & mask
+               o[0] = float64(int64(d0+ref)) * fac * exp
+               o[1] = float64(int64(d1+ref)) * fac * exp
+               o[2] = float64(int64(d2+ref)) * fac * exp
+               o[3] = float64(int64(d3+ref)) * fac * exp
+               bitPos += 4 * bitWidth
+       }
+       for ; i < len(out); i++ {
+               d := binary.LittleEndian.Uint64(src[bitPos>>3:]) >> (bitPos & 
7) & mask
+               out[i] = float64(int64(d+ref)) * fac * exp
+               bitPos += bitWidth
+       }
+}
+
+// alpDecodePacked32 is the FLOAT form of alpDecodePacked64, with bitWidth from
+// 1 to 32. The frame of reference is added in 32 bits, as it was subtracted.
+func alpDecodePacked32(out []float32, src []byte, bitWidth uint, ref uint32, 
fac, exp float32, scratch []uint32) {
+       if alpDecodeGroups32 != nil {
+               n := alpDecodeGroups32(out, src, bitWidth, ref, fac, exp)
+               out, src = out[n:], src[n*int(bitWidth)/8:]
+       }
+       n := utils.Unpack32Vectorized(src, scratch[:len(out)], int(bitWidth))
+       head := out[:n]
+       for i, d := range scratch[:n] {
+               head[i] = float32(int32(d+ref)) * fac * exp
+       }
+       out, src = out[n:], src[n*int(bitWidth)/8:]
+
+       mask := ^uint64(0) >> (64 - bitWidth)
+       bitPos := uint(0)
+       i := 0
+       for ; i+4 <= len(out); i += 4 {
+               o := out[i : i+4 : i+4]
+               p1, p2, p3 := bitPos+bitWidth, bitPos+2*bitWidth, 
bitPos+3*bitWidth
+               d0 := binary.LittleEndian.Uint64(src[bitPos>>3:]) >> (bitPos & 
7) & mask
+               d1 := binary.LittleEndian.Uint64(src[p1>>3:]) >> (p1 & 7) & mask
+               d2 := binary.LittleEndian.Uint64(src[p2>>3:]) >> (p2 & 7) & mask
+               d3 := binary.LittleEndian.Uint64(src[p3>>3:]) >> (p3 & 7) & mask
+               o[0] = float32(int32(uint32(d0)+ref)) * fac * exp
+               o[1] = float32(int32(uint32(d1)+ref)) * fac * exp
+               o[2] = float32(int32(uint32(d2)+ref)) * fac * exp
+               o[3] = float32(int32(uint32(d3)+ref)) * fac * exp
+               bitPos += 4 * bitWidth
+       }
+       for ; i < len(out); i++ {
+               d := binary.LittleEndian.Uint64(src[bitPos>>3:]) >> (bitPos & 
7) & mask
+               out[i] = float32(int32(uint32(d)+ref)) * fac * exp
+               bitPos += bitWidth
+       }
+}
+
+// alpPatch64 overwrites out at each exception's position with the value stored
+// for it, and returns the first position outside out, or -1. positions holds
+// two bytes for each exception and values eight.
+func alpPatch64(out []float64, positions, values []byte) int {
+       values = values[:len(positions)*4]
+       // Four at a time, for the reason alpDecodePacked64 gives. A group with 
a
+       // position outside out is left to the loop below, which reports it.
+       for len(positions) >= 8 && len(values) >= 32 {
+               p, v := positions[:8], values[:32]
+               i0 := int(binary.LittleEndian.Uint16(p[0:]))
+               i1 := int(binary.LittleEndian.Uint16(p[2:]))
+               i2 := int(binary.LittleEndian.Uint16(p[4:]))
+               i3 := int(binary.LittleEndian.Uint16(p[6:]))
+               if i0 >= len(out) || i1 >= len(out) || i2 >= len(out) || i3 >= 
len(out) {
+                       break
+               }
+               out[i0] = 
math.Float64frombits(binary.LittleEndian.Uint64(v[0:]))
+               out[i1] = 
math.Float64frombits(binary.LittleEndian.Uint64(v[8:]))
+               out[i2] = 
math.Float64frombits(binary.LittleEndian.Uint64(v[16:]))
+               out[i3] = 
math.Float64frombits(binary.LittleEndian.Uint64(v[24:]))
+               positions, values = positions[8:], values[32:]
+       }
+       for len(positions) >= 2 && len(values) >= 8 {
+               idx := int(binary.LittleEndian.Uint16(positions))
+               if idx >= len(out) {
+                       return idx
+               }
+               out[idx] = 
math.Float64frombits(binary.LittleEndian.Uint64(values))
+               positions, values = positions[2:], values[8:]
+       }
+       return -1
+}
+
+// alpPatch32 is the FLOAT form of alpPatch64, with four bytes to a value.
+func alpPatch32(out []float32, positions, values []byte) int {
+       values = values[:len(positions)*2]
+       for len(positions) >= 8 && len(values) >= 16 {
+               p, v := positions[:8], values[:16]
+               i0 := int(binary.LittleEndian.Uint16(p[0:]))
+               i1 := int(binary.LittleEndian.Uint16(p[2:]))
+               i2 := int(binary.LittleEndian.Uint16(p[4:]))
+               i3 := int(binary.LittleEndian.Uint16(p[6:]))
+               if i0 >= len(out) || i1 >= len(out) || i2 >= len(out) || i3 >= 
len(out) {
+                       break
+               }
+               out[i0] = 
math.Float32frombits(binary.LittleEndian.Uint32(v[0:]))
+               out[i1] = 
math.Float32frombits(binary.LittleEndian.Uint32(v[4:]))
+               out[i2] = 
math.Float32frombits(binary.LittleEndian.Uint32(v[8:]))
+               out[i3] = 
math.Float32frombits(binary.LittleEndian.Uint32(v[12:]))
+               positions, values = positions[8:], values[16:]
+       }
+       for len(positions) >= 2 && len(values) >= 4 {
+               idx := int(binary.LittleEndian.Uint16(positions))
+               if idx >= len(out) {
+                       return idx
+               }
+               out[idx] = 
math.Float32frombits(binary.LittleEndian.Uint32(values))
+               positions, values = positions[2:], values[4:]
+       }
+       return -1
+}
diff --git a/parquet/internal/encoding/alp_unpack_amd64.go 
b/parquet/internal/encoding/alp_unpack_amd64.go
new file mode 100644
index 00000000..893126af
--- /dev/null
+++ b/parquet/internal/encoding/alp_unpack_amd64.go
@@ -0,0 +1,116 @@
+// 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 !noasm
+
+package encoding
+
+import (
+       "unsafe"
+
+       "golang.org/x/sys/cpu"
+)
+
+func init() {
+       if cpu.X86.HasAVX2 {
+               alpDecodeGroups32 = alpDecodeGroups32AVX2
+               alpDecodeGroups64 = alpDecodeGroups64AVX2
+       }
+}
+
+// alpAVX2MaxBitWidth is the widest delta the AVX2 kernels decode. Wider, a
+// delta can span 5 bytes, more than its 32-bit lane holds.
+const alpAVX2MaxBitWidth = 25
+
+// alpAVX2Table is what the kernels need to unpack one width: the shuffle that
+// moves the 4 bytes holding each of a group's 8 deltas into its own 32-bit
+// lane, the shift that brings the delta down to bit 0, and its mask.
+type alpAVX2Table struct {
+       shuffle [32]byte
+       shifts  [8]uint32
+       masks   [8]uint32
+}
+
+var alpAVX2Tables = func() (tables [alpAVX2MaxBitWidth + 1]alpAVX2Table) {
+       for w := 1; w <= alpAVX2MaxBitWidth; w++ {
+               t := &tables[w]
+               for j := range 8 {
+                       // The upper 16 bytes of the register are loaded from 
w/2 bytes
+                       // into the group, and a shuffle cannot cross into the 
other half.
+                       bit := j * w
+                       if j >= 4 {
+                               bit -= 8 * (w / 2)
+                       }
+                       for b := range 4 {
+                               t.shuffle[4*j+b] = byte(bit/8 + b)
+                       }
+                       t.shifts[j] = uint32(bit % 8)
+                       t.masks[j] = 1<<w - 1
+               }
+       }
+       return
+}()
+
+// alpAVX2Groups returns how many whole groups of 8 deltas of bitWidth bits the
+// kernels can decode into count values from src without loading past its end.
+// A group's loads reach 16 bytes past w/2 bytes into it.
+func alpAVX2Groups(count, srcLen int, bitWidth uint) int {
+       w := int(bitWidth)
+       reach := w/2 + 16
+       if w > alpAVX2MaxBitWidth || srcLen < reach {
+               return 0
+       }
+       return min(count/8, (srcLen-reach)/w+1)
+}
+
+//go:noescape
+func _alpDecodeGroups32AVX2(src, out unsafe.Pointer, groups, bitWidth int, 
table *alpAVX2Table, ref uint32, fac, exp float32)
+
+//go:noescape
+func _alpDecodeGroups64AVX2(src, out unsafe.Pointer, groups, bitWidth int, 
table *alpAVX2Table, ref uint64, fac, exp float64)
+
+//go:noescape
+func _alpDecodeGroups64SmallAVX2(src, out unsafe.Pointer, groups, bitWidth 
int, table *alpAVX2Table, ref uint64, fac, exp float64)
+
+func alpDecodeGroups32AVX2(out []float32, src []byte, bitWidth uint, ref 
uint32, fac, exp float32) int {
+       groups := alpAVX2Groups(len(out), len(src), bitWidth)
+       if groups == 0 {
+               return 0
+       }
+       _alpDecodeGroups32AVX2(unsafe.Pointer(&src[0]), 
unsafe.Pointer(&out[0]), groups, int(bitWidth),
+               &alpAVX2Tables[bitWidth], ref, fac, exp)
+       return groups * 8
+}
+
+// alpSmallLimit bounds the integers that the short conversion handles: those
+// in [-2^51, 2^51).
+const alpSmallLimit = 1 << 51
+
+func alpDecodeGroups64AVX2(out []float64, src []byte, bitWidth uint, ref 
uint64, fac, exp float64) int {
+       groups := alpAVX2Groups(len(out), len(src), bitWidth)
+       if groups == 0 {
+               return 0
+       }
+       kernel := _alpDecodeGroups64AVX2
+       // The vector's integers run from ref to ref + 2^bitWidth - 1. When all 
of
+       // them are small enough, a shorter conversion is exact.
+       if r := int64(ref); r >= -alpSmallLimit && r <= 
alpSmallLimit-1<<bitWidth {
+               kernel = _alpDecodeGroups64SmallAVX2
+       }
+       kernel(unsafe.Pointer(&src[0]), unsafe.Pointer(&out[0]), groups, 
int(bitWidth),
+               &alpAVX2Tables[bitWidth], ref, fac, exp)
+       return groups * 8
+}
diff --git a/parquet/internal/encoding/alp_unpack_avx2_amd64.s 
b/parquet/internal/encoding/alp_unpack_avx2_amd64.s
new file mode 100644
index 00000000..e660db9b
--- /dev/null
+++ b/parquet/internal/encoding/alp_unpack_avx2_amd64.s
@@ -0,0 +1,195 @@
+// 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 !noasm
+
+#include "textflag.h"
+
+// The kernels decode groups of 8 deltas of w bits, 1 to 25. A group spans w
+// bytes, so each starts on a byte boundary. Its first 4 deltas lie in the 16
+// bytes from its start, and its last 4 in the 16 bytes from w/2 bytes in.
+// Both loads go in one register, a shuffle moves the 4 bytes holding each
+// delta into its own 32-bit lane, and a shift and a mask leave the delta.
+//
+// The table holds, in order, the shuffle, the shifts and the masks for w.
+//
+// The values are scaled with two separate multiplications, as Go does, so
+// they round the same.
+
+// 3*2^67 and 3*2^67 + 2^52: converting the upper 48 bits of an int64.
+DATA alpMagicHigh<>+0(SB)/8, $0x4438000000000000
+GLOBL alpMagicHigh<>(SB), RODATA|NOPTR, $8
+DATA alpMagicHighSub<>+0(SB)/8, $0x4438001000000000
+GLOBL alpMagicHighSub<>(SB), RODATA|NOPTR, $8
+// 2^52: converting the lower 16 bits.
+DATA alpMagicLow<>+0(SB)/8, $0x4330000000000000
+GLOBL alpMagicLow<>(SB), RODATA|NOPTR, $8
+// 2^52 + 2^51: converting an integer in [-2^51, 2^51).
+DATA alpMagicSmall<>+0(SB)/8, $0x4338000000000000
+GLOBL alpMagicSmall<>(SB), RODATA|NOPTR, $8
+
+// UNPACK_GROUP leaves the 8 deltas of the group at SI in Y0, as 32-bit lanes.
+#define UNPACK_GROUP \
+       VMOVDQU     (SI), X0;                \
+       VINSERTI128 $1, (SI)(R8*1), Y0, Y0;  \
+       VPSHUFB     Y8, Y0, Y0;              \
+       VPSRLVD     Y9, Y0, Y0;              \
+       VPAND       Y10, Y0, Y0
+
+// func _alpDecodeGroups32AVX2(src, out unsafe.Pointer, groups, bitWidth int, 
table *alpAVX2Table, ref uint32, fac, exp float32)
+TEXT ·_alpDecodeGroups32AVX2(SB), NOSPLIT, $0-52
+       MOVQ src+0(FP), SI
+       MOVQ out+8(FP), DI
+       MOVQ groups+16(FP), CX
+       MOVQ bitWidth+24(FP), DX
+       MOVQ table+32(FP), AX
+       MOVQ DX, R8
+       SHRQ $1, R8
+       VMOVDQU      0(AX), Y8
+       VMOVDQU      32(AX), Y9
+       VMOVDQU      64(AX), Y10
+       MOVL         ref+40(FP), BX
+       VMOVD        BX, X11
+       VPBROADCASTD X11, Y11
+       VBROADCASTSS fac+44(FP), Y12
+       VBROADCASTSS exp+48(FP), Y13
+       TESTQ CX, CX
+       JZ    done32
+
+loop32:
+       UNPACK_GROUP
+       // The frame of reference is added in 32 bits, wrapping as it was
+       // subtracted.
+       VPADDD    Y11, Y0, Y0
+       VCVTDQ2PS Y0, Y0
+       VMULPS    Y12, Y0, Y0
+       VMULPS    Y13, Y0, Y0
+       VMOVUPS   Y0, (DI)
+       ADDQ      DX, SI
+       ADDQ      $32, DI
+       DECQ      CX
+       JNZ       loop32
+
+done32:
+       VZEROUPPER
+       RET
+
+// WIDEN_GROUP widens the deltas in Y0 to 64 bits and adds the frame of
+// reference in Y11, wrapping: the first 4 in Y1, the last 4 in Y2.
+#define WIDEN_GROUP \
+       VPMOVZXDQ    X0, Y1;      \
+       VEXTRACTI128 $1, Y0, X2;  \
+       VPMOVZXDQ    X2, Y2;      \
+       VPADDQ       Y11, Y1, Y1; \
+       VPADDQ       Y11, Y2, Y2
+
+// INT64_TO_DOUBLE converts the int64s in src to the nearest doubles, as
+// CVTSI2SDQ does, using tmp. The upper 48 bits and the lower 16 each convert
+// exactly, so the one rounding is in the final addition.
+#define INT64_TO_DOUBLE(src, tmp) \
+       VPSRAD   $16, src, tmp;        \
+       VPBLENDW $0x33, Y14, tmp, tmp; \
+       VPADDQ   Y15, tmp, tmp;        \
+       VPBLENDW $0x88, Y4, src, src;  \
+       VSUBPD   Y5, tmp, tmp;         \
+       VADDPD   tmp, src, src
+
+// func _alpDecodeGroups64AVX2(src, out unsafe.Pointer, groups, bitWidth int, 
table *alpAVX2Table, ref uint64, fac, exp float64)
+TEXT ·_alpDecodeGroups64AVX2(SB), NOSPLIT, $0-64
+       MOVQ src+0(FP), SI
+       MOVQ out+8(FP), DI
+       MOVQ groups+16(FP), CX
+       MOVQ bitWidth+24(FP), DX
+       MOVQ table+32(FP), AX
+       MOVQ DX, R8
+       SHRQ $1, R8
+       VMOVDQU      0(AX), Y8
+       VMOVDQU      32(AX), Y9
+       VMOVDQU      64(AX), Y10
+       VPBROADCASTQ ref+40(FP), Y11
+       VBROADCASTSD fac+48(FP), Y12
+       VBROADCASTSD exp+56(FP), Y13
+       VPXOR        Y14, Y14, Y14
+       VPBROADCASTQ alpMagicHigh<>(SB), Y15
+       VPBROADCASTQ alpMagicLow<>(SB), Y4
+       VBROADCASTSD alpMagicHighSub<>(SB), Y5
+       TESTQ CX, CX
+       JZ    done64
+
+loop64:
+       UNPACK_GROUP
+       WIDEN_GROUP
+       INT64_TO_DOUBLE(Y1, Y3)
+       INT64_TO_DOUBLE(Y2, Y6)
+       VMULPD  Y12, Y1, Y1
+       VMULPD  Y12, Y2, Y2
+       VMULPD  Y13, Y1, Y1
+       VMULPD  Y13, Y2, Y2
+       VMOVUPD Y1, (DI)
+       VMOVUPD Y2, 32(DI)
+       ADDQ    DX, SI
+       ADDQ    $64, DI
+       DECQ    CX
+       JNZ     loop64
+
+done64:
+       VZEROUPPER
+       RET
+
+// func _alpDecodeGroups64SmallAVX2(src, out unsafe.Pointer, groups, bitWidth 
int, table *alpAVX2Table, ref uint64, fac, exp float64)
+//
+// For a vector whose integers all lie in [-2^51, 2^51): adding 2^52 + 2^51
+// puts each in the mantissa of a double, and subtracting it as a double
+// leaves the integer's value.
+TEXT ·_alpDecodeGroups64SmallAVX2(SB), NOSPLIT, $0-64
+       MOVQ src+0(FP), SI
+       MOVQ out+8(FP), DI
+       MOVQ groups+16(FP), CX
+       MOVQ bitWidth+24(FP), DX
+       MOVQ table+32(FP), AX
+       MOVQ DX, R8
+       SHRQ $1, R8
+       VMOVDQU      0(AX), Y8
+       VMOVDQU      32(AX), Y9
+       VMOVDQU      64(AX), Y10
+       VPBROADCASTQ ref+40(FP), Y11
+       VBROADCASTSD fac+48(FP), Y12
+       VBROADCASTSD exp+56(FP), Y13
+       VPBROADCASTQ alpMagicSmall<>(SB), Y14
+       TESTQ CX, CX
+       JZ    doneSmall
+
+loopSmall:
+       UNPACK_GROUP
+       WIDEN_GROUP
+       VPADDQ  Y14, Y1, Y1
+       VPADDQ  Y14, Y2, Y2
+       VSUBPD  Y14, Y1, Y1
+       VSUBPD  Y14, Y2, Y2
+       VMULPD  Y12, Y1, Y1
+       VMULPD  Y12, Y2, Y2
+       VMULPD  Y13, Y1, Y1
+       VMULPD  Y13, Y2, Y2
+       VMOVUPD Y1, (DI)
+       VMOVUPD Y2, 32(DI)
+       ADDQ    DX, SI
+       ADDQ    $64, DI
+       DECQ    CX
+       JNZ     loopSmall
+
+doneSmall:
+       VZEROUPPER
+       RET
diff --git a/parquet/internal/encoding/alp_unpack_guard_test.go 
b/parquet/internal/encoding/alp_unpack_guard_test.go
new file mode 100644
index 00000000..4f13872f
--- /dev/null
+++ b/parquet/internal/encoding/alp_unpack_guard_test.go
@@ -0,0 +1,73 @@
+// 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 linux || darwin
+
+package encoding
+
+import (
+       "math"
+       "math/rand/v2"
+       "syscall"
+       "testing"
+
+       "github.com/stretchr/testify/require"
+)
+
+// The unpacking loops load no further than alpUnpackSize bytes: placed right
+// before a page that cannot be read, the packed deltas decode without a fault.
+func TestALPDecodePackedGuardPage(t *testing.T) {
+       pageSize := syscall.Getpagesize()
+       mapped, err := syscall.Mmap(-1, 0, 2*pageSize, 
syscall.PROT_READ|syscall.PROT_WRITE, syscall.MAP_PRIVATE|syscall.MAP_ANON)
+       require.NoError(t, err)
+       t.Cleanup(func() { require.NoError(t, syscall.Munmap(mapped)) })
+       require.NoError(t, syscall.Mprotect(mapped[pageSize:], 
syscall.PROT_NONE))
+
+       rng := rand.New(rand.NewPCG(5, 6))
+       scratch := make([]uint32, 1024)
+       for bitWidth := 1; bitWidth <= 64; bitWidth++ {
+               for _, count := range []int{8, 9, 64, 65, 1024} {
+                       size := alpUnpackSize(count, bitWidth)
+                       if size > pageSize {
+                               continue
+                       }
+                       deltas := alpTestDeltas(rng, count, bitWidth)
+                       src := mapped[pageSize-size : pageSize]
+                       clear(src)
+                       copy(src, alpTestPack(deltas, bitWidth))
+                       ref := rng.Uint64() >> 20
+
+                       got := make([]float64, count)
+                       alpDecodePacked64(got, src, uint(bitWidth), ref, 1e3, 
1e-7, scratch)
+                       for i, d := range deltas {
+                               want := float64(int64(d+ref)) * 1e3 * 1e-7
+                               require.Equal(t, math.Float64bits(want), 
math.Float64bits(got[i]),
+                                       "double bitWidth=%d count=%d i=%d", 
bitWidth, count, i)
+                       }
+
+                       if bitWidth > 32 {
+                               continue
+                       }
+                       got32 := make([]float32, count)
+                       alpDecodePacked32(got32, src, uint(bitWidth), 
uint32(ref), 1e3, 1e-7, scratch)
+                       for i, d := range deltas {
+                               want := float32(int32(uint32(d)+uint32(ref))) * 
float32(1e3) * float32(1e-7)
+                               require.Equal(t, math.Float32bits(want), 
math.Float32bits(got32[i]),
+                                       "float bitWidth=%d count=%d i=%d", 
bitWidth, count, i)
+                       }
+               }
+       }
+}
diff --git a/parquet/internal/encoding/alp_unpack_test.go 
b/parquet/internal/encoding/alp_unpack_test.go
new file mode 100644
index 00000000..27206811
--- /dev/null
+++ b/parquet/internal/encoding/alp_unpack_test.go
@@ -0,0 +1,250 @@
+// 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.
+
+package encoding
+
+import (
+       "encoding/binary"
+       "math"
+       "math/rand/v2"
+       "testing"
+
+       "github.com/apache/arrow-go/v18/arrow/memory"
+       format "github.com/apache/arrow-go/v18/parquet/internal/gen-go/parquet"
+       "github.com/stretchr/testify/assert"
+       "github.com/stretchr/testify/require"
+)
+
+// alpTestPack packs deltas at bitWidth bits each, least significant bit first,
+// one bit at a time.
+func alpTestPack(deltas []uint64, bitWidth int) []byte {
+       packed := make([]byte, alpPackedSize(len(deltas), bitWidth))
+       bit := 0
+       for _, d := range deltas {
+               for b := range bitWidth {
+                       packed[bit/8] |= byte(d>>b&1) << (bit % 8)
+                       bit++
+               }
+       }
+       return packed
+}
+
+func alpTestDeltas(rng *rand.Rand, count, bitWidth int) []uint64 {
+       deltas := make([]uint64, count)
+       for i := range deltas {
+               deltas[i] = rng.Uint64() >> (64 - bitWidth)
+       }
+       return deltas
+}
+
+// The lengths sit either side of the groups of 4, 8 and 32 that the loops work
+// in, and include a vector the default size and one past it.
+var alpTestVectorLengths = []int{1, 2, 3, 4, 5, 7, 8, 9, 31, 32, 33, 63, 64, 
65, 1000, 1024, 1027}
+
+// alpTestRefs returns frames of reference for deltas of bitWidth bits: one at
+// random, and DOUBLE ones either side of each end of the range in which every
+// integer of the vector lies in [-2^51, 2^51), which converts differently.
+func alpTestRefs(rng *rand.Rand, bitWidth int) []uint64 {
+       const limit = 1 << 51
+       refs := []uint64{rng.Uint64()}
+       if bitWidth < 51 {
+               lo, hi := int64(-limit), int64(limit-1<<bitWidth)
+               refs = append(refs, uint64(lo-1), uint64(lo), uint64(hi), 
uint64(hi+1))
+       }
+       return refs
+}
+
+func TestALPDecodePacked(t *testing.T) {
+       rng := rand.New(rand.NewPCG(3, 4))
+       scratch := make([]uint32, 1027)
+       for bitWidth := 1; bitWidth <= 64; bitWidth++ {
+               for _, count := range alpTestVectorLengths {
+                       for _, ref := range alpTestRefs(rng, bitWidth) {
+                               alpTestDecodePacked(t, rng, scratch, bitWidth, 
count, ref)
+                       }
+               }
+       }
+}
+
+func alpTestDecodePacked(t *testing.T, rng *rand.Rand, scratch []uint32, 
bitWidth, count int, ref uint64) {
+       deltas := alpTestDeltas(rng, count, bitWidth)
+       // Some vectors have their deltas at both extremes.
+       if count > 2 {
+               deltas[0], deltas[count-1] = 0, ^uint64(0)>>(64-bitWidth)
+       }
+       // What follows the deltas must not reach the values: the loops load it,
+       // and discard it.
+       src := make([]byte, alpUnpackSize(count, bitWidth))
+       for i := copy(src, alpTestPack(deltas, bitWidth)); i < len(src); i++ {
+               src[i] = 0xFF
+       }
+
+       got := make([]float64, count)
+       alpDecodePacked64(got, src, uint(bitWidth), ref, 1e3, 1e-7, scratch)
+       for i, d := range deltas {
+               want := float64(int64(d+ref)) * 1e3 * 1e-7
+               require.Equal(t, math.Float64bits(want), 
math.Float64bits(got[i]),
+                       "double bitWidth=%d count=%d ref=%d i=%d", bitWidth, 
count, int64(ref), i)
+       }
+
+       if bitWidth > 32 {
+               return
+       }
+       got32 := make([]float32, count)
+       alpDecodePacked32(got32, src, uint(bitWidth), uint32(ref), 1e3, 1e-7, 
scratch)
+       for i, d := range deltas {
+               want := float32(int32(uint32(d)+uint32(ref))) * float32(1e3) * 
float32(1e-7)
+               require.Equal(t, math.Float32bits(want), 
math.Float32bits(got32[i]),
+                       "float bitWidth=%d count=%d ref=%d i=%d", bitWidth, 
count, int32(ref), i)
+       }
+}
+
+func TestALPPatch(t *testing.T) {
+       const vectorLen = 100
+       for _, numExceptions := range []int{0, 1, 3, 4, 5, 8, 11, vectorLen} {
+               positions := make([]byte, 2*numExceptions)
+               values64 := make([]byte, 8*numExceptions)
+               values32 := make([]byte, 4*numExceptions)
+               want64, want32 := make([]float64, vectorLen), make([]float32, 
vectorLen)
+               for e := range numExceptions {
+                       // Spread out and out of order, with NaN payloads that 
must
+                       // survive.
+                       pos := (e*37 + 5) % vectorLen
+                       bits := 0x7FF8_0000_0000_0000 | uint64(e+1)
+                       binary.LittleEndian.PutUint16(positions[2*e:], 
uint16(pos))
+                       binary.LittleEndian.PutUint64(values64[8*e:], bits)
+                       binary.LittleEndian.PutUint32(values32[4*e:], 
0x7FC0_0000|uint32(e+1))
+                       want64[pos] = math.Float64frombits(bits)
+                       want32[pos] = math.Float32frombits(0x7FC0_0000 | 
uint32(e+1))
+               }
+
+               got64, got32 := make([]float64, vectorLen), make([]float32, 
vectorLen)
+               require.Equal(t, -1, alpPatch64(got64, positions, values64))
+               require.Equal(t, -1, alpPatch32(got32, positions, values32))
+               for i := range vectorLen {
+                       require.Equal(t, math.Float64bits(want64[i]), 
math.Float64bits(got64[i]), "exceptions=%d i=%d", numExceptions, i)
+                       require.Equal(t, math.Float32bits(want32[i]), 
math.Float32bits(got32[i]), "exceptions=%d i=%d", numExceptions, i)
+               }
+
+               // A position outside the vector is reported wherever it falls 
among
+               // the exceptions.
+               for bad := range numExceptions {
+                       corrupt := append([]byte(nil), positions...)
+                       binary.LittleEndian.PutUint16(corrupt[2*bad:], 
vectorLen+7)
+                       assert.Equal(t, vectorLen+7, alpPatch64(make([]float64, 
vectorLen), corrupt, values64), "exceptions=%d bad=%d", numExceptions, bad)
+                       assert.Equal(t, vectorLen+7, alpPatch32(make([]float32, 
vectorLen), corrupt, values32), "exceptions=%d bad=%d", numExceptions, bad)
+               }
+       }
+}
+
+// alpTestPackedPage builds a page of one vector with no exceptions, whose 
packed
+// deltas are the page's last bytes.
+func alpTestPackedPage[T alpFloat](deltas []uint64, ref uint64, bitWidth int) 
[]byte {
+       page := []byte{alpCompressionMode, alpIntegerEncodingFOR, 
alpDefaultLogVectorSize}
+       page = binary.LittleEndian.AppendUint32(page, uint32(len(deltas)))
+       page = binary.LittleEndian.AppendUint32(page, 4) // the vector follows 
its own offset
+       page = append(page, 0, 0)                        // exponent and 
factor: the integers are the values
+       page = binary.LittleEndian.AppendUint16(page, 0)
+       if alpEncodedBytes[T]() == 4 {
+               page = binary.LittleEndian.AppendUint32(page, uint32(ref))
+       } else {
+               page = binary.LittleEndian.AppendUint64(page, ref)
+       }
+       page = append(page, byte(bitWidth))
+       return append(page, alpTestPack(deltas, bitWidth)...)
+}
+
+// The last vector of a page has nothing after its packed deltas for the
+// unpacking loops to load, at any width and any length.
+func TestALPDecodeVectorEndingPage(t *testing.T) {
+       rng := rand.New(rand.NewPCG(5, 6))
+       for bitWidth := 0; bitWidth <= 64; bitWidth++ {
+               for _, count := range []int{1, 2, 5, 31, 32, 33, 100, 1024} {
+                       deltas := make([]uint64, count)
+                       if bitWidth > 0 {
+                               deltas = alpTestDeltas(rng, count, bitWidth)
+                       }
+                       ref := rng.Uint64()
+
+                       dec64 := newALPDecoder[float64](format.Encoding_ALP, 
newFloat64Column())
+                       require.NoError(t, dec64.SetData(count, 
alpTestPackedPage[float64](deltas, ref, bitWidth)))
+                       got64 := make([]float64, count)
+                       n, err := dec64.Decode(got64)
+                       require.NoError(t, err, "double bitWidth=%d count=%d", 
bitWidth, count)
+                       require.Equal(t, count, n)
+                       for i, d := range deltas {
+                               require.Equal(t, float64(int64(d+ref)), 
got64[i], "double bitWidth=%d count=%d i=%d", bitWidth, count, i)
+                       }
+
+                       if bitWidth > 32 {
+                               continue
+                       }
+                       dec32 := newALPDecoder[float32](format.Encoding_ALP, 
newFloat32Column())
+                       require.NoError(t, dec32.SetData(count, 
alpTestPackedPage[float32](deltas, ref, bitWidth)))
+                       got32 := make([]float32, count)
+                       n, err = dec32.Decode(got32)
+                       require.NoError(t, err, "float bitWidth=%d count=%d", 
bitWidth, count)
+                       require.Equal(t, count, n)
+                       for i, d := range deltas {
+                               require.Equal(t, 
float32(int32(uint32(d)+uint32(ref))), got32[i], "float bitWidth=%d count=%d 
i=%d", bitWidth, count, i)
+                       }
+               }
+       }
+}
+
+// A read that starts on a vector and takes all of it is decoded straight into
+// the caller's slice; any other goes through the decoder's buffer. Whatever 
the
+// reads, the values are the same.
+func TestALPDecodeReadSizes(t *testing.T) {
+       const count = 5*alpDefaultVectorSize + 300
+       values := make([]float64, count)
+       for i := range values {
+               values[i] = float64(i%10007) / 100
+               if i%97 == 0 {
+                       values[i] = math.NaN()
+               }
+       }
+       enc := newALPEncoder[float64](format.Encoding_ALP, newFloat64Column(), 
memory.DefaultAllocator)
+       enc.Put(values)
+       buf, err := enc.FlushValues()
+       require.NoError(t, err)
+       defer buf.Release()
+
+       for _, sizes := range [][]int{
+               {count},
+               {alpDefaultVectorSize},
+               {2 * alpDefaultVectorSize},
+               {1000},
+               {1},
+               // Whole vectors, then part of one, then the rest of it and 
more.
+               {alpDefaultVectorSize, 10, 2*alpDefaultVectorSize + 500, 
alpDefaultVectorSize, 3},
+               {alpDefaultVectorSize + 1, alpDefaultVectorSize - 1, 
alpDefaultVectorSize},
+       } {
+               dec := newALPDecoder[float64](format.Encoding_ALP, 
newFloat64Column())
+               require.NoError(t, dec.SetData(count, buf.Bytes()))
+               got := make([]float64, 0, count)
+               for i := 0; len(got) < count; i++ {
+                       size := min(sizes[i%len(sizes)], count-len(got))
+                       n, err := dec.Decode(got[len(got) : len(got)+size])
+                       require.NoError(t, err, "sizes=%v", sizes)
+                       require.Equal(t, size, n, "sizes=%v", sizes)
+                       got = got[:len(got)+n]
+               }
+               for i := range values {
+                       require.Equal(t, math.Float64bits(values[i]), 
math.Float64bits(got[i]), "sizes=%v i=%d", sizes, i)
+               }
+       }
+}
diff --git a/parquet/internal/utils/bit_packing_amd64.go 
b/parquet/internal/utils/bit_packing_amd64.go
index 72702578..02774ace 100644
--- a/parquet/internal/utils/bit_packing_amd64.go
+++ b/parquet/internal/utils/bit_packing_amd64.go
@@ -26,6 +26,7 @@ import (
 func init() {
        if cpu.X86.HasAVX2 {
                unpack32 = unpack32Avx2
+               unpack32Bytes = unpack32BytesAvx2
        } else { // default to the pure go implementation if no avx2 available
                unpack32 = unpack32Default
        }
diff --git a/parquet/internal/utils/bit_packing_arm64.go 
b/parquet/internal/utils/bit_packing_arm64.go
index 082ac444..2104ec96 100644
--- a/parquet/internal/utils/bit_packing_arm64.go
+++ b/parquet/internal/utils/bit_packing_arm64.go
@@ -29,6 +29,7 @@ import (
 func init() {
        if cpuid.CPU.Has(cpuid.ASIMD) {
                unpack32 = unpack32NEON
+               unpack32Bytes = unpack32BytesNEON
        } else { // default to the pure go implementation if no avx2 available
                unpack32 = unpack32Default
        }
diff --git a/parquet/internal/utils/bit_packing_avx2_amd64.go 
b/parquet/internal/utils/bit_packing_avx2_amd64.go
index 74eb936b..6c5ebc6f 100644
--- a/parquet/internal/utils/bit_packing_avx2_amd64.go
+++ b/parquet/internal/utils/bit_packing_avx2_amd64.go
@@ -59,3 +59,7 @@ func unpack32Avx2(in io.Reader, out []uint32, nbits int) 
(int, error) {
 
        return _unpack32_avx2(input, output, completeBatch, nbits), err
 }
+
+func unpack32BytesAvx2(in []byte, out []uint32, nbits int) int {
+       return _unpack32_avx2(unsafe.Pointer(&in[0]), unsafe.Pointer(&out[0]), 
len(out), nbits)
+}
diff --git a/parquet/internal/utils/bit_packing_default.go 
b/parquet/internal/utils/bit_packing_default.go
index 27f4b275..dc076850 100644
--- a/parquet/internal/utils/bit_packing_default.go
+++ b/parquet/internal/utils/bit_packing_default.go
@@ -24,6 +24,28 @@ import (
 
 var unpack32 func(io.Reader, []uint32, int) (int, error) = unpack32Default
 
+// unpack32Bytes is the platform's vectorized unpacker, reading straight from a
+// byte slice. It is nil where there is none.
+var unpack32Bytes func(in []byte, out []uint32, nbits int) int
+
+// Unpack32Vectorized unpacks values of nbits bits, 1 to 32, from the front of
+// in, least significant bit first. It unpacks whole groups of 32, as many as 
in
+// and out both hold, and returns how many values that was.
+//
+// It unpacks nothing on a platform without a vectorized unpacker. A caller's
+// own loop over the bytes is faster there than the scalar unpackers, which
+// read through an io.Reader.
+func Unpack32Vectorized(in []byte, out []uint32, nbits int) int {
+       if unpack32Bytes == nil || nbits < 1 || nbits > 32 {
+               return 0
+       }
+       out = out[:min(len(out), len(in)*8/nbits)/32*32]
+       if len(out) == 0 {
+               return 0
+       }
+       return unpack32Bytes(in, out, nbits)
+}
+
 type unpackFunc func(in io.Reader, out []uint32)
 
 func unpack1_32(in io.Reader, out []uint32) {
diff --git a/parquet/internal/utils/bit_packing_neon_arm64.go 
b/parquet/internal/utils/bit_packing_neon_arm64.go
index fa204657..145e2f25 100644
--- a/parquet/internal/utils/bit_packing_neon_arm64.go
+++ b/parquet/internal/utils/bit_packing_neon_arm64.go
@@ -59,3 +59,7 @@ func unpack32NEON(in io.Reader, out []uint32, nbits int) 
(int, error) {
 
        return _unpack32_neon(input, output, completeBatch, nbits), err
 }
+
+func unpack32BytesNEON(in []byte, out []uint32, nbits int) int {
+       return _unpack32_neon(unsafe.Pointer(&in[0]), unsafe.Pointer(&out[0]), 
len(out), nbits)
+}
diff --git a/parquet/internal/utils/unpack32_vectorized_test.go 
b/parquet/internal/utils/unpack32_vectorized_test.go
new file mode 100644
index 00000000..72f7fd9b
--- /dev/null
+++ b/parquet/internal/utils/unpack32_vectorized_test.go
@@ -0,0 +1,75 @@
+// 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.
+
+package utils_test
+
+import (
+       "math/rand/v2"
+       "testing"
+
+       "github.com/apache/arrow-go/v18/parquet/internal/utils"
+       "github.com/stretchr/testify/require"
+)
+
+// packLSB packs values at width bits each, least significant bit first, one
+// bit at a time.
+func packLSB(values []uint32, width int) []byte {
+       packed := make([]byte, (len(values)*width+7)/8)
+       bit := 0
+       for _, v := range values {
+               for b := range width {
+                       packed[bit/8] |= byte(v>>b&1) << (bit % 8)
+                       bit++
+               }
+       }
+       return packed
+}
+
+func TestUnpack32Vectorized(t *testing.T) {
+       rng := rand.New(rand.NewPCG(1, 2))
+       for width := 1; width <= 32; width++ {
+               values := make([]uint32, 1024)
+               for i := range values {
+                       values[i] = rng.Uint32() >> (32 - width)
+               }
+               packed := packLSB(values, width)
+
+               for _, count := range []int{0, 1, 31, 32, 33, 64, 1000, 1024} {
+                       out := make([]uint32, count)
+                       n := utils.Unpack32Vectorized(packed, out, width)
+                       // A platform without a vectorized unpacker unpacks 
nothing.
+                       // One with it takes every whole group of 32.
+                       if n != 0 {
+                               require.Equal(t, count/32*32, n, "width=%d 
count=%d", width, count)
+                       }
+                       require.Equal(t, values[:n], out[:n], "width=%d 
count=%d", width, count)
+               }
+
+               // The input holds fewer whole groups than the output has room 
for.
+               out := make([]uint32, 1024)
+               short := packed[:3*32*width/8+1]
+               if n := utils.Unpack32Vectorized(short, out, width); n != 0 {
+                       require.Equal(t, 3*32, n, "width=%d", width)
+                       require.Equal(t, values[:n], out[:n], "width=%d", width)
+               }
+       }
+
+       // Widths the 32-bit unpacker cannot serve.
+       out := make([]uint32, 64)
+       for _, width := range []int{-1, 0, 33, 64} {
+               require.Zero(t, utils.Unpack32Vectorized(make([]byte, 1024), 
out, width), "width=%d", width)
+       }
+}

Reply via email to