Skip to content

Commit 1c24958

Browse files
committed
Impl view strategy example.
1 parent 45429cd commit 1c24958

File tree

1 file changed

+107
-0
lines changed

1 file changed

+107
-0
lines changed
Lines changed: 107 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,107 @@
1+
import 'dart:io';
2+
import 'dart:typed_data';
3+
4+
void main() {
5+
final byteList = SomeData()
6+
..add('Hello guru')
7+
..add(123456789)
8+
..add(3.1456564984);
9+
10+
final strFormat = byteList.toStringView(StrViewStrategy());
11+
final hexFormat = byteList.toStringView(HexViewStrategy());
12+
final zipFormat = byteList.toStringView(ZipViewStrategy());
13+
14+
print(strFormat);
15+
print(hexFormat);
16+
print(zipFormat);
17+
}
18+
19+
abstract class ViewStrategy {
20+
String out(SomeData byteList);
21+
}
22+
23+
class HexViewStrategy implements ViewStrategy {
24+
@override
25+
String out(SomeData byteList) {
26+
final buf = StringBuffer();
27+
28+
for (final val in byteList.toList()) {
29+
buf.write('${val.toString().padRight(15)}: ');
30+
31+
if (val is String) {
32+
buf.writeln(_stringToHex(val));
33+
} else {
34+
buf.writeln(_valueToHex(val, size: 8));
35+
}
36+
}
37+
38+
return buf.toString();
39+
}
40+
41+
String _stringToHex(String value) {
42+
return value.codeUnits
43+
.map((charCode) => _valueToHex(size: 1, charCode))
44+
.join(' ');
45+
}
46+
47+
String _valueToHex<T>(T value, {required int size}) {
48+
late ByteData byteData;
49+
50+
if (size == 1) {
51+
byteData = ByteData(1)..setInt8(0, value as int);
52+
} else {
53+
byteData = ByteData(size);
54+
if (value is double) {
55+
byteData.setFloat64(0, value);
56+
} else if (value is int) {
57+
byteData.setInt64(0, value);
58+
}
59+
}
60+
61+
final bytes = byteData.buffer.asUint8List();
62+
return bytes.map((e) => e.toRadixString(16).padLeft(2, '0')).join(' ');
63+
}
64+
}
65+
66+
class StrViewStrategy implements ViewStrategy {
67+
@override
68+
String out(SomeData byteList) {
69+
return '${byteList.toList().join(', ')}\n';
70+
}
71+
}
72+
73+
class ZipViewStrategy extends StrViewStrategy {
74+
@override
75+
String out(SomeData byteList) {
76+
final codes = super.out(byteList).codeUnits;
77+
final bytes = GZipCodec().encode(codes);
78+
final buf = StringBuffer();
79+
80+
var odd = 1;
81+
for (final byte in bytes) {
82+
final hexByte = byte.toRadixString(16).padLeft(2, '0');
83+
buf.write('$hexByte ');
84+
85+
if (odd++ % 16 == 0) {
86+
buf.writeln();
87+
}
88+
}
89+
90+
return buf.toString();
91+
}
92+
}
93+
94+
class SomeData {
95+
String toStringView(ViewStrategy strategy) {
96+
return '${strategy.runtimeType}:\n'
97+
'${strategy.out(this)}';
98+
}
99+
100+
void add(dynamic str) {
101+
_buf.add(str);
102+
}
103+
104+
List toList() => _buf;
105+
106+
final _buf = <dynamic>[];
107+
}

0 commit comments

Comments
 (0)