1 package com.atlassian.vcache.marshallers;
2
3 import java.nio.ByteBuffer;
4 import java.nio.CharBuffer;
5 import java.nio.charset.CharacterCodingException;
6 import java.nio.charset.Charset;
7 import java.nio.charset.CharsetEncoder;
8 import java.nio.charset.CodingErrorAction;
9 import java.nio.charset.StandardCharsets;
10 import java.util.Arrays;
11 import javax.annotation.Nonnull;
12
13 import com.atlassian.annotations.Internal;
14 import com.atlassian.vcache.Marshaller;
15 import com.atlassian.vcache.MarshallerException;
16
17
18
19
20
21
22 @Internal
23 class StringMarshaller implements Marshaller<String>
24 {
25 private static final Charset ENCODING_CHARSET = StandardCharsets.UTF_8;
26
27 @Nonnull
28 @Override
29 public byte[] marshall(String str) throws MarshallerException
30 {
31
32 final CharsetEncoder encoder = ENCODING_CHARSET.newEncoder();
33 encoder.onMalformedInput(CodingErrorAction.REPORT);
34
35 try
36 {
37 final ByteBuffer buffer = encoder.encode(CharBuffer.wrap(str));
38 return Arrays.copyOf(buffer.array(), buffer.limit());
39 }
40 catch (CharacterCodingException e)
41 {
42 throw new MarshallerException("Unable to encode: " + str, e);
43 }
44 }
45
46 @Nonnull
47 @Override
48 public String unmarshall(byte[] raw)
49 {
50 return new String(raw, ENCODING_CHARSET);
51 }
52 }