View Javadoc
1   /*
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2026, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v2.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.classic.kryo;
15  
16  import java.nio.ByteBuffer;
17  import java.nio.CharBuffer;
18  import java.nio.charset.CharsetDecoder;
19  import java.nio.charset.CharsetEncoder;
20  import java.nio.charset.CoderResult;
21  import java.nio.charset.CodingErrorAction;
22  import java.nio.charset.StandardCharsets;
23  
24  /**
25   * Recycled UTF-8 {@link CharsetEncoder}/{@link CharsetDecoder} for the string codecs.
26   * Matches {@link String#getBytes} / {@code new String(byte[], UTF_8)} replacement policy.
27   * Not thread-safe; one instance per serializer.
28   */
29  final class ReusableUtf8 {
30  
31      /** UTF-8 is at most 3 bytes per Java {@code char} (surrogate pairs use 4 bytes for 2 chars). */
32      static final int MAX_BYTES_PER_CHAR = 3;
33  
34      private final CharsetEncoder encoder = StandardCharsets.UTF_8.newEncoder()
35              .onMalformedInput(CodingErrorAction.REPLACE)
36              .onUnmappableCharacter(CodingErrorAction.REPLACE);
37      private final CharsetDecoder decoder = StandardCharsets.UTF_8.newDecoder()
38              .onMalformedInput(CodingErrorAction.REPLACE)
39              .onUnmappableCharacter(CodingErrorAction.REPLACE);
40  
41      private byte[] encodeBuf = new byte[512];
42      private char[] decodeBuf = new char[512];
43  
44      byte[] buffer() {
45          return encodeBuf;
46      }
47  
48      int maxEncodedLength(int charCount) {
49          return encodedCapacity(charCount);
50      }
51  
52      /**
53       * Encodes {@code s} into {@link #buffer()}. Returns the UTF-8 byte count;
54       * valid bytes are {@code buffer()[0 .. length)}.
55       */
56      int encode(String s) {
57          int cap = encodedCapacity(s.length());
58          if (encodeBuf.length < cap) {
59              encodeBuf = new byte[cap];
60          }
61          return encode(s, encodeBuf, 0);
62      }
63  
64      /**
65       * Encodes {@code s} into {@code dest} starting at {@code off}.
66       * {@code dest} must have room for {@link #maxEncodedLength(int) maxEncodedLength(s.length())}
67       * bytes from {@code off}.
68       */
69      int encode(String s, byte[] dest, int off) {
70          encoder.reset();
71          CharBuffer in = CharBuffer.wrap(s);
72          ByteBuffer out = ByteBuffer.wrap(dest, off, dest.length - off);
73          CoderResult cr = encoder.encode(in, out, true);
74          throwIfError(cr);
75          if (cr.isOverflow()) {
76              throw new IllegalArgumentException("UTF-8 dest too small for " + s.length() + " chars");
77          }
78          cr = encoder.flush(out);
79          throwIfError(cr);
80          if (cr.isOverflow()) {
81              throw new IllegalArgumentException("UTF-8 dest too small for flush");
82          }
83          return out.position() - off;
84      }
85  
86      String decode(byte[] src, int off, int len) {
87          if (len == 0) {
88              return "";
89          }
90          int cap = decodedCapacity(len);
91          if (decodeBuf.length < cap) {
92              decodeBuf = new char[cap];
93          }
94          for (;;) {
95              decoder.reset();
96              ByteBuffer in = ByteBuffer.wrap(src, off, len);
97              CharBuffer out = CharBuffer.wrap(decodeBuf);
98              CoderResult cr = decoder.decode(in, out, true);
99              if (growDecodeBufIfOverflow(cr)) {
100                 continue;
101             }
102             throwIfError(cr);
103             cr = decoder.flush(out);
104             if (growDecodeBufIfOverflow(cr)) {
105                 continue;
106             }
107             throwIfError(cr);
108             return new String(decodeBuf, 0, out.position());
109         }
110     }
111 
112     private boolean growDecodeBufIfOverflow(CoderResult cr) {
113         if (!cr.isOverflow()) {
114             return false;
115         }
116         decodeBuf = new char[decodeBuf.length * 2];
117         return true;
118     }
119 
120     private static void throwIfError(CoderResult cr) {
121         if (cr.isError()) {
122             throw new IllegalStateException("UTF-8 coding error: " + cr);
123         }
124     }
125 
126     private int encodedCapacity(int charCount) {
127         int n = (int) Math.ceil(charCount * (double) encoder.maxBytesPerChar());
128         return Math.max(n, 16);
129     }
130 
131     private int decodedCapacity(int byteCount) {
132         int n = (int) Math.ceil(byteCount * (double) decoder.maxCharsPerByte());
133         return Math.max(n, 16);
134     }
135 }