|
| 1 | +import 'package:runtime/src/exceptions.dart'; |
| 2 | + |
| 3 | +const String _listPrefix = "List<"; |
| 4 | +const String _mapPrefix = "Map<String,"; |
| 5 | + |
| 6 | +T cast<T>(dynamic input) { |
| 7 | + if (input == null) { |
| 8 | + return null; |
| 9 | + } |
| 10 | + |
| 11 | + try { |
| 12 | + final typeString = T.toString(); |
| 13 | + if (typeString.startsWith(_listPrefix)) { |
| 14 | + if (input is! List) { |
| 15 | + throw TypeError(); |
| 16 | + } |
| 17 | + |
| 18 | + if (typeString == "List<int>") { |
| 19 | + return List<int>.from(input) as T; |
| 20 | + } else if (typeString == "List<num>") { |
| 21 | + return List<num>.from(input) as T; |
| 22 | + } else if (typeString == "List<double>") { |
| 23 | + return List<double>.from(input) as T; |
| 24 | + } else if (typeString == "List<String>") { |
| 25 | + return List<String>.from(input) as T; |
| 26 | + } else if (typeString == "List<bool>") { |
| 27 | + return List<bool>.from(input) as T; |
| 28 | + } else if (typeString == "List<Map<String, dynamic>>") { |
| 29 | + final objects = <Map<String, dynamic>>[]; |
| 30 | + (input as List).forEach((o) { |
| 31 | + if (o == null) { |
| 32 | + objects.add(null); |
| 33 | + } else { |
| 34 | + if (o is! Map<String, dynamic>) { |
| 35 | + throw TypeError(); |
| 36 | + } |
| 37 | + objects.add(o); |
| 38 | + } |
| 39 | + }); |
| 40 | + return objects as T; |
| 41 | + } |
| 42 | + } else if (typeString.startsWith(_mapPrefix)) { |
| 43 | + if (input is! Map) { |
| 44 | + throw TypeError(); |
| 45 | + } |
| 46 | + |
| 47 | + final inputMap = input as Map<String, dynamic>; |
| 48 | + if (typeString == "Map<String, int>") { |
| 49 | + return Map<String, int>.from(inputMap) as T; |
| 50 | + } else if (typeString == "Map<String, num>") { |
| 51 | + return Map<String, num>.from(inputMap) as T; |
| 52 | + } else if (typeString == "Map<String, double>") { |
| 53 | + return Map<String, double>.from(inputMap) as T; |
| 54 | + } else if (typeString == "Map<String, String>") { |
| 55 | + return Map<String, String>.from(inputMap) as T; |
| 56 | + } else if (typeString == "Map<String, bool>") { |
| 57 | + return Map<String, bool>.from(inputMap) as T; |
| 58 | + } |
| 59 | + } |
| 60 | + |
| 61 | + return input as T; |
| 62 | + } on CastError { |
| 63 | + throw TypeCoercionException(T, input.runtimeType as Type); |
| 64 | + } on TypeError { |
| 65 | + throw TypeCoercionException(T, input.runtimeType as Type); |
| 66 | + } |
| 67 | +} |
0 commit comments