floatBitsEqual function
Whether a and b have the same length and the same IEEE-754 bit
pattern at every index.
There is no == on a double anywhere in it: +0.0 and -0.0 differ, two
NaNs are equal exactly when their patterns are identical (payload
included), and the infinities and subnormals compare as the bits they are.
length, when given, is the number of leading elements of a that take
part, for a destination whose storage is sized to its capacity and whose
count is held beside it (InlineFloat32Array.storage and .length). It
must not exceed a.length. b is always taken whole, so the call
floatBitsEqual(field.storage, b, length: field.length) is the default test
of a field against an array. A generated class, whose default is a constant,
holds it in a Float32ArrayDefault / Float64ArrayDefault instead, which
answers the same question faster.
The length is compared first and a mismatch returns without reading an element. No allocation beyond two typed-list views, no mutation.
- Two
Float32Lists are compared on their 32-bit patterns, throughUint32Listviews, so an fp32 signaling NaN is compared as stored and not as the quieteddoubleit widens to. - Two
Float64Lists are compared on their 64-bit patterns, throughInt64Listviews. - Any other combination (a plain
List<double>, aconstliteral, or aFloat32Listagainst aFloat64List) compares the 64-bit pattern of thedoubleeach element holds. For an fp32 value held as a double that is the widened pattern, which distinguishes everything an fp32 can hold except the quiet bit of a signaling NaN, which the widening may set. The fp32 signaling-NaN raw-bytes path (CORELIB_PLAN ยง6.5) is separate and does not go through here.
Implementation
bool floatBitsEqual(List<double> a, List<double> b, {int? length}) {
final n = length ?? a.length;
RangeError.checkValueInInterval(n, 0, a.length, 'length');
if (n != b.length) return false;
if (n == 0) return true;
if (a is Float32List && b is Float32List) {
final x = Uint32List.view(a.buffer, a.offsetInBytes, n);
final y = Uint32List.view(b.buffer, b.offsetInBytes, n);
for (var i = 0; i < n; i++) {
if (x[i] != y[i]) return false;
}
return true;
}
if (a is Float64List && b is Float64List) {
final x = Int64List.view(a.buffer, a.offsetInBytes, n);
final y = Int64List.view(b.buffer, b.offsetInBytes, n);
for (var i = 0; i < n; i++) {
if (x[i] != y[i]) return false;
}
return true;
}
for (var i = 0; i < n; i++) {
_f64[0] = a[i];
final p = _i64[0];
_f64[0] = b[i];
if (p != _i64[0]) return false;
}
return true;
}