java.util.IdentityHashMap Java Examples

The following examples show how to use java.util.IdentityHashMap. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DistinctEntrySetElements.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final IdentityHashMap<String, String> identityHashMap =
        new IdentityHashMap<>();

    identityHashMap.put("One", "Un");
    identityHashMap.put("Two", "Deux");
    identityHashMap.put("Three", "Trois");

    Set<Map.Entry<String, String>> entrySet = identityHashMap.entrySet();
    HashSet<Map.Entry<String, String>> hashSet = new HashSet<>(entrySet);

    // NB: These comparisons are valid in this case because none of the
    //     keys put into 'identityHashMap' above are equal to any other.
    if (false == hashSet.equals(entrySet)) {
        throw new RuntimeException("Test FAILED: Sets are not equal.");
    }
    if (hashSet.hashCode() != entrySet.hashCode()) {
        throw new RuntimeException("Test FAILED: Set's hashcodes are not equal.");
    }
}
 
Example #2
Source File: MapWithCollisionsProviders.java    From streamsupport with GNU General Public License v2.0 6 votes vote down vote up
private static <T> Collection<Object[]> makeMapsMoreTypes(String desc,
                                                          T[] keys,
                                                          T val) {
    Collection<Object[]> cases = new ArrayList<>();
    cases.add(createCase("Hashtable with " + desc,
                         new Hashtable<>(), keys, val));
    cases.add(createCase("IdentityHashMap with " + desc,
                         new IdentityHashMap<>(), keys, val));
    cases.add(createCase("TreeMap with " + desc,
                         new TreeMap<>(), keys, val));
    cases.add(createCase("WeakHashMap with " + desc,
                         new WeakHashMap<>(), keys, val));
    cases.add(createCase("ConcurrentHashMap with " + desc,
                         new ConcurrentHashMap<>(), keys, val));
    cases.add(createCase("ConcurrentSkipListMap with " + desc,
                         new ConcurrentSkipListMap<>(), keys, val));
    return cases;
}
 
Example #3
Source File: ListMapTestCase.java    From vespa with Apache License 2.0 6 votes vote down vote up
@Test
public void testAnotherImplementation() {
    ListMap<String, String> stringMap = new ListMap<>(IdentityHashMap.class);
    String foo = "foo";
    String bar = "bar";
    String far = "far";
    String rab = "rab";

    stringMap.put(foo, bar);
    stringMap.put(foo, far);
    stringMap.put(bar, rab);

    List<String> fooValues = stringMap.get(new String("foo"));
    assertEquals(0, fooValues.size());
    fooValues = stringMap.get(foo);
    assertEquals(2, fooValues.size());
    assertEquals("bar", fooValues.get(0));
    assertEquals("far", fooValues.get(1));


    List<String> barValues = stringMap.get(new String("bar"));
    assertEquals(0, barValues.size());
    barValues = stringMap.get(bar);
    assertEquals(1, barValues.size());
    assertEquals("rab", barValues.get(0));
}
 
Example #4
Source File: AvroSchemaUtil.java    From avro-util with BSD 2-Clause "Simplified" License 6 votes vote down vote up
private static void traverseSchema(Schema schema, SchemaVisitor visitor, IdentityHashMap<Object, Boolean> visited) {
  if (visited.put(schema, Boolean.TRUE) != null) {
    return; //been there, done that
  }
  visitor.visitSchema(schema);
  switch (schema.getType()) {
    case UNION:
      for (Schema unionBranch : schema.getTypes()) {
        traverseSchema(unionBranch, visitor, visited);
      }
      return;
    case ARRAY:
      traverseSchema(schema.getElementType(), visitor, visited);
      return;
    case MAP:
      traverseSchema(schema.getValueType(), visitor, visited);
      return;
    case RECORD:
      for (Schema.Field field : schema.getFields()) {
        visitor.visitField(field);
        traverseSchema(field.schema(), visitor, visited);
      }
      break;
    default:
  }
}
 
Example #5
Source File: EntrySetIteratorRemoveInvalidatesEntry.java    From native-obfuscator with GNU General Public License v3.0 6 votes vote down vote up
public static void main(String[] args) throws Exception {
    final IdentityHashMap<String, String> identityHashMap =
        new IdentityHashMap<>();

    identityHashMap.put("One", "Un");
    identityHashMap.put("Two", "Deux");
    identityHashMap.put("Three", "Trois");

    Iterator<Map.Entry<String, String>> entrySetIterator =
        identityHashMap.entrySet().iterator();
    Map.Entry<String, String> entry = entrySetIterator.next();

    entrySetIterator.remove();

    try {
        entry.getKey();
        throw new RuntimeException("Test FAILED: Entry not invalidated by removal.");
    } catch (Exception e) { }
}
 
Example #6
Source File: SyncDeserializer.java    From syncer with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
public static EventDeserializer defaultDeserializer() {
  Map<Long, TableMapEventData> tableMapEventByTableId = new HashMap<>();
  Map<EventType, EventDataDeserializer> eventDataDeserializers = new IdentityHashMap<>();
  eventDataDeserializers.put(EventType.WRITE_ROWS,
      new WriteRowsEventDataDeserializer(tableMapEventByTableId));
  eventDataDeserializers.put(EventType.UPDATE_ROWS,
      new UpdateRowsEventDataDeserializer(tableMapEventByTableId));
  eventDataDeserializers.put(EventType.DELETE_ROWS,
      new DeleteRowsEventDataDeserializer(tableMapEventByTableId));
  eventDataDeserializers.put(EventType.EXT_WRITE_ROWS,
      new WriteRowsEventDataDeserializer(tableMapEventByTableId).
          setMayContainExtraInformation(true));
  eventDataDeserializers.put(EventType.EXT_UPDATE_ROWS,
      new UpdateRowsEventDataDeserializer(tableMapEventByTableId).
          setMayContainExtraInformation(true));
  eventDataDeserializers.put(EventType.EXT_DELETE_ROWS,
      new DeleteRowsEventDataDeserializer(tableMapEventByTableId).
          setMayContainExtraInformation(true));
  eventDataDeserializers.put(EventType.QUERY, new QueryEventDataDeserializer());
  eventDataDeserializers.put(EventType.TABLE_MAP, new TableMapEventDataDeserializer());

  return new EventDeserializer(new EventHeaderV4Deserializer(), new NullEventDataDeserializer(),
      eventDataDeserializers, tableMapEventByTableId);
}
 
Example #7
Source File: BonusManager.java    From pcgen with GNU Lesser General Public License v2.1 6 votes vote down vote up
private Map<BonusObj, Object> getTempBonuses()
{
	Map<BonusObj, Object> map = new IdentityHashMap<>();
	getFilteredTempBonusList().forEach((bonus, value) -> {
		pc.setApplied(bonus, false);

		Object source = value.source;
		CDOMObject cdomsource = (source instanceof CDOMObject) ? (CDOMObject) source : null;
		if (bonus.qualifies(pc, cdomsource))
		{
			pc.setApplied(bonus, true);
		}

		if (pc.isApplied(bonus))
		{
			map.put(bonus, source);
		}
	});
	return map;
}
 
Example #8
Source File: Capacity.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks that 4 methods of requiring capacity lead to the same
 * internal capacity, unless sized below default capacity.
 */
@Test(dataProvider = "sizes")
public void differentGrowthPatternsResultInSameCapacity(int size)
    throws Throwable {
    if (size < 21)          // 21 is default maxExpectedSize
        return;

    IdentityHashMap<Object,Object> m;
    m = new IdentityHashMap<Object,Object>(size);
    int capacity1 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingPut(m, size);
    int capacity2 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingPutAll(m, size);
    int capacity3 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingRepeatedPutAll(m, size);
    int capacity4 = capacity(m);

    if (capacity1 != capacity2 ||
        capacity2 != capacity3 ||
        capacity3 != capacity4)
        throw new AssertionError("Capacities not equal: "
                                 + capacity1 + " "
                                 + capacity2 + " "
                                 + capacity3 + " "
                                 + capacity4);
}
 
Example #9
Source File: CollectionUtils.java    From swellrt with Apache License 2.0 5 votes vote down vote up
/**
 * Adds all entries from the source map to the target map. NOTE(patcoleman):
 * please only call from assertions/testing code. Ideally everything should be
 * ignorant of the java.util.Map implementations as the collection API here
 * becomes more useful.
 *
 * @return java.util.Map version of our IdentityMap
 */
public static <K, V> Map<K, V> copyToJavaIdentityMapForTesting(IdentityMap<K, V> source) {
  final Map<K, V> result = new IdentityHashMap<K, V>();
  source.each(new IdentityMap.ProcV<K, V>() {
    @Override
    public void apply(K key, V value) {
      result.put(key, value);
    }
  });
  return result;
}
 
Example #10
Source File: ModifiableLocationTypeAdapter.java    From sis with Apache License 2.0 5 votes vote down vote up
/**
 * Returns type type as-is if it is already an instance of {@code ModifiableLocationType},
 * or returns a copy otherwise.
 */
static ModifiableLocationType copy(final AbstractLocationType type) {
    if (type instanceof ModifiableLocationType) {
        return (ModifiableLocationType) type;
    } else {
        return new ModifiableLocationTypeAdapter(type,
                new IdentityHashMap<AbstractLocationType,ModifiableLocationTypeAdapter>());
    }
}
 
Example #11
Source File: InternalThreadLocal.java    From Jupiter with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void addToVariablesToRemove(InternalThreadLocalMap threadLocalMap, InternalThreadLocal<?> variable) {
    Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex);
    Set<InternalThreadLocal<?>> variablesToRemove;
    if (v == InternalThreadLocalMap.UNSET || v == null) {
        variablesToRemove = Collections.newSetFromMap(new IdentityHashMap<>());
        threadLocalMap.setIndexedVariable(variablesToRemoveIndex, variablesToRemove);
    } else {
        variablesToRemove = (Set<InternalThreadLocal<?>>) v;
    }

    variablesToRemove.add(variable);
}
 
Example #12
Source File: ADag.java    From pegasus with Apache License 2.0 5 votes vote down vote up
/**
 * Checks the underlying graph structure for any corruption. Corruption can be where a parent or
 * a child of a node refers to an object, that is not in underlying graph node list.
 *
 * @throws RuntimeException in case of corruption.
 */
public void checkForCorruption() {
    Set<GraphNode> s = Collections.newSetFromMap(new IdentityHashMap());

    // put all the nodes in the idendity backed set
    for (Iterator<GraphNode> it = this.nodeIterator(); it.hasNext(); ) {
        s.add(it.next());
    }

    // now again traverse and make sure all the parents and children
    // of each node exist in the set
    for (Iterator<GraphNode> it = this.nodeIterator(); it.hasNext(); ) {
        GraphNode node = it.next();

        for (GraphNode parent : node.getParents()) {
            // contains operation is on basis of underlying IdentityHashMap
            if (!s.contains(parent)) {
                throw new RuntimeException(complain("Parent", node, parent));
            }
        }

        for (GraphNode child : node.getChildren()) {
            if (!s.contains(child)) {
                throw new RuntimeException(complain("Child", node, child));
            }
        }
    }
}
 
Example #13
Source File: EdgesBuilder.java    From astor with GNU General Public License v2.0 5 votes vote down vote up
/** Simple constructor.
 * @param root tree root
 * @param tolerance below which points are consider to be identical
 */
public EdgesBuilder(final BSPTree<Sphere2D> root, final double tolerance) {
    this.root            = root;
    this.tolerance       = tolerance;
    this.edgeToNode      = new IdentityHashMap<Edge, BSPTree<Sphere2D>>();
    this.nodeToEdgesList = new IdentityHashMap<BSPTree<Sphere2D>, List<Edge>>();
}
 
Example #14
Source File: Node.java    From gef with Eclipse Public License 2.0 5 votes vote down vote up
/**
 * Returns the local incoming {@link Edge}s of this {@link Node}. Only the
 * {@link #getGraph() associated graph} is scanned for incoming edges, and
 * not the whole graph hierarchy.
 *
 * @return The local incoming {@link Edge}s.
 */
public Set<Edge> getIncomingEdges() {
	if (graph == null) {
		return Collections.emptySet();
	}
	Set<Edge> incoming = Collections.newSetFromMap(new IdentityHashMap<Edge, Boolean>());
	for (Edge e : graph.getEdges()) {
		if (e.getTarget() == this) {
			incoming.add(e);
		}
	}
	return incoming;
}
 
Example #15
Source File: TestDefaultTcpServerMetrics.java    From servicecomb-java-chassis with Apache License 2.0 5 votes vote down vote up
@Test
public void createMetrics() {
  Map<Object, Object> instances = new IdentityHashMap<>();
  instances.put(metrics_listen1_server1, null);
  instances.put(metrics_listen1_server2, null);
  instances.put(metrics_listen2_server1, null);
  instances.put(metrics_listen2_server2, null);
  Assert.assertEquals(4, instances.size());

  Assert.assertSame(metrics_listen1_server1.getEndpointMetric(), metrics_listen1_server2.getEndpointMetric());
  Assert.assertNotSame(metrics_listen1_server1.getEndpointMetric(), metrics_listen2_server1.getEndpointMetric());
  Assert.assertSame(metrics_listen2_server1.getEndpointMetric(), metrics_listen2_server2.getEndpointMetric());
}
 
Example #16
Source File: GetBuilder.java    From NewsMe with Apache License 2.0 5 votes vote down vote up
@Override
public GetBuilder addParams(String key, String val)
{
    if (this.params == null)
    {
        params = new IdentityHashMap<>();
    }
    params.put(key, val);
    return this;
}
 
Example #17
Source File: OffHeapValidationJUnitTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void putIdentityHashMap(Region<Object, Object> region, List<ExpectedValues> expected) {
  String key = "keyIdentityHashMap";
  IdentityHashMap<Object,Object> value = new IdentityHashMap<Object,Object>();
  value.put("1", "string 1");
  value.put("2", "string 2");
  region.put(key, value);
  expected.add(new ExpectedValues(value, 40, "java.util.IdentityHashMap", -1, getMemoryAddress(region, key), 1, 0, false, true));
}
 
Example #18
Source File: FastThreadLocal.java    From netty-4.1.22 with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void addToVariablesToRemove(InternalThreadLocalMap threadLocalMap, FastThreadLocal<?> variable) {
    Object v = threadLocalMap.indexedVariable(variablesToRemoveIndex);
    Set<FastThreadLocal<?>> variablesToRemove;
    if (v == InternalThreadLocalMap.UNSET || v == null) {
        variablesToRemove = Collections.newSetFromMap(new IdentityHashMap<FastThreadLocal<?>, Boolean>());
        threadLocalMap.setIndexedVariable(variablesToRemoveIndex, variablesToRemove);
    } else {
        variablesToRemove = (Set<FastThreadLocal<?>>) v;
    }

    variablesToRemove.add(variable);
}
 
Example #19
Source File: ClusteredIndexablesCacheTest.java    From netbeans with Apache License 2.0 5 votes vote down vote up
private void globalPathRegistry_register(String id, ClassPath [] classpaths) {
    Map<ClassPath,Void> map = registeredClasspaths.get(id);
    if (map == null) {
        map = new IdentityHashMap<ClassPath, Void>();
        registeredClasspaths.put(id, map);
    }
    for (ClassPath cp :  classpaths) {
        map.put(cp,null);
    }
    GlobalPathRegistry.getDefault().register(id, classpaths);
}
 
Example #20
Source File: BonusManager.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<BonusObj, Object> getAllActiveBonuses()
{
	Map<BonusObj, Object> ret = new IdentityHashMap<>();
	for (final BonusContainer pobj : pc.getBonusContainerList())
	{
		// We exclude equipmods here as their bonuses are already counted in
		// the equipment they belong to.
		if (pobj != null && !(pobj instanceof EquipmentModifier))
		{
			boolean use = true;
			if (pobj instanceof PCClass)
			{
				// Class bonuses are only included if the level is greater
				// than 0
				// This is because 0 levels of a class can be added to
				// access spell casting etc
				use = pc.getLevel(((PCClass) pobj)) > 0;
			}
			if (use)
			{
				pobj.activateBonuses(pc);
				List<BonusObj> abs = pobj.getActiveBonuses(pc);
				for (BonusObj bo : abs)
				{
					ret.put(bo, pobj);
				}
			}
		}
	}

	if (pc.getUseTempMods())
	{
		ret.putAll(getTempBonuses());
	}
	return ret;
}
 
Example #21
Source File: TreeLayout.java    From treelayout with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Creates a TreeLayout for a given tree.
 * <p>
 * In addition to the tree the {@link NodeExtentProvider} and the
 * {@link Configuration} must be given.
 * 
    * @param tree &nbsp;
    * @param nodeExtentProvider &nbsp;
    * @param configuration &nbsp;
    * @param useIdentity
 *            [default: false] when true, identity ("==") is used instead of
 *            equality ("equals(...)") when checking nodes. Within a tree
 *            each node must only exist once (using this check).
 */
public TreeLayout(TreeForTreeLayout<TreeNode> tree,
		NodeExtentProvider<TreeNode> nodeExtentProvider,
		Configuration<TreeNode> configuration, boolean useIdentity) {
	this.tree = tree;
	this.nodeExtentProvider = nodeExtentProvider;
	this.configuration = configuration;
	this.useIdentity = useIdentity;

	if (this.useIdentity) {
		this.mod = new IdentityHashMap<TreeNode, Double>();
		this.thread = new IdentityHashMap<TreeNode, TreeNode>();
		this.prelim = new IdentityHashMap<TreeNode, Double>();
		this.change = new IdentityHashMap<TreeNode, Double>();
		this.shift = new IdentityHashMap<TreeNode, Double>();
		this.ancestor = new IdentityHashMap<TreeNode, TreeNode>();
		this.number = new IdentityHashMap<TreeNode, Integer>();
		this.positions = new IdentityHashMap<TreeNode, Point2D>();
	} else {
		this.mod = new HashMap<TreeNode, Double>();
		this.thread = new HashMap<TreeNode, TreeNode>();
		this.prelim = new HashMap<TreeNode, Double>();
		this.change = new HashMap<TreeNode, Double>();
		this.shift = new HashMap<TreeNode, Double>();
		this.ancestor = new HashMap<TreeNode, TreeNode>();
		this.number = new HashMap<TreeNode, Integer>();
		this.positions = new HashMap<TreeNode, Point2D>();
	}
	
	// No need to explicitly set mod, thread and ancestor as their getters
	// are taking care of the initial values. This avoids a full tree walk
	// through and saves some memory as no entries are added for
	// "initial values".

	TreeNode r = tree.getRoot();
	firstWalk(r, null);
	calcSizeOfLevels(r, 0);
	secondWalk(r, -getPrelim(r), 0, 0);
}
 
Example #22
Source File: ClassUtils.java    From quarkus-http with Apache License 2.0 5 votes vote down vote up
/**
 * Returns a map of all supported message types by the given handler class.
 * The key of the map is the supported message type; the value indicates
 * whether it is a partial message handler or not.
 *
 * @return a map of all supported message types by the given handler class.
 */
public static Map<Class<?>, Boolean> getHandlerTypes(Class<? extends MessageHandler> clazz) {
    Map<Class<?>, Boolean> types = new IdentityHashMap<>(2);
    for (Class<?> c = clazz; c != Object.class; c = c.getSuperclass()) {
        exampleGenericInterfaces(types, c, clazz);
    }
    if (types.isEmpty()) {
        throw JsrWebSocketMessages.MESSAGES.unknownHandlerType(clazz);
    }
    return types;
}
 
Example #23
Source File: Capacity.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
static int capacity(IdentityHashMap<?,?> map) {
    try {
        return ((Object[]) tableField.get(map)).length / 2;
    } catch (Throwable t) {
        throw new LinkageError("table", t);
    }
}
 
Example #24
Source File: BonusManager.java    From pcgen with GNU Lesser General Public License v2.1 5 votes vote down vote up
private Map<BonusObj, TempBonusInfo> getFilteredTempBonusList()
{
	final Map<BonusObj, TempBonusInfo> ret = new IdentityHashMap<>();
	for (Map.Entry<BonusObj, TempBonusInfo> me : tempBonusBySource.entrySet())
	{
		BonusObj bonus = me.getKey();
		TempBonusInfo ti = me.getValue();
		if (!tempBonusFilters.contains(BonusDisplay.getBonusDisplayName(ti)))
		{
			ret.put(bonus, ti);
		}
	}
	return ret;
}
 
Example #25
Source File: PostFormBuilder.java    From NewsMe with Apache License 2.0 5 votes vote down vote up
@Override
public PostFormBuilder addHeader(String key, String val)
{
    if (this.headers == null)
    {
        headers = new IdentityHashMap<>();
    }
    headers.put(key, val);
    return this;
}
 
Example #26
Source File: HlsMediaPeriod.java    From Telegram-FOSS with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Creates an HLS media period.
 *
 * @param extractorFactory An {@link HlsExtractorFactory} for {@link Extractor}s for the segments.
 * @param playlistTracker A tracker for HLS playlists.
 * @param dataSourceFactory An {@link HlsDataSourceFactory} for {@link DataSource}s for segments
 *     and keys.
 * @param mediaTransferListener The transfer listener to inform of any media data transfers. May
 *     be null if no listener is available.
 * @param loadErrorHandlingPolicy A {@link LoadErrorHandlingPolicy}.
 * @param eventDispatcher A dispatcher to notify of events.
 * @param allocator An {@link Allocator} from which to obtain media buffer allocations.
 * @param compositeSequenceableLoaderFactory A factory to create composite {@link
 *     SequenceableLoader}s for when this media source loads data from multiple streams.
 * @param allowChunklessPreparation Whether chunkless preparation is allowed.
 * @param useSessionKeys Whether to use #EXT-X-SESSION-KEY tags.
 */
public HlsMediaPeriod(
    HlsExtractorFactory extractorFactory,
    HlsPlaylistTracker playlistTracker,
    HlsDataSourceFactory dataSourceFactory,
    @Nullable TransferListener mediaTransferListener,
    LoadErrorHandlingPolicy loadErrorHandlingPolicy,
    EventDispatcher eventDispatcher,
    Allocator allocator,
    CompositeSequenceableLoaderFactory compositeSequenceableLoaderFactory,
    boolean allowChunklessPreparation,
    @HlsMetadataType int metadataType,
    boolean useSessionKeys) {
  this.extractorFactory = extractorFactory;
  this.playlistTracker = playlistTracker;
  this.dataSourceFactory = dataSourceFactory;
  this.mediaTransferListener = mediaTransferListener;
  this.loadErrorHandlingPolicy = loadErrorHandlingPolicy;
  this.eventDispatcher = eventDispatcher;
  this.allocator = allocator;
  this.compositeSequenceableLoaderFactory = compositeSequenceableLoaderFactory;
  this.allowChunklessPreparation = allowChunklessPreparation;
  this.metadataType = metadataType;
  this.useSessionKeys = useSessionKeys;
  compositeSequenceableLoader =
      compositeSequenceableLoaderFactory.createCompositeSequenceableLoader();
  streamWrapperIndices = new IdentityHashMap<>();
  timestampAdjusterProvider = new TimestampAdjusterProvider();
  sampleStreamWrappers = new HlsSampleStreamWrapper[0];
  enabledSampleStreamWrappers = new HlsSampleStreamWrapper[0];
  manifestUrlIndicesPerWrapper = new int[0][];
  eventDispatcher.mediaPeriodCreated();
}
 
Example #27
Source File: ASTRewriteAnalyzer.java    From Eclipse-Postfix-Code-Completion with Eclipse Public License 1.0 5 votes vote down vote up
/**
 * Constructor for ASTRewriteAnalyzer.
 * <p>The given options cannot be null.</p>
 * 
 * @param content the content of the compilation unit to rewrite.
 * @param lineInfo line information for the content of the compilation unit to rewrite.
 * @param rootEdit the edit to add all generated edits to
 * @param eventStore the event store containing the description of changes
 * @param nodeInfos annotations to nodes, such as if a node is a string placeholder or a copy target
 * @param comments list of comments of the compilation unit to rewrite (elements of type <code>Comment</code>) or <code>null</code>.
 * @param options the current jdt.core options (formatting/compliance)
 * @param extendedSourceRangeComputer the source range computer to use
 * @param recoveryScannerData internal data used by {@link RecoveryScanner}
 */
public ASTRewriteAnalyzer(
		char[] content,
		LineInformation lineInfo,
		String lineDelim,
		TextEdit rootEdit,
		RewriteEventStore eventStore,
		NodeInfoStore nodeInfos,
		List comments,
		Map options,
		TargetSourceRangeComputer extendedSourceRangeComputer,
		RecoveryScannerData recoveryScannerData) {
	this.eventStore= eventStore;
	this.content= content;
	this.lineInfo= lineInfo;
	this.nodeInfos= nodeInfos;
	this.tokenScanner= null;
	this.currentEdit= rootEdit;
	this.sourceCopyInfoToEdit= new IdentityHashMap();
	this.sourceCopyEndNodes= new Stack();

	this.formatter= new ASTRewriteFormatter(nodeInfos, eventStore, options, lineDelim);

	this.extendedSourceRangeComputer = extendedSourceRangeComputer;
	this.lineCommentEndOffsets= new LineCommentEndOffsets(comments);
	
	this.options = options;
	
	this.recoveryScannerData = recoveryScannerData;
}
 
Example #28
Source File: OffHeapMapTest.java    From gadtry with Apache License 2.0 5 votes vote down vote up
@Test
public void putAllTest()
{
    final Map<String, Integer> offHeapMap = new OffHeapMap<>(
            (Integer str) -> String.valueOf(str).getBytes(UTF_8),
            (byte[] bytes) -> Integer.valueOf(new String(bytes, UTF_8)),
            IdentityHashMap::new
    );
    Map<String, Integer> integerMap = MutableMap.of("a1", 123);
    offHeapMap.putAll(integerMap);

    Assert.assertEquals(offHeapMap, integerMap);
}
 
Example #29
Source File: Capacity.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Checks that 4 methods of requiring capacity lead to the same
 * internal capacity, unless sized below default capacity.
 */
@Test(dataProvider = "sizes")
public void differentGrowthPatternsResultInSameCapacity(int size)
    throws Throwable {
    if (size < 21)          // 21 is default maxExpectedSize
        return;

    IdentityHashMap<Object,Object> m;
    m = new IdentityHashMap<Object,Object>(size);
    int capacity1 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingPut(m, size);
    int capacity2 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingPutAll(m, size);
    int capacity3 = capacity(m);

    m = new IdentityHashMap<>();
    growUsingRepeatedPutAll(m, size);
    int capacity4 = capacity(m);

    if (capacity1 != capacity2 ||
        capacity2 != capacity3 ||
        capacity3 != capacity4)
        throw new AssertionError("Capacities not equal: "
                                 + capacity1 + " "
                                 + capacity2 + " "
                                 + capacity3 + " "
                                 + capacity4);
}
 
Example #30
Source File: Translator.java    From kodkod with MIT License 5 votes vote down vote up
/**
 * Returns an annotated formula f such that f.node is equivalent to annotated.node
 * with its <tt>simplified</tt> predicates replaced with their corresponding Formulas and the remaining
 * predicates replaced with equivalent constraints.  The annotated formula f will contain transitive source 
 * information for each of the subformulas of f.node.  Specifically, let t be a subformula of f.node, and
 * s be a descdendent of annotated.node from which t was derived.  Then, f.source[t] = annotated.source[s]. </p>
 * @requires simplified.keySet() in annotated.predicates()[RelationPredicate.NAME]
 * @requires no disj p, p': simplified.keySet() | simplified.get(p) = simplified.get(p') // this must hold in order
 * to maintain the invariant that each subformula of the returned formula has exactly one source
 * @requires for each p in simplified.keySet(), the formulas "p and [[this.bounds]]" and
 * "simplified.get(p) and [[this.bounds]]" are equisatisfiable
 * @return an annotated formula f such that f.node is equivalent to annotated.node
 * with its <tt>simplified</tt> predicates replaced with their corresponding Formulas and the remaining
 * predicates replaced with equivalent constraints.
 */
private AnnotatedNode<Formula> inlinePredicates(final AnnotatedNode<Formula> annotated, final Map<RelationPredicate,Formula> simplified) {
	final Map<Node,Node> sources = new IdentityHashMap<Node,Node>();
	final AbstractReplacer inliner = new AbstractReplacer(annotated.sharedNodes()) {
		private RelationPredicate source =  null;			
		protected <N extends Node> N cache(N node, N replacement) {
			if (replacement instanceof Formula) {
				if (source==null) {
					final Node nsource = annotated.sourceOf(node);
					if (replacement!=nsource) 
						sources.put(replacement, nsource);
				} else {
					sources.put(replacement, source);
				}
			}
			return super.cache(node, replacement);
		}
		public Formula visit(RelationPredicate pred) {
			Formula ret = lookup(pred);
			if (ret!=null) return ret;
			source = pred;
			if (simplified.containsKey(pred)) {
				ret = simplified.get(pred).accept(this);
			} else {
				ret = pred.toConstraints().accept(this);
			}
			source = null;
			return cache(pred, ret);
		}
	};

	return annotate(annotated.node().accept(inliner), sources);
}