code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import java.util.concurrent.Future; /** * Transforms a value, possibly asynchronously. For an example usage and more * information, see {@link Futures#transform(ListenableFuture, AsyncFunction)}. * * @author Chris Povirk * @since 11.0 */ public interface AsyncFunction<I, O> { /** * Returns an output {@code Future} to use in place of the given {@code * input}. The output {@code Future} need not be {@linkplain Future#isDone * done}, making {@code AsyncFunction} suitable for asynchronous derivations. * * <p>Throwing an exception from this method is equivalent to returning a * failing {@code Future}. */ ListenableFuture<O> apply(I input) throws Exception; }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/AsyncFunction.java
Java
asf20
1,340
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import java.util.concurrent.Executor; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; /** * <p>A list of listeners, each with an associated {@code Executor}, that * guarantees that every {@code Runnable} that is {@linkplain #add added} will * be executed after {@link #execute()} is called. Any {@code Runnable} added * after the call to {@code execute} is still guaranteed to execute. There is no * guarantee, however, that listeners will be executed in the order that they * are added. * * <p>Exceptions thrown by a listener will be propagated up to the executor. * Any exception thrown during {@code Executor.execute} (e.g., a {@code * RejectedExecutionException} or an exception thrown by {@linkplain * MoreExecutors#sameThreadExecutor inline execution}) will be caught and * logged. * * @author Nishant Thakkar * @author Sven Mawson * @since 1.0 */ public final class ExecutionList { // Logger to log exceptions caught when running runnables. @VisibleForTesting static final Logger log = Logger.getLogger(ExecutionList.class.getName()); /** * The runnable, executor pairs to execute. This acts as a stack threaded through the * {@link RunnableExecutorPair#next} field. */ @GuardedBy("this") private RunnableExecutorPair runnables; @GuardedBy("this") private boolean executed; /** Creates a new, empty {@link ExecutionList}. */ public ExecutionList() {} /** * Adds the {@code Runnable} and accompanying {@code Executor} to the list of * listeners to execute. If execution has already begun, the listener is * executed immediately. * * <p>Note: For fast, lightweight listeners that would be safe to execute in * any thread, consider {@link MoreExecutors#sameThreadExecutor}. For heavier * listeners, {@code sameThreadExecutor()} carries some caveats: First, the * thread that the listener runs in depends on whether the {@code * ExecutionList} has been executed at the time it is added. In particular, * listeners may run in the thread that calls {@code add}. Second, the thread * that calls {@link #execute} may be an internal implementation thread, such * as an RPC network thread, and {@code sameThreadExecutor()} listeners may * run in this thread. Finally, during the execution of a {@code * sameThreadExecutor} listener, all other registered but unexecuted * listeners are prevented from running, even if those listeners are to run * in other executors. */ public void add(Runnable runnable, Executor executor) { // Fail fast on a null. We throw NPE here because the contract of // Executor states that it throws NPE on null listener, so we propagate // that contract up into the add method as well. Preconditions.checkNotNull(runnable, "Runnable was null."); Preconditions.checkNotNull(executor, "Executor was null."); // Lock while we check state. We must maintain the lock while adding the // new pair so that another thread can't run the list out from under us. // We only add to the list if we have not yet started execution. synchronized (this) { if (!executed) { runnables = new RunnableExecutorPair(runnable, executor, runnables); return; } } // Execute the runnable immediately. Because of scheduling this may end up // getting called before some of the previously added runnables, but we're // OK with that. If we want to change the contract to guarantee ordering // among runnables we'd have to modify the logic here to allow it. executeListener(runnable, executor); } /** * Runs this execution list, executing all existing pairs in the order they * were added. However, note that listeners added after this point may be * executed before those previously added, and note that the execution order * of all listeners is ultimately chosen by the implementations of the * supplied executors. * * <p>This method is idempotent. Calling it several times in parallel is * semantically equivalent to calling it exactly once. * * @since 10.0 (present in 1.0 as {@code run}) */ public void execute() { // Lock while we update our state so the add method above will finish adding // any listeners before we start to run them. RunnableExecutorPair list; synchronized (this) { if (executed) { return; } executed = true; list = runnables; runnables = null; // allow GC to free listeners even if this stays around for a while. } // If we succeeded then list holds all the runnables we to execute. The pairs in the stack are // in the opposite order from how they were added so we need to reverse the list to fulfill our // contract. // This is somewhat annoying, but turns out to be very fast in practice. Alternatively, we // could drop the contract on the method that enforces this queue like behavior since depending // on it is likely to be a bug anyway. // N.B. All writes to the list and the next pointers must have happened before the above // synchronized block, so we can iterate the list without the lock held here. RunnableExecutorPair reversedList = null; while (list != null) { RunnableExecutorPair tmp = list; list = list.next; tmp.next = reversedList; reversedList = tmp; } while (reversedList != null) { executeListener(reversedList.runnable, reversedList.executor); reversedList = reversedList.next; } } /** * Submits the given runnable to the given {@link Executor} catching and logging all * {@linkplain RuntimeException runtime exceptions} thrown by the executor. */ private static void executeListener(Runnable runnable, Executor executor) { try { executor.execute(runnable); } catch (RuntimeException e) { // Log it and keep going, bad runnable and/or executor. Don't // punish the other runnables if we're given a bad one. We only // catch RuntimeException because we want Errors to propagate up. log.log(Level.SEVERE, "RuntimeException while executing runnable " + runnable + " with executor " + executor, e); } } private static final class RunnableExecutorPair { final Runnable runnable; final Executor executor; @Nullable RunnableExecutorPair next; RunnableExecutorPair(Runnable runnable, Executor executor, RunnableExecutorPair next) { this.runnable = runnable; this.executor = executor; this.next = next; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/ExecutionList.java
Java
asf20
7,400
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; /** * Produces proxies that impose a time limit on method * calls to the proxied object. For example, to return the value of * {@code target.someMethod()}, but substitute {@code DEFAULT_VALUE} if this * method call takes over 50 ms, you can use this code: * <pre> * TimeLimiter limiter = . . .; * TargetType proxy = limiter.newProxy( * target, TargetType.class, 50, TimeUnit.MILLISECONDS); * try { * return proxy.someMethod(); * } catch (UncheckedTimeoutException e) { * return DEFAULT_VALUE; * } * </pre> * <p>Please see {@code SimpleTimeLimiterTest} for more usage examples. * * @author Kevin Bourrillion * @since 1.0 */ @Beta public interface TimeLimiter { /** * Returns an instance of {@code interfaceType} that delegates all method * calls to the {@code target} object, enforcing the specified time limit on * each call. This time-limited delegation is also performed for calls to * {@link Object#equals}, {@link Object#hashCode}, and * {@link Object#toString}. * <p> * If the target method call finishes before the limit is reached, the return * value or exception is propagated to the caller exactly as-is. If, on the * other hand, the time limit is reached, the proxy will attempt to abort the * call to the target, and will throw an {@link UncheckedTimeoutException} to * the caller. * <p> * It is important to note that the primary purpose of the proxy object is to * return control to the caller when the timeout elapses; aborting the target * method call is of secondary concern. The particular nature and strength * of the guarantees made by the proxy is implementation-dependent. However, * it is important that each of the methods on the target object behaves * appropriately when its thread is interrupted. * * @param target the object to proxy * @param interfaceType the interface you wish the returned proxy to * implement * @param timeoutDuration with timeoutUnit, the maximum length of time that * callers are willing to wait on each method call to the proxy * @param timeoutUnit with timeoutDuration, the maximum length of time that * callers are willing to wait on each method call to the proxy * @return a time-limiting proxy * @throws IllegalArgumentException if {@code interfaceType} is a regular * class, enum, or annotation type, rather than an interface */ <T> T newProxy(T target, Class<T> interfaceType, long timeoutDuration, TimeUnit timeoutUnit); /** * Invokes a specified Callable, timing out after the specified time limit. * If the target method call finished before the limit is reached, the return * value or exception is propagated to the caller exactly as-is. If, on the * other hand, the time limit is reached, we attempt to abort the call to the * target, and throw an {@link UncheckedTimeoutException} to the caller. * <p> * <b>Warning:</b> The future of this method is in doubt. It may be nuked, or * changed significantly. * * @param callable the Callable to execute * @param timeoutDuration with timeoutUnit, the maximum length of time to wait * @param timeoutUnit with timeoutDuration, the maximum length of time to wait * @param interruptible whether to respond to thread interruption by aborting * the operation and throwing InterruptedException; if false, the * operation is allowed to complete or time out, and the current thread's * interrupt status is re-asserted. * @return the result returned by the Callable * @throws InterruptedException if {@code interruptible} is true and our * thread is interrupted during execution * @throws UncheckedTimeoutException if the time limit is reached * @throws Exception */ <T> T callWithTimeout(Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean interruptible) throws Exception; }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/TimeLimiter.java
Java
asf20
4,721
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import com.google.common.base.Supplier; import com.google.common.base.Throwables; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.logging.Level; import java.util.logging.Logger; /** * Base class for services that can implement {@link #startUp}, {@link #run} and * {@link #shutDown} methods. This class uses a single thread to execute the * service; consider {@link AbstractService} if you would like to manage any * threading manually. * * @author Jesse Wilson * @since 1.0 */ @Beta public abstract class AbstractExecutionThreadService implements Service { private static final Logger logger = Logger.getLogger( AbstractExecutionThreadService.class.getName()); /* use AbstractService for state management */ private final Service delegate = new AbstractService() { @Override protected final void doStart() { Executor executor = MoreExecutors.renamingDecorator(executor(), new Supplier<String>() { @Override public String get() { return serviceName(); } }); executor.execute(new Runnable() { @Override public void run() { try { startUp(); notifyStarted(); if (isRunning()) { try { AbstractExecutionThreadService.this.run(); } catch (Throwable t) { try { shutDown(); } catch (Exception ignored) { logger.log(Level.WARNING, "Error while attempting to shut down the service" + " after failure.", ignored); } throw t; } } shutDown(); notifyStopped(); } catch (Throwable t) { notifyFailed(t); throw Throwables.propagate(t); } } }); } @Override protected void doStop() { triggerShutdown(); } }; /** * Constructor for use by subclasses. */ protected AbstractExecutionThreadService() {} /** * Start the service. This method is invoked on the execution thread. * * <p>By default this method does nothing. */ protected void startUp() throws Exception {} /** * Run the service. This method is invoked on the execution thread. * Implementations must respond to stop requests. You could poll for lifecycle * changes in a work loop: * <pre> * public void run() { * while ({@link #isRunning()}) { * // perform a unit of work * } * } * </pre> * ...or you could respond to stop requests by implementing {@link * #triggerShutdown()}, which should cause {@link #run()} to return. */ protected abstract void run() throws Exception; /** * Stop the service. This method is invoked on the execution thread. * * <p>By default this method does nothing. */ // TODO: consider supporting a TearDownTestCase-like API protected void shutDown() throws Exception {} /** * Invoked to request the service to stop. * * <p>By default this method does nothing. */ protected void triggerShutdown() {} /** * Returns the {@link Executor} that will be used to run this service. * Subclasses may override this method to use a custom {@link Executor}, which * may configure its worker thread with a specific name, thread group or * priority. The returned executor's {@link Executor#execute(Runnable) * execute()} method is called when this service is started, and should return * promptly. * * <p>The default implementation returns a new {@link Executor} that sets the * name of its threads to the string returned by {@link #serviceName} */ protected Executor executor() { return new Executor() { @Override public void execute(Runnable command) { MoreExecutors.newThread(serviceName(), command).start(); } }; } @Override public String toString() { return serviceName() + " [" + state() + "]"; } @Override public final boolean isRunning() { return delegate.isRunning(); } @Override public final State state() { return delegate.state(); } /** * @since 13.0 */ @Override public final void addListener(Listener listener, Executor executor) { delegate.addListener(listener, executor); } /** * @since 14.0 */ @Override public final Throwable failureCause() { return delegate.failureCause(); } /** * @since 15.0 */ @Override public final Service startAsync() { delegate.startAsync(); return this; } /** * @since 15.0 */ @Override public final Service stopAsync() { delegate.stopAsync(); return this; } /** * @since 15.0 */ @Override public final void awaitRunning() { delegate.awaitRunning(); } /** * @since 15.0 */ @Override public final void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException { delegate.awaitRunning(timeout, unit); } /** * @since 15.0 */ @Override public final void awaitTerminated() { delegate.awaitTerminated(); } /** * @since 15.0 */ @Override public final void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException { delegate.awaitTerminated(timeout, unit); } /** * Returns the name of this service. {@link AbstractExecutionThreadService} * may include the name in debugging output. * * <p>Subclasses may override this method. * * @since 14.0 (present in 10.0 as getServiceName) */ protected String serviceName() { return getClass().getSimpleName(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/AbstractExecutionThreadService.java
Java
asf20
6,413
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static java.util.logging.Level.SEVERE; import com.google.common.annotations.VisibleForTesting; import java.lang.Thread.UncaughtExceptionHandler; import java.util.logging.Logger; /** * Factories for {@link UncaughtExceptionHandler} instances. * * @author Gregory Kick * @since 8.0 */ public final class UncaughtExceptionHandlers { private UncaughtExceptionHandlers() {} /** * Returns an exception handler that exits the system. This is particularly useful for the main * thread, which may start up other, non-daemon threads, but fail to fully initialize the * application successfully. * * <p>Example usage: * <pre>public static void main(String[] args) { * Thread.currentThread().setUncaughtExceptionHandler(UncaughtExceptionHandlers.systemExit()); * ... * </pre> * * <p>The returned handler logs any exception at severity {@code SEVERE} and then shuts down the * process with an exit status of 1, indicating abnormal termination. */ public static UncaughtExceptionHandler systemExit() { return new Exiter(Runtime.getRuntime()); } @VisibleForTesting static final class Exiter implements UncaughtExceptionHandler { private static final Logger logger = Logger.getLogger(Exiter.class.getName()); private final Runtime runtime; Exiter(Runtime runtime) { this.runtime = runtime; } @Override public void uncaughtException(Thread t, Throwable e) { try { // cannot use FormattingLogger due to a dependency loop logger.log(SEVERE, String.format("Caught an exception in %s. Shutting down.", t), e); } catch (Throwable errorInLogging) { // If logging fails, e.g. due to missing memory, at least try to log the // message and the cause for the failed logging. System.err.println(e.getMessage()); System.err.println(errorInLogging.getMessage()); } finally { runtime.exit(1); } } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/UncaughtExceptionHandlers.java
Java
asf20
2,606
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.GwtCompatible; import javax.annotation.Nullable; /** * Unchecked variant of {@link java.util.concurrent.ExecutionException}. As with * {@code ExecutionException}, the exception's {@linkplain #getCause() cause} * comes from a failed task, possibly run in another thread. * * <p>{@code UncheckedExecutionException} is intended as an alternative to * {@code ExecutionException} when the exception thrown by a task is an * unchecked exception. However, it may also wrap a checked exception in some * cases. * * <p>When wrapping an {@code Error} from another thread, prefer {@link * ExecutionError}. When wrapping a checked exception, prefer {@code * ExecutionException}. * * @author Charles Fry * @since 10.0 */ @GwtCompatible public class UncheckedExecutionException extends RuntimeException { /** * Creates a new instance with {@code null} as its detail message. */ protected UncheckedExecutionException() {} /** * Creates a new instance with the given detail message. */ protected UncheckedExecutionException(@Nullable String message) { super(message); } /** * Creates a new instance with the given detail message and cause. */ public UncheckedExecutionException(@Nullable String message, @Nullable Throwable cause) { super(message, cause); } /** * Creates a new instance with the given cause. */ public UncheckedExecutionException(@Nullable Throwable cause) { super(cause); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/UncheckedExecutionException.java
Java
asf20
2,191
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.collect.ForwardingQueue; import java.util.Collection; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; /** * A {@link BlockingQueue} which forwards all its method calls to another * {@link BlockingQueue}. Subclasses should override one or more methods to * modify the behavior of the backing collection as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Raimundo Mirisola * * @param <E> the type of elements held in this collection * @since 4.0 */ public abstract class ForwardingBlockingQueue<E> extends ForwardingQueue<E> implements BlockingQueue<E> { /** Constructor for use by subclasses. */ protected ForwardingBlockingQueue() {} @Override protected abstract BlockingQueue<E> delegate(); @Override public int drainTo( Collection<? super E> c, int maxElements) { return delegate().drainTo(c, maxElements); } @Override public int drainTo(Collection<? super E> c) { return delegate().drainTo(c); } @Override public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { return delegate().offer(e, timeout, unit); } @Override public E poll(long timeout, TimeUnit unit) throws InterruptedException { return delegate().poll(timeout, unit); } @Override public void put(E e) throws InterruptedException { delegate().put(e); } @Override public int remainingCapacity() { return delegate().remainingCapacity(); } @Override public E take() throws InterruptedException { return delegate().take(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/ForwardingBlockingQueue.java
Java
asf20
2,286
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import com.google.common.base.Supplier; import com.google.common.base.Throwables; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Base class for services that do not need a thread while "running" * but may need one during startup and shutdown. Subclasses can * implement {@link #startUp} and {@link #shutDown} methods, each * which run in a executor which by default uses a separate thread * for each method. * * @author Chris Nokleberg * @since 1.0 */ @Beta public abstract class AbstractIdleService implements Service { /* Thread names will look like {@code "MyService STARTING"}. */ private final Supplier<String> threadNameSupplier = new Supplier<String>() { @Override public String get() { return serviceName() + " " + state(); } }; /* use AbstractService for state management */ private final Service delegate = new AbstractService() { @Override protected final void doStart() { MoreExecutors.renamingDecorator(executor(), threadNameSupplier) .execute(new Runnable() { @Override public void run() { try { startUp(); notifyStarted(); } catch (Throwable t) { notifyFailed(t); throw Throwables.propagate(t); } } }); } @Override protected final void doStop() { MoreExecutors.renamingDecorator(executor(), threadNameSupplier) .execute(new Runnable() { @Override public void run() { try { shutDown(); notifyStopped(); } catch (Throwable t) { notifyFailed(t); throw Throwables.propagate(t); } } }); } }; /** Constructor for use by subclasses. */ protected AbstractIdleService() {} /** Start the service. */ protected abstract void startUp() throws Exception; /** Stop the service. */ protected abstract void shutDown() throws Exception; /** * Returns the {@link Executor} that will be used to run this service. * Subclasses may override this method to use a custom {@link Executor}, which * may configure its worker thread with a specific name, thread group or * priority. The returned executor's {@link Executor#execute(Runnable) * execute()} method is called when this service is started and stopped, * and should return promptly. */ protected Executor executor() { return new Executor() { @Override public void execute(Runnable command) { MoreExecutors.newThread(threadNameSupplier.get(), command).start(); } }; } @Override public String toString() { return serviceName() + " [" + state() + "]"; } @Override public final boolean isRunning() { return delegate.isRunning(); } @Override public final State state() { return delegate.state(); } /** * @since 13.0 */ @Override public final void addListener(Listener listener, Executor executor) { delegate.addListener(listener, executor); } /** * @since 14.0 */ @Override public final Throwable failureCause() { return delegate.failureCause(); } /** * @since 15.0 */ @Override public final Service startAsync() { delegate.startAsync(); return this; } /** * @since 15.0 */ @Override public final Service stopAsync() { delegate.stopAsync(); return this; } /** * @since 15.0 */ @Override public final void awaitRunning() { delegate.awaitRunning(); } /** * @since 15.0 */ @Override public final void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException { delegate.awaitRunning(timeout, unit); } /** * @since 15.0 */ @Override public final void awaitTerminated() { delegate.awaitTerminated(); } /** * @since 15.0 */ @Override public final void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException { delegate.awaitTerminated(timeout, unit); } /** * Returns the name of this service. {@link AbstractIdleService} may include the name in debugging * output. * * @since 14.0 */ protected String serviceName() { return getClass().getSimpleName(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/AbstractIdleService.java
Java
asf20
5,036
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import java.util.concurrent.Callable; import java.util.concurrent.TimeUnit; /** * A TimeLimiter implementation which actually does not attempt to limit time * at all. This may be desirable to use in some unit tests. More importantly, * attempting to debug a call which is time-limited would be extremely annoying, * so this gives you a time-limiter you can easily swap in for your real * time-limiter while you're debugging. * * @author Kevin Bourrillion * @since 1.0 */ @Beta public final class FakeTimeLimiter implements TimeLimiter { @Override public <T> T newProxy(T target, Class<T> interfaceType, long timeoutDuration, TimeUnit timeoutUnit) { checkNotNull(target); checkNotNull(interfaceType); checkNotNull(timeoutUnit); return target; // ha ha } @Override public <T> T callWithTimeout(Callable<T> callable, long timeoutDuration, TimeUnit timeoutUnit, boolean amInterruptible) throws Exception { checkNotNull(timeoutUnit); return callable.call(); // fooled you } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/FakeTimeLimiter.java
Java
asf20
1,788
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.base.Preconditions; import java.util.concurrent.Executor; /** * A {@link ListenableFuture} which forwards all its method calls to another * future. Subclasses should override one or more methods to modify the behavior * of the backing future as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p>Most subclasses can just use {@link SimpleForwardingListenableFuture}. * * @param <V> The result type returned by this Future's {@code get} method * * @author Shardul Deo * @since 4.0 */ public abstract class ForwardingListenableFuture<V> extends ForwardingFuture<V> implements ListenableFuture<V> { /** Constructor for use by subclasses. */ protected ForwardingListenableFuture() {} @Override protected abstract ListenableFuture<V> delegate(); @Override public void addListener(Runnable listener, Executor exec) { delegate().addListener(listener, exec); } /* * TODO(cpovirk): Use standard Javadoc form for SimpleForwarding* class and * constructor */ /** * A simplified version of {@link ForwardingListenableFuture} where subclasses * can pass in an already constructed {@link ListenableFuture} * as the delegate. * * @since 9.0 */ public abstract static class SimpleForwardingListenableFuture<V> extends ForwardingListenableFuture<V> { private final ListenableFuture<V> delegate; protected SimpleForwardingListenableFuture(ListenableFuture<V> delegate) { this.delegate = Preconditions.checkNotNull(delegate); } @Override protected final ListenableFuture<V> delegate() { return delegate; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/ForwardingListenableFuture.java
Java
asf20
2,338
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.base.Throwables; import java.util.concurrent.Callable; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.concurrent.GuardedBy; /** * Base class for services that can implement {@link #startUp} and {@link #shutDown} but while in * the "running" state need to perform a periodic task. Subclasses can implement {@link #startUp}, * {@link #shutDown} and also a {@link #runOneIteration} method that will be executed periodically. * * <p>This class uses the {@link ScheduledExecutorService} returned from {@link #executor} to run * the {@link #startUp} and {@link #shutDown} methods and also uses that service to schedule the * {@link #runOneIteration} that will be executed periodically as specified by its * {@link Scheduler}. When this service is asked to stop via {@link #stopAsync} it will cancel the * periodic task (but not interrupt it) and wait for it to stop before running the * {@link #shutDown} method. * * <p>Subclasses are guaranteed that the life cycle methods ({@link #runOneIteration}, {@link * #startUp} and {@link #shutDown}) will never run concurrently. Notably, if any execution of {@link * #runOneIteration} takes longer than its schedule defines, then subsequent executions may start * late. Also, all life cycle methods are executed with a lock held, so subclasses can safely * modify shared state without additional synchronization necessary for visibility to later * executions of the life cycle methods. * * <h3>Usage Example</h3> * * <p>Here is a sketch of a service which crawls a website and uses the scheduling capabilities to * rate limit itself. <pre> {@code * class CrawlingService extends AbstractScheduledService { * private Set<Uri> visited; * private Queue<Uri> toCrawl; * protected void startUp() throws Exception { * toCrawl = readStartingUris(); * } * * protected void runOneIteration() throws Exception { * Uri uri = toCrawl.remove(); * Collection<Uri> newUris = crawl(uri); * visited.add(uri); * for (Uri newUri : newUris) { * if (!visited.contains(newUri)) { toCrawl.add(newUri); } * } * } * * protected void shutDown() throws Exception { * saveUris(toCrawl); * } * * protected Scheduler scheduler() { * return Scheduler.newFixedRateSchedule(0, 1, TimeUnit.SECONDS); * } * }}</pre> * * <p>This class uses the life cycle methods to read in a list of starting URIs and save the set of * outstanding URIs when shutting down. Also, it takes advantage of the scheduling functionality to * rate limit the number of queries we perform. * * @author Luke Sandberg * @since 11.0 */ @Beta public abstract class AbstractScheduledService implements Service { private static final Logger logger = Logger.getLogger(AbstractScheduledService.class.getName()); /** * A scheduler defines the policy for how the {@link AbstractScheduledService} should run its * task. * * <p>Consider using the {@link #newFixedDelaySchedule} and {@link #newFixedRateSchedule} factory * methods, these provide {@link Scheduler} instances for the common use case of running the * service with a fixed schedule. If more flexibility is needed then consider subclassing * {@link CustomScheduler}. * * @author Luke Sandberg * @since 11.0 */ public abstract static class Scheduler { /** * Returns a {@link Scheduler} that schedules the task using the * {@link ScheduledExecutorService#scheduleWithFixedDelay} method. * * @param initialDelay the time to delay first execution * @param delay the delay between the termination of one execution and the commencement of the * next * @param unit the time unit of the initialDelay and delay parameters */ public static Scheduler newFixedDelaySchedule(final long initialDelay, final long delay, final TimeUnit unit) { return new Scheduler() { @Override public Future<?> schedule(AbstractService service, ScheduledExecutorService executor, Runnable task) { return executor.scheduleWithFixedDelay(task, initialDelay, delay, unit); } }; } /** * Returns a {@link Scheduler} that schedules the task using the * {@link ScheduledExecutorService#scheduleAtFixedRate} method. * * @param initialDelay the time to delay first execution * @param period the period between successive executions of the task * @param unit the time unit of the initialDelay and period parameters */ public static Scheduler newFixedRateSchedule(final long initialDelay, final long period, final TimeUnit unit) { return new Scheduler() { @Override public Future<?> schedule(AbstractService service, ScheduledExecutorService executor, Runnable task) { return executor.scheduleAtFixedRate(task, initialDelay, period, unit); } }; } /** Schedules the task to run on the provided executor on behalf of the service. */ abstract Future<?> schedule(AbstractService service, ScheduledExecutorService executor, Runnable runnable); private Scheduler() {} } /* use AbstractService for state management */ private final AbstractService delegate = new AbstractService() { // A handle to the running task so that we can stop it when a shutdown has been requested. // These two fields are volatile because their values will be accessed from multiple threads. private volatile Future<?> runningTask; private volatile ScheduledExecutorService executorService; // This lock protects the task so we can ensure that none of the template methods (startUp, // shutDown or runOneIteration) run concurrently with one another. private final ReentrantLock lock = new ReentrantLock(); private final Runnable task = new Runnable() { @Override public void run() { lock.lock(); try { AbstractScheduledService.this.runOneIteration(); } catch (Throwable t) { try { shutDown(); } catch (Exception ignored) { logger.log(Level.WARNING, "Error while attempting to shut down the service after failure.", ignored); } notifyFailed(t); throw Throwables.propagate(t); } finally { lock.unlock(); } } }; @Override protected final void doStart() { executorService = MoreExecutors.renamingDecorator(executor(), new Supplier<String>() { @Override public String get() { return serviceName() + " " + state(); } }); executorService.execute(new Runnable() { @Override public void run() { lock.lock(); try { startUp(); runningTask = scheduler().schedule(delegate, executorService, task); notifyStarted(); } catch (Throwable t) { notifyFailed(t); throw Throwables.propagate(t); } finally { lock.unlock(); } } }); } @Override protected final void doStop() { runningTask.cancel(false); executorService.execute(new Runnable() { @Override public void run() { try { lock.lock(); try { if (state() != State.STOPPING) { // This means that the state has changed since we were scheduled. This implies that // an execution of runOneIteration has thrown an exception and we have transitioned // to a failed state, also this means that shutDown has already been called, so we // do not want to call it again. return; } shutDown(); } finally { lock.unlock(); } notifyStopped(); } catch (Throwable t) { notifyFailed(t); throw Throwables.propagate(t); } } }); } }; /** Constructor for use by subclasses. */ protected AbstractScheduledService() {} /** * Run one iteration of the scheduled task. If any invocation of this method throws an exception, * the service will transition to the {@link Service.State#FAILED} state and this method will no * longer be called. */ protected abstract void runOneIteration() throws Exception; /** * Start the service. * * <p>By default this method does nothing. */ protected void startUp() throws Exception {} /** * Stop the service. This is guaranteed not to run concurrently with {@link #runOneIteration}. * * <p>By default this method does nothing. */ protected void shutDown() throws Exception {} /** * Returns the {@link Scheduler} object used to configure this service. This method will only be * called once. */ protected abstract Scheduler scheduler(); /** * Returns the {@link ScheduledExecutorService} that will be used to execute the {@link #startUp}, * {@link #runOneIteration} and {@link #shutDown} methods. If this method is overridden the * executor will not be {@linkplain ScheduledExecutorService#shutdown shutdown} when this * service {@linkplain Service.State#TERMINATED terminates} or * {@linkplain Service.State#TERMINATED fails}. Subclasses may override this method to supply a * custom {@link ScheduledExecutorService} instance. This method is guaranteed to only be called * once. * * <p>By default this returns a new {@link ScheduledExecutorService} with a single thread thread * pool that sets the name of the thread to the {@linkplain #serviceName() service name}. * Also, the pool will be {@linkplain ScheduledExecutorService#shutdown() shut down} when the * service {@linkplain Service.State#TERMINATED terminates} or * {@linkplain Service.State#TERMINATED fails}. */ protected ScheduledExecutorService executor() { final ScheduledExecutorService executor = Executors.newSingleThreadScheduledExecutor( new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { return MoreExecutors.newThread(serviceName(), runnable); } }); // Add a listener to shutdown the executor after the service is stopped. This ensures that the // JVM shutdown will not be prevented from exiting after this service has stopped or failed. // Technically this listener is added after start() was called so it is a little gross, but it // is called within doStart() so we know that the service cannot terminate or fail concurrently // with adding this listener so it is impossible to miss an event that we are interested in. addListener(new Listener() { @Override public void terminated(State from) { executor.shutdown(); } @Override public void failed(State from, Throwable failure) { executor.shutdown(); }}, MoreExecutors.sameThreadExecutor()); return executor; } /** * Returns the name of this service. {@link AbstractScheduledService} may include the name in * debugging output. * * @since 14.0 */ protected String serviceName() { return getClass().getSimpleName(); } @Override public String toString() { return serviceName() + " [" + state() + "]"; } @Override public final boolean isRunning() { return delegate.isRunning(); } @Override public final State state() { return delegate.state(); } /** * @since 13.0 */ @Override public final void addListener(Listener listener, Executor executor) { delegate.addListener(listener, executor); } /** * @since 14.0 */ @Override public final Throwable failureCause() { return delegate.failureCause(); } /** * @since 15.0 */ @Override public final Service startAsync() { delegate.startAsync(); return this; } /** * @since 15.0 */ @Override public final Service stopAsync() { delegate.stopAsync(); return this; } /** * @since 15.0 */ @Override public final void awaitRunning() { delegate.awaitRunning(); } /** * @since 15.0 */ @Override public final void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException { delegate.awaitRunning(timeout, unit); } /** * @since 15.0 */ @Override public final void awaitTerminated() { delegate.awaitTerminated(); } /** * @since 15.0 */ @Override public final void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException { delegate.awaitTerminated(timeout, unit); } /** * A {@link Scheduler} that provides a convenient way for the {@link AbstractScheduledService} to * use a dynamically changing schedule. After every execution of the task, assuming it hasn't * been cancelled, the {@link #getNextSchedule} method will be called. * * @author Luke Sandberg * @since 11.0 */ @Beta public abstract static class CustomScheduler extends Scheduler { /** * A callable class that can reschedule itself using a {@link CustomScheduler}. */ private class ReschedulableCallable extends ForwardingFuture<Void> implements Callable<Void> { /** The underlying task. */ private final Runnable wrappedRunnable; /** The executor on which this Callable will be scheduled. */ private final ScheduledExecutorService executor; /** * The service that is managing this callable. This is used so that failure can be * reported properly. */ private final AbstractService service; /** * This lock is used to ensure safe and correct cancellation, it ensures that a new task is * not scheduled while a cancel is ongoing. Also it protects the currentFuture variable to * ensure that it is assigned atomically with being scheduled. */ private final ReentrantLock lock = new ReentrantLock(); /** The future that represents the next execution of this task.*/ @GuardedBy("lock") private Future<Void> currentFuture; ReschedulableCallable(AbstractService service, ScheduledExecutorService executor, Runnable runnable) { this.wrappedRunnable = runnable; this.executor = executor; this.service = service; } @Override public Void call() throws Exception { wrappedRunnable.run(); reschedule(); return null; } /** * Atomically reschedules this task and assigns the new future to {@link #currentFuture}. */ public void reschedule() { // We reschedule ourselves with a lock held for two reasons. 1. we want to make sure that // cancel calls cancel on the correct future. 2. we want to make sure that the assignment // to currentFuture doesn't race with itself so that currentFuture is assigned in the // correct order. lock.lock(); try { if (currentFuture == null || !currentFuture.isCancelled()) { final Schedule schedule = CustomScheduler.this.getNextSchedule(); currentFuture = executor.schedule(this, schedule.delay, schedule.unit); } } catch (Throwable e) { // If an exception is thrown by the subclass then we need to make sure that the service // notices and transitions to the FAILED state. We do it by calling notifyFailed directly // because the service does not monitor the state of the future so if the exception is not // caught and forwarded to the service the task would stop executing but the service would // have no idea. service.notifyFailed(e); } finally { lock.unlock(); } } // N.B. Only protect cancel and isCancelled because those are the only methods that are // invoked by the AbstractScheduledService. @Override public boolean cancel(boolean mayInterruptIfRunning) { // Ensure that a task cannot be rescheduled while a cancel is ongoing. lock.lock(); try { return currentFuture.cancel(mayInterruptIfRunning); } finally { lock.unlock(); } } @Override protected Future<Void> delegate() { throw new UnsupportedOperationException("Only cancel is supported by this future"); } } @Override final Future<?> schedule(AbstractService service, ScheduledExecutorService executor, Runnable runnable) { ReschedulableCallable task = new ReschedulableCallable(service, executor, runnable); task.reschedule(); return task; } /** * A value object that represents an absolute delay until a task should be invoked. * * @author Luke Sandberg * @since 11.0 */ @Beta protected static final class Schedule { private final long delay; private final TimeUnit unit; /** * @param delay the time from now to delay execution * @param unit the time unit of the delay parameter */ public Schedule(long delay, TimeUnit unit) { this.delay = delay; this.unit = Preconditions.checkNotNull(unit); } } /** * Calculates the time at which to next invoke the task. * * <p>This is guaranteed to be called immediately after the task has completed an iteration and * on the same thread as the previous execution of {@link * AbstractScheduledService#runOneIteration}. * * @return a schedule that defines the delay before the next execution. */ protected abstract Schedule getNextSchedule() throws Exception; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/AbstractScheduledService.java
Java
asf20
19,087
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import java.util.concurrent.Callable; /** * A listening executor service which forwards all its method calls to another * listening executor service. Subclasses should override one or more methods to * modify the behavior of the backing executor service as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Isaac Shum * @since 10.0 */ public abstract class ForwardingListeningExecutorService extends ForwardingExecutorService implements ListeningExecutorService { /** Constructor for use by subclasses. */ protected ForwardingListeningExecutorService() {} @Override protected abstract ListeningExecutorService delegate(); @Override public <T> ListenableFuture<T> submit(Callable<T> task) { return delegate().submit(task); } @Override public ListenableFuture<?> submit(Runnable task) { return delegate().submit(task); } @Override public <T> ListenableFuture<T> submit(Runnable task, T result) { return delegate().submit(task, result); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/ForwardingListeningExecutorService.java
Java
asf20
1,699
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Objects.firstNonNull; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.MapMaker; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.EnumMap; import java.util.List; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.Nullable; import javax.annotation.concurrent.ThreadSafe; /** * The {@code CycleDetectingLockFactory} creates {@link ReentrantLock} instances and * {@link ReentrantReadWriteLock} instances that detect potential deadlock by checking * for cycles in lock acquisition order. * <p> * Potential deadlocks detected when calling the {@code lock()}, * {@code lockInterruptibly()}, or {@code tryLock()} methods will result in the * execution of the {@link Policy} specified when creating the factory. The * currently available policies are: * <ul> * <li>DISABLED * <li>WARN * <li>THROW * </ul> * <p>The locks created by a factory instance will detect lock acquisition cycles * with locks created by other {@code CycleDetectingLockFactory} instances * (except those with {@code Policy.DISABLED}). A lock's behavior when a cycle * is detected, however, is defined by the {@code Policy} of the factory that * created it. This allows detection of cycles across components while * delegating control over lock behavior to individual components. * <p> * Applications are encouraged to use a {@code CycleDetectingLockFactory} to * create any locks for which external/unmanaged code is executed while the lock * is held. (See caveats under <strong>Performance</strong>). * <p> * <strong>Cycle Detection</strong> * <p> * Deadlocks can arise when locks are acquired in an order that forms a cycle. * In a simple example involving two locks and two threads, deadlock occurs * when one thread acquires Lock A, and then Lock B, while another thread * acquires Lock B, and then Lock A: * <pre> * Thread1: acquire(LockA) --X acquire(LockB) * Thread2: acquire(LockB) --X acquire(LockA) * </pre> * <p>Neither thread will progress because each is waiting for the other. In more * complex applications, cycles can arise from interactions among more than 2 * locks: * <pre> * Thread1: acquire(LockA) --X acquire(LockB) * Thread2: acquire(LockB) --X acquire(LockC) * ... * ThreadN: acquire(LockN) --X acquire(LockA) * </pre> * <p>The implementation detects cycles by constructing a directed graph in which * each lock represents a node and each edge represents an acquisition ordering * between two locks. * <ul> * <li>Each lock adds (and removes) itself to/from a ThreadLocal Set of acquired * locks when the Thread acquires its first hold (and releases its last * remaining hold). * <li>Before the lock is acquired, the lock is checked against the current set * of acquired locks---to each of the acquired locks, an edge from the * soon-to-be-acquired lock is either verified or created. * <li>If a new edge needs to be created, the outgoing edges of the acquired * locks are traversed to check for a cycle that reaches the lock to be * acquired. If no cycle is detected, a new "safe" edge is created. * <li>If a cycle is detected, an "unsafe" (cyclic) edge is created to represent * a potential deadlock situation, and the appropriate Policy is executed. * </ul> * <p>Note that detection of potential deadlock does not necessarily indicate that * deadlock will happen, as it is possible that higher level application logic * prevents the cyclic lock acquisition from occurring. One example of a false * positive is: * <pre> * LockA -&gt; LockB -&gt; LockC * LockA -&gt; LockC -&gt; LockB * </pre> * * <strong>ReadWriteLocks</strong> * <p> * While {@code ReadWriteLock} instances have different properties and can form cycles * without potential deadlock, this class treats {@code ReadWriteLock} instances as * equivalent to traditional exclusive locks. Although this increases the false * positives that the locks detect (i.e. cycles that will not actually result in * deadlock), it simplifies the algorithm and implementation considerably. The * assumption is that a user of this factory wishes to eliminate any cyclic * acquisition ordering. * <p> * <strong>Explicit Lock Acquisition Ordering</strong> * <p> * The {@link CycleDetectingLockFactory.WithExplicitOrdering} class can be used * to enforce an application-specific ordering in addition to performing general * cycle detection. * <p> * <strong>Garbage Collection</strong> * <p> * In order to allow proper garbage collection of unused locks, the edges of * the lock graph are weak references. * <p> * <strong>Performance</strong> * <p> * The extra bookkeeping done by cycle detecting locks comes at some cost to * performance. Benchmarks (as of December 2011) show that: * * <ul> * <li>for an unnested {@code lock()} and {@code unlock()}, a cycle detecting * lock takes 38ns as opposed to the 24ns taken by a plain lock. * <li>for nested locking, the cost increases with the depth of the nesting: * <ul> * <li> 2 levels: average of 64ns per lock()/unlock() * <li> 3 levels: average of 77ns per lock()/unlock() * <li> 4 levels: average of 99ns per lock()/unlock() * <li> 5 levels: average of 103ns per lock()/unlock() * <li>10 levels: average of 184ns per lock()/unlock() * <li>20 levels: average of 393ns per lock()/unlock() * </ul> * </ul> * * <p>As such, the CycleDetectingLockFactory may not be suitable for * performance-critical applications which involve tightly-looped or * deeply-nested locking algorithms. * * @author Darick Tong * @since 13.0 */ @Beta @ThreadSafe public class CycleDetectingLockFactory { /** * Encapsulates the action to be taken when a potential deadlock is * encountered. Clients can use one of the predefined {@link Policies} or * specify a custom implementation. Implementations must be thread-safe. * * @since 13.0 */ @Beta @ThreadSafe public interface Policy { /** * Called when a potential deadlock is encountered. Implementations can * throw the given {@code exception} and/or execute other desired logic. * <p> * Note that the method will be called even upon an invocation of * {@code tryLock()}. Although {@code tryLock()} technically recovers from * deadlock by eventually timing out, this behavior is chosen based on the * assumption that it is the application's wish to prohibit any cyclical * lock acquisitions. */ void handlePotentialDeadlock(PotentialDeadlockException exception); } /** * Pre-defined {@link Policy} implementations. * * @since 13.0 */ @Beta public enum Policies implements Policy { /** * When potential deadlock is detected, this policy results in the throwing * of the {@code PotentialDeadlockException} indicating the potential * deadlock, which includes stack traces illustrating the cycle in lock * acquisition order. */ THROW { @Override public void handlePotentialDeadlock(PotentialDeadlockException e) { throw e; } }, /** * When potential deadlock is detected, this policy results in the logging * of a {@link Level#SEVERE} message indicating the potential deadlock, * which includes stack traces illustrating the cycle in lock acquisition * order. */ WARN { @Override public void handlePotentialDeadlock(PotentialDeadlockException e) { logger.log(Level.SEVERE, "Detected potential deadlock", e); } }, /** * Disables cycle detection. This option causes the factory to return * unmodified lock implementations provided by the JDK, and is provided to * allow applications to easily parameterize when cycle detection is * enabled. * <p> * Note that locks created by a factory with this policy will <em>not</em> * participate the cycle detection performed by locks created by other * factories. */ DISABLED { @Override public void handlePotentialDeadlock(PotentialDeadlockException e) { } }; } /** * Creates a new factory with the specified policy. */ public static CycleDetectingLockFactory newInstance(Policy policy) { return new CycleDetectingLockFactory(policy); } /** * Equivalent to {@code newReentrantLock(lockName, false)}. */ public ReentrantLock newReentrantLock(String lockName) { return newReentrantLock(lockName, false); } /** * Creates a {@link ReentrantLock} with the given fairness policy. The * {@code lockName} is used in the warning or exception output to help * identify the locks involved in the detected deadlock. */ public ReentrantLock newReentrantLock(String lockName, boolean fair) { return policy == Policies.DISABLED ? new ReentrantLock(fair) : new CycleDetectingReentrantLock( new LockGraphNode(lockName), fair); } /** * Equivalent to {@code newReentrantReadWriteLock(lockName, false)}. */ public ReentrantReadWriteLock newReentrantReadWriteLock(String lockName) { return newReentrantReadWriteLock(lockName, false); } /** * Creates a {@link ReentrantReadWriteLock} with the given fairness policy. * The {@code lockName} is used in the warning or exception output to help * identify the locks involved in the detected deadlock. */ public ReentrantReadWriteLock newReentrantReadWriteLock( String lockName, boolean fair) { return policy == Policies.DISABLED ? new ReentrantReadWriteLock(fair) : new CycleDetectingReentrantReadWriteLock( new LockGraphNode(lockName), fair); } // A static mapping from an Enum type to its set of LockGraphNodes. private static final ConcurrentMap<Class<? extends Enum>, Map<? extends Enum, LockGraphNode>> lockGraphNodesPerType = new MapMaker().weakKeys().makeMap(); /** * Creates a {@code CycleDetectingLockFactory.WithExplicitOrdering<E>}. */ public static <E extends Enum<E>> WithExplicitOrdering<E> newInstanceWithExplicitOrdering(Class<E> enumClass, Policy policy) { // createNodes maps each enumClass to a Map with the corresponding enum key // type. checkNotNull(enumClass); checkNotNull(policy); @SuppressWarnings("unchecked") Map<E, LockGraphNode> lockGraphNodes = (Map<E, LockGraphNode>) getOrCreateNodes(enumClass); return new WithExplicitOrdering<E>(policy, lockGraphNodes); } private static Map<? extends Enum, LockGraphNode> getOrCreateNodes( Class<? extends Enum> clazz) { Map<? extends Enum, LockGraphNode> existing = lockGraphNodesPerType.get(clazz); if (existing != null) { return existing; } Map<? extends Enum, LockGraphNode> created = createNodes(clazz); existing = lockGraphNodesPerType.putIfAbsent(clazz, created); return firstNonNull(existing, created); } /** * For a given Enum type, creates an immutable map from each of the Enum's * values to a corresponding LockGraphNode, with the * {@code allowedPriorLocks} and {@code disallowedPriorLocks} prepopulated * with nodes according to the natural ordering of the associated Enum values. */ @VisibleForTesting static <E extends Enum<E>> Map<E, LockGraphNode> createNodes(Class<E> clazz) { EnumMap<E, LockGraphNode> map = Maps.newEnumMap(clazz); E[] keys = clazz.getEnumConstants(); final int numKeys = keys.length; ArrayList<LockGraphNode> nodes = Lists.newArrayListWithCapacity(numKeys); // Create a LockGraphNode for each enum value. for (E key : keys) { LockGraphNode node = new LockGraphNode(getLockName(key)); nodes.add(node); map.put(key, node); } // Pre-populate all allowedPriorLocks with nodes of smaller ordinal. for (int i = 1; i < numKeys; i++) { nodes.get(i).checkAcquiredLocks(Policies.THROW, nodes.subList(0, i)); } // Pre-populate all disallowedPriorLocks with nodes of larger ordinal. for (int i = 0; i < numKeys - 1; i++) { nodes.get(i).checkAcquiredLocks( Policies.DISABLED, nodes.subList(i + 1, numKeys)); } return Collections.unmodifiableMap(map); } /** * For the given Enum value {@code rank}, returns the value's * {@code "EnumClass.name"}, which is used in exception and warning * output. */ private static String getLockName(Enum<?> rank) { return rank.getDeclaringClass().getSimpleName() + "." + rank.name(); } /** * <p>A {@code CycleDetectingLockFactory.WithExplicitOrdering} provides the * additional enforcement of an application-specified ordering of lock * acquisitions. The application defines the allowed ordering with an * {@code Enum} whose values each correspond to a lock type. The order in * which the values are declared dictates the allowed order of lock * acquisition. In other words, locks corresponding to smaller values of * {@link Enum#ordinal()} should only be acquired before locks with larger * ordinals. Example: * * <pre> {@code * enum MyLockOrder { * FIRST, SECOND, THIRD; * } * * CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory = * CycleDetectingLockFactory.newInstanceWithExplicitOrdering(Policies.THROW); * * Lock lock1 = factory.newReentrantLock(MyLockOrder.FIRST); * Lock lock2 = factory.newReentrantLock(MyLockOrder.SECOND); * Lock lock3 = factory.newReentrantLock(MyLockOrder.THIRD); * * lock1.lock(); * lock3.lock(); * lock2.lock(); // will throw an IllegalStateException}</pre> * * <p>As with all locks created by instances of {@code CycleDetectingLockFactory} * explicitly ordered locks participate in general cycle detection with all * other cycle detecting locks, and a lock's behavior when detecting a cyclic * lock acquisition is defined by the {@code Policy} of the factory that * created it. * * <p>Note, however, that although multiple locks can be created for a given Enum * value, whether it be through separate factory instances or through multiple * calls to the same factory, attempting to acquire multiple locks with the * same Enum value (within the same thread) will result in an * IllegalStateException regardless of the factory's policy. For example: * * <pre> {@code * CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory1 = * CycleDetectingLockFactory.newInstanceWithExplicitOrdering(...); * CycleDetectingLockFactory.WithExplicitOrdering<MyLockOrder> factory2 = * CycleDetectingLockFactory.newInstanceWithExplicitOrdering(...); * * Lock lockA = factory1.newReentrantLock(MyLockOrder.FIRST); * Lock lockB = factory1.newReentrantLock(MyLockOrder.FIRST); * Lock lockC = factory2.newReentrantLock(MyLockOrder.FIRST); * * lockA.lock(); * * lockB.lock(); // will throw an IllegalStateException * lockC.lock(); // will throw an IllegalStateException * * lockA.lock(); // reentrant acquisition is okay}</pre> * * <p>It is the responsibility of the application to ensure that multiple lock * instances with the same rank are never acquired in the same thread. * * @param <E> The Enum type representing the explicit lock ordering. * @since 13.0 */ @Beta public static final class WithExplicitOrdering<E extends Enum<E>> extends CycleDetectingLockFactory { private final Map<E, LockGraphNode> lockGraphNodes; @VisibleForTesting WithExplicitOrdering( Policy policy, Map<E, LockGraphNode> lockGraphNodes) { super(policy); this.lockGraphNodes = lockGraphNodes; } /** * Equivalent to {@code newReentrantLock(rank, false)}. */ public ReentrantLock newReentrantLock(E rank) { return newReentrantLock(rank, false); } /** * Creates a {@link ReentrantLock} with the given fairness policy and rank. * The values returned by {@link Enum#getDeclaringClass()} and * {@link Enum#name()} are used to describe the lock in warning or * exception output. * * @throws IllegalStateException If the factory has already created a * {@code Lock} with the specified rank. */ public ReentrantLock newReentrantLock(E rank, boolean fair) { return policy == Policies.DISABLED ? new ReentrantLock(fair) : new CycleDetectingReentrantLock(lockGraphNodes.get(rank), fair); } /** * Equivalent to {@code newReentrantReadWriteLock(rank, false)}. */ public ReentrantReadWriteLock newReentrantReadWriteLock(E rank) { return newReentrantReadWriteLock(rank, false); } /** * Creates a {@link ReentrantReadWriteLock} with the given fairness policy * and rank. The values returned by {@link Enum#getDeclaringClass()} and * {@link Enum#name()} are used to describe the lock in warning or exception * output. * * @throws IllegalStateException If the factory has already created a * {@code Lock} with the specified rank. */ public ReentrantReadWriteLock newReentrantReadWriteLock( E rank, boolean fair) { return policy == Policies.DISABLED ? new ReentrantReadWriteLock(fair) : new CycleDetectingReentrantReadWriteLock( lockGraphNodes.get(rank), fair); } } //////// Implementation ///////// private static final Logger logger = Logger.getLogger( CycleDetectingLockFactory.class.getName()); final Policy policy; private CycleDetectingLockFactory(Policy policy) { this.policy = checkNotNull(policy); } /** * Tracks the currently acquired locks for each Thread, kept up to date by * calls to {@link #aboutToAcquire(CycleDetectingLock)} and * {@link #lockStateChanged(CycleDetectingLock)}. */ // This is logically a Set, but an ArrayList is used to minimize the amount // of allocation done on lock()/unlock(). private static final ThreadLocal<ArrayList<LockGraphNode>> acquiredLocks = new ThreadLocal<ArrayList<LockGraphNode>>() { @Override protected ArrayList<LockGraphNode> initialValue() { return Lists.<LockGraphNode>newArrayListWithCapacity(3); } }; /** * A Throwable used to record a stack trace that illustrates an example of * a specific lock acquisition ordering. The top of the stack trace is * truncated such that it starts with the acquisition of the lock in * question, e.g. * * <pre> * com...ExampleStackTrace: LockB -&gt; LockC * at com...CycleDetectingReentrantLock.lock(CycleDetectingLockFactory.java:443) * at ... * at ... * at com...MyClass.someMethodThatAcquiresLockB(MyClass.java:123) * </pre> */ private static class ExampleStackTrace extends IllegalStateException { static final StackTraceElement[] EMPTY_STACK_TRACE = new StackTraceElement[0]; static Set<String> EXCLUDED_CLASS_NAMES = ImmutableSet.of( CycleDetectingLockFactory.class.getName(), ExampleStackTrace.class.getName(), LockGraphNode.class.getName()); ExampleStackTrace(LockGraphNode node1, LockGraphNode node2) { super(node1.getLockName() + " -> " + node2.getLockName()); StackTraceElement[] origStackTrace = getStackTrace(); for (int i = 0, n = origStackTrace.length; i < n; i++) { if (WithExplicitOrdering.class.getName().equals( origStackTrace[i].getClassName())) { // For pre-populated disallowedPriorLocks edges, omit the stack trace. setStackTrace(EMPTY_STACK_TRACE); break; } if (!EXCLUDED_CLASS_NAMES.contains(origStackTrace[i].getClassName())) { setStackTrace(Arrays.copyOfRange(origStackTrace, i, n)); break; } } } } /** * Represents a detected cycle in lock acquisition ordering. The exception * includes a causal chain of {@code ExampleStackTrace} instances to illustrate the * cycle, e.g. * * <pre> * com....PotentialDeadlockException: Potential Deadlock from LockC -&gt; ReadWriteA * at ... * at ... * Caused by: com...ExampleStackTrace: LockB -&gt; LockC * at ... * at ... * Caused by: com...ExampleStackTrace: ReadWriteA -&gt; LockB * at ... * at ... * </pre> * * <p>Instances are logged for the {@code Policies.WARN}, and thrown for * {@code Policies.THROW}. * * @since 13.0 */ @Beta public static final class PotentialDeadlockException extends ExampleStackTrace { private final ExampleStackTrace conflictingStackTrace; private PotentialDeadlockException( LockGraphNode node1, LockGraphNode node2, ExampleStackTrace conflictingStackTrace) { super(node1, node2); this.conflictingStackTrace = conflictingStackTrace; initCause(conflictingStackTrace); } public ExampleStackTrace getConflictingStackTrace() { return conflictingStackTrace; } /** * Appends the chain of messages from the {@code conflictingStackTrace} to * the original {@code message}. */ @Override public String getMessage() { StringBuilder message = new StringBuilder(super.getMessage()); for (Throwable t = conflictingStackTrace; t != null; t = t.getCause()) { message.append(", ").append(t.getMessage()); } return message.toString(); } } /** * Internal Lock implementations implement the {@code CycleDetectingLock} * interface, allowing the detection logic to treat all locks in the same * manner. */ private interface CycleDetectingLock { /** @return the {@link LockGraphNode} associated with this lock. */ LockGraphNode getLockGraphNode(); /** @return {@code true} if the current thread has acquired this lock. */ boolean isAcquiredByCurrentThread(); } /** * A {@code LockGraphNode} associated with each lock instance keeps track of * the directed edges in the lock acquisition graph. */ private static class LockGraphNode { /** * The map tracking the locks that are known to be acquired before this * lock, each associated with an example stack trace. Locks are weakly keyed * to allow proper garbage collection when they are no longer referenced. */ final Map<LockGraphNode, ExampleStackTrace> allowedPriorLocks = new MapMaker().weakKeys().makeMap(); /** * The map tracking lock nodes that can cause a lock acquisition cycle if * acquired before this node. */ final Map<LockGraphNode, PotentialDeadlockException> disallowedPriorLocks = new MapMaker().weakKeys().makeMap(); final String lockName; LockGraphNode(String lockName) { this.lockName = Preconditions.checkNotNull(lockName); } String getLockName() { return lockName; } void checkAcquiredLocks( Policy policy, List<LockGraphNode> acquiredLocks) { for (int i = 0, size = acquiredLocks.size(); i < size; i++) { checkAcquiredLock(policy, acquiredLocks.get(i)); } } /** * Checks the acquisition-ordering between {@code this}, which is about to * be acquired, and the specified {@code acquiredLock}. * <p> * When this method returns, the {@code acquiredLock} should be in either * the {@code preAcquireLocks} map, for the case in which it is safe to * acquire {@code this} after the {@code acquiredLock}, or in the * {@code disallowedPriorLocks} map, in which case it is not safe. */ void checkAcquiredLock(Policy policy, LockGraphNode acquiredLock) { // checkAcquiredLock() should never be invoked by a lock that has already // been acquired. For unordered locks, aboutToAcquire() ensures this by // checking isAcquiredByCurrentThread(). For ordered locks, however, this // can happen because multiple locks may share the same LockGraphNode. In // this situation, throw an IllegalStateException as defined by contract // described in the documentation of WithExplicitOrdering. Preconditions.checkState( this != acquiredLock, "Attempted to acquire multiple locks with the same rank " + acquiredLock.getLockName()); if (allowedPriorLocks.containsKey(acquiredLock)) { // The acquisition ordering from "acquiredLock" to "this" has already // been verified as safe. In a properly written application, this is // the common case. return; } PotentialDeadlockException previousDeadlockException = disallowedPriorLocks.get(acquiredLock); if (previousDeadlockException != null) { // Previously determined to be an unsafe lock acquisition. // Create a new PotentialDeadlockException with the same causal chain // (the example cycle) as that of the cached exception. PotentialDeadlockException exception = new PotentialDeadlockException( acquiredLock, this, previousDeadlockException.getConflictingStackTrace()); policy.handlePotentialDeadlock(exception); return; } // Otherwise, it's the first time seeing this lock relationship. Look for // a path from the acquiredLock to this. Set<LockGraphNode> seen = Sets.newIdentityHashSet(); ExampleStackTrace path = acquiredLock.findPathTo(this, seen); if (path == null) { // this can be safely acquired after the acquiredLock. // // Note that there is a race condition here which can result in missing // a cyclic edge: it's possible for two threads to simultaneous find // "safe" edges which together form a cycle. Preventing this race // condition efficiently without _introducing_ deadlock is probably // tricky. For now, just accept the race condition---missing a warning // now and then is still better than having no deadlock detection. allowedPriorLocks.put( acquiredLock, new ExampleStackTrace(acquiredLock, this)); } else { // Unsafe acquisition order detected. Create and cache a // PotentialDeadlockException. PotentialDeadlockException exception = new PotentialDeadlockException(acquiredLock, this, path); disallowedPriorLocks.put(acquiredLock, exception); policy.handlePotentialDeadlock(exception); } } /** * Performs a depth-first traversal of the graph edges defined by each * node's {@code allowedPriorLocks} to find a path between {@code this} and * the specified {@code lock}. * * @return If a path was found, a chained {@link ExampleStackTrace} * illustrating the path to the {@code lock}, or {@code null} if no path * was found. */ @Nullable private ExampleStackTrace findPathTo( LockGraphNode node, Set<LockGraphNode> seen) { if (!seen.add(this)) { return null; // Already traversed this node. } ExampleStackTrace found = allowedPriorLocks.get(node); if (found != null) { return found; // Found a path ending at the node! } // Recurse the edges. for (Map.Entry<LockGraphNode, ExampleStackTrace> entry : allowedPriorLocks.entrySet()) { LockGraphNode preAcquiredLock = entry.getKey(); found = preAcquiredLock.findPathTo(node, seen); if (found != null) { // One of this node's allowedPriorLocks found a path. Prepend an // ExampleStackTrace(preAcquiredLock, this) to the returned chain of // ExampleStackTraces. ExampleStackTrace path = new ExampleStackTrace(preAcquiredLock, this); path.setStackTrace(entry.getValue().getStackTrace()); path.initCause(found); return path; } } return null; } } /** * CycleDetectingLock implementations must call this method before attempting * to acquire the lock. */ private void aboutToAcquire(CycleDetectingLock lock) { if (!lock.isAcquiredByCurrentThread()) { ArrayList<LockGraphNode> acquiredLockList = acquiredLocks.get(); LockGraphNode node = lock.getLockGraphNode(); node.checkAcquiredLocks(policy, acquiredLockList); acquiredLockList.add(node); } } /** * CycleDetectingLock implementations must call this method in a * {@code finally} clause after any attempt to change the lock state, * including both lock and unlock attempts. Failure to do so can result in * corrupting the acquireLocks set. */ private void lockStateChanged(CycleDetectingLock lock) { if (!lock.isAcquiredByCurrentThread()) { ArrayList<LockGraphNode> acquiredLockList = acquiredLocks.get(); LockGraphNode node = lock.getLockGraphNode(); // Iterate in reverse because locks are usually locked/unlocked in a // LIFO order. for (int i = acquiredLockList.size() - 1; i >=0; i--) { if (acquiredLockList.get(i) == node) { acquiredLockList.remove(i); break; } } } } final class CycleDetectingReentrantLock extends ReentrantLock implements CycleDetectingLock { private final LockGraphNode lockGraphNode; private CycleDetectingReentrantLock( LockGraphNode lockGraphNode, boolean fair) { super(fair); this.lockGraphNode = Preconditions.checkNotNull(lockGraphNode); } ///// CycleDetectingLock methods. ///// @Override public LockGraphNode getLockGraphNode() { return lockGraphNode; } @Override public boolean isAcquiredByCurrentThread() { return isHeldByCurrentThread(); } ///// Overridden ReentrantLock methods. ///// @Override public void lock() { aboutToAcquire(this); try { super.lock(); } finally { lockStateChanged(this); } } @Override public void lockInterruptibly() throws InterruptedException { aboutToAcquire(this); try { super.lockInterruptibly(); } finally { lockStateChanged(this); } } @Override public boolean tryLock() { aboutToAcquire(this); try { return super.tryLock(); } finally { lockStateChanged(this); } } @Override public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { aboutToAcquire(this); try { return super.tryLock(timeout, unit); } finally { lockStateChanged(this); } } @Override public void unlock() { try { super.unlock(); } finally { lockStateChanged(this); } } } final class CycleDetectingReentrantReadWriteLock extends ReentrantReadWriteLock implements CycleDetectingLock { // These ReadLock/WriteLock implementations shadow those in the // ReentrantReadWriteLock superclass. They are simply wrappers around the // internal Sync object, so this is safe since the shadowed locks are never // exposed or used. private final CycleDetectingReentrantReadLock readLock; private final CycleDetectingReentrantWriteLock writeLock; private final LockGraphNode lockGraphNode; private CycleDetectingReentrantReadWriteLock( LockGraphNode lockGraphNode, boolean fair) { super(fair); this.readLock = new CycleDetectingReentrantReadLock(this); this.writeLock = new CycleDetectingReentrantWriteLock(this); this.lockGraphNode = Preconditions.checkNotNull(lockGraphNode); } ///// Overridden ReentrantReadWriteLock methods. ///// @Override public ReadLock readLock() { return readLock; } @Override public WriteLock writeLock() { return writeLock; } ///// CycleDetectingLock methods. ///// @Override public LockGraphNode getLockGraphNode() { return lockGraphNode; } @Override public boolean isAcquiredByCurrentThread() { return isWriteLockedByCurrentThread() || getReadHoldCount() > 0; } } private class CycleDetectingReentrantReadLock extends ReentrantReadWriteLock.ReadLock { final CycleDetectingReentrantReadWriteLock readWriteLock; CycleDetectingReentrantReadLock( CycleDetectingReentrantReadWriteLock readWriteLock) { super(readWriteLock); this.readWriteLock = readWriteLock; } @Override public void lock() { aboutToAcquire(readWriteLock); try { super.lock(); } finally { lockStateChanged(readWriteLock); } } @Override public void lockInterruptibly() throws InterruptedException { aboutToAcquire(readWriteLock); try { super.lockInterruptibly(); } finally { lockStateChanged(readWriteLock); } } @Override public boolean tryLock() { aboutToAcquire(readWriteLock); try { return super.tryLock(); } finally { lockStateChanged(readWriteLock); } } @Override public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { aboutToAcquire(readWriteLock); try { return super.tryLock(timeout, unit); } finally { lockStateChanged(readWriteLock); } } @Override public void unlock() { try { super.unlock(); } finally { lockStateChanged(readWriteLock); } } } private class CycleDetectingReentrantWriteLock extends ReentrantReadWriteLock.WriteLock { final CycleDetectingReentrantReadWriteLock readWriteLock; CycleDetectingReentrantWriteLock( CycleDetectingReentrantReadWriteLock readWriteLock) { super(readWriteLock); this.readWriteLock = readWriteLock; } @Override public void lock() { aboutToAcquire(readWriteLock); try { super.lock(); } finally { lockStateChanged(readWriteLock); } } @Override public void lockInterruptibly() throws InterruptedException { aboutToAcquire(readWriteLock); try { super.lockInterruptibly(); } finally { lockStateChanged(readWriteLock); } } @Override public boolean tryLock() { aboutToAcquire(readWriteLock); try { return super.tryLock(); } finally { lockStateChanged(readWriteLock); } } @Override public boolean tryLock(long timeout, TimeUnit unit) throws InterruptedException { aboutToAcquire(readWriteLock); try { return super.tryLock(timeout, unit); } finally { lockStateChanged(readWriteLock); } } @Override public void unlock() { try { super.unlock(); } finally { lockStateChanged(readWriteLock); } } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/CycleDetectingLockFactory.java
Java
asf20
36,213
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; import javax.annotation.Nullable; /** * A settable future that can be set asynchronously via {@link #setFuture}. * A similar effect could be accomplished by adding a listener to the delegate * future that sets a normal settable future after the delegate is complete. * This approach gains us the ability to keep track of whether a delegate has * been set (i.e. so that we can prevent collisions from setting it twice and * can know before the computation is done whether it has been set), as well * as improved cancellation semantics (i.e. if either future is cancelled, * then the other one is too). This class is thread-safe. * * @param <V> The result type returned by the Future's {@code get} method. * * @author Stephen Hicks */ final class AsyncSettableFuture<V> extends ForwardingListenableFuture<V> { /** Creates a new asynchronously-settable future. */ public static <V> AsyncSettableFuture<V> create() { return new AsyncSettableFuture<V>(); } private final NestedFuture<V> nested = new NestedFuture<V>(); private final ListenableFuture<V> dereferenced = Futures.dereference(nested); private AsyncSettableFuture() {} @Override protected ListenableFuture<V> delegate() { return dereferenced; } /** * Sets this future to forward to the given future. Returns {@code true} * if the future was able to be set (i.e. it hasn't been set already). */ public boolean setFuture(ListenableFuture<? extends V> future) { return nested.setFuture(checkNotNull(future)); } /** * Convenience method that calls {@link #setFuture} on a {@link * Futures#immediateFuture}. Returns {@code true} if the future * was able to be set (i.e. it hasn't been set already). */ public boolean setValue(@Nullable V value) { return setFuture(Futures.immediateFuture(value)); } /** * Convenience method that calls {@link #setFuture} on a {@link * Futures#immediateFailedFuture}. Returns {@code true} if the * future was able to be set (i.e. it hasn't been set already). */ public boolean setException(Throwable exception) { return setFuture(Futures.<V>immediateFailedFuture(exception)); } /** * Returns {@code true} if this future has been (possibly asynchronously) set. * Note that a {@code false} result in no way gaurantees that a later call * to, e.g., {@link #setFuture} will succeed, since another thread could * make the call in between. This is somewhat analogous to {@link #isDone}, * but since setting and completing are not the same event, it is useful to * have this method broken out. */ public boolean isSet() { return nested.isDone(); } private static final class NestedFuture<V> extends AbstractFuture<ListenableFuture<? extends V>> { boolean setFuture(ListenableFuture<? extends V> value) { boolean result = set(value); if (isCancelled()) { value.cancel(wasInterrupted()); } return result; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/AsyncSettableFuture.java
Java
asf20
3,687
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.base.Throwables; import java.util.concurrent.TimeUnit; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import javax.annotation.concurrent.GuardedBy; /** * A synchronization abstraction supporting waiting on arbitrary boolean conditions. * * <p>This class is intended as a replacement for {@link ReentrantLock}. Code using {@code Monitor} * is less error-prone and more readable than code using {@code ReentrantLock}, without significant * performance loss. {@code Monitor} even has the potential for performance gain by optimizing the * evaluation and signaling of conditions. Signaling is entirely * <a href="http://en.wikipedia.org/wiki/Monitor_(synchronization)#Implicit_signaling"> * implicit</a>. * By eliminating explicit signaling, this class can guarantee that only one thread is awakened * when a condition becomes true (no "signaling storms" due to use of {@link * java.util.concurrent.locks.Condition#signalAll Condition.signalAll}) and that no signals are lost * (no "hangs" due to incorrect use of {@link java.util.concurrent.locks.Condition#signal * Condition.signal}). * * <p>A thread is said to <i>occupy</i> a monitor if it has <i>entered</i> the monitor but not yet * <i>left</i>. Only one thread may occupy a given monitor at any moment. A monitor is also * reentrant, so a thread may enter a monitor any number of times, and then must leave the same * number of times. The <i>enter</i> and <i>leave</i> operations have the same synchronization * semantics as the built-in Java language synchronization primitives. * * <p>A call to any of the <i>enter</i> methods with <b>void</b> return type should always be * followed immediately by a <i>try/finally</i> block to ensure that the current thread leaves the * monitor cleanly: <pre> {@code * * monitor.enter(); * try { * // do things while occupying the monitor * } finally { * monitor.leave(); * }}</pre> * * <p>A call to any of the <i>enter</i> methods with <b>boolean</b> return type should always * appear as the condition of an <i>if</i> statement containing a <i>try/finally</i> block to * ensure that the current thread leaves the monitor cleanly: <pre> {@code * * if (monitor.tryEnter()) { * try { * // do things while occupying the monitor * } finally { * monitor.leave(); * } * } else { * // do other things since the monitor was not available * }}</pre> * * <h2>Comparison with {@code synchronized} and {@code ReentrantLock}</h2> * * <p>The following examples show a simple threadsafe holder expressed using {@code synchronized}, * {@link ReentrantLock}, and {@code Monitor}. * * <h3>{@code synchronized}</h3> * * <p>This version is the fewest lines of code, largely because the synchronization mechanism used * is built into the language and runtime. But the programmer has to remember to avoid a couple of * common bugs: The {@code wait()} must be inside a {@code while} instead of an {@code if}, and * {@code notifyAll()} must be used instead of {@code notify()} because there are two different * logical conditions being awaited. <pre> {@code * * public class SafeBox<V> { * private V value; * * public synchronized V get() throws InterruptedException { * while (value == null) { * wait(); * } * V result = value; * value = null; * notifyAll(); * return result; * } * * public synchronized void set(V newValue) throws InterruptedException { * while (value != null) { * wait(); * } * value = newValue; * notifyAll(); * } * }}</pre> * * <h3>{@code ReentrantLock}</h3> * * <p>This version is much more verbose than the {@code synchronized} version, and still suffers * from the need for the programmer to remember to use {@code while} instead of {@code if}. * However, one advantage is that we can introduce two separate {@code Condition} objects, which * allows us to use {@code signal()} instead of {@code signalAll()}, which may be a performance * benefit. <pre> {@code * * public class SafeBox<V> { * private final ReentrantLock lock = new ReentrantLock(); * private final Condition valuePresent = lock.newCondition(); * private final Condition valueAbsent = lock.newCondition(); * private V value; * * public V get() throws InterruptedException { * lock.lock(); * try { * while (value == null) { * valuePresent.await(); * } * V result = value; * value = null; * valueAbsent.signal(); * return result; * } finally { * lock.unlock(); * } * } * * public void set(V newValue) throws InterruptedException { * lock.lock(); * try { * while (value != null) { * valueAbsent.await(); * } * value = newValue; * valuePresent.signal(); * } finally { * lock.unlock(); * } * } * }}</pre> * * <h3>{@code Monitor}</h3> * * <p>This version adds some verbosity around the {@code Guard} objects, but removes that same * verbosity, and more, from the {@code get} and {@code set} methods. {@code Monitor} implements the * same efficient signaling as we had to hand-code in the {@code ReentrantLock} version above. * Finally, the programmer no longer has to hand-code the wait loop, and therefore doesn't have to * remember to use {@code while} instead of {@code if}. <pre> {@code * * public class SafeBox<V> { * private final Monitor monitor = new Monitor(); * private final Monitor.Guard valuePresent = new Monitor.Guard(monitor) { * public boolean isSatisfied() { * return value != null; * } * }; * private final Monitor.Guard valueAbsent = new Monitor.Guard(monitor) { * public boolean isSatisfied() { * return value == null; * } * }; * private V value; * * public V get() throws InterruptedException { * monitor.enterWhen(valuePresent); * try { * V result = value; * value = null; * return result; * } finally { * monitor.leave(); * } * } * * public void set(V newValue) throws InterruptedException { * monitor.enterWhen(valueAbsent); * try { * value = newValue; * } finally { * monitor.leave(); * } * } * }}</pre> * * @author Justin T. Sampson * @author Martin Buchholz * @since 10.0 */ @Beta public final class Monitor { // TODO(user): Use raw LockSupport or AbstractQueuedSynchronizer instead of ReentrantLock. // TODO(user): "Port" jsr166 tests for ReentrantLock. // // TODO(user): Change API to make it impossible to use a Guard with the "wrong" monitor, // by making the monitor implicit, and to eliminate other sources of IMSE. // Imagine: // guard.lock(); // try { /* monitor locked and guard satisfied here */ } // finally { guard.unlock(); } // Here are Justin's design notes about this: // // This idea has come up from time to time, and I think one of my // earlier versions of Monitor even did something like this. I ended // up strongly favoring the current interface. // // I probably can't remember all the reasons (it's possible you // could find them in the code review archives), but here are a few: // // 1. What about leaving/unlocking? Are you going to do // guard.enter() paired with monitor.leave()? That might get // confusing. It's nice for the finally block to look as close as // possible to the thing right before the try. You could have // guard.leave(), but that's a little odd as well because the // guard doesn't have anything to do with leaving. You can't // really enforce that the guard you're leaving is the same one // you entered with, and it doesn't actually matter. // // 2. Since you can enter the monitor without a guard at all, some // places you'll have monitor.enter()/monitor.leave() and other // places you'll have guard.enter()/guard.leave() even though // it's the same lock being acquired underneath. Always using // monitor.enterXXX()/monitor.leave() will make it really clear // which lock is held at any point in the code. // // 3. I think "enterWhen(notEmpty)" reads better than "notEmpty.enter()". // // TODO(user): Implement ReentrantLock features: // - toString() method // - getOwner() method // - getQueuedThreads() method // - getWaitingThreads(Guard) method // - implement Serializable // - redo the API to be as close to identical to ReentrantLock as possible, // since, after all, this class is also a reentrant mutual exclusion lock!? /* * One of the key challenges of this class is to prevent lost signals, while trying hard to * minimize unnecessary signals. One simple and correct algorithm is to signal some other * waiter with a satisfied guard (if one exists) whenever any thread occupying the monitor * exits the monitor, either by unlocking all of its held locks, or by starting to wait for a * guard. This includes exceptional exits, so all control paths involving signalling must be * protected by a finally block. * * Further optimizations of this algorithm become increasingly subtle. A wait that terminates * without the guard being satisfied (due to timeout, but not interrupt) can then immediately * exit the monitor without signalling. If it timed out without being signalled, it does not * need to "pass on" the signal to another thread. If it *was* signalled, then its guard must * have been satisfied at the time of signal, and has since been modified by some other thread * to be non-satisfied before reacquiring the lock, and that other thread takes over the * responsibility of signaling the next waiter. * * Unlike the underlying Condition, if we are not careful, an interrupt *can* cause a signal to * be lost, because the signal may be sent to a condition whose sole waiter has just been * interrupted. * * Imagine a monitor with multiple guards. A thread enters the monitor, satisfies all the * guards, and leaves, calling signalNextWaiter. With traditional locks and conditions, all * the conditions need to be signalled because it is not known which if any of them have * waiters (and hasWaiters can't be used reliably because of a check-then-act race). With our * Monitor guards, we only signal the first active guard that is satisfied. But the * corresponding thread may have already been interrupted and is waiting to reacquire the lock * while still registered in activeGuards, in which case the signal is a no-op, and the * bigger-picture signal is lost unless interrupted threads take special action by * participating in the signal-passing game. */ /** * A boolean condition for which a thread may wait. A {@code Guard} is associated with a single * {@code Monitor}. The monitor may check the guard at arbitrary times from any thread occupying * the monitor, so code should not be written to rely on how often a guard might or might not be * checked. * * <p>If a {@code Guard} is passed into any method of a {@code Monitor} other than the one it is * associated with, an {@link IllegalMonitorStateException} is thrown. * * @since 10.0 */ @Beta public abstract static class Guard { final Monitor monitor; final Condition condition; @GuardedBy("monitor.lock") int waiterCount = 0; /** The next active guard */ @GuardedBy("monitor.lock") Guard next; protected Guard(Monitor monitor) { this.monitor = checkNotNull(monitor, "monitor"); this.condition = monitor.lock.newCondition(); } /** * Evaluates this guard's boolean condition. This method is always called with the associated * monitor already occupied. Implementations of this method must depend only on state protected * by the associated monitor, and must not modify that state. */ public abstract boolean isSatisfied(); } /** * Whether this monitor is fair. */ private final boolean fair; /** * The lock underlying this monitor. */ private final ReentrantLock lock; /** * The guards associated with this monitor that currently have waiters ({@code waiterCount > 0}). * A linked list threaded through the Guard.next field. */ @GuardedBy("lock") private Guard activeGuards = null; /** * Creates a monitor with a non-fair (but fast) ordering policy. Equivalent to {@code * Monitor(false)}. */ public Monitor() { this(false); } /** * Creates a monitor with the given ordering policy. * * @param fair whether this monitor should use a fair ordering policy rather than a non-fair (but * fast) one */ public Monitor(boolean fair) { this.fair = fair; this.lock = new ReentrantLock(fair); } /** * Enters this monitor. Blocks indefinitely. */ public void enter() { lock.lock(); } /** * Enters this monitor. Blocks indefinitely, but may be interrupted. */ public void enterInterruptibly() throws InterruptedException { lock.lockInterruptibly(); } /** * Enters this monitor. Blocks at most the given time. * * @return whether the monitor was entered */ public boolean enter(long time, TimeUnit unit) { long timeoutNanos = unit.toNanos(time); final ReentrantLock lock = this.lock; if (!fair && lock.tryLock()) { return true; } long deadline = System.nanoTime() + timeoutNanos; boolean interrupted = Thread.interrupted(); try { while (true) { try { return lock.tryLock(timeoutNanos, TimeUnit.NANOSECONDS); } catch (InterruptedException interrupt) { interrupted = true; timeoutNanos = deadline - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Enters this monitor. Blocks at most the given time, and may be interrupted. * * @return whether the monitor was entered */ public boolean enterInterruptibly(long time, TimeUnit unit) throws InterruptedException { return lock.tryLock(time, unit); } /** * Enters this monitor if it is possible to do so immediately. Does not block. * * <p><b>Note:</b> This method disregards the fairness setting of this monitor. * * @return whether the monitor was entered */ public boolean tryEnter() { return lock.tryLock(); } /** * Enters this monitor when the guard is satisfied. Blocks indefinitely, but may be interrupted. */ public void enterWhen(Guard guard) throws InterruptedException { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); lock.lockInterruptibly(); boolean satisfied = false; try { if (!guard.isSatisfied()) { await(guard, signalBeforeWaiting); } satisfied = true; } finally { if (!satisfied) { leave(); } } } /** * Enters this monitor when the guard is satisfied. Blocks indefinitely. */ public void enterWhenUninterruptibly(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); lock.lock(); boolean satisfied = false; try { if (!guard.isSatisfied()) { awaitUninterruptibly(guard, signalBeforeWaiting); } satisfied = true; } finally { if (!satisfied) { leave(); } } } /** * Enters this monitor when the guard is satisfied. Blocks at most the given time, including both * the time to acquire the lock and the time to wait for the guard to be satisfied, and may be * interrupted. * * @return whether the monitor was entered with the guard satisfied */ public boolean enterWhen(Guard guard, long time, TimeUnit unit) throws InterruptedException { long timeoutNanos = unit.toNanos(time); if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; boolean reentrant = lock.isHeldByCurrentThread(); if (fair || !lock.tryLock()) { long deadline = System.nanoTime() + timeoutNanos; if (!lock.tryLock(time, unit)) { return false; } timeoutNanos = deadline - System.nanoTime(); } boolean satisfied = false; boolean threw = true; try { satisfied = guard.isSatisfied() || awaitNanos(guard, timeoutNanos, reentrant); threw = false; return satisfied; } finally { if (!satisfied) { try { // Don't need to signal if timed out, but do if interrupted if (threw && !reentrant) { signalNextWaiter(); } } finally { lock.unlock(); } } } } /** * Enters this monitor when the guard is satisfied. Blocks at most the given time, including * both the time to acquire the lock and the time to wait for the guard to be satisfied. * * @return whether the monitor was entered with the guard satisfied */ public boolean enterWhenUninterruptibly(Guard guard, long time, TimeUnit unit) { long timeoutNanos = unit.toNanos(time); if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; long deadline = System.nanoTime() + timeoutNanos; boolean signalBeforeWaiting = lock.isHeldByCurrentThread(); boolean interrupted = Thread.interrupted(); try { if (fair || !lock.tryLock()) { boolean locked = false; do { try { locked = lock.tryLock(timeoutNanos, TimeUnit.NANOSECONDS); if (!locked) { return false; } } catch (InterruptedException interrupt) { interrupted = true; } timeoutNanos = deadline - System.nanoTime(); } while (!locked); } boolean satisfied = false; try { while (true) { try { return satisfied = guard.isSatisfied() || awaitNanos(guard, timeoutNanos, signalBeforeWaiting); } catch (InterruptedException interrupt) { interrupted = true; signalBeforeWaiting = false; timeoutNanos = deadline - System.nanoTime(); } } } finally { if (!satisfied) { lock.unlock(); // No need to signal if timed out } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but * does not wait for the guard to be satisfied. * * @return whether the monitor was entered with the guard satisfied */ public boolean enterIf(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; lock.lock(); boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } } /** * Enters this monitor if the guard is satisfied. Blocks indefinitely acquiring the lock, but does * not wait for the guard to be satisfied, and may be interrupted. * * @return whether the monitor was entered with the guard satisfied */ public boolean enterIfInterruptibly(Guard guard) throws InterruptedException { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; lock.lockInterruptibly(); boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } } /** * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the * lock, but does not wait for the guard to be satisfied. * * @return whether the monitor was entered with the guard satisfied */ public boolean enterIf(Guard guard, long time, TimeUnit unit) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } if (!enter(time, unit)) { return false; } boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } } /** * Enters this monitor if the guard is satisfied. Blocks at most the given time acquiring the * lock, but does not wait for the guard to be satisfied, and may be interrupted. * * @return whether the monitor was entered with the guard satisfied */ public boolean enterIfInterruptibly(Guard guard, long time, TimeUnit unit) throws InterruptedException { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; if (!lock.tryLock(time, unit)) { return false; } boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } } /** * Enters this monitor if it is possible to do so immediately and the guard is satisfied. Does not * block acquiring the lock and does not wait for the guard to be satisfied. * * <p><b>Note:</b> This method disregards the fairness setting of this monitor. * * @return whether the monitor was entered with the guard satisfied */ public boolean tryEnterIf(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } final ReentrantLock lock = this.lock; if (!lock.tryLock()) { return false; } boolean satisfied = false; try { return satisfied = guard.isSatisfied(); } finally { if (!satisfied) { lock.unlock(); } } } /** * Waits for the guard to be satisfied. Waits indefinitely, but may be interrupted. May be * called only by a thread currently occupying this monitor. */ public void waitFor(Guard guard) throws InterruptedException { if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (!guard.isSatisfied()) { await(guard, true); } } /** * Waits for the guard to be satisfied. Waits indefinitely. May be called only by a thread * currently occupying this monitor. */ public void waitForUninterruptibly(Guard guard) { if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (!guard.isSatisfied()) { awaitUninterruptibly(guard, true); } } /** * Waits for the guard to be satisfied. Waits at most the given time, and may be interrupted. * May be called only by a thread currently occupying this monitor. * * @return whether the guard is now satisfied */ public boolean waitFor(Guard guard, long time, TimeUnit unit) throws InterruptedException { long timeoutNanos = unit.toNanos(time); if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } return guard.isSatisfied() || awaitNanos(guard, timeoutNanos, true); } /** * Waits for the guard to be satisfied. Waits at most the given time. May be called only by a * thread currently occupying this monitor. * * @return whether the guard is now satisfied */ public boolean waitForUninterruptibly(Guard guard, long time, TimeUnit unit) { long timeoutNanos = unit.toNanos(time); if (!((guard.monitor == this) & lock.isHeldByCurrentThread())) { throw new IllegalMonitorStateException(); } if (guard.isSatisfied()) { return true; } boolean signalBeforeWaiting = true; long deadline = System.nanoTime() + timeoutNanos; boolean interrupted = Thread.interrupted(); try { while (true) { try { return awaitNanos(guard, timeoutNanos, signalBeforeWaiting); } catch (InterruptedException interrupt) { interrupted = true; if (guard.isSatisfied()) { return true; } signalBeforeWaiting = false; timeoutNanos = deadline - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Leaves this monitor. May be called only by a thread currently occupying this monitor. */ public void leave() { final ReentrantLock lock = this.lock; try { // No need to signal if we will still be holding the lock when we return if (lock.getHoldCount() == 1) { signalNextWaiter(); } } finally { lock.unlock(); // Will throw IllegalMonitorStateException if not held } } /** * Returns whether this monitor is using a fair ordering policy. */ public boolean isFair() { return fair; } /** * Returns whether this monitor is occupied by any thread. This method is designed for use in * monitoring of the system state, not for synchronization control. */ public boolean isOccupied() { return lock.isLocked(); } /** * Returns whether the current thread is occupying this monitor (has entered more times than it * has left). */ public boolean isOccupiedByCurrentThread() { return lock.isHeldByCurrentThread(); } /** * Returns the number of times the current thread has entered this monitor in excess of the number * of times it has left. Returns 0 if the current thread is not occupying this monitor. */ public int getOccupiedDepth() { return lock.getHoldCount(); } /** * Returns an estimate of the number of threads waiting to enter this monitor. The value is only * an estimate because the number of threads may change dynamically while this method traverses * internal data structures. This method is designed for use in monitoring of the system state, * not for synchronization control. */ public int getQueueLength() { return lock.getQueueLength(); } /** * Returns whether any threads are waiting to enter this monitor. Note that because cancellations * may occur at any time, a {@code true} return does not guarantee that any other thread will ever * enter this monitor. This method is designed primarily for use in monitoring of the system * state. */ public boolean hasQueuedThreads() { return lock.hasQueuedThreads(); } /** * Queries whether the given thread is waiting to enter this monitor. Note that because * cancellations may occur at any time, a {@code true} return does not guarantee that this thread * will ever enter this monitor. This method is designed primarily for use in monitoring of the * system state. */ public boolean hasQueuedThread(Thread thread) { return lock.hasQueuedThread(thread); } /** * Queries whether any threads are waiting for the given guard to become satisfied. Note that * because timeouts and interrupts may occur at any time, a {@code true} return does not guarantee * that the guard becoming satisfied in the future will awaken any threads. This method is * designed primarily for use in monitoring of the system state. */ public boolean hasWaiters(Guard guard) { return getWaitQueueLength(guard) > 0; } /** * Returns an estimate of the number of threads waiting for the given guard to become satisfied. * Note that because timeouts and interrupts may occur at any time, the estimate serves only as an * upper bound on the actual number of waiters. This method is designed for use in monitoring of * the system state, not for synchronization control. */ public int getWaitQueueLength(Guard guard) { if (guard.monitor != this) { throw new IllegalMonitorStateException(); } lock.lock(); try { return guard.waiterCount; } finally { lock.unlock(); } } /** * Signals some other thread waiting on a satisfied guard, if one exists. * * We manage calls to this method carefully, to signal only when necessary, but never losing a * signal, which is the classic problem of this kind of concurrency construct. We must signal if * the current thread is about to relinquish the lock and may have changed the state protected by * the monitor, thereby causing some guard to be satisfied. * * In addition, any thread that has been signalled when its guard was satisfied acquires the * responsibility of signalling the next thread when it again relinquishes the lock. Unlike a * normal Condition, there is no guarantee that an interrupted thread has not been signalled, * since the concurrency control must manage multiple Conditions. So this method must generally * be called when waits are interrupted. * * On the other hand, if a signalled thread wakes up to discover that its guard is still not * satisfied, it does *not* need to call this method before returning to wait. This can only * happen due to spurious wakeup (ignorable) or another thread acquiring the lock before the * current thread can and returning the guard to the unsatisfied state. In the latter case the * other thread (last thread modifying the state protected by the monitor) takes over the * responsibility of signalling the next waiter. * * This method must not be called from within a beginWaitingFor/endWaitingFor block, or else the * current thread's guard might be mistakenly signalled, leading to a lost signal. */ @GuardedBy("lock") private void signalNextWaiter() { for (Guard guard = activeGuards; guard != null; guard = guard.next) { if (isSatisfied(guard)) { guard.condition.signal(); break; } } } /** * Exactly like signalNextWaiter, but caller guarantees that guardToSkip need not be considered, * because caller has previously checked that guardToSkip.isSatisfied() returned false. * An optimization for the case that guardToSkip.isSatisfied() may be expensive. * * We decided against using this method, since in practice, isSatisfied() is likely to be very * cheap (typically one field read). Resurrect this method if you find that not to be true. */ // @GuardedBy("lock") // private void signalNextWaiterSkipping(Guard guardToSkip) { // for (Guard guard = activeGuards; guard != null; guard = guard.next) { // if (guard != guardToSkip && isSatisfied(guard)) { // guard.condition.signal(); // break; // } // } // } /** * Exactly like guard.isSatisfied(), but in addition signals all waiting threads in the * (hopefully unlikely) event that isSatisfied() throws. */ @GuardedBy("lock") private boolean isSatisfied(Guard guard) { try { return guard.isSatisfied(); } catch (Throwable throwable) { signalAllWaiters(); throw Throwables.propagate(throwable); } } /** * Signals all threads waiting on guards. */ @GuardedBy("lock") private void signalAllWaiters() { for (Guard guard = activeGuards; guard != null; guard = guard.next) { guard.condition.signalAll(); } } /** * Records that the current thread is about to wait on the specified guard. */ @GuardedBy("lock") private void beginWaitingFor(Guard guard) { int waiters = guard.waiterCount++; if (waiters == 0) { // push guard onto activeGuards guard.next = activeGuards; activeGuards = guard; } } /** * Records that the current thread is no longer waiting on the specified guard. */ @GuardedBy("lock") private void endWaitingFor(Guard guard) { int waiters = --guard.waiterCount; if (waiters == 0) { // unlink guard from activeGuards for (Guard p = activeGuards, pred = null;; pred = p, p = p.next) { if (p == guard) { if (pred == null) { activeGuards = p.next; } else { pred.next = p.next; } p.next = null; // help GC break; } } } } /* * Methods that loop waiting on a guard's condition until the guard is satisfied, while * recording this fact so that other threads know to check our guard and signal us. * It's caller's responsibility to ensure that the guard is *not* currently satisfied. */ @GuardedBy("lock") private void await(Guard guard, boolean signalBeforeWaiting) throws InterruptedException { if (signalBeforeWaiting) { signalNextWaiter(); } beginWaitingFor(guard); try { do { guard.condition.await(); } while (!guard.isSatisfied()); } finally { endWaitingFor(guard); } } @GuardedBy("lock") private void awaitUninterruptibly(Guard guard, boolean signalBeforeWaiting) { if (signalBeforeWaiting) { signalNextWaiter(); } beginWaitingFor(guard); try { do { guard.condition.awaitUninterruptibly(); } while (!guard.isSatisfied()); } finally { endWaitingFor(guard); } } @GuardedBy("lock") private boolean awaitNanos(Guard guard, long nanos, boolean signalBeforeWaiting) throws InterruptedException { if (signalBeforeWaiting) { signalNextWaiter(); } beginWaitingFor(guard); try { do { if (nanos < 0L) { return false; } nanos = guard.condition.awaitNanos(nanos); } while (!guard.isSatisfied()); return true; } finally { endWaitingFor(guard); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/Monitor.java
Java
asf20
35,001
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.FutureTask; import java.util.concurrent.RejectedExecutionException; /** * A {@link Future} that accepts completion listeners. Each listener has an * associated executor, and it is invoked using this executor once the future's * computation is {@linkplain Future#isDone() complete}. If the computation has * already completed when the listener is added, the listener will execute * immediately. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/ListenableFutureExplained"> * {@code ListenableFuture}</a>. * * <h3>Purpose</h3> * * <p>Most commonly, {@code ListenableFuture} is used as an input to another * derived {@code Future}, as in {@link Futures#allAsList(Iterable) * Futures.allAsList}. Many such methods are impossible to implement efficiently * without listener support. * * <p>It is possible to call {@link #addListener addListener} directly, but this * is uncommon because the {@code Runnable} interface does not provide direct * access to the {@code Future} result. (Users who want such access may prefer * {@link Futures#addCallback Futures.addCallback}.) Still, direct {@code * addListener} calls are occasionally useful:<pre> {@code * final String name = ...; * inFlight.add(name); * ListenableFuture<Result> future = service.query(name); * future.addListener(new Runnable() { * public void run() { * processedCount.incrementAndGet(); * inFlight.remove(name); * lastProcessed.set(name); * logger.info("Done with {0}", name); * } * }, executor);}</pre> * * <h3>How to get an instance</h3> * * <p>Developers are encouraged to return {@code ListenableFuture} from their * methods so that users can take advantages of the utilities built atop the * class. The way that they will create {@code ListenableFuture} instances * depends on how they currently create {@code Future} instances: * <ul> * <li>If they are returned from an {@code ExecutorService}, convert that * service to a {@link ListeningExecutorService}, usually by calling {@link * MoreExecutors#listeningDecorator(ExecutorService) * MoreExecutors.listeningDecorator}. (Custom executors may find it more * convenient to use {@link ListenableFutureTask} directly.) * <li>If they are manually filled in by a call to {@link FutureTask#set} or a * similar method, create a {@link SettableFuture} instead. (Users with more * complex needs may prefer {@link AbstractFuture}.) * </ul> * * <p>Occasionally, an API will return a plain {@code Future} and it will be * impossible to change the return type. For this case, we provide a more * expensive workaround in {@code JdkFutureAdapters}. However, when possible, it * is more efficient and reliable to create a {@code ListenableFuture} directly. * * @author Sven Mawson * @author Nishant Thakkar * @since 1.0 */ public interface ListenableFuture<V> extends Future<V> { /** * Registers a listener to be {@linkplain Executor#execute(Runnable) run} on * the given executor. The listener will run when the {@code Future}'s * computation is {@linkplain Future#isDone() complete} or, if the computation * is already complete, immediately. * * <p>There is no guaranteed ordering of execution of listeners, but any * listener added through this method is guaranteed to be called once the * computation is complete. * * <p>Exceptions thrown by a listener will be propagated up to the executor. * Any exception thrown during {@code Executor.execute} (e.g., a {@code * RejectedExecutionException} or an exception thrown by {@linkplain * MoreExecutors#sameThreadExecutor inline execution}) will be caught and * logged. * * <p>Note: For fast, lightweight listeners that would be safe to execute in * any thread, consider {@link MoreExecutors#sameThreadExecutor}. For heavier * listeners, {@code sameThreadExecutor()} carries some caveats. For * example, the listener may run on an unpredictable or undesirable thread: * * <ul> * <li>If this {@code Future} is done at the time {@code addListener} is * called, {@code addListener} will execute the listener inline. * <li>If this {@code Future} is not yet done, {@code addListener} will * schedule the listener to be run by the thread that completes this {@code * Future}, which may be an internal system thread such as an RPC network * thread. * </ul> * * <p>Also note that, regardless of which thread executes the * {@code sameThreadExecutor()} listener, all other registered but unexecuted * listeners are prevented from running during its execution, even if those * listeners are to run in other executors. * * <p>This is the most general listener interface. For common operations * performed using listeners, see {@link * com.google.common.util.concurrent.Futures}. For a simplified but general * listener interface, see {@link * com.google.common.util.concurrent.Futures#addCallback addCallback()}. * * @param listener the listener to run when the computation is complete * @param executor the executor to run the listener in * @throws NullPointerException if the executor or listener was null * @throws RejectedExecutionException if we tried to execute the listener * immediately but the executor rejected it. */ void addListener(Runnable listener, Executor executor); }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/ListenableFuture.java
Java
asf20
6,229
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly; import com.google.common.annotations.Beta; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicBoolean; /** * Utilities necessary for working with libraries that supply plain {@link * Future} instances. Note that, whenver possible, it is strongly preferred to * modify those libraries to return {@code ListenableFuture} directly. * * @author Sven Mawson * @since 10.0 (replacing {@code Futures.makeListenable}, which * existed in 1.0) */ @Beta public final class JdkFutureAdapters { /** * Assigns a thread to the given {@link Future} to provide {@link * ListenableFuture} functionality. * * <p><b>Warning:</b> If the input future does not already implement {@code * ListenableFuture}, the returned future will emulate {@link * ListenableFuture#addListener} by taking a thread from an internal, * unbounded pool at the first call to {@code addListener} and holding it * until the future is {@linkplain Future#isDone() done}. * * <p>Prefer to create {@code ListenableFuture} instances with {@link * SettableFuture}, {@link MoreExecutors#listeningDecorator( * java.util.concurrent.ExecutorService)}, {@link ListenableFutureTask}, * {@link AbstractFuture}, and other utilities over creating plain {@code * Future} instances to be upgraded to {@code ListenableFuture} after the * fact. */ public static <V> ListenableFuture<V> listenInPoolThread( Future<V> future) { if (future instanceof ListenableFuture) { return (ListenableFuture<V>) future; } return new ListenableFutureAdapter<V>(future); } /** * Submits a blocking task for the given {@link Future} to provide {@link * ListenableFuture} functionality. * * <p><b>Warning:</b> If the input future does not already implement {@code * ListenableFuture}, the returned future will emulate {@link * ListenableFuture#addListener} by submitting a task to the given executor at * the first call to {@code addListener}. The task must be started by the * executor promptly, or else the returned {@code ListenableFuture} may fail * to work. The task's execution consists of blocking until the input future * is {@linkplain Future#isDone() done}, so each call to this method may * claim and hold a thread for an arbitrary length of time. Use of bounded * executors or other executors that may fail to execute a task promptly may * result in deadlocks. * * <p>Prefer to create {@code ListenableFuture} instances with {@link * SettableFuture}, {@link MoreExecutors#listeningDecorator( * java.util.concurrent.ExecutorService)}, {@link ListenableFutureTask}, * {@link AbstractFuture}, and other utilities over creating plain {@code * Future} instances to be upgraded to {@code ListenableFuture} after the * fact. * * @since 12.0 */ public static <V> ListenableFuture<V> listenInPoolThread( Future<V> future, Executor executor) { checkNotNull(executor); if (future instanceof ListenableFuture) { return (ListenableFuture<V>) future; } return new ListenableFutureAdapter<V>(future, executor); } /** * An adapter to turn a {@link Future} into a {@link ListenableFuture}. This * will wait on the future to finish, and when it completes, run the * listeners. This implementation will wait on the source future * indefinitely, so if the source future never completes, the adapter will * never complete either. * * <p>If the delegate future is interrupted or throws an unexpected unchecked * exception, the listeners will not be invoked. */ private static class ListenableFutureAdapter<V> extends ForwardingFuture<V> implements ListenableFuture<V> { private static final ThreadFactory threadFactory = new ThreadFactoryBuilder() .setDaemon(true) .setNameFormat("ListenableFutureAdapter-thread-%d") .build(); private static final Executor defaultAdapterExecutor = Executors.newCachedThreadPool(threadFactory); private final Executor adapterExecutor; // The execution list to hold our listeners. private final ExecutionList executionList = new ExecutionList(); // This allows us to only start up a thread waiting on the delegate future // when the first listener is added. private final AtomicBoolean hasListeners = new AtomicBoolean(false); // The delegate future. private final Future<V> delegate; ListenableFutureAdapter(Future<V> delegate) { this(delegate, defaultAdapterExecutor); } ListenableFutureAdapter(Future<V> delegate, Executor adapterExecutor) { this.delegate = checkNotNull(delegate); this.adapterExecutor = checkNotNull(adapterExecutor); } @Override protected Future<V> delegate() { return delegate; } @Override public void addListener(Runnable listener, Executor exec) { executionList.add(listener, exec); // When a listener is first added, we run a task that will wait for // the delegate to finish, and when it is done will run the listeners. if (hasListeners.compareAndSet(false, true)) { if (delegate.isDone()) { // If the delegate is already done, run the execution list // immediately on the current thread. executionList.execute(); return; } adapterExecutor.execute(new Runnable() { @Override public void run() { try { /* * Threads from our private pool are never interrupted. Threads * from a user-supplied executor might be, but... what can we do? * This is another reason to return a proper ListenableFuture * instead of using listenInPoolThread. */ getUninterruptibly(delegate); } catch (Error e) { throw e; } catch (Throwable e) { // ExecutionException / CancellationException / RuntimeException // The task is done, run the listeners. } executionList.execute(); } }); } } } private JdkFutureAdapters() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/JdkFutureAdapters.java
Java
asf20
7,149
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; /** * Provides a backup {@code Future} to replace an earlier failed {@code Future}. * An implementation of this interface can be applied to an input {@code Future} * with {@link Futures#withFallback}. * * @param <V> the result type of the provided backup {@code Future} * * @author Bruno Diniz * @since 14.0 */ @Beta public interface FutureFallback<V> { /** * Returns a {@code Future} to be used in place of the {@code Future} that * failed with the given exception. The exception is provided so that the * {@code Fallback} implementation can conditionally determine whether to * propagate the exception or to attempt to recover. * * @param t the exception that made the future fail. If the future's {@link * Future#get() get} method throws an {@link ExecutionException}, then the * cause is passed to this method. Any other thrown object is passed * unaltered. */ ListenableFuture<V> create(Throwable t) throws Exception; }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/FutureFallback.java
Java
asf20
1,755
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import java.lang.Thread.UncaughtExceptionHandler; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.atomic.AtomicLong; /** * A ThreadFactory builder, providing any combination of these features: * <ul> * <li> whether threads should be marked as {@linkplain Thread#setDaemon daemon} * threads * <li> a {@linkplain ThreadFactoryBuilder#setNameFormat naming format} * <li> a {@linkplain Thread#setPriority thread priority} * <li> an {@linkplain Thread#setUncaughtExceptionHandler uncaught exception * handler} * <li> a {@linkplain ThreadFactory#newThread backing thread factory} * </ul> * <p>If no backing thread factory is provided, a default backing thread factory is * used as if by calling {@code setThreadFactory(}{@link * Executors#defaultThreadFactory()}{@code )}. * * @author Kurt Alfred Kluever * @since 4.0 */ public final class ThreadFactoryBuilder { private String nameFormat = null; private Boolean daemon = null; private Integer priority = null; private UncaughtExceptionHandler uncaughtExceptionHandler = null; private ThreadFactory backingThreadFactory = null; /** * Creates a new {@link ThreadFactory} builder. */ public ThreadFactoryBuilder() {} /** * Sets the naming format to use when naming threads ({@link Thread#setName}) * which are created with this ThreadFactory. * * @param nameFormat a {@link String#format(String, Object...)}-compatible * format String, to which a unique integer (0, 1, etc.) will be supplied * as the single parameter. This integer will be unique to the built * instance of the ThreadFactory and will be assigned sequentially. For * example, {@code "rpc-pool-%d"} will generate thread names like * {@code "rpc-pool-0"}, {@code "rpc-pool-1"}, {@code "rpc-pool-2"}, etc. * @return this for the builder pattern */ @SuppressWarnings("ReturnValueIgnored") public ThreadFactoryBuilder setNameFormat(String nameFormat) { String.format(nameFormat, 0); // fail fast if the format is bad or null this.nameFormat = nameFormat; return this; } /** * Sets daemon or not for new threads created with this ThreadFactory. * * @param daemon whether or not new Threads created with this ThreadFactory * will be daemon threads * @return this for the builder pattern */ public ThreadFactoryBuilder setDaemon(boolean daemon) { this.daemon = daemon; return this; } /** * Sets the priority for new threads created with this ThreadFactory. * * @param priority the priority for new Threads created with this * ThreadFactory * @return this for the builder pattern */ public ThreadFactoryBuilder setPriority(int priority) { // Thread#setPriority() already checks for validity. These error messages // are nicer though and will fail-fast. checkArgument(priority >= Thread.MIN_PRIORITY, "Thread priority (%s) must be >= %s", priority, Thread.MIN_PRIORITY); checkArgument(priority <= Thread.MAX_PRIORITY, "Thread priority (%s) must be <= %s", priority, Thread.MAX_PRIORITY); this.priority = priority; return this; } /** * Sets the {@link UncaughtExceptionHandler} for new threads created with this * ThreadFactory. * * @param uncaughtExceptionHandler the uncaught exception handler for new * Threads created with this ThreadFactory * @return this for the builder pattern */ public ThreadFactoryBuilder setUncaughtExceptionHandler( UncaughtExceptionHandler uncaughtExceptionHandler) { this.uncaughtExceptionHandler = checkNotNull(uncaughtExceptionHandler); return this; } /** * Sets the backing {@link ThreadFactory} for new threads created with this * ThreadFactory. Threads will be created by invoking #newThread(Runnable) on * this backing {@link ThreadFactory}. * * @param backingThreadFactory the backing {@link ThreadFactory} which will * be delegated to during thread creation. * @return this for the builder pattern * * @see MoreExecutors */ public ThreadFactoryBuilder setThreadFactory( ThreadFactory backingThreadFactory) { this.backingThreadFactory = checkNotNull(backingThreadFactory); return this; } /** * Returns a new thread factory using the options supplied during the building * process. After building, it is still possible to change the options used to * build the ThreadFactory and/or build again. State is not shared amongst * built instances. * * @return the fully constructed {@link ThreadFactory} */ public ThreadFactory build() { return build(this); } private static ThreadFactory build(ThreadFactoryBuilder builder) { final String nameFormat = builder.nameFormat; final Boolean daemon = builder.daemon; final Integer priority = builder.priority; final UncaughtExceptionHandler uncaughtExceptionHandler = builder.uncaughtExceptionHandler; final ThreadFactory backingThreadFactory = (builder.backingThreadFactory != null) ? builder.backingThreadFactory : Executors.defaultThreadFactory(); final AtomicLong count = (nameFormat != null) ? new AtomicLong(0) : null; return new ThreadFactory() { @Override public Thread newThread(Runnable runnable) { Thread thread = backingThreadFactory.newThread(runnable); if (nameFormat != null) { thread.setName(String.format(nameFormat, count.getAndIncrement())); } if (daemon != null) { thread.setDaemon(daemon); } if (priority != null) { thread.setPriority(priority); } if (uncaughtExceptionHandler != null) { thread.setUncaughtExceptionHandler(uncaughtExceptionHandler); } return thread; } }; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/ThreadFactoryBuilder.java
Java
asf20
6,663
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Objects.firstNonNull; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Preconditions; import com.google.common.base.Supplier; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterables; import com.google.common.collect.MapMaker; import com.google.common.math.IntMath; import com.google.common.primitives.Ints; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.math.RoundingMode; import java.util.Arrays; import java.util.Collections; import java.util.List; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Semaphore; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantLock; import java.util.concurrent.locks.ReentrantReadWriteLock; /** * A striped {@code Lock/Semaphore/ReadWriteLock}. This offers the underlying lock striping * similar to that of {@code ConcurrentHashMap} in a reusable form, and extends it for * semaphores and read-write locks. Conceptually, lock striping is the technique of dividing a lock * into many <i>stripes</i>, increasing the granularity of a single lock and allowing independent * operations to lock different stripes and proceed concurrently, instead of creating contention * for a single lock. * * <p>The guarantee provided by this class is that equal keys lead to the same lock (or semaphore), * i.e. {@code if (key1.equals(key2))} then {@code striped.get(key1) == striped.get(key2)} * (assuming {@link Object#hashCode()} is correctly implemented for the keys). Note * that if {@code key1} is <strong>not</strong> equal to {@code key2}, it is <strong>not</strong> * guaranteed that {@code striped.get(key1) != striped.get(key2)}; the elements might nevertheless * be mapped to the same lock. The lower the number of stripes, the higher the probability of this * happening. * * <p>There are three flavors of this class: {@code Striped<Lock>}, {@code Striped<Semaphore>}, * and {@code Striped<ReadWriteLock>}. For each type, two implementations are offered: * {@linkplain #lock(int) strong} and {@linkplain #lazyWeakLock(int) weak} * {@code Striped<Lock>}, {@linkplain #semaphore(int, int) strong} and {@linkplain * #lazyWeakSemaphore(int, int) weak} {@code Striped<Semaphore>}, and {@linkplain * #readWriteLock(int) strong} and {@linkplain #lazyWeakReadWriteLock(int) weak} * {@code Striped<ReadWriteLock>}. <i>Strong</i> means that all stripes (locks/semaphores) are * initialized eagerly, and are not reclaimed unless {@code Striped} itself is reclaimable. * <i>Weak</i> means that locks/semaphores are created lazily, and they are allowed to be reclaimed * if nobody is holding on to them. This is useful, for example, if one wants to create a {@code * Striped<Lock>} of many locks, but worries that in most cases only a small portion of these * would be in use. * * <p>Prior to this class, one might be tempted to use {@code Map<K, Lock>}, where {@code K} * represents the task. This maximizes concurrency by having each unique key mapped to a unique * lock, but also maximizes memory footprint. On the other extreme, one could use a single lock * for all tasks, which minimizes memory footprint but also minimizes concurrency. Instead of * choosing either of these extremes, {@code Striped} allows the user to trade between required * concurrency and memory footprint. For example, if a set of tasks are CPU-bound, one could easily * create a very compact {@code Striped<Lock>} of {@code availableProcessors() * 4} stripes, * instead of possibly thousands of locks which could be created in a {@code Map<K, Lock>} * structure. * * @author Dimitris Andreou * @since 13.0 */ @Beta public abstract class Striped<L> { /** * If there are at least this many stripes, we assume the memory usage of a ConcurrentMap will be * smaller than a large array. (This assumes that in the lazy case, most stripes are unused. As * always, if many stripes are in use, a non-lazy striped makes more sense.) */ private static final int LARGE_LAZY_CUTOFF = 1024; private Striped() {} /** * Returns the stripe that corresponds to the passed key. It is always guaranteed that if * {@code key1.equals(key2)}, then {@code get(key1) == get(key2)}. * * @param key an arbitrary, non-null key * @return the stripe that the passed key corresponds to */ public abstract L get(Object key); /** * Returns the stripe at the specified index. Valid indexes are 0, inclusively, to * {@code size()}, exclusively. * * @param index the index of the stripe to return; must be in {@code [0...size())} * @return the stripe at the specified index */ public abstract L getAt(int index); /** * Returns the index to which the given key is mapped, so that getAt(indexFor(key)) == get(key). */ abstract int indexFor(Object key); /** * Returns the total number of stripes in this instance. */ public abstract int size(); /** * Returns the stripes that correspond to the passed objects, in ascending (as per * {@link #getAt(int)}) order. Thus, threads that use the stripes in the order returned * by this method are guaranteed to not deadlock each other. * * <p>It should be noted that using a {@code Striped<L>} with relatively few stripes, and * {@code bulkGet(keys)} with a relative large number of keys can cause an excessive number * of shared stripes (much like the birthday paradox, where much fewer than anticipated birthdays * are needed for a pair of them to match). Please consider carefully the implications of the * number of stripes, the intended concurrency level, and the typical number of keys used in a * {@code bulkGet(keys)} operation. See <a href="http://www.mathpages.com/home/kmath199.htm">Balls * in Bins model</a> for mathematical formulas that can be used to estimate the probability of * collisions. * * @param keys arbitrary non-null keys * @return the stripes corresponding to the objects (one per each object, derived by delegating * to {@link #get(Object)}; may contain duplicates), in an increasing index order. */ public Iterable<L> bulkGet(Iterable<?> keys) { // Initially using the array to store the keys, then reusing it to store the respective L's final Object[] array = Iterables.toArray(keys, Object.class); if (array.length == 0) { return ImmutableList.of(); } int[] stripes = new int[array.length]; for (int i = 0; i < array.length; i++) { stripes[i] = indexFor(array[i]); } Arrays.sort(stripes); // optimize for runs of identical stripes int previousStripe = stripes[0]; array[0] = getAt(previousStripe); for (int i = 1; i < array.length; i++) { int currentStripe = stripes[i]; if (currentStripe == previousStripe) { array[i] = array[i - 1]; } else { array[i] = getAt(currentStripe); previousStripe = currentStripe; } } /* * Note that the returned Iterable holds references to the returned stripes, to avoid * error-prone code like: * * Striped<Lock> stripedLock = Striped.lazyWeakXXX(...)' * Iterable<Lock> locks = stripedLock.bulkGet(keys); * for (Lock lock : locks) { * lock.lock(); * } * operation(); * for (Lock lock : locks) { * lock.unlock(); * } * * If we only held the int[] stripes, translating it on the fly to L's, the original locks * might be garbage collected after locking them, ending up in a huge mess. */ @SuppressWarnings("unchecked") // we carefully replaced all keys with their respective L's List<L> asList = (List<L>) Arrays.asList(array); return Collections.unmodifiableList(asList); } // Static factories /** * Creates a {@code Striped<Lock>} with eagerly initialized, strongly referenced locks. * Every lock is reentrant. * * @param stripes the minimum number of stripes (locks) required * @return a new {@code Striped<Lock>} */ public static Striped<Lock> lock(int stripes) { return new CompactStriped<Lock>(stripes, new Supplier<Lock>() { @Override public Lock get() { return new PaddedLock(); } }); } /** * Creates a {@code Striped<Lock>} with lazily initialized, weakly referenced locks. * Every lock is reentrant. * * @param stripes the minimum number of stripes (locks) required * @return a new {@code Striped<Lock>} */ public static Striped<Lock> lazyWeakLock(int stripes) { return lazy(stripes, new Supplier<Lock>() { @Override public Lock get() { return new ReentrantLock(false); } }); } private static <L> Striped<L> lazy(int stripes, Supplier<L> supplier) { return stripes < LARGE_LAZY_CUTOFF ? new SmallLazyStriped<L>(stripes, supplier) : new LargeLazyStriped<L>(stripes, supplier); } /** * Creates a {@code Striped<Semaphore>} with eagerly initialized, strongly referenced semaphores, * with the specified number of permits. * * @param stripes the minimum number of stripes (semaphores) required * @param permits the number of permits in each semaphore * @return a new {@code Striped<Semaphore>} */ public static Striped<Semaphore> semaphore(int stripes, final int permits) { return new CompactStriped<Semaphore>(stripes, new Supplier<Semaphore>() { @Override public Semaphore get() { return new PaddedSemaphore(permits); } }); } /** * Creates a {@code Striped<Semaphore>} with lazily initialized, weakly referenced semaphores, * with the specified number of permits. * * @param stripes the minimum number of stripes (semaphores) required * @param permits the number of permits in each semaphore * @return a new {@code Striped<Semaphore>} */ public static Striped<Semaphore> lazyWeakSemaphore(int stripes, final int permits) { return lazy(stripes, new Supplier<Semaphore>() { @Override public Semaphore get() { return new Semaphore(permits, false); } }); } /** * Creates a {@code Striped<ReadWriteLock>} with eagerly initialized, strongly referenced * read-write locks. Every lock is reentrant. * * @param stripes the minimum number of stripes (locks) required * @return a new {@code Striped<ReadWriteLock>} */ public static Striped<ReadWriteLock> readWriteLock(int stripes) { return new CompactStriped<ReadWriteLock>(stripes, READ_WRITE_LOCK_SUPPLIER); } /** * Creates a {@code Striped<ReadWriteLock>} with lazily initialized, weakly referenced * read-write locks. Every lock is reentrant. * * @param stripes the minimum number of stripes (locks) required * @return a new {@code Striped<ReadWriteLock>} */ public static Striped<ReadWriteLock> lazyWeakReadWriteLock(int stripes) { return lazy(stripes, READ_WRITE_LOCK_SUPPLIER); } // ReentrantReadWriteLock is large enough to make padding probably unnecessary private static final Supplier<ReadWriteLock> READ_WRITE_LOCK_SUPPLIER = new Supplier<ReadWriteLock>() { @Override public ReadWriteLock get() { return new ReentrantReadWriteLock(); } }; private abstract static class PowerOfTwoStriped<L> extends Striped<L> { /** Capacity (power of two) minus one, for fast mod evaluation */ final int mask; PowerOfTwoStriped(int stripes) { Preconditions.checkArgument(stripes > 0, "Stripes must be positive"); this.mask = stripes > Ints.MAX_POWER_OF_TWO ? ALL_SET : ceilToPowerOfTwo(stripes) - 1; } @Override final int indexFor(Object key) { int hash = smear(key.hashCode()); return hash & mask; } @Override public final L get(Object key) { return getAt(indexFor(key)); } } /** * Implementation of Striped where 2^k stripes are represented as an array of the same length, * eagerly initialized. */ private static class CompactStriped<L> extends PowerOfTwoStriped<L> { /** Size is a power of two. */ private final Object[] array; private CompactStriped(int stripes, Supplier<L> supplier) { super(stripes); Preconditions.checkArgument(stripes <= Ints.MAX_POWER_OF_TWO, "Stripes must be <= 2^30)"); this.array = new Object[mask + 1]; for (int i = 0; i < array.length; i++) { array[i] = supplier.get(); } } @SuppressWarnings("unchecked") // we only put L's in the array @Override public L getAt(int index) { return (L) array[index]; } @Override public int size() { return array.length; } } /** * Implementation of Striped where up to 2^k stripes can be represented, using an * AtomicReferenceArray of size 2^k. To map a user key into a stripe, we take a k-bit slice of the * user key's (smeared) hashCode(). The stripes are lazily initialized and are weakly referenced. */ @VisibleForTesting static class SmallLazyStriped<L> extends PowerOfTwoStriped<L> { final AtomicReferenceArray<ArrayReference<? extends L>> locks; final Supplier<L> supplier; final int size; final ReferenceQueue<L> queue = new ReferenceQueue<L>(); SmallLazyStriped(int stripes, Supplier<L> supplier) { super(stripes); this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1; this.locks = new AtomicReferenceArray<ArrayReference<? extends L>>(size); this.supplier = supplier; } @Override public L getAt(int index) { if (size != Integer.MAX_VALUE) { Preconditions.checkElementIndex(index, size()); } // else no check necessary, all index values are valid ArrayReference<? extends L> existingRef = locks.get(index); L existing = existingRef == null ? null : existingRef.get(); if (existing != null) { return existing; } L created = supplier.get(); ArrayReference<L> newRef = new ArrayReference<L>(created, index, queue); while (!locks.compareAndSet(index, existingRef, newRef)) { // we raced, we need to re-read and try again existingRef = locks.get(index); existing = existingRef == null ? null : existingRef.get(); if (existing != null) { return existing; } } drainQueue(); return created; } // N.B. Draining the queue is only necessary to ensure that we don't accumulate empty references // in the array. We could skip this if we decide we don't care about holding on to Reference // objects indefinitely. private void drainQueue() { Reference<? extends L> ref; while ((ref = queue.poll()) != null) { // We only ever register ArrayReferences with the queue so this is always safe. ArrayReference<? extends L> arrayRef = (ArrayReference<? extends L>) ref; // Try to clear out the array slot, n.b. if we fail that is fine, in either case the // arrayRef will be out of the array after this step. locks.compareAndSet(arrayRef.index, arrayRef, null); } } @Override public int size() { return size; } private static final class ArrayReference<L> extends WeakReference<L> { final int index; ArrayReference(L referent, int index, ReferenceQueue<L> queue) { super(referent, queue); this.index = index; } } } /** * Implementation of Striped where up to 2^k stripes can be represented, using a ConcurrentMap * where the key domain is [0..2^k). To map a user key into a stripe, we take a k-bit slice of the * user key's (smeared) hashCode(). The stripes are lazily initialized and are weakly referenced. */ @VisibleForTesting static class LargeLazyStriped<L> extends PowerOfTwoStriped<L> { final ConcurrentMap<Integer, L> locks; final Supplier<L> supplier; final int size; LargeLazyStriped(int stripes, Supplier<L> supplier) { super(stripes); this.size = (mask == ALL_SET) ? Integer.MAX_VALUE : mask + 1; this.supplier = supplier; this.locks = new MapMaker().weakValues().makeMap(); } @Override public L getAt(int index) { if (size != Integer.MAX_VALUE) { Preconditions.checkElementIndex(index, size()); } // else no check necessary, all index values are valid L existing = locks.get(index); if (existing != null) { return existing; } L created = supplier.get(); existing = locks.putIfAbsent(index, created); return firstNonNull(existing, created); } @Override public int size() { return size; } } /** * A bit mask were all bits are set. */ private static final int ALL_SET = ~0; private static int ceilToPowerOfTwo(int x) { return 1 << IntMath.log2(x, RoundingMode.CEILING); } /* * This method was written by Doug Lea with assistance from members of JCP * JSR-166 Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain * * As of 2010/06/11, this method is identical to the (package private) hash * method in OpenJDK 7's java.util.HashMap class. */ // Copied from java/com/google/common/collect/Hashing.java private static int smear(int hashCode) { hashCode ^= (hashCode >>> 20) ^ (hashCode >>> 12); return hashCode ^ (hashCode >>> 7) ^ (hashCode >>> 4); } private static class PaddedLock extends ReentrantLock { /* * Padding from 40 into 64 bytes, same size as cache line. Might be beneficial to add * a fourth long here, to minimize chance of interference between consecutive locks, * but I couldn't observe any benefit from that. */ @SuppressWarnings("unused") long q1, q2, q3; PaddedLock() { super(false); } } private static class PaddedSemaphore extends Semaphore { // See PaddedReentrantLock comment @SuppressWarnings("unused") long q1, q2, q3; PaddedSemaphore(int permits) { super(permits, false); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/Striped.java
Java
asf20
18,934
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.collect.Queues; import java.util.Iterator; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; import java.util.concurrent.locks.ReentrantLock; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.ThreadSafe; /** * A thread-safe queue of listeners, each with an associated {@code Executor}, that guarantees * that every {@code Runnable} that is {@linkplain #add added} will be * {@link Executor#execute(Runnable) executed} in the same order that it was added. * * <p>While similar in structure and API to {@link ExecutionList}, this class differs in several * ways: * * <ul> * <li>This class makes strict ordering guarantees. ExecutionList makes no ordering guarantees. * <li>{@link ExecutionQueue#execute} executes all currently pending listeners. Later calls * to {@link ExecutionQueue#add} are delayed until the <em>next</em> call to execute. * {@link ExecutionList#execute()} executes all current listeners and also causes immediate * execution on subsequent calls to {@link ExecutionList#add}. * </ul> * * <p>These differences make {@link ExecutionQueue} suitable for when you need to execute callbacks * multiple times in response to different events. ExecutionList is suitable for when you have a * single event. * * <p>For example, this implements a simple atomic data structure that lets a listener * asynchronously listen to changes to a value: <pre> {@code * interface CountListener { * void update(int v); * } * * class AtomicListenableCounter { * private int value; * private final ExecutionQueue queue = new ExecutionQueue(); * private final CountListener listener; * private final Executor executor; * * AtomicListenableCounter(CountListener listener, Executor executor) { * this.listener = listener; * this.exeucutor = executor; * } * * void add(int amt) { * synchronized (this) { * v += amt; * final int currentValue = v; * queue.add(new Runnable() { * public void run() { * listener.update(currentValue); * } * }, executor); * } * queue.execute(); * } * }}</pre> * * <p>This AtomicListenableCounter allows a listener to be run asynchronously on every update and * the ExecutionQueue enforces that: * * <ul> * <li>The listener is never run with the lock held (even if the executor is the * {@link MoreExecutors#sameThreadExecutor()}) * <li>The listeners are never run out of order * <li>Each added listener is called only once. * </ul> * * <p>Exceptions thrown by a listener will be propagated up to the executor. Any exception thrown * during {@code Executor.execute} (e.g., a {@code RejectedExecutionException} or an exception * thrown by {@linkplain MoreExecutors#sameThreadExecutor inline execution}) will be caught and * logged. * * @author Luke Sandberg */ @ThreadSafe final class ExecutionQueue { private static final Logger logger = Logger.getLogger(ExecutionQueue.class.getName()); /** The listeners to execute in order. */ private final ConcurrentLinkedQueue<RunnableExecutorPair> queuedListeners = Queues.newConcurrentLinkedQueue(); /** * This lock is used with {@link RunnableExecutorPair#submit} to ensure that each listener is * executed at most once. */ private final ReentrantLock lock = new ReentrantLock(); /** * Adds the {@code Runnable} and accompanying {@code Executor} to the queue of listeners to * execute. * * <p>Note: This method will never directly invoke {@code executor.execute(runnable)}, though your * runnable may be executed before it returns if another thread has concurrently called * {@link #execute}. */ public void add(Runnable runnable, Executor executor) { queuedListeners.add(new RunnableExecutorPair(runnable, executor)); } /** * Executes all listeners in the queue. * * <p>Note that there is no guarantee that concurrently {@linkplain #add added} listeners will be * executed prior to the return of this method, only that all calls to {@link #add} that * happen-before this call will be executed. */ public void execute() { // We need to make sure that listeners are submitted to their executors in the correct order. So // we cannot remove a listener from the queue until we know that it has been submited to its // executor. So we use an iterator and only call remove after submit. This iterator is 'weakly // consistent' which means it observes the list in the correct order but not neccesarily all of // it (i.e. concurrently added or removed items may or may not be observed correctly by this // iterator). This is fine because 1. our contract says we may not execute all concurrently // added items and 2. calling listener.submit is idempotent, so it is safe (and generally cheap) // to call it multiple times. // TODO(user): we are relying on an underdocumented feature of ConcurrentLinkedQueue, the // general strategy in other JDK libraries appears to be bring-your-own-queue :( Consider doing // that. Iterator<RunnableExecutorPair> iterator = queuedListeners.iterator(); while (iterator.hasNext()) { iterator.next().submit(); iterator.remove(); } } /** * The listener object for the queue. * * <p>This ensures that: * <ol> * <li>{@link #executor executor}.{@link Executor#execute execute} is called at most once * <li>{@link #runnable runnable}.{@link Runnable#run run} is called at most once by the * executor * <li>{@link #lock lock} is not held when {@link #runnable runnable}.{@link Runnable#run run} * is called * <li>no thread calling {@link #submit} can return until the task has been accepted by the * executor * </ol> */ private final class RunnableExecutorPair implements Runnable { private final Executor executor; private final Runnable runnable; /** * Should be set to {@code true} after {@link #executor}.{@link Executor#execute execute} has * been called. */ @GuardedBy("lock") private boolean hasBeenExecuted = false; RunnableExecutorPair(Runnable runnable, Executor executor) { this.runnable = checkNotNull(runnable); this.executor = checkNotNull(executor); } /** Submit this listener to its executor */ private void submit() { lock.lock(); try { if (!hasBeenExecuted) { try { executor.execute(this); } catch (Exception e) { logger.log(Level.SEVERE, "Exception while executing listener " + runnable + " with executor " + executor, e); } } } finally { // If the executor was the sameThreadExecutor we may have already released the lock, so // check for that here. if (lock.isHeldByCurrentThread()) { hasBeenExecuted = true; lock.unlock(); } } } @Override public final void run() { // If the executor was the sameThreadExecutor then we might still be holding the lock and // hasBeenExecuted may not have been assigned yet so we unlock now to ensure that we are not // still holding the lock while execute is called. if (lock.isHeldByCurrentThread()) { hasBeenExecuted = true; lock.unlock(); } runnable.run(); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/ExecutionQueue.java
Java
asf20
8,334
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import java.util.concurrent.Callable; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; /** * An abstract {@code ScheduledExecutorService} that allows subclasses to * {@linkplain #wrapTask(Callable) wrap} tasks before they are submitted to the underlying executor. * * <p>Note that task wrapping may occur even if the task is never executed. * * @author Luke Sandberg */ abstract class WrappingScheduledExecutorService extends WrappingExecutorService implements ScheduledExecutorService { final ScheduledExecutorService delegate; protected WrappingScheduledExecutorService(ScheduledExecutorService delegate) { super(delegate); this.delegate = delegate; } @Override public final ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) { return delegate.schedule(wrapTask(command), delay, unit); } @Override public final <V> ScheduledFuture<V> schedule(Callable<V> task, long delay, TimeUnit unit) { return delegate.schedule(wrapTask(task), delay, unit); } @Override public final ScheduledFuture<?> scheduleAtFixedRate( Runnable command, long initialDelay, long period, TimeUnit unit) { return delegate.scheduleAtFixedRate(wrapTask(command), initialDelay, period, unit); } @Override public final ScheduledFuture<?> scheduleWithFixedDelay( Runnable command, long initialDelay, long delay, TimeUnit unit) { return delegate.scheduleWithFixedDelay(wrapTask(command), initialDelay, delay, unit); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/WrappingScheduledExecutorService.java
Java
asf20
2,225
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.collect.ForwardingObject; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * An executor service which forwards all its method calls to another executor * service. Subclasses should override one or more methods to modify the * behavior of the backing executor service as desired per the <a * href="http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * @author Kurt Alfred Kluever * @since 10.0 */ public abstract class ForwardingExecutorService extends ForwardingObject implements ExecutorService { /** Constructor for use by subclasses. */ protected ForwardingExecutorService() {} @Override protected abstract ExecutorService delegate(); @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return delegate().awaitTermination(timeout, unit); } @Override public <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks) throws InterruptedException { return delegate().invokeAll(tasks); } @Override public <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { return delegate().invokeAll(tasks, timeout, unit); } @Override public <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return delegate().invokeAny(tasks); } @Override public <T> T invokeAny( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate().invokeAny(tasks, timeout, unit); } @Override public boolean isShutdown() { return delegate().isShutdown(); } @Override public boolean isTerminated() { return delegate().isTerminated(); } @Override public void shutdown() { delegate().shutdown(); } @Override public List<Runnable> shutdownNow() { return delegate().shutdownNow(); } @Override public void execute(Runnable command) { delegate().execute(command); } public <T> Future<T> submit(Callable<T> task) { return delegate().submit(task); } @Override public Future<?> submit(Runnable task) { return delegate().submit(task); } @Override public <T> Future<T> submit(Runnable task, T result) { return delegate().submit(task, result); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/ForwardingExecutorService.java
Java
asf20
3,348
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import javax.annotation.Nullable; /** * A callback for accepting the results of a {@link java.util.concurrent.Future} * computation asynchronously. * * <p>To attach to a {@link ListenableFuture} use {@link Futures#addCallback}. * * @author Anthony Zana * @since 10.0 */ public interface FutureCallback<V> { /** * Invoked with the result of the {@code Future} computation when it is * successful. */ void onSuccess(@Nullable V result); /** * Invoked when a {@code Future} computation fails or is canceled. * * <p>If the future's {@link Future#get() get} method throws an {@link * ExecutionException}, then the cause is passed to this method. Any other * thrown object is passed unaltered. */ void onFailure(Throwable t); }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/FutureCallback.java
Java
asf20
1,498
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import javax.annotation.Nullable; /** * Unchecked version of {@link java.util.concurrent.TimeoutException}. * * @author Kevin Bourrillion * @since 1.0 */ public class UncheckedTimeoutException extends RuntimeException { public UncheckedTimeoutException() {} public UncheckedTimeoutException(@Nullable String message) { super(message); } public UncheckedTimeoutException(@Nullable Throwable cause) { super(cause); } public UncheckedTimeoutException(@Nullable String message, @Nullable Throwable cause) { super(message, cause); } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/UncheckedTimeoutException.java
Java
asf20
1,262
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * A future which forwards all its method calls to another future. Subclasses * should override one or more methods to modify the behavior of the backing * future as desired per the <a href= * "http://en.wikipedia.org/wiki/Decorator_pattern">decorator pattern</a>. * * <p>Most subclasses can simply extend {@link SimpleForwardingCheckedFuture}. * * @param <V> The result type returned by this Future's {@code get} method * @param <X> The type of the Exception thrown by the Future's * {@code checkedGet} method * * @author Anthony Zana * @since 9.0 */ @Beta public abstract class ForwardingCheckedFuture<V, X extends Exception> extends ForwardingListenableFuture<V> implements CheckedFuture<V, X> { @Override public V checkedGet() throws X { return delegate().checkedGet(); } @Override public V checkedGet(long timeout, TimeUnit unit) throws TimeoutException, X { return delegate().checkedGet(timeout, unit); } @Override protected abstract CheckedFuture<V, X> delegate(); // TODO(cpovirk): Use Standard Javadoc form for SimpleForwarding* /** * A simplified version of {@link ForwardingCheckedFuture} where subclasses * can pass in an already constructed {@link CheckedFuture} as the delegate. * * @since 9.0 */ @Beta public abstract static class SimpleForwardingCheckedFuture< V, X extends Exception> extends ForwardingCheckedFuture<V, X> { private final CheckedFuture<V, X> delegate; protected SimpleForwardingCheckedFuture(CheckedFuture<V, X> delegate) { this.delegate = Preconditions.checkNotNull(delegate); } @Override protected final CheckedFuture<V, X> delegate() { return delegate; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/ForwardingCheckedFuture.java
Java
asf20
2,549
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutorService; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; /** * An {@link ExecutorService} that returns {@link ListenableFuture} instances. To create an instance * from an existing {@link ExecutorService}, call * {@link MoreExecutors#listeningDecorator(ExecutorService)}. * * @author Chris Povirk * @since 10.0 */ public interface ListeningExecutorService extends ExecutorService { /** * @return a {@code ListenableFuture} representing pending completion of the task * @throws RejectedExecutionException {@inheritDoc} */ @Override <T> ListenableFuture<T> submit(Callable<T> task); /** * @return a {@code ListenableFuture} representing pending completion of the task * @throws RejectedExecutionException {@inheritDoc} */ @Override ListenableFuture<?> submit(Runnable task); /** * @return a {@code ListenableFuture} representing pending completion of the task * @throws RejectedExecutionException {@inheritDoc} */ @Override <T> ListenableFuture<T> submit(Runnable task, T result); /** * {@inheritDoc} * * <p>All elements in the returned list must be {@link ListenableFuture} instances. The easiest * way to obtain a {@code List<ListenableFuture<T>>} from this method is an unchecked (but safe) * cast:<pre> * {@code @SuppressWarnings("unchecked") // guaranteed by invokeAll contract} * {@code List<ListenableFuture<T>> futures = (List) executor.invokeAll(tasks);} * </pre> * * @return A list of {@code ListenableFuture} instances representing the tasks, in the same * sequential order as produced by the iterator for the given task list, each of which has * completed. * @throws RejectedExecutionException {@inheritDoc} * @throws NullPointerException if any task is null */ @Override <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException; /** * {@inheritDoc} * * <p>All elements in the returned list must be {@link ListenableFuture} instances. The easiest * way to obtain a {@code List<ListenableFuture<T>>} from this method is an unchecked (but safe) * cast:<pre> * {@code @SuppressWarnings("unchecked") // guaranteed by invokeAll contract} * {@code List<ListenableFuture<T>> futures = (List) executor.invokeAll(tasks, timeout, unit);} * </pre> * * @return a list of {@code ListenableFuture} instances representing the tasks, in the same * sequential order as produced by the iterator for the given task list. If the operation * did not time out, each task will have completed. If it did time out, some of these * tasks will not have completed. * @throws RejectedExecutionException {@inheritDoc} * @throws NullPointerException if any task is null */ @Override <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException; }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/ListeningExecutorService.java
Java
asf20
3,817
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Throwables; import com.google.common.collect.ImmutableList; import java.util.Collection; import java.util.List; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * An abstract {@code ExecutorService} that allows subclasses to * {@linkplain #wrapTask(Callable) wrap} tasks before they are submitted * to the underlying executor. * * <p>Note that task wrapping may occur even if the task is never executed. * * <p>For delegation without task-wrapping, see * {@link ForwardingExecutorService}. * * @author Chris Nokleberg */ abstract class WrappingExecutorService implements ExecutorService { private final ExecutorService delegate; protected WrappingExecutorService(ExecutorService delegate) { this.delegate = checkNotNull(delegate); } /** * Wraps a {@code Callable} for submission to the underlying executor. This * method is also applied to any {@code Runnable} passed to the default * implementation of {@link #wrapTest(Runnable)}. */ protected abstract <T> Callable<T> wrapTask(Callable<T> callable); /** * Wraps a {@code Runnable} for submission to the underlying executor. The * default implementation delegates to {@link #wrapTask(Callable)}. */ protected Runnable wrapTask(Runnable command) { final Callable<Object> wrapped = wrapTask( Executors.callable(command, null)); return new Runnable() { @Override public void run() { try { wrapped.call(); } catch (Exception e) { Throwables.propagate(e); } } }; } /** * Wraps a collection of tasks. * * @throws NullPointerException if any element of {@code tasks} is null */ private final <T> ImmutableList<Callable<T>> wrapTasks( Collection<? extends Callable<T>> tasks) { ImmutableList.Builder<Callable<T>> builder = ImmutableList.builder(); for (Callable<T> task : tasks) { builder.add(wrapTask(task)); } return builder.build(); } // These methods wrap before delegating. @Override public final void execute(Runnable command) { delegate.execute(wrapTask(command)); } @Override public final <T> Future<T> submit(Callable<T> task) { return delegate.submit(wrapTask(checkNotNull(task))); } @Override public final Future<?> submit(Runnable task) { return delegate.submit(wrapTask(task)); } @Override public final <T> Future<T> submit(Runnable task, T result) { return delegate.submit(wrapTask(task), result); } @Override public final <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks) throws InterruptedException { return delegate.invokeAll(wrapTasks(tasks)); } @Override public final <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException { return delegate.invokeAll(wrapTasks(tasks), timeout, unit); } @Override public final <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException { return delegate.invokeAny(wrapTasks(tasks)); } @Override public final <T> T invokeAny( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException { return delegate.invokeAny(wrapTasks(tasks), timeout, unit); } // The remaining methods just delegate. @Override public final void shutdown() { delegate.shutdown(); } @Override public final List<Runnable> shutdownNow() { return delegate.shutdownNow(); } @Override public final boolean isShutdown() { return delegate.isShutdown(); } @Override public final boolean isTerminated() { return delegate.isTerminated(); } @Override public final boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return delegate.awaitTermination(timeout, unit); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/WrappingExecutorService.java
Java
asf20
4,930
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static java.util.concurrent.TimeUnit.NANOSECONDS; import com.google.common.annotations.Beta; import com.google.common.base.Preconditions; import java.util.concurrent.BlockingQueue; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * Utilities for treating interruptible operations as uninterruptible. * In all cases, if a thread is interrupted during such a call, the call * continues to block until the result is available or the timeout elapses, * and only then re-interrupts the thread. * * @author Anthony Zana * @since 10.0 */ @Beta public final class Uninterruptibles { // Implementation Note: As of 3-7-11, the logic for each blocking/timeout // methods is identical, save for method being invoked. /** * Invokes {@code latch.}{@link CountDownLatch#await() await()} * uninterruptibly. */ public static void awaitUninterruptibly(CountDownLatch latch) { boolean interrupted = false; try { while (true) { try { latch.await(); return; } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes * {@code latch.}{@link CountDownLatch#await(long, TimeUnit) * await(timeout, unit)} uninterruptibly. */ public static boolean awaitUninterruptibly(CountDownLatch latch, long timeout, TimeUnit unit) { boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // CountDownLatch treats negative timeouts just like zero. return latch.await(remainingNanos, NANOSECONDS); } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes {@code toJoin.}{@link Thread#join() join()} uninterruptibly. */ public static void joinUninterruptibly(Thread toJoin) { boolean interrupted = false; try { while (true) { try { toJoin.join(); return; } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes {@code future.}{@link Future#get() get()} uninterruptibly. * To get uninterruptibility and remove checked exceptions, see * {@link Futures#getUnchecked}. * * <p>If instead, you wish to treat {@link InterruptedException} uniformly * with other exceptions, see {@link Futures#get(Future, Class) Futures.get} * or {@link Futures#makeChecked}. * * @throws ExecutionException if the computation threw an exception * @throws CancellationException if the computation was cancelled */ public static <V> V getUninterruptibly(Future<V> future) throws ExecutionException { boolean interrupted = false; try { while (true) { try { return future.get(); } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes * {@code future.}{@link Future#get(long, TimeUnit) get(timeout, unit)} * uninterruptibly. * * <p>If instead, you wish to treat {@link InterruptedException} uniformly * with other exceptions, see {@link Futures#get(Future, Class) Futures.get} * or {@link Futures#makeChecked}. * * @throws ExecutionException if the computation threw an exception * @throws CancellationException if the computation was cancelled * @throws TimeoutException if the wait timed out */ public static <V> V getUninterruptibly( Future<V> future, long timeout, TimeUnit unit) throws ExecutionException, TimeoutException { boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // Future treats negative timeouts just like zero. return future.get(remainingNanos, NANOSECONDS); } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes * {@code unit.}{@link TimeUnit#timedJoin(Thread, long) * timedJoin(toJoin, timeout)} uninterruptibly. */ public static void joinUninterruptibly(Thread toJoin, long timeout, TimeUnit unit) { Preconditions.checkNotNull(toJoin); boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // TimeUnit.timedJoin() treats negative timeouts just like zero. NANOSECONDS.timedJoin(toJoin, remainingNanos); return; } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes {@code queue.}{@link BlockingQueue#take() take()} uninterruptibly. */ public static <E> E takeUninterruptibly(BlockingQueue<E> queue) { boolean interrupted = false; try { while (true) { try { return queue.take(); } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } /** * Invokes {@code queue.}{@link BlockingQueue#put(Object) put(element)} * uninterruptibly. * * @throws ClassCastException if the class of the specified element prevents * it from being added to the given queue * @throws IllegalArgumentException if some property of the specified element * prevents it from being added to the given queue */ public static <E> void putUninterruptibly(BlockingQueue<E> queue, E element) { boolean interrupted = false; try { while (true) { try { queue.put(element); return; } catch (InterruptedException e) { interrupted = true; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } // TODO(user): Support Sleeper somehow (wrapper or interface method)? /** * Invokes {@code unit.}{@link TimeUnit#sleep(long) sleep(sleepFor)} * uninterruptibly. */ public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) { boolean interrupted = false; try { long remainingNanos = unit.toNanos(sleepFor); long end = System.nanoTime() + remainingNanos; while (true) { try { // TimeUnit.sleep() treats negative timeouts just like zero. NANOSECONDS.sleep(remainingNanos); return; } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } // TODO(user): Add support for waitUninterruptibly. private Uninterruptibles() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/Uninterruptibles.java
Java
asf20
8,408
/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ /* * Source: * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/jsr166e/extra/AtomicDoubleArray.java?revision=1.5 * (Modified to adapt to guava coding conventions and * to use AtomicLongArray instead of sun.misc.Unsafe) */ package com.google.common.util.concurrent; import static java.lang.Double.doubleToRawLongBits; import static java.lang.Double.longBitsToDouble; import java.util.concurrent.atomic.AtomicLongArray; /** * A {@code double} array in which elements may be updated atomically. * See the {@link java.util.concurrent.atomic} package specification * for description of the properties of atomic variables. * * <p><a name="bitEquals">This class compares primitive {@code double} * values in methods such as {@link #compareAndSet} by comparing their * bitwise representation using {@link Double#doubleToRawLongBits}, * which differs from both the primitive double {@code ==} operator * and from {@link Double#equals}, as if implemented by: * <pre> {@code * static boolean bitEquals(double x, double y) { * long xBits = Double.doubleToRawLongBits(x); * long yBits = Double.doubleToRawLongBits(y); * return xBits == yBits; * }}</pre> * * @author Doug Lea * @author Martin Buchholz * @since 11.0 */ public class AtomicDoubleArray implements java.io.Serializable { private static final long serialVersionUID = 0L; // Making this non-final is the lesser evil according to Effective // Java 2nd Edition Item 76: Write readObject methods defensively. private transient AtomicLongArray longs; /** * Creates a new {@code AtomicDoubleArray} of the given length, * with all elements initially zero. * * @param length the length of the array */ public AtomicDoubleArray(int length) { this.longs = new AtomicLongArray(length); } /** * Creates a new {@code AtomicDoubleArray} with the same length * as, and all elements copied from, the given array. * * @param array the array to copy elements from * @throws NullPointerException if array is null */ public AtomicDoubleArray(double[] array) { final int len = array.length; long[] longArray = new long[len]; for (int i = 0; i < len; i++) { longArray[i] = doubleToRawLongBits(array[i]); } this.longs = new AtomicLongArray(longArray); } /** * Returns the length of the array. * * @return the length of the array */ public final int length() { return longs.length(); } /** * Gets the current value at position {@code i}. * * @param i the index * @return the current value */ public final double get(int i) { return longBitsToDouble(longs.get(i)); } /** * Sets the element at position {@code i} to the given value. * * @param i the index * @param newValue the new value */ public final void set(int i, double newValue) { long next = doubleToRawLongBits(newValue); longs.set(i, next); } /** * Eventually sets the element at position {@code i} to the given value. * * @param i the index * @param newValue the new value */ public final void lazySet(int i, double newValue) { set(i, newValue); // TODO(user): replace with code below when jdk5 support is dropped. // long next = doubleToRawLongBits(newValue); // longs.lazySet(i, next); } /** * Atomically sets the element at position {@code i} to the given value * and returns the old value. * * @param i the index * @param newValue the new value * @return the previous value */ public final double getAndSet(int i, double newValue) { long next = doubleToRawLongBits(newValue); return longBitsToDouble(longs.getAndSet(i, next)); } /** * Atomically sets the element at position {@code i} to the given * updated value * if the current value is <a href="#bitEquals">bitwise equal</a> * to the expected value. * * @param i the index * @param expect the expected value * @param update the new value * @return true if successful. False return indicates that * the actual value was not equal to the expected value. */ public final boolean compareAndSet(int i, double expect, double update) { return longs.compareAndSet(i, doubleToRawLongBits(expect), doubleToRawLongBits(update)); } /** * Atomically sets the element at position {@code i} to the given * updated value * if the current value is <a href="#bitEquals">bitwise equal</a> * to the expected value. * * <p>May <a * href="http://download.oracle.com/javase/7/docs/api/java/util/concurrent/atomic/package-summary.html#Spurious"> * fail spuriously</a> * and does not provide ordering guarantees, so is only rarely an * appropriate alternative to {@code compareAndSet}. * * @param i the index * @param expect the expected value * @param update the new value * @return true if successful */ public final boolean weakCompareAndSet(int i, double expect, double update) { return longs.weakCompareAndSet(i, doubleToRawLongBits(expect), doubleToRawLongBits(update)); } /** * Atomically adds the given value to the element at index {@code i}. * * @param i the index * @param delta the value to add * @return the previous value */ public final double getAndAdd(int i, double delta) { while (true) { long current = longs.get(i); double currentVal = longBitsToDouble(current); double nextVal = currentVal + delta; long next = doubleToRawLongBits(nextVal); if (longs.compareAndSet(i, current, next)) { return currentVal; } } } /** * Atomically adds the given value to the element at index {@code i}. * * @param i the index * @param delta the value to add * @return the updated value */ public double addAndGet(int i, double delta) { while (true) { long current = longs.get(i); double currentVal = longBitsToDouble(current); double nextVal = currentVal + delta; long next = doubleToRawLongBits(nextVal); if (longs.compareAndSet(i, current, next)) { return nextVal; } } } /** * Returns the String representation of the current values of array. * @return the String representation of the current values of array */ public String toString() { int iMax = length() - 1; if (iMax == -1) { return "[]"; } // Double.toString(Math.PI).length() == 17 StringBuilder b = new StringBuilder((17 + 2) * (iMax + 1)); b.append('['); for (int i = 0;; i++) { b.append(longBitsToDouble(longs.get(i))); if (i == iMax) { return b.append(']').toString(); } b.append(',').append(' '); } } /** * Saves the state to a stream (that is, serializes it). * * @serialData The length of the array is emitted (int), followed by all * of its elements (each a {@code double}) in the proper order. */ private void writeObject(java.io.ObjectOutputStream s) throws java.io.IOException { s.defaultWriteObject(); // Write out array length int length = length(); s.writeInt(length); // Write out all elements in the proper order. for (int i = 0; i < length; i++) { s.writeDouble(get(i)); } } /** * Reconstitutes the instance from a stream (that is, deserializes it). */ private void readObject(java.io.ObjectInputStream s) throws java.io.IOException, ClassNotFoundException { s.defaultReadObject(); // Read in array length and allocate array int length = s.readInt(); this.longs = new AtomicLongArray(length); // Read in all elements in the proper order. for (int i = 0; i < length; i++) { set(i, s.readDouble()); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/AtomicDoubleArray.java
Java
asf20
8,085
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.util.concurrent.Service.State.FAILED; import static com.google.common.util.concurrent.Service.State.NEW; import static com.google.common.util.concurrent.Service.State.RUNNING; import static com.google.common.util.concurrent.Service.State.STARTING; import static com.google.common.util.concurrent.Service.State.STOPPING; import static com.google.common.util.concurrent.Service.State.TERMINATED; import com.google.common.annotations.Beta; import com.google.common.collect.Lists; import com.google.common.util.concurrent.Monitor.Guard; import com.google.common.util.concurrent.Service.State; // javadoc needs this import java.util.List; import java.util.concurrent.Executor; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import javax.annotation.Nullable; import javax.annotation.concurrent.GuardedBy; import javax.annotation.concurrent.Immutable; /** * Base class for implementing services that can handle {@link #doStart} and {@link #doStop} * requests, responding to them with {@link #notifyStarted()} and {@link #notifyStopped()} * callbacks. Its subclasses must manage threads manually; consider * {@link AbstractExecutionThreadService} if you need only a single execution thread. * * @author Jesse Wilson * @author Luke Sandberg * @since 1.0 */ @Beta public abstract class AbstractService implements Service { private final Monitor monitor = new Monitor(); private final Guard isStartable = new Guard(monitor) { @Override public boolean isSatisfied() { return state() == NEW; } }; private final Guard isStoppable = new Guard(monitor) { @Override public boolean isSatisfied() { return state().compareTo(RUNNING) <= 0; } }; private final Guard hasReachedRunning = new Guard(monitor) { @Override public boolean isSatisfied() { return state().compareTo(RUNNING) >= 0; } }; private final Guard isStopped = new Guard(monitor) { @Override public boolean isSatisfied() { return state().isTerminal(); } }; /** * The listeners to notify during a state transition. */ @GuardedBy("monitor") private final List<ListenerExecutorPair> listeners = Lists.newArrayList(); /** * The queue of listeners that are waiting to be executed. * * <p>Enqueue operations should be protected by {@link #monitor} while calling * {@link ExecutionQueue#execute()} should not be protected. */ private final ExecutionQueue queuedListeners = new ExecutionQueue(); /** * The current state of the service. This should be written with the lock held but can be read * without it because it is an immutable object in a volatile field. This is desirable so that * methods like {@link #state}, {@link #failureCause} and notably {@link #toString} can be run * without grabbing the lock. * * <p>To update this field correctly the lock must be held to guarantee that the state is * consistent. */ @GuardedBy("monitor") private volatile StateSnapshot snapshot = new StateSnapshot(NEW); /** Constructor for use by subclasses. */ protected AbstractService() {} /** * This method is called by {@link #startAsync} to initiate service startup. The invocation of * this method should cause a call to {@link #notifyStarted()}, either during this method's run, * or after it has returned. If startup fails, the invocation should cause a call to * {@link #notifyFailed(Throwable)} instead. * * <p>This method should return promptly; prefer to do work on a different thread where it is * convenient. It is invoked exactly once on service startup, even when {@link #startAsync} is * called multiple times. */ protected abstract void doStart(); /** * This method should be used to initiate service shutdown. The invocation of this method should * cause a call to {@link #notifyStopped()}, either during this method's run, or after it has * returned. If shutdown fails, the invocation should cause a call to * {@link #notifyFailed(Throwable)} instead. * * <p> This method should return promptly; prefer to do work on a different thread where it is * convenient. It is invoked exactly once on service shutdown, even when {@link #stopAsync} is * called multiple times. */ protected abstract void doStop(); @Override public final Service startAsync() { if (monitor.enterIf(isStartable)) { try { snapshot = new StateSnapshot(STARTING); starting(); doStart(); // TODO(user): justify why we are catching Throwable and not RuntimeException } catch (Throwable startupFailure) { notifyFailed(startupFailure); } finally { monitor.leave(); executeListeners(); } } else { throw new IllegalStateException("Service " + this + " has already been started"); } return this; } @Override public final Service stopAsync() { if (monitor.enterIf(isStoppable)) { try { State previous = state(); switch (previous) { case NEW: snapshot = new StateSnapshot(TERMINATED); terminated(NEW); break; case STARTING: snapshot = new StateSnapshot(STARTING, true, null); stopping(STARTING); break; case RUNNING: snapshot = new StateSnapshot(STOPPING); stopping(RUNNING); doStop(); break; case STOPPING: case TERMINATED: case FAILED: // These cases are impossible due to the if statement above. throw new AssertionError("isStoppable is incorrectly implemented, saw: " + previous); default: throw new AssertionError("Unexpected state: " + previous); } // TODO(user): justify why we are catching Throwable and not RuntimeException. Also, we // may inadvertently catch our AssertionErrors. } catch (Throwable shutdownFailure) { notifyFailed(shutdownFailure); } finally { monitor.leave(); executeListeners(); } } return this; } @Override public final void awaitRunning() { monitor.enterWhenUninterruptibly(hasReachedRunning); try { checkCurrentState(RUNNING); } finally { monitor.leave(); } } @Override public final void awaitRunning(long timeout, TimeUnit unit) throws TimeoutException { if (monitor.enterWhenUninterruptibly(hasReachedRunning, timeout, unit)) { try { checkCurrentState(RUNNING); } finally { monitor.leave(); } } else { // It is possible due to races the we are currently in the expected state even though we // timed out. e.g. if we weren't event able to grab the lock within the timeout we would never // even check the guard. I don't think we care too much about this use case but it could lead // to a confusing error message. throw new TimeoutException("Timed out waiting for " + this + " to reach the RUNNING state. " + "Current state: " + state()); } } @Override public final void awaitTerminated() { monitor.enterWhenUninterruptibly(isStopped); try { checkCurrentState(TERMINATED); } finally { monitor.leave(); } } @Override public final void awaitTerminated(long timeout, TimeUnit unit) throws TimeoutException { if (monitor.enterWhenUninterruptibly(isStopped, timeout, unit)) { try { checkCurrentState(TERMINATED); } finally { monitor.leave(); } } else { // It is possible due to races the we are currently in the expected state even though we // timed out. e.g. if we weren't event able to grab the lock within the timeout we would never // even check the guard. I don't think we care too much about this use case but it could lead // to a confusing error message. throw new TimeoutException("Timed out waiting for " + this + " to reach a terminal state. " + "Current state: " + state()); } } /** Checks that the current state is equal to the expected state. */ @GuardedBy("monitor") private void checkCurrentState(State expected) { State actual = state(); if (actual != expected) { if (actual == FAILED) { // Handle this specially so that we can include the failureCause, if there is one. throw new IllegalStateException("Expected the service to be " + expected + ", but the service has FAILED", failureCause()); } throw new IllegalStateException("Expected the service to be " + expected + ", but was " + actual); } } /** * Implementing classes should invoke this method once their service has started. It will cause * the service to transition from {@link State#STARTING} to {@link State#RUNNING}. * * @throws IllegalStateException if the service is not {@link State#STARTING}. */ protected final void notifyStarted() { monitor.enter(); try { // We have to examine the internal state of the snapshot here to properly handle the stop // while starting case. if (snapshot.state != STARTING) { IllegalStateException failure = new IllegalStateException( "Cannot notifyStarted() when the service is " + snapshot.state); notifyFailed(failure); throw failure; } if (snapshot.shutdownWhenStartupFinishes) { snapshot = new StateSnapshot(STOPPING); // We don't call listeners here because we already did that when we set the // shutdownWhenStartupFinishes flag. doStop(); } else { snapshot = new StateSnapshot(RUNNING); running(); } } finally { monitor.leave(); executeListeners(); } } /** * Implementing classes should invoke this method once their service has stopped. It will cause * the service to transition from {@link State#STOPPING} to {@link State#TERMINATED}. * * @throws IllegalStateException if the service is neither {@link State#STOPPING} nor * {@link State#RUNNING}. */ protected final void notifyStopped() { monitor.enter(); try { // We check the internal state of the snapshot instead of state() directly so we don't allow // notifyStopped() to be called while STARTING, even if stop() has already been called. State previous = snapshot.state; if (previous != STOPPING && previous != RUNNING) { IllegalStateException failure = new IllegalStateException( "Cannot notifyStopped() when the service is " + previous); notifyFailed(failure); throw failure; } snapshot = new StateSnapshot(TERMINATED); terminated(previous); } finally { monitor.leave(); executeListeners(); } } /** * Invoke this method to transition the service to the {@link State#FAILED}. The service will * <b>not be stopped</b> if it is running. Invoke this method when a service has failed critically * or otherwise cannot be started nor stopped. */ protected final void notifyFailed(Throwable cause) { checkNotNull(cause); monitor.enter(); try { State previous = state(); switch (previous) { case NEW: case TERMINATED: throw new IllegalStateException("Failed while in state:" + previous, cause); case RUNNING: case STARTING: case STOPPING: snapshot = new StateSnapshot(FAILED, false, cause); failed(previous, cause); break; case FAILED: // Do nothing break; default: throw new AssertionError("Unexpected state: " + previous); } } finally { monitor.leave(); executeListeners(); } } @Override public final boolean isRunning() { return state() == RUNNING; } @Override public final State state() { return snapshot.externalState(); } /** * @since 14.0 */ @Override public final Throwable failureCause() { return snapshot.failureCause(); } /** * @since 13.0 */ @Override public final void addListener(Listener listener, Executor executor) { checkNotNull(listener, "listener"); checkNotNull(executor, "executor"); monitor.enter(); try { State currentState = state(); if (currentState != TERMINATED && currentState != FAILED) { listeners.add(new ListenerExecutorPair(listener, executor)); } } finally { monitor.leave(); } } @Override public String toString() { return getClass().getSimpleName() + " [" + state() + "]"; } /** * Attempts to execute all the listeners in {@link #queuedListeners} while not holding the * {@link #monitor}. */ private void executeListeners() { if (!monitor.isOccupiedByCurrentThread()) { queuedListeners.execute(); } } @GuardedBy("monitor") private void starting() { for (final ListenerExecutorPair pair : listeners) { queuedListeners.add(new Runnable() { @Override public void run() { pair.listener.starting(); } }, pair.executor); } } @GuardedBy("monitor") private void running() { for (final ListenerExecutorPair pair : listeners) { queuedListeners.add(new Runnable() { @Override public void run() { pair.listener.running(); } }, pair.executor); } } @GuardedBy("monitor") private void stopping(final State from) { for (final ListenerExecutorPair pair : listeners) { queuedListeners.add(new Runnable() { @Override public void run() { pair.listener.stopping(from); } }, pair.executor); } } @GuardedBy("monitor") private void terminated(final State from) { for (final ListenerExecutorPair pair : listeners) { queuedListeners.add(new Runnable() { @Override public void run() { pair.listener.terminated(from); } }, pair.executor); } // There are no more state transitions so we can clear this out. listeners.clear(); } @GuardedBy("monitor") private void failed(final State from, final Throwable cause) { for (final ListenerExecutorPair pair : listeners) { queuedListeners.add(new Runnable() { @Override public void run() { pair.listener.failed(from, cause); } }, pair.executor); } // There are no more state transitions so we can clear this out. listeners.clear(); } /** A simple holder for a listener and its executor. */ private static class ListenerExecutorPair { final Listener listener; final Executor executor; ListenerExecutorPair(Listener listener, Executor executor) { this.listener = listener; this.executor = executor; } } /** * An immutable snapshot of the current state of the service. This class represents a consistent * snapshot of the state and therefore it can be used to answer simple queries without needing to * grab a lock. */ @Immutable private static final class StateSnapshot { /** * The internal state, which equals external state unless * shutdownWhenStartupFinishes is true. */ final State state; /** * If true, the user requested a shutdown while the service was still starting * up. */ final boolean shutdownWhenStartupFinishes; /** * The exception that caused this service to fail. This will be {@code null} * unless the service has failed. */ @Nullable final Throwable failure; StateSnapshot(State internalState) { this(internalState, false, null); } StateSnapshot( State internalState, boolean shutdownWhenStartupFinishes, @Nullable Throwable failure) { checkArgument(!shutdownWhenStartupFinishes || internalState == STARTING, "shudownWhenStartupFinishes can only be set if state is STARTING. Got %s instead.", internalState); checkArgument(!(failure != null ^ internalState == FAILED), "A failure cause should be set if and only if the state is failed. Got %s and %s " + "instead.", internalState, failure); this.state = internalState; this.shutdownWhenStartupFinishes = shutdownWhenStartupFinishes; this.failure = failure; } /** @see Service#state() */ State externalState() { if (shutdownWhenStartupFinishes && state == STARTING) { return STOPPING; } else { return state; } } /** @see Service#failureCause() */ Throwable failureCause() { checkState(state == FAILED, "failureCause() is only valid if the service has failed, service is %s", state); return failure; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/AbstractService.java
Java
asf20
17,688
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Supplier; import com.google.common.base.Throwables; import com.google.common.collect.Lists; import com.google.common.collect.Queues; import com.google.common.util.concurrent.ForwardingListenableFuture.SimpleForwardingListenableFuture; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.Callable; import java.util.concurrent.Delayed; import java.util.concurrent.ExecutionException; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledExecutorService; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.ScheduledThreadPoolExecutor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.ThreadPoolExecutor.CallerRunsPolicy; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; /** * Factory and utility methods for {@link java.util.concurrent.Executor}, {@link * ExecutorService}, and {@link ThreadFactory}. * * @author Eric Fellheimer * @author Kyle Littlefield * @author Justin Mahoney * @since 3.0 */ public final class MoreExecutors { private MoreExecutors() {} /** * Converts the given ThreadPoolExecutor into an ExecutorService that exits * when the application is complete. It does so by using daemon threads and * adding a shutdown hook to wait for their completion. * * <p>This is mainly for fixed thread pools. * See {@link Executors#newFixedThreadPool(int)}. * * @param executor the executor to modify to make sure it exits when the * application is finished * @param terminationTimeout how long to wait for the executor to * finish before terminating the JVM * @param timeUnit unit of time for the time parameter * @return an unmodifiable version of the input which will not hang the JVM */ @Beta public static ExecutorService getExitingExecutorService( ThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) { return new Application() .getExitingExecutorService(executor, terminationTimeout, timeUnit); } /** * Converts the given ScheduledThreadPoolExecutor into a * ScheduledExecutorService that exits when the application is complete. It * does so by using daemon threads and adding a shutdown hook to wait for * their completion. * * <p>This is mainly for fixed thread pools. * See {@link Executors#newScheduledThreadPool(int)}. * * @param executor the executor to modify to make sure it exits when the * application is finished * @param terminationTimeout how long to wait for the executor to * finish before terminating the JVM * @param timeUnit unit of time for the time parameter * @return an unmodifiable version of the input which will not hang the JVM */ @Beta public static ScheduledExecutorService getExitingScheduledExecutorService( ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) { return new Application() .getExitingScheduledExecutorService(executor, terminationTimeout, timeUnit); } /** * Add a shutdown hook to wait for thread completion in the given * {@link ExecutorService service}. This is useful if the given service uses * daemon threads, and we want to keep the JVM from exiting immediately on * shutdown, instead giving these daemon threads a chance to terminate * normally. * @param service ExecutorService which uses daemon threads * @param terminationTimeout how long to wait for the executor to finish * before terminating the JVM * @param timeUnit unit of time for the time parameter */ @Beta public static void addDelayedShutdownHook( ExecutorService service, long terminationTimeout, TimeUnit timeUnit) { new Application() .addDelayedShutdownHook(service, terminationTimeout, timeUnit); } /** * Converts the given ThreadPoolExecutor into an ExecutorService that exits * when the application is complete. It does so by using daemon threads and * adding a shutdown hook to wait for their completion. * * <p>This method waits 120 seconds before continuing with JVM termination, * even if the executor has not finished its work. * * <p>This is mainly for fixed thread pools. * See {@link Executors#newFixedThreadPool(int)}. * * @param executor the executor to modify to make sure it exits when the * application is finished * @return an unmodifiable version of the input which will not hang the JVM */ @Beta public static ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) { return new Application().getExitingExecutorService(executor); } /** * Converts the given ThreadPoolExecutor into a ScheduledExecutorService that * exits when the application is complete. It does so by using daemon threads * and adding a shutdown hook to wait for their completion. * * <p>This method waits 120 seconds before continuing with JVM termination, * even if the executor has not finished its work. * * <p>This is mainly for fixed thread pools. * See {@link Executors#newScheduledThreadPool(int)}. * * @param executor the executor to modify to make sure it exits when the * application is finished * @return an unmodifiable version of the input which will not hang the JVM */ @Beta public static ScheduledExecutorService getExitingScheduledExecutorService( ScheduledThreadPoolExecutor executor) { return new Application().getExitingScheduledExecutorService(executor); } /** Represents the current application to register shutdown hooks. */ @VisibleForTesting static class Application { final ExecutorService getExitingExecutorService( ThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) { useDaemonThreadFactory(executor); ExecutorService service = Executors.unconfigurableExecutorService(executor); addDelayedShutdownHook(service, terminationTimeout, timeUnit); return service; } final ScheduledExecutorService getExitingScheduledExecutorService( ScheduledThreadPoolExecutor executor, long terminationTimeout, TimeUnit timeUnit) { useDaemonThreadFactory(executor); ScheduledExecutorService service = Executors.unconfigurableScheduledExecutorService(executor); addDelayedShutdownHook(service, terminationTimeout, timeUnit); return service; } final void addDelayedShutdownHook( final ExecutorService service, final long terminationTimeout, final TimeUnit timeUnit) { checkNotNull(service); checkNotNull(timeUnit); addShutdownHook(MoreExecutors.newThread("DelayedShutdownHook-for-" + service, new Runnable() { @Override public void run() { try { // We'd like to log progress and failures that may arise in the // following code, but unfortunately the behavior of logging // is undefined in shutdown hooks. // This is because the logging code installs a shutdown hook of its // own. See Cleaner class inside {@link LogManager}. service.shutdown(); service.awaitTermination(terminationTimeout, timeUnit); } catch (InterruptedException ignored) { // We're shutting down anyway, so just ignore. } } })); } final ExecutorService getExitingExecutorService(ThreadPoolExecutor executor) { return getExitingExecutorService(executor, 120, TimeUnit.SECONDS); } final ScheduledExecutorService getExitingScheduledExecutorService( ScheduledThreadPoolExecutor executor) { return getExitingScheduledExecutorService(executor, 120, TimeUnit.SECONDS); } @VisibleForTesting void addShutdownHook(Thread hook) { Runtime.getRuntime().addShutdownHook(hook); } } private static void useDaemonThreadFactory(ThreadPoolExecutor executor) { executor.setThreadFactory(new ThreadFactoryBuilder() .setDaemon(true) .setThreadFactory(executor.getThreadFactory()) .build()); } /** * Creates an executor service that runs each task in the thread * that invokes {@code execute/submit}, as in {@link CallerRunsPolicy} This * applies both to individually submitted tasks and to collections of tasks * submitted via {@code invokeAll} or {@code invokeAny}. In the latter case, * tasks will run serially on the calling thread. Tasks are run to * completion before a {@code Future} is returned to the caller (unless the * executor has been shutdown). * * <p>Although all tasks are immediately executed in the thread that * submitted the task, this {@code ExecutorService} imposes a small * locking overhead on each task submission in order to implement shutdown * and termination behavior. * * <p>The implementation deviates from the {@code ExecutorService} * specification with regards to the {@code shutdownNow} method. First, * "best-effort" with regards to canceling running tasks is implemented * as "no-effort". No interrupts or other attempts are made to stop * threads executing tasks. Second, the returned list will always be empty, * as any submitted task is considered to have started execution. * This applies also to tasks given to {@code invokeAll} or {@code invokeAny} * which are pending serial execution, even the subset of the tasks that * have not yet started execution. It is unclear from the * {@code ExecutorService} specification if these should be included, and * it's much easier to implement the interpretation that they not be. * Finally, a call to {@code shutdown} or {@code shutdownNow} may result * in concurrent calls to {@code invokeAll/invokeAny} throwing * RejectedExecutionException, although a subset of the tasks may already * have been executed. * * @since 10.0 (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility" * >mostly source-compatible</a> since 3.0) */ public static ListeningExecutorService sameThreadExecutor() { return new SameThreadExecutorService(); } // See sameThreadExecutor javadoc for behavioral notes. private static class SameThreadExecutorService extends AbstractListeningExecutorService { /** * Lock used whenever accessing the state variables * (runningTasks, shutdown, terminationCondition) of the executor */ private final Lock lock = new ReentrantLock(); /** Signaled after the executor is shutdown and running tasks are done */ private final Condition termination = lock.newCondition(); /* * Conceptually, these two variables describe the executor being in * one of three states: * - Active: shutdown == false * - Shutdown: runningTasks > 0 and shutdown == true * - Terminated: runningTasks == 0 and shutdown == true */ private int runningTasks = 0; private boolean shutdown = false; @Override public void execute(Runnable command) { startTask(); try { command.run(); } finally { endTask(); } } @Override public boolean isShutdown() { lock.lock(); try { return shutdown; } finally { lock.unlock(); } } @Override public void shutdown() { lock.lock(); try { shutdown = true; } finally { lock.unlock(); } } // See sameThreadExecutor javadoc for unusual behavior of this method. @Override public List<Runnable> shutdownNow() { shutdown(); return Collections.emptyList(); } @Override public boolean isTerminated() { lock.lock(); try { return shutdown && runningTasks == 0; } finally { lock.unlock(); } } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { long nanos = unit.toNanos(timeout); lock.lock(); try { for (;;) { if (isTerminated()) { return true; } else if (nanos <= 0) { return false; } else { nanos = termination.awaitNanos(nanos); } } } finally { lock.unlock(); } } /** * Checks if the executor has been shut down and increments the running * task count. * * @throws RejectedExecutionException if the executor has been previously * shutdown */ private void startTask() { lock.lock(); try { if (isShutdown()) { throw new RejectedExecutionException("Executor already shutdown"); } runningTasks++; } finally { lock.unlock(); } } /** * Decrements the running task count. */ private void endTask() { lock.lock(); try { runningTasks--; if (isTerminated()) { termination.signalAll(); } } finally { lock.unlock(); } } } /** * Creates an {@link ExecutorService} whose {@code submit} and {@code * invokeAll} methods submit {@link ListenableFutureTask} instances to the * given delegate executor. Those methods, as well as {@code execute} and * {@code invokeAny}, are implemented in terms of calls to {@code * delegate.execute}. All other methods are forwarded unchanged to the * delegate. This implies that the returned {@code ListeningExecutorService} * never calls the delegate's {@code submit}, {@code invokeAll}, and {@code * invokeAny} methods, so any special handling of tasks must be implemented in * the delegate's {@code execute} method or by wrapping the returned {@code * ListeningExecutorService}. * * <p>If the delegate executor was already an instance of {@code * ListeningExecutorService}, it is returned untouched, and the rest of this * documentation does not apply. * * @since 10.0 */ public static ListeningExecutorService listeningDecorator( ExecutorService delegate) { return (delegate instanceof ListeningExecutorService) ? (ListeningExecutorService) delegate : (delegate instanceof ScheduledExecutorService) ? new ScheduledListeningDecorator((ScheduledExecutorService) delegate) : new ListeningDecorator(delegate); } /** * Creates a {@link ScheduledExecutorService} whose {@code submit} and {@code * invokeAll} methods submit {@link ListenableFutureTask} instances to the * given delegate executor. Those methods, as well as {@code execute} and * {@code invokeAny}, are implemented in terms of calls to {@code * delegate.execute}. All other methods are forwarded unchanged to the * delegate. This implies that the returned {@code * ListeningScheduledExecutorService} never calls the delegate's {@code * submit}, {@code invokeAll}, and {@code invokeAny} methods, so any special * handling of tasks must be implemented in the delegate's {@code execute} * method or by wrapping the returned {@code * ListeningScheduledExecutorService}. * * <p>If the delegate executor was already an instance of {@code * ListeningScheduledExecutorService}, it is returned untouched, and the rest * of this documentation does not apply. * * @since 10.0 */ public static ListeningScheduledExecutorService listeningDecorator( ScheduledExecutorService delegate) { return (delegate instanceof ListeningScheduledExecutorService) ? (ListeningScheduledExecutorService) delegate : new ScheduledListeningDecorator(delegate); } private static class ListeningDecorator extends AbstractListeningExecutorService { private final ExecutorService delegate; ListeningDecorator(ExecutorService delegate) { this.delegate = checkNotNull(delegate); } @Override public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { return delegate.awaitTermination(timeout, unit); } @Override public boolean isShutdown() { return delegate.isShutdown(); } @Override public boolean isTerminated() { return delegate.isTerminated(); } @Override public void shutdown() { delegate.shutdown(); } @Override public List<Runnable> shutdownNow() { return delegate.shutdownNow(); } @Override public void execute(Runnable command) { delegate.execute(command); } } private static class ScheduledListeningDecorator extends ListeningDecorator implements ListeningScheduledExecutorService { @SuppressWarnings("hiding") final ScheduledExecutorService delegate; ScheduledListeningDecorator(ScheduledExecutorService delegate) { super(delegate); this.delegate = checkNotNull(delegate); } @Override public ListenableScheduledFuture<?> schedule( Runnable command, long delay, TimeUnit unit) { ListenableFutureTask<Void> task = ListenableFutureTask.create(command, null); ScheduledFuture<?> scheduled = delegate.schedule(task, delay, unit); return new ListenableScheduledTask<Void>(task, scheduled); } @Override public <V> ListenableScheduledFuture<V> schedule( Callable<V> callable, long delay, TimeUnit unit) { ListenableFutureTask<V> task = ListenableFutureTask.create(callable); ScheduledFuture<?> scheduled = delegate.schedule(task, delay, unit); return new ListenableScheduledTask<V>(task, scheduled); } @Override public ListenableScheduledFuture<?> scheduleAtFixedRate( Runnable command, long initialDelay, long period, TimeUnit unit) { NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(command); ScheduledFuture<?> scheduled = delegate.scheduleAtFixedRate(task, initialDelay, period, unit); return new ListenableScheduledTask<Void>(task, scheduled); } @Override public ListenableScheduledFuture<?> scheduleWithFixedDelay( Runnable command, long initialDelay, long delay, TimeUnit unit) { NeverSuccessfulListenableFutureTask task = new NeverSuccessfulListenableFutureTask(command); ScheduledFuture<?> scheduled = delegate.scheduleWithFixedDelay(task, initialDelay, delay, unit); return new ListenableScheduledTask<Void>(task, scheduled); } private static final class ListenableScheduledTask<V> extends SimpleForwardingListenableFuture<V> implements ListenableScheduledFuture<V> { private final ScheduledFuture<?> scheduledDelegate; public ListenableScheduledTask( ListenableFuture<V> listenableDelegate, ScheduledFuture<?> scheduledDelegate) { super(listenableDelegate); this.scheduledDelegate = scheduledDelegate; } @Override public boolean cancel(boolean mayInterruptIfRunning) { boolean cancelled = super.cancel(mayInterruptIfRunning); if (cancelled) { // Unless it is cancelled, the delegate may continue being scheduled scheduledDelegate.cancel(mayInterruptIfRunning); // TODO(user): Cancel "this" if "scheduledDelegate" is cancelled. } return cancelled; } @Override public long getDelay(TimeUnit unit) { return scheduledDelegate.getDelay(unit); } @Override public int compareTo(Delayed other) { return scheduledDelegate.compareTo(other); } } private static final class NeverSuccessfulListenableFutureTask extends AbstractFuture<Void> implements Runnable { private final Runnable delegate; public NeverSuccessfulListenableFutureTask(Runnable delegate) { this.delegate = checkNotNull(delegate); } @Override public void run() { try { delegate.run(); } catch (Throwable t) { setException(t); throw Throwables.propagate(t); } } } } /* * This following method is a modified version of one found in * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/test/tck/AbstractExecutorServiceTest.java?revision=1.30 * which contained the following notice: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ * Other contributors include Andrew Wright, Jeffrey Hayes, * Pat Fisher, Mike Judd. */ /** * An implementation of {@link ExecutorService#invokeAny} for {@link ListeningExecutorService} * implementations. */ static <T> T invokeAnyImpl(ListeningExecutorService executorService, Collection<? extends Callable<T>> tasks, boolean timed, long nanos) throws InterruptedException, ExecutionException, TimeoutException { checkNotNull(executorService); int ntasks = tasks.size(); checkArgument(ntasks > 0); List<Future<T>> futures = Lists.newArrayListWithCapacity(ntasks); BlockingQueue<Future<T>> futureQueue = Queues.newLinkedBlockingQueue(); // For efficiency, especially in executors with limited // parallelism, check to see if previously submitted tasks are // done before submitting more of them. This interleaving // plus the exception mechanics account for messiness of main // loop. try { // Record exceptions so that if we fail to obtain any // result, we can throw the last exception we got. ExecutionException ee = null; long lastTime = timed ? System.nanoTime() : 0; Iterator<? extends Callable<T>> it = tasks.iterator(); futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue)); --ntasks; int active = 1; for (;;) { Future<T> f = futureQueue.poll(); if (f == null) { if (ntasks > 0) { --ntasks; futures.add(submitAndAddQueueListener(executorService, it.next(), futureQueue)); ++active; } else if (active == 0) { break; } else if (timed) { f = futureQueue.poll(nanos, TimeUnit.NANOSECONDS); if (f == null) { throw new TimeoutException(); } long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; } else { f = futureQueue.take(); } } if (f != null) { --active; try { return f.get(); } catch (ExecutionException eex) { ee = eex; } catch (RuntimeException rex) { ee = new ExecutionException(rex); } } } if (ee == null) { ee = new ExecutionException(null); } throw ee; } finally { for (Future<T> f : futures) { f.cancel(true); } } } /** * Submits the task and adds a listener that adds the future to {@code queue} when it completes. */ private static <T> ListenableFuture<T> submitAndAddQueueListener( ListeningExecutorService executorService, Callable<T> task, final BlockingQueue<Future<T>> queue) { final ListenableFuture<T> future = executorService.submit(task); future.addListener(new Runnable() { @Override public void run() { queue.add(future); } }, MoreExecutors.sameThreadExecutor()); return future; } /** * Returns a default thread factory used to create new threads. * * <p>On AppEngine, returns {@code ThreadManager.currentRequestThreadFactory()}. * Otherwise, returns {@link Executors#defaultThreadFactory()}. * * @since 14.0 */ @Beta public static ThreadFactory platformThreadFactory() { if (!isAppEngine()) { return Executors.defaultThreadFactory(); } try { return (ThreadFactory) Class.forName("com.google.appengine.api.ThreadManager") .getMethod("currentRequestThreadFactory") .invoke(null); } catch (IllegalAccessException e) { throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); } catch (ClassNotFoundException e) { throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); } catch (NoSuchMethodException e) { throw new RuntimeException("Couldn't invoke ThreadManager.currentRequestThreadFactory", e); } catch (InvocationTargetException e) { throw Throwables.propagate(e.getCause()); } } private static boolean isAppEngine() { if (System.getProperty("com.google.appengine.runtime.environment") == null) { return false; } try { // If the current environment is null, we're not inside AppEngine. return Class.forName("com.google.apphosting.api.ApiProxy") .getMethod("getCurrentEnvironment") .invoke(null) != null; } catch (ClassNotFoundException e) { // If ApiProxy doesn't exist, we're not on AppEngine at all. return false; } catch (InvocationTargetException e) { // If ApiProxy throws an exception, we're not in a proper AppEngine environment. return false; } catch (IllegalAccessException e) { // If the method isn't accessible, we're not on a supported version of AppEngine; return false; } catch (NoSuchMethodException e) { // If the method doesn't exist, we're not on a supported version of AppEngine; return false; } } /** * Creates a thread using {@link #platformThreadFactory}, and sets its name to {@code name} * unless changing the name is forbidden by the security manager. */ static Thread newThread(String name, Runnable runnable) { checkNotNull(name); checkNotNull(runnable); Thread result = platformThreadFactory().newThread(runnable); try { result.setName(name); } catch (SecurityException e) { // OK if we can't set the name in this environment. } return result; } // TODO(user): provide overloads for ListeningExecutorService? ListeningScheduledExecutorService? // TODO(user): provide overloads that take constant strings? Function<Runnable, String>s to // calculate names? /** * Creates an {@link Executor} that renames the {@link Thread threads} that its tasks run in. * * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed * right before each task is run. The renaming is best effort, if a {@link SecurityManager} * prevents the renaming then it will be skipped but the tasks will still execute. * * @param executor The executor to decorate * @param nameSupplier The source of names for each task */ static Executor renamingDecorator(final Executor executor, final Supplier<String> nameSupplier) { checkNotNull(executor); checkNotNull(nameSupplier); if (isAppEngine()) { // AppEngine doesn't support thread renaming, so don't even try return executor; } return new Executor() { @Override public void execute(Runnable command) { executor.execute(Callables.threadRenaming(command, nameSupplier)); } }; } /** * Creates an {@link ExecutorService} that renames the {@link Thread threads} that its tasks run * in. * * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed * right before each task is run. The renaming is best effort, if a {@link SecurityManager} * prevents the renaming then it will be skipped but the tasks will still execute. * * @param service The executor to decorate * @param nameSupplier The source of names for each task */ static ExecutorService renamingDecorator(final ExecutorService service, final Supplier<String> nameSupplier) { checkNotNull(service); checkNotNull(nameSupplier); if (isAppEngine()) { // AppEngine doesn't support thread renaming, so don't even try. return service; } return new WrappingExecutorService(service) { @Override protected <T> Callable<T> wrapTask(Callable<T> callable) { return Callables.threadRenaming(callable, nameSupplier); } @Override protected Runnable wrapTask(Runnable command) { return Callables.threadRenaming(command, nameSupplier); } }; } /** * Creates a {@link ScheduledExecutorService} that renames the {@link Thread threads} that its * tasks run in. * * <p>The names are retrieved from the {@code nameSupplier} on the thread that is being renamed * right before each task is run. The renaming is best effort, if a {@link SecurityManager} * prevents the renaming then it will be skipped but the tasks will still execute. * * @param service The executor to decorate * @param nameSupplier The source of names for each task */ static ScheduledExecutorService renamingDecorator(final ScheduledExecutorService service, final Supplier<String> nameSupplier) { checkNotNull(service); checkNotNull(nameSupplier); if (isAppEngine()) { // AppEngine doesn't support thread renaming, so don't even try. return service; } return new WrappingScheduledExecutorService(service) { @Override protected <T> Callable<T> wrapTask(Callable<T> callable) { return Callables.threadRenaming(callable, nameSupplier); } @Override protected Runnable wrapTask(Runnable command) { return Callables.threadRenaming(command, nameSupplier); } }; } /** * Shuts down the given executor gradually, first disabling new submissions and later cancelling * existing tasks. * * <p>The method takes the following steps: * <ol> * <li>calls {@link ExecutorService#shutdown()}, disabling acceptance of new submitted tasks. * <li>waits for half of the specified timeout. * <li>if the timeout expires, it calls {@link ExecutorService#shutdownNow()}, cancelling * pending tasks and interrupting running tasks. * <li>waits for the other half of the specified timeout. * </ol> * * <p>If, at any step of the process, the given executor is terminated or the calling thread is * interrupted, the method may return without executing any remaining steps. * * @param service the {@code ExecutorService} to shut down * @param timeout the maximum time to wait for the {@code ExecutorService} to terminate * @param unit the time unit of the timeout argument * @return {@code true) if the pool was terminated successfully, {@code false} if the * {@code ExecutorService} could not terminate <b>or</b> the thread running this method * is interrupted while waiting for the {@code ExecutorService} to terminate * @since 17.0 */ @Beta public static boolean shutdownAndAwaitTermination( ExecutorService service, long timeout, TimeUnit unit) { checkNotNull(unit); // Disable new tasks from being submitted service.shutdown(); try { long halfTimeoutNanos = TimeUnit.NANOSECONDS.convert(timeout, unit) / 2; // Wait for half the duration of the timeout for existing tasks to terminate if (!service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS)) { // Cancel currently executing tasks service.shutdownNow(); // Wait the other half of the timeout for tasks to respond to being cancelled service.awaitTermination(halfTimeoutNanos, TimeUnit.NANOSECONDS); } } catch (InterruptedException ie) { // Preserve interrupt status Thread.currentThread().interrupt(); // (Re-)Cancel if current thread also interrupted service.shutdownNow(); } return service.isTerminated(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/util/concurrent/MoreExecutors.java
Java
asf20
33,324
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Arithmetic functions operating on primitive values and {@link java.math.BigInteger} instances. * * <p>This package is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/MathExplained"> * math utilities</a>. */ @ParametersAreNonnullByDefault package com.google.common.math; import javax.annotation.ParametersAreNonnullByDefault;
zzhhhhh-aw4rwer
guava/src/com/google/common/math/package-info.java
Java
asf20
1,095
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.math; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.math.MathPreconditions.checkNoOverflow; import static com.google.common.math.MathPreconditions.checkNonNegative; import static com.google.common.math.MathPreconditions.checkPositive; import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.math.RoundingMode.HALF_EVEN; import static java.math.RoundingMode.HALF_UP; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import java.math.BigInteger; import java.math.RoundingMode; /** * A class for arithmetic on values of type {@code long}. Where possible, methods are defined and * named analogously to their {@code BigInteger} counterparts. * * <p>The implementations of many methods in this class are based on material from Henry S. Warren, * Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002). * * <p>Similar functionality for {@code int} and for {@link BigInteger} can be found in * {@link IntMath} and {@link BigIntegerMath} respectively. For other common operations on * {@code long} values, see {@link com.google.common.primitives.Longs}. * * @author Louis Wasserman * @since 11.0 */ @GwtCompatible(emulated = true) public final class LongMath { // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, || /** * Returns {@code true} if {@code x} represents a power of two. * * <p>This differs from {@code Long.bitCount(x) == 1}, because * {@code Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two. */ public static boolean isPowerOfTwo(long x) { return x > 0 & (x & (x - 1)) == 0; } /** * Returns 1 if {@code x < y} as unsigned longs, and 0 otherwise. Assumes that x - y fits into a * signed long. The implementation is branch-free, and benchmarks suggest it is measurably * faster than the straightforward ternary expression. */ @VisibleForTesting static int lessThanBranchFree(long x, long y) { // Returns the sign bit of x - y. return (int) (~~(x - y) >>> (Long.SIZE - 1)); } /** * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of two */ @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log2(long x, RoundingMode mode) { checkPositive("x", x); switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through case DOWN: case FLOOR: return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x); case UP: case CEILING: return Long.SIZE - Long.numberOfLeadingZeros(x - 1); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 int leadingZeros = Long.numberOfLeadingZeros(x); long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros; // floor(2^(logFloor + 0.5)) int logFloor = (Long.SIZE - 1) - leadingZeros; return logFloor + lessThanBranchFree(cmp, x); default: throw new AssertionError("impossible"); } } /** The biggest half power of two that fits into an unsigned long */ @VisibleForTesting static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L; /** * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of ten */ @GwtIncompatible("TODO") @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log10(long x, RoundingMode mode) { checkPositive("x", x); int logFloor = log10Floor(x); long floorPow = powersOf10[logFloor]; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(x == floorPow); // fall through case FLOOR: case DOWN: return logFloor; case CEILING: case UP: return logFloor + lessThanBranchFree(floorPow, x); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5 return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x); default: throw new AssertionError(); } } @GwtIncompatible("TODO") static int log10Floor(long x) { /* * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation. * * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))), * we can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x)) * is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2. */ int y = maxLog10ForLeadingZeros[Long.numberOfLeadingZeros(x)]; /* * y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the * lower of the two possible values, or y - 1, otherwise, we want y. */ return y - lessThanBranchFree(x, powersOf10[y]); } // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i))) @VisibleForTesting static final byte[] maxLog10ForLeadingZeros = { 19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12, 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 }; @GwtIncompatible("TODO") @VisibleForTesting static final long[] powersOf10 = { 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L, 10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L, 1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L }; // halfPowersOf10[i] = largest long less than 10^(i + 0.5) @GwtIncompatible("TODO") @VisibleForTesting static final long[] halfPowersOf10 = { 3L, 31L, 316L, 3162L, 31622L, 316227L, 3162277L, 31622776L, 316227766L, 3162277660L, 31622776601L, 316227766016L, 3162277660168L, 31622776601683L, 316227766016837L, 3162277660168379L, 31622776601683793L, 316227766016837933L, 3162277660168379331L }; /** * Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to * {@code BigInteger.valueOf(b).pow(k).longValue()}. This implementation runs in {@code O(log k)} * time. * * @throws IllegalArgumentException if {@code k < 0} */ @GwtIncompatible("TODO") public static long pow(long b, int k) { checkNonNegative("exponent", k); if (-2 <= b && b <= 2) { switch ((int) b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: return (k < Long.SIZE) ? 1L << k : 0; case (-2): if (k < Long.SIZE) { return ((k & 1) == 0) ? 1L << k : -(1L << k); } else { return 0; } default: throw new AssertionError(); } } for (long accum = 1;; k >>= 1) { switch (k) { case 0: return accum; case 1: return accum * b; default: accum *= ((k & 1) == 0) ? 1 : b; b *= b; } } } /** * Returns the square root of {@code x}, rounded with the specified rounding mode. * * @throws IllegalArgumentException if {@code x < 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and * {@code sqrt(x)} is not an integer */ @GwtIncompatible("TODO") @SuppressWarnings("fallthrough") public static long sqrt(long x, RoundingMode mode) { checkNonNegative("x", x); if (fitsInInt(x)) { return IntMath.sqrt((int) x, mode); } /* * Let k be the true value of floor(sqrt(x)), so that * * k * k <= x < (k + 1) * (k + 1) * (double) (k * k) <= (double) x <= (double) ((k + 1) * (k + 1)) * since casting to double is nondecreasing. * Note that the right-hand inequality is no longer strict. * Math.sqrt(k * k) <= Math.sqrt(x) <= Math.sqrt((k + 1) * (k + 1)) * since Math.sqrt is monotonic. * (long) Math.sqrt(k * k) <= (long) Math.sqrt(x) <= (long) Math.sqrt((k + 1) * (k + 1)) * since casting to long is monotonic * k <= (long) Math.sqrt(x) <= k + 1 * since (long) Math.sqrt(k * k) == k, as checked exhaustively in * {@link LongMathTest#testSqrtOfPerfectSquareAsDoubleIsPerfect} */ long guess = (long) Math.sqrt(x); // Note: guess is always <= FLOOR_SQRT_MAX_LONG. long guessSquared = guess * guess; // Note (2013-2-26): benchmarks indicate that, inscrutably enough, using if statements is // faster here than using lessThanBranchFree. switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(guessSquared == x); return guess; case FLOOR: case DOWN: if (x < guessSquared) { return guess - 1; } return guess; case CEILING: case UP: if (x > guessSquared) { return guess + 1; } return guess; case HALF_DOWN: case HALF_UP: case HALF_EVEN: long sqrtFloor = guess - ((x < guessSquared) ? 1 : 0); long halfSquare = sqrtFloor * sqrtFloor + sqrtFloor; /* * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both * x and halfSquare are integers, this is equivalent to testing whether or not x <= * halfSquare. (We have to deal with overflow, though.) * * If we treat halfSquare as an unsigned long, we know that * sqrtFloor^2 <= x < (sqrtFloor + 1)^2 * halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1 * so |x - halfSquare| <= sqrtFloor. Therefore, it's safe to treat x - halfSquare as a * signed long, so lessThanBranchFree is safe for use. */ return sqrtFloor + lessThanBranchFree(halfSquare, x); default: throw new AssertionError(); } } /** * Returns the result of dividing {@code p} by {@code q}, rounding using the specified * {@code RoundingMode}. * * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a} * is not an integer multiple of {@code b} */ @GwtIncompatible("TODO") @SuppressWarnings("fallthrough") public static long divide(long p, long q, RoundingMode mode) { checkNotNull(mode); long div = p / q; // throws if q == 0 long rem = p - q * div; // equals p % q if (rem == 0) { return div; } /* * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to * deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of * p / q. * * signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise. */ int signum = 1 | (int) ((p ^ q) >> (Long.SIZE - 1)); boolean increment; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(rem == 0); // fall through case DOWN: increment = false; break; case UP: increment = true; break; case CEILING: increment = signum > 0; break; case FLOOR: increment = signum < 0; break; case HALF_EVEN: case HALF_DOWN: case HALF_UP: long absRem = abs(rem); long cmpRemToHalfDivisor = absRem - (abs(q) - absRem); // subtracting two nonnegative longs can't overflow // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2). if (cmpRemToHalfDivisor == 0) { // exactly on the half mark increment = (mode == HALF_UP | (mode == HALF_EVEN & (div & 1) != 0)); } else { increment = cmpRemToHalfDivisor > 0; // closer to the UP value } break; default: throw new AssertionError(); } return increment ? div + signum : div; } /** * Returns {@code x mod m}, a non-negative value less than {@code m}. * This differs from {@code x % m}, which might be negative. * * <p>For example: * * <pre> {@code * * mod(7, 4) == 3 * mod(-7, 4) == 1 * mod(-1, 4) == 3 * mod(-8, 4) == 0 * mod(8, 4) == 0}</pre> * * @throws ArithmeticException if {@code m <= 0} * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3"> * Remainder Operator</a> */ @GwtIncompatible("TODO") public static int mod(long x, int m) { // Cast is safe because the result is guaranteed in the range [0, m) return (int) mod(x, (long) m); } /** * Returns {@code x mod m}, a non-negative value less than {@code m}. * This differs from {@code x % m}, which might be negative. * * <p>For example: * * <pre> {@code * * mod(7, 4) == 3 * mod(-7, 4) == 1 * mod(-1, 4) == 3 * mod(-8, 4) == 0 * mod(8, 4) == 0}</pre> * * @throws ArithmeticException if {@code m <= 0} * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3"> * Remainder Operator</a> */ @GwtIncompatible("TODO") public static long mod(long x, long m) { if (m <= 0) { throw new ArithmeticException("Modulus must be positive"); } long result = x % m; return (result >= 0) ? result : result + m; } /** * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if * {@code a == 0 && b == 0}. * * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0} */ public static long gcd(long a, long b) { /* * The reason we require both arguments to be >= 0 is because otherwise, what do you return on * gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive 2^63, but positive 2^63 isn't * an int. */ checkNonNegative("a", a); checkNonNegative("b", b); if (a == 0) { // 0 % b == 0, so b divides a, but the converse doesn't hold. // BigInteger.gcd is consistent with this decision. return b; } else if (b == 0) { return a; // similar logic } /* * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm. * This is >60% faster than the Euclidean algorithm in benchmarks. */ int aTwos = Long.numberOfTrailingZeros(a); a >>= aTwos; // divide out all 2s int bTwos = Long.numberOfTrailingZeros(b); b >>= bTwos; // divide out all 2s while (a != b) { // both a, b are odd // The key to the binary GCD algorithm is as follows: // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b). // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two. // We bend over backwards to avoid branching, adapting a technique from // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax long delta = a - b; // can't overflow, since a and b are nonnegative long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1)); // equivalent to Math.min(delta, 0) a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b) // a is now nonnegative and even b += minDeltaOrZero; // sets b to min(old a, b) a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b } return a << min(aTwos, bTwos); } /** * Returns the sum of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a + b} overflows in signed {@code long} arithmetic */ @GwtIncompatible("TODO") public static long checkedAdd(long a, long b) { long result = a + b; checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0); return result; } /** * Returns the difference of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a - b} overflows in signed {@code long} arithmetic */ @GwtIncompatible("TODO") public static long checkedSubtract(long a, long b) { long result = a - b; checkNoOverflow((a ^ b) >= 0 | (a ^ result) >= 0); return result; } /** * Returns the product of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a * b} overflows in signed {@code long} arithmetic */ @GwtIncompatible("TODO") public static long checkedMultiply(long a, long b) { // Hacker's Delight, Section 2-12 int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a) + Long.numberOfLeadingZeros(b) + Long.numberOfLeadingZeros(~b); /* * If leadingZeros > Long.SIZE + 1 it's definitely fine, if it's < Long.SIZE it's definitely * bad. We do the leadingZeros check to avoid the division below if at all possible. * * Otherwise, if b == Long.MIN_VALUE, then the only allowed values of a are 0 and 1. We take * care of all a < 0 with their own check, because in particular, the case a == -1 will * incorrectly pass the division check below. * * In all other cases, we check that either a is 0 or the result is consistent with division. */ if (leadingZeros > Long.SIZE + 1) { return a * b; } checkNoOverflow(leadingZeros >= Long.SIZE); checkNoOverflow(a >= 0 | b != Long.MIN_VALUE); long result = a * b; checkNoOverflow(a == 0 || result / a == b); return result; } /** * Returns the {@code b} to the {@code k}th power, provided it does not overflow. * * @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed * {@code long} arithmetic */ @GwtIncompatible("TODO") public static long checkedPow(long b, int k) { checkNonNegative("exponent", k); if (b >= -2 & b <= 2) { switch ((int) b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: checkNoOverflow(k < Long.SIZE - 1); return 1L << k; case (-2): checkNoOverflow(k < Long.SIZE); return ((k & 1) == 0) ? (1L << k) : (-1L << k); default: throw new AssertionError(); } } long accum = 1; while (true) { switch (k) { case 0: return accum; case 1: return checkedMultiply(accum, b); default: if ((k & 1) != 0) { accum = checkedMultiply(accum, b); } k >>= 1; if (k > 0) { checkNoOverflow(b <= FLOOR_SQRT_MAX_LONG); b *= b; } } } } @VisibleForTesting static final long FLOOR_SQRT_MAX_LONG = 3037000499L; /** * Returns {@code n!}, that is, the product of the first {@code n} positive * integers, {@code 1} if {@code n == 0}, or {@link Long#MAX_VALUE} if the * result does not fit in a {@code long}. * * @throws IllegalArgumentException if {@code n < 0} */ @GwtIncompatible("TODO") public static long factorial(int n) { checkNonNegative("n", n); return (n < factorials.length) ? factorials[n] : Long.MAX_VALUE; } static final long[] factorials = { 1L, 1L, 1L * 2, 1L * 2 * 3, 1L * 2 * 3 * 4, 1L * 2 * 3 * 4 * 5, 1L * 2 * 3 * 4 * 5 * 6, 1L * 2 * 3 * 4 * 5 * 6 * 7, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 }; /** * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and * {@code k}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}. * * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n} */ public static long binomial(int n, int k) { checkNonNegative("n", n); checkNonNegative("k", k); checkArgument(k <= n, "k (%s) > n (%s)", k, n); if (k > (n >> 1)) { k = n - k; } switch (k) { case 0: return 1; case 1: return n; default: if (n < factorials.length) { return factorials[n] / (factorials[k] * factorials[n - k]); } else if (k >= biggestBinomials.length || n > biggestBinomials[k]) { return Long.MAX_VALUE; } else if (k < biggestSimpleBinomials.length && n <= biggestSimpleBinomials[k]) { // guaranteed not to overflow long result = n--; for (int i = 2; i <= k; n--, i++) { result *= n; result /= i; } return result; } else { int nBits = LongMath.log2(n, RoundingMode.CEILING); long result = 1; long numerator = n--; long denominator = 1; int numeratorBits = nBits; // This is an upper bound on log2(numerator, ceiling). /* * We want to do this in long math for speed, but want to avoid overflow. We adapt the * technique previously used by BigIntegerMath: maintain separate numerator and * denominator accumulators, multiplying the fraction into result when near overflow. */ for (int i = 2; i <= k; i++, n--) { if (numeratorBits + nBits < Long.SIZE - 1) { // It's definitely safe to multiply into numerator and denominator. numerator *= n; denominator *= i; numeratorBits += nBits; } else { // It might not be safe to multiply into numerator and denominator, // so multiply (numerator / denominator) into result. result = multiplyFraction(result, numerator, denominator); numerator = n; denominator = i; numeratorBits = nBits; } } return multiplyFraction(result, numerator, denominator); } } } /** * Returns (x * numerator / denominator), which is assumed to come out to an integral value. */ static long multiplyFraction(long x, long numerator, long denominator) { if (x == 1) { return numerator / denominator; } long commonDivisor = gcd(x, denominator); x /= commonDivisor; denominator /= commonDivisor; // We know gcd(x, denominator) = 1, and x * numerator / denominator is exact, // so denominator must be a divisor of numerator. return x * (numerator / denominator); } /* * binomial(biggestBinomials[k], k) fits in a long, but not * binomial(biggestBinomials[k] + 1, k). */ static final int[] biggestBinomials = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733, 887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68, 67, 67, 66, 66, 66, 66}; /* * binomial(biggestSimpleBinomials[k], k) doesn't need to use the slower GCD-based impl, * but binomial(biggestSimpleBinomials[k] + 1, k) does. */ @VisibleForTesting static final int[] biggestSimpleBinomials = {Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, 86251, 11724, 3218, 1313, 684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, 62, 62, 61, 61, 61}; // These values were generated by using checkedMultiply to see when the simple multiply/divide // algorithm would lead to an overflow. static boolean fitsInInt(long x) { return (int) x == x; } /** * Returns the arithmetic mean of {@code x} and {@code y}, rounded toward * negative infinity. This method is resilient to overflow. * * @since 14.0 */ public static long mean(long x, long y) { // Efficient method for computing the arithmetic mean. // The alternative (x + y) / 2 fails for large values. // The alternative (x + y) >>> 1 fails for negative values. return (x & y) + ((x ^ y) >> 1); } private LongMath() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/math/LongMath.java
Java
asf20
26,464
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.math; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.math.DoubleUtils.IMPLICIT_BIT; import static com.google.common.math.DoubleUtils.SIGNIFICAND_BITS; import static com.google.common.math.DoubleUtils.getSignificand; import static com.google.common.math.DoubleUtils.isFinite; import static com.google.common.math.DoubleUtils.isNormal; import static com.google.common.math.DoubleUtils.scaleNormalize; import static com.google.common.math.MathPreconditions.checkInRange; import static com.google.common.math.MathPreconditions.checkNonNegative; import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary; import static java.lang.Math.abs; import static java.lang.Math.copySign; import static java.lang.Math.getExponent; import static java.lang.Math.log; import static java.lang.Math.rint; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.primitives.Booleans; import java.math.BigInteger; import java.math.RoundingMode; import java.util.Iterator; /** * A class for arithmetic on doubles that is not covered by {@link java.lang.Math}. * * @author Louis Wasserman * @since 11.0 */ @GwtCompatible(emulated = true) public final class DoubleMath { /* * This method returns a value y such that rounding y DOWN (towards zero) gives the same result * as rounding x according to the specified mode. */ @GwtIncompatible("#isMathematicalInteger, com.google.common.math.DoubleUtils") static double roundIntermediate(double x, RoundingMode mode) { if (!isFinite(x)) { throw new ArithmeticException("input is infinite or NaN"); } switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(isMathematicalInteger(x)); return x; case FLOOR: if (x >= 0.0 || isMathematicalInteger(x)) { return x; } else { return x - 1.0; } case CEILING: if (x <= 0.0 || isMathematicalInteger(x)) { return x; } else { return x + 1.0; } case DOWN: return x; case UP: if (isMathematicalInteger(x)) { return x; } else { return x + Math.copySign(1.0, x); } case HALF_EVEN: return rint(x); case HALF_UP: { double z = rint(x); if (abs(x - z) == 0.5) { return x + copySign(0.5, x); } else { return z; } } case HALF_DOWN: { double z = rint(x); if (abs(x - z) == 0.5) { return x; } else { return z; } } default: throw new AssertionError(); } } /** * Returns the {@code int} value that is equal to {@code x} rounded with the specified rounding * mode, if possible. * * @throws ArithmeticException if * <ul> * <li>{@code x} is infinite or NaN * <li>{@code x}, after being rounded to a mathematical integer using the specified * rounding mode, is either less than {@code Integer.MIN_VALUE} or greater than {@code * Integer.MAX_VALUE} * <li>{@code x} is not a mathematical integer and {@code mode} is * {@link RoundingMode#UNNECESSARY} * </ul> */ @GwtIncompatible("#roundIntermediate") public static int roundToInt(double x, RoundingMode mode) { double z = roundIntermediate(x, mode); checkInRange(z > MIN_INT_AS_DOUBLE - 1.0 & z < MAX_INT_AS_DOUBLE + 1.0); return (int) z; } private static final double MIN_INT_AS_DOUBLE = -0x1p31; private static final double MAX_INT_AS_DOUBLE = 0x1p31 - 1.0; /** * Returns the {@code long} value that is equal to {@code x} rounded with the specified rounding * mode, if possible. * * @throws ArithmeticException if * <ul> * <li>{@code x} is infinite or NaN * <li>{@code x}, after being rounded to a mathematical integer using the specified * rounding mode, is either less than {@code Long.MIN_VALUE} or greater than {@code * Long.MAX_VALUE} * <li>{@code x} is not a mathematical integer and {@code mode} is * {@link RoundingMode#UNNECESSARY} * </ul> */ @GwtIncompatible("#roundIntermediate") public static long roundToLong(double x, RoundingMode mode) { double z = roundIntermediate(x, mode); checkInRange(MIN_LONG_AS_DOUBLE - z < 1.0 & z < MAX_LONG_AS_DOUBLE_PLUS_ONE); return (long) z; } private static final double MIN_LONG_AS_DOUBLE = -0x1p63; /* * We cannot store Long.MAX_VALUE as a double without losing precision. Instead, we store * Long.MAX_VALUE + 1 == -Long.MIN_VALUE, and then offset all comparisons by 1. */ private static final double MAX_LONG_AS_DOUBLE_PLUS_ONE = 0x1p63; /** * Returns the {@code BigInteger} value that is equal to {@code x} rounded with the specified * rounding mode, if possible. * * @throws ArithmeticException if * <ul> * <li>{@code x} is infinite or NaN * <li>{@code x} is not a mathematical integer and {@code mode} is * {@link RoundingMode#UNNECESSARY} * </ul> */ @GwtIncompatible("#roundIntermediate, java.lang.Math.getExponent, " + "com.google.common.math.DoubleUtils") public static BigInteger roundToBigInteger(double x, RoundingMode mode) { x = roundIntermediate(x, mode); if (MIN_LONG_AS_DOUBLE - x < 1.0 & x < MAX_LONG_AS_DOUBLE_PLUS_ONE) { return BigInteger.valueOf((long) x); } int exponent = getExponent(x); long significand = getSignificand(x); BigInteger result = BigInteger.valueOf(significand).shiftLeft(exponent - SIGNIFICAND_BITS); return (x < 0) ? result.negate() : result; } /** * Returns {@code true} if {@code x} is exactly equal to {@code 2^k} for some finite integer * {@code k}. */ @GwtIncompatible("com.google.common.math.DoubleUtils") public static boolean isPowerOfTwo(double x) { return x > 0.0 && isFinite(x) && LongMath.isPowerOfTwo(getSignificand(x)); } /** * Returns the base 2 logarithm of a double value. * * <p>Special cases: * <ul> * <li>If {@code x} is NaN or less than zero, the result is NaN. * <li>If {@code x} is positive infinity, the result is positive infinity. * <li>If {@code x} is positive or negative zero, the result is negative infinity. * </ul> * * <p>The computed result is within 1 ulp of the exact result. * * <p>If the result of this method will be immediately rounded to an {@code int}, * {@link #log2(double, RoundingMode)} is faster. */ public static double log2(double x) { return log(x) / LN_2; // surprisingly within 1 ulp according to tests } private static final double LN_2 = log(2); /** * Returns the base 2 logarithm of a double value, rounded with the specified rounding mode to an * {@code int}. * * <p>Regardless of the rounding mode, this is faster than {@code (int) log2(x)}. * * @throws IllegalArgumentException if {@code x <= 0.0}, {@code x} is NaN, or {@code x} is * infinite */ @GwtIncompatible("java.lang.Math.getExponent, com.google.common.math.DoubleUtils") @SuppressWarnings("fallthrough") public static int log2(double x, RoundingMode mode) { checkArgument(x > 0.0 && isFinite(x), "x must be positive and finite"); int exponent = getExponent(x); if (!isNormal(x)) { return log2(x * IMPLICIT_BIT, mode) - SIGNIFICAND_BITS; // Do the calculation on a normal value. } // x is positive, finite, and normal boolean increment; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through case FLOOR: increment = false; break; case CEILING: increment = !isPowerOfTwo(x); break; case DOWN: increment = exponent < 0 & !isPowerOfTwo(x); break; case UP: increment = exponent >= 0 & !isPowerOfTwo(x); break; case HALF_DOWN: case HALF_EVEN: case HALF_UP: double xScaled = scaleNormalize(x); // sqrt(2) is irrational, and the spec is relative to the "exact numerical result," // so log2(x) is never exactly exponent + 0.5. increment = (xScaled * xScaled) > 2.0; break; default: throw new AssertionError(); } return increment ? exponent + 1 : exponent; } /** * Returns {@code true} if {@code x} represents a mathematical integer. * * <p>This is equivalent to, but not necessarily implemented as, the expression {@code * !Double.isNaN(x) && !Double.isInfinite(x) && x == Math.rint(x)}. */ @GwtIncompatible("java.lang.Math.getExponent, com.google.common.math.DoubleUtils") public static boolean isMathematicalInteger(double x) { return isFinite(x) && (x == 0.0 || SIGNIFICAND_BITS - Long.numberOfTrailingZeros(getSignificand(x)) <= getExponent(x)); } /** * Returns {@code n!}, that is, the product of the first {@code n} positive * integers, {@code 1} if {@code n == 0}, or e n!}, or * {@link Double#POSITIVE_INFINITY} if {@code n! > Double.MAX_VALUE}. * * <p>The result is within 1 ulp of the true value. * * @throws IllegalArgumentException if {@code n < 0} */ public static double factorial(int n) { checkNonNegative("n", n); if (n > MAX_FACTORIAL) { return Double.POSITIVE_INFINITY; } else { // Multiplying the last (n & 0xf) values into their own accumulator gives a more accurate // result than multiplying by everySixteenthFactorial[n >> 4] directly. double accum = 1.0; for (int i = 1 + (n & ~0xf); i <= n; i++) { accum *= i; } return accum * everySixteenthFactorial[n >> 4]; } } @VisibleForTesting static final int MAX_FACTORIAL = 170; @VisibleForTesting static final double[] everySixteenthFactorial = { 0x1.0p0, 0x1.30777758p44, 0x1.956ad0aae33a4p117, 0x1.ee69a78d72cb6p202, 0x1.fe478ee34844ap295, 0x1.c619094edabffp394, 0x1.3638dd7bd6347p498, 0x1.7cac197cfe503p605, 0x1.1e5dfc140e1e5p716, 0x1.8ce85fadb707ep829, 0x1.95d5f3d928edep945}; /** * Returns {@code true} if {@code a} and {@code b} are within {@code tolerance} of each other. * * <p>Technically speaking, this is equivalent to * {@code Math.abs(a - b) <= tolerance || Double.valueOf(a).equals(Double.valueOf(b))}. * * <p>Notable special cases include: * <ul> * <li>All NaNs are fuzzily equal. * <li>If {@code a == b}, then {@code a} and {@code b} are always fuzzily equal. * <li>Positive and negative zero are always fuzzily equal. * <li>If {@code tolerance} is zero, and neither {@code a} nor {@code b} is NaN, then * {@code a} and {@code b} are fuzzily equal if and only if {@code a == b}. * <li>With {@link Double#POSITIVE_INFINITY} tolerance, all non-NaN values are fuzzily equal. * <li>With finite tolerance, {@code Double.POSITIVE_INFINITY} and {@code * Double.NEGATIVE_INFINITY} are fuzzily equal only to themselves. * </li> * * <p>This is reflexive and symmetric, but <em>not</em> transitive, so it is <em>not</em> an * equivalence relation and <em>not</em> suitable for use in {@link Object#equals} * implementations. * * @throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN * @since 13.0 */ public static boolean fuzzyEquals(double a, double b, double tolerance) { MathPreconditions.checkNonNegative("tolerance", tolerance); return Math.copySign(a - b, 1.0) <= tolerance // copySign(x, 1.0) is a branch-free version of abs(x), but with different NaN semantics || (a == b) // needed to ensure that infinities equal themselves || (Double.isNaN(a) && Double.isNaN(b)); } /** * Compares {@code a} and {@code b} "fuzzily," with a tolerance for nearly-equal values. * * <p>This method is equivalent to * {@code fuzzyEquals(a, b, tolerance) ? 0 : Double.compare(a, b)}. In particular, like * {@link Double#compare(double, double)}, it treats all NaN values as equal and greater than all * other values (including {@link Double#POSITIVE_INFINITY}). * * <p>This is <em>not</em> a total ordering and is <em>not</em> suitable for use in * {@link Comparable#compareTo} implementations. In particular, it is not transitive. * * @throws IllegalArgumentException if {@code tolerance} is {@code < 0} or NaN * @since 13.0 */ public static int fuzzyCompare(double a, double b, double tolerance) { if (fuzzyEquals(a, b, tolerance)) { return 0; } else if (a < b) { return -1; } else if (a > b) { return 1; } else { return Booleans.compare(Double.isNaN(a), Double.isNaN(b)); } } @GwtIncompatible("com.google.common.math.DoubleUtils") private static final class MeanAccumulator { private long count = 0; private double mean = 0.0; void add(double value) { checkArgument(isFinite(value)); ++count; // Art of Computer Programming vol. 2, Knuth, 4.2.2, (15) mean += (value - mean) / count; } double mean() { checkArgument(count > 0, "Cannot take mean of 0 values"); return mean; } } /** * Returns the arithmetic mean of the values. There must be at least one value, and they must all * be finite. */ @GwtIncompatible("MeanAccumulator") public static double mean(double... values) { MeanAccumulator accumulator = new MeanAccumulator(); for (double value : values) { accumulator.add(value); } return accumulator.mean(); } /** * Returns the arithmetic mean of the values. There must be at least one value. The values will * be converted to doubles, which does not cause any loss of precision for ints. */ @GwtIncompatible("MeanAccumulator") public static double mean(int... values) { MeanAccumulator accumulator = new MeanAccumulator(); for (int value : values) { accumulator.add(value); } return accumulator.mean(); } /** * Returns the arithmetic mean of the values. There must be at least one value. The values will * be converted to doubles, which causes loss of precision for longs of magnitude over 2^53 * (slightly over 9e15). */ @GwtIncompatible("MeanAccumulator") public static double mean(long... values) { MeanAccumulator accumulator = new MeanAccumulator(); for (long value : values) { accumulator.add(value); } return accumulator.mean(); } /** * Returns the arithmetic mean of the values. There must be at least one value, and they must all * be finite. The values will be converted to doubles, which may cause loss of precision for some * numeric types. */ @GwtIncompatible("MeanAccumulator") public static double mean(Iterable<? extends Number> values) { MeanAccumulator accumulator = new MeanAccumulator(); for (Number value : values) { accumulator.add(value.doubleValue()); } return accumulator.mean(); } /** * Returns the arithmetic mean of the values. There must be at least one value, and they must all * be finite. The values will be converted to doubles, which may cause loss of precision for some * numeric types. */ @GwtIncompatible("MeanAccumulator") public static double mean(Iterator<? extends Number> values) { MeanAccumulator accumulator = new MeanAccumulator(); while (values.hasNext()) { accumulator.add(values.next().doubleValue()); } return accumulator.mean(); } private DoubleMath() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/math/DoubleMath.java
Java
asf20
16,510
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.math; import static com.google.common.base.Preconditions.checkArgument; import static java.lang.Double.MAX_EXPONENT; import static java.lang.Double.MIN_EXPONENT; import static java.lang.Double.POSITIVE_INFINITY; import static java.lang.Double.doubleToRawLongBits; import static java.lang.Double.isNaN; import static java.lang.Double.longBitsToDouble; import static java.lang.Math.getExponent; import java.math.BigInteger; /** * Utilities for {@code double} primitives. * * @author Louis Wasserman */ final class DoubleUtils { private DoubleUtils() { } static double nextDown(double d) { return -Math.nextUp(-d); } // The mask for the significand, according to the {@link // Double#doubleToRawLongBits(double)} spec. static final long SIGNIFICAND_MASK = 0x000fffffffffffffL; // The mask for the exponent, according to the {@link // Double#doubleToRawLongBits(double)} spec. static final long EXPONENT_MASK = 0x7ff0000000000000L; // The mask for the sign, according to the {@link // Double#doubleToRawLongBits(double)} spec. static final long SIGN_MASK = 0x8000000000000000L; static final int SIGNIFICAND_BITS = 52; static final int EXPONENT_BIAS = 1023; /** * The implicit 1 bit that is omitted in significands of normal doubles. */ static final long IMPLICIT_BIT = SIGNIFICAND_MASK + 1; static long getSignificand(double d) { checkArgument(isFinite(d), "not a normal value"); int exponent = getExponent(d); long bits = doubleToRawLongBits(d); bits &= SIGNIFICAND_MASK; return (exponent == MIN_EXPONENT - 1) ? bits << 1 : bits | IMPLICIT_BIT; } static boolean isFinite(double d) { return getExponent(d) <= MAX_EXPONENT; } static boolean isNormal(double d) { return getExponent(d) >= MIN_EXPONENT; } /* * Returns x scaled by a power of 2 such that it is in the range [1, 2). Assumes x is positive, * normal, and finite. */ static double scaleNormalize(double x) { long significand = doubleToRawLongBits(x) & SIGNIFICAND_MASK; return longBitsToDouble(significand | ONE_BITS); } static double bigToDouble(BigInteger x) { // This is an extremely fast implementation of BigInteger.doubleValue(). JDK patch pending. BigInteger absX = x.abs(); int exponent = absX.bitLength() - 1; // exponent == floor(log2(abs(x))) if (exponent < Long.SIZE - 1) { return x.longValue(); } else if (exponent > MAX_EXPONENT) { return x.signum() * POSITIVE_INFINITY; } /* * We need the top SIGNIFICAND_BITS + 1 bits, including the "implicit" one bit. To make * rounding easier, we pick out the top SIGNIFICAND_BITS + 2 bits, so we have one to help us * round up or down. twiceSignifFloor will contain the top SIGNIFICAND_BITS + 2 bits, and * signifFloor the top SIGNIFICAND_BITS + 1. * * It helps to consider the real number signif = absX * 2^(SIGNIFICAND_BITS - exponent). */ int shift = exponent - SIGNIFICAND_BITS - 1; long twiceSignifFloor = absX.shiftRight(shift).longValue(); long signifFloor = twiceSignifFloor >> 1; signifFloor &= SIGNIFICAND_MASK; // remove the implied bit /* * We round up if either the fractional part of signif is strictly greater than 0.5 (which is * true if the 0.5 bit is set and any lower bit is set), or if the fractional part of signif is * >= 0.5 and signifFloor is odd (which is true if both the 0.5 bit and the 1 bit are set). */ boolean increment = (twiceSignifFloor & 1) != 0 && ((signifFloor & 1) != 0 || absX.getLowestSetBit() < shift); long signifRounded = increment ? signifFloor + 1 : signifFloor; long bits = (long) ((exponent + EXPONENT_BIAS)) << SIGNIFICAND_BITS; bits += signifRounded; /* * If signifRounded == 2^53, we'd need to set all of the significand bits to zero and add 1 to * the exponent. This is exactly the behavior we get from just adding signifRounded to bits * directly. If the exponent is MAX_DOUBLE_EXPONENT, we round up (correctly) to * Double.POSITIVE_INFINITY. */ bits |= x.signum() & SIGN_MASK; return longBitsToDouble(bits); } /** * Returns its argument if it is non-negative, zero if it is negative. */ static double ensureNonNegative(double value) { checkArgument(!isNaN(value)); if (value > 0.0) { return value; } else { return 0.0; } } private static final long ONE_BITS = doubleToRawLongBits(1.0); }
zzhhhhh-aw4rwer
guava/src/com/google/common/math/DoubleUtils.java
Java
asf20
5,150
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations * under the License. */ package com.google.common.math; import com.google.common.annotations.GwtCompatible; import java.math.BigInteger; import javax.annotation.Nullable; /** * A collection of preconditions for math functions. * * @author Louis Wasserman */ @GwtCompatible final class MathPreconditions { static int checkPositive(@Nullable String role, int x) { if (x <= 0) { throw new IllegalArgumentException(role + " (" + x + ") must be > 0"); } return x; } static long checkPositive(@Nullable String role, long x) { if (x <= 0) { throw new IllegalArgumentException(role + " (" + x + ") must be > 0"); } return x; } static BigInteger checkPositive(@Nullable String role, BigInteger x) { if (x.signum() <= 0) { throw new IllegalArgumentException(role + " (" + x + ") must be > 0"); } return x; } static int checkNonNegative(@Nullable String role, int x) { if (x < 0) { throw new IllegalArgumentException(role + " (" + x + ") must be >= 0"); } return x; } static long checkNonNegative(@Nullable String role, long x) { if (x < 0) { throw new IllegalArgumentException(role + " (" + x + ") must be >= 0"); } return x; } static BigInteger checkNonNegative(@Nullable String role, BigInteger x) { if (x.signum() < 0) { throw new IllegalArgumentException(role + " (" + x + ") must be >= 0"); } return x; } static double checkNonNegative(@Nullable String role, double x) { if (!(x >= 0)) { // not x < 0, to work with NaN. throw new IllegalArgumentException(role + " (" + x + ") must be >= 0"); } return x; } static void checkRoundingUnnecessary(boolean condition) { if (!condition) { throw new ArithmeticException("mode was UNNECESSARY, but rounding was necessary"); } } static void checkInRange(boolean condition) { if (!condition) { throw new ArithmeticException("not in range"); } } static void checkNoOverflow(boolean condition) { if (!condition) { throw new ArithmeticException("overflow"); } } private MathPreconditions() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/math/MathPreconditions.java
Java
asf20
2,728
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.math; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.math.MathPreconditions.checkNonNegative; import static com.google.common.math.MathPreconditions.checkPositive; import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary; import static java.math.RoundingMode.CEILING; import static java.math.RoundingMode.FLOOR; import static java.math.RoundingMode.HALF_EVEN; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import java.math.BigDecimal; import java.math.BigInteger; import java.math.RoundingMode; import java.util.ArrayList; import java.util.List; /** * A class for arithmetic on values of type {@code BigInteger}. * * <p>The implementations of many methods in this class are based on material from Henry S. Warren, * Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002). * * <p>Similar functionality for {@code int} and for {@code long} can be found in * {@link IntMath} and {@link LongMath} respectively. * * @author Louis Wasserman * @since 11.0 */ @GwtCompatible(emulated = true) public final class BigIntegerMath { /** * Returns {@code true} if {@code x} represents a power of two. */ public static boolean isPowerOfTwo(BigInteger x) { checkNotNull(x); return x.signum() > 0 && x.getLowestSetBit() == x.bitLength() - 1; } /** * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of two */ @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log2(BigInteger x, RoundingMode mode) { checkPositive("x", checkNotNull(x)); int logFloor = x.bitLength() - 1; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through case DOWN: case FLOOR: return logFloor; case UP: case CEILING: return isPowerOfTwo(x) ? logFloor : logFloor + 1; case HALF_DOWN: case HALF_UP: case HALF_EVEN: if (logFloor < SQRT2_PRECOMPUTE_THRESHOLD) { BigInteger halfPower = SQRT2_PRECOMPUTED_BITS.shiftRight( SQRT2_PRECOMPUTE_THRESHOLD - logFloor); if (x.compareTo(halfPower) <= 0) { return logFloor; } else { return logFloor + 1; } } /* * Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 * * To determine which side of logFloor.5 the logarithm is, we compare x^2 to 2^(2 * * logFloor + 1). */ BigInteger x2 = x.pow(2); int logX2Floor = x2.bitLength() - 1; return (logX2Floor < 2 * logFloor + 1) ? logFloor : logFloor + 1; default: throw new AssertionError(); } } /* * The maximum number of bits in a square root for which we'll precompute an explicit half power * of two. This can be any value, but higher values incur more class load time and linearly * increasing memory consumption. */ @VisibleForTesting static final int SQRT2_PRECOMPUTE_THRESHOLD = 256; @VisibleForTesting static final BigInteger SQRT2_PRECOMPUTED_BITS = new BigInteger("16a09e667f3bcc908b2fb1366ea957d3e3adec17512775099da2f590b0667322a", 16); /** * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of ten */ @GwtIncompatible("TODO") @SuppressWarnings("fallthrough") public static int log10(BigInteger x, RoundingMode mode) { checkPositive("x", x); if (fitsInLong(x)) { return LongMath.log10(x.longValue(), mode); } int approxLog10 = (int) (log2(x, FLOOR) * LN_2 / LN_10); BigInteger approxPow = BigInteger.TEN.pow(approxLog10); int approxCmp = approxPow.compareTo(x); /* * We adjust approxLog10 and approxPow until they're equal to floor(log10(x)) and * 10^floor(log10(x)). */ if (approxCmp > 0) { /* * The code is written so that even completely incorrect approximations will still yield the * correct answer eventually, but in practice this branch should almost never be entered, * and even then the loop should not run more than once. */ do { approxLog10--; approxPow = approxPow.divide(BigInteger.TEN); approxCmp = approxPow.compareTo(x); } while (approxCmp > 0); } else { BigInteger nextPow = BigInteger.TEN.multiply(approxPow); int nextCmp = nextPow.compareTo(x); while (nextCmp <= 0) { approxLog10++; approxPow = nextPow; approxCmp = nextCmp; nextPow = BigInteger.TEN.multiply(approxPow); nextCmp = nextPow.compareTo(x); } } int floorLog = approxLog10; BigInteger floorPow = approxPow; int floorCmp = approxCmp; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(floorCmp == 0); // fall through case FLOOR: case DOWN: return floorLog; case CEILING: case UP: return floorPow.equals(x) ? floorLog : floorLog + 1; case HALF_DOWN: case HALF_UP: case HALF_EVEN: // Since sqrt(10) is irrational, log10(x) - floorLog can never be exactly 0.5 BigInteger x2 = x.pow(2); BigInteger halfPowerSquared = floorPow.pow(2).multiply(BigInteger.TEN); return (x2.compareTo(halfPowerSquared) <= 0) ? floorLog : floorLog + 1; default: throw new AssertionError(); } } private static final double LN_10 = Math.log(10); private static final double LN_2 = Math.log(2); /** * Returns the square root of {@code x}, rounded with the specified rounding mode. * * @throws IllegalArgumentException if {@code x < 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and * {@code sqrt(x)} is not an integer */ @GwtIncompatible("TODO") @SuppressWarnings("fallthrough") public static BigInteger sqrt(BigInteger x, RoundingMode mode) { checkNonNegative("x", x); if (fitsInLong(x)) { return BigInteger.valueOf(LongMath.sqrt(x.longValue(), mode)); } BigInteger sqrtFloor = sqrtFloor(x); switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(sqrtFloor.pow(2).equals(x)); // fall through case FLOOR: case DOWN: return sqrtFloor; case CEILING: case UP: int sqrtFloorInt = sqrtFloor.intValue(); boolean sqrtFloorIsExact = (sqrtFloorInt * sqrtFloorInt == x.intValue()) // fast check mod 2^32 && sqrtFloor.pow(2).equals(x); // slow exact check return sqrtFloorIsExact ? sqrtFloor : sqrtFloor.add(BigInteger.ONE); case HALF_DOWN: case HALF_UP: case HALF_EVEN: BigInteger halfSquare = sqrtFloor.pow(2).add(sqrtFloor); /* * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both * x and halfSquare are integers, this is equivalent to testing whether or not x <= * halfSquare. */ return (halfSquare.compareTo(x) >= 0) ? sqrtFloor : sqrtFloor.add(BigInteger.ONE); default: throw new AssertionError(); } } @GwtIncompatible("TODO") private static BigInteger sqrtFloor(BigInteger x) { /* * Adapted from Hacker's Delight, Figure 11-1. * * Using DoubleUtils.bigToDouble, getting a double approximation of x is extremely fast, and * then we can get a double approximation of the square root. Then, we iteratively improve this * guess with an application of Newton's method, which sets guess := (guess + (x / guess)) / 2. * This iteration has the following two properties: * * a) every iteration (except potentially the first) has guess >= floor(sqrt(x)). This is * because guess' is the arithmetic mean of guess and x / guess, sqrt(x) is the geometric mean, * and the arithmetic mean is always higher than the geometric mean. * * b) this iteration converges to floor(sqrt(x)). In fact, the number of correct digits doubles * with each iteration, so this algorithm takes O(log(digits)) iterations. * * We start out with a double-precision approximation, which may be higher or lower than the * true value. Therefore, we perform at least one Newton iteration to get a guess that's * definitely >= floor(sqrt(x)), and then continue the iteration until we reach a fixed point. */ BigInteger sqrt0; int log2 = log2(x, FLOOR); if (log2 < Double.MAX_EXPONENT) { sqrt0 = sqrtApproxWithDoubles(x); } else { int shift = (log2 - DoubleUtils.SIGNIFICAND_BITS) & ~1; // even! /* * We have that x / 2^shift < 2^54. Our initial approximation to sqrtFloor(x) will be * 2^(shift/2) * sqrtApproxWithDoubles(x / 2^shift). */ sqrt0 = sqrtApproxWithDoubles(x.shiftRight(shift)).shiftLeft(shift >> 1); } BigInteger sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1); if (sqrt0.equals(sqrt1)) { return sqrt0; } do { sqrt0 = sqrt1; sqrt1 = sqrt0.add(x.divide(sqrt0)).shiftRight(1); } while (sqrt1.compareTo(sqrt0) < 0); return sqrt0; } @GwtIncompatible("TODO") private static BigInteger sqrtApproxWithDoubles(BigInteger x) { return DoubleMath.roundToBigInteger(Math.sqrt(DoubleUtils.bigToDouble(x)), HALF_EVEN); } /** * Returns the result of dividing {@code p} by {@code q}, rounding using the specified * {@code RoundingMode}. * * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a} * is not an integer multiple of {@code b} */ @GwtIncompatible("TODO") public static BigInteger divide(BigInteger p, BigInteger q, RoundingMode mode) { BigDecimal pDec = new BigDecimal(p); BigDecimal qDec = new BigDecimal(q); return pDec.divide(qDec, 0, mode).toBigIntegerExact(); } /** * Returns {@code n!}, that is, the product of the first {@code n} positive * integers, or {@code 1} if {@code n == 0}. * * <p><b>Warning</b>: the result takes <i>O(n log n)</i> space, so use cautiously. * * <p>This uses an efficient binary recursive algorithm to compute the factorial * with balanced multiplies. It also removes all the 2s from the intermediate * products (shifting them back in at the end). * * @throws IllegalArgumentException if {@code n < 0} */ public static BigInteger factorial(int n) { checkNonNegative("n", n); // If the factorial is small enough, just use LongMath to do it. if (n < LongMath.factorials.length) { return BigInteger.valueOf(LongMath.factorials[n]); } // Pre-allocate space for our list of intermediate BigIntegers. int approxSize = IntMath.divide(n * IntMath.log2(n, CEILING), Long.SIZE, CEILING); ArrayList<BigInteger> bignums = new ArrayList<BigInteger>(approxSize); // Start from the pre-computed maximum long factorial. int startingNumber = LongMath.factorials.length; long product = LongMath.factorials[startingNumber - 1]; // Strip off 2s from this value. int shift = Long.numberOfTrailingZeros(product); product >>= shift; // Use floor(log2(num)) + 1 to prevent overflow of multiplication. int productBits = LongMath.log2(product, FLOOR) + 1; int bits = LongMath.log2(startingNumber, FLOOR) + 1; // Check for the next power of two boundary, to save us a CLZ operation. int nextPowerOfTwo = 1 << (bits - 1); // Iteratively multiply the longs as big as they can go. for (long num = startingNumber; num <= n; num++) { // Check to see if the floor(log2(num)) + 1 has changed. if ((num & nextPowerOfTwo) != 0) { nextPowerOfTwo <<= 1; bits++; } // Get rid of the 2s in num. int tz = Long.numberOfTrailingZeros(num); long normalizedNum = num >> tz; shift += tz; // Adjust floor(log2(num)) + 1. int normalizedBits = bits - tz; // If it won't fit in a long, then we store off the intermediate product. if (normalizedBits + productBits >= Long.SIZE) { bignums.add(BigInteger.valueOf(product)); product = 1; productBits = 0; } product *= normalizedNum; productBits = LongMath.log2(product, FLOOR) + 1; } // Check for leftovers. if (product > 1) { bignums.add(BigInteger.valueOf(product)); } // Efficiently multiply all the intermediate products together. return listProduct(bignums).shiftLeft(shift); } static BigInteger listProduct(List<BigInteger> nums) { return listProduct(nums, 0, nums.size()); } static BigInteger listProduct(List<BigInteger> nums, int start, int end) { switch (end - start) { case 0: return BigInteger.ONE; case 1: return nums.get(start); case 2: return nums.get(start).multiply(nums.get(start + 1)); case 3: return nums.get(start).multiply(nums.get(start + 1)).multiply(nums.get(start + 2)); default: // Otherwise, split the list in half and recursively do this. int m = (end + start) >>> 1; return listProduct(nums, start, m).multiply(listProduct(nums, m, end)); } } /** * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and * {@code k}, that is, {@code n! / (k! (n - k)!)}. * * <p><b>Warning</b>: the result can take as much as <i>O(k log n)</i> space. * * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n} */ public static BigInteger binomial(int n, int k) { checkNonNegative("n", n); checkNonNegative("k", k); checkArgument(k <= n, "k (%s) > n (%s)", k, n); if (k > (n >> 1)) { k = n - k; } if (k < LongMath.biggestBinomials.length && n <= LongMath.biggestBinomials[k]) { return BigInteger.valueOf(LongMath.binomial(n, k)); } BigInteger accum = BigInteger.ONE; long numeratorAccum = n; long denominatorAccum = 1; int bits = LongMath.log2(n, RoundingMode.CEILING); int numeratorBits = bits; for (int i = 1; i < k; i++) { int p = n - i; int q = i + 1; // log2(p) >= bits - 1, because p >= n/2 if (numeratorBits + bits >= Long.SIZE - 1) { // The numerator is as big as it can get without risking overflow. // Multiply numeratorAccum / denominatorAccum into accum. accum = accum .multiply(BigInteger.valueOf(numeratorAccum)) .divide(BigInteger.valueOf(denominatorAccum)); numeratorAccum = p; denominatorAccum = q; numeratorBits = bits; } else { // We can definitely multiply into the long accumulators without overflowing them. numeratorAccum *= p; denominatorAccum *= q; numeratorBits += bits; } } return accum .multiply(BigInteger.valueOf(numeratorAccum)) .divide(BigInteger.valueOf(denominatorAccum)); } // Returns true if BigInteger.valueOf(x.longValue()).equals(x). @GwtIncompatible("TODO") static boolean fitsInLong(BigInteger x) { return x.bitLength() <= Long.SIZE - 1; } private BigIntegerMath() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/math/BigIntegerMath.java
Java
asf20
16,482
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.math; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.math.MathPreconditions.checkNoOverflow; import static com.google.common.math.MathPreconditions.checkNonNegative; import static com.google.common.math.MathPreconditions.checkPositive; import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.math.RoundingMode.HALF_EVEN; import static java.math.RoundingMode.HALF_UP; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import java.math.BigInteger; import java.math.RoundingMode; /** * A class for arithmetic on values of type {@code int}. Where possible, methods are defined and * named analogously to their {@code BigInteger} counterparts. * * <p>The implementations of many methods in this class are based on material from Henry S. Warren, * Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002). * * <p>Similar functionality for {@code long} and for {@link BigInteger} can be found in * {@link LongMath} and {@link BigIntegerMath} respectively. For other common operations on * {@code int} values, see {@link com.google.common.primitives.Ints}. * * @author Louis Wasserman * @since 11.0 */ @GwtCompatible(emulated = true) public final class IntMath { // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, || /** * Returns {@code true} if {@code x} represents a power of two. * * <p>This differs from {@code Integer.bitCount(x) == 1}, because * {@code Integer.bitCount(Integer.MIN_VALUE) == 1}, but {@link Integer#MIN_VALUE} is not a power * of two. */ public static boolean isPowerOfTwo(int x) { return x > 0 & (x & (x - 1)) == 0; } /** * Returns 1 if {@code x < y} as unsigned integers, and 0 otherwise. Assumes that x - y fits into * a signed int. The implementation is branch-free, and benchmarks suggest it is measurably (if * narrowly) faster than the straightforward ternary expression. */ @VisibleForTesting static int lessThanBranchFree(int x, int y) { // The double negation is optimized away by normal Java, but is necessary for GWT // to make sure bit twiddling works as expected. return ~~(x - y) >>> (Integer.SIZE - 1); } /** * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of two */ @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log2(int x, RoundingMode mode) { checkPositive("x", x); switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through case DOWN: case FLOOR: return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x); case UP: case CEILING: return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 int leadingZeros = Integer.numberOfLeadingZeros(x); int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros; // floor(2^(logFloor + 0.5)) int logFloor = (Integer.SIZE - 1) - leadingZeros; return logFloor + lessThanBranchFree(cmp, x); default: throw new AssertionError(); } } /** The biggest half power of two that can fit in an unsigned int. */ @VisibleForTesting static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333; /** * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of ten */ @GwtIncompatible("need BigIntegerMath to adequately test") @SuppressWarnings("fallthrough") public static int log10(int x, RoundingMode mode) { checkPositive("x", x); int logFloor = log10Floor(x); int floorPow = powersOf10[logFloor]; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(x == floorPow); // fall through case FLOOR: case DOWN: return logFloor; case CEILING: case UP: return logFloor + lessThanBranchFree(floorPow, x); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // sqrt(10) is irrational, so log10(x) - logFloor is never exactly 0.5 return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x); default: throw new AssertionError(); } } private static int log10Floor(int x) { /* * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation. * * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))), * we can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x)) * is 6, then 64 <= x < 128, so floor(log10(x)) is either 1 or 2. */ int y = maxLog10ForLeadingZeros[Integer.numberOfLeadingZeros(x)]; /* * y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the * lower of the two possible values, or y - 1, otherwise, we want y. */ return y - lessThanBranchFree(x, powersOf10[y]); } // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i))) @VisibleForTesting static final byte[] maxLog10ForLeadingZeros = {9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0}; @VisibleForTesting static final int[] powersOf10 = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000}; // halfPowersOf10[i] = largest int less than 10^(i + 0.5) @VisibleForTesting static final int[] halfPowersOf10 = {3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, Integer.MAX_VALUE}; /** * Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to * {@code BigInteger.valueOf(b).pow(k).intValue()}. This implementation runs in {@code O(log k)} * time. * * <p>Compare {@link #checkedPow}, which throws an {@link ArithmeticException} upon overflow. * * @throws IllegalArgumentException if {@code k < 0} */ @GwtIncompatible("failing tests") public static int pow(int b, int k) { checkNonNegative("exponent", k); switch (b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: return (k < Integer.SIZE) ? (1 << k) : 0; case (-2): if (k < Integer.SIZE) { return ((k & 1) == 0) ? (1 << k) : -(1 << k); } else { return 0; } default: // continue below to handle the general case } for (int accum = 1;; k >>= 1) { switch (k) { case 0: return accum; case 1: return b * accum; default: accum *= ((k & 1) == 0) ? 1 : b; b *= b; } } } /** * Returns the square root of {@code x}, rounded with the specified rounding mode. * * @throws IllegalArgumentException if {@code x < 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and * {@code sqrt(x)} is not an integer */ @GwtIncompatible("need BigIntegerMath to adequately test") @SuppressWarnings("fallthrough") public static int sqrt(int x, RoundingMode mode) { checkNonNegative("x", x); int sqrtFloor = sqrtFloor(x); switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through case FLOOR: case DOWN: return sqrtFloor; case CEILING: case UP: return sqrtFloor + lessThanBranchFree(sqrtFloor * sqrtFloor, x); case HALF_DOWN: case HALF_UP: case HALF_EVEN: int halfSquare = sqrtFloor * sqrtFloor + sqrtFloor; /* * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both * x and halfSquare are integers, this is equivalent to testing whether or not x <= * halfSquare. (We have to deal with overflow, though.) * * If we treat halfSquare as an unsigned int, we know that * sqrtFloor^2 <= x < (sqrtFloor + 1)^2 * halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1 * so |x - halfSquare| <= sqrtFloor. Therefore, it's safe to treat x - halfSquare as a * signed int, so lessThanBranchFree is safe for use. */ return sqrtFloor + lessThanBranchFree(halfSquare, x); default: throw new AssertionError(); } } private static int sqrtFloor(int x) { // There is no loss of precision in converting an int to a double, according to // http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2 return (int) Math.sqrt(x); } /** * Returns the result of dividing {@code p} by {@code q}, rounding using the specified * {@code RoundingMode}. * * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a} * is not an integer multiple of {@code b} */ @SuppressWarnings("fallthrough") public static int divide(int p, int q, RoundingMode mode) { checkNotNull(mode); if (q == 0) { throw new ArithmeticException("/ by zero"); // for GWT } int div = p / q; int rem = p - q * div; // equal to p % q if (rem == 0) { return div; } /* * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to * deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of * p / q. * * signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise. */ int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1)); boolean increment; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(rem == 0); // fall through case DOWN: increment = false; break; case UP: increment = true; break; case CEILING: increment = signum > 0; break; case FLOOR: increment = signum < 0; break; case HALF_EVEN: case HALF_DOWN: case HALF_UP: int absRem = abs(rem); int cmpRemToHalfDivisor = absRem - (abs(q) - absRem); // subtracting two nonnegative ints can't overflow // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2). if (cmpRemToHalfDivisor == 0) { // exactly on the half mark increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0)); } else { increment = cmpRemToHalfDivisor > 0; // closer to the UP value } break; default: throw new AssertionError(); } return increment ? div + signum : div; } /** * Returns {@code x mod m}, a non-negative value less than {@code m}. * This differs from {@code x % m}, which might be negative. * * <p>For example:<pre> {@code * * mod(7, 4) == 3 * mod(-7, 4) == 1 * mod(-1, 4) == 3 * mod(-8, 4) == 0 * mod(8, 4) == 0}</pre> * * @throws ArithmeticException if {@code m <= 0} * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3"> * Remainder Operator</a> */ public static int mod(int x, int m) { if (m <= 0) { throw new ArithmeticException("Modulus " + m + " must be > 0"); } int result = x % m; return (result >= 0) ? result : result + m; } /** * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if * {@code a == 0 && b == 0}. * * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0} */ public static int gcd(int a, int b) { /* * The reason we require both arguments to be >= 0 is because otherwise, what do you return on * gcd(0, Integer.MIN_VALUE)? BigInteger.gcd would return positive 2^31, but positive 2^31 * isn't an int. */ checkNonNegative("a", a); checkNonNegative("b", b); if (a == 0) { // 0 % b == 0, so b divides a, but the converse doesn't hold. // BigInteger.gcd is consistent with this decision. return b; } else if (b == 0) { return a; // similar logic } /* * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm. * This is >40% faster than the Euclidean algorithm in benchmarks. */ int aTwos = Integer.numberOfTrailingZeros(a); a >>= aTwos; // divide out all 2s int bTwos = Integer.numberOfTrailingZeros(b); b >>= bTwos; // divide out all 2s while (a != b) { // both a, b are odd // The key to the binary GCD algorithm is as follows: // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b). // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two. // We bend over backwards to avoid branching, adapting a technique from // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax int delta = a - b; // can't overflow, since a and b are nonnegative int minDeltaOrZero = delta & (delta >> (Integer.SIZE - 1)); // equivalent to Math.min(delta, 0) a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b) // a is now nonnegative and even b += minDeltaOrZero; // sets b to min(old a, b) a >>= Integer.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b } return a << min(aTwos, bTwos); } /** * Returns the sum of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic */ public static int checkedAdd(int a, int b) { long result = (long) a + b; checkNoOverflow(result == (int) result); return (int) result; } /** * Returns the difference of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a - b} overflows in signed {@code int} arithmetic */ public static int checkedSubtract(int a, int b) { long result = (long) a - b; checkNoOverflow(result == (int) result); return (int) result; } /** * Returns the product of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a * b} overflows in signed {@code int} arithmetic */ public static int checkedMultiply(int a, int b) { long result = (long) a * b; checkNoOverflow(result == (int) result); return (int) result; } /** * Returns the {@code b} to the {@code k}th power, provided it does not overflow. * * <p>{@link #pow} may be faster, but does not check for overflow. * * @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed * {@code int} arithmetic */ public static int checkedPow(int b, int k) { checkNonNegative("exponent", k); switch (b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: checkNoOverflow(k < Integer.SIZE - 1); return 1 << k; case (-2): checkNoOverflow(k < Integer.SIZE); return ((k & 1) == 0) ? 1 << k : -1 << k; default: // continue below to handle the general case } int accum = 1; while (true) { switch (k) { case 0: return accum; case 1: return checkedMultiply(accum, b); default: if ((k & 1) != 0) { accum = checkedMultiply(accum, b); } k >>= 1; if (k > 0) { checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT); b *= b; } } } } @VisibleForTesting static final int FLOOR_SQRT_MAX_INT = 46340; /** * Returns {@code n!}, that is, the product of the first {@code n} positive * integers, {@code 1} if {@code n == 0}, or {@link Integer#MAX_VALUE} if the * result does not fit in a {@code int}. * * @throws IllegalArgumentException if {@code n < 0} */ public static int factorial(int n) { checkNonNegative("n", n); return (n < factorials.length) ? factorials[n] : Integer.MAX_VALUE; } private static final int[] factorials = { 1, 1, 1 * 2, 1 * 2 * 3, 1 * 2 * 3 * 4, 1 * 2 * 3 * 4 * 5, 1 * 2 * 3 * 4 * 5 * 6, 1 * 2 * 3 * 4 * 5 * 6 * 7, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12}; /** * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and * {@code k}, or {@link Integer#MAX_VALUE} if the result does not fit in an {@code int}. * * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0} or {@code k > n} */ @GwtIncompatible("need BigIntegerMath to adequately test") public static int binomial(int n, int k) { checkNonNegative("n", n); checkNonNegative("k", k); checkArgument(k <= n, "k (%s) > n (%s)", k, n); if (k > (n >> 1)) { k = n - k; } if (k >= biggestBinomials.length || n > biggestBinomials[k]) { return Integer.MAX_VALUE; } switch (k) { case 0: return 1; case 1: return n; default: long result = 1; for (int i = 0; i < k; i++) { result *= n - i; result /= i + 1; } return (int) result; } } // binomial(biggestBinomials[k], k) fits in an int, but not binomial(biggestBinomials[k]+1,k). @VisibleForTesting static int[] biggestBinomials = { Integer.MAX_VALUE, Integer.MAX_VALUE, 65536, 2345, 477, 193, 110, 75, 58, 49, 43, 39, 37, 35, 34, 34, 33 }; /** * Returns the arithmetic mean of {@code x} and {@code y}, rounded towards * negative infinity. This method is overflow resilient. * * @since 14.0 */ public static int mean(int x, int y) { // Efficient method for computing the arithmetic mean. // The alternative (x + y) / 2 fails for large values. // The alternative (x + y) >>> 1 fails for negative values. return (x & y) + ((x ^ y) >> 1); } private IntMath() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/math/IntMath.java
Java
asf20
19,806
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import static java.lang.Float.NEGATIVE_INFINITY; import static java.lang.Float.POSITIVE_INFINITY; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Converter; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@code float} primitives, that are not * already found in either {@link Float} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Floats { private Floats() {} /** * The number of bytes required to represent a primitive {@code float} * value. * * @since 10.0 */ public static final int BYTES = Float.SIZE / Byte.SIZE; /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Float) value).hashCode()}. * * @param value a primitive {@code float} value * @return a hash code for the value */ public static int hashCode(float value) { // TODO(kevinb): is there a better way, that's still gwt-safe? return ((Float) value).hashCode(); } /** * Compares the two specified {@code float} values using {@link * Float#compare(float, float)}. You may prefer to invoke that method * directly; this method exists only for consistency with the other utilities * in this package. * * <p><b>Note:</b> this method simply delegates to the JDK method {@link * Float#compare}. It is provided for consistency with the other primitive * types, whose compare methods were not added to the JDK until JDK 7. * * @param a the first {@code float} to compare * @param b the second {@code float} to compare * @return the result of invoking {@link Float#compare(float, float)} */ public static int compare(float a, float b) { return Float.compare(a, b); } /** * Returns {@code true} if {@code value} represents a real number. This is * equivalent to, but not necessarily implemented as, * {@code !(Float.isInfinite(value) || Float.isNaN(value))}. * * @since 10.0 */ public static boolean isFinite(float value) { return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY; } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. Note that this always returns {@code false} when {@code * target} is {@code NaN}. * * @param array an array of {@code float} values, possibly empty * @param target a primitive {@code float} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(float[] array, float target) { for (float value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. Note that this always returns {@code -1} when {@code target} * is {@code NaN}. * * @param array an array of {@code float} values, possibly empty * @param target a primitive {@code float} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(float[] array, float target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( float[] array, float target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * <p>Note that this always returns {@code -1} when {@code target} contains * {@code NaN}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(float[] array, float[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. Note that this always returns {@code -1} when {@code target} * is {@code NaN}. * * @param array an array of {@code float} values, possibly empty * @param target a primitive {@code float} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(float[] array, float target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( float[] array, float target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}, using the same rules of * comparison as {@link Math#min(float, float)}. * * @param array a <i>nonempty</i> array of {@code float} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static float min(float... array) { checkArgument(array.length > 0); float min = array[0]; for (int i = 1; i < array.length; i++) { min = Math.min(min, array[i]); } return min; } /** * Returns the greatest value present in {@code array}, using the same rules * of comparison as {@link Math#min(float, float)}. * * @param array a <i>nonempty</i> array of {@code float} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static float max(float... array) { checkArgument(array.length > 0); float max = array[0]; for (int i = 1; i < array.length; i++) { max = Math.max(max, array[i]); } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new float[] {a, b}, new float[] {}, new * float[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code float} arrays * @return a single array containing all the values from the source arrays, in * order */ public static float[] concat(float[]... arrays) { int length = 0; for (float[] array : arrays) { length += array.length; } float[] result = new float[length]; int pos = 0; for (float[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } private static final class FloatConverter extends Converter<String, Float> implements Serializable { static final FloatConverter INSTANCE = new FloatConverter(); @Override protected Float doForward(String value) { return Float.valueOf(value); } @Override protected String doBackward(Float value) { return value.toString(); } @Override public String toString() { return "Floats.stringConverter()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } /** * Returns a serializable converter object that converts between strings and * floats using {@link Float#valueOf} and {@link Float#toString()}. * * @since 16.0 */ @Beta public static Converter<String, Float> stringConverter() { return FloatConverter.INSTANCE; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static float[] ensureCapacity( float[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static float[] copyOf(float[] original, int length) { float[] copy = new float[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code float} values, converted * to strings as specified by {@link Float#toString(float)}, and separated by * {@code separator}. For example, {@code join("-", 1.0f, 2.0f, 3.0f)} * returns the string {@code "1.0-2.0-3.0"}. * * <p>Note that {@link Float#toString(float)} formats {@code float} * differently in GWT. In the previous example, it returns the string {@code * "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code float} values, possibly empty */ public static String join(String separator, float... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 12); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code float} arrays * lexicographically. That is, it compares, using {@link * #compare(float, float)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, {@code [] < [1.0f] < [1.0f, 2.0f] * < [2.0f]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(float[], float[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<float[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<float[]> { INSTANCE; @Override public int compare(float[] left, float[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Floats.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Returns an array containing each value of {@code collection}, converted to * a {@code float} value in the manner of {@link Number#floatValue}. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null * @since 1.0 (parameter was {@code Collection<Float>} before 12.0) */ public static float[] toArray(Collection<? extends Number> collection) { if (collection instanceof FloatArrayAsList) { return ((FloatArrayAsList) collection).toFloatArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; float[] array = new float[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).floatValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Float} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * <p>The returned list may have unexpected behavior if it contains {@code * NaN}, or if {@code NaN} is used as a parameter to any of its methods. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Float> asList(float... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new FloatArrayAsList(backingArray); } @GwtCompatible private static class FloatArrayAsList extends AbstractList<Float> implements RandomAccess, Serializable { final float[] array; final int start; final int end; FloatArrayAsList(float[] array) { this(array, 0, array.length); } FloatArrayAsList(float[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Float get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Float) && Floats.indexOf(array, (Float) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Float) { int i = Floats.indexOf(array, (Float) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Float) { int i = Floats.lastIndexOf(array, (Float) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Float set(int index, Float element) { checkElementIndex(index, size()); float oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Float> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new FloatArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof FloatArrayAsList) { FloatArrayAsList that = (FloatArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Floats.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 12); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } float[] toFloatArray() { // Arrays.copyOfRange() is not available under GWT int size = size(); float[] result = new float[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } /** * Parses the specified string as a single-precision floating point value. * The ASCII character {@code '-'} (<code>'&#92;u002D'</code>) is recognized * as the minus sign. * * <p>Unlike {@link Float#parseFloat(String)}, this method returns * {@code null} instead of throwing an exception if parsing fails. * Valid inputs are exactly those accepted by {@link Float#valueOf(String)}, * except that leading and trailing whitespace is not permitted. * * <p>This implementation is likely to be faster than {@code * Float.parseFloat} if many failures are expected. * * @param string the string representation of a {@code float} value * @return the floating point value represented by {@code string}, or * {@code null} if {@code string} has a length of zero or cannot be * parsed as a {@code float} value * @since 14.0 */ @GwtIncompatible("regular expressions") @Nullable @Beta public static Float tryParse(String string) { if (Doubles.FLOATING_POINT_PATTERN.matcher(string).matches()) { // TODO(user): could be potentially optimized, but only with // extensive testing try { return Float.parseFloat(string); } catch (NumberFormatException e) { // Float.parseFloat has changed specs several times, so fall through // gracefully } } return null; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/Floats.java
Java
asf20
20,451
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Static utilities for working with the eight primitive types and {@code void}, * and value types for treating them as unsigned. * * <p>This package is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * <h2>Contents</h2> * * <h3>General static utilities</h3> * * <ul> * <li>{@link com.google.common.primitives.Primitives} * </ul> * * <h3>Per-type static utilities</h3> * * <ul> * <li>{@link com.google.common.primitives.Booleans} * <li>{@link com.google.common.primitives.Bytes} * <ul> * <li>{@link com.google.common.primitives.SignedBytes} * <li>{@link com.google.common.primitives.UnsignedBytes} * </ul> * <li>{@link com.google.common.primitives.Chars} * <li>{@link com.google.common.primitives.Doubles} * <li>{@link com.google.common.primitives.Floats} * <li>{@link com.google.common.primitives.Ints} * <ul> * <li>{@link com.google.common.primitives.UnsignedInts} * </ul> * <li>{@link com.google.common.primitives.Longs} * <ul> * <li>{@link com.google.common.primitives.UnsignedLongs} * </ul> * <li>{@link com.google.common.primitives.Shorts} * </ul> * * <h3>Value types</h3> * <ul> * <li>{@link com.google.common.primitives.UnsignedInteger} * <li>{@link com.google.common.primitives.UnsignedLong} * </ul> */ @ParametersAreNonnullByDefault package com.google.common.primitives; import javax.annotation.ParametersAreNonnullByDefault;
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/package-info.java
Java
asf20
2,224
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Converter; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import javax.annotation.CheckForNull; /** * Static utility methods pertaining to {@code int} primitives, that are not * already found in either {@link Integer} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Ints { private Ints() {} /** * The number of bytes required to represent a primitive {@code int} * value. */ public static final int BYTES = Integer.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as an {@code int}. * * @since 10.0 */ public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Integer) value).hashCode()}. * * @param value a primitive {@code int} value * @return a hash code for the value */ public static int hashCode(int value) { return value; } /** * Returns the {@code int} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code int} type * @return the {@code int} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link * Integer#MAX_VALUE} or less than {@link Integer#MIN_VALUE} */ public static int checkedCast(long value) { int result = (int) value; if (result != value) { // don't use checkArgument here, to avoid boxing throw new IllegalArgumentException("Out of range: " + value); } return result; } /** * Returns the {@code int} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code int} if it is in the range of the * {@code int} type, {@link Integer#MAX_VALUE} if it is too large, * or {@link Integer#MIN_VALUE} if it is too small */ public static int saturatedCast(long value) { if (value > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } if (value < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } return (int) value; } /** * Compares the two specified {@code int} values. The sign of the value * returned is the same as that of {@code ((Integer) a).compareTo(b)}. * * <p><b>Note:</b> projects using JDK 7 or later should use the equivalent * {@link Integer#compare} method instead. * * @param a the first {@code int} to compare * @param b the second {@code int} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(int a, int b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(int[] array, int target) { for (int value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(int[] array, int target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( int[] array, int target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(int[] array, int[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(int[] array, int target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( int[] array, int target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code int} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static int min(int... array) { checkArgument(array.length > 0); int min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code int} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static int max(int... array) { checkArgument(array.length > 0); int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new int[] {a, b}, new int[] {}, new * int[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code int} arrays * @return a single array containing all the values from the source arrays, in * order */ public static int[] concat(int[]... arrays) { int length = 0; for (int[] array : arrays) { length += array.length; } int[] result = new int[length]; int pos = 0; for (int[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in a 4-element byte * array; equivalent to {@code ByteBuffer.allocate(4).putInt(value).array()}. * For example, the input value {@code 0x12131415} would yield the byte array * {@code {0x12, 0x13, 0x14, 0x15}}. * * <p>If you need to convert and concatenate several values (possibly even of * different types), use a shared {@link java.nio.ByteBuffer} instance, or use * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable * buffer. */ @GwtIncompatible("doesn't work") public static byte[] toByteArray(int value) { return new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value}; } /** * Returns the {@code int} value whose big-endian representation is stored in * the first 4 bytes of {@code bytes}; equivalent to {@code * ByteBuffer.wrap(bytes).getInt()}. For example, the input byte array {@code * {0x12, 0x13, 0x14, 0x15, 0x33}} would yield the {@code int} value {@code * 0x12131415}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that * library exposes much more flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 4 elements */ @GwtIncompatible("doesn't work") public static int fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]); } /** * Returns the {@code int} value whose byte representation is the given 4 * bytes, in big-endian order; equivalent to {@code Ints.fromByteArray(new * byte[] {b1, b2, b3, b4})}. * * @since 7.0 */ @GwtIncompatible("doesn't work") public static int fromBytes(byte b1, byte b2, byte b3, byte b4) { return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF); } private static final class IntConverter extends Converter<String, Integer> implements Serializable { static final IntConverter INSTANCE = new IntConverter(); @Override protected Integer doForward(String value) { return Integer.decode(value); } @Override protected String doBackward(Integer value) { return value.toString(); } @Override public String toString() { return "Ints.stringConverter()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } /** * Returns a serializable converter object that converts between strings and * integers using {@link Integer#decode} and {@link Integer#toString()}. * * @since 16.0 */ @Beta public static Converter<String, Integer> stringConverter() { return IntConverter.INSTANCE; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static int[] ensureCapacity( int[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static int[] copyOf(int[] original, int length) { int[] copy = new int[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code int} values separated * by {@code separator}. For example, {@code join("-", 1, 2, 3)} returns * the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code int} values, possibly empty */ public static String join(String separator, int... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code int} arrays * lexicographically. That is, it compares, using {@link * #compare(int, int)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, {@code [] < [1] < [1, 2] < [2]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(int[], int[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<int[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<int[]> { INSTANCE; @Override public int compare(int[] left, int[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Ints.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Returns an array containing each value of {@code collection}, converted to * a {@code int} value in the manner of {@link Number#intValue}. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null * @since 1.0 (parameter was {@code Collection<Integer>} before 12.0) */ public static int[] toArray(Collection<? extends Number> collection) { if (collection instanceof IntArrayAsList) { return ((IntArrayAsList) collection).toIntArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; int[] array = new int[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).intValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Integer} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Integer> asList(int... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new IntArrayAsList(backingArray); } @GwtCompatible private static class IntArrayAsList extends AbstractList<Integer> implements RandomAccess, Serializable { final int[] array; final int start; final int end; IntArrayAsList(int[] array) { this(array, 0, array.length); } IntArrayAsList(int[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Integer get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Integer) { int i = Ints.indexOf(array, (Integer) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Integer) { int i = Ints.lastIndexOf(array, (Integer) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Integer set(int index, Integer element) { checkElementIndex(index, size()); int oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Integer> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new IntArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof IntArrayAsList) { IntArrayAsList that = (IntArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Ints.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 5); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } int[] toIntArray() { // Arrays.copyOfRange() is not available under GWT int size = size(); int[] result = new int[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } private static final byte[] asciiDigits = new byte[128]; static { Arrays.fill(asciiDigits, (byte) -1); for (int i = 0; i <= 9; i++) { asciiDigits['0' + i] = (byte) i; } for (int i = 0; i <= 26; i++) { asciiDigits['A' + i] = (byte) (10 + i); asciiDigits['a' + i] = (byte) (10 + i); } } private static int digit(char c) { return (c < 128) ? asciiDigits[c] : -1; } /** * Parses the specified string as a signed decimal integer value. The ASCII * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the * minus sign. * * <p>Unlike {@link Integer#parseInt(String)}, this method returns * {@code null} instead of throwing an exception if parsing fails. * Additionally, this method only accepts ASCII digits, and returns * {@code null} if non-ASCII digits are present in the string. * * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even * under JDK 7, despite the change to {@link Integer#parseInt(String)} for * that version. * * @param string the string representation of an integer value * @return the integer value represented by {@code string}, or {@code null} if * {@code string} has a length of zero or cannot be parsed as an integer * value * @since 11.0 */ @Beta @CheckForNull @GwtIncompatible("TODO") public static Integer tryParse(String string) { return tryParse(string, 10); } /** * Parses the specified string as a signed integer value using the specified * radix. The ASCII character {@code '-'} (<code>'&#92;u002D'</code>) is * recognized as the minus sign. * * <p>Unlike {@link Integer#parseInt(String, int)}, this method returns * {@code null} instead of throwing an exception if parsing fails. * Additionally, this method only accepts ASCII digits, and returns * {@code null} if non-ASCII digits are present in the string. * * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even * under JDK 7, despite the change to {@link Integer#parseInt(String, int)} * for that version. * * @param string the string representation of an integer value * @param radix the radix to use when parsing * @return the integer value represented by {@code string} using * {@code radix}, or {@code null} if {@code string} has a length of zero * or cannot be parsed as an integer value * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or * {@code radix > Character.MAX_RADIX} */ @CheckForNull @GwtIncompatible("TODO") static Integer tryParse( String string, int radix) { if (checkNotNull(string).isEmpty()) { return null; } if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new IllegalArgumentException( "radix must be between MIN_RADIX and MAX_RADIX but was " + radix); } boolean negative = string.charAt(0) == '-'; int index = negative ? 1 : 0; if (index == string.length()) { return null; } int digit = digit(string.charAt(index++)); if (digit < 0 || digit >= radix) { return null; } int accum = -digit; int cap = Integer.MIN_VALUE / radix; while (index < string.length()) { digit = digit(string.charAt(index++)); if (digit < 0 || digit >= radix || accum < cap) { return null; } accum *= radix; if (accum < Integer.MIN_VALUE + digit) { return null; } accum -= digit; } if (negative) { return accum; } else if (accum == Integer.MIN_VALUE) { return null; } else { return -accum; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/Ints.java
Java
asf20
24,413
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import sun.misc.Unsafe; import java.nio.ByteOrder; import java.util.Comparator; /** * Static utility methods pertaining to {@code byte} primitives that interpret * values as <i>unsigned</i> (that is, any negative value {@code b} is treated * as the positive value {@code 256 + b}). The corresponding methods that treat * the values as signed are found in {@link SignedBytes}, and the methods for * which signedness is not an issue are in {@link Bytes}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @author Martin Buchholz * @author Hiroshi Yamauchi * @author Louis Wasserman * @since 1.0 */ public final class UnsignedBytes { private UnsignedBytes() {} /** * The largest power of two that can be represented as an unsigned {@code * byte}. * * @since 10.0 */ public static final byte MAX_POWER_OF_TWO = (byte) 0x80; /** * The largest value that fits into an unsigned byte. * * @since 13.0 */ public static final byte MAX_VALUE = (byte) 0xFF; private static final int UNSIGNED_MASK = 0xFF; /** * Returns the value of the given byte as an integer, when treated as * unsigned. That is, returns {@code value + 256} if {@code value} is * negative; {@code value} itself otherwise. * * @since 6.0 */ public static int toInt(byte value) { return value & UNSIGNED_MASK; } /** * Returns the {@code byte} value that, when treated as unsigned, is equal to * {@code value}, if possible. * * @param value a value between 0 and 255 inclusive * @return the {@code byte} value that, when treated as unsigned, equals * {@code value} * @throws IllegalArgumentException if {@code value} is negative or greater * than 255 */ public static byte checkedCast(long value) { if ((value >> Byte.SIZE) != 0) { // don't use checkArgument here, to avoid boxing throw new IllegalArgumentException("Out of range: " + value); } return (byte) value; } /** * Returns the {@code byte} value that, when treated as unsigned, is nearest * in value to {@code value}. * * @param value any {@code long} value * @return {@code (byte) 255} if {@code value >= 255}, {@code (byte) 0} if * {@code value <= 0}, and {@code value} cast to {@code byte} otherwise */ public static byte saturatedCast(long value) { if (value > toInt(MAX_VALUE)) { return MAX_VALUE; // -1 } if (value < 0) { return (byte) 0; } return (byte) value; } /** * Compares the two specified {@code byte} values, treating them as unsigned * values between 0 and 255 inclusive. For example, {@code (byte) -127} is * considered greater than {@code (byte) 127} because it is seen as having * the value of positive {@code 129}. * * @param a the first {@code byte} to compare * @param b the second {@code byte} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(byte a, byte b) { return toInt(a) - toInt(b); } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code byte} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static byte min(byte... array) { checkArgument(array.length > 0); int min = toInt(array[0]); for (int i = 1; i < array.length; i++) { int next = toInt(array[i]); if (next < min) { min = next; } } return (byte) min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code byte} values * @return the value present in {@code array} that is greater than or equal * to every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static byte max(byte... array) { checkArgument(array.length > 0); int max = toInt(array[0]); for (int i = 1; i < array.length; i++) { int next = toInt(array[i]); if (next > max) { max = next; } } return (byte) max; } /** * Returns a string representation of x, where x is treated as unsigned. * * @since 13.0 */ @Beta public static String toString(byte x) { return toString(x, 10); } /** * Returns a string representation of {@code x} for the given radix, where {@code x} is treated * as unsigned. * * @param x the value to convert to a string. * @param radix the radix to use while working with {@code x} * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX} * and {@link Character#MAX_RADIX}. * @since 13.0 */ @Beta public static String toString(byte x, int radix) { checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX, "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix); // Benchmarks indicate this is probably not worth optimizing. return Integer.toString(toInt(x), radix); } /** * Returns the unsigned {@code byte} value represented by the given decimal string. * * @throws NumberFormatException if the string does not contain a valid unsigned {@code byte} * value * @throws NullPointerException if {@code s} is null * (in contrast to {@link Byte#parseByte(String)}) * @since 13.0 */ @Beta public static byte parseUnsignedByte(String string) { return parseUnsignedByte(string, 10); } /** * Returns the unsigned {@code byte} value represented by a string with the given radix. * * @param string the string containing the unsigned {@code byte} representation to be parsed. * @param radix the radix to use while parsing {@code string} * @throws NumberFormatException if the string does not contain a valid unsigned {@code byte} * with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX} * and {@link Character#MAX_RADIX}. * @throws NullPointerException if {@code s} is null * (in contrast to {@link Byte#parseByte(String)}) * @since 13.0 */ @Beta public static byte parseUnsignedByte(String string, int radix) { int parse = Integer.parseInt(checkNotNull(string), radix); // We need to throw a NumberFormatException, so we have to duplicate checkedCast. =( if (parse >> Byte.SIZE == 0) { return (byte) parse; } else { throw new NumberFormatException("out of range: " + parse); } } /** * Returns a string containing the supplied {@code byte} values separated by * {@code separator}. For example, {@code join(":", (byte) 1, (byte) 2, * (byte) 255)} returns the string {@code "1:2:255"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code byte} values, possibly empty */ public static String join(String separator, byte... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * (3 + separator.length())); builder.append(toInt(array[0])); for (int i = 1; i < array.length; i++) { builder.append(separator).append(toString(array[i])); } return builder.toString(); } /** * Returns a comparator that compares two {@code byte} arrays * lexicographically. That is, it compares, using {@link * #compare(byte, byte)}), the first pair of values that follow any common * prefix, or when one array is a prefix of the other, treats the shorter * array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x7F] < * [0x01, 0x80] < [0x02]}. Values are treated as unsigned. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<byte[]> lexicographicalComparator() { return LexicographicalComparatorHolder.BEST_COMPARATOR; } @VisibleForTesting static Comparator<byte[]> lexicographicalComparatorJavaImpl() { return LexicographicalComparatorHolder.PureJavaComparator.INSTANCE; } /** * Provides a lexicographical comparator implementation; either a Java * implementation or a faster implementation based on {@link Unsafe}. * * <p>Uses reflection to gracefully fall back to the Java implementation if * {@code Unsafe} isn't available. */ @VisibleForTesting static class LexicographicalComparatorHolder { static final String UNSAFE_COMPARATOR_NAME = LexicographicalComparatorHolder.class.getName() + "$UnsafeComparator"; static final Comparator<byte[]> BEST_COMPARATOR = getBestComparator(); @VisibleForTesting enum UnsafeComparator implements Comparator<byte[]> { INSTANCE; static final boolean BIG_ENDIAN = ByteOrder.nativeOrder().equals(ByteOrder.BIG_ENDIAN); /* * The following static final fields exist for performance reasons. * * In UnsignedBytesBenchmark, accessing the following objects via static * final fields is the fastest (more than twice as fast as the Java * implementation, vs ~1.5x with non-final static fields, on x86_32) * under the Hotspot server compiler. The reason is obviously that the * non-final fields need to be reloaded inside the loop. * * And, no, defining (final or not) local variables out of the loop still * isn't as good because the null check on the theUnsafe object remains * inside the loop and BYTE_ARRAY_BASE_OFFSET doesn't get * constant-folded. * * The compiler can treat static final fields as compile-time constants * and can constant-fold them while (final or not) local variables are * run time values. */ static final Unsafe theUnsafe; /** The offset to the first element in a byte array. */ static final int BYTE_ARRAY_BASE_OFFSET; static { theUnsafe = getUnsafe(); BYTE_ARRAY_BASE_OFFSET = theUnsafe.arrayBaseOffset(byte[].class); // sanity check - this should never fail if (theUnsafe.arrayIndexScale(byte[].class) != 1) { throw new AssertionError(); } } /** * Returns a sun.misc.Unsafe. Suitable for use in a 3rd party package. * Replace with a simple call to Unsafe.getUnsafe when integrating * into a jdk. * * @return a sun.misc.Unsafe */ private static sun.misc.Unsafe getUnsafe() { try { return sun.misc.Unsafe.getUnsafe(); } catch (SecurityException tryReflectionInstead) {} try { return java.security.AccessController.doPrivileged (new java.security.PrivilegedExceptionAction<sun.misc.Unsafe>() { public sun.misc.Unsafe run() throws Exception { Class<sun.misc.Unsafe> k = sun.misc.Unsafe.class; for (java.lang.reflect.Field f : k.getDeclaredFields()) { f.setAccessible(true); Object x = f.get(null); if (k.isInstance(x)) return k.cast(x); } throw new NoSuchFieldError("the Unsafe"); }}); } catch (java.security.PrivilegedActionException e) { throw new RuntimeException("Could not initialize intrinsics", e.getCause()); } } @Override public int compare(byte[] left, byte[] right) { int minLength = Math.min(left.length, right.length); int minWords = minLength / Longs.BYTES; /* * Compare 8 bytes at a time. Benchmarking shows comparing 8 bytes at a * time is no slower than comparing 4 bytes at a time even on 32-bit. * On the other hand, it is substantially faster on 64-bit. */ for (int i = 0; i < minWords * Longs.BYTES; i += Longs.BYTES) { long lw = theUnsafe.getLong(left, BYTE_ARRAY_BASE_OFFSET + (long) i); long rw = theUnsafe.getLong(right, BYTE_ARRAY_BASE_OFFSET + (long) i); if (lw != rw) { if (BIG_ENDIAN) { return UnsignedLongs.compare(lw, rw); } /* * We want to compare only the first index where left[index] != right[index]. * This corresponds to the least significant nonzero byte in lw ^ rw, since lw * and rw are little-endian. Long.numberOfTrailingZeros(diff) tells us the least * significant nonzero bit, and zeroing out the first three bits of L.nTZ gives us the * shift to get that least significant nonzero byte. */ int n = Long.numberOfTrailingZeros(lw ^ rw) & ~0x7; return (int) (((lw >>> n) & UNSIGNED_MASK) - ((rw >>> n) & UNSIGNED_MASK)); } } // The epilogue to cover the last (minLength % 8) elements. for (int i = minWords * Longs.BYTES; i < minLength; i++) { int result = UnsignedBytes.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } enum PureJavaComparator implements Comparator<byte[]> { INSTANCE; @Override public int compare(byte[] left, byte[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = UnsignedBytes.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Returns the Unsafe-using Comparator, or falls back to the pure-Java * implementation if unable to do so. */ static Comparator<byte[]> getBestComparator() { try { Class<?> theClass = Class.forName(UNSAFE_COMPARATOR_NAME); // yes, UnsafeComparator does implement Comparator<byte[]> @SuppressWarnings("unchecked") Comparator<byte[]> comparator = (Comparator<byte[]>) theClass.getEnumConstants()[0]; return comparator; } catch (Throwable t) { // ensure we really catch *everything* return lexicographicalComparatorJavaImpl(); } } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/UnsignedBytes.java
Java
asf20
16,055
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Set; /** * Contains static utility methods pertaining to primitive types and their * corresponding wrapper types. * * @author Kevin Bourrillion * @since 1.0 */ public final class Primitives { private Primitives() {} /** A map from primitive types to their corresponding wrapper types. */ private static final Map<Class<?>, Class<?>> PRIMITIVE_TO_WRAPPER_TYPE; /** A map from wrapper types to their corresponding primitive types. */ private static final Map<Class<?>, Class<?>> WRAPPER_TO_PRIMITIVE_TYPE; // Sad that we can't use a BiMap. :( static { Map<Class<?>, Class<?>> primToWrap = new HashMap<Class<?>, Class<?>>(16); Map<Class<?>, Class<?>> wrapToPrim = new HashMap<Class<?>, Class<?>>(16); add(primToWrap, wrapToPrim, boolean.class, Boolean.class); add(primToWrap, wrapToPrim, byte.class, Byte.class); add(primToWrap, wrapToPrim, char.class, Character.class); add(primToWrap, wrapToPrim, double.class, Double.class); add(primToWrap, wrapToPrim, float.class, Float.class); add(primToWrap, wrapToPrim, int.class, Integer.class); add(primToWrap, wrapToPrim, long.class, Long.class); add(primToWrap, wrapToPrim, short.class, Short.class); add(primToWrap, wrapToPrim, void.class, Void.class); PRIMITIVE_TO_WRAPPER_TYPE = Collections.unmodifiableMap(primToWrap); WRAPPER_TO_PRIMITIVE_TYPE = Collections.unmodifiableMap(wrapToPrim); } private static void add(Map<Class<?>, Class<?>> forward, Map<Class<?>, Class<?>> backward, Class<?> key, Class<?> value) { forward.put(key, value); backward.put(value, key); } /** * Returns an immutable set of all nine primitive types (including {@code * void}). Note that a simpler way to test whether a {@code Class} instance * is a member of this set is to call {@link Class#isPrimitive}. * * @since 3.0 */ public static Set<Class<?>> allPrimitiveTypes() { return PRIMITIVE_TO_WRAPPER_TYPE.keySet(); } /** * Returns an immutable set of all nine primitive-wrapper types (including * {@link Void}). * * @since 3.0 */ public static Set<Class<?>> allWrapperTypes() { return WRAPPER_TO_PRIMITIVE_TYPE.keySet(); } /** * Returns {@code true} if {@code type} is one of the nine * primitive-wrapper types, such as {@link Integer}. * * @see Class#isPrimitive */ public static boolean isWrapperType(Class<?> type) { return WRAPPER_TO_PRIMITIVE_TYPE.containsKey(checkNotNull(type)); } /** * Returns the corresponding wrapper type of {@code type} if it is a primitive * type; otherwise returns {@code type} itself. Idempotent. * <pre> * wrap(int.class) == Integer.class * wrap(Integer.class) == Integer.class * wrap(String.class) == String.class * </pre> */ public static <T> Class<T> wrap(Class<T> type) { checkNotNull(type); // cast is safe: long.class and Long.class are both of type Class<Long> @SuppressWarnings("unchecked") Class<T> wrapped = (Class<T>) PRIMITIVE_TO_WRAPPER_TYPE.get(type); return (wrapped == null) ? type : wrapped; } /** * Returns the corresponding primitive type of {@code type} if it is a * wrapper type; otherwise returns {@code type} itself. Idempotent. * <pre> * unwrap(Integer.class) == int.class * unwrap(int.class) == int.class * unwrap(String.class) == String.class * </pre> */ public static <T> Class<T> unwrap(Class<T> type) { checkNotNull(type); // cast is safe: long.class and Long.class are both of type Class<Long> @SuppressWarnings("unchecked") Class<T> unwrapped = (Class<T>) WRAPPER_TO_PRIMITIVE_TYPE.get(type); return (unwrapped == null) ? type : unwrapped; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/Primitives.java
Java
asf20
4,545
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; /** * Static utility methods pertaining to {@code byte} primitives that * interpret values as signed. The corresponding methods that treat the values * as unsigned are found in {@link UnsignedBytes}, and the methods for which * signedness is not an issue are in {@link Bytes}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ // TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT // javadoc? @GwtCompatible public final class SignedBytes { private SignedBytes() {} /** * The largest power of two that can be represented as a signed {@code byte}. * * @since 10.0 */ public static final byte MAX_POWER_OF_TWO = 1 << 6; /** * Returns the {@code byte} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code byte} type * @return the {@code byte} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link * Byte#MAX_VALUE} or less than {@link Byte#MIN_VALUE} */ public static byte checkedCast(long value) { byte result = (byte) value; if (result != value) { // don't use checkArgument here, to avoid boxing throw new IllegalArgumentException("Out of range: " + value); } return result; } /** * Returns the {@code byte} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code byte} if it is in the range of the * {@code byte} type, {@link Byte#MAX_VALUE} if it is too large, * or {@link Byte#MIN_VALUE} if it is too small */ public static byte saturatedCast(long value) { if (value > Byte.MAX_VALUE) { return Byte.MAX_VALUE; } if (value < Byte.MIN_VALUE) { return Byte.MIN_VALUE; } return (byte) value; } /** * Compares the two specified {@code byte} values. The sign of the value * returned is the same as that of {@code ((Byte) a).compareTo(b)}. * * <p><b>Note:</b> this method behaves identically to the JDK 7 method {@link * Byte#compare}. * * @param a the first {@code byte} to compare * @param b the second {@code byte} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ // TODO(kevinb): if Ints.compare etc. are ever removed, *maybe* remove this // one too, which would leave compare methods only on the Unsigned* classes. public static int compare(byte a, byte b) { return a - b; // safe due to restricted range } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code byte} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static byte min(byte... array) { checkArgument(array.length > 0); byte min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code byte} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static byte max(byte... array) { checkArgument(array.length > 0); byte max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns a string containing the supplied {@code byte} values separated * by {@code separator}. For example, {@code join(":", 0x01, 0x02, -0x01)} * returns the string {@code "1:2:-1"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code byte} values, possibly empty */ public static String join(String separator, byte... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code byte} arrays * lexicographically. That is, it compares, using {@link * #compare(byte, byte)}), the first pair of values that follow any common * prefix, or when one array is a prefix of the other, treats the shorter * array as the lesser. For example, {@code [] < [0x01] < [0x01, 0x80] < * [0x01, 0x7F] < [0x02]}. Values are treated as signed. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link java.util.Arrays#equals(byte[], byte[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<byte[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<byte[]> { INSTANCE; @Override public int compare(byte[] left, byte[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = SignedBytes.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/SignedBytes.java
Java
asf20
6,956
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code char} primitives, that are not * already found in either {@link Character} or {@link Arrays}. * * <p>All the operations in this class treat {@code char} values strictly * numerically; they are neither Unicode-aware nor locale-dependent. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Chars { private Chars() {} /** * The number of bytes required to represent a primitive {@code char} * value. */ public static final int BYTES = Character.SIZE / Byte.SIZE; /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Character) value).hashCode()}. * * @param value a primitive {@code char} value * @return a hash code for the value */ public static int hashCode(char value) { return value; } /** * Returns the {@code char} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code char} type * @return the {@code char} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link * Character#MAX_VALUE} or less than {@link Character#MIN_VALUE} */ public static char checkedCast(long value) { char result = (char) value; if (result != value) { // don't use checkArgument here, to avoid boxing throw new IllegalArgumentException("Out of range: " + value); } return result; } /** * Returns the {@code char} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code char} if it is in the range of the * {@code char} type, {@link Character#MAX_VALUE} if it is too large, * or {@link Character#MIN_VALUE} if it is too small */ public static char saturatedCast(long value) { if (value > Character.MAX_VALUE) { return Character.MAX_VALUE; } if (value < Character.MIN_VALUE) { return Character.MIN_VALUE; } return (char) value; } /** * Compares the two specified {@code char} values. The sign of the value * returned is the same as that of {@code ((Character) a).compareTo(b)}. * * <p><b>Note:</b> projects using JDK 7 or later should use the equivalent * {@link Character#compare} method instead. * * @param a the first {@code char} to compare * @param b the second {@code char} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(char a, char b) { return a - b; // safe due to restricted range } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(char[] array, char target) { for (char value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(char[] array, char target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( char[] array, char target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(char[] array, char[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(char[] array, char target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( char[] array, char target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code char} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static char min(char... array) { checkArgument(array.length > 0); char min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code char} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static char max(char... array) { checkArgument(array.length > 0); char max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new char[] {a, b}, new char[] {}, new * char[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code char} arrays * @return a single array containing all the values from the source arrays, in * order */ public static char[] concat(char[]... arrays) { int length = 0; for (char[] array : arrays) { length += array.length; } char[] result = new char[length]; int pos = 0; for (char[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in a 2-element byte * array; equivalent to {@code * ByteBuffer.allocate(2).putChar(value).array()}. For example, the input * value {@code '\\u5432'} would yield the byte array {@code {0x54, 0x32}}. * * <p>If you need to convert and concatenate several values (possibly even of * different types), use a shared {@link java.nio.ByteBuffer} instance, or use * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable * buffer. */ @GwtIncompatible("doesn't work") public static byte[] toByteArray(char value) { return new byte[] { (byte) (value >> 8), (byte) value}; } /** * Returns the {@code char} value whose big-endian representation is * stored in the first 2 bytes of {@code bytes}; equivalent to {@code * ByteBuffer.wrap(bytes).getChar()}. For example, the input byte array * {@code {0x54, 0x32}} would yield the {@code char} value {@code '\\u5432'}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that * library exposes much more flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 2 * elements */ @GwtIncompatible("doesn't work") public static char fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1]); } /** * Returns the {@code char} value whose byte representation is the given 2 * bytes, in big-endian order; equivalent to {@code Chars.fromByteArray(new * byte[] {b1, b2})}. * * @since 7.0 */ @GwtIncompatible("doesn't work") public static char fromBytes(byte b1, byte b2) { return (char) ((b1 << 8) | (b2 & 0xFF)); } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static char[] ensureCapacity( char[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static char[] copyOf(char[] original, int length) { char[] copy = new char[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code char} values separated * by {@code separator}. For example, {@code join("-", '1', '2', '3')} returns * the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code char} values, possibly empty */ public static String join(String separator, char... array) { checkNotNull(separator); int len = array.length; if (len == 0) { return ""; } StringBuilder builder = new StringBuilder(len + separator.length() * (len - 1)); builder.append(array[0]); for (int i = 1; i < len; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code char} arrays * lexicographically. That is, it compares, using {@link * #compare(char, char)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, * {@code [] < ['a'] < ['a', 'b'] < ['b']}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(char[], char[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<char[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<char[]> { INSTANCE; @Override public int compare(char[] left, char[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Chars.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Copies a collection of {@code Character} instances into a new array of * primitive {@code char} values. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Character} objects * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null */ public static char[] toArray(Collection<Character> collection) { if (collection instanceof CharArrayAsList) { return ((CharArrayAsList) collection).toCharArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; char[] array = new char[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = (Character) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Character} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Character> asList(char... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new CharArrayAsList(backingArray); } @GwtCompatible private static class CharArrayAsList extends AbstractList<Character> implements RandomAccess, Serializable { final char[] array; final int start; final int end; CharArrayAsList(char[] array) { this(array, 0, array.length); } CharArrayAsList(char[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Character get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Character) && Chars.indexOf(array, (Character) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Character) { int i = Chars.indexOf(array, (Character) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Character) { int i = Chars.lastIndexOf(array, (Character) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Character set(int index, Character element) { checkElementIndex(index, size()); char oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Character> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new CharArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof CharArrayAsList) { CharArrayAsList that = (CharArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Chars.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 3); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } char[] toCharArray() { // Arrays.copyOfRange() is not available under GWT int size = size(); char[] result = new char[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/Chars.java
Java
asf20
19,552
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; /** * Static utility methods pertaining to {@code long} primitives that interpret values as * <i>unsigned</i> (that is, any negative value {@code x} is treated as the positive value * {@code 2^64 + x}). The methods for which signedness is not an issue are in {@link Longs}, as * well as signed versions of methods for which signedness is an issue. * * <p>In addition, this class provides several static methods for converting a {@code long} to a * {@code String} and a {@code String} to a {@code long} that treat the {@code long} as an unsigned * number. * * <p>Users of these utilities must be <i>extremely careful</i> not to mix up signed and unsigned * {@code long} values. When possible, it is recommended that the {@link UnsignedLong} wrapper * class be used, at a small efficiency penalty, to enforce the distinction in the type system. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support"> * unsigned primitive utilities</a>. * * @author Louis Wasserman * @author Brian Milch * @author Colin Evans * @since 10.0 */ @Beta @GwtCompatible public final class UnsignedLongs { private UnsignedLongs() {} public static final long MAX_VALUE = -1L; // Equivalent to 2^64 - 1 /** * A (self-inverse) bijection which converts the ordering on unsigned longs to the ordering on * longs, that is, {@code a <= b} as unsigned longs if and only if {@code flip(a) <= flip(b)} * as signed longs. */ private static long flip(long a) { return a ^ Long.MIN_VALUE; } /** * Compares the two specified {@code long} values, treating them as unsigned values between * {@code 0} and {@code 2^64 - 1} inclusive. * * @param a the first unsigned {@code long} to compare * @param b the second unsigned {@code long} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(long a, long b) { return Longs.compare(flip(a), flip(b)); } /** * Returns the least value present in {@code array}, treating values as unsigned. * * @param array a <i>nonempty</i> array of unsigned {@code long} values * @return the value present in {@code array} that is less than or equal to every other value in * the array according to {@link #compare} * @throws IllegalArgumentException if {@code array} is empty */ public static long min(long... array) { checkArgument(array.length > 0); long min = flip(array[0]); for (int i = 1; i < array.length; i++) { long next = flip(array[i]); if (next < min) { min = next; } } return flip(min); } /** * Returns the greatest value present in {@code array}, treating values as unsigned. * * @param array a <i>nonempty</i> array of unsigned {@code long} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array according to {@link #compare} * @throws IllegalArgumentException if {@code array} is empty */ public static long max(long... array) { checkArgument(array.length > 0); long max = flip(array[0]); for (int i = 1; i < array.length; i++) { long next = flip(array[i]); if (next > max) { max = next; } } return flip(max); } /** * Returns a string containing the supplied unsigned {@code long} values separated by * {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting * string (but not at the start or end) * @param array an array of unsigned {@code long} values, possibly empty */ public static String join(String separator, long... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(toString(array[0])); for (int i = 1; i < array.length; i++) { builder.append(separator).append(toString(array[i])); } return builder.toString(); } /** * Returns a comparator that compares two arrays of unsigned {@code long} values * lexicographically. That is, it compares, using {@link #compare(long, long)}), the first pair of * values that follow any common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, {@code [] < [1L] < [1L, 2L] < [2L] < [1L << 63]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with * {@link Arrays#equals(long[], long[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order">Lexicographical order * article at Wikipedia</a> */ public static Comparator<long[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } enum LexicographicalComparator implements Comparator<long[]> { INSTANCE; @Override public int compare(long[] left, long[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { if (left[i] != right[i]) { return UnsignedLongs.compare(left[i], right[i]); } } return left.length - right.length; } } /** * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 64-bit * quantities. * * @param dividend the dividend (numerator) * @param divisor the divisor (denominator) * @throws ArithmeticException if divisor is 0 */ public static long divide(long dividend, long divisor) { if (divisor < 0) { // i.e., divisor >= 2^63: if (compare(dividend, divisor) < 0) { return 0; // dividend < divisor } else { return 1; // dividend >= divisor } } // Optimization - use signed division if dividend < 2^63 if (dividend >= 0) { return dividend / divisor; } /* * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is * guaranteed to be either exact or one less than the correct value. This follows from fact * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not * quite trivial. */ long quotient = ((dividend >>> 1) / divisor) << 1; long rem = dividend - quotient * divisor; return quotient + (compare(rem, divisor) >= 0 ? 1 : 0); } /** * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 64-bit * quantities. * * @param dividend the dividend (numerator) * @param divisor the divisor (denominator) * @throws ArithmeticException if divisor is 0 * @since 11.0 */ public static long remainder(long dividend, long divisor) { if (divisor < 0) { // i.e., divisor >= 2^63: if (compare(dividend, divisor) < 0) { return dividend; // dividend < divisor } else { return dividend - divisor; // dividend >= divisor } } // Optimization - use signed modulus if dividend < 2^63 if (dividend >= 0) { return dividend % divisor; } /* * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is * guaranteed to be either exact or one less than the correct value. This follows from fact * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not * quite trivial. */ long quotient = ((dividend >>> 1) / divisor) << 1; long rem = dividend - quotient * divisor; return rem - (compare(rem, divisor) >= 0 ? divisor : 0); } /** * Returns the unsigned {@code long} value represented by the given decimal string. * * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} * value * @throws NullPointerException if {@code s} is null * (in contrast to {@link Long#parseLong(String)}) */ public static long parseUnsignedLong(String s) { return parseUnsignedLong(s, 10); } /** * Returns the unsigned {@code long} value represented by the given string. * * Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix: * * <ul> * <li>{@code 0x}<i>HexDigits</i> * <li>{@code 0X}<i>HexDigits</i> * <li>{@code #}<i>HexDigits</i> * <li>{@code 0}<i>OctalDigits</i> * </ul> * * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} * value * @since 13.0 */ public static long decode(String stringValue) { ParseRequest request = ParseRequest.fromString(stringValue); try { return parseUnsignedLong(request.rawValue, request.radix); } catch (NumberFormatException e) { NumberFormatException decodeException = new NumberFormatException("Error parsing value: " + stringValue); decodeException.initCause(e); throw decodeException; } } /** * Returns the unsigned {@code long} value represented by a string with the given radix. * * @param s the string containing the unsigned {@code long} representation to be parsed. * @param radix the radix to use while parsing {@code s} * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} * with the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX} * and {@link Character#MAX_RADIX}. * @throws NullPointerException if {@code s} is null * (in contrast to {@link Long#parseLong(String)}) */ public static long parseUnsignedLong(String s, int radix) { checkNotNull(s); if (s.length() == 0) { throw new NumberFormatException("empty string"); } if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new NumberFormatException("illegal radix: " + radix); } int max_safe_pos = maxSafeDigits[radix] - 1; long value = 0; for (int pos = 0; pos < s.length(); pos++) { int digit = Character.digit(s.charAt(pos), radix); if (digit == -1) { throw new NumberFormatException(s); } if (pos > max_safe_pos && overflowInParse(value, digit, radix)) { throw new NumberFormatException("Too large for unsigned long: " + s); } value = (value * radix) + digit; } return value; } /** * Returns true if (current * radix) + digit is a number too large to be represented by an * unsigned long. This is useful for detecting overflow while parsing a string representation of * a number. Does not verify whether supplied radix is valid, passing an invalid radix will give * undefined results or an ArrayIndexOutOfBoundsException. */ private static boolean overflowInParse(long current, int digit, int radix) { if (current >= 0) { if (current < maxValueDivs[radix]) { return false; } if (current > maxValueDivs[radix]) { return true; } // current == maxValueDivs[radix] return (digit > maxValueMods[radix]); } // current < 0: high bit is set return true; } /** * Returns a string representation of x, where x is treated as unsigned. */ public static String toString(long x) { return toString(x, 10); } /** * Returns a string representation of {@code x} for the given radix, where {@code x} is treated * as unsigned. * * @param x the value to convert to a string. * @param radix the radix to use while working with {@code x} * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX} * and {@link Character#MAX_RADIX}. */ public static String toString(long x, int radix) { checkArgument(radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX, "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix); if (x == 0) { // Simply return "0" return "0"; } else { char[] buf = new char[64]; int i = buf.length; if (x < 0) { // Separate off the last digit using unsigned division. That will leave // a number that is nonnegative as a signed integer. long quotient = divide(x, radix); long rem = x - quotient * radix; buf[--i] = Character.forDigit((int) rem, radix); x = quotient; } // Simple modulo/division approach while (x > 0) { buf[--i] = Character.forDigit((int) (x % radix), radix); x /= radix; } // Generate string return new String(buf, i, buf.length - i); } } // calculated as 0xffffffffffffffff / radix private static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1]; private static final int[] maxValueMods = new int[Character.MAX_RADIX + 1]; private static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1]; static { BigInteger overflow = new BigInteger("10000000000000000", 16); for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) { maxValueDivs[i] = divide(MAX_VALUE, i); maxValueMods[i] = (int) remainder(MAX_VALUE, i); maxSafeDigits[i] = overflow.toString(i).length() - 1; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/UnsignedLongs.java
Java
asf20
14,512
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import static java.lang.Double.NEGATIVE_INFINITY; import static java.lang.Double.POSITIVE_INFINITY; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Converter; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import java.util.regex.Pattern; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@code double} primitives, that are not * already found in either {@link Double} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Doubles { private Doubles() {} /** * The number of bytes required to represent a primitive {@code double} * value. * * @since 10.0 */ public static final int BYTES = Double.SIZE / Byte.SIZE; /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Double) value).hashCode()}. * * @param value a primitive {@code double} value * @return a hash code for the value */ public static int hashCode(double value) { return ((Double) value).hashCode(); // TODO(kevinb): do it this way when we can (GWT problem): // long bits = Double.doubleToLongBits(value); // return (int) (bits ^ (bits >>> 32)); } /** * Compares the two specified {@code double} values. The sign of the value * returned is the same as that of <code>((Double) a).{@linkplain * Double#compareTo compareTo}(b)</code>. As with that method, {@code NaN} is * treated as greater than all other values, and {@code 0.0 > -0.0}. * * <p><b>Note:</b> this method simply delegates to the JDK method {@link * Double#compare}. It is provided for consistency with the other primitive * types, whose compare methods were not added to the JDK until JDK 7. * * @param a the first {@code double} to compare * @param b the second {@code double} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(double a, double b) { return Double.compare(a, b); } /** * Returns {@code true} if {@code value} represents a real number. This is * equivalent to, but not necessarily implemented as, * {@code !(Double.isInfinite(value) || Double.isNaN(value))}. * * @since 10.0 */ public static boolean isFinite(double value) { return NEGATIVE_INFINITY < value & value < POSITIVE_INFINITY; } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. Note that this always returns {@code false} when {@code * target} is {@code NaN}. * * @param array an array of {@code double} values, possibly empty * @param target a primitive {@code double} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(double[] array, double target) { for (double value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. Note that this always returns {@code -1} when {@code target} * is {@code NaN}. * * @param array an array of {@code double} values, possibly empty * @param target a primitive {@code double} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(double[] array, double target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( double[] array, double target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * <p>Note that this always returns {@code -1} when {@code target} contains * {@code NaN}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(double[] array, double[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. Note that this always returns {@code -1} when {@code target} * is {@code NaN}. * * @param array an array of {@code double} values, possibly empty * @param target a primitive {@code double} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(double[] array, double target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( double[] array, double target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}, using the same rules of * comparison as {@link Math#min(double, double)}. * * @param array a <i>nonempty</i> array of {@code double} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static double min(double... array) { checkArgument(array.length > 0); double min = array[0]; for (int i = 1; i < array.length; i++) { min = Math.min(min, array[i]); } return min; } /** * Returns the greatest value present in {@code array}, using the same rules * of comparison as {@link Math#max(double, double)}. * * @param array a <i>nonempty</i> array of {@code double} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static double max(double... array) { checkArgument(array.length > 0); double max = array[0]; for (int i = 1; i < array.length; i++) { max = Math.max(max, array[i]); } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new double[] {a, b}, new double[] {}, new * double[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code double} arrays * @return a single array containing all the values from the source arrays, in * order */ public static double[] concat(double[]... arrays) { int length = 0; for (double[] array : arrays) { length += array.length; } double[] result = new double[length]; int pos = 0; for (double[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } private static final class DoubleConverter extends Converter<String, Double> implements Serializable { static final DoubleConverter INSTANCE = new DoubleConverter(); @Override protected Double doForward(String value) { return Double.valueOf(value); } @Override protected String doBackward(Double value) { return value.toString(); } @Override public String toString() { return "Doubles.stringConverter()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } /** * Returns a serializable converter object that converts between strings and * doubles using {@link Double#valueOf} and {@link Double#toString()}. * * @since 16.0 */ @Beta public static Converter<String, Double> stringConverter() { return DoubleConverter.INSTANCE; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static double[] ensureCapacity( double[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static double[] copyOf(double[] original, int length) { double[] copy = new double[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code double} values, converted * to strings as specified by {@link Double#toString(double)}, and separated * by {@code separator}. For example, {@code join("-", 1.0, 2.0, 3.0)} returns * the string {@code "1.0-2.0-3.0"}. * * <p>Note that {@link Double#toString(double)} formats {@code double} * differently in GWT sometimes. In the previous example, it returns the * string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code double} values, possibly empty */ public static String join(String separator, double... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 12); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code double} arrays * lexicographically. That is, it compares, using {@link * #compare(double, double)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, * {@code [] < [1.0] < [1.0, 2.0] < [2.0]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(double[], double[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<double[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<double[]> { INSTANCE; @Override public int compare(double[] left, double[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Doubles.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Returns an array containing each value of {@code collection}, converted to * a {@code double} value in the manner of {@link Number#doubleValue}. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null * @since 1.0 (parameter was {@code Collection<Double>} before 12.0) */ public static double[] toArray(Collection<? extends Number> collection) { if (collection instanceof DoubleArrayAsList) { return ((DoubleArrayAsList) collection).toDoubleArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; double[] array = new double[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Double} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * <p>The returned list may have unexpected behavior if it contains {@code * NaN}, or if {@code NaN} is used as a parameter to any of its methods. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Double> asList(double... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new DoubleArrayAsList(backingArray); } @GwtCompatible private static class DoubleArrayAsList extends AbstractList<Double> implements RandomAccess, Serializable { final double[] array; final int start; final int end; DoubleArrayAsList(double[] array) { this(array, 0, array.length); } DoubleArrayAsList(double[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Double get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Double) && Doubles.indexOf(array, (Double) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Double) { int i = Doubles.indexOf(array, (Double) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Double) { int i = Doubles.lastIndexOf(array, (Double) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Double set(int index, Double element) { checkElementIndex(index, size()); double oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Double> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new DoubleArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof DoubleArrayAsList) { DoubleArrayAsList that = (DoubleArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Doubles.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 12); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } double[] toDoubleArray() { // Arrays.copyOfRange() is not available under GWT int size = size(); double[] result = new double[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } /** * This is adapted from the regex suggested by {@link Double#valueOf(String)} * for prevalidating inputs. All valid inputs must pass this regex, but it's * semantically fine if not all inputs that pass this regex are valid -- * only a performance hit is incurred, not a semantics bug. */ @GwtIncompatible("regular expressions") static final Pattern FLOATING_POINT_PATTERN = fpPattern(); @GwtIncompatible("regular expressions") private static Pattern fpPattern() { String decimal = "(?:\\d++(?:\\.\\d*+)?|\\.\\d++)"; String completeDec = decimal + "(?:[eE][+-]?\\d++)?[fFdD]?"; String hex = "(?:\\p{XDigit}++(?:\\.\\p{XDigit}*+)?|\\.\\p{XDigit}++)"; String completeHex = "0[xX]" + hex + "[pP][+-]?\\d++[fFdD]?"; String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")"; return Pattern.compile(fpPattern); } /** * Parses the specified string as a double-precision floating point value. * The ASCII character {@code '-'} (<code>'&#92;u002D'</code>) is recognized * as the minus sign. * * <p>Unlike {@link Double#parseDouble(String)}, this method returns * {@code null} instead of throwing an exception if parsing fails. * Valid inputs are exactly those accepted by {@link Double#valueOf(String)}, * except that leading and trailing whitespace is not permitted. * * <p>This implementation is likely to be faster than {@code * Double.parseDouble} if many failures are expected. * * @param string the string representation of a {@code double} value * @return the floating point value represented by {@code string}, or * {@code null} if {@code string} has a length of zero or cannot be * parsed as a {@code double} value * @since 14.0 */ @GwtIncompatible("regular expressions") @Nullable @Beta public static Double tryParse(String string) { if (FLOATING_POINT_PATTERN.matcher(string).matches()) { // TODO(user): could be potentially optimized, but only with // extensive testing try { return Double.parseDouble(string); } catch (NumberFormatException e) { // Double.parseDouble has changed specs several times, so fall through // gracefully } } return null; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/Doubles.java
Java
asf20
21,756
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.Arrays; import java.util.Comparator; /** * Static utility methods pertaining to {@code int} primitives that interpret values as * <i>unsigned</i> (that is, any negative value {@code x} is treated as the positive value * {@code 2^32 + x}). The methods for which signedness is not an issue are in {@link Ints}, as well * as signed versions of methods for which signedness is an issue. * * <p>In addition, this class provides several static methods for converting an {@code int} to a * {@code String} and a {@code String} to an {@code int} that treat the {@code int} as an unsigned * number. * * <p>Users of these utilities must be <i>extremely careful</i> not to mix up signed and unsigned * {@code int} values. When possible, it is recommended that the {@link UnsignedInteger} wrapper * class be used, at a small efficiency penalty, to enforce the distinction in the type system. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support"> * unsigned primitive utilities</a>. * * @author Louis Wasserman * @since 11.0 */ @Beta @GwtCompatible public final class UnsignedInts { static final long INT_MASK = 0xffffffffL; private UnsignedInts() {} static int flip(int value) { return value ^ Integer.MIN_VALUE; } /** * Compares the two specified {@code int} values, treating them as unsigned values between * {@code 0} and {@code 2^32 - 1} inclusive. * * @param a the first unsigned {@code int} to compare * @param b the second unsigned {@code int} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(int a, int b) { return Ints.compare(flip(a), flip(b)); } /** * Returns the value of the given {@code int} as a {@code long}, when treated as unsigned. */ public static long toLong(int value) { return value & INT_MASK; } /** * Returns the least value present in {@code array}, treating values as unsigned. * * @param array a <i>nonempty</i> array of unsigned {@code int} values * @return the value present in {@code array} that is less than or equal to every other value in * the array according to {@link #compare} * @throws IllegalArgumentException if {@code array} is empty */ public static int min(int... array) { checkArgument(array.length > 0); int min = flip(array[0]); for (int i = 1; i < array.length; i++) { int next = flip(array[i]); if (next < min) { min = next; } } return flip(min); } /** * Returns the greatest value present in {@code array}, treating values as unsigned. * * @param array a <i>nonempty</i> array of unsigned {@code int} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array according to {@link #compare} * @throws IllegalArgumentException if {@code array} is empty */ public static int max(int... array) { checkArgument(array.length > 0); int max = flip(array[0]); for (int i = 1; i < array.length; i++) { int next = flip(array[i]); if (next > max) { max = next; } } return flip(max); } /** * Returns a string containing the supplied unsigned {@code int} values separated by * {@code separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting * string (but not at the start or end) * @param array an array of unsigned {@code int} values, possibly empty */ public static String join(String separator, int... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(toString(array[0])); for (int i = 1; i < array.length; i++) { builder.append(separator).append(toString(array[i])); } return builder.toString(); } /** * Returns a comparator that compares two arrays of unsigned {@code int} values lexicographically. * That is, it compares, using {@link #compare(int, int)}), the first pair of values that follow * any common prefix, or when one array is a prefix of the other, treats the shorter array as the * lesser. For example, {@code [] < [1] < [1, 2] < [2] < [1 << 31]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> Lexicographical order * article at Wikipedia</a> */ public static Comparator<int[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } enum LexicographicalComparator implements Comparator<int[]> { INSTANCE; @Override public int compare(int[] left, int[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { if (left[i] != right[i]) { return UnsignedInts.compare(left[i], right[i]); } } return left.length - right.length; } } /** * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 32-bit * quantities. * * @param dividend the dividend (numerator) * @param divisor the divisor (denominator) * @throws ArithmeticException if divisor is 0 */ public static int divide(int dividend, int divisor) { return (int) (toLong(dividend) / toLong(divisor)); } /** * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 32-bit * quantities. * * @param dividend the dividend (numerator) * @param divisor the divisor (denominator) * @throws ArithmeticException if divisor is 0 */ public static int remainder(int dividend, int divisor) { return (int) (toLong(dividend) % toLong(divisor)); } /** * Returns the unsigned {@code int} value represented by the given string. * * Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix: * * <ul> * <li>{@code 0x}<i>HexDigits</i> * <li>{@code 0X}<i>HexDigits</i> * <li>{@code #}<i>HexDigits</i> * <li>{@code 0}<i>OctalDigits</i> * </ul> * * @throws NumberFormatException if the string does not contain a valid unsigned {@code int} value * @since 13.0 */ public static int decode(String stringValue) { ParseRequest request = ParseRequest.fromString(stringValue); try { return parseUnsignedInt(request.rawValue, request.radix); } catch (NumberFormatException e) { NumberFormatException decodeException = new NumberFormatException("Error parsing value: " + stringValue); decodeException.initCause(e); throw decodeException; } } /** * Returns the unsigned {@code int} value represented by the given decimal string. * * @throws NumberFormatException if the string does not contain a valid unsigned {@code int} value * @throws NullPointerException if {@code s} is null * (in contrast to {@link Integer#parseInt(String)}) */ public static int parseUnsignedInt(String s) { return parseUnsignedInt(s, 10); } /** * Returns the unsigned {@code int} value represented by a string with the given radix. * * @param string the string containing the unsigned integer representation to be parsed. * @param radix the radix to use while parsing {@code s}; must be between * {@link Character#MIN_RADIX} and {@link Character#MAX_RADIX}. * @throws NumberFormatException if the string does not contain a valid unsigned {@code int}, or * if supplied radix is invalid. * @throws NullPointerException if {@code s} is null * (in contrast to {@link Integer#parseInt(String)}) */ public static int parseUnsignedInt(String string, int radix) { checkNotNull(string); long result = Long.parseLong(string, radix); if ((result & INT_MASK) != result) { throw new NumberFormatException("Input " + string + " in base " + radix + " is not in the range of an unsigned integer"); } return (int) result; } /** * Returns a string representation of x, where x is treated as unsigned. */ public static String toString(int x) { return toString(x, 10); } /** * Returns a string representation of {@code x} for the given radix, where {@code x} is treated * as unsigned. * * @param x the value to convert to a string. * @param radix the radix to use while working with {@code x} * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX} * and {@link Character#MAX_RADIX}. */ public static String toString(int x, int radix) { long asLong = x & INT_MASK; return Long.toString(asLong, radix); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/UnsignedInts.java
Java
asf20
10,108
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.primitives.UnsignedInts.INT_MASK; import static com.google.common.primitives.UnsignedInts.compare; import static com.google.common.primitives.UnsignedInts.toLong; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.math.BigInteger; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /** * A wrapper class for unsigned {@code int} values, supporting arithmetic operations. * * <p>In some cases, when speed is more important than code readability, it may be faster simply to * treat primitive {@code int} values as unsigned, using the methods from {@link UnsignedInts}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support"> * unsigned primitive utilities</a>. * * @author Louis Wasserman * @since 11.0 */ @GwtCompatible(emulated = true) public final class UnsignedInteger extends Number implements Comparable<UnsignedInteger> { public static final UnsignedInteger ZERO = fromIntBits(0); public static final UnsignedInteger ONE = fromIntBits(1); public static final UnsignedInteger MAX_VALUE = fromIntBits(-1); private final int value; private UnsignedInteger(int value) { // GWT doesn't consistently overflow values to make them 32-bit, so we need to force it. this.value = value & 0xffffffff; } /** * Returns an {@code UnsignedInteger} corresponding to a given bit representation. * The argument is interpreted as an unsigned 32-bit value. Specifically, the sign bit * of {@code bits} is interpreted as a normal bit, and all other bits are treated as usual. * * <p>If the argument is nonnegative, the returned result will be equal to {@code bits}, * otherwise, the result will be equal to {@code 2^32 + bits}. * * <p>To represent unsigned decimal constants, consider {@link #valueOf(long)} instead. * * @since 14.0 */ public static UnsignedInteger fromIntBits(int bits) { return new UnsignedInteger(bits); } /** * Returns an {@code UnsignedInteger} that is equal to {@code value}, * if possible. The inverse operation of {@link #longValue()}. */ public static UnsignedInteger valueOf(long value) { checkArgument((value & INT_MASK) == value, "value (%s) is outside the range for an unsigned integer value", value); return fromIntBits((int) value); } /** * Returns a {@code UnsignedInteger} representing the same value as the specified * {@link BigInteger}. This is the inverse operation of {@link #bigIntegerValue()}. * * @throws IllegalArgumentException if {@code value} is negative or {@code value >= 2^32} */ public static UnsignedInteger valueOf(BigInteger value) { checkNotNull(value); checkArgument(value.signum() >= 0 && value.bitLength() <= Integer.SIZE, "value (%s) is outside the range for an unsigned integer value", value); return fromIntBits(value.intValue()); } /** * Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed * as an unsigned {@code int} value. * * @throws NumberFormatException if the string does not contain a parsable unsigned {@code int} * value */ public static UnsignedInteger valueOf(String string) { return valueOf(string, 10); } /** * Returns an {@code UnsignedInteger} holding the value of the specified {@code String}, parsed * as an unsigned {@code int} value in the specified radix. * * @throws NumberFormatException if the string does not contain a parsable unsigned {@code int} * value */ public static UnsignedInteger valueOf(String string, int radix) { return fromIntBits(UnsignedInts.parseUnsignedInt(string, radix)); } /** * Returns the result of adding this and {@code val}. If the result would have more than 32 bits, * returns the low 32 bits of the result. * * @since 14.0 */ @CheckReturnValue public UnsignedInteger plus(UnsignedInteger val) { return fromIntBits(this.value + checkNotNull(val).value); } /** * Returns the result of subtracting this and {@code val}. If the result would be negative, * returns the low 32 bits of the result. * * @since 14.0 */ @CheckReturnValue public UnsignedInteger minus(UnsignedInteger val) { return fromIntBits(value - checkNotNull(val).value); } /** * Returns the result of multiplying this and {@code val}. If the result would have more than 32 * bits, returns the low 32 bits of the result. * * @since 14.0 */ @CheckReturnValue @GwtIncompatible("Does not truncate correctly") public UnsignedInteger times(UnsignedInteger val) { // TODO(user): make this GWT-compatible return fromIntBits(value * checkNotNull(val).value); } /** * Returns the result of dividing this by {@code val}. * * @throws ArithmeticException if {@code val} is zero * @since 14.0 */ @CheckReturnValue public UnsignedInteger dividedBy(UnsignedInteger val) { return fromIntBits(UnsignedInts.divide(value, checkNotNull(val).value)); } /** * Returns this mod {@code val}. * * @throws ArithmeticException if {@code val} is zero * @since 14.0 */ @CheckReturnValue public UnsignedInteger mod(UnsignedInteger val) { return fromIntBits(UnsignedInts.remainder(value, checkNotNull(val).value)); } /** * Returns the value of this {@code UnsignedInteger} as an {@code int}. This is an inverse * operation to {@link #fromIntBits}. * * <p>Note that if this {@code UnsignedInteger} holds a value {@code >= 2^31}, the returned value * will be equal to {@code this - 2^32}. */ @Override public int intValue() { return value; } /** * Returns the value of this {@code UnsignedInteger} as a {@code long}. */ @Override public long longValue() { return toLong(value); } /** * Returns the value of this {@code UnsignedInteger} as a {@code float}, analogous to a widening * primitive conversion from {@code int} to {@code float}, and correctly rounded. */ @Override public float floatValue() { return longValue(); } /** * Returns the value of this {@code UnsignedInteger} as a {@code float}, analogous to a widening * primitive conversion from {@code int} to {@code double}, and correctly rounded. */ @Override public double doubleValue() { return longValue(); } /** * Returns the value of this {@code UnsignedInteger} as a {@link BigInteger}. */ public BigInteger bigIntegerValue() { return BigInteger.valueOf(longValue()); } /** * Compares this unsigned integer to another unsigned integer. * Returns {@code 0} if they are equal, a negative number if {@code this < other}, * and a positive number if {@code this > other}. */ @Override public int compareTo(UnsignedInteger other) { checkNotNull(other); return compare(value, other.value); } @Override public int hashCode() { return value; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof UnsignedInteger) { UnsignedInteger other = (UnsignedInteger) obj; return value == other.value; } return false; } /** * Returns a string representation of the {@code UnsignedInteger} value, in base 10. */ @Override public String toString() { return toString(10); } /** * Returns a string representation of the {@code UnsignedInteger} value, in base {@code radix}. * If {@code radix < Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}, the radix * {@code 10} is used. */ public String toString(int radix) { return UnsignedInts.toString(value, radix); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/UnsignedInteger.java
Java
asf20
8,579
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.math.BigInteger; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /** * A wrapper class for unsigned {@code long} values, supporting arithmetic operations. * * <p>In some cases, when speed is more important than code readability, it may be faster simply to * treat primitive {@code long} values as unsigned, using the methods from {@link UnsignedLongs}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained#Unsigned_support"> * unsigned primitive utilities</a>. * * @author Louis Wasserman * @author Colin Evans * @since 11.0 */ @GwtCompatible(serializable = true) public final class UnsignedLong extends Number implements Comparable<UnsignedLong>, Serializable { private static final long UNSIGNED_MASK = 0x7fffffffffffffffL; public static final UnsignedLong ZERO = new UnsignedLong(0); public static final UnsignedLong ONE = new UnsignedLong(1); public static final UnsignedLong MAX_VALUE = new UnsignedLong(-1L); private final long value; private UnsignedLong(long value) { this.value = value; } /** * Returns an {@code UnsignedLong} corresponding to a given bit representation. * The argument is interpreted as an unsigned 64-bit value. Specifically, the sign bit * of {@code bits} is interpreted as a normal bit, and all other bits are treated as usual. * * <p>If the argument is nonnegative, the returned result will be equal to {@code bits}, * otherwise, the result will be equal to {@code 2^64 + bits}. * * <p>To represent decimal constants less than {@code 2^63}, consider {@link #valueOf(long)} * instead. * * @since 14.0 */ public static UnsignedLong fromLongBits(long bits) { // TODO(user): consider caching small values, like Long.valueOf return new UnsignedLong(bits); } /** * Returns an {@code UnsignedLong} representing the same value as the specified {@code long}. * * @throws IllegalArgumentException if {@code value} is negative * @since 14.0 */ public static UnsignedLong valueOf(long value) { checkArgument(value >= 0, "value (%s) is outside the range for an unsigned long value", value); return fromLongBits(value); } /** * Returns a {@code UnsignedLong} representing the same value as the specified * {@code BigInteger}. This is the inverse operation of {@link #bigIntegerValue()}. * * @throws IllegalArgumentException if {@code value} is negative or {@code value >= 2^64} */ public static UnsignedLong valueOf(BigInteger value) { checkNotNull(value); checkArgument(value.signum() >= 0 && value.bitLength() <= Long.SIZE, "value (%s) is outside the range for an unsigned long value", value); return fromLongBits(value.longValue()); } /** * Returns an {@code UnsignedLong} holding the value of the specified {@code String}, parsed as * an unsigned {@code long} value. * * @throws NumberFormatException if the string does not contain a parsable unsigned {@code long} * value */ public static UnsignedLong valueOf(String string) { return valueOf(string, 10); } /** * Returns an {@code UnsignedLong} holding the value of the specified {@code String}, parsed as * an unsigned {@code long} value in the specified radix. * * @throws NumberFormatException if the string does not contain a parsable unsigned {@code long} * value, or {@code radix} is not between {@link Character#MIN_RADIX} and * {@link Character#MAX_RADIX} */ public static UnsignedLong valueOf(String string, int radix) { return fromLongBits(UnsignedLongs.parseUnsignedLong(string, radix)); } /** * Returns the result of adding this and {@code val}. If the result would have more than 64 bits, * returns the low 64 bits of the result. * * @since 14.0 */ public UnsignedLong plus(UnsignedLong val) { return fromLongBits(this.value + checkNotNull(val).value); } /** * Returns the result of subtracting this and {@code val}. If the result would have more than 64 * bits, returns the low 64 bits of the result. * * @since 14.0 */ public UnsignedLong minus(UnsignedLong val) { return fromLongBits(this.value - checkNotNull(val).value); } /** * Returns the result of multiplying this and {@code val}. If the result would have more than 64 * bits, returns the low 64 bits of the result. * * @since 14.0 */ @CheckReturnValue public UnsignedLong times(UnsignedLong val) { return fromLongBits(value * checkNotNull(val).value); } /** * Returns the result of dividing this by {@code val}. * * @since 14.0 */ @CheckReturnValue public UnsignedLong dividedBy(UnsignedLong val) { return fromLongBits(UnsignedLongs.divide(value, checkNotNull(val).value)); } /** * Returns this modulo {@code val}. * * @since 14.0 */ @CheckReturnValue public UnsignedLong mod(UnsignedLong val) { return fromLongBits(UnsignedLongs.remainder(value, checkNotNull(val).value)); } /** * Returns the value of this {@code UnsignedLong} as an {@code int}. */ @Override public int intValue() { return (int) value; } /** * Returns the value of this {@code UnsignedLong} as a {@code long}. This is an inverse operation * to {@link #fromLongBits}. * * <p>Note that if this {@code UnsignedLong} holds a value {@code >= 2^63}, the returned value * will be equal to {@code this - 2^64}. */ @Override public long longValue() { return value; } /** * Returns the value of this {@code UnsignedLong} as a {@code float}, analogous to a widening * primitive conversion from {@code long} to {@code float}, and correctly rounded. */ @Override public float floatValue() { @SuppressWarnings("cast") float fValue = (float) (value & UNSIGNED_MASK); if (value < 0) { fValue += 0x1.0p63f; } return fValue; } /** * Returns the value of this {@code UnsignedLong} as a {@code double}, analogous to a widening * primitive conversion from {@code long} to {@code double}, and correctly rounded. */ @Override public double doubleValue() { @SuppressWarnings("cast") double dValue = (double) (value & UNSIGNED_MASK); if (value < 0) { dValue += 0x1.0p63; } return dValue; } /** * Returns the value of this {@code UnsignedLong} as a {@link BigInteger}. */ public BigInteger bigIntegerValue() { BigInteger bigInt = BigInteger.valueOf(value & UNSIGNED_MASK); if (value < 0) { bigInt = bigInt.setBit(Long.SIZE - 1); } return bigInt; } @Override public int compareTo(UnsignedLong o) { checkNotNull(o); return UnsignedLongs.compare(value, o.value); } @Override public int hashCode() { return Longs.hashCode(value); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof UnsignedLong) { UnsignedLong other = (UnsignedLong) obj; return value == other.value; } return false; } /** * Returns a string representation of the {@code UnsignedLong} value, in base 10. */ @Override public String toString() { return UnsignedLongs.toString(value); } /** * Returns a string representation of the {@code UnsignedLong} value, in base {@code radix}. If * {@code radix < Character.MIN_RADIX} or {@code radix > Character.MAX_RADIX}, the radix * {@code 10} is used. */ public String toString(int radix) { return UnsignedLongs.toString(value, radix); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/UnsignedLong.java
Java
asf20
8,469
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Converter; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code long} primitives, that are not * already found in either {@link Long} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible public final class Longs { private Longs() {} /** * The number of bytes required to represent a primitive {@code long} * value. */ public static final int BYTES = Long.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as a {@code long}. * * @since 10.0 */ public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Long) value).hashCode()}. * * <p>This method always return the value specified by {@link * Long#hashCode()} in java, which might be different from * {@code ((Long) value).hashCode()} in GWT because {@link Long#hashCode()} * in GWT does not obey the JRE contract. * * @param value a primitive {@code long} value * @return a hash code for the value */ public static int hashCode(long value) { return (int) (value ^ (value >>> 32)); } /** * Compares the two specified {@code long} values. The sign of the value * returned is the same as that of {@code ((Long) a).compareTo(b)}. * * <p><b>Note:</b> projects using JDK 7 or later should use the equivalent * {@link Long#compare} method instead. * * @param a the first {@code long} to compare * @param b the second {@code long} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(long a, long b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(long[] array, long target) { for (long value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(long[] array, long target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( long[] array, long target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(long[] array, long[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(long[] array, long target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( long[] array, long target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code long} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static long min(long... array) { checkArgument(array.length > 0); long min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code long} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static long max(long... array) { checkArgument(array.length > 0); long max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new long[] {a, b}, new long[] {}, new * long[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code long} arrays * @return a single array containing all the values from the source arrays, in * order */ public static long[] concat(long[]... arrays) { int length = 0; for (long[] array : arrays) { length += array.length; } long[] result = new long[length]; int pos = 0; for (long[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in an 8-element byte * array; equivalent to {@code ByteBuffer.allocate(8).putLong(value).array()}. * For example, the input value {@code 0x1213141516171819L} would yield the * byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}}. * * <p>If you need to convert and concatenate several values (possibly even of * different types), use a shared {@link java.nio.ByteBuffer} instance, or use * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable * buffer. */ public static byte[] toByteArray(long value) { // Note that this code needs to stay compatible with GWT, which has known // bugs when narrowing byte casts of long values occur. byte[] result = new byte[8]; for (int i = 7; i >= 0; i--) { result[i] = (byte) (value & 0xffL); value >>= 8; } return result; } /** * Returns the {@code long} value whose big-endian representation is * stored in the first 8 bytes of {@code bytes}; equivalent to {@code * ByteBuffer.wrap(bytes).getLong()}. For example, the input byte array * {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the * {@code long} value {@code 0x1213141516171819L}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that * library exposes much more flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 8 * elements */ public static long fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]) ; } /** * Returns the {@code long} value whose byte representation is the given 8 * bytes, in big-endian order; equivalent to {@code Longs.fromByteArray(new * byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}. * * @since 7.0 */ public static long fromBytes(byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) { return (b1 & 0xFFL) << 56 | (b2 & 0xFFL) << 48 | (b3 & 0xFFL) << 40 | (b4 & 0xFFL) << 32 | (b5 & 0xFFL) << 24 | (b6 & 0xFFL) << 16 | (b7 & 0xFFL) << 8 | (b8 & 0xFFL); } /** * Parses the specified string as a signed decimal long value. The ASCII * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the * minus sign. * * <p>Unlike {@link Long#parseLong(String)}, this method returns * {@code null} instead of throwing an exception if parsing fails. * Additionally, this method only accepts ASCII digits, and returns * {@code null} if non-ASCII digits are present in the string. * * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even * under JDK 7, despite the change to {@link Long#parseLong(String)} for * that version. * * @param string the string representation of a long value * @return the long value represented by {@code string}, or {@code null} if * {@code string} has a length of zero or cannot be parsed as a long * value * @since 14.0 */ @Beta public static Long tryParse(String string) { if (checkNotNull(string).isEmpty()) { return null; } boolean negative = string.charAt(0) == '-'; int index = negative ? 1 : 0; if (index == string.length()) { return null; } int digit = string.charAt(index++) - '0'; if (digit < 0 || digit > 9) { return null; } long accum = -digit; while (index < string.length()) { digit = string.charAt(index++) - '0'; if (digit < 0 || digit > 9 || accum < Long.MIN_VALUE / 10) { return null; } accum *= 10; if (accum < Long.MIN_VALUE + digit) { return null; } accum -= digit; } if (negative) { return accum; } else if (accum == Long.MIN_VALUE) { return null; } else { return -accum; } } private static final class LongConverter extends Converter<String, Long> implements Serializable { static final LongConverter INSTANCE = new LongConverter(); @Override protected Long doForward(String value) { return Long.decode(value); } @Override protected String doBackward(Long value) { return value.toString(); } @Override public String toString() { return "Longs.stringConverter()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } /** * Returns a serializable converter object that converts between strings and * longs using {@link Long#decode} and {@link Long#toString()}. * * @since 16.0 */ @Beta public static Converter<String, Long> stringConverter() { return LongConverter.INSTANCE; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static long[] ensureCapacity( long[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static long[] copyOf(long[] original, int length) { long[] copy = new long[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code long} values separated * by {@code separator}. For example, {@code join("-", 1L, 2L, 3L)} returns * the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code long} values, possibly empty */ public static String join(String separator, long... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 10); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code long} arrays * lexicographically. That is, it compares, using {@link * #compare(long, long)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, * {@code [] < [1L] < [1L, 2L] < [2L]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(long[], long[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<long[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<long[]> { INSTANCE; @Override public int compare(long[] left, long[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Longs.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Returns an array containing each value of {@code collection}, converted to * a {@code long} value in the manner of {@link Number#longValue}. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null * @since 1.0 (parameter was {@code Collection<Long>} before 12.0) */ public static long[] toArray(Collection<? extends Number> collection) { if (collection instanceof LongArrayAsList) { return ((LongArrayAsList) collection).toLongArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; long[] array = new long[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).longValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Long} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Long> asList(long... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new LongArrayAsList(backingArray); } @GwtCompatible private static class LongArrayAsList extends AbstractList<Long> implements RandomAccess, Serializable { final long[] array; final int start; final int end; LongArrayAsList(long[] array) { this(array, 0, array.length); } LongArrayAsList(long[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Long get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Long) { int i = Longs.indexOf(array, (Long) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Long) { int i = Longs.lastIndexOf(array, (Long) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Long set(int index, Long element) { checkElementIndex(index, size()); long oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Long> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new LongArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof LongArrayAsList) { LongArrayAsList that = (LongArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Longs.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 10); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } long[] toLongArray() { // Arrays.copyOfRange() is not available under GWT int size = size(); long[] result = new long[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/Longs.java
Java
asf20
21,850
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code byte} primitives, that are not * already found in either {@link Byte} or {@link Arrays}, <i>and interpret * bytes as neither signed nor unsigned</i>. The methods which specifically * treat bytes as signed or unsigned are found in {@link SignedBytes} and {@link * UnsignedBytes}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ // TODO(kevinb): how to prevent warning on UnsignedBytes when building GWT // javadoc? @GwtCompatible public final class Bytes { private Bytes() {} /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Byte) value).hashCode()}. * * @param value a primitive {@code byte} value * @return a hash code for the value */ public static int hashCode(byte value) { return value; } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code byte} values, possibly empty * @param target a primitive {@code byte} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(byte[] array, byte target) { for (byte value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code byte} values, possibly empty * @param target a primitive {@code byte} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(byte[] array, byte target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( byte[] array, byte target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(byte[] array, byte[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code byte} values, possibly empty * @param target a primitive {@code byte} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(byte[] array, byte target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( byte[] array, byte target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new byte[] {a, b}, new byte[] {}, new * byte[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code byte} arrays * @return a single array containing all the values from the source arrays, in * order */ public static byte[] concat(byte[]... arrays) { int length = 0; for (byte[] array : arrays) { length += array.length; } byte[] result = new byte[length]; int pos = 0; for (byte[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static byte[] ensureCapacity( byte[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static byte[] copyOf(byte[] original, int length) { byte[] copy = new byte[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns an array containing each value of {@code collection}, converted to * a {@code byte} value in the manner of {@link Number#byteValue}. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null * @since 1.0 (parameter was {@code Collection<Byte>} before 12.0) */ public static byte[] toArray(Collection<? extends Number> collection) { if (collection instanceof ByteArrayAsList) { return ((ByteArrayAsList) collection).toByteArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; byte[] array = new byte[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).byteValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Byte} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Byte> asList(byte... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new ByteArrayAsList(backingArray); } @GwtCompatible private static class ByteArrayAsList extends AbstractList<Byte> implements RandomAccess, Serializable { final byte[] array; final int start; final int end; ByteArrayAsList(byte[] array) { this(array, 0, array.length); } ByteArrayAsList(byte[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Byte get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Byte) && Bytes.indexOf(array, (Byte) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Byte) { int i = Bytes.indexOf(array, (Byte) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Byte) { int i = Bytes.lastIndexOf(array, (Byte) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Byte set(int index, Byte element) { checkElementIndex(index, size()); byte oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Byte> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new ByteArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof ByteArrayAsList) { ByteArrayAsList that = (ByteArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Bytes.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 5); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } byte[] toByteArray() { // Arrays.copyOfRange() is not available under GWT int size = size(); byte[] result = new byte[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/Bytes.java
Java
asf20
12,548
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Converter; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code short} primitives, that are not * already found in either {@link Short} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Shorts { private Shorts() {} /** * The number of bytes required to represent a primitive {@code short} * value. */ public static final int BYTES = Short.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as a {@code short}. * * @since 10.0 */ public static final short MAX_POWER_OF_TWO = 1 << (Short.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Short) value).hashCode()}. * * @param value a primitive {@code short} value * @return a hash code for the value */ public static int hashCode(short value) { return value; } /** * Returns the {@code short} value that is equal to {@code value}, if * possible. * * @param value any value in the range of the {@code short} type * @return the {@code short} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link * Short#MAX_VALUE} or less than {@link Short#MIN_VALUE} */ public static short checkedCast(long value) { short result = (short) value; if (result != value) { // don't use checkArgument here, to avoid boxing throw new IllegalArgumentException("Out of range: " + value); } return result; } /** * Returns the {@code short} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code short} if it is in the range of the * {@code short} type, {@link Short#MAX_VALUE} if it is too large, * or {@link Short#MIN_VALUE} if it is too small */ public static short saturatedCast(long value) { if (value > Short.MAX_VALUE) { return Short.MAX_VALUE; } if (value < Short.MIN_VALUE) { return Short.MIN_VALUE; } return (short) value; } /** * Compares the two specified {@code short} values. The sign of the value * returned is the same as that of {@code ((Short) a).compareTo(b)}. * * <p><b>Note:</b> projects using JDK 7 or later should use the equivalent * {@link Short#compare} method instead. * * @param a the first {@code short} to compare * @param b the second {@code short} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(short a, short b) { return a - b; // safe due to restricted range } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code short} values, possibly empty * @param target a primitive {@code short} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(short[] array, short target) { for (short value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code short} values, possibly empty * @param target a primitive {@code short} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(short[] array, short target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( short[] array, short target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(short[] array, short[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code short} values, possibly empty * @param target a primitive {@code short} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(short[] array, short target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( short[] array, short target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code short} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static short min(short... array) { checkArgument(array.length > 0); short min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code short} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static short max(short... array) { checkArgument(array.length > 0); short max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new short[] {a, b}, new short[] {}, new * short[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code short} arrays * @return a single array containing all the values from the source arrays, in * order */ public static short[] concat(short[]... arrays) { int length = 0; for (short[] array : arrays) { length += array.length; } short[] result = new short[length]; int pos = 0; for (short[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in a 2-element byte * array; equivalent to {@code * ByteBuffer.allocate(2).putShort(value).array()}. For example, the input * value {@code (short) 0x1234} would yield the byte array {@code {0x12, * 0x34}}. * * <p>If you need to convert and concatenate several values (possibly even of * different types), use a shared {@link java.nio.ByteBuffer} instance, or use * {@link com.google.common.io.ByteStreams#newDataOutput()} to get a growable * buffer. */ @GwtIncompatible("doesn't work") public static byte[] toByteArray(short value) { return new byte[] { (byte) (value >> 8), (byte) value}; } /** * Returns the {@code short} value whose big-endian representation is * stored in the first 2 bytes of {@code bytes}; equivalent to {@code * ByteBuffer.wrap(bytes).getShort()}. For example, the input byte array * {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that * library exposes much more flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 2 * elements */ @GwtIncompatible("doesn't work") public static short fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1]); } /** * Returns the {@code short} value whose byte representation is the given 2 * bytes, in big-endian order; equivalent to {@code Shorts.fromByteArray(new * byte[] {b1, b2})}. * * @since 7.0 */ @GwtIncompatible("doesn't work") public static short fromBytes(byte b1, byte b2) { return (short) ((b1 << 8) | (b2 & 0xFF)); } private static final class ShortConverter extends Converter<String, Short> implements Serializable { static final ShortConverter INSTANCE = new ShortConverter(); @Override protected Short doForward(String value) { return Short.decode(value); } @Override protected String doBackward(Short value) { return value.toString(); } @Override public String toString() { return "Shorts.stringConverter()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } /** * Returns a serializable converter object that converts between strings and * shorts using {@link Short#decode} and {@link Short#toString()}. * * @since 16.0 */ @Beta public static Converter<String, Short> stringConverter() { return ShortConverter.INSTANCE; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static short[] ensureCapacity( short[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static short[] copyOf(short[] original, int length) { short[] copy = new short[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code short} values separated * by {@code separator}. For example, {@code join("-", (short) 1, (short) 2, * (short) 3)} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code short} values, possibly empty */ public static String join(String separator, short... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 6); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code short} arrays * lexicographically. That is, it compares, using {@link * #compare(short, short)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, {@code [] < [(short) 1] < * [(short) 1, (short) 2] < [(short) 2]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(short[], short[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<short[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<short[]> { INSTANCE; @Override public int compare(short[] left, short[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Shorts.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Returns an array containing each value of {@code collection}, converted to * a {@code short} value in the manner of {@link Number#shortValue}. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null * @since 1.0 (parameter was {@code Collection<Short>} before 12.0) */ public static short[] toArray(Collection<? extends Number> collection) { if (collection instanceof ShortArrayAsList) { return ((ShortArrayAsList) collection).toShortArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; short[] array = new short[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).shortValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Short} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Short> asList(short... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new ShortArrayAsList(backingArray); } @GwtCompatible private static class ShortArrayAsList extends AbstractList<Short> implements RandomAccess, Serializable { final short[] array; final int start; final int end; ShortArrayAsList(short[] array) { this(array, 0, array.length); } ShortArrayAsList(short[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Short get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Short) && Shorts.indexOf(array, (Short) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Short) { int i = Shorts.indexOf(array, (Short) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Short) { int i = Shorts.lastIndexOf(array, (Short) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Short set(int index, Short element) { checkElementIndex(index, size()); short oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Short> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new ShortArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof ShortArrayAsList) { ShortArrayAsList that = (ShortArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Shorts.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 6); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } short[] toShortArray() { // Arrays.copyOfRange() is not available under GWT int size = size(); short[] result = new short[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/Shorts.java
Java
asf20
20,775
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code boolean} primitives, that are not * already found in either {@link Boolean} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible public final class Booleans { private Booleans() {} /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Boolean) value).hashCode()}. * * @param value a primitive {@code boolean} value * @return a hash code for the value */ public static int hashCode(boolean value) { return value ? 1231 : 1237; } /** * Compares the two specified {@code boolean} values in the standard way * ({@code false} is considered less than {@code true}). The sign of the * value returned is the same as that of {@code ((Boolean) a).compareTo(b)}. * * <p><b>Note:</b> projects using JDK 7 or later should use the equivalent * {@link Boolean#compare} method instead. * * @param a the first {@code boolean} to compare * @param b the second {@code boolean} to compare * @return a positive number if only {@code a} is {@code true}, a negative * number if only {@code b} is true, or zero if {@code a == b} */ public static int compare(boolean a, boolean b) { return (a == b) ? 0 : (a ? 1 : -1); } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * <p><b>Note:</b> consider representing the array as a {@link * BitSet} instead, replacing {@code Booleans.contains(array, true)} * with {@code !bitSet.isEmpty()} and {@code Booleans.contains(array, false)} * with {@code bitSet.nextClearBit(0) == sizeOfBitSet}. * * @param array an array of {@code boolean} values, possibly empty * @param target a primitive {@code boolean} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(boolean[] array, boolean target) { for (boolean value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * <p><b>Note:</b> consider representing the array as a {@link BitSet} * instead, and using {@link BitSet#nextSetBit(int)} or {@link * BitSet#nextClearBit(int)}. * * @param array an array of {@code boolean} values, possibly empty * @param target a primitive {@code boolean} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(boolean[] array, boolean target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( boolean[] array, boolean target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(boolean[] array, boolean[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code boolean} values, possibly empty * @param target a primitive {@code boolean} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(boolean[] array, boolean target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( boolean[] array, boolean target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new boolean[] {a, b}, new boolean[] {}, new * boolean[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code boolean} arrays * @return a single array containing all the values from the source arrays, in * order */ public static boolean[] concat(boolean[]... arrays) { int length = 0; for (boolean[] array : arrays) { length += array.length; } boolean[] result = new boolean[length]; int pos = 0; for (boolean[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static boolean[] ensureCapacity( boolean[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static boolean[] copyOf(boolean[] original, int length) { boolean[] copy = new boolean[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code boolean} values separated * by {@code separator}. For example, {@code join("-", false, true, false)} * returns the string {@code "false-true-false"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code boolean} values, possibly empty */ public static String join(String separator, boolean... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 7); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code boolean} arrays * lexicographically. That is, it compares, using {@link * #compare(boolean, boolean)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, * {@code [] < [false] < [false, true] < [true]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(boolean[], boolean[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<boolean[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<boolean[]> { INSTANCE; @Override public int compare(boolean[] left, boolean[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Booleans.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Copies a collection of {@code Boolean} instances into a new array of * primitive {@code boolean} values. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * <p><b>Note:</b> consider representing the collection as a {@link * BitSet} instead. * * @param collection a collection of {@code Boolean} objects * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null */ public static boolean[] toArray(Collection<Boolean> collection) { if (collection instanceof BooleanArrayAsList) { return ((BooleanArrayAsList) collection).toBooleanArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; boolean[] array = new boolean[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = (Boolean) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Boolean} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Boolean> asList(boolean... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new BooleanArrayAsList(backingArray); } @GwtCompatible private static class BooleanArrayAsList extends AbstractList<Boolean> implements RandomAccess, Serializable { final boolean[] array; final int start; final int end; BooleanArrayAsList(boolean[] array) { this(array, 0, array.length); } BooleanArrayAsList(boolean[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Boolean get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Boolean) && Booleans.indexOf(array, (Boolean) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Boolean) { int i = Booleans.indexOf(array, (Boolean) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Boolean) { int i = Booleans.lastIndexOf(array, (Boolean) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Boolean set(int index, Boolean element) { checkElementIndex(index, size()); boolean oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Boolean> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new BooleanArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof BooleanArrayAsList) { BooleanArrayAsList that = (BooleanArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Booleans.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 7); builder.append(array[start] ? "[true" : "[false"); for (int i = start + 1; i < end; i++) { builder.append(array[i] ? ", true" : ", false"); } return builder.append(']').toString(); } boolean[] toBooleanArray() { // Arrays.copyOfRange() is not available under GWT int size = size(); boolean[] result = new boolean[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } /** * Returns the number of {@code values} that are {@code true}. * * @since 16.0 */ @Beta public static int countTrue(boolean... values) { int count = 0; for (boolean value : values) { if (value) { count++; } } return count; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/Booleans.java
Java
asf20
16,276
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import com.google.common.annotations.GwtCompatible; /** * A string to be parsed as a number and the radix to interpret it in. */ @GwtCompatible final class ParseRequest { final String rawValue; final int radix; private ParseRequest(String rawValue, int radix) { this.rawValue = rawValue; this.radix = radix; } static ParseRequest fromString(String stringValue) { if (stringValue.length() == 0) { throw new NumberFormatException("empty string"); } // Handle radix specifier if present String rawValue; int radix; char firstChar = stringValue.charAt(0); if (stringValue.startsWith("0x") || stringValue.startsWith("0X")) { rawValue = stringValue.substring(2); radix = 16; } else if (firstChar == '#') { rawValue = stringValue.substring(1); radix = 16; } else if (firstChar == '0' && stringValue.length() > 1) { rawValue = stringValue.substring(1); radix = 8; } else { rawValue = stringValue; radix = 10; } return new ParseRequest(rawValue, radix); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/primitives/ParseRequest.java
Java
asf20
1,713
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.eventbus; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Throwables; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.HashMultimap; import com.google.common.collect.Multimap; import com.google.common.collect.SetMultimap; import com.google.common.reflect.TypeToken; import com.google.common.util.concurrent.UncheckedExecutionException; import java.lang.reflect.InvocationTargetException; import java.util.Collection; import java.util.LinkedList; import java.util.Map.Entry; import java.util.Queue; import java.util.Set; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import java.util.logging.Level; import java.util.logging.Logger; /** * Dispatches events to listeners, and provides ways for listeners to register * themselves. * * <p>The EventBus allows publish-subscribe-style communication between * components without requiring the components to explicitly register with one * another (and thus be aware of each other). It is designed exclusively to * replace traditional Java in-process event distribution using explicit * registration. It is <em>not</em> a general-purpose publish-subscribe system, * nor is it intended for interprocess communication. * * <h2>Receiving Events</h2> * <p>To receive events, an object should: * <ol> * <li>Expose a public method, known as the <i>event subscriber</i>, which accepts * a single argument of the type of event desired;</li> * <li>Mark it with a {@link Subscribe} annotation;</li> * <li>Pass itself to an EventBus instance's {@link #register(Object)} method. * </li> * </ol> * * <h2>Posting Events</h2> * <p>To post an event, simply provide the event object to the * {@link #post(Object)} method. The EventBus instance will determine the type * of event and route it to all registered listeners. * * <p>Events are routed based on their type &mdash; an event will be delivered * to any subscriber for any type to which the event is <em>assignable.</em> This * includes implemented interfaces, all superclasses, and all interfaces * implemented by superclasses. * * <p>When {@code post} is called, all registered subscribers for an event are run * in sequence, so subscribers should be reasonably quick. If an event may trigger * an extended process (such as a database load), spawn a thread or queue it for * later. (For a convenient way to do this, use an {@link AsyncEventBus}.) * * <h2>Subscriber Methods</h2> * <p>Event subscriber methods must accept only one argument: the event. * * <p>Subscribers should not, in general, throw. If they do, the EventBus will * catch and log the exception. This is rarely the right solution for error * handling and should not be relied upon; it is intended solely to help find * problems during development. * * <p>The EventBus guarantees that it will not call a subscriber method from * multiple threads simultaneously, unless the method explicitly allows it by * bearing the {@link AllowConcurrentEvents} annotation. If this annotation is * not present, subscriber methods need not worry about being reentrant, unless * also called from outside the EventBus. * * <h2>Dead Events</h2> * <p>If an event is posted, but no registered subscribers can accept it, it is * considered "dead." To give the system a second chance to handle dead events, * they are wrapped in an instance of {@link DeadEvent} and reposted. * * <p>If a subscriber for a supertype of all events (such as Object) is registered, * no event will ever be considered dead, and no DeadEvents will be generated. * Accordingly, while DeadEvent extends {@link Object}, a subscriber registered to * receive any Object will never receive a DeadEvent. * * <p>This class is safe for concurrent use. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/EventBusExplained"> * {@code EventBus}</a>. * * @author Cliff Biffle * @since 10.0 */ @Beta public class EventBus { /** * A thread-safe cache for flattenHierarchy(). The Class class is immutable. This cache is shared * across all EventBus instances, which greatly improves performance if multiple such instances * are created and objects of the same class are posted on all of them. */ private static final LoadingCache<Class<?>, Set<Class<?>>> flattenHierarchyCache = CacheBuilder.newBuilder() .weakKeys() .build(new CacheLoader<Class<?>, Set<Class<?>>>() { @SuppressWarnings({"unchecked", "rawtypes"}) // safe cast @Override public Set<Class<?>> load(Class<?> concreteClass) { return (Set) TypeToken.of(concreteClass).getTypes().rawTypes(); } }); /** * All registered event subscribers, indexed by event type. * * <p>This SetMultimap is NOT safe for concurrent use; all access should be * made after acquiring a read or write lock via {@link #subscribersByTypeLock}. */ private final SetMultimap<Class<?>, EventSubscriber> subscribersByType = HashMultimap.create(); private final ReadWriteLock subscribersByTypeLock = new ReentrantReadWriteLock(); /** * Strategy for finding subscriber methods in registered objects. Currently, * only the {@link AnnotatedSubscriberFinder} is supported, but this is * encapsulated for future expansion. */ private final SubscriberFindingStrategy finder = new AnnotatedSubscriberFinder(); /** queues of events for the current thread to dispatch */ private final ThreadLocal<Queue<EventWithSubscriber>> eventsToDispatch = new ThreadLocal<Queue<EventWithSubscriber>>() { @Override protected Queue<EventWithSubscriber> initialValue() { return new LinkedList<EventWithSubscriber>(); } }; /** true if the current thread is currently dispatching an event */ private final ThreadLocal<Boolean> isDispatching = new ThreadLocal<Boolean>() { @Override protected Boolean initialValue() { return false; } }; private SubscriberExceptionHandler subscriberExceptionHandler; /** * Creates a new EventBus named "default". */ public EventBus() { this("default"); } /** * Creates a new EventBus with the given {@code identifier}. * * @param identifier a brief name for this bus, for logging purposes. Should * be a valid Java identifier. */ public EventBus(String identifier) { this(new LoggingSubscriberExceptionHandler(identifier)); } /** * Creates a new EventBus with the given {@link SubscriberExceptionHandler}. * * @param subscriberExceptionHandler Handler for subscriber exceptions. * @since 16.0 */ public EventBus(SubscriberExceptionHandler subscriberExceptionHandler) { this.subscriberExceptionHandler = checkNotNull(subscriberExceptionHandler); } /** * Registers all subscriber methods on {@code object} to receive events. * Subscriber methods are selected and classified using this EventBus's * {@link SubscriberFindingStrategy}; the default strategy is the * {@link AnnotatedSubscriberFinder}. * * @param object object whose subscriber methods should be registered. */ public void register(Object object) { Multimap<Class<?>, EventSubscriber> methodsInListener = finder.findAllSubscribers(object); subscribersByTypeLock.writeLock().lock(); try { subscribersByType.putAll(methodsInListener); } finally { subscribersByTypeLock.writeLock().unlock(); } } /** * Unregisters all subscriber methods on a registered {@code object}. * * @param object object whose subscriber methods should be unregistered. * @throws IllegalArgumentException if the object was not previously registered. */ public void unregister(Object object) { Multimap<Class<?>, EventSubscriber> methodsInListener = finder.findAllSubscribers(object); for (Entry<Class<?>, Collection<EventSubscriber>> entry : methodsInListener.asMap().entrySet()) { Class<?> eventType = entry.getKey(); Collection<EventSubscriber> eventMethodsInListener = entry.getValue(); subscribersByTypeLock.writeLock().lock(); try { Set<EventSubscriber> currentSubscribers = subscribersByType.get(eventType); if (!currentSubscribers.containsAll(eventMethodsInListener)) { throw new IllegalArgumentException( "missing event subscriber for an annotated method. Is " + object + " registered?"); } currentSubscribers.removeAll(eventMethodsInListener); } finally { subscribersByTypeLock.writeLock().unlock(); } } } /** * Posts an event to all registered subscribers. This method will return * successfully after the event has been posted to all subscribers, and * regardless of any exceptions thrown by subscribers. * * <p>If no subscribers have been subscribed for {@code event}'s class, and * {@code event} is not already a {@link DeadEvent}, it will be wrapped in a * DeadEvent and reposted. * * @param event event to post. */ public void post(Object event) { Set<Class<?>> dispatchTypes = flattenHierarchy(event.getClass()); boolean dispatched = false; for (Class<?> eventType : dispatchTypes) { subscribersByTypeLock.readLock().lock(); try { Set<EventSubscriber> wrappers = subscribersByType.get(eventType); if (!wrappers.isEmpty()) { dispatched = true; for (EventSubscriber wrapper : wrappers) { enqueueEvent(event, wrapper); } } } finally { subscribersByTypeLock.readLock().unlock(); } } if (!dispatched && !(event instanceof DeadEvent)) { post(new DeadEvent(this, event)); } dispatchQueuedEvents(); } /** * Queue the {@code event} for dispatch during * {@link #dispatchQueuedEvents()}. Events are queued in-order of occurrence * so they can be dispatched in the same order. */ void enqueueEvent(Object event, EventSubscriber subscriber) { eventsToDispatch.get().offer(new EventWithSubscriber(event, subscriber)); } /** * Drain the queue of events to be dispatched. As the queue is being drained, * new events may be posted to the end of the queue. */ void dispatchQueuedEvents() { // don't dispatch if we're already dispatching, that would allow reentrancy // and out-of-order events. Instead, leave the events to be dispatched // after the in-progress dispatch is complete. if (isDispatching.get()) { return; } isDispatching.set(true); try { Queue<EventWithSubscriber> events = eventsToDispatch.get(); EventWithSubscriber eventWithSubscriber; while ((eventWithSubscriber = events.poll()) != null) { dispatch(eventWithSubscriber.event, eventWithSubscriber.subscriber); } } finally { isDispatching.remove(); eventsToDispatch.remove(); } } /** * Dispatches {@code event} to the subscriber in {@code wrapper}. This method * is an appropriate override point for subclasses that wish to make * event delivery asynchronous. * * @param event event to dispatch. * @param wrapper wrapper that will call the subscriber. */ void dispatch(Object event, EventSubscriber wrapper) { try { wrapper.handleEvent(event); } catch (InvocationTargetException e) { try { subscriberExceptionHandler.handleException( e.getCause(), new SubscriberExceptionContext( this, event, wrapper.getSubscriber(), wrapper.getMethod())); } catch (Throwable t) { // If the exception handler throws, log it. There isn't much else to do! Logger.getLogger(EventBus.class.getName()).log(Level.SEVERE, String.format( "Exception %s thrown while handling exception: %s", t, e.getCause()), t); } } } /** * Flattens a class's type hierarchy into a set of Class objects. The set * will include all superclasses (transitively), and all interfaces * implemented by these superclasses. * * @param concreteClass class whose type hierarchy will be retrieved. * @return {@code clazz}'s complete type hierarchy, flattened and uniqued. */ @VisibleForTesting Set<Class<?>> flattenHierarchy(Class<?> concreteClass) { try { return flattenHierarchyCache.getUnchecked(concreteClass); } catch (UncheckedExecutionException e) { throw Throwables.propagate(e.getCause()); } } /** * Simple logging handler for subscriber exceptions. */ private static final class LoggingSubscriberExceptionHandler implements SubscriberExceptionHandler { /** * Logger for event dispatch failures. Named by the fully-qualified name of * this class, followed by the identifier provided at construction. */ private final Logger logger; /** * @param identifier a brief name for this bus, for logging purposes. Should * be a valid Java identifier. */ public LoggingSubscriberExceptionHandler(String identifier) { logger = Logger.getLogger( EventBus.class.getName() + "." + checkNotNull(identifier)); } @Override public void handleException(Throwable exception, SubscriberExceptionContext context) { logger.log(Level.SEVERE, "Could not dispatch event: " + context.getSubscriber() + " to " + context.getSubscriberMethod(), exception.getCause()); } } /** simple struct representing an event and it's subscriber */ static class EventWithSubscriber { final Object event; final EventSubscriber subscriber; public EventWithSubscriber(Object event, EventSubscriber subscriber) { this.event = checkNotNull(event); this.subscriber = checkNotNull(subscriber); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/eventbus/EventBus.java
Java
asf20
14,903
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.eventbus; /** * Handler for exceptions thrown by event subscribers. * * @since 16.0 */ public interface SubscriberExceptionHandler { /** * Handles exceptions thrown by subscribers. */ void handleException(Throwable exception, SubscriberExceptionContext context); }
zzhhhhh-aw4rwer
guava/src/com/google/common/eventbus/SubscriberExceptionHandler.java
Java
asf20
907
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.eventbus; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.Executor; /** * An {@link EventBus} that takes the Executor of your choice and uses it to * dispatch events, allowing dispatch to occur asynchronously. * * @author Cliff Biffle * @since 10.0 */ @Beta public class AsyncEventBus extends EventBus { private final Executor executor; /** the queue of events is shared across all threads */ private final ConcurrentLinkedQueue<EventWithSubscriber> eventsToDispatch = new ConcurrentLinkedQueue<EventWithSubscriber>(); /** * Creates a new AsyncEventBus that will use {@code executor} to dispatch * events. Assigns {@code identifier} as the bus's name for logging purposes. * * @param identifier short name for the bus, for logging purposes. * @param executor Executor to use to dispatch events. It is the caller's * responsibility to shut down the executor after the last event has * been posted to this event bus. */ public AsyncEventBus(String identifier, Executor executor) { super(identifier); this.executor = checkNotNull(executor); } /** * Creates a new AsyncEventBus that will use {@code executor} to dispatch * events. * * @param executor Executor to use to dispatch events. It is the caller's * responsibility to shut down the executor after the last event has * been posted to this event bus. * @param subscriberExceptionHandler Handler used to handle exceptions thrown from subscribers. * See {@link SubscriberExceptionHandler} for more information. * @since 16.0 */ public AsyncEventBus(Executor executor, SubscriberExceptionHandler subscriberExceptionHandler) { super(subscriberExceptionHandler); this.executor = checkNotNull(executor); } /** * Creates a new AsyncEventBus that will use {@code executor} to dispatch * events. * * @param executor Executor to use to dispatch events. It is the caller's * responsibility to shut down the executor after the last event has * been posted to this event bus. */ public AsyncEventBus(Executor executor) { super("default"); this.executor = checkNotNull(executor); } @Override void enqueueEvent(Object event, EventSubscriber subscriber) { eventsToDispatch.offer(new EventWithSubscriber(event, subscriber)); } /** * Dispatch {@code events} in the order they were posted, regardless of * the posting thread. */ @SuppressWarnings("deprecation") // only deprecated for external subclasses @Override protected void dispatchQueuedEvents() { while (true) { EventWithSubscriber eventWithSubscriber = eventsToDispatch.poll(); if (eventWithSubscriber == null) { break; } dispatch(eventWithSubscriber.event, eventWithSubscriber.subscriber); } } /** * Calls the {@link #executor} to dispatch {@code event} to {@code subscriber}. */ @Override void dispatch(final Object event, final EventSubscriber subscriber) { checkNotNull(event); checkNotNull(subscriber); executor.execute( new Runnable() { @Override public void run() { AsyncEventBus.super.dispatch(event, subscriber); } }); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/eventbus/AsyncEventBus.java
Java
asf20
4,039
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.eventbus; import com.google.common.annotations.Beta; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks a method as an event subscriber. * * <p>The type of event will be indicated by the method's first (and only) * parameter. If this annotation is applied to methods with zero parameters, * or more than one parameter, the object containing the method will not be able * to register for event delivery from the {@link EventBus}. * * <p>Unless also annotated with @{@link AllowConcurrentEvents}, event subscriber * methods will be invoked serially by each event bus that they are registered * with. * * @author Cliff Biffle * @since 10.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Beta public @interface Subscribe { }
zzhhhhh-aw4rwer
guava/src/com/google/common/eventbus/Subscribe.java
Java
asf20
1,510
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * The EventBus allows publish-subscribe-style communication between components * without requiring the components to explicitly register with one another * (and thus be aware of each other). It is designed exclusively to replace * traditional Java in-process event distribution using explicit registration. * It is <em>not</em> a general-purpose publish-subscribe system, nor is it * intended for interprocess communication. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/EventBusExplained"> * {@code EventBus}</a>. * * <h2>One-Minute Guide</h2> * * <p>Converting an existing EventListener-based system to use the EventBus is * easy. * * <h3>For Listeners</h3> * <p>To listen for a specific flavor of event (say, a CustomerChangeEvent)... * <ul> * <li><strong>...in traditional Java events:</strong> implement an interface * defined with the event &mdash; such as CustomerChangeEventListener.</li> * <li><strong>...with EventBus:</strong> create a method that accepts * CustomerChangeEvent as its sole argument, and mark it with the * {@link com.google.common.eventbus.Subscribe} annotation.</li> * </ul> * * <p>To register your listener methods with the event producers... * <ul> * <li><strong>...in traditional Java events:</strong> pass your object to each * producer's {@code registerCustomerChangeEventListener} method. These * methods are rarely defined in common interfaces, so in addition to * knowing every possible producer, you must also know its type.</li> * <li><strong>...with EventBus:</strong> pass your object to the * {@link com.google.common.eventbus.EventBus#register(Object)} method on an * EventBus. You'll need to * make sure that your object shares an EventBus instance with the event * producers.</li> * </ul> * * <p>To listen for a common event supertype (such as EventObject or Object)... * <ul> * <li><strong>...in traditional Java events:</strong> not easy.</li> * <li><strong>...with EventBus:</strong> events are automatically dispatched to * listeners of any supertype, allowing listeners for interface types * or "wildcard listeners" for Object.</li> * </ul> * * <p>To listen for and detect events that were dispatched without listeners... * <ul> * <li><strong>...in traditional Java events:</strong> add code to each * event-dispatching method (perhaps using AOP).</li> * <li><strong>...with EventBus:</strong> subscribe to {@link * com.google.common.eventbus.DeadEvent}. The * EventBus will notify you of any events that were posted but not * delivered. (Handy for debugging.)</li> * </ul> * * <h3>For Producers</h3> * <p>To keep track of listeners to your events... * <ul> * <li><strong>...in traditional Java events:</strong> write code to manage * a list of listeners to your object, including synchronization, or use a * utility class like EventListenerList.</li> * <li><strong>...with EventBus:</strong> EventBus does this for you.</li> * </ul> * * <p>To dispatch an event to listeners... * <ul> * <li><strong>...in traditional Java events:</strong> write a method to * dispatch events to each event listener, including error isolation and * (if desired) asynchronicity.</li> * <li><strong>...with EventBus:</strong> pass the event object to an EventBus's * {@link com.google.common.eventbus.EventBus#post(Object)} method.</li> * </ul> * * <h2>Glossary</h2> * * <p>The EventBus system and code use the following terms to discuss event * distribution: * <dl> * <dt>Event</dt><dd>Any object that may be <em>posted</em> to a bus.</dd> * <dt>Subscribing</dt><dd>The act of registering a <em>listener</em> with an * EventBus, so that its <em>subscriber methods</em> will receive events.</dd> * <dt>Listener</dt><dd>An object that wishes to receive events, by exposing * <em>subscriber methods</em>.</dt> * <dt>Subscriber method</dt><dd>A public method that the EventBus should use to * deliver <em>posted</em> events. Subscriber methods are marked by the * {@link com.google.common.eventbus.Subscribe} annotation.</dd> * <dt>Posting an event</dt><dd>Making the event available to any * <em>listeners</em> through the EventBus.</dt> * </dl> * * <h2>FAQ</h2> * <h3>Why must I create my own Event Bus, rather than using a singleton?</h3> * * <p>The Event Bus doesn't specify how you use it; there's nothing stopping your * application from having separate EventBus instances for each component, or * using separate instances to separate events by context or topic. This also * makes it trivial to set up and tear down EventBus objects in your tests. * * <p>Of course, if you'd like to have a process-wide EventBus singleton, * there's nothing stopping you from doing it that way. Simply have your * container (such as Guice) create the EventBus as a singleton at global scope * (or stash it in a static field, if you're into that sort of thing). * * <p>In short, the EventBus is not a singleton because we'd rather not make * that decision for you. Use it how you like. * * <h3>Why use an annotation to mark subscriber methods, rather than requiring the * listener to implement an interface?</h3> * <p>We feel that the Event Bus's {@code @Subscribe} annotation conveys your * intentions just as explicitly as implementing an interface (or perhaps more * so), while leaving you free to place event subscriber methods wherever you wish * and give them intention-revealing names. * * <p>Traditional Java Events use a listener interface which typically sports * only a handful of methods -- typically one. This has a number of * disadvantages: * <ul> * <li>Any one class can only implement a single response to a given event. * <li>Listener interface methods may conflict. * <li>The method must be named after the event (e.g. {@code * handleChangeEvent}), rather than its purpose (e.g. {@code * recordChangeInJournal}). * <li>Each event usually has its own interface, without a common parent * interface for a family of events (e.g. all UI events). * </ul> * * <p>The difficulties in implementing this cleanly has given rise to a pattern, * particularly common in Swing apps, of using tiny anonymous classes to * implement event listener interfaces. * * <p>Compare these two cases: <pre> * class ChangeRecorder { * void setCustomer(Customer cust) { * cust.addChangeListener(new ChangeListener() { * void customerChanged(ChangeEvent e) { * recordChange(e.getChange()); * } * }; * } * } * * // Class is typically registered by the container. * class EventBusChangeRecorder { * &#064;Subscribe void recordCustomerChange(ChangeEvent e) { * recordChange(e.getChange()); * } * }</pre> * * <p>The intent is actually clearer in the second case: there's less noise code, * and the event subscriber has a clear and meaningful name. * * <h3>What about a generic {@code Subscriber<T>} interface?</h3> * <p>Some have proposed a generic {@code Subscriber<T>} interface for EventBus * listeners. This runs into issues with Java's use of type erasure, not to * mention problems in usability. * * <p>Let's say the interface looked something like the following: <pre> {@code * interface Subscriber<T> { * void handleEvent(T event); * }}</pre> * * <p>Due to erasure, no single class can implement a generic interface more than * once with different type parameters. This is a giant step backwards from * traditional Java Events, where even if {@code actionPerformed} and {@code * keyPressed} aren't very meaningful names, at least you can implement both * methods! * * <h3>Doesn't EventBus destroy static typing and eliminate automated * refactoring support?</h3> * <p>Some have freaked out about EventBus's {@code register(Object)} and {@code * post(Object)} methods' use of the {@code Object} type. * * <p>{@code Object} is used here for a good reason: the Event Bus library * places no restrictions on the types of either your event listeners (as in * {@code register(Object)}) or the events themselves (in {@code post(Object)}). * * <p>Event subscriber methods, on the other hand, must explicitly declare their * argument type -- the type of event desired (or one of its supertypes). Thus, * searching for references to an event class will instantly find all subscriber * methods for that event, and renaming the type will affect all subscriber methods * within view of your IDE (and any code that creates the event). * * <p>It's true that you can rename your {@code @Subscribed} event subscriber * methods at will; Event Bus will not stop this or do anything to propagate the * rename because, to Event Bus, the names of your subscriber methods are * irrelevant. Test code that calls the methods directly, of course, will be * affected by your renaming -- but that's what your refactoring tools are for. * * <h3>What happens if I {@code register} a listener without any subscriber * methods?</h3> * <p>Nothing at all. * * <p>The Event Bus was designed to integrate with containers and module * systems, with Guice as the prototypical example. In these cases, it's * convenient to have the container/factory/environment pass <i>every</i> * created object to an EventBus's {@code register(Object)} method. * * <p>This way, any object created by the container/factory/environment can * hook into the system's event model simply by exposing subscriber methods. * * <h3>What Event Bus problems can be detected at compile time?</h3> * <p>Any problem that can be unambiguously detected by Java's type system. For * example, defining a subscriber method for a nonexistent event type. * * <h3>What Event Bus problems can be detected immediately at registration?</h3> * <p>Immediately upon invoking {@code register(Object)} , the listener being * registered is checked for the <i>well-formedness</i> of its subscriber methods. * Specifically, any methods marked with {@code @Subscribe} must take only a * single argument. * * <p>Any violations of this rule will cause an {@code IllegalArgumentException} * to be thrown. * * <p>(This check could be moved to compile-time using APT, a solution we're * researching.) * * <h3>What Event Bus problems may only be detected later, at runtime?</h3> * <p>If a component posts events with no registered listeners, it <i>may</i> * indicate an error (typically an indication that you missed a * {@code @Subscribe} annotation, or that the listening component is not loaded). * * <p>(Note that this is <i>not necessarily</i> indicative of a problem. There * are many cases where an application will deliberately ignore a posted event, * particularly if the event is coming from code you don't control.) * * <p>To handle such events, register a subscriber method for the {@code DeadEvent} * class. Whenever EventBus receives an event with no registered subscribers, it * will turn it into a {@code DeadEvent} and pass it your way -- allowing you to * log it or otherwise recover. * * <h3>How do I test event listeners and their subscriber methods?</h3> * <p>Because subscriber methods on your listener classes are normal methods, you can * simply call them from your test code to simulate the EventBus. */ package com.google.common.eventbus;
zzhhhhh-aw4rwer
guava/src/com/google/common/eventbus/package-info.java
Java
asf20
12,106
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.eventbus; import com.google.common.annotations.Beta; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Marks an event subscriber method as being thread-safe. This annotation * indicates that EventBus may invoke the event subscriber simultaneously from * multiple threads. * * <p>This does not mark the method, and so should be used in combination with * {@link Subscribe}. * * @author Cliff Biffle * @since 10.0 */ @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @Beta public @interface AllowConcurrentEvents { }
zzhhhhh-aw4rwer
guava/src/com/google/common/eventbus/AllowConcurrentEvents.java
Java
asf20
1,288
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.eventbus; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; /** * Wraps a single-argument subscriber method on a specific object, and ensures * that only one thread may enter the method at a time. * * <p>Beyond synchronization, this class behaves identically to * {@link EventSubscriber}. * * @author Cliff Biffle */ final class SynchronizedEventSubscriber extends EventSubscriber { /** * Creates a new SynchronizedEventSubscriber to wrap {@code method} on * {@code target}. * * @param target object to which the method applies. * @param method subscriber method. */ public SynchronizedEventSubscriber(Object target, Method method) { super(target, method); } @Override public void handleEvent(Object event) throws InvocationTargetException { // https://code.google.com/p/guava-libraries/issues/detail?id=1403 synchronized (this) { super.handleEvent(event); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/eventbus/SynchronizedEventSubscriber.java
Java
asf20
1,591
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.eventbus; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.base.Preconditions; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import javax.annotation.Nullable; /** * Wraps a single-argument subscriber method on a specific object. * * <p>This class only verifies the suitability of the method and event type if * something fails. Callers are expected to verify their uses of this class. * * <p>Two EventSubscribers are equivalent when they refer to the same method on the * same object (not class). This property is used to ensure that no subscriber * method is registered more than once. * * @author Cliff Biffle */ class EventSubscriber { /** Object sporting the subscriber method. */ private final Object target; /** Subscriber method. */ private final Method method; /** * Creates a new EventSubscriber to wrap {@code method} on @{code target}. * * @param target object to which the method applies. * @param method subscriber method. */ EventSubscriber(Object target, Method method) { Preconditions.checkNotNull(target, "EventSubscriber target cannot be null."); Preconditions.checkNotNull(method, "EventSubscriber method cannot be null."); this.target = target; this.method = method; method.setAccessible(true); } /** * Invokes the wrapped subscriber method to handle {@code event}. * * @param event event to handle * @throws InvocationTargetException if the wrapped method throws any * {@link Throwable} that is not an {@link Error} ({@code Error} instances are * propagated as-is). */ public void handleEvent(Object event) throws InvocationTargetException { checkNotNull(event); try { method.invoke(target, new Object[] { event }); } catch (IllegalArgumentException e) { throw new Error("Method rejected target/argument: " + event, e); } catch (IllegalAccessException e) { throw new Error("Method became inaccessible: " + event, e); } catch (InvocationTargetException e) { if (e.getCause() instanceof Error) { throw (Error) e.getCause(); } throw e; } } @Override public String toString() { return "[wrapper " + method + "]"; } @Override public int hashCode() { final int PRIME = 31; return (PRIME + method.hashCode()) * PRIME + System.identityHashCode(target); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof EventSubscriber) { EventSubscriber that = (EventSubscriber) obj; // Use == so that different equal instances will still receive events. // We only guard against the case that the same object is registered // multiple times return target == that.target && method.equals(that.method); } return false; } public Object getSubscriber() { return target; } public Method getMethod() { return method; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/eventbus/EventSubscriber.java
Java
asf20
3,630
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.common.eventbus; import static com.google.common.base.Preconditions.checkNotNull; import java.lang.reflect.Method; /** * Context for an exception thrown by a subscriber. * * @since 16.0 */ public class SubscriberExceptionContext { private final EventBus eventBus; private final Object event; private final Object subscriber; private final Method subscriberMethod; /** * @param eventBus The {@link EventBus} that handled the event and the * subscriber. Useful for broadcasting a a new event based on the error. * @param event The event object that caused the subscriber to throw. * @param subscriber The source subscriber context. * @param subscriberMethod the subscribed method. */ SubscriberExceptionContext(EventBus eventBus, Object event, Object subscriber, Method subscriberMethod) { this.eventBus = checkNotNull(eventBus); this.event = checkNotNull(event); this.subscriber = checkNotNull(subscriber); this.subscriberMethod = checkNotNull(subscriberMethod); } /** * @return The {@link EventBus} that handled the event and the subscriber. * Useful for broadcasting a a new event based on the error. */ public EventBus getEventBus() { return eventBus; } /** * @return The event object that caused the subscriber to throw. */ public Object getEvent() { return event; } /** * @return The object context that the subscriber was called on. */ public Object getSubscriber() { return subscriber; } /** * @return The subscribed method that threw the exception. */ public Method getSubscriberMethod() { return subscriberMethod; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/eventbus/SubscriberExceptionContext.java
Java
asf20
2,287
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.eventbus; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; /** * Wraps an event that was posted, but which had no subscribers and thus could * not be delivered. * * <p>Registering a DeadEvent subscriber is useful for debugging or logging, as * it can detect misconfigurations in a system's event distribution. * * @author Cliff Biffle * @since 10.0 */ @Beta public class DeadEvent { private final Object source; private final Object event; /** * Creates a new DeadEvent. * * @param source object broadcasting the DeadEvent (generally the * {@link EventBus}). * @param event the event that could not be delivered. */ public DeadEvent(Object source, Object event) { this.source = checkNotNull(source); this.event = checkNotNull(event); } /** * Returns the object that originated this event (<em>not</em> the object that * originated the wrapped event). This is generally an {@link EventBus}. * * @return the source of this event. */ public Object getSource() { return source; } /** * Returns the wrapped, 'dead' event, which the system was unable to deliver * to any registered subscriber. * * @return the 'dead' event that could not be delivered. */ public Object getEvent() { return event; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/eventbus/DeadEvent.java
Java
asf20
2,003
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.eventbus; import com.google.common.collect.Multimap; /** * A method for finding event subscriber methods in objects, for use by * {@link EventBus}. * * @author Cliff Biffle */ interface SubscriberFindingStrategy { /** * Finds all suitable event subscriber methods in {@code source}, organizes them * by the type of event they handle, and wraps them in {@link EventSubscriber} instances. * * @param source object whose subscribers are desired. * @return EventSubscriber objects for each subscriber method, organized by event * type. * * @throws IllegalArgumentException if {@code source} is not appropriate for * this strategy (in ways that this interface does not define). */ Multimap<Class<?>, EventSubscriber> findAllSubscribers(Object source); }
zzhhhhh-aw4rwer
guava/src/com/google/common/eventbus/SubscriberFindingStrategy.java
Java
asf20
1,437
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.eventbus; import com.google.common.base.Objects; import com.google.common.base.Throwables; import com.google.common.cache.CacheBuilder; import com.google.common.cache.CacheLoader; import com.google.common.cache.LoadingCache; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.reflect.TypeToken; import com.google.common.util.concurrent.UncheckedExecutionException; import java.lang.reflect.Method; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * A {@link SubscriberFindingStrategy} for collecting all event subscriber methods that are marked * with the {@link Subscribe} annotation. * * @author Cliff Biffle * @author Louis Wasserman */ class AnnotatedSubscriberFinder implements SubscriberFindingStrategy { /** * A thread-safe cache that contains the mapping from each class to all methods in that class and * all super-classes, that are annotated with {@code @Subscribe}. The cache is shared across all * instances of this class; this greatly improves performance if multiple EventBus instances are * created and objects of the same class are registered on all of them. */ private static final LoadingCache<Class<?>, ImmutableList<Method>> subscriberMethodsCache = CacheBuilder.newBuilder() .weakKeys() .build(new CacheLoader<Class<?>, ImmutableList<Method>>() { @Override public ImmutableList<Method> load(Class<?> concreteClass) throws Exception { return getAnnotatedMethodsInternal(concreteClass); } }); /** * {@inheritDoc} * * This implementation finds all methods marked with a {@link Subscribe} annotation. */ @Override public Multimap<Class<?>, EventSubscriber> findAllSubscribers(Object listener) { Multimap<Class<?>, EventSubscriber> methodsInListener = HashMultimap.create(); Class<?> clazz = listener.getClass(); for (Method method : getAnnotatedMethods(clazz)) { Class<?>[] parameterTypes = method.getParameterTypes(); Class<?> eventType = parameterTypes[0]; EventSubscriber subscriber = makeSubscriber(listener, method); methodsInListener.put(eventType, subscriber); } return methodsInListener; } private static ImmutableList<Method> getAnnotatedMethods(Class<?> clazz) { try { return subscriberMethodsCache.getUnchecked(clazz); } catch (UncheckedExecutionException e) { throw Throwables.propagate(e.getCause()); } } private static final class MethodIdentifier { private final String name; private final List<Class<?>> parameterTypes; MethodIdentifier(Method method) { this.name = method.getName(); this.parameterTypes = Arrays.asList(method.getParameterTypes()); } @Override public int hashCode() { return Objects.hashCode(name, parameterTypes); } @Override public boolean equals(@Nullable Object o) { if (o instanceof MethodIdentifier) { MethodIdentifier ident = (MethodIdentifier) o; return name.equals(ident.name) && parameterTypes.equals(ident.parameterTypes); } return false; } } private static ImmutableList<Method> getAnnotatedMethodsInternal(Class<?> clazz) { Set<? extends Class<?>> supers = TypeToken.of(clazz).getTypes().rawTypes(); Map<MethodIdentifier, Method> identifiers = Maps.newHashMap(); for (Class<?> superClazz : supers) { for (Method superClazzMethod : superClazz.getMethods()) { if (superClazzMethod.isAnnotationPresent(Subscribe.class)) { Class<?>[] parameterTypes = superClazzMethod.getParameterTypes(); if (parameterTypes.length != 1) { throw new IllegalArgumentException("Method " + superClazzMethod + " has @Subscribe annotation, but requires " + parameterTypes.length + " arguments. Event subscriber methods must require a single argument."); } MethodIdentifier ident = new MethodIdentifier(superClazzMethod); if (!identifiers.containsKey(ident)) { identifiers.put(ident, superClazzMethod); } } } } return ImmutableList.copyOf(identifiers.values()); } /** * Creates an {@code EventSubscriber} for subsequently calling {@code method} on * {@code listener}. * Selects an EventSubscriber implementation based on the annotations on * {@code method}. * * @param listener object bearing the event subscriber method. * @param method the event subscriber method to wrap in an EventSubscriber. * @return an EventSubscriber that will call {@code method} on {@code listener} * when invoked. */ private static EventSubscriber makeSubscriber(Object listener, Method method) { EventSubscriber wrapper; if (methodIsDeclaredThreadSafe(method)) { wrapper = new EventSubscriber(listener, method); } else { wrapper = new SynchronizedEventSubscriber(listener, method); } return wrapper; } /** * Checks whether {@code method} is thread-safe, as indicated by the * {@link AllowConcurrentEvents} annotation. * * @param method subscriber method to check. * @return {@code true} if {@code subscriber} is marked as thread-safe, * {@code false} otherwise. */ private static boolean methodIsDeclaredThreadSafe(Method method) { return method.getAnnotation(AllowConcurrentEvents.class) != null; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/eventbus/AnnotatedSubscriberFinder.java
Java
asf20
6,301
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.util.Arrays; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /** * Helper functions that can operate on any {@code Object}. * * <p>See the Guava User Guide on <a * href="http://code.google.com/p/guava-libraries/wiki/CommonObjectUtilitiesExplained">writing * {@code Object} methods with {@code Objects}</a>. * * @author Laurence Gonsalves * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public final class Objects { private Objects() {} /** * Determines whether two possibly-null objects are equal. Returns: * * <ul> * <li>{@code true} if {@code a} and {@code b} are both null. * <li>{@code true} if {@code a} and {@code b} are both non-null and they are * equal according to {@link Object#equals(Object)}. * <li>{@code false} in all other situations. * </ul> * * <p>This assumes that any non-null objects passed to this function conform * to the {@code equals()} contract. */ @CheckReturnValue public static boolean equal(@Nullable Object a, @Nullable Object b) { return a == b || (a != null && a.equals(b)); } /** * Generates a hash code for multiple values. The hash code is generated by * calling {@link Arrays#hashCode(Object[])}. Note that array arguments to * this method, with the exception of a single Object array, do not get any * special handling; their hash codes are based on identity and not contents. * * <p>This is useful for implementing {@link Object#hashCode()}. For example, * in an object that has three properties, {@code x}, {@code y}, and * {@code z}, one could write: * <pre> {@code * public int hashCode() { * return Objects.hashCode(getX(), getY(), getZ()); * }}</pre> * * <p><b>Warning</b>: When a single object is supplied, the returned hash code * does not equal the hash code of that object. */ public static int hashCode(@Nullable Object... objects) { return Arrays.hashCode(objects); } /** * Creates an instance of {@link ToStringHelper}. * * <p>This is helpful for implementing {@link Object#toString()}. * Specification by example: <pre> {@code * // Returns "ClassName{}" * Objects.toStringHelper(this) * .toString(); * * // Returns "ClassName{x=1}" * Objects.toStringHelper(this) * .add("x", 1) * .toString(); * * // Returns "MyObject{x=1}" * Objects.toStringHelper("MyObject") * .add("x", 1) * .toString(); * * // Returns "ClassName{x=1, y=foo}" * Objects.toStringHelper(this) * .add("x", 1) * .add("y", "foo") * .toString(); * * // Returns "ClassName{x=1}" * Objects.toStringHelper(this) * .omitNullValues() * .add("x", 1) * .add("y", null) * .toString(); * }}</pre> * * <p>Note that in GWT, class names are often obfuscated. * * @param self the object to generate the string for (typically {@code this}), * used only for its class name * @since 2.0 */ public static ToStringHelper toStringHelper(Object self) { return new ToStringHelper(simpleName(self.getClass())); } /** * Creates an instance of {@link ToStringHelper} in the same manner as * {@link Objects#toStringHelper(Object)}, but using the name of {@code clazz} * instead of using an instance's {@link Object#getClass()}. * * <p>Note that in GWT, class names are often obfuscated. * * @param clazz the {@link Class} of the instance * @since 7.0 (source-compatible since 2.0) */ public static ToStringHelper toStringHelper(Class<?> clazz) { return new ToStringHelper(simpleName(clazz)); } /** * Creates an instance of {@link ToStringHelper} in the same manner as * {@link Objects#toStringHelper(Object)}, but using {@code className} instead * of using an instance's {@link Object#getClass()}. * * @param className the name of the instance type * @since 7.0 (source-compatible since 2.0) */ public static ToStringHelper toStringHelper(String className) { return new ToStringHelper(className); } /** * {@link Class#getSimpleName()} is not GWT compatible yet, so we * provide our own implementation. */ private static String simpleName(Class<?> clazz) { String name = clazz.getName(); // the nth anonymous class has a class name ending in "Outer$n" // and local inner classes have names ending in "Outer.$1Inner" name = name.replaceAll("\\$[0-9]+", "\\$"); // we want the name of the inner class all by its lonesome int start = name.lastIndexOf('$'); // if this isn't an inner class, just find the start of the // top level class name. if (start == -1) { start = name.lastIndexOf('.'); } return name.substring(start + 1); } /** * Returns the first of two given parameters that is not {@code null}, if * either is, or otherwise throws a {@link NullPointerException}. * * <p><b>Note:</b> if {@code first} is represented as an {@link Optional}, * this can be accomplished with * {@linkplain Optional#or(Object) first.or(second)}. * That approach also allows for lazy evaluation of the fallback instance, * using {@linkplain Optional#or(Supplier) first.or(Supplier)}. * * @return {@code first} if {@code first} is not {@code null}, or * {@code second} if {@code first} is {@code null} and {@code second} is * not {@code null} * @throws NullPointerException if both {@code first} and {@code second} were * {@code null} * @since 3.0 */ public static <T> T firstNonNull(@Nullable T first, @Nullable T second) { return first != null ? first : checkNotNull(second); } /** * Support class for {@link Objects#toStringHelper}. * * @author Jason Lee * @since 2.0 */ public static final class ToStringHelper { private final String className; private ValueHolder holderHead = new ValueHolder(); private ValueHolder holderTail = holderHead; private boolean omitNullValues = false; /** * Use {@link Objects#toStringHelper(Object)} to create an instance. */ private ToStringHelper(String className) { this.className = checkNotNull(className); } /** * Configures the {@link ToStringHelper} so {@link #toString()} will ignore * properties with null value. The order of calling this method, relative * to the {@code add()}/{@code addValue()} methods, is not significant. * * @since 12.0 */ public ToStringHelper omitNullValues() { omitNullValues = true; return this; } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. If {@code value} is {@code null}, the string {@code "null"} * is used, unless {@link #omitNullValues()} is called, in which case this * name/value pair will not be added. */ public ToStringHelper add(String name, @Nullable Object value) { return addHolder(name, value); } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper add(String name, boolean value) { return addHolder(name, String.valueOf(value)); } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper add(String name, char value) { return addHolder(name, String.valueOf(value)); } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper add(String name, double value) { return addHolder(name, String.valueOf(value)); } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper add(String name, float value) { return addHolder(name, String.valueOf(value)); } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper add(String name, int value) { return addHolder(name, String.valueOf(value)); } /** * Adds a name/value pair to the formatted output in {@code name=value} * format. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper add(String name, long value) { return addHolder(name, String.valueOf(value)); } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, Object)} instead * and give value a readable name. */ public ToStringHelper addValue(@Nullable Object value) { return addHolder(value); } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, boolean)} instead * and give value a readable name. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper addValue(boolean value) { return addHolder(String.valueOf(value)); } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, char)} instead * and give value a readable name. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper addValue(char value) { return addHolder(String.valueOf(value)); } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, double)} instead * and give value a readable name. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper addValue(double value) { return addHolder(String.valueOf(value)); } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, float)} instead * and give value a readable name. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper addValue(float value) { return addHolder(String.valueOf(value)); } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, int)} instead * and give value a readable name. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper addValue(int value) { return addHolder(String.valueOf(value)); } /** * Adds an unnamed value to the formatted output. * * <p>It is strongly encouraged to use {@link #add(String, long)} instead * and give value a readable name. * * @since 11.0 (source-compatible since 2.0) */ public ToStringHelper addValue(long value) { return addHolder(String.valueOf(value)); } /** * Returns a string in the format specified by {@link * Objects#toStringHelper(Object)}. * * <p>After calling this method, you can keep adding more properties to later * call toString() again and get a more complete representation of the * same object; but properties cannot be removed, so this only allows * limited reuse of the helper instance. The helper allows duplication of * properties (multiple name/value pairs with the same name can be added). */ @Override public String toString() { // create a copy to keep it consistent in case value changes boolean omitNullValuesSnapshot = omitNullValues; String nextSeparator = ""; StringBuilder builder = new StringBuilder(32).append(className) .append('{'); for (ValueHolder valueHolder = holderHead.next; valueHolder != null; valueHolder = valueHolder.next) { if (!omitNullValuesSnapshot || valueHolder.value != null) { builder.append(nextSeparator); nextSeparator = ", "; if (valueHolder.name != null) { builder.append(valueHolder.name).append('='); } builder.append(valueHolder.value); } } return builder.append('}').toString(); } private ValueHolder addHolder() { ValueHolder valueHolder = new ValueHolder(); holderTail = holderTail.next = valueHolder; return valueHolder; } private ToStringHelper addHolder(@Nullable Object value) { ValueHolder valueHolder = addHolder(); valueHolder.value = value; return this; } private ToStringHelper addHolder(String name, @Nullable Object value) { ValueHolder valueHolder = addHolder(); valueHolder.value = value; valueHolder.name = checkNotNull(name); return this; } private static final class ValueHolder { String name; Object value; ValueHolder next; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Objects.java
Java
asf20
13,936
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import javax.annotation.Nullable; /** * Determines an output value based on an input value. * * <p>The {@link Functions} class provides common functions and related utilites. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the use of {@code * Function}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface Function<F, T> { /** * Returns the result of applying this function to {@code input}. This method is <i>generally * expected</i>, but not absolutely required, to have the following properties: * * <ul> * <li>Its execution does not cause any observable side effects. * <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal * Objects.equal}{@code (a, b)} implies that {@code Objects.equal(function.apply(a), * function.apply(b))}. * </ul> * * @throws NullPointerException if {@code input} is null and this function does not accept null * arguments */ @Nullable T apply(@Nullable F input); /** * Indicates whether another object is equal to this function. * * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}. * However, an implementation may also choose to return {@code true} whenever {@code object} is a * {@link Function} that it considers <i>interchangeable</i> with this one. "Interchangeable" * <i>typically</i> means that {@code Objects.equal(this.apply(f), that.apply(f))} is true for all * {@code f} of type {@code F}. Note that a {@code false} result from this method does not imply * that the functions are known <i>not</i> to be interchangeable. */ @Override boolean equals(@Nullable Object object); }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Function.java
Java
asf20
2,529
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import java.lang.ref.PhantomReference; import java.lang.ref.ReferenceQueue; /** * Phantom reference with a {@code finalizeReferent()} method which a background thread invokes * after the garbage collector reclaims the referent. This is a simpler alternative to using a * {@link ReferenceQueue}. * * <p>Unlike a normal phantom reference, this reference will be cleared automatically. * * @author Bob Lee * @since 2.0 (imported from Google Collections Library) */ public abstract class FinalizablePhantomReference<T> extends PhantomReference<T> implements FinalizableReference { /** * Constructs a new finalizable phantom reference. * * @param referent to phantom reference * @param queue that should finalize the referent */ protected FinalizablePhantomReference(T referent, FinalizableReferenceQueue queue) { super(referent, queue.queue); queue.cleanUp(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/FinalizablePhantomReference.java
Java
asf20
1,538
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Iterator; import javax.annotation.Nullable; @GwtCompatible(serializable = true) final class PairwiseEquivalence<T> extends Equivalence<Iterable<T>> implements Serializable { final Equivalence<? super T> elementEquivalence; PairwiseEquivalence(Equivalence<? super T> elementEquivalence) { this.elementEquivalence = Preconditions.checkNotNull(elementEquivalence); } @Override protected boolean doEquivalent(Iterable<T> iterableA, Iterable<T> iterableB) { Iterator<T> iteratorA = iterableA.iterator(); Iterator<T> iteratorB = iterableB.iterator(); while (iteratorA.hasNext() && iteratorB.hasNext()) { if (!elementEquivalence.equivalent(iteratorA.next(), iteratorB.next())) { return false; } } return !iteratorA.hasNext() && !iteratorB.hasNext(); } @Override protected int doHash(Iterable<T> iterable) { int hash = 78721; for (T element : iterable) { hash = hash * 24943 + elementEquivalence.hash(element); } return hash; } @Override public boolean equals(@Nullable Object object) { if (object instanceof PairwiseEquivalence) { PairwiseEquivalence<?> that = (PairwiseEquivalence<?>) object; return this.elementEquivalence.equals(that.elementEquivalence); } return false; } @Override public int hashCode() { return elementEquivalence.hashCode() ^ 0x46a3eb07; } @Override public String toString() { return elementEquivalence + ".pairwise()"; } private static final long serialVersionUID = 1; }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/PairwiseEquivalence.java
Java
asf20
2,275
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import javax.annotation.Nullable; /** * Static convenience methods that help a method or constructor check whether it was invoked * correctly (whether its <i>preconditions</i> have been met). These methods generally accept a * {@code boolean} expression which is expected to be {@code true} (or in the case of {@code * checkNotNull}, an object reference which is expected to be non-null). When {@code false} (or * {@code null}) is passed instead, the {@code Preconditions} method throws an unchecked exception, * which helps the calling method communicate to <i>its</i> caller that <i>that</i> caller has made * a mistake. Example: <pre> {@code * * /** * * Returns the positive square root of the given value. * * * * @throws IllegalArgumentException if the value is negative * *}{@code / * public static double sqrt(double value) { * Preconditions.checkArgument(value >= 0.0, "negative value: %s", value); * // calculate the square root * } * * void exampleBadCaller() { * double d = sqrt(-1.0); * }}</pre> * * In this example, {@code checkArgument} throws an {@code IllegalArgumentException} to indicate * that {@code exampleBadCaller} made an error in <i>its</i> call to {@code sqrt}. * * <h3>Warning about performance</h3> * * <p>The goal of this class is to improve readability of code, but in some circumstances this may * come at a significant performance cost. Remember that parameter values for message construction * must all be computed eagerly, and autoboxing and varargs array creation may happen as well, even * when the precondition check then succeeds (as it should almost always do in production). In some * circumstances these wasted CPU cycles and allocations can add up to a real problem. * Performance-sensitive precondition checks can always be converted to the customary form: * <pre> {@code * * if (value < 0.0) { * throw new IllegalArgumentException("negative value: " + value); * }}</pre> * * <h3>Other types of preconditions</h3> * * <p>Not every type of precondition failure is supported by these methods. Continue to throw * standard JDK exceptions such as {@link java.util.NoSuchElementException} or {@link * UnsupportedOperationException} in the situations they are intended for. * * <h3>Non-preconditions</h3> * * <p>It is of course possible to use the methods of this class to check for invalid conditions * which are <i>not the caller's fault</i>. Doing so is <b>not recommended</b> because it is * misleading to future readers of the code and of stack traces. See * <a href="http://code.google.com/p/guava-libraries/wiki/ConditionalFailuresExplained">Conditional * failures explained</a> in the Guava User Guide for more advice. * * <h3>{@code java.util.Objects.requireNonNull()}</h3> * * <p>Projects which use {@code com.google.common} should generally avoid the use of {@link * java.util.Objects#requireNonNull(Object)}. Instead, use whichever of {@link * #checkNotNull(Object)} or {@link Verify#verifyNotNull(Object)} is appropriate to the situation. * (The same goes for the message-accepting overloads.) * * <h3>Only {@code %s} is supported</h3> * * <p>In {@code Preconditions} error message template strings, only the {@code "%s"} specifier is * supported, not the full range of {@link java.util.Formatter} specifiers. However, note that if * the number of arguments does not match the number of occurrences of {@code "%s"} in the format * string, {@code Preconditions} will still behave as expected, and will still include all argument * values in the error message; the message will simply not be formatted exactly as intended. * * <h3>More information</h3> * * <p>See the Guava User Guide on * <a href="http://code.google.com/p/guava-libraries/wiki/PreconditionsExplained">using {@code * Preconditions}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public final class Preconditions { private Preconditions() {} /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression) { if (!expression) { throw new IllegalArgumentException(); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression, @Nullable Object errorMessage) { if (!expression) { throw new IllegalArgumentException(String.valueOf(errorMessage)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message * in square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @throws IllegalArgumentException if {@code expression} is false * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or * {@code errorMessageArgs} is null (don't let this happen) */ public static void checkArgument(boolean expression, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (!expression) { throw new IllegalArgumentException(format(errorMessageTemplate, errorMessageArgs)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @throws IllegalStateException if {@code expression} is false */ public static void checkState(boolean expression) { if (!expression) { throw new IllegalStateException(); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @throws IllegalStateException if {@code expression} is false */ public static void checkState(boolean expression, @Nullable Object errorMessage) { if (!expression) { throw new IllegalStateException(String.valueOf(errorMessage)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message * in square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @throws IllegalStateException if {@code expression} is false * @throws NullPointerException if the check fails and either {@code errorMessageTemplate} or * {@code errorMessageArgs} is null (don't let this happen) */ public static void checkState(boolean expression, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (!expression) { throw new IllegalStateException(format(errorMessageTemplate, errorMessageArgs)); } } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(T reference) { if (reference == null) { throw new NullPointerException(); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(T reference, @Nullable Object errorMessage) { if (reference == null) { throw new NullPointerException(String.valueOf(errorMessage)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message * in square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null */ public static <T> T checkNotNull(T reference, @Nullable String errorMessageTemplate, @Nullable Object... errorMessageArgs) { if (reference == null) { // If either of these parameters is null, the right thing happens anyway throw new NullPointerException(format(errorMessageTemplate, errorMessageArgs)); } return reference; } /* * All recent hotspots (as of 2009) *really* like to have the natural code * * if (guardExpression) { * throw new BadException(messageExpression); * } * * refactored so that messageExpression is moved to a separate String-returning method. * * if (guardExpression) { * throw new BadException(badMsg(...)); * } * * The alternative natural refactorings into void or Exception-returning methods are much slower. * This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This * is a hotspot optimizer bug, which should be fixed, but that's a separate, big project). * * The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a * RangeCheckMicroBenchmark in the JDK that was used to test this. * * But the methods in this class want to throw different exceptions, depending on the args, so it * appears that this pattern is not directly applicable. But we can use the ridiculous, devious * trick of throwing an exception in the middle of the construction of another exception. Hotspot * is fine with that. */ /** * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive. * * @param index a user-supplied index identifying an element of an array, list or string * @param size the size of that array, list or string * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkElementIndex(int index, int size) { return checkElementIndex(index, size, "index"); } /** * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive. * * @param index a user-supplied index identifying an element of an array, list or string * @param size the size of that array, list or string * @param desc the text to use to describe this index in an error message * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkElementIndex( int index, int size, @Nullable String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(badElementIndex(index, size, desc)); } return index; } private static String badElementIndex(int index, int size, String desc) { if (index < 0) { return format("%s (%s) must not be negative", desc, index); } else if (size < 0) { throw new IllegalArgumentException("negative size: " + size); } else { // index >= size return format("%s (%s) must be less than size (%s)", desc, index, size); } } /** * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of * size {@code size}. A position index may range from zero to {@code size}, inclusive. * * @param index a user-supplied index identifying a position in an array, list or string * @param size the size of that array, list or string * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkPositionIndex(int index, int size) { return checkPositionIndex(index, size, "index"); } /** * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of * size {@code size}. A position index may range from zero to {@code size}, inclusive. * * @param index a user-supplied index identifying a position in an array, list or string * @param size the size of that array, list or string * @param desc the text to use to describe this index in an error message * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ public static int checkPositionIndex(int index, int size, @Nullable String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index > size) { throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc)); } return index; } private static String badPositionIndex(int index, int size, String desc) { if (index < 0) { return format("%s (%s) must not be negative", desc, index); } else if (size < 0) { throw new IllegalArgumentException("negative size: " + size); } else { // index > size return format("%s (%s) must not be greater than size (%s)", desc, index, size); } } /** * Ensures that {@code start} and {@code end} specify a valid <i>positions</i> in an array, list * or string of size {@code size}, and are in order. A position index may range from zero to * {@code size}, inclusive. * * @param start a user-supplied index identifying a starting position in an array, list or string * @param end a user-supplied index identifying a ending position in an array, list or string * @param size the size of that array, list or string * @throws IndexOutOfBoundsException if either index is negative or is greater than {@code size}, * or if {@code end} is less than {@code start} * @throws IllegalArgumentException if {@code size} is negative */ public static void checkPositionIndexes(int start, int end, int size) { // Carefully optimized for execution by hotspot (explanatory comment above) if (start < 0 || end < start || end > size) { throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size)); } } private static String badPositionIndexes(int start, int end, int size) { if (start < 0 || start > size) { return badPositionIndex(start, size, "start index"); } if (end < 0 || end > size) { return badPositionIndex(end, size, "end index"); } // end < start return format("end index (%s) must not be less than start index (%s)", end, start); } /** * Substitutes each {@code %s} in {@code template} with an argument. These are matched by * position: the first {@code %s} gets {@code args[0]}, etc. If there are more arguments than * placeholders, the unmatched arguments will be appended to the end of the formatted message in * square braces. * * @param template a non-null string containing 0 or more {@code %s} placeholders. * @param args the arguments to be substituted into the message template. Arguments are converted * to strings using {@link String#valueOf(Object)}. Arguments can be null. */ // Note that this is somewhat-improperly used from Verify.java as well. static String format(String template, @Nullable Object... args) { template = String.valueOf(template); // null -> "null" // start substituting the arguments into the '%s' placeholders StringBuilder builder = new StringBuilder(template.length() + 16 * args.length); int templateStart = 0; int i = 0; while (i < args.length) { int placeholderStart = template.indexOf("%s", templateStart); if (placeholderStart == -1) { break; } builder.append(template.substring(templateStart, placeholderStart)); builder.append(args[i++]); templateStart = placeholderStart + 2; } builder.append(template.substring(templateStart)); // if we run out of placeholders, append the extra args in square braces if (i < args.length) { builder.append(" ["); builder.append(args[i++]); while (i < args.length) { builder.append(", "); builder.append(args[i++]); } builder.append(']'); } return builder.toString(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Preconditions.java
Java
asf20
19,830
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.GwtCompatible; import java.util.Iterator; import java.util.NoSuchElementException; /** * Note this class is a copy of * {@link com.google.common.collect.AbstractIterator} (for dependency reasons). */ @GwtCompatible abstract class AbstractIterator<T> implements Iterator<T> { private State state = State.NOT_READY; protected AbstractIterator() {} private enum State { READY, NOT_READY, DONE, FAILED, } private T next; protected abstract T computeNext(); protected final T endOfData() { state = State.DONE; return null; } @Override public final boolean hasNext() { checkState(state != State.FAILED); switch (state) { case DONE: return false; case READY: return true; default: } return tryToComputeNext(); } private boolean tryToComputeNext() { state = State.FAILED; // temporary pessimism next = computeNext(); if (state != State.DONE) { state = State.READY; return true; } return false; } @Override public final T next() { if (!hasNext()) { throw new NoSuchElementException(); } state = State.NOT_READY; T result = next; next = null; return result; } @Override public final void remove() { throw new UnsupportedOperationException(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/AbstractIterator.java
Java
asf20
2,050
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Iterator; import javax.annotation.Nullable; /** * A function from {@code A} to {@code B} with an associated <i>reverse</i> function from {@code B} * to {@code A}; used for converting back and forth between <i>different representations of the same * information</i>. * * <h3>Invertibility</h3> * * <p>The reverse operation <b>may</b> be a strict <i>inverse</i> (meaning that {@code * converter.reverse().convert(converter.convert(a)).equals(a)} is always true). However, it is * very common (perhaps <i>more</i> common) for round-trip conversion to be <i>lossy</i>. Consider * an example round-trip using {@link com.google.common.primitives.Doubles#stringConverter}: * * <ol> * <li>{@code stringConverter().convert("1.00")} returns the {@code Double} value {@code 1.0} * <li>{@code stringConverter().reverse().convert(1.0)} returns the string {@code "1.0"} -- * <i>not</i> the same string ({@code "1.00"}) we started with * </ol> * * <p>Note that it should still be the case that the round-tripped and original objects are * <i>similar</i>. * * <h3>Nullability</h3> * * <p>A converter always converts {@code null} to {@code null} and non-null references to non-null * references. It would not make sense to consider {@code null} and a non-null reference to be * "different representations of the same information", since one is distinguishable from * <i>missing</i> information and the other is not. The {@link #convert} method handles this null * behavior for all converters; implementations of {@link #doForward} and {@link #doBackward} are * guaranteed to never be passed {@code null}, and must never return {@code null}. * * <h3>Common ways to use</h3> * * <p>Getting a converter: * * <ul> * <li>Use a provided converter implementation, such as {@link Enums#stringConverter}, {@link * com.google.common.primitives.Ints#stringConverter Ints.stringConverter} or the {@linkplain * #reverse reverse} views of these. * <li>Convert between specific preset values using {@link * com.google.common.collect.Maps#asConverter Maps.asConverter}. For example, use this to create * a "fake" converter for a unit test. It is unnecessary (and confusing) to <i>mock</i> the * {@code Converter} type using a mocking framework. * <li>Otherwise, extend this class and implement its {@link #doForward} and {@link #doBackward} * methods. * </ul> * * <p>Using a converter: * * <ul> * <li>Convert one instance in the "forward" direction using {@code converter.convert(a)}. * <li>Convert multiple instances "forward" using {@code converter.convertAll(as)}. * <li>Convert in the "backward" direction using {@code converter.reverse().convert(b)} or {@code * converter.reverse().convertAll(bs)}. * <li>Use {@code converter} or {@code converter.reverse()} anywhere a {@link Function} is accepted * <li><b>Do not</b> call {@link #doForward} or {@link #doBackward} directly; these exist only to be * overridden. * </ul> * * @author Mike Ward * @author Kurt Alfred Kluever * @author Gregory Kick * @since 16.0 */ @Beta @GwtCompatible public abstract class Converter<A, B> implements Function<A, B> { private final boolean handleNullAutomatically; // We lazily cache the reverse view to avoid allocating on every call to reverse(). private transient Converter<B, A> reverse; /** Constructor for use by subclasses. */ protected Converter() { this(true); } /** * Constructor used only by {@code LegacyConverter} to suspend automatic null-handling. */ Converter(boolean handleNullAutomatically) { this.handleNullAutomatically = handleNullAutomatically; } // SPI methods (what subclasses must implement) /** * Returns a representation of {@code a} as an instance of type {@code B}. If {@code a} cannot be * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown. * * @param a the instance to convert; will never be null * @return the converted instance; <b>must not</b> be null */ protected abstract B doForward(A a); /** * Returns a representation of {@code b} as an instance of type {@code A}. If {@code b} cannot be * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown. * * @param b the instance to convert; will never be null * @return the converted instance; <b>must not</b> be null * @throws UnsupportedOperationException if backward conversion is not implemented; this should be * very rare. Note that if backward conversion is not only unimplemented but * unimplement<i>able</i> (for example, consider a {@code Converter<Chicken, ChickenNugget>}), * then this is not logically a {@code Converter} at all, and should just implement {@link * Function}. */ protected abstract A doBackward(B b); // API (consumer-side) methods /** * Returns a representation of {@code a} as an instance of type {@code B}. * * @return the converted value; is null <i>if and only if</i> {@code a} is null */ @Nullable public final B convert(@Nullable A a) { return correctedDoForward(a); } @Nullable B correctedDoForward(@Nullable A a) { if (handleNullAutomatically) { // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? return a == null ? null : checkNotNull(doForward(a)); } else { return doForward(a); } } @Nullable A correctedDoBackward(@Nullable B b) { if (handleNullAutomatically) { // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? return b == null ? null : checkNotNull(doBackward(b)); } else { return doBackward(b); } } /** * Returns an iterable that applies {@code convert} to each element of {@code fromIterable}. The * conversion is done lazily. * * <p>The returned iterable's iterator supports {@code remove()} if the input iterator does. After * a successful {@code remove()} call, {@code fromIterable} no longer contains the corresponding * element. */ public Iterable<B> convertAll(final Iterable<? extends A> fromIterable) { checkNotNull(fromIterable, "fromIterable"); return new Iterable<B>() { @Override public Iterator<B> iterator() { return new Iterator<B>() { private final Iterator<? extends A> fromIterator = fromIterable.iterator(); @Override public boolean hasNext() { return fromIterator.hasNext(); } @Override public B next() { return convert(fromIterator.next()); } @Override public void remove() { fromIterator.remove(); } }; } }; } /** * Returns the reversed view of this converter, which converts {@code this.convert(a)} back to a * value roughly equivalent to {@code a}. * * <p>The returned converter is serializable if {@code this} converter is. */ // TODO(user): Make this method final public Converter<B, A> reverse() { Converter<B, A> result = reverse; return (result == null) ? reverse = new ReverseConverter<A, B>(this) : result; } private static final class ReverseConverter<A, B> extends Converter<B, A> implements Serializable { final Converter<A, B> original; ReverseConverter(Converter<A, B> original) { this.original = original; } /* * These gymnastics are a little confusing. Basically this class has neither legacy nor * non-legacy behavior; it just needs to let the behavior of the backing converter shine * through. So, we override the correctedDo* methods, after which the do* methods should never * be reached. */ @Override protected A doForward(B b) { throw new AssertionError(); } @Override protected B doBackward(A a) { throw new AssertionError(); } @Override @Nullable A correctedDoForward(@Nullable B b) { return original.correctedDoBackward(b); } @Override @Nullable B correctedDoBackward(@Nullable A a) { return original.correctedDoForward(a); } @Override public Converter<A, B> reverse() { return original; } @Override public boolean equals(@Nullable Object object) { if (object instanceof ReverseConverter) { ReverseConverter<?, ?> that = (ReverseConverter<?, ?>) object; return this.original.equals(that.original); } return false; } @Override public int hashCode() { return ~original.hashCode(); } @Override public String toString() { return original + ".reverse()"; } private static final long serialVersionUID = 0L; } /** * Returns a converter whose {@code convert} method applies {@code secondConverter} to the result * of this converter. Its {@code reverse} method applies the converters in reverse order. * * <p>The returned converter is serializable if {@code this} converter and {@code secondConverter} * are. */ public <C> Converter<A, C> andThen(Converter<B, C> secondConverter) { return new ConverterComposition<A, B, C>(this, checkNotNull(secondConverter)); } private static final class ConverterComposition<A, B, C> extends Converter<A, C> implements Serializable { final Converter<A, B> first; final Converter<B, C> second; ConverterComposition(Converter<A, B> first, Converter<B, C> second) { this.first = first; this.second = second; } /* * These gymnastics are a little confusing. Basically this class has neither legacy nor * non-legacy behavior; it just needs to let the behaviors of the backing converters shine * through (which might even differ from each other!). So, we override the correctedDo* methods, * after which the do* methods should never be reached. */ @Override protected C doForward(A a) { throw new AssertionError(); } @Override protected A doBackward(C c) { throw new AssertionError(); } @Override @Nullable C correctedDoForward(@Nullable A a) { return second.correctedDoForward(first.correctedDoForward(a)); } @Override @Nullable A correctedDoBackward(@Nullable C c) { return first.correctedDoBackward(second.correctedDoBackward(c)); } @Override public boolean equals(@Nullable Object object) { if (object instanceof ConverterComposition) { ConverterComposition<?, ?, ?> that = (ConverterComposition<?, ?, ?>) object; return this.first.equals(that.first) && this.second.equals(that.second); } return false; } @Override public int hashCode() { return 31 * first.hashCode() + second.hashCode(); } @Override public String toString() { return first + ".andThen(" + second + ")"; } private static final long serialVersionUID = 0L; } /** * @deprecated Provided to satisfy the {@code Function} interface; use {@link #convert} instead. */ @Deprecated @Override @Nullable public final B apply(@Nullable A a) { return convert(a); } /** * Indicates whether another object is equal to this converter. * * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}. * However, an implementation may also choose to return {@code true} whenever {@code object} is a * {@link Converter} that it considers <i>interchangeable</i> with this one. "Interchangeable" * <i>typically</i> means that {@code Objects.equal(this.convert(a), that.convert(a))} is true for * all {@code a} of type {@code A} (and similarly for {@code reverse}). Note that a {@code false} * result from this method does not imply that the converters are known <i>not</i> to be * interchangeable. */ @Override public boolean equals(@Nullable Object object) { return super.equals(object); } // Static converters /** * Returns a converter based on <i>existing</i> forward and backward functions. Note that it is * unnecessary to create <i>new</i> classes implementing {@code Function} just to pass them in * here. Instead, simply subclass {@code Converter} and implement its {@link #doForward} and * {@link #doBackward} methods directly. * * <p>These functions will never be passed {@code null} and must not under any circumstances * return {@code null}. If a value cannot be converted, the function should throw an unchecked * exception (typically, but not necessarily, {@link IllegalArgumentException}). * * <p>The returned converter is serializable if both provided functions are. * * @since 17.0 */ public static <A, B> Converter<A, B> from( Function<? super A, ? extends B> forwardFunction, Function<? super B, ? extends A> backwardFunction) { return new FunctionBasedConverter<A, B>(forwardFunction, backwardFunction); } private static final class FunctionBasedConverter<A, B> extends Converter<A, B> implements Serializable { private final Function<? super A, ? extends B> forwardFunction; private final Function<? super B, ? extends A> backwardFunction; private FunctionBasedConverter( Function<? super A, ? extends B> forwardFunction, Function<? super B, ? extends A> backwardFunction) { this.forwardFunction = checkNotNull(forwardFunction); this.backwardFunction = checkNotNull(backwardFunction); } @Override protected B doForward(A a) { return forwardFunction.apply(a); } @Override protected A doBackward(B b) { return backwardFunction.apply(b); } @Override public boolean equals(@Nullable Object object) { if (object instanceof FunctionBasedConverter) { FunctionBasedConverter<?, ?> that = (FunctionBasedConverter<?, ?>) object; return this.forwardFunction.equals(that.forwardFunction) && this.backwardFunction.equals(that.backwardFunction); } return false; } @Override public int hashCode() { return forwardFunction.hashCode() * 31 + backwardFunction.hashCode(); } @Override public String toString() { return "Converter.from(" + forwardFunction + ", " + backwardFunction + ")"; } } /** * Returns a serializable converter that always converts or reverses an object to itself. */ @SuppressWarnings("unchecked") // implementation is "fully variant" public static <T> Converter<T, T> identity() { return (IdentityConverter<T>) IdentityConverter.INSTANCE; } /** * A converter that always converts or reverses an object to itself. Note that T is now a * "pass-through type". */ private static final class IdentityConverter<T> extends Converter<T, T> implements Serializable { static final IdentityConverter INSTANCE = new IdentityConverter(); @Override protected T doForward(T t) { return t; } @Override protected T doBackward(T t) { return t; } @Override public IdentityConverter<T> reverse() { return this; } @Override public <S> Converter<T, S> andThen(Converter<T, S> otherConverter) { return checkNotNull(otherConverter, "otherConverter"); } /* * We *could* override convertAll() to return its input, but it's a rather pointless * optimization and opened up a weird type-safety problem. */ @Override public String toString() { return "Converter.identity()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 0L; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Converter.java
Java
asf20
16,580
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import javax.annotation.Nullable; /** * A strategy for determining whether two instances are considered equivalent. Examples of * equivalences are the {@linkplain #identity() identity equivalence} and {@linkplain #equals equals * equivalence}. * * @author Bob Lee * @author Ben Yu * @author Gregory Kick * @since 10.0 (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility" * >mostly source-compatible</a> since 4.0) */ @GwtCompatible public abstract class Equivalence<T> { /** * Constructor for use by subclasses. */ protected Equivalence() {} /** * Returns {@code true} if the given objects are considered equivalent. * * <p>The {@code equivalent} method implements an equivalence relation on object references: * * <ul> * <li>It is <i>reflexive</i>: for any reference {@code x}, including null, {@code * equivalent(x, x)} returns {@code true}. * <li>It is <i>symmetric</i>: for any references {@code x} and {@code y}, {@code * equivalent(x, y) == equivalent(y, x)}. * <li>It is <i>transitive</i>: for any references {@code x}, {@code y}, and {@code z}, if * {@code equivalent(x, y)} returns {@code true} and {@code equivalent(y, z)} returns {@code * true}, then {@code equivalent(x, z)} returns {@code true}. * <li>It is <i>consistent</i>: for any references {@code x} and {@code y}, multiple invocations * of {@code equivalent(x, y)} consistently return {@code true} or consistently return {@code * false} (provided that neither {@code x} nor {@code y} is modified). * </ul> */ public final boolean equivalent(@Nullable T a, @Nullable T b) { if (a == b) { return true; } if (a == null || b == null) { return false; } return doEquivalent(a, b); } /** * Returns {@code true} if {@code a} and {@code b} are considered equivalent. * * <p>Called by {@link #equivalent}. {@code a} and {@code b} are not the same * object and are not nulls. * * @since 10.0 (previously, subclasses would override equivalent()) */ protected abstract boolean doEquivalent(T a, T b); /** * Returns a hash code for {@code t}. * * <p>The {@code hash} has the following properties: * <ul> * <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of * {@code hash(x}} consistently return the same value provided {@code x} remains unchanged * according to the definition of the equivalence. The hash need not remain consistent from * one execution of an application to another execution of the same application. * <li>It is <i>distributable across equivalence</i>: for any references {@code x} and {@code y}, * if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> necessary * that the hash be distributable across <i>inequivalence</i>. If {@code equivalence(x, y)} * is false, {@code hash(x) == hash(y)} may still be true. * <li>{@code hash(null)} is {@code 0}. * </ul> */ public final int hash(@Nullable T t) { if (t == null) { return 0; } return doHash(t); } /** * Returns a hash code for non-null object {@code t}. * * <p>Called by {@link #hash}. * * @since 10.0 (previously, subclasses would override hash()) */ protected abstract int doHash(T t); /** * Returns a new equivalence relation for {@code F} which evaluates equivalence by first applying * {@code function} to the argument, then evaluating using {@code this}. That is, for any pair of * non-null objects {@code x} and {@code y}, {@code * equivalence.onResultOf(function).equivalent(a, b)} is true if and only if {@code * equivalence.equivalent(function.apply(a), function.apply(b))} is true. * * <p>For example: * * <pre> {@code * Equivalence<Person> SAME_AGE = Equivalence.equals().onResultOf(GET_PERSON_AGE);}</pre> * * <p>{@code function} will never be invoked with a null value. * * <p>Note that {@code function} must be consistent according to {@code this} equivalence * relation. That is, invoking {@link Function#apply} multiple times for a given value must return * equivalent results. * For example, {@code Equivalence.identity().onResultOf(Functions.toStringFunction())} is broken * because it's not guaranteed that {@link Object#toString}) always returns the same string * instance. * * @since 10.0 */ public final <F> Equivalence<F> onResultOf(Function<F, ? extends T> function) { return new FunctionalEquivalence<F, T>(function, this); } /** * Returns a wrapper of {@code reference} that implements * {@link Wrapper#equals(Object) Object.equals()} such that * {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a, b)}. * * @since 10.0 */ public final <S extends T> Wrapper<S> wrap(@Nullable S reference) { return new Wrapper<S>(this, reference); } /** * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an * {@link Equivalence}. * * <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv} * that tests equivalence using their lengths: * * <pre> {@code * equiv.wrap("a").equals(equiv.wrap("b")) // true * equiv.wrap("a").equals(equiv.wrap("hello")) // false}</pre> * * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps. * * <pre> {@code * equiv.wrap(obj).equals(obj) // always false}</pre> * * @since 10.0 */ public static final class Wrapper<T> implements Serializable { private final Equivalence<? super T> equivalence; @Nullable private final T reference; private Wrapper(Equivalence<? super T> equivalence, @Nullable T reference) { this.equivalence = checkNotNull(equivalence); this.reference = reference; } /** Returns the (possibly null) reference wrapped by this instance. */ @Nullable public T get() { return reference; } /** * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped * references is {@code true} and both wrappers use the {@link Object#equals(Object) same} * equivalence. */ @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } if (obj instanceof Wrapper) { Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T> if (this.equivalence.equals(that.equivalence)) { /* * We'll accept that as sufficient "proof" that either equivalence should be able to * handle either reference, so it's safe to circumvent compile-time type checking. */ @SuppressWarnings("unchecked") Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence; return equivalence.equivalent(this.reference, that.reference); } } return false; } /** * Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference. */ @Override public int hashCode() { return equivalence.hash(reference); } /** * Returns a string representation for this equivalence wrapper. The form of this string * representation is not specified. */ @Override public String toString() { return equivalence + ".wrap(" + reference + ")"; } private static final long serialVersionUID = 0; } /** * Returns an equivalence over iterables based on the equivalence of their elements. More * specifically, two iterables are considered equivalent if they both contain the same number of * elements, and each pair of corresponding elements is equivalent according to * {@code this}. Null iterables are equivalent to one another. * * <p>Note that this method performs a similar function for equivalences as {@link * com.google.common.collect.Ordering#lexicographical} does for orderings. * * @since 10.0 */ @GwtCompatible(serializable = true) public final <S extends T> Equivalence<Iterable<S>> pairwise() { // Ideally, the returned equivalence would support Iterable<? extends T>. However, // the need for this is so rare that it's not worth making callers deal with the ugly wildcard. return new PairwiseEquivalence<S>(this); } /** * Returns a predicate that evaluates to true if and only if the input is * equivalent to {@code target} according to this equivalence relation. * * @since 10.0 */ @Beta public final Predicate<T> equivalentTo(@Nullable T target) { return new EquivalentToPredicate<T>(this, target); } private static final class EquivalentToPredicate<T> implements Predicate<T>, Serializable { private final Equivalence<T> equivalence; @Nullable private final T target; EquivalentToPredicate(Equivalence<T> equivalence, @Nullable T target) { this.equivalence = checkNotNull(equivalence); this.target = target; } @Override public boolean apply(@Nullable T input) { return equivalence.equivalent(input, target); } @Override public boolean equals(@Nullable Object obj) { if (this == obj) { return true; } if (obj instanceof EquivalentToPredicate) { EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj; return equivalence.equals(that.equivalence) && Objects.equal(target, that.target); } return false; } @Override public int hashCode() { return Objects.hashCode(equivalence, target); } @Override public String toString() { return equivalence + ".equivalentTo(" + target + ")"; } private static final long serialVersionUID = 0; } /** * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}. * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns * {@code 0} if passed a null value. * * @since 13.0 * @since 8.0 (in Equivalences with null-friendly behavior) * @since 4.0 (in Equivalences) */ public static Equivalence<Object> equals() { return Equals.INSTANCE; } /** * Returns an equivalence that uses {@code ==} to compare values and {@link * System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent} * returns {@code true} if {@code a == b}, including in the case that a and b are both null. * * @since 13.0 * @since 4.0 (in Equivalences) */ public static Equivalence<Object> identity() { return Identity.INSTANCE; } static final class Equals extends Equivalence<Object> implements Serializable { static final Equals INSTANCE = new Equals(); @Override protected boolean doEquivalent(Object a, Object b) { return a.equals(b); } @Override public int doHash(Object o) { return o.hashCode(); } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } static final class Identity extends Equivalence<Object> implements Serializable { static final Identity INSTANCE = new Identity(); @Override protected boolean doEquivalent(Object a, Object b) { return false; } @Override protected int doHash(Object o) { return System.identityHashCode(o); } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Equivalence.java
Java
asf20
12,567
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /** * Basic utility libraries and interfaces. * * <p>This package is a part of the open-source * <a href="http://guava-libraries.googlecode.com">Guava libraries</a>. * * <h2>Contents</h2> * * <h3>String-related utilities</h3> * * <ul> * <li>{@link com.google.common.base.Ascii} * <li>{@link com.google.common.base.CaseFormat} * <li>{@link com.google.common.base.CharMatcher} * <li>{@link com.google.common.base.Charsets} * <li>{@link com.google.common.base.Joiner} * <li>{@link com.google.common.base.Splitter} * <li>{@link com.google.common.base.Strings} * </ul> * * <h3>Function types</h3> * * <ul> * <li>{@link com.google.common.base.Function}, * {@link com.google.common.base.Functions} * <li>{@link com.google.common.base.Predicate}, * {@link com.google.common.base.Predicates} * <li>{@link com.google.common.base.Equivalence} * <li>{@link com.google.common.base.Converter} * <li>{@link com.google.common.base.Supplier}, * {@link com.google.common.base.Suppliers} * </ul> * * <h3>Other</h3> * * <ul> * <li>{@link com.google.common.base.Defaults} * <li>{@link com.google.common.base.Enums} * <li>{@link com.google.common.base.Objects} * <li>{@link com.google.common.base.Optional} * <li>{@link com.google.common.base.Preconditions} * <li>{@link com.google.common.base.Stopwatch} * <li>{@link com.google.common.base.Throwables} * </ul> * */ @ParametersAreNonnullByDefault package com.google.common.base; import javax.annotation.ParametersAreNonnullByDefault;
zzhhhhh-aw4rwer
guava/src/com/google/common/base/package-info.java
Java
asf20
2,122
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.util.Arrays; import java.util.BitSet; import javax.annotation.CheckReturnValue; /** * Determines a true or false value for any Java {@code char} value, just as {@link Predicate} does * for any {@link Object}. Also offers basic text processing methods based on this function. * Implementations are strongly encouraged to be side-effect-free and immutable. * * <p>Throughout the documentation of this class, the phrase "matching character" is used to mean * "any character {@code c} for which {@code this.matches(c)} returns {@code true}". * * <p><b>Note:</b> This class deals only with {@code char} values; it does not understand * supplementary Unicode code points in the range {@code 0x10000} to {@code 0x10FFFF}. Such logical * characters are encoded into a {@code String} using surrogate pairs, and a {@code CharMatcher} * treats these just as two separate characters. * * <p>Example usages: <pre> * String trimmed = {@link #WHITESPACE WHITESPACE}.{@link #trimFrom trimFrom}(userInput); * if ({@link #ASCII ASCII}.{@link #matchesAllOf matchesAllOf}(s)) { ... }</pre> * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/StringsExplained#CharMatcher"> * {@code CharMatcher}</a>. * * @author Kevin Bourrillion * @since 1.0 */ @Beta // Possibly change from chars to code points; decide constants vs. methods @GwtCompatible(emulated = true) public abstract class CharMatcher implements Predicate<Character> { // Constants /** * Determines whether a character is a breaking whitespace (that is, a whitespace which can be * interpreted as a break between words for formatting purposes). See {@link #WHITESPACE} for a * discussion of that term. * * @since 2.0 */ public static final CharMatcher BREAKING_WHITESPACE = new CharMatcher() { @Override public boolean matches(char c) { switch (c) { case '\t': case '\n': case '\013': case '\f': case '\r': case ' ': case '\u0085': case '\u1680': case '\u2028': case '\u2029': case '\u205f': case '\u3000': return true; case '\u2007': return false; default: return c >= '\u2000' && c <= '\u200a'; } } @Override public String toString() { return "CharMatcher.BREAKING_WHITESPACE"; } }; /** * Determines whether a character is ASCII, meaning that its code point is less than 128. */ public static final CharMatcher ASCII = inRange('\0', '\u007f', "CharMatcher.ASCII"); private static class RangesMatcher extends CharMatcher { private final char[] rangeStarts; private final char[] rangeEnds; RangesMatcher(String description, char[] rangeStarts, char[] rangeEnds) { super(description); this.rangeStarts = rangeStarts; this.rangeEnds = rangeEnds; checkArgument(rangeStarts.length == rangeEnds.length); for (int i = 0; i < rangeStarts.length; i++) { checkArgument(rangeStarts[i] <= rangeEnds[i]); if (i + 1 < rangeStarts.length) { checkArgument(rangeEnds[i] < rangeStarts[i + 1]); } } } @Override public boolean matches(char c) { int index = Arrays.binarySearch(rangeStarts, c); if (index >= 0) { return true; } else { index = ~index - 1; return index >= 0 && c <= rangeEnds[index]; } } } // Must be in ascending order. private static final String ZEROES = "0\u0660\u06f0\u07c0\u0966\u09e6\u0a66\u0ae6\u0b66\u0be6" + "\u0c66\u0ce6\u0d66\u0e50\u0ed0\u0f20\u1040\u1090\u17e0\u1810\u1946\u19d0\u1b50\u1bb0" + "\u1c40\u1c50\ua620\ua8d0\ua900\uaa50\uff10"; private static final String NINES; static { StringBuilder builder = new StringBuilder(ZEROES.length()); for (int i = 0; i < ZEROES.length(); i++) { builder.append((char) (ZEROES.charAt(i) + 9)); } NINES = builder.toString(); } /** * Determines whether a character is a digit according to * <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bdigit%7D">Unicode</a>. * If you only care to match ASCII digits, you can use {@code inRange('0', '9')}. */ public static final CharMatcher DIGIT = new RangesMatcher( "CharMatcher.DIGIT", ZEROES.toCharArray(), NINES.toCharArray()); /** * Determines whether a character is a digit according to {@linkplain Character#isDigit(char) * Java's definition}. If you only care to match ASCII digits, you can use {@code * inRange('0', '9')}. */ public static final CharMatcher JAVA_DIGIT = new CharMatcher("CharMatcher.JAVA_DIGIT") { @Override public boolean matches(char c) { return Character.isDigit(c); } }; /** * Determines whether a character is a letter according to {@linkplain Character#isLetter(char) * Java's definition}. If you only care to match letters of the Latin alphabet, you can use {@code * inRange('a', 'z').or(inRange('A', 'Z'))}. */ public static final CharMatcher JAVA_LETTER = new CharMatcher("CharMatcher.JAVA_LETTER") { @Override public boolean matches(char c) { return Character.isLetter(c); } }; /** * Determines whether a character is a letter or digit according to {@linkplain * Character#isLetterOrDigit(char) Java's definition}. */ public static final CharMatcher JAVA_LETTER_OR_DIGIT = new CharMatcher("CharMatcher.JAVA_LETTER_OR_DIGIT") { @Override public boolean matches(char c) { return Character.isLetterOrDigit(c); } }; /** * Determines whether a character is upper case according to {@linkplain * Character#isUpperCase(char) Java's definition}. */ public static final CharMatcher JAVA_UPPER_CASE = new CharMatcher("CharMatcher.JAVA_UPPER_CASE") { @Override public boolean matches(char c) { return Character.isUpperCase(c); } }; /** * Determines whether a character is lower case according to {@linkplain * Character#isLowerCase(char) Java's definition}. */ public static final CharMatcher JAVA_LOWER_CASE = new CharMatcher("CharMatcher.JAVA_LOWER_CASE") { @Override public boolean matches(char c) { return Character.isLowerCase(c); } }; /** * Determines whether a character is an ISO control character as specified by {@link * Character#isISOControl(char)}. */ public static final CharMatcher JAVA_ISO_CONTROL = inRange('\u0000', '\u001f') .or(inRange('\u007f', '\u009f')) .withToString("CharMatcher.JAVA_ISO_CONTROL"); /** * Determines whether a character is invisible; that is, if its Unicode category is any of * SPACE_SEPARATOR, LINE_SEPARATOR, PARAGRAPH_SEPARATOR, CONTROL, FORMAT, SURROGATE, and * PRIVATE_USE according to ICU4J. */ public static final CharMatcher INVISIBLE = new RangesMatcher("CharMatcher.INVISIBLE", ( "\u0000\u007f\u00ad\u0600\u061c\u06dd\u070f\u1680\u180e\u2000\u2028\u205f\u2066\u2067\u2068" + "\u2069\u206a\u3000\ud800\ufeff\ufff9\ufffa").toCharArray(), ( "\u0020\u00a0\u00ad\u0604\u061c\u06dd\u070f\u1680\u180e\u200f\u202f\u2064\u2066\u2067\u2068" + "\u2069\u206f\u3000\uf8ff\ufeff\ufff9\ufffb").toCharArray()); private static String showCharacter(char c) { String hex = "0123456789ABCDEF"; char[] tmp = {'\\', 'u', '\0', '\0', '\0', '\0'}; for (int i = 0; i < 4; i++) { tmp[5 - i] = hex.charAt(c & 0xF); c >>= 4; } return String.copyValueOf(tmp); } /** * Determines whether a character is single-width (not double-width). When in doubt, this matcher * errs on the side of returning {@code false} (that is, it tends to assume a character is * double-width). * * <p><b>Note:</b> as the reference file evolves, we will modify this constant to keep it up to * date. */ public static final CharMatcher SINGLE_WIDTH = new RangesMatcher("CharMatcher.SINGLE_WIDTH", "\u0000\u05be\u05d0\u05f3\u0600\u0750\u0e00\u1e00\u2100\ufb50\ufe70\uff61".toCharArray(), "\u04f9\u05be\u05ea\u05f4\u06ff\u077f\u0e7f\u20af\u213a\ufdff\ufeff\uffdc".toCharArray()); /** Matches any character. */ public static final CharMatcher ANY = new FastMatcher("CharMatcher.ANY") { @Override public boolean matches(char c) { return true; } @Override public int indexIn(CharSequence sequence) { return (sequence.length() == 0) ? -1 : 0; } @Override public int indexIn(CharSequence sequence, int start) { int length = sequence.length(); Preconditions.checkPositionIndex(start, length); return (start == length) ? -1 : start; } @Override public int lastIndexIn(CharSequence sequence) { return sequence.length() - 1; } @Override public boolean matchesAllOf(CharSequence sequence) { checkNotNull(sequence); return true; } @Override public boolean matchesNoneOf(CharSequence sequence) { return sequence.length() == 0; } @Override public String removeFrom(CharSequence sequence) { checkNotNull(sequence); return ""; } @Override public String replaceFrom(CharSequence sequence, char replacement) { char[] array = new char[sequence.length()]; Arrays.fill(array, replacement); return new String(array); } @Override public String replaceFrom(CharSequence sequence, CharSequence replacement) { StringBuilder retval = new StringBuilder(sequence.length() * replacement.length()); for (int i = 0; i < sequence.length(); i++) { retval.append(replacement); } return retval.toString(); } @Override public String collapseFrom(CharSequence sequence, char replacement) { return (sequence.length() == 0) ? "" : String.valueOf(replacement); } @Override public String trimFrom(CharSequence sequence) { checkNotNull(sequence); return ""; } @Override public int countIn(CharSequence sequence) { return sequence.length(); } @Override public CharMatcher and(CharMatcher other) { return checkNotNull(other); } @Override public CharMatcher or(CharMatcher other) { checkNotNull(other); return this; } @Override public CharMatcher negate() { return NONE; } }; /** Matches no characters. */ public static final CharMatcher NONE = new FastMatcher("CharMatcher.NONE") { @Override public boolean matches(char c) { return false; } @Override public int indexIn(CharSequence sequence) { checkNotNull(sequence); return -1; } @Override public int indexIn(CharSequence sequence, int start) { int length = sequence.length(); Preconditions.checkPositionIndex(start, length); return -1; } @Override public int lastIndexIn(CharSequence sequence) { checkNotNull(sequence); return -1; } @Override public boolean matchesAllOf(CharSequence sequence) { return sequence.length() == 0; } @Override public boolean matchesNoneOf(CharSequence sequence) { checkNotNull(sequence); return true; } @Override public String removeFrom(CharSequence sequence) { return sequence.toString(); } @Override public String replaceFrom(CharSequence sequence, char replacement) { return sequence.toString(); } @Override public String replaceFrom(CharSequence sequence, CharSequence replacement) { checkNotNull(replacement); return sequence.toString(); } @Override public String collapseFrom(CharSequence sequence, char replacement) { return sequence.toString(); } @Override public String trimFrom(CharSequence sequence) { return sequence.toString(); } @Override public String trimLeadingFrom(CharSequence sequence) { return sequence.toString(); } @Override public String trimTrailingFrom(CharSequence sequence) { return sequence.toString(); } @Override public int countIn(CharSequence sequence) { checkNotNull(sequence); return 0; } @Override public CharMatcher and(CharMatcher other) { checkNotNull(other); return this; } @Override public CharMatcher or(CharMatcher other) { return checkNotNull(other); } @Override public CharMatcher negate() { return ANY; } }; // Static factories /** * Returns a {@code char} matcher that matches only one specified character. */ public static CharMatcher is(final char match) { String description = "CharMatcher.is('" + showCharacter(match) + "')"; return new FastMatcher(description) { @Override public boolean matches(char c) { return c == match; } @Override public String replaceFrom(CharSequence sequence, char replacement) { return sequence.toString().replace(match, replacement); } @Override public CharMatcher and(CharMatcher other) { return other.matches(match) ? this : NONE; } @Override public CharMatcher or(CharMatcher other) { return other.matches(match) ? other : super.or(other); } @Override public CharMatcher negate() { return isNot(match); } @GwtIncompatible("java.util.BitSet") @Override void setBits(BitSet table) { table.set(match); } }; } /** * Returns a {@code char} matcher that matches any character except the one specified. * * <p>To negate another {@code CharMatcher}, use {@link #negate()}. */ public static CharMatcher isNot(final char match) { String description = "CharMatcher.isNot('" + showCharacter(match) + "')"; return new FastMatcher(description) { @Override public boolean matches(char c) { return c != match; } @Override public CharMatcher and(CharMatcher other) { return other.matches(match) ? super.and(other) : other; } @Override public CharMatcher or(CharMatcher other) { return other.matches(match) ? ANY : this; } @GwtIncompatible("java.util.BitSet") @Override void setBits(BitSet table) { table.set(0, match); table.set(match + 1, Character.MAX_VALUE + 1); } @Override public CharMatcher negate() { return is(match); } }; } /** * Returns a {@code char} matcher that matches any character present in the given character * sequence. */ public static CharMatcher anyOf(final CharSequence sequence) { switch (sequence.length()) { case 0: return NONE; case 1: return is(sequence.charAt(0)); case 2: return isEither(sequence.charAt(0), sequence.charAt(1)); default: // continue below to handle the general case } // TODO(user): is it potentially worth just going ahead and building a precomputed matcher? final char[] chars = sequence.toString().toCharArray(); Arrays.sort(chars); StringBuilder description = new StringBuilder("CharMatcher.anyOf(\""); for (char c : chars) { description.append(showCharacter(c)); } description.append("\")"); return new CharMatcher(description.toString()) { @Override public boolean matches(char c) { return Arrays.binarySearch(chars, c) >= 0; } @Override @GwtIncompatible("java.util.BitSet") void setBits(BitSet table) { for (char c : chars) { table.set(c); } } }; } private static CharMatcher isEither( final char match1, final char match2) { String description = "CharMatcher.anyOf(\"" + showCharacter(match1) + showCharacter(match2) + "\")"; return new FastMatcher(description) { @Override public boolean matches(char c) { return c == match1 || c == match2; } @GwtIncompatible("java.util.BitSet") @Override void setBits(BitSet table) { table.set(match1); table.set(match2); } }; } /** * Returns a {@code char} matcher that matches any character not present in the given character * sequence. */ public static CharMatcher noneOf(CharSequence sequence) { return anyOf(sequence).negate(); } /** * Returns a {@code char} matcher that matches any character in a given range (both endpoints are * inclusive). For example, to match any lowercase letter of the English alphabet, use {@code * CharMatcher.inRange('a', 'z')}. * * @throws IllegalArgumentException if {@code endInclusive < startInclusive} */ public static CharMatcher inRange(final char startInclusive, final char endInclusive) { checkArgument(endInclusive >= startInclusive); String description = "CharMatcher.inRange('" + showCharacter(startInclusive) + "', '" + showCharacter(endInclusive) + "')"; return inRange(startInclusive, endInclusive, description); } static CharMatcher inRange(final char startInclusive, final char endInclusive, String description) { return new FastMatcher(description) { @Override public boolean matches(char c) { return startInclusive <= c && c <= endInclusive; } @GwtIncompatible("java.util.BitSet") @Override void setBits(BitSet table) { table.set(startInclusive, endInclusive + 1); } }; } /** * Returns a matcher with identical behavior to the given {@link Character}-based predicate, but * which operates on primitive {@code char} instances instead. */ public static CharMatcher forPredicate(final Predicate<? super Character> predicate) { checkNotNull(predicate); if (predicate instanceof CharMatcher) { return (CharMatcher) predicate; } String description = "CharMatcher.forPredicate(" + predicate + ")"; return new CharMatcher(description) { @Override public boolean matches(char c) { return predicate.apply(c); } @Override public boolean apply(Character character) { return predicate.apply(checkNotNull(character)); } }; } // State final String description; // Constructors /** * Sets the {@code toString()} from the given description. */ CharMatcher(String description) { this.description = description; } /** * Constructor for use by subclasses. When subclassing, you may want to override * {@code toString()} to provide a useful description. */ protected CharMatcher() { description = super.toString(); } // Abstract methods /** Determines a true or false value for the given character. */ public abstract boolean matches(char c); // Non-static factories /** * Returns a matcher that matches any character not matched by this matcher. */ public CharMatcher negate() { return new NegatedMatcher(this); } private static class NegatedMatcher extends CharMatcher { final CharMatcher original; NegatedMatcher(String toString, CharMatcher original) { super(toString); this.original = original; } NegatedMatcher(CharMatcher original) { this(original + ".negate()", original); } @Override public boolean matches(char c) { return !original.matches(c); } @Override public boolean matchesAllOf(CharSequence sequence) { return original.matchesNoneOf(sequence); } @Override public boolean matchesNoneOf(CharSequence sequence) { return original.matchesAllOf(sequence); } @Override public int countIn(CharSequence sequence) { return sequence.length() - original.countIn(sequence); } @GwtIncompatible("java.util.BitSet") @Override void setBits(BitSet table) { BitSet tmp = new BitSet(); original.setBits(tmp); tmp.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1); table.or(tmp); } @Override public CharMatcher negate() { return original; } @Override CharMatcher withToString(String description) { return new NegatedMatcher(description, original); } } /** * Returns a matcher that matches any character matched by both this matcher and {@code other}. */ public CharMatcher and(CharMatcher other) { return new And(this, checkNotNull(other)); } private static class And extends CharMatcher { final CharMatcher first; final CharMatcher second; And(CharMatcher a, CharMatcher b) { this(a, b, "CharMatcher.and(" + a + ", " + b + ")"); } And(CharMatcher a, CharMatcher b, String description) { super(description); first = checkNotNull(a); second = checkNotNull(b); } @Override public boolean matches(char c) { return first.matches(c) && second.matches(c); } @GwtIncompatible("java.util.BitSet") @Override void setBits(BitSet table) { BitSet tmp1 = new BitSet(); first.setBits(tmp1); BitSet tmp2 = new BitSet(); second.setBits(tmp2); tmp1.and(tmp2); table.or(tmp1); } @Override CharMatcher withToString(String description) { return new And(first, second, description); } } /** * Returns a matcher that matches any character matched by either this matcher or {@code other}. */ public CharMatcher or(CharMatcher other) { return new Or(this, checkNotNull(other)); } private static class Or extends CharMatcher { final CharMatcher first; final CharMatcher second; Or(CharMatcher a, CharMatcher b, String description) { super(description); first = checkNotNull(a); second = checkNotNull(b); } Or(CharMatcher a, CharMatcher b) { this(a, b, "CharMatcher.or(" + a + ", " + b + ")"); } @GwtIncompatible("java.util.BitSet") @Override void setBits(BitSet table) { first.setBits(table); second.setBits(table); } @Override public boolean matches(char c) { return first.matches(c) || second.matches(c); } @Override CharMatcher withToString(String description) { return new Or(first, second, description); } } /** * Returns a {@code char} matcher functionally equivalent to this one, but which may be faster to * query than the original; your mileage may vary. Precomputation takes time and is likely to be * worthwhile only if the precomputed matcher is queried many thousands of times. * * <p>This method has no effect (returns {@code this}) when called in GWT: it's unclear whether a * precomputed matcher is faster, but it certainly consumes more memory, which doesn't seem like a * worthwhile tradeoff in a browser. */ public CharMatcher precomputed() { return Platform.precomputeCharMatcher(this); } /** * Subclasses should provide a new CharMatcher with the same characteristics as {@code this}, * but with their {@code toString} method overridden with the new description. * * <p>This is unsupported by default. */ CharMatcher withToString(String description) { throw new UnsupportedOperationException(); } private static final int DISTINCT_CHARS = Character.MAX_VALUE - Character.MIN_VALUE + 1; /** * This is the actual implementation of {@link #precomputed}, but we bounce calls through a * method on {@link Platform} so that we can have different behavior in GWT. * * <p>This implementation tries to be smart in a number of ways. It recognizes cases where * the negation is cheaper to precompute than the matcher itself; it tries to build small * hash tables for matchers that only match a few characters, and so on. In the worst-case * scenario, it constructs an eight-kilobyte bit array and queries that. * In many situations this produces a matcher which is faster to query than the original. */ @GwtIncompatible("java.util.BitSet") CharMatcher precomputedInternal() { final BitSet table = new BitSet(); setBits(table); int totalCharacters = table.cardinality(); if (totalCharacters * 2 <= DISTINCT_CHARS) { return precomputedPositive(totalCharacters, table, description); } else { // TODO(user): is it worth it to worry about the last character of large matchers? table.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1); int negatedCharacters = DISTINCT_CHARS - totalCharacters; String suffix = ".negate()"; String negatedDescription = description.endsWith(suffix) ? description.substring(0, description.length() - suffix.length()) : description + suffix; return new NegatedFastMatcher(toString(), precomputedPositive(negatedCharacters, table, negatedDescription)); } } /** * A matcher for which precomputation will not yield any significant benefit. */ abstract static class FastMatcher extends CharMatcher { FastMatcher() { super(); } FastMatcher(String description) { super(description); } @Override public final CharMatcher precomputed() { return this; } @Override public CharMatcher negate() { return new NegatedFastMatcher(this); } } static final class NegatedFastMatcher extends NegatedMatcher { NegatedFastMatcher(CharMatcher original) { super(original); } NegatedFastMatcher(String toString, CharMatcher original) { super(toString, original); } @Override public final CharMatcher precomputed() { return this; } @Override CharMatcher withToString(String description) { return new NegatedFastMatcher(description, original); } } /** * Helper method for {@link #precomputedInternal} that doesn't test if the negation is cheaper. */ @GwtIncompatible("java.util.BitSet") private static CharMatcher precomputedPositive( int totalCharacters, BitSet table, String description) { switch (totalCharacters) { case 0: return NONE; case 1: return is((char) table.nextSetBit(0)); case 2: char c1 = (char) table.nextSetBit(0); char c2 = (char) table.nextSetBit(c1 + 1); return isEither(c1, c2); default: return isSmall(totalCharacters, table.length()) ? SmallCharMatcher.from(table, description) : new BitSetMatcher(table, description); } } @GwtIncompatible("SmallCharMatcher") private static boolean isSmall(int totalCharacters, int tableLength) { return totalCharacters <= SmallCharMatcher.MAX_SIZE && tableLength > (totalCharacters * 4 * Character.SIZE); // err on the side of BitSetMatcher } @GwtIncompatible("java.util.BitSet") private static class BitSetMatcher extends FastMatcher { private final BitSet table; private BitSetMatcher(BitSet table, String description) { super(description); if (table.length() + Long.SIZE < table.size()) { table = (BitSet) table.clone(); // If only we could actually call BitSet.trimToSize() ourselves... } this.table = table; } @Override public boolean matches(char c) { return table.get(c); } @Override void setBits(BitSet bitSet) { bitSet.or(table); } } /** * Sets bits in {@code table} matched by this matcher. */ @GwtIncompatible("java.util.BitSet") void setBits(BitSet table) { for (int c = Character.MAX_VALUE; c >= Character.MIN_VALUE; c--) { if (matches((char) c)) { table.set(c); } } } // Text processing routines /** * Returns {@code true} if a character sequence contains at least one matching character. * Equivalent to {@code !matchesNoneOf(sequence)}. * * <p>The default implementation iterates over the sequence, invoking {@link #matches} for each * character, until this returns {@code true} or the end is reached. * * @param sequence the character sequence to examine, possibly empty * @return {@code true} if this matcher matches at least one character in the sequence * @since 8.0 */ public boolean matchesAnyOf(CharSequence sequence) { return !matchesNoneOf(sequence); } /** * Returns {@code true} if a character sequence contains only matching characters. * * <p>The default implementation iterates over the sequence, invoking {@link #matches} for each * character, until this returns {@code false} or the end is reached. * * @param sequence the character sequence to examine, possibly empty * @return {@code true} if this matcher matches every character in the sequence, including when * the sequence is empty */ public boolean matchesAllOf(CharSequence sequence) { for (int i = sequence.length() - 1; i >= 0; i--) { if (!matches(sequence.charAt(i))) { return false; } } return true; } /** * Returns {@code true} if a character sequence contains no matching characters. Equivalent to * {@code !matchesAnyOf(sequence)}. * * <p>The default implementation iterates over the sequence, invoking {@link #matches} for each * character, until this returns {@code false} or the end is reached. * * @param sequence the character sequence to examine, possibly empty * @return {@code true} if this matcher matches every character in the sequence, including when * the sequence is empty */ public boolean matchesNoneOf(CharSequence sequence) { return indexIn(sequence) == -1; } /** * Returns the index of the first matching character in a character sequence, or {@code -1} if no * matching character is present. * * <p>The default implementation iterates over the sequence in forward order calling {@link * #matches} for each character. * * @param sequence the character sequence to examine from the beginning * @return an index, or {@code -1} if no character matches */ public int indexIn(CharSequence sequence) { int length = sequence.length(); for (int i = 0; i < length; i++) { if (matches(sequence.charAt(i))) { return i; } } return -1; } /** * Returns the index of the first matching character in a character sequence, starting from a * given position, or {@code -1} if no character matches after that position. * * <p>The default implementation iterates over the sequence in forward order, beginning at {@code * start}, calling {@link #matches} for each character. * * @param sequence the character sequence to examine * @param start the first index to examine; must be nonnegative and no greater than {@code * sequence.length()} * @return the index of the first matching character, guaranteed to be no less than {@code start}, * or {@code -1} if no character matches * @throws IndexOutOfBoundsException if start is negative or greater than {@code * sequence.length()} */ public int indexIn(CharSequence sequence, int start) { int length = sequence.length(); Preconditions.checkPositionIndex(start, length); for (int i = start; i < length; i++) { if (matches(sequence.charAt(i))) { return i; } } return -1; } /** * Returns the index of the last matching character in a character sequence, or {@code -1} if no * matching character is present. * * <p>The default implementation iterates over the sequence in reverse order calling {@link * #matches} for each character. * * @param sequence the character sequence to examine from the end * @return an index, or {@code -1} if no character matches */ public int lastIndexIn(CharSequence sequence) { for (int i = sequence.length() - 1; i >= 0; i--) { if (matches(sequence.charAt(i))) { return i; } } return -1; } /** * Returns the number of matching characters found in a character sequence. */ public int countIn(CharSequence sequence) { int count = 0; for (int i = 0; i < sequence.length(); i++) { if (matches(sequence.charAt(i))) { count++; } } return count; } /** * Returns a string containing all non-matching characters of a character sequence, in order. For * example: <pre> {@code * * CharMatcher.is('a').removeFrom("bazaar")}</pre> * * ... returns {@code "bzr"}. */ @CheckReturnValue public String removeFrom(CharSequence sequence) { String string = sequence.toString(); int pos = indexIn(string); if (pos == -1) { return string; } char[] chars = string.toCharArray(); int spread = 1; // This unusual loop comes from extensive benchmarking OUT: while (true) { pos++; while (true) { if (pos == chars.length) { break OUT; } if (matches(chars[pos])) { break; } chars[pos - spread] = chars[pos]; pos++; } spread++; } return new String(chars, 0, pos - spread); } /** * Returns a string containing all matching characters of a character sequence, in order. For * example: <pre> {@code * * CharMatcher.is('a').retainFrom("bazaar")}</pre> * * ... returns {@code "aaa"}. */ @CheckReturnValue public String retainFrom(CharSequence sequence) { return negate().removeFrom(sequence); } /** * Returns a string copy of the input character sequence, with each character that matches this * matcher replaced by a given replacement character. For example: <pre> {@code * * CharMatcher.is('a').replaceFrom("radar", 'o')}</pre> * * ... returns {@code "rodor"}. * * <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching * character, then iterates the remainder of the sequence calling {@link #matches(char)} for each * character. * * @param sequence the character sequence to replace matching characters in * @param replacement the character to append to the result string in place of each matching * character in {@code sequence} * @return the new string */ @CheckReturnValue public String replaceFrom(CharSequence sequence, char replacement) { String string = sequence.toString(); int pos = indexIn(string); if (pos == -1) { return string; } char[] chars = string.toCharArray(); chars[pos] = replacement; for (int i = pos + 1; i < chars.length; i++) { if (matches(chars[i])) { chars[i] = replacement; } } return new String(chars); } /** * Returns a string copy of the input character sequence, with each character that matches this * matcher replaced by a given replacement sequence. For example: <pre> {@code * * CharMatcher.is('a').replaceFrom("yaha", "oo")}</pre> * * ... returns {@code "yoohoo"}. * * <p><b>Note:</b> If the replacement is a fixed string with only one character, you are better * off calling {@link #replaceFrom(CharSequence, char)} directly. * * @param sequence the character sequence to replace matching characters in * @param replacement the characters to append to the result string in place of each matching * character in {@code sequence} * @return the new string */ @CheckReturnValue public String replaceFrom(CharSequence sequence, CharSequence replacement) { int replacementLen = replacement.length(); if (replacementLen == 0) { return removeFrom(sequence); } if (replacementLen == 1) { return replaceFrom(sequence, replacement.charAt(0)); } String string = sequence.toString(); int pos = indexIn(string); if (pos == -1) { return string; } int len = string.length(); StringBuilder buf = new StringBuilder((len * 3 / 2) + 16); int oldpos = 0; do { buf.append(string, oldpos, pos); buf.append(replacement); oldpos = pos + 1; pos = indexIn(string, oldpos); } while (pos != -1); buf.append(string, oldpos, len); return buf.toString(); } /** * Returns a substring of the input character sequence that omits all characters this matcher * matches from the beginning and from the end of the string. For example: <pre> {@code * * CharMatcher.anyOf("ab").trimFrom("abacatbab")}</pre> * * ... returns {@code "cat"}. * * <p>Note that: <pre> {@code * * CharMatcher.inRange('\0', ' ').trimFrom(str)}</pre> * * ... is equivalent to {@link String#trim()}. */ @CheckReturnValue public String trimFrom(CharSequence sequence) { int len = sequence.length(); int first; int last; for (first = 0; first < len; first++) { if (!matches(sequence.charAt(first))) { break; } } for (last = len - 1; last > first; last--) { if (!matches(sequence.charAt(last))) { break; } } return sequence.subSequence(first, last + 1).toString(); } /** * Returns a substring of the input character sequence that omits all characters this matcher * matches from the beginning of the string. For example: <pre> {@code * * CharMatcher.anyOf("ab").trimLeadingFrom("abacatbab")}</pre> * * ... returns {@code "catbab"}. */ @CheckReturnValue public String trimLeadingFrom(CharSequence sequence) { int len = sequence.length(); for (int first = 0; first < len; first++) { if (!matches(sequence.charAt(first))) { return sequence.subSequence(first, len).toString(); } } return ""; } /** * Returns a substring of the input character sequence that omits all characters this matcher * matches from the end of the string. For example: <pre> {@code * * CharMatcher.anyOf("ab").trimTrailingFrom("abacatbab")}</pre> * * ... returns {@code "abacat"}. */ @CheckReturnValue public String trimTrailingFrom(CharSequence sequence) { int len = sequence.length(); for (int last = len - 1; last >= 0; last--) { if (!matches(sequence.charAt(last))) { return sequence.subSequence(0, last + 1).toString(); } } return ""; } /** * Returns a string copy of the input character sequence, with each group of consecutive * characters that match this matcher replaced by a single replacement character. For example: * <pre> {@code * * CharMatcher.anyOf("eko").collapseFrom("bookkeeper", '-')}</pre> * * ... returns {@code "b-p-r"}. * * <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching * character, then iterates the remainder of the sequence calling {@link #matches(char)} for each * character. * * @param sequence the character sequence to replace matching groups of characters in * @param replacement the character to append to the result string in place of each group of * matching characters in {@code sequence} * @return the new string */ @CheckReturnValue public String collapseFrom(CharSequence sequence, char replacement) { // This implementation avoids unnecessary allocation. int len = sequence.length(); for (int i = 0; i < len; i++) { char c = sequence.charAt(i); if (matches(c)) { if (c == replacement && (i == len - 1 || !matches(sequence.charAt(i + 1)))) { // a no-op replacement i++; } else { StringBuilder builder = new StringBuilder(len) .append(sequence.subSequence(0, i)) .append(replacement); return finishCollapseFrom(sequence, i + 1, len, replacement, builder, true); } } } // no replacement needed return sequence.toString(); } /** * Collapses groups of matching characters exactly as {@link #collapseFrom} does, except that * groups of matching characters at the start or end of the sequence are removed without * replacement. */ @CheckReturnValue public String trimAndCollapseFrom(CharSequence sequence, char replacement) { // This implementation avoids unnecessary allocation. int len = sequence.length(); int first; int last; for (first = 0; first < len && matches(sequence.charAt(first)); first++) {} for (last = len - 1; last > first && matches(sequence.charAt(last)); last--) {} return (first == 0 && last == len - 1) ? collapseFrom(sequence, replacement) : finishCollapseFrom( sequence, first, last + 1, replacement, new StringBuilder(last + 1 - first), false); } private String finishCollapseFrom( CharSequence sequence, int start, int end, char replacement, StringBuilder builder, boolean inMatchingGroup) { for (int i = start; i < end; i++) { char c = sequence.charAt(i); if (matches(c)) { if (!inMatchingGroup) { builder.append(replacement); inMatchingGroup = true; } } else { builder.append(c); inMatchingGroup = false; } } return builder.toString(); } /** * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #matches} * instead. */ @Deprecated @Override public boolean apply(Character character) { return matches(character); } /** * Returns a string representation of this {@code CharMatcher}, such as * {@code CharMatcher.or(WHITESPACE, JAVA_DIGIT)}. */ @Override public String toString() { return description; } static final String WHITESPACE_TABLE = "" + "\u2002\u3000\r\u0085\u200A\u2005\u2000\u3000" + "\u2029\u000B\u3000\u2008\u2003\u205F\u3000\u1680" + "\u0009\u0020\u2006\u2001\u202F\u00A0\u000C\u2009" + "\u3000\u2004\u3000\u3000\u2028\n\u2007\u3000"; static final int WHITESPACE_MULTIPLIER = 1682554634; static final int WHITESPACE_SHIFT = Integer.numberOfLeadingZeros(WHITESPACE_TABLE.length() - 1); /** * Determines whether a character is whitespace according to the latest Unicode standard, as * illustrated * <a href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bwhitespace%7D">here</a>. * This is not the same definition used by other Java APIs. (See a * <a href="http://spreadsheets.google.com/pub?key=pd8dAQyHbdewRsnE5x5GzKQ">comparison of several * definitions of "whitespace"</a>.) * * <p><b>Note:</b> as the Unicode definition evolves, we will modify this constant to keep it up * to date. */ public static final CharMatcher WHITESPACE = new FastMatcher("WHITESPACE") { @Override public boolean matches(char c) { return WHITESPACE_TABLE.charAt((WHITESPACE_MULTIPLIER * c) >>> WHITESPACE_SHIFT) == c; } @GwtIncompatible("java.util.BitSet") @Override void setBits(BitSet table) { for (int i = 0; i < WHITESPACE_TABLE.length(); i++) { table.set(WHITESPACE_TABLE.charAt(i)); } } }; }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/CharMatcher.java
Java
asf20
44,360
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; import javax.annotation.CheckReturnValue; /** * Extracts non-overlapping substrings from an input string, typically by * recognizing appearances of a <i>separator</i> sequence. This separator can be * specified as a single {@linkplain #on(char) character}, fixed {@linkplain * #on(String) string}, {@linkplain #onPattern regular expression} or {@link * #on(CharMatcher) CharMatcher} instance. Or, instead of using a separator at * all, a splitter can extract adjacent substrings of a given {@linkplain * #fixedLength fixed length}. * * <p>For example, this expression: <pre> {@code * * Splitter.on(',').split("foo,bar,qux")}</pre> * * ... produces an {@code Iterable} containing {@code "foo"}, {@code "bar"} and * {@code "qux"}, in that order. * * <p>By default, {@code Splitter}'s behavior is simplistic and unassuming. The * following expression: <pre> {@code * * Splitter.on(',').split(" foo,,, bar ,")}</pre> * * ... yields the substrings {@code [" foo", "", "", " bar ", ""]}. If this * is not the desired behavior, use configuration methods to obtain a <i>new</i> * splitter instance with modified behavior: <pre> {@code * * private static final Splitter MY_SPLITTER = Splitter.on(',') * .trimResults() * .omitEmptyStrings();}</pre> * * <p>Now {@code MY_SPLITTER.split("foo,,, bar ,")} returns just {@code ["foo", * "bar"]}. Note that the order in which these configuration methods are called * is never significant. * * <p><b>Warning:</b> Splitter instances are immutable. Invoking a configuration * method has no effect on the receiving instance; you must store and use the * new splitter instance it returns instead. <pre> {@code * * // Do NOT do this * Splitter splitter = Splitter.on('/'); * splitter.trimResults(); // does nothing! * return splitter.split("wrong / wrong / wrong");}</pre> * * <p>For separator-based splitters that do not use {@code omitEmptyStrings}, an * input string containing {@code n} occurrences of the separator naturally * yields an iterable of size {@code n + 1}. So if the separator does not occur * anywhere in the input, a single substring is returned containing the entire * input. Consequently, all splitters split the empty string to {@code [""]} * (note: even fixed-length splitters). * * <p>Splitter instances are thread-safe immutable, and are therefore safe to * store as {@code static final} constants. * * <p>The {@link Joiner} class provides the inverse operation to splitting, but * note that a round-trip between the two should be assumed to be lossy. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/StringsExplained#Splitter"> * {@code Splitter}</a>. * * @author Julien Silland * @author Jesse Wilson * @author Kevin Bourrillion * @author Louis Wasserman * @since 1.0 */ @GwtCompatible(emulated = true) public final class Splitter { private final CharMatcher trimmer; private final boolean omitEmptyStrings; private final Strategy strategy; private final int limit; private Splitter(Strategy strategy) { this(strategy, false, CharMatcher.NONE, Integer.MAX_VALUE); } private Splitter(Strategy strategy, boolean omitEmptyStrings, CharMatcher trimmer, int limit) { this.strategy = strategy; this.omitEmptyStrings = omitEmptyStrings; this.trimmer = trimmer; this.limit = limit; } /** * Returns a splitter that uses the given single-character separator. For * example, {@code Splitter.on(',').split("foo,,bar")} returns an iterable * containing {@code ["foo", "", "bar"]}. * * @param separator the character to recognize as a separator * @return a splitter, with default settings, that recognizes that separator */ public static Splitter on(char separator) { return on(CharMatcher.is(separator)); } /** * Returns a splitter that considers any single character matched by the * given {@code CharMatcher} to be a separator. For example, {@code * Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux")} returns an * iterable containing {@code ["foo", "", "bar", "quux"]}. * * @param separatorMatcher a {@link CharMatcher} that determines whether a * character is a separator * @return a splitter, with default settings, that uses this matcher */ public static Splitter on(final CharMatcher separatorMatcher) { checkNotNull(separatorMatcher); return new Splitter(new Strategy() { @Override public SplittingIterator iterator( Splitter splitter, final CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override int separatorStart(int start) { return separatorMatcher.indexIn(toSplit, start); } @Override int separatorEnd(int separatorPosition) { return separatorPosition + 1; } }; } }); } /** * Returns a splitter that uses the given fixed string as a separator. For * example, {@code Splitter.on(", ").split("foo, bar,baz")} returns an * iterable containing {@code ["foo", "bar,baz"]}. * * @param separator the literal, nonempty string to recognize as a separator * @return a splitter, with default settings, that recognizes that separator */ public static Splitter on(final String separator) { checkArgument(separator.length() != 0, "The separator may not be the empty string."); return new Splitter(new Strategy() { @Override public SplittingIterator iterator( Splitter splitter, CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { int separatorLength = separator.length(); positions: for (int p = start, last = toSplit.length() - separatorLength; p <= last; p++) { for (int i = 0; i < separatorLength; i++) { if (toSplit.charAt(i + p) != separator.charAt(i)) { continue positions; } } return p; } return -1; } @Override public int separatorEnd(int separatorPosition) { return separatorPosition + separator.length(); } }; } }); } /** * Returns a splitter that considers any subsequence matching {@code * pattern} to be a separator. For example, {@code * Splitter.on(Pattern.compile("\r?\n")).split(entireFile)} splits a string * into lines whether it uses DOS-style or UNIX-style line terminators. * * @param separatorPattern the pattern that determines whether a subsequence * is a separator. This pattern may not match the empty string. * @return a splitter, with default settings, that uses this pattern * @throws IllegalArgumentException if {@code separatorPattern} matches the * empty string */ @GwtIncompatible("java.util.regex") public static Splitter on(final Pattern separatorPattern) { checkNotNull(separatorPattern); checkArgument(!separatorPattern.matcher("").matches(), "The pattern may not match the empty string: %s", separatorPattern); return new Splitter(new Strategy() { @Override public SplittingIterator iterator( final Splitter splitter, CharSequence toSplit) { final Matcher matcher = separatorPattern.matcher(toSplit); return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { return matcher.find(start) ? matcher.start() : -1; } @Override public int separatorEnd(int separatorPosition) { return matcher.end(); } }; } }); } /** * Returns a splitter that considers any subsequence matching a given * pattern (regular expression) to be a separator. For example, {@code * Splitter.onPattern("\r?\n").split(entireFile)} splits a string into lines * whether it uses DOS-style or UNIX-style line terminators. This is * equivalent to {@code Splitter.on(Pattern.compile(pattern))}. * * @param separatorPattern the pattern that determines whether a subsequence * is a separator. This pattern may not match the empty string. * @return a splitter, with default settings, that uses this pattern * @throws java.util.regex.PatternSyntaxException if {@code separatorPattern} * is a malformed expression * @throws IllegalArgumentException if {@code separatorPattern} matches the * empty string */ @GwtIncompatible("java.util.regex") public static Splitter onPattern(String separatorPattern) { return on(Pattern.compile(separatorPattern)); } /** * Returns a splitter that divides strings into pieces of the given length. * For example, {@code Splitter.fixedLength(2).split("abcde")} returns an * iterable containing {@code ["ab", "cd", "e"]}. The last piece can be * smaller than {@code length} but will never be empty. * * <p><b>Exception:</b> for consistency with separator-based splitters, {@code * split("")} does not yield an empty iterable, but an iterable containing * {@code ""}. This is the only case in which {@code * Iterables.size(split(input))} does not equal {@code * IntMath.divide(input.length(), length, CEILING)}. To avoid this behavior, * use {@code omitEmptyStrings}. * * @param length the desired length of pieces after splitting, a positive * integer * @return a splitter, with default settings, that can split into fixed sized * pieces * @throws IllegalArgumentException if {@code length} is zero or negative */ public static Splitter fixedLength(final int length) { checkArgument(length > 0, "The length may not be less than 1"); return new Splitter(new Strategy() { @Override public SplittingIterator iterator( final Splitter splitter, CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { int nextChunkStart = start + length; return (nextChunkStart < toSplit.length() ? nextChunkStart : -1); } @Override public int separatorEnd(int separatorPosition) { return separatorPosition; } }; } }); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but * automatically omits empty strings from the results. For example, {@code * Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,")} returns an * iterable containing only {@code ["a", "b", "c"]}. * * <p>If either {@code trimResults} option is also specified when creating a * splitter, that splitter always trims results first before checking for * emptiness. So, for example, {@code * Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ")} returns * an empty iterable. * * <p>Note that it is ordinarily not possible for {@link #split(CharSequence)} * to return an empty iterable, but when using this option, it can (if the * input sequence consists of nothing but separators). * * @return a splitter with the desired configuration */ @CheckReturnValue public Splitter omitEmptyStrings() { return new Splitter(strategy, true, trimmer, limit); } /** * Returns a splitter that behaves equivalently to {@code this} splitter but * stops splitting after it reaches the limit. * The limit defines the maximum number of items returned by the iterator. * * <p>For example, * {@code Splitter.on(',').limit(3).split("a,b,c,d")} returns an iterable * containing {@code ["a", "b", "c,d"]}. When omitting empty strings, the * omitted strings do no count. Hence, * {@code Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d")} * returns an iterable containing {@code ["a", "b", "c,d"}. * When trim is requested, all entries, including the last are trimmed. Hence * {@code Splitter.on(',').limit(3).trimResults().split(" a , b , c , d ")} * results in @{code ["a", "b", "c , d"]}. * * @param limit the maximum number of items returns * @return a splitter with the desired configuration * @since 9.0 */ @CheckReturnValue public Splitter limit(int limit) { checkArgument(limit > 0, "must be greater than zero: %s", limit); return new Splitter(strategy, omitEmptyStrings, trimmer, limit); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but * automatically removes leading and trailing {@linkplain * CharMatcher#WHITESPACE whitespace} from each returned substring; equivalent * to {@code trimResults(CharMatcher.WHITESPACE)}. For example, {@code * Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable * containing {@code ["a", "b", "c"]}. * * @return a splitter with the desired configuration */ @CheckReturnValue public Splitter trimResults() { return trimResults(CharMatcher.WHITESPACE); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but * removes all leading or trailing characters matching the given {@code * CharMatcher} from each returned substring. For example, {@code * Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")} * returns an iterable containing {@code ["a ", "b_ ", "c"]}. * * @param trimmer a {@link CharMatcher} that determines whether a character * should be removed from the beginning/end of a subsequence * @return a splitter with the desired configuration */ // TODO(kevinb): throw if a trimmer was already specified! @CheckReturnValue public Splitter trimResults(CharMatcher trimmer) { checkNotNull(trimmer); return new Splitter(strategy, omitEmptyStrings, trimmer, limit); } /** * Splits {@code sequence} into string components and makes them available * through an {@link Iterator}, which may be lazily evaluated. If you want * an eagerly computed {@link List}, use {@link #splitToList(CharSequence)}. * * @param sequence the sequence of characters to split * @return an iteration over the segments split from the parameter. */ public Iterable<String> split(final CharSequence sequence) { checkNotNull(sequence); return new Iterable<String>() { @Override public Iterator<String> iterator() { return splittingIterator(sequence); } @Override public String toString() { return Joiner.on(", ") .appendTo(new StringBuilder().append('['), this) .append(']') .toString(); } }; } private Iterator<String> splittingIterator(CharSequence sequence) { return strategy.iterator(this, sequence); } /** * Splits {@code sequence} into string components and returns them as * an immutable list. If you want an {@link Iterable} which may be lazily * evaluated, use {@link #split(CharSequence)}. * * @param sequence the sequence of characters to split * @return an immutable list of the segments split from the parameter * @since 15.0 */ @Beta public List<String> splitToList(CharSequence sequence) { checkNotNull(sequence); Iterator<String> iterator = splittingIterator(sequence); List<String> result = new ArrayList<String>(); while (iterator.hasNext()) { result.add(iterator.next()); } return Collections.unmodifiableList(result); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, * and splits entries into keys and values using the specified separator. * * @since 10.0 */ @CheckReturnValue @Beta public MapSplitter withKeyValueSeparator(String separator) { return withKeyValueSeparator(on(separator)); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, * and splits entries into keys and values using the specified separator. * * @since 14.0 */ @CheckReturnValue @Beta public MapSplitter withKeyValueSeparator(char separator) { return withKeyValueSeparator(on(separator)); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, * and splits entries into keys and values using the specified key-value * splitter. * * @since 10.0 */ @CheckReturnValue @Beta public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) { return new MapSplitter(this, keyValueSplitter); } /** * An object that splits strings into maps as {@code Splitter} splits * iterables and lists. Like {@code Splitter}, it is thread-safe and * immutable. * * @since 10.0 */ @Beta public static final class MapSplitter { private static final String INVALID_ENTRY_MESSAGE = "Chunk [%s] is not a valid entry"; private final Splitter outerSplitter; private final Splitter entrySplitter; private MapSplitter(Splitter outerSplitter, Splitter entrySplitter) { this.outerSplitter = outerSplitter; // only "this" is passed this.entrySplitter = checkNotNull(entrySplitter); } /** * Splits {@code sequence} into substrings, splits each substring into * an entry, and returns an unmodifiable map with each of the entries. For * example, <code> * Splitter.on(';').trimResults().withKeyValueSeparator("=>") * .split("a=>b ; c=>b") * </code> will return a mapping from {@code "a"} to {@code "b"} and * {@code "c"} to {@code b}. * * <p>The returned map preserves the order of the entries from * {@code sequence}. * * @throws IllegalArgumentException if the specified sequence does not split * into valid map entries, or if there are duplicate keys */ public Map<String, String> split(CharSequence sequence) { Map<String, String> map = new LinkedHashMap<String, String>(); for (String entry : outerSplitter.split(sequence)) { Iterator<String> entryFields = entrySplitter.splittingIterator(entry); checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); String key = entryFields.next(); checkArgument(!map.containsKey(key), "Duplicate key [%s] found.", key); checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); String value = entryFields.next(); map.put(key, value); checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); } return Collections.unmodifiableMap(map); } } private interface Strategy { Iterator<String> iterator(Splitter splitter, CharSequence toSplit); } private abstract static class SplittingIterator extends AbstractIterator<String> { final CharSequence toSplit; final CharMatcher trimmer; final boolean omitEmptyStrings; /** * Returns the first index in {@code toSplit} at or after {@code start} * that contains the separator. */ abstract int separatorStart(int start); /** * Returns the first index in {@code toSplit} after {@code * separatorPosition} that does not contain a separator. This method is only * invoked after a call to {@code separatorStart}. */ abstract int separatorEnd(int separatorPosition); int offset = 0; int limit; protected SplittingIterator(Splitter splitter, CharSequence toSplit) { this.trimmer = splitter.trimmer; this.omitEmptyStrings = splitter.omitEmptyStrings; this.limit = splitter.limit; this.toSplit = toSplit; } @Override protected String computeNext() { /* * The returned string will be from the end of the last match to the * beginning of the next one. nextStart is the start position of the * returned substring, while offset is the place to start looking for a * separator. */ int nextStart = offset; while (offset != -1) { int start = nextStart; int end; int separatorPosition = separatorStart(offset); if (separatorPosition == -1) { end = toSplit.length(); offset = -1; } else { end = separatorPosition; offset = separatorEnd(separatorPosition); } if (offset == nextStart) { /* * This occurs when some pattern has an empty match, even if it * doesn't match the empty string -- for example, if it requires * lookahead or the like. The offset must be increased to look for * separators beyond this point, without changing the start position * of the next returned substring -- so nextStart stays the same. */ offset++; if (offset >= toSplit.length()) { offset = -1; } continue; } while (start < end && trimmer.matches(toSplit.charAt(start))) { start++; } while (end > start && trimmer.matches(toSplit.charAt(end - 1))) { end--; } if (omitEmptyStrings && start == end) { // Don't include the (unused) separator in next split string. nextStart = offset; continue; } if (limit == 1) { // The limit has been reached, return the rest of the string as the // final item. This is tested after empty string removal so that // empty strings do not count towards the limit. end = toSplit.length(); offset = -1; // Since we may have changed the end, we need to trim it again. while (end > start && trimmer.matches(toSplit.charAt(end - 1))) { end--; } } else { limit--; } return toSplit.subSequence(start, end).toString(); } return endOfData(); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Splitter.java
Java
asf20
23,089
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import java.util.Formatter; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@code String} or {@code CharSequence} * instances. * * @author Kevin Bourrillion * @since 3.0 */ @GwtCompatible public final class Strings { private Strings() {} /** * Returns the given string if it is non-null; the empty string otherwise. * * @param string the string to test and possibly return * @return {@code string} itself if it is non-null; {@code ""} if it is null */ public static String nullToEmpty(@Nullable String string) { return (string == null) ? "" : string; } /** * Returns the given string if it is nonempty; {@code null} otherwise. * * @param string the string to test and possibly return * @return {@code string} itself if it is nonempty; {@code null} if it is * empty or null */ public static @Nullable String emptyToNull(@Nullable String string) { return isNullOrEmpty(string) ? null : string; } /** * Returns {@code true} if the given string is null or is the empty string. * * <p>Consider normalizing your string references with {@link #nullToEmpty}. * If you do, you can use {@link String#isEmpty()} instead of this * method, and you won't need special null-safe forms of methods like {@link * String#toUpperCase} either. Or, if you'd like to normalize "in the other * direction," converting empty strings to {@code null}, you can use {@link * #emptyToNull}. * * @param string a string reference to check * @return {@code true} if the string is null or is the empty string */ public static boolean isNullOrEmpty(@Nullable String string) { return string == null || string.length() == 0; // string.isEmpty() in Java 6 } /** * Returns a string, of length at least {@code minLength}, consisting of * {@code string} prepended with as many copies of {@code padChar} as are * necessary to reach that length. For example, * * <ul> * <li>{@code padStart("7", 3, '0')} returns {@code "007"} * <li>{@code padStart("2010", 3, '0')} returns {@code "2010"} * </ul> * * <p>See {@link Formatter} for a richer set of formatting capabilities. * * @param string the string which should appear at the end of the result * @param minLength the minimum length the resulting string must have. Can be * zero or negative, in which case the input string is always returned. * @param padChar the character to insert at the beginning of the result until * the minimum length is reached * @return the padded string */ public static String padStart(String string, int minLength, char padChar) { checkNotNull(string); // eager for GWT. if (string.length() >= minLength) { return string; } StringBuilder sb = new StringBuilder(minLength); for (int i = string.length(); i < minLength; i++) { sb.append(padChar); } sb.append(string); return sb.toString(); } /** * Returns a string, of length at least {@code minLength}, consisting of * {@code string} appended with as many copies of {@code padChar} as are * necessary to reach that length. For example, * * <ul> * <li>{@code padEnd("4.", 5, '0')} returns {@code "4.000"} * <li>{@code padEnd("2010", 3, '!')} returns {@code "2010"} * </ul> * * <p>See {@link Formatter} for a richer set of formatting capabilities. * * @param string the string which should appear at the beginning of the result * @param minLength the minimum length the resulting string must have. Can be * zero or negative, in which case the input string is always returned. * @param padChar the character to append to the end of the result until the * minimum length is reached * @return the padded string */ public static String padEnd(String string, int minLength, char padChar) { checkNotNull(string); // eager for GWT. if (string.length() >= minLength) { return string; } StringBuilder sb = new StringBuilder(minLength); sb.append(string); for (int i = string.length(); i < minLength; i++) { sb.append(padChar); } return sb.toString(); } /** * Returns a string consisting of a specific number of concatenated copies of * an input string. For example, {@code repeat("hey", 3)} returns the string * {@code "heyheyhey"}. * * @param string any non-null string * @param count the number of times to repeat it; a nonnegative integer * @return a string containing {@code string} repeated {@code count} times * (the empty string if {@code count} is zero) * @throws IllegalArgumentException if {@code count} is negative */ public static String repeat(String string, int count) { checkNotNull(string); // eager for GWT. if (count <= 1) { checkArgument(count >= 0, "invalid count: %s", count); return (count == 0) ? "" : string; } // IF YOU MODIFY THE CODE HERE, you must update StringsRepeatBenchmark final int len = string.length(); final long longSize = (long) len * (long) count; final int size = (int) longSize; if (size != longSize) { throw new ArrayIndexOutOfBoundsException( "Required array size too large: " + longSize); } final char[] array = new char[size]; string.getChars(0, len, array, 0); int n; for (n = len; n < size - n; n <<= 1) { System.arraycopy(array, 0, array, n, n); } System.arraycopy(array, 0, array, n, size - n); return new String(array); } /** * Returns the longest string {@code prefix} such that * {@code a.toString().startsWith(prefix) && b.toString().startsWith(prefix)}, * taking care not to split surrogate pairs. If {@code a} and {@code b} have * no common prefix, returns the empty string. * * @since 11.0 */ public static String commonPrefix(CharSequence a, CharSequence b) { checkNotNull(a); checkNotNull(b); int maxPrefixLength = Math.min(a.length(), b.length()); int p = 0; while (p < maxPrefixLength && a.charAt(p) == b.charAt(p)) { p++; } if (validSurrogatePairAt(a, p - 1) || validSurrogatePairAt(b, p - 1)) { p--; } return a.subSequence(0, p).toString(); } /** * Returns the longest string {@code suffix} such that * {@code a.toString().endsWith(suffix) && b.toString().endsWith(suffix)}, * taking care not to split surrogate pairs. If {@code a} and {@code b} have * no common suffix, returns the empty string. * * @since 11.0 */ public static String commonSuffix(CharSequence a, CharSequence b) { checkNotNull(a); checkNotNull(b); int maxSuffixLength = Math.min(a.length(), b.length()); int s = 0; while (s < maxSuffixLength && a.charAt(a.length() - s - 1) == b.charAt(b.length() - s - 1)) { s++; } if (validSurrogatePairAt(a, a.length() - s - 1) || validSurrogatePairAt(b, b.length() - s - 1)) { s--; } return a.subSequence(a.length() - s, a.length()).toString(); } /** * True when a valid surrogate pair starts at the given {@code index} in the * given {@code string}. Out-of-range indexes return false. */ @VisibleForTesting static boolean validSurrogatePairAt(CharSequence string, int index) { return index >= 0 && index <= (string.length() - 2) && Character.isHighSurrogate(string.charAt(index)) && Character.isLowSurrogate(string.charAt(index + 1)); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Strings.java
Java
asf20
8,383
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import javax.annotation.Nullable; /** * Utility class for converting between various ASCII case formats. Behavior is undefined for * non-ASCII input. * * @author Mike Bostock * @since 1.0 */ @GwtCompatible public enum CaseFormat { /** * Hyphenated variable naming convention, e.g., "lower-hyphen". */ LOWER_HYPHEN(CharMatcher.is('-'), "-") { @Override String normalizeWord(String word) { return Ascii.toLowerCase(word); } @Override String convert(CaseFormat format, String s) { if (format == LOWER_UNDERSCORE) { return s.replace('-', '_'); } if (format == UPPER_UNDERSCORE) { return Ascii.toUpperCase(s.replace('-', '_')); } return super.convert(format, s); } }, /** * C++ variable naming convention, e.g., "lower_underscore". */ LOWER_UNDERSCORE(CharMatcher.is('_'), "_") { @Override String normalizeWord(String word) { return Ascii.toLowerCase(word); } @Override String convert(CaseFormat format, String s) { if (format == LOWER_HYPHEN) { return s.replace('_', '-'); } if (format == UPPER_UNDERSCORE) { return Ascii.toUpperCase(s); } return super.convert(format, s); } }, /** * Java variable naming convention, e.g., "lowerCamel". */ LOWER_CAMEL(CharMatcher.inRange('A', 'Z'), "") { @Override String normalizeWord(String word) { return firstCharOnlyToUpper(word); } }, /** * Java and C++ class naming convention, e.g., "UpperCamel". */ UPPER_CAMEL(CharMatcher.inRange('A', 'Z'), "") { @Override String normalizeWord(String word) { return firstCharOnlyToUpper(word); } }, /** * Java and C++ constant naming convention, e.g., "UPPER_UNDERSCORE". */ UPPER_UNDERSCORE(CharMatcher.is('_'), "_") { @Override String normalizeWord(String word) { return Ascii.toUpperCase(word); } @Override String convert(CaseFormat format, String s) { if (format == LOWER_HYPHEN) { return Ascii.toLowerCase(s.replace('_', '-')); } if (format == LOWER_UNDERSCORE) { return Ascii.toLowerCase(s); } return super.convert(format, s); } }; private final CharMatcher wordBoundary; private final String wordSeparator; CaseFormat(CharMatcher wordBoundary, String wordSeparator) { this.wordBoundary = wordBoundary; this.wordSeparator = wordSeparator; } /** * Converts the specified {@code String str} from this format to the specified {@code format}. A * "best effort" approach is taken; if {@code str} does not conform to the assumed format, then * the behavior of this method is undefined but we make a reasonable effort at converting anyway. */ public final String to(CaseFormat format, String str) { checkNotNull(format); checkNotNull(str); return (format == this) ? str : convert(format, str); } /** * Enum values can override for performance reasons. */ String convert(CaseFormat format, String s) { // deal with camel conversion StringBuilder out = null; int i = 0; int j = -1; while ((j = wordBoundary.indexIn(s, ++j)) != -1) { if (i == 0) { // include some extra space for separators out = new StringBuilder(s.length() + 4 * wordSeparator.length()); out.append(format.normalizeFirstWord(s.substring(i, j))); } else { out.append(format.normalizeWord(s.substring(i, j))); } out.append(format.wordSeparator); i = j + wordSeparator.length(); } return (i == 0) ? format.normalizeFirstWord(s) : out.append(format.normalizeWord(s.substring(i))).toString(); } /** * Returns a {@code Converter} that converts strings from this format to {@code targetFormat}. * * @since 16.0 */ @Beta public Converter<String, String> converterTo(CaseFormat targetFormat) { return new StringConverter(this, targetFormat); } private static final class StringConverter extends Converter<String, String> implements Serializable { private final CaseFormat sourceFormat; private final CaseFormat targetFormat; StringConverter(CaseFormat sourceFormat, CaseFormat targetFormat) { this.sourceFormat = checkNotNull(sourceFormat); this.targetFormat = checkNotNull(targetFormat); } @Override protected String doForward(String s) { // TODO(kevinb): remove null boilerplate (convert() will do it automatically) return s == null ? null : sourceFormat.to(targetFormat, s); } @Override protected String doBackward(String s) { // TODO(kevinb): remove null boilerplate (convert() will do it automatically) return s == null ? null : targetFormat.to(sourceFormat, s); } @Override public boolean equals(@Nullable Object object) { if (object instanceof StringConverter) { StringConverter that = (StringConverter) object; return sourceFormat.equals(that.sourceFormat) && targetFormat.equals(that.targetFormat); } return false; } @Override public int hashCode() { return sourceFormat.hashCode() ^ targetFormat.hashCode(); } @Override public String toString() { return sourceFormat + ".converterTo(" + targetFormat + ")"; } private static final long serialVersionUID = 0L; } abstract String normalizeWord(String word); private String normalizeFirstWord(String word) { return (this == LOWER_CAMEL) ? Ascii.toLowerCase(word) : normalizeWord(word); } private static String firstCharOnlyToUpper(String word) { return (word.isEmpty()) ? word : new StringBuilder(word.length()) .append(Ascii.toUpperCase(word.charAt(0))) .append(Ascii.toLowerCase(word.substring(1))) .toString(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/CaseFormat.java
Java
asf20
6,668
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.annotation.Nullable; /** * Static utility methods pertaining to instances of {@link Throwable}. * * <p>See the Guava User Guide entry on <a href= * "http://code.google.com/p/guava-libraries/wiki/ThrowablesExplained"> * Throwables</a>. * * @author Kevin Bourrillion * @author Ben Yu * @since 1.0 */ public final class Throwables { private Throwables() {} /** * Propagates {@code throwable} exactly as-is, if and only if it is an * instance of {@code declaredType}. Example usage: * <pre> * try { * someMethodThatCouldThrowAnything(); * } catch (IKnowWhatToDoWithThisException e) { * handle(e); * } catch (Throwable t) { * Throwables.propagateIfInstanceOf(t, IOException.class); * Throwables.propagateIfInstanceOf(t, SQLException.class); * throw Throwables.propagate(t); * } * </pre> */ public static <X extends Throwable> void propagateIfInstanceOf( @Nullable Throwable throwable, Class<X> declaredType) throws X { // Check for null is needed to avoid frequent JNI calls to isInstance(). if (throwable != null && declaredType.isInstance(throwable)) { throw declaredType.cast(throwable); } } /** * Propagates {@code throwable} exactly as-is, if and only if it is an * instance of {@link RuntimeException} or {@link Error}. Example usage: * <pre> * try { * someMethodThatCouldThrowAnything(); * } catch (IKnowWhatToDoWithThisException e) { * handle(e); * } catch (Throwable t) { * Throwables.propagateIfPossible(t); * throw new RuntimeException("unexpected", t); * } * </pre> */ public static void propagateIfPossible(@Nullable Throwable throwable) { propagateIfInstanceOf(throwable, Error.class); propagateIfInstanceOf(throwable, RuntimeException.class); } /** * Propagates {@code throwable} exactly as-is, if and only if it is an * instance of {@link RuntimeException}, {@link Error}, or * {@code declaredType}. Example usage: * <pre> * try { * someMethodThatCouldThrowAnything(); * } catch (IKnowWhatToDoWithThisException e) { * handle(e); * } catch (Throwable t) { * Throwables.propagateIfPossible(t, OtherException.class); * throw new RuntimeException("unexpected", t); * } * </pre> * * @param throwable the Throwable to possibly propagate * @param declaredType the single checked exception type declared by the * calling method */ public static <X extends Throwable> void propagateIfPossible( @Nullable Throwable throwable, Class<X> declaredType) throws X { propagateIfInstanceOf(throwable, declaredType); propagateIfPossible(throwable); } /** * Propagates {@code throwable} exactly as-is, if and only if it is an * instance of {@link RuntimeException}, {@link Error}, {@code declaredType1}, * or {@code declaredType2}. In the unlikely case that you have three or more * declared checked exception types, you can handle them all by invoking these * methods repeatedly. See usage example in {@link * #propagateIfPossible(Throwable, Class)}. * * @param throwable the Throwable to possibly propagate * @param declaredType1 any checked exception type declared by the calling * method * @param declaredType2 any other checked exception type declared by the * calling method */ public static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible(@Nullable Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2) throws X1, X2 { checkNotNull(declaredType2); propagateIfInstanceOf(throwable, declaredType1); propagateIfPossible(throwable, declaredType2); } /** * Propagates {@code throwable} as-is if it is an instance of * {@link RuntimeException} or {@link Error}, or else as a last resort, wraps * it in a {@code RuntimeException} then propagates. * <p> * This method always throws an exception. The {@code RuntimeException} return * type is only for client code to make Java type system happy in case a * return value is required by the enclosing method. Example usage: * <pre> * T doSomething() { * try { * return someMethodThatCouldThrowAnything(); * } catch (IKnowWhatToDoWithThisException e) { * return handle(e); * } catch (Throwable t) { * throw Throwables.propagate(t); * } * } * </pre> * * @param throwable the Throwable to propagate * @return nothing will ever be returned; this return type is only for your * convenience, as illustrated in the example above */ public static RuntimeException propagate(Throwable throwable) { propagateIfPossible(checkNotNull(throwable)); throw new RuntimeException(throwable); } /** * Returns the innermost cause of {@code throwable}. The first throwable in a * chain provides context from when the error or exception was initially * detected. Example usage: * <pre> * assertEquals("Unable to assign a customer id", * Throwables.getRootCause(e).getMessage()); * </pre> */ public static Throwable getRootCause(Throwable throwable) { Throwable cause; while ((cause = throwable.getCause()) != null) { throwable = cause; } return throwable; } /** * Gets a {@code Throwable} cause chain as a list. The first entry in the * list will be {@code throwable} followed by its cause hierarchy. Note * that this is a snapshot of the cause chain and will not reflect * any subsequent changes to the cause chain. * * <p>Here's an example of how it can be used to find specific types * of exceptions in the cause chain: * * <pre> * Iterables.filter(Throwables.getCausalChain(e), IOException.class)); * </pre> * * @param throwable the non-null {@code Throwable} to extract causes from * @return an unmodifiable list containing the cause chain starting with * {@code throwable} */ @Beta // TODO(kevinb): decide best return type public static List<Throwable> getCausalChain(Throwable throwable) { checkNotNull(throwable); List<Throwable> causes = new ArrayList<Throwable>(4); while (throwable != null) { causes.add(throwable); throwable = throwable.getCause(); } return Collections.unmodifiableList(causes); } /** * Returns a string containing the result of * {@link Throwable#toString() toString()}, followed by the full, recursive * stack trace of {@code throwable}. Note that you probably should not be * parsing the resulting string; if you need programmatic access to the stack * frames, you can call {@link Throwable#getStackTrace()}. */ public static String getStackTraceAsString(Throwable throwable) { StringWriter stringWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Throwables.java
Java
asf20
7,902
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; /** * Soft reference with a {@code finalizeReferent()} method which a background thread invokes after * the garbage collector reclaims the referent. This is a simpler alternative to using a {@link * ReferenceQueue}. * * @author Bob Lee * @since 2.0 (imported from Google Collections Library) */ public abstract class FinalizableSoftReference<T> extends SoftReference<T> implements FinalizableReference { /** * Constructs a new finalizable soft reference. * * @param referent to softly reference * @param queue that should finalize the referent */ protected FinalizableSoftReference(T referent, FinalizableReferenceQueue queue) { super(referent, queue.queue); queue.cleanUp(); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/FinalizableSoftReference.java
Java
asf20
1,429
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; /** * A time source; returns a time value representing the number of nanoseconds elapsed since some * fixed but arbitrary point in time. Note that most users should use {@link Stopwatch} instead of * interacting with this class directly. * * <p><b>Warning:</b> this interface can only be used to measure elapsed time, not wall time. * * @author Kevin Bourrillion * @since 10.0 * (<a href="http://code.google.com/p/guava-libraries/wiki/Compatibility" * >mostly source-compatible</a> since 9.0) */ @Beta @GwtCompatible public abstract class Ticker { /** * Constructor for use by subclasses. */ protected Ticker() {} /** * Returns the number of nanoseconds elapsed since this ticker's fixed * point of reference. */ public abstract long read(); /** * A ticker that reads the current time using {@link System#nanoTime}. * * @since 10.0 */ public static Ticker systemTicker() { return SYSTEM_TICKER; } private static final Ticker SYSTEM_TICKER = new Ticker() { @Override public long read() { return Platform.systemNanoTime(); } }; }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Ticker.java
Java
asf20
1,848
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; /** * Implemented by references that have code to run after garbage collection of their referents. * * @see FinalizableReferenceQueue * @author Bob Lee * @since 2.0 (imported from Google Collections Library) */ public interface FinalizableReference { /** * Invoked on a background thread after the referent has been garbage collected unless security * restrictions prevented starting a background thread, in which case this method is invoked when * new references are created. */ void finalizeReferent(); }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/FinalizableReference.java
Java
asf20
1,164
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.util.Collections; import java.util.Set; import javax.annotation.Nullable; /** * Implementation of an {@link Optional} not containing a reference. */ @GwtCompatible final class Absent<T> extends Optional<T> { static final Absent<Object> INSTANCE = new Absent<Object>(); @SuppressWarnings("unchecked") // implementation is "fully variant" static <T> Optional<T> withType() { return (Optional<T>) INSTANCE; } private Absent() {} @Override public boolean isPresent() { return false; } @Override public T get() { throw new IllegalStateException("Optional.get() cannot be called on an absent value"); } @Override public T or(T defaultValue) { return checkNotNull(defaultValue, "use Optional.orNull() instead of Optional.or(null)"); } @SuppressWarnings("unchecked") // safe covariant cast @Override public Optional<T> or(Optional<? extends T> secondChoice) { return (Optional<T>) checkNotNull(secondChoice); } @Override public T or(Supplier<? extends T> supplier) { return checkNotNull(supplier.get(), "use Optional.orNull() instead of a Supplier that returns null"); } @Override @Nullable public T orNull() { return null; } @Override public Set<T> asSet() { return Collections.emptySet(); } @Override public <V> Optional<V> transform(Function<? super T, V> function) { checkNotNull(function); return Optional.absent(); } @Override public boolean equals(@Nullable Object object) { return object == this; } @Override public int hashCode() { return 0x598df91c; } @Override public String toString() { return "Optional.absent()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Absent.java
Java
asf20
2,532
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.CharMatcher.FastMatcher; import java.util.BitSet; /** * An immutable version of CharMatcher for smallish sets of characters that uses a hash table * with linear probing to check for matches. * * @author Christopher Swenson */ @GwtIncompatible("no precomputation is done in GWT") final class SmallCharMatcher extends FastMatcher { static final int MAX_SIZE = 1023; private final char[] table; private final boolean containsZero; private final long filter; private SmallCharMatcher(char[] table, long filter, boolean containsZero, String description) { super(description); this.table = table; this.filter = filter; this.containsZero = containsZero; } private static final int C1 = 0xcc9e2d51; private static final int C2 = 0x1b873593; /* * This method was rewritten in Java from an intermediate step of the Murmur hash function in * http://code.google.com/p/smhasher/source/browse/trunk/MurmurHash3.cpp, which contained the * following header: * * MurmurHash3 was written by Austin Appleby, and is placed in the public domain. The author * hereby disclaims copyright to this source code. */ static int smear(int hashCode) { return C2 * Integer.rotateLeft(hashCode * C1, 15); } private boolean checkFilter(int c) { return 1 == (1 & (filter >> c)); } // This is all essentially copied from ImmutableSet, but we have to duplicate because // of dependencies. // Represents how tightly we can pack things, as a maximum. private static final double DESIRED_LOAD_FACTOR = 0.5; /** * Returns an array size suitable for the backing array of a hash table that * uses open addressing with linear probing in its implementation. The * returned size is the smallest power of two that can hold setSize elements * with the desired load factor. */ @VisibleForTesting static int chooseTableSize(int setSize) { if (setSize == 1) { return 2; } // Correct the size for open addressing to match desired load factor. // Round up to the next highest power of 2. int tableSize = Integer.highestOneBit(setSize - 1) << 1; while (tableSize * DESIRED_LOAD_FACTOR < setSize) { tableSize <<= 1; } return tableSize; } static CharMatcher from(BitSet chars, String description) { // Compute the filter. long filter = 0; int size = chars.cardinality(); boolean containsZero = chars.get(0); // Compute the hash table. char[] table = new char[chooseTableSize(size)]; int mask = table.length - 1; for (int c = chars.nextSetBit(0); c != -1; c = chars.nextSetBit(c + 1)) { // Compute the filter at the same time. filter |= 1L << c; int index = smear(c) & mask; while (true) { // Check for empty. if (table[index] == 0) { table[index] = (char) c; break; } // Linear probing. index = (index + 1) & mask; } } return new SmallCharMatcher(table, filter, containsZero, description); } @Override public boolean matches(char c) { if (c == 0) { return containsZero; } if (!checkFilter(c)) { return false; } int mask = table.length - 1; int startingIndex = smear(c) & mask; int index = startingIndex; do { // Check for empty. if (table[index] == 0) { return false; // Check for match. } else if (table[index] == c) { return true; } else { // Linear probing. index = (index + 1) & mask; } // Check to see if we wrapped around the whole table. } while (index != startingIndex); return false; } @Override void setBits(BitSet table) { if (containsZero) { table.set(0); } for (char c : this.table) { if (c != 0) { table.set(c); } } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/SmallCharMatcher.java
Java
asf20
4,632
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static java.util.concurrent.TimeUnit.DAYS; import static java.util.concurrent.TimeUnit.HOURS; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.MINUTES; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.util.concurrent.TimeUnit; /** * An object that measures elapsed time in nanoseconds. It is useful to measure * elapsed time using this class instead of direct calls to {@link * System#nanoTime} for a few reasons: * * <ul> * <li>An alternate time source can be substituted, for testing or performance * reasons. * <li>As documented by {@code nanoTime}, the value returned has no absolute * meaning, and can only be interpreted as relative to another timestamp * returned by {@code nanoTime} at a different time. {@code Stopwatch} is a * more effective abstraction because it exposes only these relative values, * not the absolute ones. * </ul> * * <p>Basic usage: * <pre> * Stopwatch stopwatch = Stopwatch.{@link #createStarted createStarted}(); * doSomething(); * stopwatch.{@link #stop stop}(); // optional * * long millis = stopwatch.elapsed(MILLISECONDS); * * log.info("time: " + stopwatch); // formatted string like "12.3 ms"</pre> * * <p>Stopwatch methods are not idempotent; it is an error to start or stop a * stopwatch that is already in the desired state. * * <p>When testing code that uses this class, use * {@link #createUnstarted(Ticker)} or {@link #createStarted(Ticker)} to * supply a fake or mock ticker. * <!-- TODO(kevinb): restore the "such as" --> This allows you to * simulate any valid behavior of the stopwatch. * * <p><b>Note:</b> This class is not thread-safe. * * @author Kevin Bourrillion * @since 10.0 */ @Beta @GwtCompatible(emulated = true) public final class Stopwatch { private final Ticker ticker; private boolean isRunning; private long elapsedNanos; private long startTick; /** * Creates (but does not start) a new stopwatch using {@link System#nanoTime} * as its time source. * * @since 15.0 */ public static Stopwatch createUnstarted() { return new Stopwatch(); } /** * Creates (but does not start) a new stopwatch, using the specified time * source. * * @since 15.0 */ public static Stopwatch createUnstarted(Ticker ticker) { return new Stopwatch(ticker); } /** * Creates (and starts) a new stopwatch using {@link System#nanoTime} * as its time source. * * @since 15.0 */ public static Stopwatch createStarted() { return new Stopwatch().start(); } /** * Creates (and starts) a new stopwatch, using the specified time * source. * * @since 15.0 */ public static Stopwatch createStarted(Ticker ticker) { return new Stopwatch(ticker).start(); } /** * Creates (but does not start) a new stopwatch using {@link System#nanoTime} * as its time source. * * @deprecated Use {@link Stopwatch#createUnstarted()} instead. */ @Deprecated Stopwatch() { this(Ticker.systemTicker()); } /** * Creates (but does not start) a new stopwatch, using the specified time * source. * * @deprecated Use {@link Stopwatch#createUnstarted(Ticker)} instead. */ @Deprecated Stopwatch(Ticker ticker) { this.ticker = checkNotNull(ticker, "ticker"); } /** * Returns {@code true} if {@link #start()} has been called on this stopwatch, * and {@link #stop()} has not been called since the last call to {@code * start()}. */ public boolean isRunning() { return isRunning; } /** * Starts the stopwatch. * * @return this {@code Stopwatch} instance * @throws IllegalStateException if the stopwatch is already running. */ public Stopwatch start() { checkState(!isRunning, "This stopwatch is already running."); isRunning = true; startTick = ticker.read(); return this; } /** * Stops the stopwatch. Future reads will return the fixed duration that had * elapsed up to this point. * * @return this {@code Stopwatch} instance * @throws IllegalStateException if the stopwatch is already stopped. */ public Stopwatch stop() { long tick = ticker.read(); checkState(isRunning, "This stopwatch is already stopped."); isRunning = false; elapsedNanos += tick - startTick; return this; } /** * Sets the elapsed time for this stopwatch to zero, * and places it in a stopped state. * * @return this {@code Stopwatch} instance */ public Stopwatch reset() { elapsedNanos = 0; isRunning = false; return this; } private long elapsedNanos() { return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos; } /** * Returns the current elapsed time shown on this stopwatch, expressed * in the desired time unit, with any fraction rounded down. * * <p>Note that the overhead of measurement can be more than a microsecond, so * it is generally not useful to specify {@link TimeUnit#NANOSECONDS} * precision here. * * @since 14.0 (since 10.0 as {@code elapsedTime()}) */ public long elapsed(TimeUnit desiredUnit) { return desiredUnit.convert(elapsedNanos(), NANOSECONDS); } /** * Returns a string representation of the current elapsed time. */ @GwtIncompatible("String.format()") @Override public String toString() { long nanos = elapsedNanos(); TimeUnit unit = chooseUnit(nanos); double value = (double) nanos / NANOSECONDS.convert(1, unit); // Too bad this functionality is not exposed as a regular method call return String.format("%.4g %s", value, abbreviate(unit)); } private static TimeUnit chooseUnit(long nanos) { if (DAYS.convert(nanos, NANOSECONDS) > 0) { return DAYS; } if (HOURS.convert(nanos, NANOSECONDS) > 0) { return HOURS; } if (MINUTES.convert(nanos, NANOSECONDS) > 0) { return MINUTES; } if (SECONDS.convert(nanos, NANOSECONDS) > 0) { return SECONDS; } if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) { return MILLISECONDS; } if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) { return MICROSECONDS; } return NANOSECONDS; } private static String abbreviate(TimeUnit unit) { switch (unit) { case NANOSECONDS: return "ns"; case MICROSECONDS: return "\u03bcs"; // μs case MILLISECONDS: return "ms"; case SECONDS: return "s"; case MINUTES: return "min"; case HOURS: return "h"; case DAYS: return "d"; default: throw new AssertionError(); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Stopwatch.java
Java
asf20
7,730
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy * of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import javax.annotation.Nullable; /** * Equivalence applied on functional result. * * @author Bob Lee * @since 10.0 */ @Beta @GwtCompatible final class FunctionalEquivalence<F, T> extends Equivalence<F> implements Serializable { private static final long serialVersionUID = 0; private final Function<F, ? extends T> function; private final Equivalence<T> resultEquivalence; FunctionalEquivalence( Function<F, ? extends T> function, Equivalence<T> resultEquivalence) { this.function = checkNotNull(function); this.resultEquivalence = checkNotNull(resultEquivalence); } @Override protected boolean doEquivalent(F a, F b) { return resultEquivalence.equivalent(function.apply(a), function.apply(b)); } @Override protected int doHash(F a) { return resultEquivalence.hash(function.apply(a)); } @Override public boolean equals(@Nullable Object obj) { if (obj == this) { return true; } if (obj instanceof FunctionalEquivalence) { FunctionalEquivalence<?, ?> that = (FunctionalEquivalence<?, ?>) obj; return function.equals(that.function) && resultEquivalence.equals(that.resultEquivalence); } return false; } @Override public int hashCode() { return Objects.hashCode(function, resultEquivalence); } @Override public String toString() { return resultEquivalence + ".onResultOf(" + function + ")"; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/FunctionalEquivalence.java
Java
asf20
2,247
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base.internal; import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.lang.reflect.Method; import java.util.logging.Level; import java.util.logging.Logger; /** * Thread that finalizes referents. All references should implement * {@code com.google.common.base.FinalizableReference}. * * <p>While this class is public, we consider it to be *internal* and not part * of our published API. It is public so we can access it reflectively across * class loaders in secure environments. * * <p>This class can't depend on other Google Collections code. If we were * to load this class in the same class loader as the rest of * Google Collections, this thread would keep an indirect strong reference * to the class loader and prevent it from being garbage collected. This * poses a problem for environments where you want to throw away the class * loader. For example, dynamically reloading a web application or unloading * an OSGi bundle. * * <p>{@code com.google.common.base.FinalizableReferenceQueue} loads this class * in its own class loader. That way, this class doesn't prevent the main * class loader from getting garbage collected, and this class can detect when * the main class loader has been garbage collected and stop itself. */ public class Finalizer implements Runnable { private static final Logger logger = Logger.getLogger(Finalizer.class.getName()); /** Name of FinalizableReference.class. */ private static final String FINALIZABLE_REFERENCE = "com.google.common.base.FinalizableReference"; /** * Starts the Finalizer thread. FinalizableReferenceQueue calls this method * reflectively. * * @param finalizableReferenceClass FinalizableReference.class. * @param queue a reference queue that the thread will poll. * @param frqReference a phantom reference to the FinalizableReferenceQueue, which will be * queued either when the FinalizableReferenceQueue is no longer referenced anywhere, or when * its close() method is called. */ public static void startFinalizer( Class<?> finalizableReferenceClass, ReferenceQueue<Object> queue, PhantomReference<Object> frqReference) { /* * We use FinalizableReference.class for two things: * * 1) To invoke FinalizableReference.finalizeReferent() * * 2) To detect when FinalizableReference's class loader has to be garbage * collected, at which point, Finalizer can stop running */ if (!finalizableReferenceClass.getName().equals(FINALIZABLE_REFERENCE)) { throw new IllegalArgumentException( "Expected " + FINALIZABLE_REFERENCE + "."); } Finalizer finalizer = new Finalizer(finalizableReferenceClass, queue, frqReference); Thread thread = new Thread(finalizer); thread.setName(Finalizer.class.getName()); thread.setDaemon(true); try { if (inheritableThreadLocals != null) { inheritableThreadLocals.set(thread, null); } } catch (Throwable t) { logger.log(Level.INFO, "Failed to clear thread local values inherited" + " by reference finalizer thread.", t); } thread.start(); } private final WeakReference<Class<?>> finalizableReferenceClassReference; private final PhantomReference<Object> frqReference; private final ReferenceQueue<Object> queue; private static final Field inheritableThreadLocals = getInheritableThreadLocalsField(); /** Constructs a new finalizer thread. */ private Finalizer( Class<?> finalizableReferenceClass, ReferenceQueue<Object> queue, PhantomReference<Object> frqReference) { this.queue = queue; this.finalizableReferenceClassReference = new WeakReference<Class<?>>(finalizableReferenceClass); // Keep track of the FRQ that started us so we know when to stop. this.frqReference = frqReference; } /** * Loops continuously, pulling references off the queue and cleaning them up. */ @SuppressWarnings("InfiniteLoopStatement") @Override public void run() { while (true) { try { if (!cleanUp(queue.remove())) { break; } } catch (InterruptedException e) { /* ignore */ } } } /** * Cleans up a single reference. Catches and logs all throwables. * @return true if the caller should continue, false if the associated FinalizableReferenceQueue * is no longer referenced. */ private boolean cleanUp(Reference<?> reference) { Method finalizeReferentMethod = getFinalizeReferentMethod(); if (finalizeReferentMethod == null) { return false; } do { /* * This is for the benefit of phantom references. Weak and soft * references will have already been cleared by this point. */ reference.clear(); if (reference == frqReference) { /* * The client no longer has a reference to the * FinalizableReferenceQueue. We can stop. */ return false; } try { finalizeReferentMethod.invoke(reference); } catch (Throwable t) { logger.log(Level.SEVERE, "Error cleaning up after reference.", t); } /* * Loop as long as we have references available so as not to waste * CPU looking up the Method over and over again. */ } while ((reference = queue.poll()) != null); return true; } /** * Looks up FinalizableReference.finalizeReferent() method. */ private Method getFinalizeReferentMethod() { Class<?> finalizableReferenceClass = finalizableReferenceClassReference.get(); if (finalizableReferenceClass == null) { /* * FinalizableReference's class loader was reclaimed. While there's a * chance that other finalizable references could be enqueued * subsequently (at which point the class loader would be resurrected * by virtue of us having a strong reference to it), we should pretty * much just shut down and make sure we don't keep it alive any longer * than necessary. */ return null; } try { return finalizableReferenceClass.getMethod("finalizeReferent"); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } public static Field getInheritableThreadLocalsField() { try { Field inheritableThreadLocals = Thread.class.getDeclaredField("inheritableThreadLocals"); inheritableThreadLocals.setAccessible(true); return inheritableThreadLocals; } catch (Throwable t) { logger.log(Level.INFO, "Couldn't access Thread.inheritableThreadLocals." + " Reference finalizer threads will inherit thread local" + " values."); return null; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/internal/Finalizer.java
Java
asf20
7,506
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; /** * Low-level, high-performance utility methods related to the {@linkplain Charsets#UTF_8 UTF-8} * character encoding. UTF-8 is defined in section D92 of * <a href="http://www.unicode.org/versions/Unicode6.2.0/ch03.pdf">The Unicode Standard Core * Specification, Chapter 3</a>. * * <p>The variant of UTF-8 implemented by this class is the restricted definition of UTF-8 * introduced in Unicode 3.1. One implication of this is that it rejects * <a href="http://www.unicode.org/versions/corrigendum1.html">"non-shortest form"</a> byte * sequences, even though the JDK decoder may accept them. * * @author Martin Buchholz * @author Clément Roux * @since 16.0 */ @Beta @GwtCompatible public final class Utf8 { /** * Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string, * this method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in * both time and space. * * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired * surrogates) */ public static int encodedLength(CharSequence sequence) { // Warning to maintainers: this implementation is highly optimized. int utf16Length = sequence.length(); int utf8Length = utf16Length; int i = 0; // This loop optimizes for pure ASCII. while (i < utf16Length && sequence.charAt(i) < 0x80) { i++; } // This loop optimizes for chars less than 0x800. for (; i < utf16Length; i++) { char c = sequence.charAt(i); if (c < 0x800) { utf8Length += ((0x7f - c) >>> 31); // branch free! } else { utf8Length += encodedLengthGeneral(sequence, i); break; } } if (utf8Length < utf16Length) { // Necessary and sufficient condition for overflow because of maximum 3x expansion throw new IllegalArgumentException("UTF-8 length does not fit in int: " + (utf8Length + (1L << 32))); } return utf8Length; } private static int encodedLengthGeneral(CharSequence sequence, int start) { int utf16Length = sequence.length(); int utf8Length = 0; for (int i = start; i < utf16Length; i++) { char c = sequence.charAt(i); if (c < 0x800) { utf8Length += (0x7f - c) >>> 31; // branch free! } else { utf8Length += 2; // jdk7+: if (Character.isSurrogate(c)) { if (Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE) { // Check that we have a well-formed surrogate pair. int cp = Character.codePointAt(sequence, i); if (cp < Character.MIN_SUPPLEMENTARY_CODE_POINT) { throw new IllegalArgumentException("Unpaired surrogate at index " + i); } i++; } } } return utf8Length; } /** * Returns {@code true} if {@code bytes} is a <i>well-formed</i> UTF-8 byte sequence according to * Unicode 6.0. Note that this is a stronger criterion than simply whether the bytes can be * decoded. For example, some versions of the JDK decoder will accept "non-shortest form" byte * sequences, but encoding never reproduces these. Such byte sequences are <i>not</i> considered * well-formed. * * <p>This method returns {@code true} if and only if {@code Arrays.equals(bytes, new * String(bytes, UTF_8).getBytes(UTF_8))} does, but is more efficient in both time and space. */ public static boolean isWellFormed(byte[] bytes) { return isWellFormed(bytes, 0, bytes.length); } /** * Returns whether the given byte array slice is a well-formed UTF-8 byte sequence, as defined by * {@link #isWellFormed(byte[])}. Note that this can be false even when {@code * isWellFormed(bytes)} is true. * * @param bytes the input buffer * @param off the offset in the buffer of the first byte to read * @param len the number of bytes to read from the buffer */ public static boolean isWellFormed(byte[] bytes, int off, int len) { int end = off + len; checkPositionIndexes(off, end, bytes.length); // Look for the first non-ASCII character. for (int i = off; i < end; i++) { if (bytes[i] < 0) { return isWellFormedSlowPath(bytes, i, end); } } return true; } private static boolean isWellFormedSlowPath(byte[] bytes, int off, int end) { int index = off; while (true) { int byte1; // Optimize for interior runs of ASCII bytes. do { if (index >= end) { return true; } } while ((byte1 = bytes[index++]) >= 0); if (byte1 < (byte) 0xE0) { // Two-byte form. if (index == end) { return false; } // Simultaneously check for illegal trailing-byte in leading position // and overlong 2-byte form. if (byte1 < (byte) 0xC2 || bytes[index++] > (byte) 0xBF) { return false; } } else if (byte1 < (byte) 0xF0) { // Three-byte form. if (index + 1 >= end) { return false; } int byte2 = bytes[index++]; if (byte2 > (byte) 0xBF // Overlong? 5 most significant bits must not all be zero. || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // Check for illegal surrogate codepoints. || (byte1 == (byte) 0xED && (byte) 0xA0 <= byte2) // Third byte trailing-byte test. || bytes[index++] > (byte) 0xBF) { return false; } } else { // Four-byte form. if (index + 2 >= end) { return false; } int byte2 = bytes[index++]; if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 // || byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 // || byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // Third byte trailing-byte test || bytes[index++] > (byte) 0xBF // Fourth byte trailing-byte test || bytes[index++] > (byte) 0xBF) { return false; } } } } private Utf8() {} }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Utf8.java
Java
asf20
7,069
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; import java.io.Serializable; import java.util.concurrent.TimeUnit; import javax.annotation.Nullable; /** * Useful suppliers. * * <p>All methods return serializable suppliers as long as they're given * serializable parameters. * * @author Laurence Gonsalves * @author Harry Heymann * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public final class Suppliers { private Suppliers() {} /** * Returns a new supplier which is the composition of the provided function * and supplier. In other words, the new supplier's value will be computed by * retrieving the value from {@code supplier}, and then applying * {@code function} to that value. Note that the resulting supplier will not * call {@code supplier} or invoke {@code function} until it is called. */ public static <F, T> Supplier<T> compose( Function<? super F, T> function, Supplier<F> supplier) { Preconditions.checkNotNull(function); Preconditions.checkNotNull(supplier); return new SupplierComposition<F, T>(function, supplier); } private static class SupplierComposition<F, T> implements Supplier<T>, Serializable { final Function<? super F, T> function; final Supplier<F> supplier; SupplierComposition(Function<? super F, T> function, Supplier<F> supplier) { this.function = function; this.supplier = supplier; } @Override public T get() { return function.apply(supplier.get()); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof SupplierComposition) { SupplierComposition<?, ?> that = (SupplierComposition<?, ?>) obj; return function.equals(that.function) && supplier.equals(that.supplier); } return false; } @Override public int hashCode() { return Objects.hashCode(function, supplier); } @Override public String toString() { return "Suppliers.compose(" + function + ", " + supplier + ")"; } private static final long serialVersionUID = 0; } /** * Returns a supplier which caches the instance retrieved during the first * call to {@code get()} and returns that value on subsequent calls to * {@code get()}. See: * <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a> * * <p>The returned supplier is thread-safe. The supplier's serialized form * does not contain the cached value, which will be recalculated when {@code * get()} is called on the reserialized instance. * * <p>If {@code delegate} is an instance created by an earlier call to {@code * memoize}, it is returned directly. */ public static <T> Supplier<T> memoize(Supplier<T> delegate) { return (delegate instanceof MemoizingSupplier) ? delegate : new MemoizingSupplier<T>(Preconditions.checkNotNull(delegate)); } @VisibleForTesting static class MemoizingSupplier<T> implements Supplier<T>, Serializable { final Supplier<T> delegate; transient volatile boolean initialized; // "value" does not need to be volatile; visibility piggy-backs // on volatile read of "initialized". transient T value; MemoizingSupplier(Supplier<T> delegate) { this.delegate = delegate; } @Override public T get() { // A 2-field variant of Double Checked Locking. if (!initialized) { synchronized (this) { if (!initialized) { T t = delegate.get(); value = t; initialized = true; return t; } } } return value; } @Override public String toString() { return "Suppliers.memoize(" + delegate + ")"; } private static final long serialVersionUID = 0; } /** * Returns a supplier that caches the instance supplied by the delegate and * removes the cached value after the specified time has passed. Subsequent * calls to {@code get()} return the cached value if the expiration time has * not passed. After the expiration time, a new value is retrieved, cached, * and returned. See: * <a href="http://en.wikipedia.org/wiki/Memoization">memoization</a> * * <p>The returned supplier is thread-safe. The supplier's serialized form * does not contain the cached value, which will be recalculated when {@code * get()} is called on the reserialized instance. * * @param duration the length of time after a value is created that it * should stop being returned by subsequent {@code get()} calls * @param unit the unit that {@code duration} is expressed in * @throws IllegalArgumentException if {@code duration} is not positive * @since 2.0 */ public static <T> Supplier<T> memoizeWithExpiration( Supplier<T> delegate, long duration, TimeUnit unit) { return new ExpiringMemoizingSupplier<T>(delegate, duration, unit); } @VisibleForTesting static class ExpiringMemoizingSupplier<T> implements Supplier<T>, Serializable { final Supplier<T> delegate; final long durationNanos; transient volatile T value; // The special value 0 means "not yet initialized". transient volatile long expirationNanos; ExpiringMemoizingSupplier( Supplier<T> delegate, long duration, TimeUnit unit) { this.delegate = Preconditions.checkNotNull(delegate); this.durationNanos = unit.toNanos(duration); Preconditions.checkArgument(duration > 0); } @Override public T get() { // Another variant of Double Checked Locking. // // We use two volatile reads. We could reduce this to one by // putting our fields into a holder class, but (at least on x86) // the extra memory consumption and indirection are more // expensive than the extra volatile reads. long nanos = expirationNanos; long now = Platform.systemNanoTime(); if (nanos == 0 || now - nanos >= 0) { synchronized (this) { if (nanos == expirationNanos) { // recheck for lost race T t = delegate.get(); value = t; nanos = now + durationNanos; // In the very unlikely event that nanos is 0, set it to 1; // no one will notice 1 ns of tardiness. expirationNanos = (nanos == 0) ? 1 : nanos; return t; } } } return value; } @Override public String toString() { // This is a little strange if the unit the user provided was not NANOS, // but we don't want to store the unit just for toString return "Suppliers.memoizeWithExpiration(" + delegate + ", " + durationNanos + ", NANOS)"; } private static final long serialVersionUID = 0; } /** * Returns a supplier that always supplies {@code instance}. */ public static <T> Supplier<T> ofInstance(@Nullable T instance) { return new SupplierOfInstance<T>(instance); } private static class SupplierOfInstance<T> implements Supplier<T>, Serializable { final T instance; SupplierOfInstance(@Nullable T instance) { this.instance = instance; } @Override public T get() { return instance; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof SupplierOfInstance) { SupplierOfInstance<?> that = (SupplierOfInstance<?>) obj; return Objects.equal(instance, that.instance); } return false; } @Override public int hashCode() { return Objects.hashCode(instance); } @Override public String toString() { return "Suppliers.ofInstance(" + instance + ")"; } private static final long serialVersionUID = 0; } /** * Returns a supplier whose {@code get()} method synchronizes on * {@code delegate} before calling it, making it thread-safe. */ public static <T> Supplier<T> synchronizedSupplier(Supplier<T> delegate) { return new ThreadSafeSupplier<T>(Preconditions.checkNotNull(delegate)); } private static class ThreadSafeSupplier<T> implements Supplier<T>, Serializable { final Supplier<T> delegate; ThreadSafeSupplier(Supplier<T> delegate) { this.delegate = delegate; } @Override public T get() { synchronized (delegate) { return delegate.get(); } } @Override public String toString() { return "Suppliers.synchronizedSupplier(" + delegate + ")"; } private static final long serialVersionUID = 0; } /** * Returns a function that accepts a supplier and returns the result of * invoking {@link Supplier#get} on that supplier. * * @since 8.0 */ @Beta public static <T> Function<Supplier<T>, T> supplierFunction() { @SuppressWarnings("unchecked") // implementation is "fully variant" SupplierFunction<T> sf = (SupplierFunction<T>) SupplierFunctionImpl.INSTANCE; return sf; } private interface SupplierFunction<T> extends Function<Supplier<T>, T> {} private enum SupplierFunctionImpl implements SupplierFunction<Object> { INSTANCE; // Note: This makes T a "pass-through type" @Override public Object apply(Supplier<Object> input) { return input.get(); } @Override public String toString() { return "Suppliers.supplierFunction()"; } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Suppliers.java
Java
asf20
10,063
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import javax.annotation.Nullable; /** * Determines a true or false value for a given input. * * <p>The {@link Predicates} class provides common predicates and related utilities. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the use of {@code * Predicate}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public interface Predicate<T> { /** * Returns the result of applying this predicate to {@code input}. This method is <i>generally * expected</i>, but not absolutely required, to have the following properties: * * <ul> * <li>Its execution does not cause any observable side effects. * <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal * Objects.equal}{@code (a, b)} implies that {@code predicate.apply(a) == * predicate.apply(b))}. * </ul> * * @throws NullPointerException if {@code input} is null and this predicate does not accept null * arguments */ boolean apply(@Nullable T input); /** * Indicates whether another object is equal to this predicate. * * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}. * However, an implementation may also choose to return {@code true} whenever {@code object} is a * {@link Predicate} that it considers <i>interchangeable</i> with this one. "Interchangeable" * <i>typically</i> means that {@code this.apply(t) == that.apply(t)} for all {@code t} of type * {@code T}). Note that a {@code false} result from this method does not imply that the * predicates are known <i>not</i> to be interchangeable. */ @Override boolean equals(@Nullable Object object); }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Predicate.java
Java
asf20
2,502
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.IOException; import java.util.AbstractList; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import javax.annotation.CheckReturnValue; import javax.annotation.Nullable; /** * An object which joins pieces of text (specified as an array, {@link Iterable}, varargs or even a * {@link Map}) with a separator. It either appends the results to an {@link Appendable} or returns * them as a {@link String}. Example: <pre> {@code * * Joiner joiner = Joiner.on("; ").skipNulls(); * . . . * return joiner.join("Harry", null, "Ron", "Hermione");}</pre> * * <p>This returns the string {@code "Harry; Ron; Hermione"}. Note that all input elements are * converted to strings using {@link Object#toString()} before being appended. * * <p>If neither {@link #skipNulls()} nor {@link #useForNull(String)} is specified, the joining * methods will throw {@link NullPointerException} if any given element is null. * * <p><b>Warning: joiner instances are always immutable</b>; a configuration method such as {@code * useForNull} has no effect on the instance it is invoked on! You must store and use the new joiner * instance returned by the method. This makes joiners thread-safe, and safe to store as {@code * static final} constants. <pre> {@code * * // Bad! Do not do this! * Joiner joiner = Joiner.on(','); * joiner.skipNulls(); // does nothing! * return joiner.join("wrong", null, "wrong");}</pre> * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/StringsExplained#Joiner">{@code Joiner}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible public class Joiner { /** * Returns a joiner which automatically places {@code separator} between consecutive elements. */ public static Joiner on(String separator) { return new Joiner(separator); } /** * Returns a joiner which automatically places {@code separator} between consecutive elements. */ public static Joiner on(char separator) { return new Joiner(String.valueOf(separator)); } private final String separator; private Joiner(String separator) { this.separator = checkNotNull(separator); } private Joiner(Joiner prototype) { this.separator = prototype.separator; } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code appendable}. */ public <A extends Appendable> A appendTo(A appendable, Iterable<?> parts) throws IOException { return appendTo(appendable, parts.iterator()); } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code appendable}. * * @since 11.0 */ public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException { checkNotNull(appendable); if (parts.hasNext()) { appendable.append(toString(parts.next())); while (parts.hasNext()) { appendable.append(separator); appendable.append(toString(parts.next())); } } return appendable; } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code appendable}. */ public final <A extends Appendable> A appendTo(A appendable, Object[] parts) throws IOException { return appendTo(appendable, Arrays.asList(parts)); } /** * Appends to {@code appendable} the string representation of each of the remaining arguments. */ public final <A extends Appendable> A appendTo( A appendable, @Nullable Object first, @Nullable Object second, Object... rest) throws IOException { return appendTo(appendable, iterable(first, second, rest)); } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable, * Iterable)}, except that it does not throw {@link IOException}. */ public final StringBuilder appendTo(StringBuilder builder, Iterable<?> parts) { return appendTo(builder, parts.iterator()); } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable, * Iterable)}, except that it does not throw {@link IOException}. * * @since 11.0 */ public final StringBuilder appendTo(StringBuilder builder, Iterator<?> parts) { try { appendTo((Appendable) builder, parts); } catch (IOException impossible) { throw new AssertionError(impossible); } return builder; } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable, * Iterable)}, except that it does not throw {@link IOException}. */ public final StringBuilder appendTo(StringBuilder builder, Object[] parts) { return appendTo(builder, Arrays.asList(parts)); } /** * Appends to {@code builder} the string representation of each of the remaining arguments. * Identical to {@link #appendTo(Appendable, Object, Object, Object...)}, except that it does not * throw {@link IOException}. */ public final StringBuilder appendTo( StringBuilder builder, @Nullable Object first, @Nullable Object second, Object... rest) { return appendTo(builder, iterable(first, second, rest)); } /** * Returns a string containing the string representation of each of {@code parts}, using the * previously configured separator between each. */ public final String join(Iterable<?> parts) { return join(parts.iterator()); } /** * Returns a string containing the string representation of each of {@code parts}, using the * previously configured separator between each. * * @since 11.0 */ public final String join(Iterator<?> parts) { return appendTo(new StringBuilder(), parts).toString(); } /** * Returns a string containing the string representation of each of {@code parts}, using the * previously configured separator between each. */ public final String join(Object[] parts) { return join(Arrays.asList(parts)); } /** * Returns a string containing the string representation of each argument, using the previously * configured separator between each. */ public final String join(@Nullable Object first, @Nullable Object second, Object... rest) { return join(iterable(first, second, rest)); } /** * Returns a joiner with the same behavior as this one, except automatically substituting {@code * nullText} for any provided null elements. */ @CheckReturnValue public Joiner useForNull(final String nullText) { checkNotNull(nullText); return new Joiner(this) { @Override CharSequence toString(@Nullable Object part) { return (part == null) ? nullText : Joiner.this.toString(part); } @Override public Joiner useForNull(String nullText) { throw new UnsupportedOperationException("already specified useForNull"); } @Override public Joiner skipNulls() { throw new UnsupportedOperationException("already specified useForNull"); } }; } /** * Returns a joiner with the same behavior as this joiner, except automatically skipping over any * provided null elements. */ @CheckReturnValue public Joiner skipNulls() { return new Joiner(this) { @Override public <A extends Appendable> A appendTo(A appendable, Iterator<?> parts) throws IOException { checkNotNull(appendable, "appendable"); checkNotNull(parts, "parts"); while (parts.hasNext()) { Object part = parts.next(); if (part != null) { appendable.append(Joiner.this.toString(part)); break; } } while (parts.hasNext()) { Object part = parts.next(); if (part != null) { appendable.append(separator); appendable.append(Joiner.this.toString(part)); } } return appendable; } @Override public Joiner useForNull(String nullText) { throw new UnsupportedOperationException("already specified skipNulls"); } @Override public MapJoiner withKeyValueSeparator(String kvs) { throw new UnsupportedOperationException("can't use .skipNulls() with maps"); } }; } /** * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as * this {@code Joiner} otherwise. */ @CheckReturnValue public MapJoiner withKeyValueSeparator(String keyValueSeparator) { return new MapJoiner(this, keyValueSeparator); } /** * An object that joins map entries in the same manner as {@code Joiner} joins iterables and * arrays. Like {@code Joiner}, it is thread-safe and immutable. * * <p>In addition to operating on {@code Map} instances, {@code MapJoiner} can operate on {@code * Multimap} entries in two distinct modes: * * <ul> * <li>To output a separate entry for each key-value pair, pass {@code multimap.entries()} to a * {@code MapJoiner} method that accepts entries as input, and receive output of the form * {@code key1=A&key1=B&key2=C}. * <li>To output a single entry for each key, pass {@code multimap.asMap()} to a {@code MapJoiner} * method that accepts a map as input, and receive output of the form {@code * key1=[A, B]&key2=C}. * </ul> * * @since 2.0 (imported from Google Collections Library) */ public static final class MapJoiner { private final Joiner joiner; private final String keyValueSeparator; private MapJoiner(Joiner joiner, String keyValueSeparator) { this.joiner = joiner; // only "this" is ever passed, so don't checkNotNull this.keyValueSeparator = checkNotNull(keyValueSeparator); } /** * Appends the string representation of each entry of {@code map}, using the previously * configured separator and key-value separator, to {@code appendable}. */ public <A extends Appendable> A appendTo(A appendable, Map<?, ?> map) throws IOException { return appendTo(appendable, map.entrySet()); } /** * Appends the string representation of each entry of {@code map}, using the previously * configured separator and key-value separator, to {@code builder}. Identical to {@link * #appendTo(Appendable, Map)}, except that it does not throw {@link IOException}. */ public StringBuilder appendTo(StringBuilder builder, Map<?, ?> map) { return appendTo(builder, map.entrySet()); } /** * Returns a string containing the string representation of each entry of {@code map}, using the * previously configured separator and key-value separator. */ public String join(Map<?, ?> map) { return join(map.entrySet()); } /** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code appendable}. * * @since 10.0 */ @Beta public <A extends Appendable> A appendTo(A appendable, Iterable<? extends Entry<?, ?>> entries) throws IOException { return appendTo(appendable, entries.iterator()); } /** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code appendable}. * * @since 11.0 */ @Beta public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts) throws IOException { checkNotNull(appendable); if (parts.hasNext()) { Entry<?, ?> entry = parts.next(); appendable.append(joiner.toString(entry.getKey())); appendable.append(keyValueSeparator); appendable.append(joiner.toString(entry.getValue())); while (parts.hasNext()) { appendable.append(joiner.separator); Entry<?, ?> e = parts.next(); appendable.append(joiner.toString(e.getKey())); appendable.append(keyValueSeparator); appendable.append(joiner.toString(e.getValue())); } } return appendable; } /** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code builder}. Identical to {@link * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}. * * @since 10.0 */ @Beta public StringBuilder appendTo(StringBuilder builder, Iterable<? extends Entry<?, ?>> entries) { return appendTo(builder, entries.iterator()); } /** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code builder}. Identical to {@link * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}. * * @since 11.0 */ @Beta public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) { try { appendTo((Appendable) builder, entries); } catch (IOException impossible) { throw new AssertionError(impossible); } return builder; } /** * Returns a string containing the string representation of each entry in {@code entries}, using * the previously configured separator and key-value separator. * * @since 10.0 */ @Beta public String join(Iterable<? extends Entry<?, ?>> entries) { return join(entries.iterator()); } /** * Returns a string containing the string representation of each entry in {@code entries}, using * the previously configured separator and key-value separator. * * @since 11.0 */ @Beta public String join(Iterator<? extends Entry<?, ?>> entries) { return appendTo(new StringBuilder(), entries).toString(); } /** * Returns a map joiner with the same behavior as this one, except automatically substituting * {@code nullText} for any provided null keys or values. */ @CheckReturnValue public MapJoiner useForNull(String nullText) { return new MapJoiner(joiner.useForNull(nullText), keyValueSeparator); } } CharSequence toString(Object part) { checkNotNull(part); // checkNotNull for GWT (do not optimize). return (part instanceof CharSequence) ? (CharSequence) part : part.toString(); } private static Iterable<Object> iterable( final Object first, final Object second, final Object[] rest) { checkNotNull(rest); return new AbstractList<Object>() { @Override public int size() { return rest.length + 2; } @Override public Object get(int index) { switch (index) { case 0: return first; case 1: return second; default: return rest[index - 2]; } } }; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Joiner.java
Java
asf20
16,234
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@code Predicate} instances. * * <p>All methods returns serializable predicates as long as they're given * serializable parameters. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the * use of {@code Predicate}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Predicates { private Predicates() {} // TODO(kevinb): considering having these implement a VisitablePredicate // interface which specifies an accept(PredicateVisitor) method. /** * Returns a predicate that always evaluates to {@code true}. */ @GwtCompatible(serializable = true) public static <T> Predicate<T> alwaysTrue() { return ObjectPredicate.ALWAYS_TRUE.withNarrowedType(); } /** * Returns a predicate that always evaluates to {@code false}. */ @GwtCompatible(serializable = true) public static <T> Predicate<T> alwaysFalse() { return ObjectPredicate.ALWAYS_FALSE.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the object reference * being tested is null. */ @GwtCompatible(serializable = true) public static <T> Predicate<T> isNull() { return ObjectPredicate.IS_NULL.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the object reference * being tested is not null. */ @GwtCompatible(serializable = true) public static <T> Predicate<T> notNull() { return ObjectPredicate.NOT_NULL.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the given predicate * evaluates to {@code false}. */ public static <T> Predicate<T> not(Predicate<T> predicate) { return new NotPredicate<T>(predicate); } /** * Returns a predicate that evaluates to {@code true} if each of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a false * predicate is found. It defensively copies the iterable passed in, so future * changes to it won't alter the behavior of this predicate. If {@code * components} is empty, the returned predicate will always evaluate to {@code * true}. */ public static <T> Predicate<T> and( Iterable<? extends Predicate<? super T>> components) { return new AndPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if each of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a false * predicate is found. It defensively copies the array passed in, so future * changes to it won't alter the behavior of this predicate. If {@code * components} is empty, the returned predicate will always evaluate to {@code * true}. */ public static <T> Predicate<T> and(Predicate<? super T>... components) { return new AndPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if both of its * components evaluate to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a false * predicate is found. */ public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second) { return new AndPredicate<T>(Predicates.<T>asList( checkNotNull(first), checkNotNull(second))); } /** * Returns a predicate that evaluates to {@code true} if any one of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a * true predicate is found. It defensively copies the iterable passed in, so * future changes to it won't alter the behavior of this predicate. If {@code * components} is empty, the returned predicate will always evaluate to {@code * false}. */ public static <T> Predicate<T> or( Iterable<? extends Predicate<? super T>> components) { return new OrPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if any one of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a * true predicate is found. It defensively copies the array passed in, so * future changes to it won't alter the behavior of this predicate. If {@code * components} is empty, the returned predicate will always evaluate to {@code * false}. */ public static <T> Predicate<T> or(Predicate<? super T>... components) { return new OrPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if either of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a * true predicate is found. */ public static <T> Predicate<T> or( Predicate<? super T> first, Predicate<? super T> second) { return new OrPredicate<T>(Predicates.<T>asList( checkNotNull(first), checkNotNull(second))); } /** * Returns a predicate that evaluates to {@code true} if the object being * tested {@code equals()} the given target or both are null. */ public static <T> Predicate<T> equalTo(@Nullable T target) { return (target == null) ? Predicates.<T>isNull() : new IsEqualToPredicate<T>(target); } /** * Returns a predicate that evaluates to {@code true} if the object being * tested is an instance of the given class. If the object being tested * is {@code null} this predicate evaluates to {@code false}. * * <p>If you want to filter an {@code Iterable} to narrow its type, consider * using {@link com.google.common.collect.Iterables#filter(Iterable, Class)} * in preference. * * <p><b>Warning:</b> contrary to the typical assumptions about predicates (as * documented at {@link Predicate#apply}), the returned predicate may not be * <i>consistent with equals</i>. For example, {@code * instanceOf(ArrayList.class)} will yield different results for the two equal * instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}. */ @GwtIncompatible("Class.isInstance") public static Predicate<Object> instanceOf(Class<?> clazz) { return new InstanceOfPredicate(clazz); } /** * Returns a predicate that evaluates to {@code true} if the class being * tested is assignable from the given class. The returned predicate * does not allow null inputs. * * @since 10.0 */ @GwtIncompatible("Class.isAssignableFrom") @Beta public static Predicate<Class<?>> assignableFrom(Class<?> clazz) { return new AssignableFromPredicate(clazz); } /** * Returns a predicate that evaluates to {@code true} if the object reference * being tested is a member of the given collection. It does not defensively * copy the collection passed in, so future changes to it will alter the * behavior of the predicate. * * <p>This method can technically accept any {@code Collection<?>}, but using * a typed collection helps prevent bugs. This approach doesn't block any * potential users since it is always possible to use {@code * Predicates.<Object>in()}. * * @param target the collection that may contain the function input */ public static <T> Predicate<T> in(Collection<? extends T> target) { return new InPredicate<T>(target); } /** * Returns the composition of a function and a predicate. For every {@code x}, * the generated predicate returns {@code predicate(function(x))}. * * @return the composition of the provided function and predicate */ public static <A, B> Predicate<A> compose( Predicate<B> predicate, Function<A, ? extends B> function) { return new CompositionPredicate<A, B>(predicate, function); } /** * Returns a predicate that evaluates to {@code true} if the * {@code CharSequence} being tested contains any match for the given * regular expression pattern. The test used is equivalent to * {@code Pattern.compile(pattern).matcher(arg).find()} * * @throws java.util.regex.PatternSyntaxException if the pattern is invalid * @since 3.0 */ @GwtIncompatible(value = "java.util.regex.Pattern") public static Predicate<CharSequence> containsPattern(String pattern) { return new ContainsPatternFromStringPredicate(pattern); } /** * Returns a predicate that evaluates to {@code true} if the * {@code CharSequence} being tested contains any match for the given * regular expression pattern. The test used is equivalent to * {@code pattern.matcher(arg).find()} * * @since 3.0 */ @GwtIncompatible(value = "java.util.regex.Pattern") public static Predicate<CharSequence> contains(Pattern pattern) { return new ContainsPatternPredicate(pattern); } // End public API, begin private implementation classes. // Package private for GWT serialization. enum ObjectPredicate implements Predicate<Object> { /** @see Predicates#alwaysTrue() */ ALWAYS_TRUE { @Override public boolean apply(@Nullable Object o) { return true; } @Override public String toString() { return "Predicates.alwaysTrue()"; } }, /** @see Predicates#alwaysFalse() */ ALWAYS_FALSE { @Override public boolean apply(@Nullable Object o) { return false; } @Override public String toString() { return "Predicates.alwaysFalse()"; } }, /** @see Predicates#isNull() */ IS_NULL { @Override public boolean apply(@Nullable Object o) { return o == null; } @Override public String toString() { return "Predicates.isNull()"; } }, /** @see Predicates#notNull() */ NOT_NULL { @Override public boolean apply(@Nullable Object o) { return o != null; } @Override public String toString() { return "Predicates.notNull()"; } }; @SuppressWarnings("unchecked") // safe contravariant cast <T> Predicate<T> withNarrowedType() { return (Predicate<T>) this; } } /** @see Predicates#not(Predicate) */ private static class NotPredicate<T> implements Predicate<T>, Serializable { final Predicate<T> predicate; NotPredicate(Predicate<T> predicate) { this.predicate = checkNotNull(predicate); } @Override public boolean apply(@Nullable T t) { return !predicate.apply(t); } @Override public int hashCode() { return ~predicate.hashCode(); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof NotPredicate) { NotPredicate<?> that = (NotPredicate<?>) obj; return predicate.equals(that.predicate); } return false; } @Override public String toString() { return "Predicates.not(" + predicate.toString() + ")"; } private static final long serialVersionUID = 0; } private static final Joiner COMMA_JOINER = Joiner.on(','); /** @see Predicates#and(Iterable) */ private static class AndPredicate<T> implements Predicate<T>, Serializable { private final List<? extends Predicate<? super T>> components; private AndPredicate(List<? extends Predicate<? super T>> components) { this.components = components; } @Override public boolean apply(@Nullable T t) { // Avoid using the Iterator to avoid generating garbage (issue 820). for (int i = 0; i < components.size(); i++) { if (!components.get(i).apply(t)) { return false; } } return true; } @Override public int hashCode() { // add a random number to avoid collisions with OrPredicate return components.hashCode() + 0x12472c2c; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof AndPredicate) { AndPredicate<?> that = (AndPredicate<?>) obj; return components.equals(that.components); } return false; } @Override public String toString() { return "Predicates.and(" + COMMA_JOINER.join(components) + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#or(Iterable) */ private static class OrPredicate<T> implements Predicate<T>, Serializable { private final List<? extends Predicate<? super T>> components; private OrPredicate(List<? extends Predicate<? super T>> components) { this.components = components; } @Override public boolean apply(@Nullable T t) { // Avoid using the Iterator to avoid generating garbage (issue 820). for (int i = 0; i < components.size(); i++) { if (components.get(i).apply(t)) { return true; } } return false; } @Override public int hashCode() { // add a random number to avoid collisions with AndPredicate return components.hashCode() + 0x053c91cf; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof OrPredicate) { OrPredicate<?> that = (OrPredicate<?>) obj; return components.equals(that.components); } return false; } @Override public String toString() { return "Predicates.or(" + COMMA_JOINER.join(components) + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#equalTo(Object) */ private static class IsEqualToPredicate<T> implements Predicate<T>, Serializable { private final T target; private IsEqualToPredicate(T target) { this.target = target; } @Override public boolean apply(T t) { return target.equals(t); } @Override public int hashCode() { return target.hashCode(); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof IsEqualToPredicate) { IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj; return target.equals(that.target); } return false; } @Override public String toString() { return "Predicates.equalTo(" + target + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#instanceOf(Class) */ @GwtIncompatible("Class.isInstance") private static class InstanceOfPredicate implements Predicate<Object>, Serializable { private final Class<?> clazz; private InstanceOfPredicate(Class<?> clazz) { this.clazz = checkNotNull(clazz); } @Override public boolean apply(@Nullable Object o) { return clazz.isInstance(o); } @Override public int hashCode() { return clazz.hashCode(); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof InstanceOfPredicate) { InstanceOfPredicate that = (InstanceOfPredicate) obj; return clazz == that.clazz; } return false; } @Override public String toString() { return "Predicates.instanceOf(" + clazz.getName() + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#assignableFrom(Class) */ @GwtIncompatible("Class.isAssignableFrom") private static class AssignableFromPredicate implements Predicate<Class<?>>, Serializable { private final Class<?> clazz; private AssignableFromPredicate(Class<?> clazz) { this.clazz = checkNotNull(clazz); } @Override public boolean apply(Class<?> input) { return clazz.isAssignableFrom(input); } @Override public int hashCode() { return clazz.hashCode(); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof AssignableFromPredicate) { AssignableFromPredicate that = (AssignableFromPredicate) obj; return clazz == that.clazz; } return false; } @Override public String toString() { return "Predicates.assignableFrom(" + clazz.getName() + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#in(Collection) */ private static class InPredicate<T> implements Predicate<T>, Serializable { private final Collection<?> target; private InPredicate(Collection<?> target) { this.target = checkNotNull(target); } @Override public boolean apply(@Nullable T t) { try { return target.contains(t); } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof InPredicate) { InPredicate<?> that = (InPredicate<?>) obj; return target.equals(that.target); } return false; } @Override public int hashCode() { return target.hashCode(); } @Override public String toString() { return "Predicates.in(" + target + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#compose(Predicate, Function) */ private static class CompositionPredicate<A, B> implements Predicate<A>, Serializable { final Predicate<B> p; final Function<A, ? extends B> f; private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) { this.p = checkNotNull(p); this.f = checkNotNull(f); } @Override public boolean apply(@Nullable A a) { return p.apply(f.apply(a)); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof CompositionPredicate) { CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj; return f.equals(that.f) && p.equals(that.p); } return false; } @Override public int hashCode() { return f.hashCode() ^ p.hashCode(); } @Override public String toString() { return p.toString() + "(" + f.toString() + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#contains(Pattern) */ @GwtIncompatible("Only used by other GWT-incompatible code.") private static class ContainsPatternPredicate implements Predicate<CharSequence>, Serializable { final Pattern pattern; ContainsPatternPredicate(Pattern pattern) { this.pattern = checkNotNull(pattern); } @Override public boolean apply(CharSequence t) { return pattern.matcher(t).find(); } @Override public int hashCode() { // Pattern uses Object.hashCode, so we have to reach // inside to build a hashCode consistent with equals. return Objects.hashCode(pattern.pattern(), pattern.flags()); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof ContainsPatternPredicate) { ContainsPatternPredicate that = (ContainsPatternPredicate) obj; // Pattern uses Object (identity) equality, so we have to reach // inside to compare individual fields. return Objects.equal(pattern.pattern(), that.pattern.pattern()) && Objects.equal(pattern.flags(), that.pattern.flags()); } return false; } @Override public String toString() { String patternString = Objects.toStringHelper(pattern) .add("pattern", pattern.pattern()) .add("pattern.flags", pattern.flags()) .toString(); return "Predicates.contains(" + patternString + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#containsPattern(String) */ @GwtIncompatible("Only used by other GWT-incompatible code.") private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate { ContainsPatternFromStringPredicate(String string) { super(Pattern.compile(string)); } @Override public String toString() { return "Predicates.containsPattern(" + pattern.pattern() + ")"; } private static final long serialVersionUID = 0; } private static <T> List<Predicate<? super T>> asList( Predicate<? super T> first, Predicate<? super T> second) { // TODO(kevinb): understand why we still get a warning despite @SafeVarargs! return Arrays.<Predicate<? super T>>asList(first, second); } private static <T> List<T> defensiveCopy(T... array) { return defensiveCopy(Arrays.asList(array)); } static <T> List<T> defensiveCopy(Iterable<T> iterable) { ArrayList<T> list = new ArrayList<T>(); for (T element : iterable) { list.add(checkNotNull(element)); } return list; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Predicates.java
Java
asf20
21,823
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.VisibleForTesting; import java.io.Closeable; import java.io.FileNotFoundException; import java.io.IOException; import java.lang.ref.PhantomReference; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.reflect.Method; import java.net.URL; import java.net.URLClassLoader; import java.util.logging.Level; import java.util.logging.Logger; /** * A reference queue with an associated background thread that dequeues references and invokes * {@link FinalizableReference#finalizeReferent()} on them. * * <p>Keep a strong reference to this object until all of the associated referents have been * finalized. If this object is garbage collected earlier, the backing thread will not invoke {@code * finalizeReferent()} on the remaining references. * * <p>As an example of how this is used, imagine you have a class {@code MyServer} that creates a * a {@link java.net.ServerSocket ServerSocket}, and you would like to ensure that the * {@code ServerSocket} is closed even if the {@code MyServer} object is garbage-collected without * calling its {@code close} method. You <em>could</em> use a finalizer to accomplish this, but * that has a number of well-known problems. Here is how you might use this class instead: * * <pre> * public class MyServer implements Closeable { * private static final FinalizableReferenceQueue frq = new FinalizableReferenceQueue(); * // You might also share this between several objects. * * private static final Set&lt;Reference&lt;?>> references = Sets.newConcurrentHashSet(); * // This ensures that the FinalizablePhantomReference itself is not garbage-collected. * * private final ServerSocket serverSocket; * * private MyServer(...) { * ... * this.serverSocket = new ServerSocket(...); * ... * } * * public static MyServer create(...) { * MyServer myServer = new MyServer(...); * final ServerSocket serverSocket = myServer.serverSocket; * Reference&lt;?> reference = new FinalizablePhantomReference&lt;MyServer>(myServer, frq) { * &#64;Override public void finalizeReferent() { * references.remove(this): * if (!serverSocket.isClosed()) { * ...log a message about how nobody called close()... * try { * serverSocket.close(); * } catch (IOException e) { * ... * } * } * } * }; * references.add(reference); * return myServer; * } * * &#64;Override public void close() { * serverSocket.close(); * } * } * </pre> * * @author Bob Lee * @since 2.0 (imported from Google Collections Library) */ public class FinalizableReferenceQueue implements Closeable { /* * The Finalizer thread keeps a phantom reference to this object. When the client (for example, a * map built by MapMaker) no longer has a strong reference to this object, the garbage collector * will reclaim it and enqueue the phantom reference. The enqueued reference will trigger the * Finalizer to stop. * * If this library is loaded in the system class loader, FinalizableReferenceQueue can load * Finalizer directly with no problems. * * If this library is loaded in an application class loader, it's important that Finalizer not * have a strong reference back to the class loader. Otherwise, you could have a graph like this: * * Finalizer Thread runs instance of -> Finalizer.class loaded by -> Application class loader * which loaded -> ReferenceMap.class which has a static -> FinalizableReferenceQueue instance * * Even if no other references to classes from the application class loader remain, the Finalizer * thread keeps an indirect strong reference to the queue in ReferenceMap, which keeps the * Finalizer running, and as a result, the application class loader can never be reclaimed. * * This means that dynamically loaded web applications and OSGi bundles can't be unloaded. * * If the library is loaded in an application class loader, we try to break the cycle by loading * Finalizer in its own independent class loader: * * System class loader -> Application class loader -> ReferenceMap -> FinalizableReferenceQueue * -> etc. -> Decoupled class loader -> Finalizer * * Now, Finalizer no longer keeps an indirect strong reference to the static * FinalizableReferenceQueue field in ReferenceMap. The application class loader can be reclaimed * at which point the Finalizer thread will stop and its decoupled class loader can also be * reclaimed. * * If any of this fails along the way, we fall back to loading Finalizer directly in the * application class loader. */ private static final Logger logger = Logger.getLogger(FinalizableReferenceQueue.class.getName()); private static final String FINALIZER_CLASS_NAME = "com.google.common.base.internal.Finalizer"; /** Reference to Finalizer.startFinalizer(). */ private static final Method startFinalizer; static { Class<?> finalizer = loadFinalizer( new SystemLoader(), new DecoupledLoader(), new DirectLoader()); startFinalizer = getStartFinalizer(finalizer); } /** * The actual reference queue that our background thread will poll. */ final ReferenceQueue<Object> queue; final PhantomReference<Object> frqRef; /** * Whether or not the background thread started successfully. */ final boolean threadStarted; /** * Constructs a new queue. */ public FinalizableReferenceQueue() { // We could start the finalizer lazily, but I'd rather it blow up early. queue = new ReferenceQueue<Object>(); frqRef = new PhantomReference<Object>(this, queue); boolean threadStarted = false; try { startFinalizer.invoke(null, FinalizableReference.class, queue, frqRef); threadStarted = true; } catch (IllegalAccessException impossible) { throw new AssertionError(impossible); // startFinalizer() is public } catch (Throwable t) { logger.log(Level.INFO, "Failed to start reference finalizer thread." + " Reference cleanup will only occur when new references are created.", t); } this.threadStarted = threadStarted; } @Override public void close() { frqRef.enqueue(); cleanUp(); } /** * Repeatedly dequeues references from the queue and invokes {@link * FinalizableReference#finalizeReferent()} on them until the queue is empty. This method is a * no-op if the background thread was created successfully. */ void cleanUp() { if (threadStarted) { return; } Reference<?> reference; while ((reference = queue.poll()) != null) { /* * This is for the benefit of phantom references. Weak and soft references will have already * been cleared by this point. */ reference.clear(); try { ((FinalizableReference) reference).finalizeReferent(); } catch (Throwable t) { logger.log(Level.SEVERE, "Error cleaning up after reference.", t); } } } /** * Iterates through the given loaders until it finds one that can load Finalizer. * * @return Finalizer.class */ private static Class<?> loadFinalizer(FinalizerLoader... loaders) { for (FinalizerLoader loader : loaders) { Class<?> finalizer = loader.loadFinalizer(); if (finalizer != null) { return finalizer; } } throw new AssertionError(); } /** * Loads Finalizer.class. */ interface FinalizerLoader { /** * Returns Finalizer.class or null if this loader shouldn't or can't load it. * * @throws SecurityException if we don't have the appropriate privileges */ Class<?> loadFinalizer(); } /** * Tries to load Finalizer from the system class loader. If Finalizer is in the system class path, * we needn't create a separate loader. */ static class SystemLoader implements FinalizerLoader { // This is used by the ClassLoader-leak test in FinalizableReferenceQueueTest to disable // finding Finalizer on the system class path even if it is there. @VisibleForTesting static boolean disabled; @Override public Class<?> loadFinalizer() { if (disabled) { return null; } ClassLoader systemLoader; try { systemLoader = ClassLoader.getSystemClassLoader(); } catch (SecurityException e) { logger.info("Not allowed to access system class loader."); return null; } if (systemLoader != null) { try { return systemLoader.loadClass(FINALIZER_CLASS_NAME); } catch (ClassNotFoundException e) { // Ignore. Finalizer is simply in a child class loader. return null; } } else { return null; } } } /** * Try to load Finalizer in its own class loader. If Finalizer's thread had a direct reference to * our class loader (which could be that of a dynamically loaded web application or OSGi bundle), * it would prevent our class loader from getting garbage collected. */ static class DecoupledLoader implements FinalizerLoader { private static final String LOADING_ERROR = "Could not load Finalizer in its own class loader." + "Loading Finalizer in the current class loader instead. As a result, you will not be able" + "to garbage collect this class loader. To support reclaiming this class loader, either" + "resolve the underlying issue, or move Google Collections to your system class path."; @Override public Class<?> loadFinalizer() { try { /* * We use URLClassLoader because it's the only concrete class loader implementation in the * JDK. If we used our own ClassLoader subclass, Finalizer would indirectly reference this * class loader: * * Finalizer.class -> CustomClassLoader -> CustomClassLoader.class -> This class loader * * System class loader will (and must) be the parent. */ ClassLoader finalizerLoader = newLoader(getBaseUrl()); return finalizerLoader.loadClass(FINALIZER_CLASS_NAME); } catch (Exception e) { logger.log(Level.WARNING, LOADING_ERROR, e); return null; } } /** * Gets URL for base of path containing Finalizer.class. */ URL getBaseUrl() throws IOException { // Find URL pointing to Finalizer.class file. String finalizerPath = FINALIZER_CLASS_NAME.replace('.', '/') + ".class"; URL finalizerUrl = getClass().getClassLoader().getResource(finalizerPath); if (finalizerUrl == null) { throw new FileNotFoundException(finalizerPath); } // Find URL pointing to base of class path. String urlString = finalizerUrl.toString(); if (!urlString.endsWith(finalizerPath)) { throw new IOException("Unsupported path style: " + urlString); } urlString = urlString.substring(0, urlString.length() - finalizerPath.length()); return new URL(finalizerUrl, urlString); } /** Creates a class loader with the given base URL as its classpath. */ URLClassLoader newLoader(URL base) { // We use the bootstrap class loader as the parent because Finalizer by design uses // only standard Java classes. That also means that FinalizableReferenceQueueTest // doesn't pick up the wrong version of the Finalizer class. return new URLClassLoader(new URL[] {base}, null); } } /** * Loads Finalizer directly using the current class loader. We won't be able to garbage collect * this class loader, but at least the world doesn't end. */ static class DirectLoader implements FinalizerLoader { @Override public Class<?> loadFinalizer() { try { return Class.forName(FINALIZER_CLASS_NAME); } catch (ClassNotFoundException e) { throw new AssertionError(e); } } } /** * Looks up Finalizer.startFinalizer(). */ static Method getStartFinalizer(Class<?> finalizer) { try { return finalizer.getMethod( "startFinalizer", Class.class, ReferenceQueue.class, PhantomReference.class); } catch (NoSuchMethodException e) { throw new AssertionError(e); } } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/FinalizableReferenceQueue.java
Java
asf20
13,032
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Iterator; import java.util.Set; import javax.annotation.Nullable; /** * An immutable object that may contain a non-null reference to another object. Each * instance of this type either contains a non-null reference, or contains nothing (in * which case we say that the reference is "absent"); it is never said to "contain {@code * null}". * * <p>A non-null {@code Optional<T>} reference can be used as a replacement for a nullable * {@code T} reference. It allows you to represent "a {@code T} that must be present" and * a "a {@code T} that might be absent" as two distinct types in your program, which can * aid clarity. * * <p>Some uses of this class include * * <ul> * <li>As a method return type, as an alternative to returning {@code null} to indicate * that no value was available * <li>To distinguish between "unknown" (for example, not present in a map) and "known to * have no value" (present in the map, with value {@code Optional.absent()}) * <li>To wrap nullable references for storage in a collection that does not support * {@code null} (though there are * <a href="http://code.google.com/p/guava-libraries/wiki/LivingWithNullHostileCollections"> * several other approaches to this</a> that should be considered first) * </ul> * * <p>A common alternative to using this class is to find or create a suitable * <a href="http://en.wikipedia.org/wiki/Null_Object_pattern">null object</a> for the * type in question. * * <p>This class is not intended as a direct analogue of any existing "option" or "maybe" * construct from other programming environments, though it may bear some similarities. * * <p>See the Guava User Guide article on <a * href="http://code.google.com/p/guava-libraries/wiki/UsingAndAvoidingNullExplained#Optional"> * using {@code Optional}</a>. * * @param <T> the type of instance that can be contained. {@code Optional} is naturally * covariant on this type, so it is safe to cast an {@code Optional<T>} to {@code * Optional<S>} for any supertype {@code S} of {@code T}. * @author Kurt Alfred Kluever * @author Kevin Bourrillion * @since 10.0 */ @GwtCompatible(serializable = true) public abstract class Optional<T> implements Serializable { /** * Returns an {@code Optional} instance with no contained reference. */ public static <T> Optional<T> absent() { return Absent.withType(); } /** * Returns an {@code Optional} instance containing the given non-null reference. */ public static <T> Optional<T> of(T reference) { return new Present<T>(checkNotNull(reference)); } /** * If {@code nullableReference} is non-null, returns an {@code Optional} instance containing that * reference; otherwise returns {@link Optional#absent}. */ public static <T> Optional<T> fromNullable(@Nullable T nullableReference) { return (nullableReference == null) ? Optional.<T>absent() : new Present<T>(nullableReference); } Optional() {} /** * Returns {@code true} if this holder contains a (non-null) instance. */ public abstract boolean isPresent(); /** * Returns the contained instance, which must be present. If the instance might be * absent, use {@link #or(Object)} or {@link #orNull} instead. * * @throws IllegalStateException if the instance is absent ({@link #isPresent} returns * {@code false}) */ public abstract T get(); /** * Returns the contained instance if it is present; {@code defaultValue} otherwise. If * no default value should be required because the instance is known to be present, use * {@link #get()} instead. For a default value of {@code null}, use {@link #orNull}. * * <p>Note about generics: The signature {@code public T or(T defaultValue)} is overly * restrictive. However, the ideal signature, {@code public <S super T> S or(S)}, is not legal * Java. As a result, some sensible operations involving subtypes are compile errors: * <pre> {@code * * Optional<Integer> optionalInt = getSomeOptionalInt(); * Number value = optionalInt.or(0.5); // error * * FluentIterable<? extends Number> numbers = getSomeNumbers(); * Optional<? extends Number> first = numbers.first(); * Number value = first.or(0.5); // error}</pre> * * <p>As a workaround, it is always safe to cast an {@code Optional<? extends T>} to {@code * Optional<T>}. Casting either of the above example {@code Optional} instances to {@code * Optional<Number>} (where {@code Number} is the desired output type) solves the problem: * <pre> {@code * * Optional<Number> optionalInt = (Optional) getSomeOptionalInt(); * Number value = optionalInt.or(0.5); // fine * * FluentIterable<? extends Number> numbers = getSomeNumbers(); * Optional<Number> first = (Optional) numbers.first(); * Number value = first.or(0.5); // fine}</pre> */ public abstract T or(T defaultValue); /** * Returns this {@code Optional} if it has a value present; {@code secondChoice} * otherwise. */ public abstract Optional<T> or(Optional<? extends T> secondChoice); /** * Returns the contained instance if it is present; {@code supplier.get()} otherwise. If the * supplier returns {@code null}, a {@link NullPointerException} is thrown. * * @throws NullPointerException if the supplier returns {@code null} */ @Beta public abstract T or(Supplier<? extends T> supplier); /** * Returns the contained instance if it is present; {@code null} otherwise. If the * instance is known to be present, use {@link #get()} instead. */ @Nullable public abstract T orNull(); /** * Returns an immutable singleton {@link Set} whose only element is the contained instance * if it is present; an empty immutable {@link Set} otherwise. * * @since 11.0 */ public abstract Set<T> asSet(); /** * If the instance is present, it is transformed with the given {@link Function}; otherwise, * {@link Optional#absent} is returned. If the function returns {@code null}, a * {@link NullPointerException} is thrown. * * @throws NullPointerException if the function returns {@code null} * * @since 12.0 */ public abstract <V> Optional<V> transform(Function<? super T, V> function); /** * Returns {@code true} if {@code object} is an {@code Optional} instance, and either * the contained references are {@linkplain Object#equals equal} to each other or both * are absent. Note that {@code Optional} instances of differing parameterized types can * be equal. */ @Override public abstract boolean equals(@Nullable Object object); /** * Returns a hash code for this instance. */ @Override public abstract int hashCode(); /** * Returns a string representation for this instance. The form of this string * representation is unspecified. */ @Override public abstract String toString(); /** * Returns the value of each present instance from the supplied {@code optionals}, in order, * skipping over occurrences of {@link Optional#absent}. Iterators are unmodifiable and are * evaluated lazily. * * @since 11.0 (generics widened in 13.0) */ @Beta public static <T> Iterable<T> presentInstances( final Iterable<? extends Optional<? extends T>> optionals) { checkNotNull(optionals); return new Iterable<T>() { @Override public Iterator<T> iterator() { return new AbstractIterator<T>() { private final Iterator<? extends Optional<? extends T>> iterator = checkNotNull(optionals.iterator()); @Override protected T computeNext() { while (iterator.hasNext()) { Optional<? extends T> optional = iterator.next(); if (optional.isPresent()) { return optional.get(); } } return endOfData(); } }; } }; } private static final long serialVersionUID = 0; }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Optional.java
Java
asf20
8,891
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import javax.annotation.CheckReturnValue; /** * Static methods pertaining to ASCII characters (those in the range of values * {@code 0x00} through {@code 0x7F}), and to strings containing such * characters. * * <p>ASCII utilities also exist in other classes of this package: * <ul> * <!-- TODO(kevinb): how can we make this not produce a warning when building gwt javadoc? --> * <li>{@link Charsets#US_ASCII} specifies the {@code Charset} of ASCII characters. * <li>{@link CharMatcher#ASCII} matches ASCII characters and provides text processing methods * which operate only on the ASCII characters of a string. * </ul> * * @author Craig Berry * @author Gregory Kick * @since 7.0 */ @GwtCompatible public final class Ascii { private Ascii() {} /* The ASCII control characters, per RFC 20. */ /** * Null ('\0'): The all-zeros character which may serve to accomplish * time fill and media fill. Normally used as a C string terminator. * <p>Although RFC 20 names this as "Null", note that it is distinct * from the C/C++ "NULL" pointer. * * @since 8.0 */ public static final byte NUL = 0; /** * Start of Heading: A communication control character used at * the beginning of a sequence of characters which constitute a * machine-sensible address or routing information. Such a sequence is * referred to as the "heading." An STX character has the effect of * terminating a heading. * * @since 8.0 */ public static final byte SOH = 1; /** * Start of Text: A communication control character which * precedes a sequence of characters that is to be treated as an entity * and entirely transmitted through to the ultimate destination. Such a * sequence is referred to as "text." STX may be used to terminate a * sequence of characters started by SOH. * * @since 8.0 */ public static final byte STX = 2; /** * End of Text: A communication control character used to * terminate a sequence of characters started with STX and transmitted * as an entity. * * @since 8.0 */ public static final byte ETX = 3; /** * End of Transmission: A communication control character used * to indicate the conclusion of a transmission, which may have * contained one or more texts and any associated headings. * * @since 8.0 */ public static final byte EOT = 4; /** * Enquiry: A communication control character used in data * communication systems as a request for a response from a remote * station. It may be used as a "Who Are You" (WRU) to obtain * identification, or may be used to obtain station status, or both. * * @since 8.0 */ public static final byte ENQ = 5; /** * Acknowledge: A communication control character transmitted * by a receiver as an affirmative response to a sender. * * @since 8.0 */ public static final byte ACK = 6; /** * Bell ('\a'): A character for use when there is a need to call for * human attention. It may control alarm or attention devices. * * @since 8.0 */ public static final byte BEL = 7; /** * Backspace ('\b'): A format effector which controls the movement of * the printing position one printing space backward on the same * printing line. (Applicable also to display devices.) * * @since 8.0 */ public static final byte BS = 8; /** * Horizontal Tabulation ('\t'): A format effector which controls the * movement of the printing position to the next in a series of * predetermined positions along the printing line. (Applicable also to * display devices and the skip function on punched cards.) * * @since 8.0 */ public static final byte HT = 9; /** * Line Feed ('\n'): A format effector which controls the movement of * the printing position to the next printing line. (Applicable also to * display devices.) Where appropriate, this character may have the * meaning "New Line" (NL), a format effector which controls the * movement of the printing point to the first printing position on the * next printing line. Use of this convention requires agreement * between sender and recipient of data. * * @since 8.0 */ public static final byte LF = 10; /** * Alternate name for {@link #LF}. ({@code LF} is preferred.) * * @since 8.0 */ public static final byte NL = 10; /** * Vertical Tabulation ('\v'): A format effector which controls the * movement of the printing position to the next in a series of * predetermined printing lines. (Applicable also to display devices.) * * @since 8.0 */ public static final byte VT = 11; /** * Form Feed ('\f'): A format effector which controls the movement of * the printing position to the first pre-determined printing line on * the next form or page. (Applicable also to display devices.) * * @since 8.0 */ public static final byte FF = 12; /** * Carriage Return ('\r'): A format effector which controls the * movement of the printing position to the first printing position on * the same printing line. (Applicable also to display devices.) * * @since 8.0 */ public static final byte CR = 13; /** * Shift Out: A control character indicating that the code * combinations which follow shall be interpreted as outside of the * character set of the standard code table until a Shift In character * is reached. * * @since 8.0 */ public static final byte SO = 14; /** * Shift In: A control character indicating that the code * combinations which follow shall be interpreted according to the * standard code table. * * @since 8.0 */ public static final byte SI = 15; /** * Data Link Escape: A communication control character which * will change the meaning of a limited number of contiguously following * characters. It is used exclusively to provide supplementary controls * in data communication networks. * * @since 8.0 */ public static final byte DLE = 16; /** * Device Control 1. Characters for the control * of ancillary devices associated with data processing or * telecommunication systems, more especially switching devices "on" or * "off." (If a single "stop" control is required to interrupt or turn * off ancillary devices, DC4 is the preferred assignment.) * * @since 8.0 */ public static final byte DC1 = 17; // aka XON /** * Transmission On: Although originally defined as DC1, this ASCII * control character is now better known as the XON code used for software * flow control in serial communications. The main use is restarting * the transmission after the communication has been stopped by the XOFF * control code. * * @since 8.0 */ public static final byte XON = 17; // aka DC1 /** * Device Control 2. Characters for the control * of ancillary devices associated with data processing or * telecommunication systems, more especially switching devices "on" or * "off." (If a single "stop" control is required to interrupt or turn * off ancillary devices, DC4 is the preferred assignment.) * * @since 8.0 */ public static final byte DC2 = 18; /** * Device Control 3. Characters for the control * of ancillary devices associated with data processing or * telecommunication systems, more especially switching devices "on" or * "off." (If a single "stop" control is required to interrupt or turn * off ancillary devices, DC4 is the preferred assignment.) * * @since 8.0 */ public static final byte DC3 = 19; // aka XOFF /** * Transmission off. See {@link #XON} for explanation. * * @since 8.0 */ public static final byte XOFF = 19; // aka DC3 /** * Device Control 4. Characters for the control * of ancillary devices associated with data processing or * telecommunication systems, more especially switching devices "on" or * "off." (If a single "stop" control is required to interrupt or turn * off ancillary devices, DC4 is the preferred assignment.) * * @since 8.0 */ public static final byte DC4 = 20; /** * Negative Acknowledge: A communication control character * transmitted by a receiver as a negative response to the sender. * * @since 8.0 */ public static final byte NAK = 21; /** * Synchronous Idle: A communication control character used by * a synchronous transmission system in the absence of any other * character to provide a signal from which synchronism may be achieved * or retained. * * @since 8.0 */ public static final byte SYN = 22; /** * End of Transmission Block: A communication control character * used to indicate the end of a block of data for communication * purposes. ETB is used for blocking data where the block structure is * not necessarily related to the processing format. * * @since 8.0 */ public static final byte ETB = 23; /** * Cancel: A control character used to indicate that the data * with which it is sent is in error or is to be disregarded. * * @since 8.0 */ public static final byte CAN = 24; /** * End of Medium: A control character associated with the sent * data which may be used to identify the physical end of the medium, or * the end of the used, or wanted, portion of information recorded on a * medium. (The position of this character does not necessarily * correspond to the physical end of the medium.) * * @since 8.0 */ public static final byte EM = 25; /** * Substitute: A character that may be substituted for a * character which is determined to be invalid or in error. * * @since 8.0 */ public static final byte SUB = 26; /** * Escape: A control character intended to provide code * extension (supplementary characters) in general information * interchange. The Escape character itself is a prefix affecting the * interpretation of a limited number of contiguously following * characters. * * @since 8.0 */ public static final byte ESC = 27; /** * File Separator: These four information separators may be * used within data in optional fashion, except that their hierarchical * relationship shall be: FS is the most inclusive, then GS, then RS, * and US is least inclusive. (The content and length of a File, Group, * Record, or Unit are not specified.) * * @since 8.0 */ public static final byte FS = 28; /** * Group Separator: These four information separators may be * used within data in optional fashion, except that their hierarchical * relationship shall be: FS is the most inclusive, then GS, then RS, * and US is least inclusive. (The content and length of a File, Group, * Record, or Unit are not specified.) * * @since 8.0 */ public static final byte GS = 29; /** * Record Separator: These four information separators may be * used within data in optional fashion, except that their hierarchical * relationship shall be: FS is the most inclusive, then GS, then RS, * and US is least inclusive. (The content and length of a File, Group, * Record, or Unit are not specified.) * * @since 8.0 */ public static final byte RS = 30; /** * Unit Separator: These four information separators may be * used within data in optional fashion, except that their hierarchical * relationship shall be: FS is the most inclusive, then GS, then RS, * and US is least inclusive. (The content and length of a File, Group, * Record, or Unit are not specified.) * * @since 8.0 */ public static final byte US = 31; /** * Space: A normally non-printing graphic character used to * separate words. It is also a format effector which controls the * movement of the printing position, one printing position forward. * (Applicable also to display devices.) * * @since 8.0 */ public static final byte SP = 32; /** * Alternate name for {@link #SP}. * * @since 8.0 */ public static final byte SPACE = 32; /** * Delete: This character is used primarily to "erase" or * "obliterate" erroneous or unwanted characters in perforated tape. * * @since 8.0 */ public static final byte DEL = 127; /** * The minimum value of an ASCII character. * * @since 9.0 (was type {@code int} before 12.0) */ public static final char MIN = 0; /** * The maximum value of an ASCII character. * * @since 9.0 (was type {@code int} before 12.0) */ public static final char MAX = 127; /** * Returns a copy of the input string in which all {@linkplain #isUpperCase(char) uppercase ASCII * characters} have been converted to lowercase. All other characters are copied without * modification. */ public static String toLowerCase(String string) { int length = string.length(); for (int i = 0; i < length; i++) { if (isUpperCase(string.charAt(i))) { char[] chars = string.toCharArray(); for (; i < length; i++) { char c = chars[i]; if (isUpperCase(c)) { chars[i] = (char) (c ^ 0x20); } } return String.valueOf(chars); } } return string; } /** * Returns a copy of the input character sequence in which all {@linkplain #isUpperCase(char) * uppercase ASCII characters} have been converted to lowercase. All other characters are copied * without modification. * * @since 14.0 */ public static String toLowerCase(CharSequence chars) { if (chars instanceof String) { return toLowerCase((String) chars); } int length = chars.length(); StringBuilder builder = new StringBuilder(length); for (int i = 0; i < length; i++) { builder.append(toLowerCase(chars.charAt(i))); } return builder.toString(); } /** * If the argument is an {@linkplain #isUpperCase(char) uppercase ASCII character} returns the * lowercase equivalent. Otherwise returns the argument. */ public static char toLowerCase(char c) { return isUpperCase(c) ? (char) (c ^ 0x20) : c; } /** * Returns a copy of the input string in which all {@linkplain #isLowerCase(char) lowercase ASCII * characters} have been converted to uppercase. All other characters are copied without * modification. */ public static String toUpperCase(String string) { int length = string.length(); for (int i = 0; i < length; i++) { if (isLowerCase(string.charAt(i))) { char[] chars = string.toCharArray(); for (; i < length; i++) { char c = chars[i]; if (isLowerCase(c)) { chars[i] = (char) (c & 0x5f); } } return String.valueOf(chars); } } return string; } /** * Returns a copy of the input character sequence in which all {@linkplain #isLowerCase(char) * lowercase ASCII characters} have been converted to uppercase. All other characters are copied * without modification. * * @since 14.0 */ public static String toUpperCase(CharSequence chars) { if (chars instanceof String) { return toUpperCase((String) chars); } int length = chars.length(); StringBuilder builder = new StringBuilder(length); for (int i = 0; i < length; i++) { builder.append(toUpperCase(chars.charAt(i))); } return builder.toString(); } /** * If the argument is a {@linkplain #isLowerCase(char) lowercase ASCII character} returns the * uppercase equivalent. Otherwise returns the argument. */ public static char toUpperCase(char c) { return isLowerCase(c) ? (char) (c & 0x5f) : c; } /** * Indicates whether {@code c} is one of the twenty-six lowercase ASCII alphabetic characters * between {@code 'a'} and {@code 'z'} inclusive. All others (including non-ASCII characters) * return {@code false}. */ public static boolean isLowerCase(char c) { // Note: This was benchmarked against the alternate expression "(char)(c - 'a') < 26" (Nov '13) // and found to perform at least as well, or better. return (c >= 'a') && (c <= 'z'); } /** * Indicates whether {@code c} is one of the twenty-six uppercase ASCII alphabetic characters * between {@code 'A'} and {@code 'Z'} inclusive. All others (including non-ASCII characters) * return {@code false}. */ public static boolean isUpperCase(char c) { return (c >= 'A') && (c <= 'Z'); } /** * Truncates the given character sequence to the given maximum length. If the length of the * sequence is greater than {@code maxLength}, the returned string will be exactly * {@code maxLength} chars in length and will end with the given {@code truncationIndicator}. * Otherwise, the sequence will be returned as a string with no changes to the content. * * <p>Examples: * * <pre> {@code * Ascii.truncate("foobar", 7, "..."); // returns "foobar" * Ascii.truncate("foobar", 5, "..."); // returns "fo..." }</pre> * * <p><b>Note:</b> This method <i>may</i> work with certain non-ASCII text but is not safe for * use with arbitrary Unicode text. It is mostly intended for use with text that is known to be * safe for use with it (such as all-ASCII text) and for simple debugging text. When using this * method, consider the following: * * <ul> * <li>it may split surrogate pairs</li> * <li>it may split characters and combining characters</li> * <li>it does not consider word boundaries</li> * <li>if truncating for display to users, there are other considerations that must be taken * into account</li> * <li>the appropriate truncation indicator may be locale-dependent</li> * <li>it is safe to use non-ASCII characters in the truncation indicator</li> * </ul> * * * @throws IllegalArgumentException if {@code maxLength} is less than the length of * {@code truncationIndicator} * @since 16.0 */ @Beta @CheckReturnValue public static String truncate(CharSequence seq, int maxLength, String truncationIndicator) { checkNotNull(seq); // length to truncate the sequence to, not including the truncation indicator int truncationLength = maxLength - truncationIndicator.length(); // in this worst case, this allows a maxLength equal to the length of the truncationIndicator, // meaning that a string will be truncated to just the truncation indicator itself checkArgument(truncationLength >= 0, "maxLength (%s) must be >= length of the truncation indicator (%s)", maxLength, truncationIndicator.length()); if (seq.length() <= maxLength) { String string = seq.toString(); if (string.length() <= maxLength) { return string; } // if the length of the toString() result was > maxLength for some reason, truncate that seq = string; } return new StringBuilder(maxLength) .append(seq, 0, truncationLength) .append(truncationIndicator) .toString(); } /** * Indicates whether the contents of the given character sequences {@code s1} and {@code s2} are * equal, ignoring the case of any ASCII alphabetic characters between {@code 'a'} and {@code 'z'} * or {@code 'A'} and {@code 'Z'} inclusive. * * <p>This method is significantly faster than {@link String#equalsIgnoreCase} and should be used * in preference if at least one of the parameters is known to contain only ASCII characters. * * <p>Note however that this method does not always behave identically to expressions such as: * <ul> * <li>{@code string.toUpperCase().equals("UPPER CASE ASCII")} * <li>{@code string.toLowerCase().equals("lower case ascii")} * </ul> * <p>due to case-folding of some non-ASCII characters (which does not occur in * {@link String#equalsIgnoreCase}). However in almost all cases that ASCII strings are used, * the author probably wanted the behavior provided by this method rather than the subtle and * sometimes surprising behavior of {@code toUpperCase()} and {@code toLowerCase()}. * * @since 16.0 */ @Beta public static boolean equalsIgnoreCase(CharSequence s1, CharSequence s2) { // Calling length() is the null pointer check (so do it before we can exit early). int length = s1.length(); if (s1 == s2) { return true; } if (length != s2.length()) { return false; } for (int i = 0; i < length; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 == c2) { continue; } int alphaIndex = getAlphaIndex(c1); // This was also benchmarked using '&' to avoid branching (but always evaluate the rhs), // however this showed no obvious improvement. if (alphaIndex < 26 && alphaIndex == getAlphaIndex(c2)) { continue; } return false; } return true; } /** * Returns the non-negative index value of the alpha character {@code c}, regardless of case. * Ie, 'a'/'A' returns 0 and 'z'/'Z' returns 25. Non-alpha characters return a value of 26 or * greater. */ private static int getAlphaIndex(char c) { // Fold upper-case ASCII to lower-case and make zero-indexed and unsigned (by casting to char). return (char) ((c | 0x20) - 'a'); } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Ascii.java
Java
asf20
22,333
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.lang.reflect.Field; import javax.annotation.Nullable; /** * Utility methods for working with {@link Enum} instances. * * @author Steve McKay * * @since 9.0 */ @GwtCompatible(emulated = true) @Beta public final class Enums { private Enums() {} /** * Returns the {@link Field} in which {@code enumValue} is defined. For example, to get the * {@code Description} annotation on the {@code GOLF} constant of enum {@code Sport}, use * {@code Enums.getField(Sport.GOLF).getAnnotation(Description.class)}. * * @since 12.0 */ @GwtIncompatible("reflection") public static Field getField(Enum<?> enumValue) { Class<?> clazz = enumValue.getDeclaringClass(); try { return clazz.getDeclaredField(enumValue.name()); } catch (NoSuchFieldException impossible) { throw new AssertionError(impossible); } } /** * Returns a {@link Function} that maps an {@link Enum} name to the associated {@code Enum} * constant. The {@code Function} will return {@code null} if the {@code Enum} constant * does not exist. * * @param enumClass the {@link Class} of the {@code Enum} declaring the constant values * @deprecated Use {@link Enums#stringConverter} instead. Note that the string converter has * slightly different behavior: it throws {@link IllegalArgumentException} if the enum * constant does not exist rather than returning {@code null}. It also converts {@code null} * to {@code null} rather than throwing {@link NullPointerException}. This method is * scheduled for removal in Guava 18.0. */ @Deprecated public static <T extends Enum<T>> Function<String, T> valueOfFunction( Class<T> enumClass) { return new ValueOfFunction<T>(enumClass); } /** * A {@link Function} that maps an {@link Enum} name to the associated constant, or {@code null} * if the constant does not exist. */ private static final class ValueOfFunction<T extends Enum<T>> implements Function<String, T>, Serializable { private final Class<T> enumClass; private ValueOfFunction(Class<T> enumClass) { this.enumClass = checkNotNull(enumClass); } @Override public T apply(String value) { try { return Enum.valueOf(enumClass, value); } catch (IllegalArgumentException e) { return null; } } @Override public boolean equals(@Nullable Object obj) { return obj instanceof ValueOfFunction && enumClass.equals(((ValueOfFunction) obj).enumClass); } @Override public int hashCode() { return enumClass.hashCode(); } @Override public String toString() { return "Enums.valueOf(" + enumClass + ")"; } private static final long serialVersionUID = 0; } /** * Returns an optional enum constant for the given type, using {@link Enum#valueOf}. If the * constant does not exist, {@link Optional#absent} is returned. A common use case is for parsing * user input or falling back to a default enum constant. For example, * {@code Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);} * * @since 12.0 */ public static <T extends Enum<T>> Optional<T> getIfPresent(Class<T> enumClass, String value) { checkNotNull(enumClass); checkNotNull(value); try { return Optional.of(Enum.valueOf(enumClass, value)); } catch (IllegalArgumentException iae) { return Optional.absent(); } } /** * Returns a converter that converts between strings and {@code enum} values of type * {@code enumClass} using {@link Enum#valueOf(Class, String)} and {@link Enum#name()}. The * converter will throw an {@code IllegalArgumentException} if the argument is not the name of * any enum constant in the specified enum. * * @since 16.0 */ public static <T extends Enum<T>> Converter<String, T> stringConverter(final Class<T> enumClass) { return new StringConverter<T>(enumClass); } private static final class StringConverter<T extends Enum<T>> extends Converter<String, T> implements Serializable { private final Class<T> enumClass; StringConverter(Class<T> enumClass) { this.enumClass = checkNotNull(enumClass); } @Override protected T doForward(String value) { return Enum.valueOf(enumClass, value); } @Override protected String doBackward(T enumValue) { return enumValue.name(); } @Override public boolean equals(@Nullable Object object) { if (object instanceof StringConverter) { StringConverter<?> that = (StringConverter<?>) object; return this.enumClass.equals(that.enumClass); } return false; } @Override public int hashCode() { return enumClass.hashCode(); } @Override public String toString() { return "Enums.stringConverter(" + enumClass.getName() + ".class)"; } private static final long serialVersionUID = 0L; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Enums.java
Java
asf20
5,851
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collections; import java.util.HashMap; import java.util.Map; /** * This class provides default values for all Java types, as defined by the JLS. * * @author Ben Yu * @since 1.0 */ public final class Defaults { private Defaults() {} private static final Map<Class<?>, Object> DEFAULTS; static { // Only add to this map via put(Map, Class<T>, T) Map<Class<?>, Object> map = new HashMap<Class<?>, Object>(); put(map, boolean.class, false); put(map, char.class, '\0'); put(map, byte.class, (byte) 0); put(map, short.class, (short) 0); put(map, int.class, 0); put(map, long.class, 0L); put(map, float.class, 0f); put(map, double.class, 0d); DEFAULTS = Collections.unmodifiableMap(map); } private static <T> void put(Map<Class<?>, Object> map, Class<T> type, T value) { map.put(type, value); } /** * Returns the default value of {@code type} as defined by JLS --- {@code 0} for numbers, {@code * false} for {@code boolean} and {@code '\0'} for {@code char}. For non-primitive types and * {@code void}, null is returned. */ public static <T> T defaultValue(Class<T> type) { // Primitives.wrap(type).cast(...) would avoid the warning, but we can't use that from here @SuppressWarnings("unchecked") // the put method enforces this key-value relationship T t = (T) DEFAULTS.get(checkNotNull(type)); return t; } }
zzhhhhh-aw4rwer
guava/src/com/google/common/base/Defaults.java
Java
asf20
2,125