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  import java.io.IOException;
17  
18  /* ------------------------------------------------------------ */
19  /** UTF-8 StringBuffer.
20   *
21   * This class wraps a standard {@link java.lang.StringBuffer} and provides methods to append 
22   * UTF-8 encoded bytes, that are converted into characters.
23   * 
24   * This class is stateful and up to 6  calls to {@link #append(byte)} may be needed before 
25   * state a character is appended to the string buffer.
26   * 
27   * The UTF-8 decoding is done by this class and no additional buffers or Readers are used.
28   * The UTF-8 code was inspired by http://javolution.org
29   * 
30   * This class is not synchronised and should probably be called Utf8StringBuilder
31   */
32  public class Utf8StringBuffer extends Utf8Appendable 
33  {
34      final StringBuffer _buffer;
35      
36      public Utf8StringBuffer()
37      {
38          super(new StringBuffer());
39          _buffer=(StringBuffer)_appendable;
40      }
41      
42      public Utf8StringBuffer(int capacity)
43      {
44          super(new StringBuffer(capacity));
45          _buffer=(StringBuffer)_appendable;
46      }
47  
48      public int length()
49      {
50          return _buffer.length();
51      }
52      
53      public void reset()
54      {
55          _buffer.setLength(0);
56          _more=0;
57          _bits=0;
58      }
59      
60      public StringBuffer getStringBuffer()
61      {
62          if (_more!=0)
63              throw new IllegalStateException("!utf8");
64          return _buffer;
65      }
66      
67      @Override
68      public String toString()
69      {
70          if (_more!=0)
71              throw new IllegalStateException("!utf8");
72          return _buffer.toString();
73      }
74  }