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 StringBuilder.
19 *
20 * This class wraps a standard {@link java.lang.StringBuilder} 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 */
30 public class Utf8StringBuilder extends Utf8Appendable
31 {
32 final StringBuilder _buffer;
33
34 public Utf8StringBuilder()
35 {
36 super(new StringBuilder());
37 _buffer=(StringBuilder)_appendable;
38 }
39
40 public Utf8StringBuilder(int capacity)
41 {
42 super(new StringBuilder(capacity));
43 _buffer=(StringBuilder)_appendable;
44 }
45
46 @Override
47 public int length()
48 {
49 return _buffer.length();
50 }
51
52 @Override
53 public void reset()
54 {
55 super.reset();
56 _buffer.setLength(0);
57 }
58
59 public StringBuilder getStringBuilder()
60 {
61 checkState();
62 return _buffer;
63 }
64
65 @Override
66 public String toString()
67 {
68 checkState();
69 return _buffer.toString();
70 }
71
72 private void checkState()
73 {
74 if (!isUtf8SequenceComplete())
75 throw new IllegalArgumentException("Tried to read incomplete UTF8 decoded String");
76 }
77 }