Flutter Engine
The Flutter Engine
Loading...
Searching...
No Matches
StringCodec.java
Go to the documentation of this file.
1// Copyright 2013 The Flutter Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5package io.flutter.plugin.common;
6
7import androidx.annotation.Nullable;
8import java.nio.ByteBuffer;
9import java.nio.charset.Charset;
10
11/**
12 * A {@link MessageCodec} using UTF-8 encoded String messages.
13 *
14 * <p>This codec is guaranteed to be compatible with the corresponding <a
15 * href="https://api.flutter.dev/flutter/services/StringCodec-class.html">StringCodec</a> on the
16 * Dart side. These parts of the Flutter SDK are evolved synchronously.
17 */
18public final class StringCodec implements MessageCodec<String> {
19 private static final Charset UTF8 = Charset.forName("UTF8");
20 public static final StringCodec INSTANCE = new StringCodec();
21
22 private StringCodec() {}
23
24 @Override
25 @Nullable
26 public ByteBuffer encodeMessage(@Nullable String message) {
27 if (message == null) {
28 return null;
29 }
30 // TODO(mravn): Avoid the extra copy below.
31 final byte[] bytes = message.getBytes(UTF8);
32 final ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.length);
33 buffer.put(bytes);
34 return buffer;
35 }
36
37 @Override
38 @Nullable
39 public String decodeMessage(@Nullable ByteBuffer message) {
40 if (message == null) {
41 return null;
42 }
43 final byte[] bytes;
44 final int offset;
45 final int length = message.remaining();
46 if (message.hasArray()) {
47 bytes = message.array();
48 offset = message.arrayOffset();
49 } else {
50 // TODO(mravn): Avoid the extra copy below.
51 bytes = new byte[length];
52 message.get(bytes);
53 offset = 0;
54 }
55 return new String(bytes, offset, length, UTF8);
56 }
57}
static final StringCodec INSTANCE
ByteBuffer encodeMessage(@Nullable String message)
String decodeMessage(@Nullable ByteBuffer message)
static const uint8_t buffer[]
size_t length
Win32Message message
Point offset