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 StringBuilder.
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   */
31  public class Utf8StringBuilder extends Utf8Appendable 
32  {
33      final StringBuilder _buffer;
34      
35      public Utf8StringBuilder()
36      {
37          super(new StringBuilder());
38          _buffer=(StringBuilder)_appendable;
39      }
40      
41      public Utf8StringBuilder(int capacity)
42      {
43          super(new StringBuilder(capacity));
44          _buffer=(StringBuilder)_appendable;
45      }
46      
47      public int length()
48      {
49          return _buffer.length();
50      }
51      
52      public void reset()
53      {
54          _buffer.setLength(0);
55          _more=0;
56          _bits=0;
57      }
58      
59      public StringBuilder getStringBuilder()
60      {
61          if (_more!=0)
62              throw new IllegalStateException("!utf8");
63          return _buffer;
64      }
65      
66      @Override
67      public String toString()
68      {
69          if (_more!=0)
70              throw new IllegalStateException("!utf8");
71          return _buffer.toString();
72      }
73  }