01: /*
02: * Copyright 2007 Google Inc.
03: *
04: * Licensed under the Apache License, Version 2.0 (the "License"); you may not
05: * use this file except in compliance with the License. You may obtain a copy of
06: * the License at
07: *
08: * http://www.apache.org/licenses/LICENSE-2.0
09: *
10: * Unless required by applicable law or agreed to in writing, software
11: * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
12: * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
13: * License for the specific language governing permissions and limitations under
14: * the License.
15: */
16: package com.google.gwt.dev.generator;
17:
18: import java.util.Set;
19: import java.util.HashSet;
20: import java.util.Collection;
21:
22: /**
23: * Generates unqiue identifiers. Use this class to avoid generating conflicting
24: * names with user code. This class isn't smart enough to know about scopes
25: * (which isn't generally a problem for generators in any case).
26: */
27: public class NameFactory {
28:
29: private final Set<String> usedNames = new HashSet<String>();
30:
31: /**
32: * Creates a new <code>NameFactory</code> that knows about
33: * <code>existingNames</code>.
34: *
35: * @param existingNames a list of names that may be <code>null</code>.
36: */
37: public NameFactory(Collection<String> existingNames) {
38: if (existingNames == null) {
39: return;
40: }
41: usedNames.addAll(existingNames);
42: }
43:
44: /**
45: * Creates a new <code>NameFactory</code> that doesn't know about any
46: * existing names.
47: */
48: public NameFactory() {
49: this (null);
50: }
51:
52: /**
53: * Adds a name to the set of already known identifiers. Has no affect if the
54: * name is already considered an existing identifier.
55: *
56: * @param name a not <code>null</code> name
57: */
58: public void addName(String name) {
59: usedNames.add(name);
60: }
61:
62: /**
63: * Creates a new unique name based off of <code>name</code> and adds it to
64: * the list of known names.
65: *
66: * @param name a not <code>null</code> name to base the new unique name from
67: * @return a new unique, not <code>null</code> name. This name may be
68: * possibly identical to <code>name</code>.
69: */
70: public String createName(String name) {
71: String newName = name;
72:
73: for (int count = 0; true; ++count) {
74: if (usedNames.contains(newName)) {
75: newName = name + count;
76: } else {
77: return newName;
78: }
79: }
80: }
81: }
|