1 /*
2  *******************************************************************************
3  * Copyright (C) 2002-2012, International Business Machines Corporation and    *
4  * others. All Rights Reserved.                                                *
5  *******************************************************************************
6  */
7 package org.unicode.cldr.util;
8 
9 import com.ibm.icu.impl.Utility;
10 import com.ibm.icu.text.UTF16;
11 
12 public abstract class Quoter {
13     private static boolean DEBUG = false;
14 
15     protected boolean quoting = false;
16     protected StringBuffer output = new StringBuffer();
17 
setQuoting(boolean value)18     public void setQuoting(boolean value) {
19         quoting = value;
20     }
21 
isQuoting()22     public boolean isQuoting() {
23         return quoting;
24     }
25 
clear()26     public void clear() {
27         quoting = false;
28         output.setLength(0);
29     }
30 
length()31     public int length() {
32         return output.length();
33     }
34 
append(String string)35     public Quoter append(String string) {
36         output.append(string);
37         return this;
38     }
39 
append(int codepoint)40     public Quoter append(int codepoint) {
41         return append(UTF16.valueOf(codepoint));
42     }
43 
44     // warning, allows access to internals
45     @Override
toString()46     public String toString() {
47         setQuoting(false); // finish quoting
48         return output.toString();
49     }
50 
51     /**
52      * Implements standard ICU rule quoting
53      */
54     public static class RuleQuoter extends Quoter {
55         private StringBuffer quoteBuffer = new StringBuffer();
56 
57         @Override
setQuoting(boolean value)58         public void setQuoting(boolean value) {
59             if (quoting == value) return;
60             if (quoting) { // stop quoting
61                 Utility.appendToRule(output, -1, true, false, quoteBuffer); // close previous quote
62             }
63             quoting = value;
64         }
65 
66         @Override
append(String s)67         public Quoter append(String s) {
68             if (DEBUG) System.out.println("\"" + s + "\"");
69             if (quoting) {
70                 Utility.appendToRule(output, s, false, false, quoteBuffer);
71             } else {
72                 output.append(s);
73             }
74             return this;
75         }
76     }
77 }