-
Notifications
You must be signed in to change notification settings - Fork 36
/
redisserialise.dart
82 lines (73 loc) · 2.13 KB
/
redisserialise.dart
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
part of redis;
/*
* Free software licenced under
* MIT License
*
* Check for document LICENCE forfull licence text
*
* Luka Rahne
*/
Utf8Encoder RedisSerializeEncoder = Utf8Encoder();
class RedisBulk {
Iterable<int> iterable;
/// This clase enables sending Iterable<int>
/// as bulk data on redis
/// it can be used when sending files for example
RedisBulk(this.iterable) {}
}
typedef Consumer = void Function(Iterable<int> s);
class Serializer {
List<int> serialize(Object? object) {
return RedisSerialize.Serialize(object);
}
}
class RedisSerialize {
static final ASCII = const AsciiCodec();
static final UTF8 = const Utf8Codec();
static final _dollar = ASCII.encode("\$");
static final _star = ASCII.encode("\*");
static final _semicol = ASCII.encode(":");
static final _linesep = ASCII.encode("\r\n");
static final _dollarminus1 = ASCII.encode("\$-1");
static List<int> Serialize(Object? object) {
final s = <int>[];
SerializeConsumable(object, (v) => s.addAll(v));
return s;
}
static void SerializeConsumable(Object? object, Consumer consumer) {
if (object is String) {
var data = UTF8.encode(object);
consumer(_dollar);
consumer(_IntToRaw(data.length));
consumer(_linesep);
consumer(data);
consumer(_linesep);
} else if (object is Iterable) {
int len = object.length;
consumer(_star);
consumer(_IntToRaw(len));
consumer(_linesep);
object.forEach(
(v) => SerializeConsumable(v is int ? v.toString() : v, consumer));
} else if (object is int) {
consumer(_semicol);
consumer(_IntToRaw(object));
consumer(_linesep);
} else if (object is RedisBulk) {
consumer(_dollar);
consumer(_IntToRaw(object.iterable.length));
consumer(_linesep);
consumer(object.iterable);
consumer(_linesep);
} else if (object == null) {
consumer(_dollarminus1); //null bulk
} else {
throw ("cant serialize such type");
}
}
static Iterable<int> _IntToRaw(int n) {
//if(i>=0 && i < _ints.length)
// return _ints[i];
return ASCII.encode(n.toString());
}
}