1 | | | import 'converter.dart'; |
2 | | |
|
3 | | | final class NumConverter extends Converter { |
4 | | 11 | const NumConverter(); |
5 | | |
|
6 | | | static const instance = NumConverter(); |
7 | | |
|
8 | | 1 | @override |
9 | | 3 | Cast<T> value<T>() => _numCastors[T] as Cast<T>? ?? Converter.identity<T>; |
10 | | |
|
11 | | 2 | static int _toInt(dynamic x) { |
12 | | 3 | if (x is int && x.isFinite) return x; |
13 | | 2 | final y = (x as num).toDouble(); |
14 | | 2 | if (!y.isFinite) return double.nan as int; // intended type error |
15 | | 3 | final z = y.toInt(), d = y - z; |
16 | | 2 | if (d != 0) return double.nan as int; // intended type error |
17 | | 0 | return z; |
18 | | 1 | } |
19 | | |
|
20 | | 3 | static double _toDbl(dynamic x) => (x as num).toDouble(); |
21 | | |
|
22 | | 4 | static final Map<Type, Cast> _numCastors = { |
23 | | 1 | int: _toInt, |
24 | | 1 | double: _toDbl, |
25 | | | }; |
26 | | | } |