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 5 package io.flutter.plugin.common; 6 7 import java.nio.ByteBuffer; 8 import java.nio.charset.Charset; 9 10 /** 11 * A {@link MessageCodec} using UTF-8 encoded String messages. 12 * 13 * <p>This codec is guaranteed to be compatible with the corresponding 14 * <a href="https://docs.flutter.io/flutter/services/StringCodec-class.html">StringCodec</a> 15 * on the Dart side. These parts of the Flutter SDK are evolved synchronously.</p> 16 */ 17 public final class StringCodec implements MessageCodec<String> { 18 private static final Charset UTF8 = Charset.forName("UTF8"); 19 public static final StringCodec INSTANCE = new StringCodec(); 20 StringCodec()21 private StringCodec() { 22 } 23 24 @Override encodeMessage(String message)25 public ByteBuffer encodeMessage(String message) { 26 if (message == null) { 27 return null; 28 } 29 // TODO(mravn): Avoid the extra copy below. 30 final byte[] bytes = message.getBytes(UTF8); 31 final ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.length); 32 buffer.put(bytes); 33 return buffer; 34 } 35 36 @Override decodeMessage(ByteBuffer message)37 public String decodeMessage(ByteBuffer message) { 38 if (message == null) { 39 return null; 40 } 41 final byte[] bytes; 42 final int offset; 43 final int length = message.remaining(); 44 if (message.hasArray()) { 45 bytes = message.array(); 46 offset = message.arrayOffset(); 47 } else { 48 // TODO(mravn): Avoid the extra copy below. 49 bytes = new byte[length]; 50 message.get(bytes); 51 offset = 0; 52 } 53 return new String(bytes, offset, length, UTF8); 54 } 55 } 56