Skip to content

Commit d0c2b40

Browse files
committed
Add encoding functionality for int list to string
1 parent f71b241 commit d0c2b40

File tree

2 files changed

+57
-0
lines changed

2 files changed

+57
-0
lines changed
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
2+
// for details. All rights reserved. Use of this source code is governed by a
3+
// BSD-style license that can be found in the LICENSE file.
4+
5+
import 'dart:convert';
6+
import 'dart:typed_data';
7+
8+
/// Base64 encodes [dataPoints] as 32-bit unsigned integers serialized with
9+
/// big endian byte order.
10+
String encodeIntsAsBigEndianBase64String(List<int> dataPoints) {
11+
final byteData = ByteData(4 * dataPoints.length);
12+
for (int i = 0; i < dataPoints.length; i++) {
13+
byteData.setUint32(4 * i, dataPoints[i]);
14+
}
15+
return base64Encode(byteData.buffer.asUint8List());
16+
}
17+
18+
/// Counter part to [encodeIntsAsBigEndianBase64String].
19+
List<int> decodeIntsFromBigEndianBase64String(String encoded) {
20+
final bytes = base64Decode(encoded);
21+
final resLength = bytes.length ~/ 4;
22+
final dataPoints = List.filled(resLength, -1);
23+
final sublist = ByteData.sublistView(bytes);
24+
for (int i = 0; i < resLength; i++) {
25+
dataPoints[i] = sublist.getUint32(4 * i);
26+
}
27+
return dataPoints;
28+
}
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
// Copyright (c) 2024, the Dart project authors. Please see the AUTHORS file
2+
// for details. All rights reserved. Use of this source code is governed by a
3+
// BSD-style license that can be found in the LICENSE file.
4+
5+
import 'package:_pub_shared/format/encoding.dart';
6+
import 'package:test/test.dart';
7+
8+
void main() {
9+
test('encode/decode success', () {
10+
final data = [1, 2, 3, 4, 5, 6, 7, 8, 9];
11+
final encoded = encodeIntsAsBigEndianBase64String(data);
12+
expect(encoded, 'AAAAAQAAAAIAAAADAAAABAAAAAUAAAAGAAAABwAAAAgAAAAJ');
13+
expect(decodeIntsFromBigEndianBase64String(encoded), data);
14+
});
15+
16+
test('encode/decode empty', () {
17+
final data = <int>[];
18+
final encoded = encodeIntsAsBigEndianBase64String(data);
19+
expect(encoded, '');
20+
expect(decodeIntsFromBigEndianBase64String(encoded), data);
21+
});
22+
23+
test('encode/decode failure with negative integers', () {
24+
final data = <int>[-1, -2];
25+
final encoded = encodeIntsAsBigEndianBase64String(data);
26+
expect(encoded, '//////////4=');
27+
expect(decodeIntsFromBigEndianBase64String(encoded), isNot(data));
28+
});
29+
}

0 commit comments

Comments
 (0)