blob: cf4e97e5c058aaa1b2e59f5b5d36f70ef0944e58 [file] [log] [blame]
// Copyright (c) 2019, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:ffi';
import 'dart:typed_data';
import 'package:test/test.dart';
import 'package:ffi/ffi.dart';
Pointer<Uint8> _bytesFromList(List<int> ints) {
final Pointer<Uint8> ptr = Pointer.allocate(count: ints.length);
final Uint8List list = ptr.asExternalTypedData(count: ints.length);
list.setAll(0, ints);
return ptr;
}
main() {
test("toUtf8 ASCII", () {
final String start = "Hello World!\n";
final Pointer<Uint8> converted = Utf8.toUtf8(start).cast();
final Uint8List end =
converted.asExternalTypedData(count: start.length + 1);
final matcher =
equals([72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 10, 0]);
expect(end, matcher);
converted.free();
});
test("fromUtf8 ASCII", () {
final Pointer<Utf8> utf8 = _bytesFromList(
[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100, 33, 10, 0]).cast();
final String end = Utf8.fromUtf8(utf8);
expect(end, "Hello World!\n");
});
test("toUtf8 emoji", () {
final String start = "πŸ˜ŽπŸ‘ΏπŸ’¬";
final Pointer<Utf8> converted = Utf8.toUtf8(start).cast();
final int length = Utf8.strlen(converted);
final Uint8List end =
converted.cast<Uint8>().asExternalTypedData(count: length + 1);
final matcher =
equals([240, 159, 152, 142, 240, 159, 145, 191, 240, 159, 146, 172, 0]);
expect(end, matcher);
converted.free();
});
test("formUtf8 emoji", () {
final Pointer<Utf8> utf8 = _bytesFromList(
[240, 159, 152, 142, 240, 159, 145, 191, 240, 159, 146, 172, 0]).cast();
final String end = Utf8.fromUtf8(utf8);
expect(end, "πŸ˜ŽπŸ‘ΏπŸ’¬");
});
test("toUtf8 unpaired surrogate", () {
final String start = String.fromCharCodes([0xD800, 0x1000]);
final Pointer<Utf8> converted = Utf8.toUtf8(start).cast();
final int length = Utf8.strlen(converted);
final Uint8List end =
converted.cast<Uint8>().asExternalTypedData(count: length + 1);
expect(end, equals([237, 160, 128, 225, 128, 128, 0]));
converted.free();
});
test("fromUtf8 unpaired surrogate", () {
final Pointer<Utf8> utf8 =
_bytesFromList([237, 160, 128, 225, 128, 128, 0]).cast();
final String end = Utf8.fromUtf8(utf8);
expect(end, equals(String.fromCharCodes([0xD800, 0x1000])));
});
test("fromUtf8 invalid", () {
final Pointer<Utf8> utf8 = _bytesFromList([0x80, 0x00]).cast();
expect(() => Utf8.fromUtf8(utf8), throwsA(isFormatException));
});
}