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 8f5cdfa7 perf(parquet/internal/encoding): speed up ALP encoding (#1553)
8f5cdfa7 is described below

commit 8f5cdfa7d0cb0e402d41cf7d0d488afe89ffbda8
Author: Matt Topol <[email protected]>
AuthorDate: Wed Nov 18 12:38:48 2026 -0500

    perf(parquet/internal/encoding): speed up ALP encoding (#1553)
    
    ### Rationale for this change
    
    Most of the time ALP encoding takes goes to four things:
    
    - Every value is scaled by `alpScaling.tryEncode`, a method generic over 
the float type that is not inlined into the loop and that branches on whether 
the value is an exception. Where exceptions and encodable values mix, that 
branch is mispredicted.
    - The integers are packed through `BitWriter.WriteValue`, one call per 
value, with a `BitWriter` and its buffer wrapper allocated for every vector.
    - The search over every exponent and factor scales the whole sample for 
each of the 190 pairs (66 for `FLOAT`), although nearly all of them are out of 
the running after a few values. A column chunk pays for that search on its 
first eight vectors, and again whenever the data changes scale.
    - Once the shortlist is built, each vector's sample is scaled to choose 
among the shortlisted scalings, even when there is only one to choose from.
    
    ### What changes are included in this PR?
    
    - `alpScale64` and `alpScale32` scale a vector in a loop written for one 
type that does not branch on the data. They give the integers and exceptions 
`tryEncode` gives. The range of the integers is found in a separate integer 
pass.
    - `alpPack` packs the integers' distances from the frame of reference a 
word at a time, in four runs side by side, with no allocation.
    - A size estimate stops as soon as its scaling can no longer beat the best 
one. Neither the exceptions nor the packing width can shrink as more values are 
scaled, so the size so far is a lower bound.
    - With one scaling on the shortlist, the vector is scaled straight away, 
and what the sample would have estimated is read off the result.
    - `Put` encodes a whole vector from the caller's slice instead of copying 
it into the encoder's buffer first.
    
    The pages are byte for byte what `main` writes. I compared the two encoders 
on decimals, whole numbers, incompressible values, data that changes scale 
partway, and values at the edges of the integer range, mixed with NaN, 
infinities and -0.0, for both types, at vector sizes from 8 to 32768.
    
    Timings on an Apple M4 (darwin/arm64). 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                │
    ALPEncodingFloat32/no_exceptions/len_1024-10      7.084µ ± 19%   2.964µ ± 
20%  -58.16% (n=50)
    ALPEncodingFloat32/no_exceptions/len_65536-10     471.0µ ± 11%   200.5µ ± 
13%  -57.43% (p=0.000 n=50)
    ALPEncodingFloat32/10%_exceptions/len_1024-10     8.116µ ± 13%   3.720µ ± 
13%  -54.17% (p=0.000 n=50)
    ALPEncodingFloat32/10%_exceptions/len_65536-10    525.7µ ± 22%   240.9µ ± 
15%  -54.19% (p=0.000 n=50)
    ALPEncodingFloat32/all_exceptions/len_1024-10    13.150µ ±  4%   4.557µ ± 
27%  -65.34% (p=0.000 n=50)
    ALPEncodingFloat32/all_exceptions/len_65536-10    863.4µ ±  4%   324.4µ ± 
21%  -62.42% (p=0.000 n=50)
    ALPEncodingFloat64/no_exceptions/len_1024-10      6.906µ ± 23%   2.765µ ± 
15%  -59.96% (n=50)
    ALPEncodingFloat64/no_exceptions/len_65536-10     515.9µ ± 17%   206.9µ ± 
13%  -59.90% (p=0.000 n=50)
    ALPEncodingFloat64/10%_exceptions/len_1024-10     7.670µ ± 18%   2.993µ ±  
9%  -60.98% (n=50)
    ALPEncodingFloat64/10%_exceptions/len_65536-10    562.4µ ±  9%   252.2µ ± 
17%  -55.16% (p=0.000 n=50)
    ALPEncodingFloat64/all_exceptions/len_1024-10    13.631µ ±  9%   4.467µ ± 
18%  -67.23% (n=50)
    ALPEncodingFloat64/all_exceptions/len_65536-10    921.9µ ± 10%   328.1µ ± 
18%  -64.41% (p=0.000 n=50)
    geomean                                           74.91µ         29.84µ     
   -60.17%
    
                                                   │     main     │             
      PR                    │
                                                   │  allocs/op   │ allocs/op   
vs base                     │
    ALPEncodingFloat32/no_exceptions/len_1024-10     2.000 ± 0%     0.000 ± 0%  
-100.00% (n=50)
    ALPEncodingFloat32/no_exceptions/len_65536-10    128.0 ± 0%       0.0 ± 0%  
-100.00% (n=50)
    ALPEncodingFloat32/10%_exceptions/len_1024-10    2.000 ± 0%     0.000 ± 0%  
-100.00% (n=50)
    ALPEncodingFloat32/10%_exceptions/len_65536-10   128.0 ± 0%       0.0 ± 0%  
-100.00% (n=50)
    ALPEncodingFloat32/all_exceptions/len_1024-10    0.000 ± 0%     0.000 ± 0%  
       ~ (p=1.000 n=50) ¹
    ALPEncodingFloat32/all_exceptions/len_65536-10   0.000 ± 0%     0.000 ± 0%  
   0.00% (p=0.000 n=50)
    ALPEncodingFloat64/no_exceptions/len_1024-10     2.000 ± 0%     0.000 ± 0%  
-100.00% (n=50)
    ALPEncodingFloat64/no_exceptions/len_65536-10    128.0 ± 0%       0.0 ± 0%  
-100.00% (n=50)
    ALPEncodingFloat64/10%_exceptions/len_1024-10    2.000 ± 0%     0.000 ± 0%  
-100.00% (n=50)
    ALPEncodingFloat64/10%_exceptions/len_65536-10   128.0 ± 0%       0.0 ± 0%  
-100.00% (n=50)
    ALPEncodingFloat64/all_exceptions/len_1024-10    0.000 ± 0%     0.000 ± 0%  
       ~ (p=1.000 n=50) ¹
    ALPEncodingFloat64/all_exceptions/len_65536-10   1.000 ± 0%     0.000 ± 0%  
-100.00% (p=0.000 n=50)
    geomean                                                     ²               
?                       ² ³
    ² summaries must be >0 to compute geomean
    ³ ratios must be >0 to compute geomean
    ```
    
    I have no amd64 timings.
    
    ### Are these changes tested?
    
    Yes, by new tests that hold the new loops to `alpScaling.tryEncode` and to 
a bit-at-a-time packer, and by the existing ALP tests.
    
    ### Are there any user-facing changes?
    
    No.
---
 parquet/internal/encoding/alp_encoding.go      | 244 +++++++++++++++++--------
 parquet/internal/encoding/alp_encoding_test.go |  76 +++++++-
 parquet/internal/encoding/alp_params.go        | 128 ++++++++++---
 parquet/internal/encoding/alp_params_test.go   |  52 ++++++
 parquet/internal/encoding/alp_scaling.go       | 127 ++++++++++++-
 parquet/internal/encoding/alp_scaling_test.go  | 120 ++++++++++++
 6 files changed, 627 insertions(+), 120 deletions(-)

diff --git a/parquet/internal/encoding/alp_encoding.go 
b/parquet/internal/encoding/alp_encoding.go
index fd518b3f..31bcab7d 100644
--- a/parquet/internal/encoding/alp_encoding.go
+++ b/parquet/internal/encoding/alp_encoding.go
@@ -47,7 +47,6 @@ import (
        "github.com/apache/arrow-go/v18/arrow/memory"
        "github.com/apache/arrow-go/v18/parquet"
        format "github.com/apache/arrow-go/v18/parquet/internal/gen-go/parquet"
-       "github.com/apache/arrow-go/v18/parquet/internal/utils"
        "github.com/apache/arrow-go/v18/parquet/schema"
 )
 
@@ -76,32 +75,81 @@ func alpPackedSize(count, bitWidth int) int {
        return (count*bitWidth + 7) / 8
 }
 
-// alpAppendPackedBits appends values to dst, packed at bitWidth bits each,
-// least significant bit first.
-func alpAppendPackedBits(dst []byte, values []uint64, bitWidth int) []byte {
-       if bitWidth == 0 || len(values) == 0 {
-               return dst
+// alpPack packs each integer's distance above minValue into dst at bitWidth
+// bits, least significant bit first. The distances collect in words that are
+// stored whole, so dst needs room for 8 bytes past the alpPackedSize ones.
+//
+// A group of 8 values ends on a byte boundary at any width. The integers are
+// therefore cut into four runs of whole groups, which are packed side by side:
+// no run's word waits for another's. What is left after the four runs is
+// packed on its own.
+func alpPack(dst []byte, encoded []int64, minValue int64, bitWidth uint) {
+       if bitWidth == 0 {
+               return
+       }
+       run := len(encoded) / 4 &^ 7
+       if run == 0 {
+               alpPackRun(dst, encoded, minValue, bitWidth)
+               return
+       }
+       size := run * int(bitWidth) / 8
+       e0, e1, e2, e3 := encoded[:run], encoded[run:2*run], 
encoded[2*run:3*run], encoded[3*run:4*run]
+       d0, d1, d2, d3 := dst[:size], dst[size:2*size], dst[2*size:3*size], 
dst[3*size:4*size]
+
+       var w0, w1, w2, w3 uint64
+       var used uint
+       base, pos := uint64(minValue), 0
+       for i := range e0 {
+               // The distance between two int64 values can exceed int64. 
Unsigned
+               // arithmetic wraps, and the decoder adds the distance back the 
same way.
+               v0, v1, v2, v3 := uint64(e0[i])-base, uint64(e1[i])-base, 
uint64(e2[i])-base, uint64(e3[i])-base
+               w0 |= v0 << used
+               w1 |= v1 << used
+               w2 |= v2 << used
+               w3 |= v3 << used
+               used += bitWidth
+               if used >= 64 {
+                       binary.LittleEndian.PutUint64(d0[pos:], w0)
+                       binary.LittleEndian.PutUint64(d1[pos:], w1)
+                       binary.LittleEndian.PutUint64(d2[pos:], w2)
+                       binary.LittleEndian.PutUint64(d3[pos:], w3)
+                       pos += 8
+                       used -= 64
+                       // The bits the full words had no room for.
+                       rest := bitWidth - used
+                       w0, w1, w2, w3 = v0>>rest, v1>>rest, v2>>rest, v3>>rest
+               }
        }
-
-       // BitWriter flushes eight bytes at a time, so it needs room past the 
last
-       // packed byte. The return drops those bytes again.
-       start, size := len(dst), alpPackedSize(len(values), bitWidth)
-       dst = slices.Grow(dst, size+8)[:start+size+8]
-       clear(dst[start:])
-
-       bw := utils.NewBitWriter(utils.NewWriterAtBuffer(dst[start:]))
-       for _, v := range values {
-               bw.WriteValue(v, uint(bitWidth))
+       // A whole word here would run into the next run, which is already
+       // written, so the last bytes of each run go out one at a time.
+       for ; pos < size; pos++ {
+               d0[pos], d1[pos], d2[pos], d3[pos] = byte(w0), byte(w1), 
byte(w2), byte(w3)
+               w0, w1, w2, w3 = w0>>8, w1>>8, w2>>8, w3>>8
        }
-       bw.Flush(true)
-       return dst[:start+size]
+       alpPackRun(dst[4*size:], encoded[4*run:], minValue, bitWidth)
 }
 
-func alpAppendInt[T alpFloat](dst []byte, v uint64) []byte {
-       if alpEncodedBytes[T]() == 4 {
-               return binary.LittleEndian.AppendUint32(dst, uint32(v))
+// alpPackRun packs one run of integers. The distances collect in a word that
+// is stored whole each time it fills, and once more at the end.
+func alpPackRun(dst []byte, encoded []int64, minValue int64, bitWidth uint) {
+       if len(encoded) == 0 {
+               return
+       }
+       var word uint64
+       var used uint
+       base, pos := uint64(minValue), 0
+       for _, e := range encoded {
+               d := uint64(e) - base
+               word |= d << used
+               used += bitWidth
+               if used >= 64 {
+                       binary.LittleEndian.PutUint64(dst[pos:], word)
+                       pos += 8
+                       used -= 64
+                       word = d >> (bitWidth - used)
+               }
        }
-       return binary.LittleEndian.AppendUint64(dst, v)
+       binary.LittleEndian.PutUint64(dst[pos:], word)
 }
 
 func alpReadInt[T alpFloat](src []byte) int64 {
@@ -129,9 +177,7 @@ type alpEncoder[T alpFloat] struct {
 
        // Scratch reused across vectors, calls, and pages.
        encodedScratch []int64
-       deltaScratch   []uint64
        excPositions   []uint16
-       excValues      []T
        sampleScratch  []T
        spacedScratch  []T
        pageHeader     []byte
@@ -164,7 +210,7 @@ func (enc *alpEncoder[T]) setVectorSize(logSize int) {
        enc.vectorSize = 1 << logSize
        enc.vectorBuf = make([]T, enc.vectorSize)
        enc.encodedScratch = make([]int64, enc.vectorSize)
-       enc.deltaScratch = make([]uint64, enc.vectorSize)
+       enc.excPositions = make([]uint16, enc.vectorSize)
 }
 
 // SetVectorSize sets how many values each vector holds: a power of two from
@@ -192,6 +238,14 @@ func (enc *alpEncoder[T]) Type() parquet.Type {
 // final partial vector.
 func (enc *alpEncoder[T]) Put(in []T) {
        for len(in) > 0 {
+               if enc.bufCount == 0 && len(in) >= enc.vectorSize {
+                       // A whole vector is here already: encode it where it 
is rather
+                       // than copy it into the buffer first.
+                       enc.encodeVector(in[:enc.vectorSize])
+                       enc.totalCount += enc.vectorSize
+                       in = in[enc.vectorSize:]
+                       continue
+               }
                n := copy(enc.vectorBuf[enc.bufCount:], in)
                enc.bufCount += n
                enc.totalCount += n
@@ -267,69 +321,103 @@ func (enc *alpEncoder[T]) research(sample []T, 
presetBits int64) (alpEncodingPar
        return full, true
 }
 
-func (enc *alpEncoder[T]) encodeVector(values []T) {
-       params := enc.findParams(values)
-
-       enc.vectorsProcessed++
-       if enc.cachedPresets == nil && enc.vectorsProcessed >= 
alpSamplerVectors {
-               enc.buildPresetCache()
-       }
-
+// scaleVector scales values with params into the encoder's scratch: every
+// integer, and the positions of the exceptions. It returns how many exceptions
+// there are, the frame of reference, and the width the integers pack at.
+func (enc *alpEncoder[T]) scaleVector(values []T, params alpEncodingParams) 
(numExc int, minValue int64, bitWidth int) {
+       // Scaling a value also determines whether it is an exception, so one 
pass
+       // collects both the integers and the exceptions.
        encoded := enc.encodedScratch[:len(values)]
-       enc.excPositions = enc.excPositions[:0]
-       enc.excValues = enc.excValues[:0]
-
-       // Encoding a value also determines whether it is an exception, so 
collect
-       // both results in one pass.
-       s := newALPScaling[T](params.exponent, params.factor)
-       minValue := int64(math.MaxInt64)
-       for i, v := range values {
-               e, ok := s.tryEncode(v)
-               if !ok {
-                       enc.excPositions = append(enc.excPositions, uint16(i))
-                       enc.excValues = append(enc.excValues, v)
-                       continue
-               }
-               encoded[i] = e
-               minValue = min(e, minValue)
-       }
+       numExc = alpScale(values, params.exponent, params.factor, encoded, 
enc.excPositions)
 
-       if len(enc.excValues) == len(values) {
-               // Nothing encoded, so nothing constrains the frame of 
reference.
-               minValue = 0
+       // When nothing encodes, nothing constrains the frame of reference, and 
a
+       // width of zero packs nothing. Otherwise the range leaves each 
exception's
+       // slot holding the frame of reference itself, which costs no bits, so 
the
+       // exceptions cannot widen the packing.
+       var maxValue int64
+       if numExc < len(values) {
+               minValue, maxValue = alpIntRange(encoded, 
enc.excPositions[:numExc])
        }
-       // An exception still takes up a slot among the packed integers. 
Filling the
-       // slot with the frame of reference itself costs no bits, so the 
exceptions
-       // cannot widen the packing.
-       for _, pos := range enc.excPositions {
-               encoded[pos] = minValue
-       }
-
        // The difference between two int64 values can exceed int64. Compute it 
in
        // unsigned arithmetic; the decoder adds the wrapped difference back.
-       deltas := enc.deltaScratch[:len(values)]
-       var maxDelta uint64
-       for i, e := range encoded {
-               deltas[i] = uint64(e) - uint64(minValue)
-               maxDelta = max(deltas[i], maxDelta)
-       }
-       bitWidth := bits.Len64(maxDelta)
+       return numExc, minValue, bits.Len64(uint64(maxValue) - uint64(minValue))
+}
 
-       startLen := len(enc.encodedBuf)
-       enc.encodedBuf = append(enc.encodedBuf, byte(params.exponent), 
byte(params.factor))
-       enc.encodedBuf = binary.LittleEndian.AppendUint16(enc.encodedBuf, 
uint16(len(enc.excPositions)))
-       enc.encodedBuf = alpAppendInt[T](enc.encodedBuf, uint64(minValue))
-       enc.encodedBuf = append(enc.encodedBuf, byte(bitWidth))
-       enc.encodedBuf = alpAppendPackedBits(enc.encodedBuf, deltas, bitWidth)
+func (enc *alpEncoder[T]) encodeVector(values []T) {
+       n := len(values)
+       var (
+               params   alpEncodingParams
+               numExc   int
+               minValue int64
+               bitWidth int
+       )
+       if len(enc.cachedPresets) == 1 {
+               // With one scaling on the shortlist there is nothing to 
choose, so
+               // the vector is scaled straight away. What the sample would 
have
+               // estimated is read off the result, and a sample is only taken 
when
+               // that is no better than PLAIN, to check whether the data has 
changed
+               // scale.
+               params = enc.cachedPresets[0]
+               numExc, minValue, bitWidth = enc.scaleVector(values, params)
+               sampleBits, sampled := 
alpSampledSizeBits[T](enc.encodedScratch[:n], enc.excPositions[:numExc])
+               if sampleBits >= int64(sampled)*int64(8*alpEncodedBytes[T]()) {
+                       sample := alpSample(values, enc.sampleScratch[:0])
+                       if full, ok := enc.research(sample, sampleBits); ok {
+                               params = full
+                               numExc, minValue, bitWidth = 
enc.scaleVector(values, params)
+                       }
+               }
+       } else {
+               params = enc.findParams(values)
+               numExc, minValue, bitWidth = enc.scaleVector(values, params)
+       }
+       encoded := enc.encodedScratch[:n]
+       excPositions := enc.excPositions[:numExc]
 
-       for _, pos := range enc.excPositions {
-               enc.encodedBuf = 
binary.LittleEndian.AppendUint16(enc.encodedBuf, pos)
+       enc.vectorsProcessed++
+       if enc.cachedPresets == nil && enc.vectorsProcessed >= 
alpSamplerVectors {
+               enc.buildPresetCache()
        }
-       for _, v := range enc.excValues {
-               enc.encodedBuf = alpAppendInt[T](enc.encodedBuf, 
alpFloatToBits(v))
+
+       // The packing stores whole words, so it needs room for one past the 
end of
+       // the vector. The exceptions overwrite what it leaves after the packed
+       // bytes, and the final reslice drops the rest.
+       valueBytes := alpEncodedBytes[T]()
+       packedSize := alpPackedSize(n, bitWidth)
+       size := alpVectorHeaderSize[T]() + packedSize + numExc*(2+valueBytes)
+       start := len(enc.encodedBuf)
+       enc.encodedBuf = slices.Grow(enc.encodedBuf, size+8)[:start+size]
+       out := enc.encodedBuf[start : start+size+8]
+
+       out[0], out[1] = byte(params.exponent), byte(params.factor)
+       binary.LittleEndian.PutUint16(out[2:], uint16(numExc))
+       if valueBytes == 4 {
+               binary.LittleEndian.PutUint32(out[4:], uint32(minValue))
+       } else {
+               binary.LittleEndian.PutUint64(out[4:], uint64(minValue))
+       }
+       out[4+valueBytes] = byte(bitWidth)
+       out = out[alpVectorHeaderSize[T]():]
+
+       alpPack(out, encoded, minValue, uint(bitWidth))
+       out = out[packedSize:]
+
+       for i, pos := range excPositions {
+               binary.LittleEndian.PutUint16(out[2*i:], pos)
+       }
+       out = out[2*numExc:]
+       switch values := any(values).(type) {
+       case []float64:
+               for i, pos := range excPositions {
+                       binary.LittleEndian.PutUint64(out[8*i:], 
math.Float64bits(values[pos]))
+               }
+       case []float32:
+               for i, pos := range excPositions {
+                       binary.LittleEndian.PutUint32(out[4*i:], 
math.Float32bits(values[pos]))
+               }
        }
 
-       enc.vectorSizes = append(enc.vectorSizes, len(enc.encodedBuf)-startLen)
+       enc.vectorSizes = append(enc.vectorSizes, size)
 }
 
 // buildPresetCache keeps the scaling pairs the sampled vectors chose most 
often,
diff --git a/parquet/internal/encoding/alp_encoding_test.go 
b/parquet/internal/encoding/alp_encoding_test.go
index 2dd3f17b..88a09942 100644
--- a/parquet/internal/encoding/alp_encoding_test.go
+++ b/parquet/internal/encoding/alp_encoding_test.go
@@ -22,6 +22,7 @@ import (
        "fmt"
        "math"
        "math/bits"
+       "math/rand/v2"
        "slices"
        "testing"
 
@@ -34,7 +35,7 @@ import (
        "github.com/stretchr/testify/require"
 )
 
-// alpTestUnpackBits reverses alpAppendPackedBits with a plain bit reader.
+// alpTestUnpackBits reverses alpPack with a plain bit reader.
 func alpTestUnpackBits(packed []byte, out []uint64, bitWidth int) error {
        if bitWidth == 0 {
                clear(out)
@@ -50,6 +51,18 @@ func alpTestUnpackBits(packed []byte, out []uint64, bitWidth 
int) error {
        return nil
 }
 
+// alpTestPackBits packs values as the distances above a minimum of zero.
+func alpTestPackBits(values []uint64, bitWidth int) []byte {
+       encoded := make([]int64, len(values))
+       for i, v := range values {
+               encoded[i] = int64(v)
+       }
+       size := alpPackedSize(len(values), bitWidth)
+       packed := make([]byte, size+8)
+       alpPack(packed, encoded, 0, uint(bitWidth))
+       return packed[:size]
+}
+
 func TestALPPackUnpackBits(t *testing.T) {
        tests := []struct {
                name     string
@@ -86,7 +99,7 @@ func TestALPPackUnpackBits(t *testing.T) {
 
        for _, tt := range tests {
                t.Run(tt.name, func(t *testing.T) {
-                       packed := alpAppendPackedBits(nil, tt.values, 
tt.bitWidth)
+                       packed := alpTestPackBits(tt.values, tt.bitWidth)
                        assert.Len(t, packed, alpPackedSize(len(tt.values), 
tt.bitWidth))
 
                        unpacked := make([]uint64, len(tt.values))
@@ -96,10 +109,38 @@ func TestALPPackUnpackBits(t *testing.T) {
        }
 }
 
+// alpPack against a packer that sets one bit at a time, at every width. The
+// lengths sit either side of the groups of 8 and the four runs alpPack works
+// in, and the frame of reference is far enough from the integers for the
+// distances to wrap.
+func TestALPPackEveryWidth(t *testing.T) {
+       rng := rand.New(rand.NewPCG(13, 14))
+       for bitWidth := 1; bitWidth <= 64; bitWidth++ {
+               for _, count := range []int{1, 7, 8, 9, 31, 32, 33, 40, 63, 64, 
65, 1000, 1024, 1031} {
+                       minValue := int64(rng.Uint64())
+                       encoded := make([]int64, count)
+                       want := make([]byte, alpPackedSize(count, bitWidth))
+                       bit := 0
+                       for i := range encoded {
+                               distance := rng.Uint64() >> (64 - bitWidth)
+                               encoded[i] = int64(uint64(minValue) + distance)
+                               for b := range bitWidth {
+                                       want[bit/8] |= byte(distance>>b&1) << 
(bit % 8)
+                                       bit++
+                               }
+                       }
+
+                       packed := make([]byte, len(want)+8)
+                       alpPack(packed, encoded, minValue, uint(bitWidth))
+                       require.Equal(t, want, packed[:len(want)], "bitWidth=%d 
count=%d", bitWidth, count)
+               }
+       }
+}
+
 // TestALPPackBitsKnownOutput pins the byte layout, so a change of bit packer
 // cannot silently break pages written by an earlier one.
 func TestALPPackBitsKnownOutput(t *testing.T) {
-       packed := alpAppendPackedBits(nil, []uint64{0, 1, 2, 3}, 2)
+       packed := alpTestPackBits([]uint64{0, 1, 2, 3}, 2)
        require.Len(t, packed, 1)
        assert.Equal(t, byte(0xE4), packed[0])
 }
@@ -1005,6 +1046,35 @@ func TestALPFloat32IncrementalPut(t *testing.T) {
        }
 }
 
+// A page does not depend on how its values were split between calls to Put:
+// whole vectors encoded straight from the caller's slice and vectors gathered
+// in the encoder's buffer come out the same.
+func TestALPEncoderPutSplitsDoNotChangeThePage(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()
+               }
+       }
+       encode := func(split int) []byte {
+               enc := newALPEncoder[float64](format.Encoding_ALP, 
newFloat64Column(), memory.DefaultAllocator)
+               for from := 0; from < count; from += split {
+                       enc.Put(values[from:min(from+split, count)])
+               }
+               buf, err := enc.FlushValues()
+               require.NoError(t, err)
+               defer buf.Release()
+               return append([]byte(nil), buf.Bytes()...)
+       }
+
+       want := encode(1)
+       for _, split := range []int{7, alpDefaultVectorSize - 1, 
alpDefaultVectorSize, alpDefaultVectorSize + 1, 3 * alpDefaultVectorSize, 
count} {
+               assert.Equal(t, want, encode(split), "split=%d", split)
+       }
+}
+
 func TestALPFloat32MixedDataPatterns(t *testing.T) {
        var values []float32
 
diff --git a/parquet/internal/encoding/alp_params.go 
b/parquet/internal/encoding/alp_params.go
index d24caeae..f691260d 100644
--- a/parquet/internal/encoding/alp_params.go
+++ b/parquet/internal/encoding/alp_params.go
@@ -56,53 +56,119 @@ type alpEncodingParams struct {
        factor   int
 }
 
-// alpSample appends up to alpSamplerSamples values to out, one from each
-// stride-wide block. The position within the block shifts from one block to
-// the next, so data that repeats with the stride's period, such as a NaN at
-// every 128th value, can't fill the whole sample.
+// alpSamplePosition returns where in a vector of n values the i-th sampled
+// value is, for i up to (n-1)/stride with stride from alpSampleStride. There 
is
+// one from each stride-wide block, and the position within the block shifts
+// from one block to the next, so data that repeats with the stride's period,
+// such as a NaN at every 128th value, can't fill the whole sample.
+func alpSamplePosition(i, stride, n int) int {
+       block := i * stride
+       if idx := block + i%stride; idx < n {
+               return idx
+       }
+       return block
+}
+
+// alpSampleStride returns the block width that samples up to alpSamplerSamples
+// of n values.
+func alpSampleStride(n int) int {
+       return max(1, (n+alpSamplerSamples-1)/alpSamplerSamples)
+}
+
+// alpSample appends the sampled values to out, up to alpSamplerSamples of 
them.
 func alpSample[T alpFloat](values []T, out []T) []T {
-       stride := max(1, (len(values)+alpSamplerSamples-1)/alpSamplerSamples)
-       for i, block := 0, 0; block < len(values); i, block = i+1, block+stride 
{
-               idx := block + i%stride
-               if idx >= len(values) {
-                       idx = block
-               }
-               out = append(out, values[idx])
+       stride := alpSampleStride(len(values))
+       for i := 0; i*stride < len(values); i++ {
+               out = append(out, values[alpSamplePosition(i, stride, 
len(values))])
        }
        return out
 }
 
+// alpSampledSizeBits is alpEstimateSizeBits over the sample of a vector that
+// is scaled already: encoded holds the integer of every value, and excPos the
+// positions of the exceptions, in order. It also returns the size of the
+// sample. Reading the sample's size off the scaled vector costs no arithmetic
+// on the values, which scaling the sample a second time would.
+func alpSampledSizeBits[T alpFloat](encoded []int64, excPos []uint16) 
(sizeBits int64, sampled int) {
+       stride := alpSampleStride(len(encoded))
+       minEncoded, maxEncoded := int64(math.MaxInt64), int64(math.MinInt64)
+       numExceptions := 0
+       for ; sampled*stride < len(encoded); sampled++ {
+               idx := alpSamplePosition(sampled, stride, len(encoded))
+               // The sampled positions only move forward, as the exceptions 
do.
+               for len(excPos) > 0 && int(excPos[0]) < idx {
+                       excPos = excPos[1:]
+               }
+               if len(excPos) > 0 && int(excPos[0]) == idx {
+                       numExceptions++
+                       continue
+               }
+               minEncoded, maxEncoded = min(minEncoded, encoded[idx]), 
max(maxEncoded, encoded[idx])
+       }
+
+       sizeBits = int64(numExceptions) * int64(alpExceptionBits[T]())
+       if numExceptions < sampled {
+               width := bits.Len64(uint64(maxEncoded) - uint64(minEncoded))
+               sizeBits += int64(sampled) * int64(width)
+       }
+       return sizeBits, sampled
+}
+
 // alpExceptionBits is what one exception costs: the value at its full width,
 // plus the position that patches it back in.
 func alpExceptionBits[T alpFloat]() int {
        return 8*alpEncodedBytes[T]() + 16
 }
 
+// alpEstimateBlock is how many values a size estimate scales between checks of
+// whether the scaling can still matter.
+const alpEstimateBlock = 32
+
 // alpEstimateSizeBits estimates the encoded size for a parameter pair and
 // reports how many values it can encode. The cost includes the packed integers
 // at the width left by the frame of reference and every exception.
 func alpEstimateSizeBits[T alpFloat](values []T, exponent, factor int) 
(sizeBits int64, numEncodable int) {
+       return alpEstimateSizeBitsWithin(values, exponent, factor, 
math.MaxInt64)
+}
+
+// alpEstimateSizeBitsWithin is alpEstimateSizeBits for a caller with no use
+// for a scaling larger than limit. Neither the exceptions nor the packing 
width
+// can shrink as more values are scaled, so the size of the values scaled so 
far
+// is a lower bound on the whole. Once that passes limit the scan stops, and
+// reports a size above limit with numEncodable 0. Most scalings turn nearly
+// every value into an exception, so most scans stop within a block or two of a
+// search that would otherwise scale every value for every scaling.
+func alpEstimateSizeBitsWithin[T alpFloat](values []T, exponent, factor int, 
limit int64) (sizeBits int64, numEncodable int) {
+       var (
+               encoded [alpEstimateBlock]int64
+               excPos  [alpEstimateBlock]uint16
+       )
+       excBits := int64(alpExceptionBits[T]())
        minEncoded, maxEncoded := int64(math.MaxInt64), int64(math.MinInt64)
        numExceptions := 0
-       s := newALPScaling[T](exponent, factor)
-       for _, v := range values {
-               e, ok := s.tryEncode(v)
-               if !ok {
-                       numExceptions++
-                       continue
+       for len(values) > numEncodable+numExceptions {
+               start := numEncodable + numExceptions
+               block := values[start:min(start+alpEstimateBlock, len(values))]
+               n := alpScale(block, exponent, factor, encoded[:], excPos[:])
+               numExceptions += n
+               numEncodable += len(block) - n
+               if n < len(block) {
+                       lo, hi := alpIntRange(encoded[:len(block)], excPos[:n])
+                       minEncoded, maxEncoded = min(minEncoded, lo), 
max(maxEncoded, hi)
                }
-               minEncoded, maxEncoded = min(minEncoded, e), max(maxEncoded, e)
-       }
 
-       sizeBits = int64(numExceptions) * int64(alpExceptionBits[T]())
-       numEncodable = len(values) - numExceptions
-       if numEncodable == 0 {
-               return sizeBits, 0
+               sizeBits = int64(numExceptions) * excBits
+               if numEncodable > 0 {
+                       // The encoded range can exceed int64, so compute its 
width in
+                       // unsigned arithmetic.
+                       width := bits.Len64(uint64(maxEncoded) - 
uint64(minEncoded))
+                       sizeBits += int64(len(values)) * int64(width)
+               }
+               if sizeBits > limit {
+                       return sizeBits, 0
+               }
        }
-       // The encoded range can exceed int64, so compute its width in unsigned
-       // arithmetic.
-       width := bits.Len64(uint64(maxEncoded) - uint64(minEncoded))
-       return sizeBits + int64(len(values))*int64(width), numEncodable
+       return sizeBits, numEncodable
 }
 
 // For equal-size estimates, the ALP paper prefers the larger exponent,
@@ -133,7 +199,9 @@ func alpFindBestParams[T alpFloat](values []T) 
(alpEncodingParams, int64) {
 
        for e := range maxExponent + 1 {
                for f := range e + 1 {
-                       sizeBits, numEncodable := alpEstimateSizeBits(values, 
e, f)
+                       // A scaling the same size as the best can still win 
the tie, so
+                       // only one that is larger is cut short.
+                       sizeBits, numEncodable := 
alpEstimateSizeBitsWithin(values, e, f, bestBits)
                        // A scaling that turns almost everything into an 
exception tells us
                        // nothing about how wide the rest would pack.
                        if numEncodable < 2 {
@@ -159,7 +227,9 @@ func alpFindBestParamsWithPresets[T alpFloat](values []T, 
presets []alpEncodingP
        for _, p := range presets {
                // Only the size counts here. Every shortlisted scaling already 
encoded
                // enough values during sampling to be worth trying.
-               sizeBits, _ := alpEstimateSizeBits(values, p.exponent, p.factor)
+               // Here a tie goes to the earlier scaling, so one that can only
+               // match the best is cut short too.
+               sizeBits, _ := alpEstimateSizeBitsWithin(values, p.exponent, 
p.factor, bestBits-1)
                if sizeBits >= bestBits {
                        notImproved++
                        if notImproved == alpPresetGiveUpAfter {
diff --git a/parquet/internal/encoding/alp_params_test.go 
b/parquet/internal/encoding/alp_params_test.go
index 0af677cd..9f5bb160 100644
--- a/parquet/internal/encoding/alp_params_test.go
+++ b/parquet/internal/encoding/alp_params_test.go
@@ -18,6 +18,7 @@ package encoding
 
 import (
        "math"
+       "math/rand/v2"
        "testing"
 
        "github.com/stretchr/testify/assert"
@@ -205,3 +206,54 @@ func TestALPSamplePeriodicData(t *testing.T) {
        params, _ := alpFindBestParams(sample)
        assert.Equal(t, 2, params.exponent-params.factor, "two decimal places, 
got %+v", params)
 }
+
+// A size estimate that is cut short must not change what a search concludes:
+// within the limit it is the full estimate, and past the limit it says so.
+func TestALPEstimateSizeBitsWithin(t *testing.T) {
+       rng := rand.New(rand.NewPCG(9, 10))
+       // More than one block of values, and not a whole number of blocks.
+       values := alpTestAwkwardValues[float64](rng, 5*alpEstimateBlock+7)
+       for e := range alpNumExponents[float64]() {
+               for f := range e + 1 {
+                       fullBits, fullEncodable := alpEstimateSizeBits(values, 
e, f)
+                       for _, limit := range []int64{0, fullBits / 2, fullBits 
- 1, fullBits, fullBits + 1, math.MaxInt64} {
+                               bits, numEncodable := 
alpEstimateSizeBitsWithin(values, e, f, limit)
+                               if fullBits <= limit {
+                                       require.Equal(t, fullBits, bits, 
"exponent %d factor %d limit %d", e, f, limit)
+                                       require.Equal(t, fullEncodable, 
numEncodable, "exponent %d factor %d limit %d", e, f, limit)
+                                       continue
+                               }
+                               require.Greater(t, bits, limit, "exponent %d 
factor %d limit %d", e, f, limit)
+                               require.Zero(t, numEncodable, "exponent %d 
factor %d limit %d", e, f, limit)
+                       }
+               }
+       }
+}
+
+// The size of a vector's sample read off the scaled vector is the size
+// estimated by scaling the sample.
+func TestALPSampledSizeBits(t *testing.T) {
+       rng := rand.New(rand.NewPCG(11, 12))
+       for _, count := range []int{1, 5, 255, 256, 257, 1000, 1024, 4096} {
+               values := alpTestAwkwardValues[float64](rng, count)
+               // A NaN at every stride-th value is the pattern the sample's 
shifting
+               // positions are there for.
+               for i := 0; i < count; i += alpSampleStride(count) {
+                       values[i] = math.NaN()
+               }
+               sample := alpSample(values, nil)
+               encoded, excPos := make([]int64, count), make([]uint16, count)
+               for e := range alpNumExponents[float64]() {
+                       for f := range e + 1 {
+                               numExc := alpScale(values, e, f, encoded, 
excPos)
+                               if numExc < count {
+                                       alpIntRange(encoded, excPos[:numExc])
+                               }
+                               wantBits, _ := alpEstimateSizeBits(sample, e, f)
+                               bits, sampled := 
alpSampledSizeBits[float64](encoded, excPos[:numExc])
+                               require.Equal(t, len(sample), sampled, "count 
%d", count)
+                               require.Equal(t, wantBits, bits, "count %d 
exponent %d factor %d", count, e, f)
+                       }
+               }
+       }
+}
diff --git a/parquet/internal/encoding/alp_scaling.go 
b/parquet/internal/encoding/alp_scaling.go
index f0b8930b..ef5cf981 100644
--- a/parquet/internal/encoding/alp_scaling.go
+++ b/parquet/internal/encoding/alp_scaling.go
@@ -23,6 +23,7 @@ package encoding
 import (
        "math"
 
+       "github.com/apache/arrow-go/v18/arrow"
        "github.com/apache/arrow-go/v18/parquet"
 )
 
@@ -133,16 +134,6 @@ func alpParquetType[T alpFloat]() parquet.Type {
        panic("parquet: ALP: unsupported float type")
 }
 
-func alpFloatToBits[T alpFloat](v T) uint64 {
-       switch f := any(v).(type) {
-       case float32:
-               return uint64(math.Float32bits(f))
-       case float64:
-               return math.Float64bits(f)
-       }
-       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 {
@@ -204,3 +195,119 @@ func (s *alpScaling[T]) tryEncode(v T) (encoded int64, ok 
bool) {
        encoded = s.encode(v)
        return encoded, s.decode(encoded) == v
 }
+
+// alpScale64 scales every value to the integer alpScaling.encode gives it and
+// checks, as tryEncode does, that the integer decodes back to the value. It
+// writes all the integers to encoded and the positions of the values that
+// fail, in order, to excPos. Both must hold len(values). It returns how many
+// failed.
+//
+// This is the loop every value of a column goes through, so it is written for
+// one type and avoids what alpScaling cannot. Nothing in it branches on the
+// data: an exception costs what any other value costs, where a branch is
+// mispredicted wherever the two mix. And it leaves the range of the integers
+// to alpIntRange, because tracking a minimum and a maximum here would make
+// every value wait for the one before.
+func alpScale64(values []float64, encExp, encFac, decFac, decExp float64, 
encoded []int64, excPos []uint16) (numExc int) {
+       encoded = encoded[:len(values)]
+       excPos = excPos[:len(values)]
+       // The same values as integers, so that comparing bits does not have to
+       // move each one out of a floating-point register.
+       raw := 
arrow.Uint64Traits.CastFromBytes(arrow.Float64Traits.CastToBytes(values))[:len(values)]
+       for i, v := range values {
+               bits := raw[i]
+               scaled := float64(v * encExp * encFac)
+               // Rounds as alpScaling.round does.
+               e := int64(math.RoundToEven(scaled))
+               // A NaN fails the comparison too.
+               if !(math.Abs(scaled) <= alpEncodingUpperFloat64) {
+                       e = int64(alpEncodingUpperFloat64)
+               }
+               encoded[i] = e
+               excPos[numExc] = uint16(i)
+               // Comparing bits rather than values also rejects -0.0, which 
scales
+               // to 0 and decodes to 0.0.
+               if math.Float64bits(float64(e)*decFac*decExp) != bits {
+                       numExc++
+               }
+       }
+       return numExc
+}
+
+// alpScale32 is the FLOAT form of alpScale64.
+func alpScale32(values []float32, encExp, encFac, decFac, decExp float32, 
encoded []int64, excPos []uint16) (numExc int) {
+       encoded = encoded[:len(values)]
+       excPos = excPos[:len(values)]
+       raw := 
arrow.Uint32Traits.CastFromBytes(arrow.Float32Traits.CastToBytes(values))[:len(values)]
+       for i, v := range values {
+               bits := raw[i]
+               scaled := float32(v * encExp * encFac)
+               e := int64(math.RoundToEven(float64(scaled)))
+               if !(float32(math.Abs(float64(scaled))) <= 
alpEncodingUpperFloat32) {
+                       e = int64(alpEncodingUpperFloat32)
+               }
+               encoded[i] = e
+               excPos[numExc] = uint16(i)
+               if math.Float32bits(float32(e)*decFac*decExp) != bits {
+                       numExc++
+               }
+       }
+       return numExc
+}
+
+// alpScale runs the loop of T's width with the constants of one exponent and
+// factor pair.
+func alpScale[T alpFloat](values []T, exponent, factor int, encoded []int64, 
excPos []uint16) (numExc int) {
+       switch values := any(values).(type) {
+       case []float64:
+               return alpScale64(values, alpDoublePow10[exponent], 
alpDoubleNegPow10[factor],
+                       alpDoublePow10[factor], alpDoubleNegPow10[exponent], 
encoded, excPos)
+       case []float32:
+               return alpScale32(values, alpFloatPow10[exponent], 
alpFloatNegPow10[factor],
+                       alpFloatPow10[factor], alpFloatNegPow10[exponent], 
encoded, excPos)
+       }
+       panic("parquet: ALP: unsupported float type")
+}
+
+// alpIntRange returns the smallest and the largest of the integers alpScale
+// wrote, leaving out those at the exception positions, of which there must be
+// fewer than there are integers. It overwrites each exception's integer with
+// the smallest.
+func alpIntRange(encoded []int64, excPos []uint16) (minValue, maxValue int64) {
+       if len(excPos) > 0 {
+               // The exceptions are in order, so the first position that is 
not its
+               // own index in excPos holds an integer that counts. Being 
within the
+               // range, it stands in for the exceptions while the range is 
found.
+               keep := 0
+               for keep < len(excPos) && int(excPos[keep]) == keep {
+                       keep++
+               }
+               fill := encoded[keep]
+               for _, pos := range excPos {
+                       encoded[pos] = fill
+               }
+       }
+
+       // Four of each, so that an integer does not wait for its neighbors.
+       min0, min1, min2, min3 := int64(math.MaxInt64), int64(math.MaxInt64), 
int64(math.MaxInt64), int64(math.MaxInt64)
+       max0, max1, max2, max3 := int64(math.MinInt64), int64(math.MinInt64), 
int64(math.MinInt64), int64(math.MinInt64)
+       i := 0
+       for ; i+4 <= len(encoded); i += 4 {
+               q := encoded[i : i+4 : i+4]
+               min0, max0 = min(min0, q[0]), max(max0, q[0])
+               min1, max1 = min(min1, q[1]), max(max1, q[1])
+               min2, max2 = min(min2, q[2]), max(max2, q[2])
+               min3, max3 = min(min3, q[3]), max(max3, q[3])
+       }
+       for ; i < len(encoded); i++ {
+               min0, max0 = min(min0, encoded[i]), max(max0, encoded[i])
+       }
+       minValue, maxValue = min(min0, min1, min2, min3), max(max0, max1, max2, 
max3)
+
+       // An exception still takes up a slot among the packed integers. The
+       // smallest integer packs to zero there, whatever the width.
+       for _, pos := range excPos {
+               encoded[pos] = minValue
+       }
+       return minValue, maxValue
+}
diff --git a/parquet/internal/encoding/alp_scaling_test.go 
b/parquet/internal/encoding/alp_scaling_test.go
index 91c5c0cd..f2214ccc 100644
--- a/parquet/internal/encoding/alp_scaling_test.go
+++ b/parquet/internal/encoding/alp_scaling_test.go
@@ -18,6 +18,7 @@ package encoding
 
 import (
        "math"
+       "math/rand/v2"
        "testing"
 
        "github.com/stretchr/testify/assert"
@@ -244,3 +245,122 @@ func TestALPScalingMultipliesByANegativePower(t 
*testing.T) {
        assert.NotEqual(t, value, 
float32(encoded)/(alpPow10[float32](exponent)/alpPow10[float32](factor)),
                "dividing has stopped losing the last bit, so this test no 
longer guards anything")
 }
+
+// alpTestAwkwardValues returns count values that are mostly short decimals,
+// with every kind of value that cannot be encoded mixed in.
+func alpTestAwkwardValues[T alpFloat](rng *rand.Rand, count int) []T {
+       values := make([]T, count)
+       for i := range values {
+               x := rng.Float64()
+               v := math.Floor(x*1e5+0.5) / 1000
+               switch rng.IntN(40) {
+               case 0:
+                       v = math.NaN()
+               case 1:
+                       v = math.Inf(1)
+               case 2:
+                       v = math.Inf(-1)
+               case 3:
+                       v = math.Copysign(0, -1)
+               case 4:
+                       v = 0
+               case 5:
+                       v = x * 1e300
+               case 6:
+                       v = -x * 9.3e18
+               case 7:
+                       v = x * 1e-300
+               case 8:
+                       v = -math.Floor(x * 1e9)
+               case 9:
+                       v = x
+               }
+               values[i] = T(v)
+       }
+       return values
+}
+
+// alpTestEdgeValues returns values a step at a time either side of the
+// magnitudes where rounding and the integer range change behavior, scaled by
+// the powers of ten that bring them there.
+func alpTestEdgeValues[T alpFloat]() []T {
+       var values []T
+       for _, edge := range []float64{
+               1 << 63, 9223372036854774784, 1 << 53, 1 << 52, 
6755399441055744, 1 << 51,
+               1 << 31, 2147483520, 1 << 24, 12582912, 1 << 23, 1 << 22,
+       } {
+               for _, scale := range []float64{1, 1e-1, 1e-2, 1e-3, 1e-5, 
1e-10, 1e-15, 1e-18, 10, 100} {
+                       up, down := T(edge*scale), T(edge*scale)
+                       for range 40 {
+                               values = append(values, up, -up, down, -down)
+                               switch any(up).(type) {
+                               case float32:
+                                       up = T(math.Nextafter32(float32(up), 
float32(math.Inf(1))))
+                                       down = 
T(math.Nextafter32(float32(down), 0))
+                               default:
+                                       up = T(math.Nextafter(float64(up), 
math.Inf(1)))
+                                       down = T(math.Nextafter(float64(down), 
0))
+                               }
+                       }
+               }
+       }
+       return values
+}
+
+// alpTestScaleMatchesTryEncode holds alpScale and alpIntRange to
+// alpScaling.tryEncode, value by value, for every exponent and factor.
+func alpTestScaleMatchesTryEncode[T alpFloat](t *testing.T, values []T) {
+       t.Helper()
+       n := len(values)
+       encoded, excPos := make([]int64, n), make([]uint16, n)
+       isException := make([]bool, n)
+       for e := range alpNumExponents[T]() {
+               for f := range e + 1 {
+                       s := newALPScaling[T](e, f)
+                       numExc := alpScale(values, e, f, encoded, excPos)
+
+                       wantExc := 0
+                       wantMin, wantMax := int64(math.MaxInt64), 
int64(math.MinInt64)
+                       for i, v := range values {
+                               want, ok := s.tryEncode(v)
+                               isException[i] = !ok
+                               if !ok {
+                                       if wantExc >= numExc || 
int(excPos[wantExc]) != i {
+                                               t.Fatalf("exponent %d factor 
%d: %v at %d is an exception", e, f, v, i)
+                                       }
+                                       wantExc++
+                                       continue
+                               }
+                               if encoded[i] != want {
+                                       t.Fatalf("exponent %d factor %d: %v at 
%d scales to %d, want %d", e, f, v, i, encoded[i], want)
+                               }
+                               wantMin, wantMax = min(wantMin, want), 
max(wantMax, want)
+                       }
+                       require.Equal(t, wantExc, numExc, "exponent %d factor 
%d", e, f)
+                       if numExc == n {
+                               continue
+                       }
+
+                       minValue, maxValue := alpIntRange(encoded, 
excPos[:numExc])
+                       require.Equal(t, wantMin, minValue, "exponent %d factor 
%d", e, f)
+                       require.Equal(t, wantMax, maxValue, "exponent %d factor 
%d", e, f)
+                       for i := range values {
+                               if isException[i] && encoded[i] != wantMin {
+                                       t.Fatalf("exponent %d factor %d: 
exception slot %d holds %d, want %d", e, f, i, encoded[i], wantMin)
+                               }
+                       }
+               }
+       }
+}
+
+func TestALPScaleMatchesTryEncode(t *testing.T) {
+       rng := rand.New(rand.NewPCG(7, 8))
+       // Lengths either side of the groups of four alpIntRange works in, and a
+       // full vector.
+       for _, count := range []int{1, 2, 3, 4, 5, 7, 1024} {
+               alpTestScaleMatchesTryEncode(t, 
alpTestAwkwardValues[float64](rng, count))
+               alpTestScaleMatchesTryEncode(t, 
alpTestAwkwardValues[float32](rng, count))
+       }
+       alpTestScaleMatchesTryEncode(t, alpTestEdgeValues[float64]())
+       alpTestScaleMatchesTryEncode(t, alpTestEdgeValues[float32]())
+}

Reply via email to