veilidchat/lib/tools/json_tools.dart

29 lines
1.1 KiB
Dart
Raw Normal View History

2023-07-17 22:39:33 -04:00
import 'dart:convert';
2023-07-26 14:20:29 -04:00
import 'dart:typed_data';
2023-07-17 22:39:33 -04:00
2023-07-26 15:58:38 -04:00
T jsonDecodeBytes<T>(T Function(dynamic) fromJson, Uint8List data) =>
fromJson(jsonDecode(utf8.decode(data)));
2023-07-17 22:39:33 -04:00
2023-07-30 13:57:00 -04:00
T? jsonDecodeOptBytes<T>(T Function(dynamic) fromJson, Uint8List? data) =>
(data == null) ? null : fromJson(jsonDecode(utf8.decode(data)));
2023-07-17 22:39:33 -04:00
Uint8List jsonEncodeBytes(Object? object,
2023-07-26 15:58:38 -04:00
{Object? Function(Object?)? toEncodable}) =>
Uint8List.fromList(
utf8.encode(jsonEncode(object, toEncodable: toEncodable)));
2023-07-17 22:39:33 -04:00
2023-07-26 15:58:38 -04:00
Future<Uint8List> jsonUpdateBytes<T>(T Function(dynamic) fromJson,
2023-07-17 22:39:33 -04:00
Uint8List oldBytes, Future<T> Function(T) update) async {
2023-07-26 14:20:29 -04:00
final oldObj = fromJson(jsonDecode(utf8.decode(oldBytes)));
final newObj = await update(oldObj);
2023-07-17 22:39:33 -04:00
return jsonEncodeBytes(newObj);
}
Future<Uint8List> Function(Uint8List) jsonUpdate<T>(
2023-07-26 15:58:38 -04:00
T Function(dynamic) fromJson, Future<T> Function(T) update) =>
(oldBytes) => jsonUpdateBytes(fromJson, oldBytes, update);
2023-07-19 00:09:57 -04:00
T Function(Object?) genericFromJson<T>(
2023-07-26 15:58:38 -04:00
T Function(Map<String, dynamic>) fromJsonMap) =>
(json) => fromJsonMap(json! as Map<String, dynamic>);