View Javadoc
1   /**
2    * Copyright (C) 2014-2017 Philip Helger (www.helger.com)
3    * philip[at]helger[dot]com
4    *
5    * Licensed under the Apache License, Version 2.0 (the "License");
6    * you may not use this file except in compliance with the License.
7    * You may obtain a copy of the License at
8    *
9    *         http://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  package com.helger.schematron.pure.preprocess;
18  
19  import javax.annotation.Nullable;
20  import javax.annotation.concurrent.NotThreadSafe;
21  
22  import com.helger.commons.collection.ext.CommonsHashSet;
23  import com.helger.commons.collection.ext.ICommonsSet;
24  import com.helger.commons.string.ToStringGenerator;
25  
26  /**
27   * Utility lookup cache for all used IDs within a schema.
28   *
29   * @author Philip Helger
30   */
31  @NotThreadSafe
32  final class PreprocessorIDPool
33  {
34    private final ICommonsSet <String> m_aUsedIDs = new CommonsHashSet <> ();
35  
36    public PreprocessorIDPool ()
37    {}
38  
39    /**
40     * Create a unique ID based on the passed one. If the passed ID is not yet
41     * contained, than a numeric index is appended until the ID is unique.
42     *
43     * @param sID
44     *        The source ID. May be <code>null</code>.
45     * @return <code>null</code> if the passed ID is <code>null</code> indicating
46     *         that no ID is present. Otherwise a unique ID is returned.
47     */
48    @Nullable
49    public String getUniqueID (@Nullable final String sID)
50    {
51      if (sID == null)
52        return null;
53  
54      if (m_aUsedIDs.add (sID))
55      {
56        // Unique ID
57        return sID;
58      }
59  
60      // Non-unique ID
61      int nIndex = 0;
62      String sNewID = sID + nIndex;
63      do
64      {
65        if (m_aUsedIDs.add (sNewID))
66        {
67          // Now it's unique
68          return sNewID;
69        }
70        ++nIndex;
71        sNewID = sID + nIndex;
72      } while (true);
73    }
74  
75    @Override
76    public String toString ()
77    {
78      return new ToStringGenerator (this).append ("usedIDs", m_aUsedIDs).getToString ();
79    }
80  }