dart-lang / sdk

The Dart SDK, including the VM, JS and Wasm compilers, analysis, core libraries, and more.
https://dart.dev
BSD 3-Clause "New" or "Revised" License
10.23k stars 1.57k forks source link

[SDK Library] Consider supporting parsing binary integers #45063

Open parlough opened 3 years ago

parlough commented 3 years ago

For some content I'm working on it would be nice if int.parse and int.tryParse natively supported parsing binary integers prefixed with 0b similar to how it handles hexadecimal 0x ones currently.

Implementing this work now would also simplify the implementation of binary integer literals in the future as included in the considered small and useful features list documented in the language repo. The CFE/analyzer currently use the method for their conversion of the literals to consistent decimal values.

Analyzer: https://cs.opensource.google/dart/sdk/+/master:pkg/analyzer/tool/summary/mini_ast.dart;l=478 https://cs.opensource.google/dart/sdk/+/master:pkg/analyzer/lib/src/fasta/ast_builder.dart;l=2972

CFE: https://cs.opensource.google/dart/sdk/+/master:pkg/front_end/lib/src/fasta/kernel/body_builder.dart;l=2444

lrhn commented 3 years ago

I'm not particularly happy with supporting 0xF00 as input to int.parse now. I'd have preferred to not support that, and only support inputs which can come from int.toString(), along with int.parseRadix to match toRadixString and perhaps int.parseLiteral to handle things that have alternative representations like 0x or 0b prefixes.

Doing everything in one function makes that function slower and more complicated, and every caller needs to pay for that, whether they use it or not. Maybe we should just add int.parseRadix(String source, int radix, [int start = 0, int end]) which can parse a substring at any radix, then you can do if (string.startsWith("0b")) return int.parseRadix(string, 2, 2);. Having to create a substring to pass it to int.parse is also an overhead.