google / google/protobuf.dart

`float` value validation isn't right, accepts invalid values

Open
#1,067 4 comments 0 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
Dart
Stars
572
Forks
196
Avg merge
1h 59m
Merged PRs (30d)
2

Description

```proto
edition = "2024";

message Foo {
repeated float fs = 1;
}
```
```dart
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: https://github.com/google/protobuf.dart/blob/27730dbb6edd7e621141353b0e19eab6d6cada3a/protobuf/lib/src/protobuf/field_error.dart#L140-L143

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.

Contributor guide

Open the contributing guide

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Reproduce the issue with the provided proto and Dart example, then inspect protobuf/lib/src/protobuf/field_error.dart around lines 140-143. Determine how a Dart value can be checked against float32 precision, including the fractional values currently accepted. Done means values that cannot round-trip as 32-bit floats are rejected while valid float values remain accepted.

Written by the indexing model from the issue text.

Assessment

Tech stack
dart
Domain
api
Issue type
Bug
Difficulty
3/5
Estimated time
1-2 days
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
48/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.