RobotCore 1.0
WPILib port to raspberry Pi
Loading...
Searching...
No Matches
CombinatoryUnitCache.java
1// Copyright (c) FIRST and other WPILib contributors.
2// Open Source Software; you can modify and/or share it under the terms of
3// the WPILib BSD license file in the root directory of this project.
4
5package org.wpilib.units;
6
7import java.util.Objects;
8import java.util.function.BiFunction;
9import org.wpilib.units.collections.LongToObjectHashMap;
10
19public final class CombinatoryUnitCache<A extends Unit, B extends Unit, Out extends Unit> {
24 private final LongToObjectHashMap<Out> m_cache = new LongToObjectHashMap<>();
25
26 private final BiFunction<? super A, ? super B, ? extends Out> m_constructor;
27
34 public CombinatoryUnitCache(BiFunction<? super A, ? super B, ? extends Out> constructor) {
35 this.m_constructor =
36 Objects.requireNonNull(constructor, "Cache unit constructor must be provided");
37 }
38
48 public Out combine(A a, B b) {
49 final long key = ((long) a.hashCode()) << 32L | (b.hashCode() & 0xFFFFFFFFL);
50
51 var existing = m_cache.get(key);
52 if (existing != null) {
53 return existing;
54 }
55
56 var newUnit = m_constructor.apply(a, b);
57 m_cache.put(key, newUnit);
58 return newUnit;
59 }
60}
CombinatoryUnitCache(BiFunction<? super A, ? super B, ? extends Out > constructor)