001/*
002 * Copyright c 2018 Rusi Popov, MDA Tools.net All rights reserved.
003 *
004 * This program and the accompanying materials are made available under the terms of the
005 * Eclipse Public License v2.0 which accompanies this distribution, and is available at
006 * http://www.eclipse.org/legal/epl-v20.html
007 */
008package net.mdatools.modelant.core.util.key;
009
010import java.util.HashMap;
011import java.util.Map;
012
013/**
014 * This class handles the generation of unique strings by mapping each one
015 * to a counter. The strings generated are:
016 *   original
017 *   original1
018 *   ...
019 *   originalN <pre>
020 * Usage:
021 *
022 *    name = constructUniqueName( name_suggestion );
023 *
024 * </pre>
025 * As it is statefull, it cannot be defined as an Operation
026 * @author Rusi Popov (popovr@mdatools.net)
027 */
028public class GenerateUniqueName {
029
030  /**
031   * Maps:
032   *   objects to actual names
033   *   names to repetition counters used to generate next unique name
034   */
035  private Map<String, Integer> wordToCounterMap = new HashMap<String, Integer>();
036
037  /**
038   * @return a non-null unique name based on the original
039   */
040  public String getUnique(String original) {
041    String result;
042    Integer counter;
043
044    counter = wordToCounterMap.get( original );
045    if ( counter == null ) {
046      counter = new Integer(0);
047      result = original;
048
049    } else { // the name is already bound, generate unique name
050      counter = new Integer(counter.intValue() +1);
051      result = original+counter;
052    }
053    wordToCounterMap.put( original, counter );
054
055    return result;
056  }
057}