Skip to content

float value validation isn't right, accepts invalid values #1067

@osa1

Description

@osa1
edition = "2024";

message Foo {
  repeated float fs = 1;
}
import 'test.pb.dart';

void main() {
  final foo = Foo();
  foo.fs.add(0.123456789);
  print(foo);
  print(Foo.fromBuffer(foo.writeToBuffer()));
}

Prints:

fs: 0.123456789
fs: 0.12345679104328156

This is because the value being set isn't valid float, but the validation function isn't correct and accepts it:

bool _isFloat32(double value) =>
value.isNaN ||
value.isInfinite ||
(-3.4028234663852886E38 <= value) && (value <= 3.4028234663852886E38);

In this particular case, it doesn't handle the numbers between the min. and max. specified by this function, but are have more fractional digits that a 32-bit float can represent. There could be other bugs too.

Ideally you would convert the number to a float and back to a double, and check that you get the same number back, but we can't easily to this in Dart. Not sure if there's a performant way to do it, without writing the number to a Float32List or a ByteData and reading it back.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions