001/*
002 * Copyright (c) 2012-2017 Institut National des Sciences Appliquées de Lyon (INSA-Lyon)
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the Eclipse Public License v1.0
006 * which accompanies this distribution, and is available at
007 * http://www.eclipse.org/legal/epl-v10.html
008 */
009
010package org.eclipse.golo.compiler.utils;
011
012import java.util.AbstractMap;
013import java.util.Map;
014import java.util.Set;
015import java.util.Collection;
016
017public abstract class AbstractRegister<K, V> extends AbstractMap<K, Set<V>> implements Register<K, V> {
018
019  private Map<K, Set<V>> map;
020
021  public AbstractRegister() {
022    super();
023    this.map = initMap();
024  };
025
026  protected abstract Map<K, Set<V>> initMap();
027
028  protected abstract Set<V> emptyValue();
029
030  @SuppressWarnings("unchecked")
031  private Set<V> getOrInit(Object key) {
032    Set<V> bag;
033    if (!this.map.containsKey(key)) {
034      bag = emptyValue();
035      this.map.put((K) key, bag);
036    } else {
037      bag = this.map.get(key);
038    }
039    return bag;
040  }
041
042  @Override
043  public Set<Map.Entry<K, Set<V>>> entrySet() {
044    return map.entrySet();
045  }
046
047  @Override
048  public Set<V> put(K key, Set<V> value) {
049    return this.map.put(key, value);
050  }
051
052  @Override
053  public boolean containsKey(Object key) {
054    return map.containsKey(key);
055  }
056
057  @Override
058  public Set<V> get(Object key) {
059    return getOrInit(key);
060  }
061
062  @Override
063  public void add(K key, V value) {
064    getOrInit(key).add(value);
065  }
066
067  @Override
068  public void addAll(K key, Collection<V> values) {
069    getOrInit(key).addAll(values);
070  }
071
072  @Override
073  public void updateKey(K oldKey, K newKey) {
074    if (this.map.containsKey(oldKey)) {
075      this.map.put(newKey, this.map.get(oldKey));
076      this.map.remove(oldKey);
077    }
078  }
079}