View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.util;
20  
21  /* ------------------------------------------------------------ */
22  /**
23   * UTF-8 StringBuffer.
24   *
25   * This class wraps a standard {@link java.lang.StringBuffer} and provides methods to append
26   * UTF-8 encoded bytes, that are converted into characters.
27   *
28   * This class is stateful and up to 4 calls to {@link #append(byte)} may be needed before
29   * state a character is appended to the string buffer.
30   *
31   * The UTF-8 decoding is done by this class and no additional buffers or Readers are used.
32   * The UTF-8 code was inspired by http://bjoern.hoehrmann.de/utf-8/decoder/dfa/
33   */
34  public class Utf8StringBuffer extends Utf8Appendable
35  {
36      final StringBuffer _buffer;
37  
38      public Utf8StringBuffer()
39      {
40          super(new StringBuffer());
41          _buffer = (StringBuffer)_appendable;
42      }
43  
44      public Utf8StringBuffer(int capacity)
45      {
46          super(new StringBuffer(capacity));
47          _buffer = (StringBuffer)_appendable;
48      }
49  
50      @Override
51      public int length()
52      {
53          return _buffer.length();
54      }
55  
56      @Override
57      public void reset()
58      {
59          super.reset();
60          _buffer.setLength(0);
61      }
62  
63      public StringBuffer getStringBuffer()
64      {
65          checkState();
66          return _buffer;
67      }
68  
69      @Override
70      public String toString()
71      {
72          checkState();
73          return _buffer.toString();
74      }
75  }