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