View Javadoc

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