code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* 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.reflect;
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.Splitter;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Maps;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Enumeration;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.logging.Logger;
import javax.annotation.Nullable;
/**
* Scans the source of a {@link ClassLoader} and finds all the classes loadable.
*
* @author Ben Yu
* @since 14.0
*/
@Beta
public final class ClassPath {
private static final Logger logger = Logger.getLogger(ClassPath.class.getName());
/** Separator for the Class-Path manifest attribute value in jar files. */
private static final Splitter CLASS_PATH_ATTRIBUTE_SEPARATOR =
Splitter.on(" ").omitEmptyStrings();
private static final String CLASS_FILE_NAME_EXTENSION = ".class";
private final ImmutableSet<ClassInfo> classes;
private ClassPath(ImmutableSet<ClassInfo> classes) {
this.classes = classes;
}
/**
* Returns a {@code ClassPath} representing all classes loadable from {@code classloader} and its
* parent class loaders.
*
* <p>Currently only {@link URLClassLoader} and only {@code file://} urls are supported.
*
* @throws IOException if the attempt to read class path resources (jar files or directories)
* failed.
*/
public static ClassPath from(ClassLoader classloader) throws IOException {
ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder();
for (Map.Entry<URI, ClassLoader> entry : getClassPathEntries(classloader).entrySet()) {
builder.addAll(readClassesFrom(entry.getKey(), entry.getValue()));
}
return new ClassPath(builder.build());
}
/** Returns all top level classes loadable from the current class path. */
public ImmutableSet<ClassInfo> getClasses() {
return classes;
}
/** Returns all top level classes whose package name is {@code packageName}. */
public ImmutableSet<ClassInfo> getClasses(String packageName) {
checkNotNull(packageName);
ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder();
for (ClassInfo classInfo : classes) {
if (classInfo.getPackageName().equals(packageName)) {
builder.add(classInfo);
}
}
return builder.build();
}
/**
* Returns all top level classes whose package name is {@code packageName} or starts with
* {@code packageName} followed by a '.'.
*/
public ImmutableSet<ClassInfo> getClassesRecursive(String packageName) {
checkNotNull(packageName);
String packagePrefix = packageName + '.';
ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder();
for (ClassInfo classInfo : classes) {
if (classInfo.getName().startsWith(packagePrefix)) {
builder.add(classInfo);
}
}
return builder.build();
}
/** Represents a class that can be loaded through {@link #load}. */
public static final class ClassInfo {
private final String className;
private final ClassLoader loader;
@VisibleForTesting ClassInfo(String className, ClassLoader loader) {
this.className = checkNotNull(className);
this.loader = checkNotNull(loader);
}
/** Returns the package name of the class, without attempting to load the class. */
public String getPackageName() {
return Reflection.getPackageName(className);
}
/** Returns the fully qualified name of the class. */
public String getName() {
return className;
}
/** Loads (but doesn't link or initialize) the class. */
public Class<?> load() {
try {
return loader.loadClass(className);
} catch (ClassNotFoundException e) {
// Shouldn't happen, since the class name is read from the class path.
throw new IllegalStateException(e);
}
}
@Override public int hashCode() {
return className.hashCode();
}
@Override public boolean equals(Object obj) {
if (obj instanceof ClassInfo) {
ClassInfo that = (ClassInfo) obj;
return className.equals(that.className)
&& loader == that.loader;
}
return false;
}
@Override public String toString() {
return className;
}
}
@VisibleForTesting static ImmutableMap<URI, ClassLoader> getClassPathEntries(
ClassLoader classloader) {
LinkedHashMap<URI, ClassLoader> entries = Maps.newLinkedHashMap();
// Search parent first, since it's the order ClassLoader#loadClass() uses.
ClassLoader parent = classloader.getParent();
if (parent != null) {
entries.putAll(getClassPathEntries(parent));
}
if (classloader instanceof URLClassLoader) {
URLClassLoader urlClassLoader = (URLClassLoader) classloader;
for (URL entry : urlClassLoader.getURLs()) {
URI uri;
try {
uri = entry.toURI();
} catch (URISyntaxException e) {
throw new IllegalArgumentException(e);
}
if (!entries.containsKey(uri)) {
entries.put(uri, classloader);
}
}
}
return ImmutableMap.copyOf(entries);
}
private static ImmutableSet<ClassInfo> readClassesFrom(URI uri, ClassLoader classloader)
throws IOException {
if (uri.getScheme().equals("file")) {
return readClassesFrom(new File(uri), classloader);
} else {
return ImmutableSet.of();
}
}
@VisibleForTesting static ImmutableSet<ClassInfo> readClassesFrom(
File file, ClassLoader classloader)
throws IOException {
if (!file.exists()) {
return ImmutableSet.of();
}
if (file.isDirectory()) {
return readClassesFromDirectory(file, classloader);
} else {
return readClassesFromJar(file, classloader);
}
}
private static ImmutableSet<ClassInfo> readClassesFromDirectory(
File directory, ClassLoader classloader) {
ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder();
readClassesFromDirectory(directory, classloader, "", builder);
return builder.build();
}
private static void readClassesFromDirectory(
File directory, ClassLoader classloader,
String packagePrefix, ImmutableSet.Builder<ClassInfo> builder) {
for (File f : directory.listFiles()) {
String name = f.getName();
if (f.isDirectory()) {
readClassesFromDirectory(f, classloader, packagePrefix + name + ".", builder);
} else if (isTopLevelClassFile(name)) {
String className = packagePrefix + getClassName(name);
builder.add(new ClassInfo(className, classloader));
}
}
}
private static ImmutableSet<ClassInfo> readClassesFromJar(File file, ClassLoader classloader)
throws IOException {
ImmutableSet.Builder<ClassInfo> builder = ImmutableSet.builder();
JarFile jarFile = new JarFile(file);
for (URI uri : getClassPathFromManifest(file, jarFile.getManifest())) {
builder.addAll(readClassesFrom(uri, classloader));
}
Enumeration<JarEntry> entries = jarFile.entries();
while (entries.hasMoreElements()) {
JarEntry entry = entries.nextElement();
if (isTopLevelClassFile(entry.getName())) {
String className = getClassName(entry.getName().replace('/', '.'));
builder.add(new ClassInfo(className, classloader));
}
}
return builder.build();
}
/**
* Returns the class path URIs specified by the {@code Class-Path} manifest attribute, according
* to <a href="http://docs.oracle.com/javase/1.4.2/docs/guide/jar/jar.html#Main%20Attributes">
* JAR File Specification</a>. If {@code manifest} is null, it means the jar file has no manifest,
* and an empty set will be returned.
*/
@VisibleForTesting static ImmutableSet<URI> getClassPathFromManifest(
File jarFile, @Nullable Manifest manifest) {
if (manifest == null) {
return ImmutableSet.of();
}
ImmutableSet.Builder<URI> builder = ImmutableSet.builder();
String classpathAttribute = manifest.getMainAttributes().getValue("Class-Path");
if (classpathAttribute != null) {
for (String path : CLASS_PATH_ATTRIBUTE_SEPARATOR.split(classpathAttribute)) {
URI uri;
try {
uri = getClassPathEntry(jarFile, path);
} catch (URISyntaxException e) {
// Ignore bad entry
logger.warning("Invalid Class-Path entry: " + path);
continue;
}
builder.add(uri);
}
}
return builder.build();
}
/**
* Returns the absolute uri of the Class-Path entry value as specified in
* <a href="http://docs.oracle.com/javase/1.4.2/docs/guide/jar/jar.html#Main%20Attributes">
* JAR File Specification</a>. Even though the specification only talks about relative urls,
* absolute urls are actually supported too (for example, in Maven surefire plugin).
*/
@VisibleForTesting static URI getClassPathEntry(File jarFile, String path)
throws URISyntaxException {
URI uri = new URI(path);
if (uri.isAbsolute()) {
return uri;
} else {
return new File(jarFile.getParentFile(), path.replace('/', File.separatorChar)).toURI();
}
}
@VisibleForTesting static boolean isTopLevelClassFile(String filename) {
return filename.endsWith(CLASS_FILE_NAME_EXTENSION) && filename.indexOf('$') < 0;
}
@VisibleForTesting static String getClassName(String filename) {
int classNameEnd = filename.length() - CLASS_FILE_NAME_EXTENSION.length();
return filename.substring(0, classNameEnd);
}
}
| Java |
/*
* 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.reflect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static com.google.common.collect.Iterables.transform;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Predicates;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Iterables;
import java.io.Serializable;
import java.lang.reflect.Array;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Arrays;
import java.util.Collection;
import javax.annotation.Nullable;
/**
* Utilities for working with {@link Type}.
*
* @author Ben Yu
*/
final class Types {
/** Class#toString without the "class " and "interface " prefixes */
private static final Function<Type, String> TYPE_TO_STRING =
new Function<Type, String>() {
@Override public String apply(Type from) {
return Types.toString(from);
}
};
private static final Joiner COMMA_JOINER = Joiner.on(", ").useForNull("null");
/** Returns the array type of {@code componentType}. */
static Type newArrayType(Type componentType) {
if (componentType instanceof WildcardType) {
WildcardType wildcard = (WildcardType) componentType;
Type[] lowerBounds = wildcard.getLowerBounds();
checkArgument(lowerBounds.length <= 1, "Wildcard cannot have more than one lower bounds.");
if (lowerBounds.length == 1) {
return supertypeOf(newArrayType(lowerBounds[0]));
} else {
Type[] upperBounds = wildcard.getUpperBounds();
checkArgument(upperBounds.length == 1, "Wildcard should have only one upper bound.");
return subtypeOf(newArrayType(upperBounds[0]));
}
}
return JavaVersion.CURRENT.newArrayType(componentType);
}
/**
* Returns a type where {@code rawType} is parameterized by
* {@code arguments} and is owned by {@code ownerType}.
*/
static ParameterizedType newParameterizedTypeWithOwner(
@Nullable Type ownerType, Class<?> rawType, Type... arguments) {
if (ownerType == null) {
return newParameterizedType(rawType, arguments);
}
// ParameterizedTypeImpl constructor already checks, but we want to throw NPE before IAE
checkNotNull(arguments);
checkArgument(rawType.getEnclosingClass() != null, "Owner type for unenclosed %s", rawType);
return new ParameterizedTypeImpl(ownerType, rawType, arguments);
}
/**
* Returns a type where {@code rawType} is parameterized by
* {@code arguments}.
*/
static ParameterizedType newParameterizedType(Class<?> rawType, Type... arguments) {
return new ParameterizedTypeImpl(
ClassOwnership.JVM_BEHAVIOR.getOwnerType(rawType), rawType, arguments);
}
/** Decides what owner type to use for constructing {@link ParameterizedType} from a raw class. */
private enum ClassOwnership {
OWNED_BY_ENCLOSING_CLASS {
@Nullable
@Override
Class<?> getOwnerType(Class<?> rawType) {
return rawType.getEnclosingClass();
}
},
LOCAL_CLASS_HAS_NO_OWNER {
@Nullable
@Override
Class<?> getOwnerType(Class<?> rawType) {
if (rawType.isLocalClass()) {
return null;
} else {
return rawType.getEnclosingClass();
}
}
};
@Nullable abstract Class<?> getOwnerType(Class<?> rawType);
static final ClassOwnership JVM_BEHAVIOR = detectJvmBehavior();
private static ClassOwnership detectJvmBehavior() {
class LocalClass<T> {}
Class<?> subclass = new LocalClass<String>() {}.getClass();
ParameterizedType parameterizedType = (ParameterizedType)
subclass.getGenericSuperclass();
for (ClassOwnership behavior : ClassOwnership.values()) {
if (behavior.getOwnerType(LocalClass.class) == parameterizedType.getOwnerType()) {
return behavior;
}
}
throw new AssertionError();
}
}
/**
* Returns a new {@link TypeVariable} that belongs to {@code declaration} with
* {@code name} and {@code bounds}.
*/
static <D extends GenericDeclaration> TypeVariable<D> newTypeVariable(
D declaration, String name, Type... bounds) {
return new TypeVariableImpl<D>(
declaration,
name,
(bounds.length == 0)
? new Type[] { Object.class }
: bounds);
}
/** Returns a new {@link WildcardType} with {@code upperBound}. */
@VisibleForTesting static WildcardType subtypeOf(Type upperBound) {
return new WildcardTypeImpl(new Type[0], new Type[] { upperBound });
}
/** Returns a new {@link WildcardType} with {@code lowerBound}. */
@VisibleForTesting static WildcardType supertypeOf(Type lowerBound) {
return new WildcardTypeImpl(new Type[] { lowerBound }, new Type[] { Object.class });
}
/**
* Returns human readable string representation of {@code type}.
* <ul>
* <li> For array type {@code Foo[]}, {@code "com.mypackage.Foo[]"} are
* returned.
* <li> For any class, {@code theClass.getName()} are returned.
* <li> For all other types, {@code type.toString()} are returned.
* </ul>
*/
static String toString(Type type) {
return (type instanceof Class)
? ((Class<?>) type).getName()
: type.toString();
}
@Nullable static Type getComponentType(Type type) {
checkNotNull(type);
if (type instanceof Class) {
return ((Class<?>) type).getComponentType();
} else if (type instanceof GenericArrayType) {
return ((GenericArrayType) type).getGenericComponentType();
} else if (type instanceof WildcardType) {
return subtypeOfComponentType(((WildcardType) type).getUpperBounds());
} else if (type instanceof TypeVariable) {
return subtypeOfComponentType(((TypeVariable<?>) type).getBounds());
} else {
return null;
}
}
/**
* Returns {@code ? extends X} if any of {@code bounds} is a subtype of {@code X[]}; or null
* otherwise.
*/
@Nullable private static Type subtypeOfComponentType(Type[] bounds) {
for (Type bound : bounds) {
Type componentType = getComponentType(bound);
if (componentType != null) {
// Only the first bound can be a class or array.
// Bounds after the first can only be interfaces.
if (componentType instanceof Class) {
Class<?> componentClass = (Class<?>) componentType;
if (componentClass.isPrimitive()) {
return componentClass;
}
}
return subtypeOf(componentType);
}
}
return null;
}
static boolean containsTypeVariable(@Nullable Type type) {
if (type instanceof TypeVariable) {
return true;
}
if (type instanceof GenericArrayType) {
return containsTypeVariable(((GenericArrayType) type).getGenericComponentType());
}
if (type instanceof ParameterizedType) {
return containsTypeVariable(((ParameterizedType) type).getActualTypeArguments());
}
if (type instanceof WildcardType) {
WildcardType wildcard = (WildcardType) type;
return containsTypeVariable(wildcard.getUpperBounds())
|| containsTypeVariable(wildcard.getLowerBounds());
}
return false;
}
private static boolean containsTypeVariable(Type[] types) {
for (Type paramType : types) {
if (containsTypeVariable(paramType)) {
return true;
}
}
return false;
}
private static final class GenericArrayTypeImpl
implements GenericArrayType, Serializable {
private final Type componentType;
GenericArrayTypeImpl(Type componentType) {
this.componentType = JavaVersion.CURRENT.usedInGenericType(componentType);
}
@Override public Type getGenericComponentType() {
return componentType;
}
@Override public String toString() {
return Types.toString(componentType) + "[]";
}
@Override public int hashCode() {
return componentType.hashCode();
}
@Override public boolean equals(Object obj) {
if (obj instanceof GenericArrayType) {
GenericArrayType that = (GenericArrayType) obj;
return Objects.equal(
getGenericComponentType(), that.getGenericComponentType());
}
return false;
}
private static final long serialVersionUID = 0;
}
private static final class ParameterizedTypeImpl
implements ParameterizedType, Serializable {
private final Type ownerType;
private final ImmutableList<Type> argumentsList;
private final Class<?> rawType;
ParameterizedTypeImpl(
@Nullable Type ownerType, Class<?> rawType, Type[] typeArguments) {
checkNotNull(rawType);
checkArgument(typeArguments.length == rawType.getTypeParameters().length);
disallowPrimitiveType(typeArguments, "type parameter");
this.ownerType = ownerType;
this.rawType = rawType;
this.argumentsList = JavaVersion.CURRENT.usedInGenericType(typeArguments);
}
@Override public Type[] getActualTypeArguments() {
return toArray(argumentsList);
}
@Override public Type getRawType() {
return rawType;
}
@Override public Type getOwnerType() {
return ownerType;
}
@Override public String toString() {
StringBuilder builder = new StringBuilder();
if (ownerType != null) {
builder.append(Types.toString(ownerType)).append('.');
}
builder.append(rawType.getName())
.append('<')
.append(COMMA_JOINER.join(transform(argumentsList, TYPE_TO_STRING)))
.append('>');
return builder.toString();
}
@Override public int hashCode() {
return (ownerType == null ? 0 : ownerType.hashCode())
^ argumentsList.hashCode() ^ rawType.hashCode();
}
@Override public boolean equals(Object other) {
if (!(other instanceof ParameterizedType)) {
return false;
}
ParameterizedType that = (ParameterizedType) other;
return getRawType().equals(that.getRawType())
&& Objects.equal(getOwnerType(), that.getOwnerType())
&& Arrays.equals(
getActualTypeArguments(), that.getActualTypeArguments());
}
private static final long serialVersionUID = 0;
}
private static final class TypeVariableImpl<D extends GenericDeclaration>
implements TypeVariable<D> {
private final D genericDeclaration;
private final String name;
private final ImmutableList<Type> bounds;
TypeVariableImpl(D genericDeclaration, String name, Type[] bounds) {
disallowPrimitiveType(bounds, "bound for type variable");
this.genericDeclaration = checkNotNull(genericDeclaration);
this.name = checkNotNull(name);
this.bounds = ImmutableList.copyOf(bounds);
}
@Override public Type[] getBounds() {
return toArray(bounds);
}
@Override public D getGenericDeclaration() {
return genericDeclaration;
}
@Override public String getName() {
return name;
}
@Override public String toString() {
return name;
}
@Override public int hashCode() {
return genericDeclaration.hashCode() ^ name.hashCode();
}
@Override public boolean equals(Object obj) {
if (obj instanceof TypeVariable) {
TypeVariable<?> that = (TypeVariable<?>) obj;
return name.equals(that.getName())
&& genericDeclaration.equals(that.getGenericDeclaration());
}
return false;
}
}
static final class WildcardTypeImpl implements WildcardType, Serializable {
private final ImmutableList<Type> lowerBounds;
private final ImmutableList<Type> upperBounds;
WildcardTypeImpl(Type[] lowerBounds, Type[] upperBounds) {
disallowPrimitiveType(lowerBounds, "lower bound for wildcard");
disallowPrimitiveType(upperBounds, "upper bound for wildcard");
this.lowerBounds = JavaVersion.CURRENT.usedInGenericType(lowerBounds);
this.upperBounds = JavaVersion.CURRENT.usedInGenericType(upperBounds);
}
@Override public Type[] getLowerBounds() {
return toArray(lowerBounds);
}
@Override public Type[] getUpperBounds() {
return toArray(upperBounds);
}
@Override public boolean equals(Object obj) {
if (obj instanceof WildcardType) {
WildcardType that = (WildcardType) obj;
return lowerBounds.equals(Arrays.asList(that.getLowerBounds()))
&& upperBounds.equals(Arrays.asList(that.getUpperBounds()));
}
return false;
}
@Override public int hashCode() {
return lowerBounds.hashCode() ^ upperBounds.hashCode();
}
@Override public String toString() {
StringBuilder builder = new StringBuilder("?");
for (Type lowerBound : lowerBounds) {
builder.append(" super ").append(Types.toString(lowerBound));
}
for (Type upperBound : filterUpperBounds(upperBounds)) {
builder.append(" extends ").append(Types.toString(upperBound));
}
return builder.toString();
}
private static final long serialVersionUID = 0;
}
private static Type[] toArray(Collection<Type> types) {
return types.toArray(new Type[types.size()]);
}
private static Iterable<Type> filterUpperBounds(Iterable<Type> bounds) {
return Iterables.filter(
bounds, Predicates.not(Predicates.<Type>equalTo(Object.class)));
}
private static void disallowPrimitiveType(Type[] types, String usedAs) {
for (Type type : types) {
if (type instanceof Class) {
Class<?> cls = (Class<?>) type;
checkArgument(!cls.isPrimitive(),
"Primitive type '%s' used as %s", cls, usedAs);
}
}
}
/** Returns the {@code Class} object of arrays with {@code componentType}. */
static Class<?> getArrayClass(Class<?> componentType) {
// TODO(user): This is not the most efficient way to handle generic
// arrays, but is there another way to extract the array class in a
// non-hacky way (i.e. using String value class names- "[L...")?
return Array.newInstance(componentType, 0).getClass();
}
// TODO(benyu): Once we are on Java 7, delete this abstraction
enum JavaVersion {
JAVA6 {
@Override GenericArrayType newArrayType(Type componentType) {
return new GenericArrayTypeImpl(componentType);
}
@Override Type usedInGenericType(Type type) {
checkNotNull(type);
if (type instanceof Class) {
Class<?> cls = (Class<?>) type;
if (cls.isArray()) {
return new GenericArrayTypeImpl(cls.getComponentType());
}
}
return type;
}
},
JAVA7 {
@Override Type newArrayType(Type componentType) {
if (componentType instanceof Class) {
return getArrayClass((Class<?>) componentType);
} else {
return new GenericArrayTypeImpl(componentType);
}
}
@Override Type usedInGenericType(Type type) {
return checkNotNull(type);
}
}
;
static final JavaVersion CURRENT =
(new TypeCapture<int[]>() {}.capture() instanceof Class)
? JAVA7 : JAVA6;
abstract Type newArrayType(Type componentType);
abstract Type usedInGenericType(Type type);
final ImmutableList<Type> usedInGenericType(Type[] types) {
ImmutableList.Builder<Type> builder = ImmutableList.builder();
for (Type type : types) {
builder.add(usedInGenericType(type));
}
return builder.build();
}
}
private Types() {}
}
| Java |
/*
* 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.reflect;
import com.google.common.annotations.Beta;
import com.google.common.collect.ImmutableList;
import com.google.common.reflect.TypeToken;
import java.lang.annotation.Annotation;
import java.lang.reflect.AnnotatedElement;
import javax.annotation.Nullable;
/**
* Represents a method or constructor parameter.
*
* @author Ben Yu
* @since 14.0
*/
@Beta
public final class Parameter implements AnnotatedElement {
private final Invokable<?, ?> declaration;
private final int position;
private final TypeToken<?> type;
private final ImmutableList<Annotation> annotations;
Parameter(
Invokable<?, ?> declaration,
int position,
TypeToken<?> type,
Annotation[] annotations) {
this.declaration = declaration;
this.position = position;
this.type = type;
this.annotations = ImmutableList.copyOf(annotations);
}
/** Returns the type of the parameter. */
public TypeToken<?> getType() {
return type;
}
/** Returns the {@link Invokable} that declares this parameter. */
public Invokable<?, ?> getInvokable() {
return declaration;
}
@Override public boolean isAnnotationPresent(Class<? extends Annotation> annotationType) {
return getAnnotation(annotationType) != null;
}
@Override
@Nullable
public <A extends Annotation> A getAnnotation(Class<A> annotationType) {
for (Annotation annotation : annotations) {
if (annotationType.isInstance(annotation)) {
return annotationType.cast(annotation);
}
}
return null;
}
@Override public Annotation[] getAnnotations() {
return getDeclaredAnnotations();
}
@Override public Annotation[] getDeclaredAnnotations() {
return annotations.toArray(new Annotation[annotations.size()]);
}
@Override public boolean equals(Object obj) {
if (obj instanceof Parameter) {
Parameter that = (Parameter) obj;
return position == that.position && declaration.equals(that.declaration);
}
return false;
}
@Override public int hashCode() {
return position;
}
@Override public String toString() {
return type + " arg" + position;
}
}
| Java |
/*
* 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.reflect;
import com.google.common.annotations.Beta;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import javax.annotation.Nullable;
/**
* Abstract implementation of {@link InvocationHandler} that handles {@link Object#equals},
* {@link Object#hashCode} and {@link Object#toString}.
*
* @author Ben Yu
* @since 12.0
*/
@Beta
public abstract class AbstractInvocationHandler implements InvocationHandler {
private static final Object[] NO_ARGS = {};
/**
* {@inheritDoc}
*
* <p><ul>
* <li>{@code proxy.hashCode()} delegates to {@link AbstractInvocationHandler#hashCode}
* <li>{@code proxy.toString()} delegates to {@link AbstractInvocationHandler#toString}
* <li>{@code proxy.equals(argument)} returns true if: <ul>
* <li>{@code proxy} and {@code argument} are of the same type
* <li>and {@link AbstractInvocationHandler#equals} returns true for the {@link
* InvocationHandler} of {@code argument}
* </ul>
* <li>other method calls are dispatched to {@link #handleInvocation}.
* </ul>
*/
@Override public final Object invoke(Object proxy, Method method, @Nullable Object[] args)
throws Throwable {
if (args == null) {
args = NO_ARGS;
}
if (args.length == 0 && method.getName().equals("hashCode")) {
return hashCode();
}
if (args.length == 1
&& method.getName().equals("equals")
&& method.getParameterTypes()[0] == Object.class) {
Object arg = args[0];
return proxy.getClass().isInstance(arg) && equals(Proxy.getInvocationHandler(arg));
}
if (args.length == 0 && method.getName().equals("toString")) {
return toString();
}
return handleInvocation(proxy, method, args);
}
/**
* {@link #invoke} delegates to this method upon any method invocation on the proxy instance,
* except {@link Object#equals}, {@link Object#hashCode} and {@link Object#toString}. The result
* will be returned as the proxied method's return value.
*
* <p>Unlike {@link #invoke}, {@code args} will never be null. When the method has no parameter,
* an empty array is passed in.
*/
protected abstract Object handleInvocation(Object proxy, Method method, Object[] args)
throws Throwable;
/**
* By default delegates to {@link Object#equals} so instances are only equal if they are
* identical. {@code proxy.equals(argument)} returns true if: <ul>
* <li>{@code proxy} and {@code argument} are of the same type
* <li>and this method returns true for the {@link InvocationHandler} of {@code argument}
* </ul>
* Subclasses can override this method to provide custom equality.
*/
@Override public boolean equals(Object obj) {
return super.equals(obj);
}
/**
* By default delegates to {@link Object#hashCode}. The dynamic proxies' {@code hashCode()} will
* delegate to this method. Subclasses can override this method to provide custom equality.
*/
@Override public int hashCode() {
return super.hashCode();
}
/**
* By default delegates to {@link Object#toString}. The dynamic proxies' {@code toString()} will
* delegate to this method. Subclasses can override this method to provide custom string
* representation for the proxies.
*/
@Override public String toString() {
return super.toString();
}
}
| Java |
/*
* 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.reflect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.annotations.Beta;
import com.google.common.collect.ImmutableList;
import com.google.common.reflect.TypeToken;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.GenericDeclaration;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import javax.annotation.Nullable;
/**
* Wrapper around either a {@link Method} or a {@link Constructor}.
* Convenience API is provided to make common reflective operation easier to deal with,
* such as {@link #isPublic}, {@link #getParameters} etc.
*
* @param <T> the type that declares this method or constructor.
* @param <R> the return type of (or supertype thereof) the method or the declaring type of the
* constructor.
* @author Ben Yu
* @since 14.0
*/
@Beta
public abstract class Invokable<T, R> extends Element implements GenericDeclaration {
<M extends AccessibleObject & Member> Invokable(M member) {
super(member);
}
/** Returns {@link Invokable} of {@code method}. */
public static Invokable<?, Object> from(Method method) {
return new MethodInvokable<Object>(method);
}
/** Returns {@link Invokable} of {@code constructor}. */
public static <T> Invokable<T, T> from(Constructor<T> constructor) {
return new ConstructorInvokable<T>(constructor);
}
/**
* Returns {@code true} if this is an overridable method; {@code false} if either it's not
* overridable, or if it's a constructor.
*/
public abstract boolean isOverridable();
/**
* Invokes with {@code receiver} as the 'this' and {@code args} passed to the underlying method
* and returns the return value; or calls the underlying constructor with {@code args} and returns
* the constructed instance.
*
* @throws IllegalAccessException if this {@code Constructor} object enforces Java language
* access control and the underlying method or constructor is inaccessible.
* @throws IllegalArgumentException if the number of actual and formal parameters differ;
* if an unwrapping conversion for primitive arguments fails; or if, after possible
* unwrapping, a parameter value cannot be converted to the corresponding formal
* parameter type by a method invocation conversion.
* @throws InvocationTargetException if the underlying method or constructor throws an exception.
*/
// All subclasses are owned by us and we'll make sure to get the R type right.
@SuppressWarnings("unchecked")
public final R invoke(@Nullable T receiver, Object... args)
throws InvocationTargetException, IllegalAccessException {
return (R) invokeInternal(receiver, checkNotNull(args));
}
/** Returns the return type of this delegate. */
// All subclasses are owned by us and we'll make sure to get the R type right.
@SuppressWarnings("unchecked")
public final TypeToken<? extends R> getReturnType() {
return (TypeToken<? extends R>) TypeToken.of(getGenericReturnType());
}
/** Returns all declared parameters of this delegate. */
public final ImmutableList<Parameter> getParameters() {
Type[] parameterTypes = getGenericParameterTypes();
Annotation[][] annotations = getParameterAnnotations();
ImmutableList.Builder<Parameter> builder = ImmutableList.builder();
for (int i = 0; i < parameterTypes.length; i++) {
builder.add(new Parameter(
this, i, TypeToken.of(parameterTypes[i]), annotations[i]));
}
return builder.build();
}
/** Returns all declared exception types of this delegate. */
public final ImmutableList<TypeToken<? extends Throwable>> getExceptionTypes() {
ImmutableList.Builder<TypeToken<? extends Throwable>> builder = ImmutableList.builder();
for (Type type : getGenericExceptionTypes()) {
// getGenericExceptionTypes() will never return a type that's not exception
@SuppressWarnings("unchecked")
TypeToken<? extends Throwable> exceptionType = (TypeToken<? extends Throwable>)
TypeToken.of(type);
builder.add(exceptionType);
}
return builder.build();
}
/**
* Explicitly specifies the {@code returnType return type} of the functor. For example:
* <pre> {@code
* Method factoryMethod = Person.class.getMethod("create");
* Invokable<?, Person> factory = Invokable.of(getNameMethod).returning(Person.class);
* }</pre>
*/
public final <R1 extends R> Invokable<T, R1> returning(Class<R1> returnType) {
return returning(TypeToken.of(returnType));
}
/** Explicitly specifies the {@code returnType return type} of the functor. */
public final <R1 extends R> Invokable<T, R1> returning(TypeToken<R1> returnType) {
if (!returnType.isAssignableFrom(getReturnType())) {
throw new IllegalArgumentException(
"Invokable is known to return " + getReturnType() + ", not " + returnType);
}
@SuppressWarnings("unchecked") // guarded by previous check
Invokable<T, R1> specialized = (Invokable<T, R1>) this;
return specialized;
}
@SuppressWarnings("unchecked") // The declaring class is T's raw class, or one of its supertypes.
@Override public final Class<? super T> getDeclaringClass() {
return (Class<? super T>) super.getDeclaringClass();
}
abstract Object invokeInternal(Object receiver, Object[] args)
throws InvocationTargetException, IllegalAccessException;
abstract Type[] getGenericParameterTypes();
/** This should never return a type that's not a subtype of Throwable. */
abstract Type[] getGenericExceptionTypes();
abstract Annotation[][] getParameterAnnotations();
abstract Type getGenericReturnType();
static class MethodInvokable<T> extends Invokable<T, Object> {
private final Method method;
MethodInvokable(Method method) {
super(method);
this.method = method;
}
@Override final Object invokeInternal(Object receiver, Object[] args)
throws InvocationTargetException, IllegalAccessException {
return method.invoke(receiver, args);
}
@Override Type getGenericReturnType() {
return method.getGenericReturnType();
}
@Override Type[] getGenericParameterTypes() {
return method.getGenericParameterTypes();
}
@Override Type[] getGenericExceptionTypes() {
return method.getGenericExceptionTypes();
}
@Override final Annotation[][] getParameterAnnotations() {
return method.getParameterAnnotations();
}
@Override public final TypeVariable<?>[] getTypeParameters() {
return method.getTypeParameters();
}
@Override public final boolean isOverridable() {
return !(isFinal() || isPrivate() || isStatic()
|| Modifier.isFinal(getDeclaringClass().getModifiers()));
}
}
static class ConstructorInvokable<T> extends Invokable<T, T> {
private final Constructor<?> constructor;
ConstructorInvokable(Constructor<?> constructor) {
super(constructor);
this.constructor = constructor;
}
@Override final Object invokeInternal(Object receiver, Object[] args)
throws InvocationTargetException, IllegalAccessException {
try {
return constructor.newInstance(args);
} catch (InstantiationException e) {
throw new RuntimeException(constructor + " failed.", e);
}
}
@Override Type getGenericReturnType() {
return constructor.getDeclaringClass();
}
@Override Type[] getGenericParameterTypes() {
return constructor.getGenericParameterTypes();
}
@Override Type[] getGenericExceptionTypes() {
return constructor.getGenericExceptionTypes();
}
@Override final Annotation[][] getParameterAnnotations() {
return constructor.getParameterAnnotations();
}
@Override public final TypeVariable<?>[] getTypeParameters() {
return constructor.getTypeParameters();
}
@Override public final boolean isOverridable() {
return false;
}
}
}
| Java |
/*
* 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.reflect;
import static com.google.common.base.Preconditions.checkArgument;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
/**
* Captures the actual type of {@code T}.
*
* @author Ben Yu
*/
abstract class TypeCapture<T> {
/** Returns the captured type. */
final Type capture() {
Type superclass = getClass().getGenericSuperclass();
checkArgument(superclass instanceof ParameterizedType,
"%s isn't parameterized", superclass);
return ((ParameterizedType) superclass).getActualTypeArguments()[0];
}
}
| Java |
/*
* 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.reflect;
import com.google.common.annotations.Beta;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A map, each entry of which maps a {@link TypeToken} to an instance of that type.
* In addition to implementing {@code Map}, the additional type-safe operations
* {@link #putInstance} and {@link #getInstance} are available.
*
* <p>Generally, implementations don't support {@link #put} and {@link #putAll}
* because there is no way to check an object at runtime to be an instance of a
* {@link TypeToken}. Instead, caller should use the type safe {@link #putInstance}.
*
* <p>Also, if caller suppresses unchecked warnings and passes in an {@code Iterable<String>}
* for type {@code Iterable<Integer>}, the map won't be able to detect and throw type error.
*
* <p>Like any other {@code Map<Class, Object>}, this map may contain entries
* for primitive types, and a primitive type and its corresponding wrapper type
* may map to different values.
*
* @param <B> the common supertype that all entries must share; often this is
* simply {@link Object}
*
* @author Ben Yu
* @since 13.0
*/
@Beta
public interface TypeToInstanceMap<B> extends Map<TypeToken<? extends B>, B> {
/**
* Returns the value the specified class is mapped to, or {@code null} if no
* entry for this class is present. This will only return a value that was
* bound to this specific class, not a value that may have been bound to a
* subtype.
*
* <p>{@code getInstance(Foo.class)} is equivalent to
* {@code getInstance(TypeToken.of(Foo.class))}.
*/
@Nullable
<T extends B> T getInstance(Class<T> type);
/**
* Maps the specified class to the specified value. Does <i>not</i> associate
* this value with any of the class's supertypes.
*
* <p>{@code putInstance(Foo.class, foo)} is equivalent to
* {@code putInstance(TypeToken.of(Foo.class), foo)}.
*
* @return the value previously associated with this class (possibly {@code null}),
* or {@code null} if there was no previous entry.
*/
@Nullable
<T extends B> T putInstance(Class<T> type, @Nullable T value);
/**
* Returns the value the specified type is mapped to, or {@code null} if no
* entry for this type is present. This will only return a value that was
* bound to this specific type, not a value that may have been bound to a subtype.
*/
@Nullable
<T extends B> T getInstance(TypeToken<T> type);
/**
* Maps the specified type to the specified value. Does <i>not</i> associate
* this value with any of the type's supertypes.
*
* @return the value previously associated with this type (possibly {@code null}),
* or {@code null} if there was no previous entry.
*/
@Nullable
<T extends B> T putInstance(TypeToken<T> type, @Nullable T value);
}
| Java |
/*
* 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.reflect;
import static com.google.common.base.Preconditions.checkNotNull;
import java.lang.annotation.Annotation;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Member;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import javax.annotation.Nullable;
/**
* Represents either a {@link Field}, a {@link Method} or a {@link Constructor}.
* Provides convenience methods such as {@link #isPublic} and {@link #isPackagePrivate}.
*
* @author Ben Yu
*/
class Element extends AccessibleObject implements Member {
private final AccessibleObject accessibleObject;
private final Member member;
<M extends AccessibleObject & Member> Element(M member) {
checkNotNull(member);
this.accessibleObject = member;
this.member = member;
}
@Override public final boolean isAnnotationPresent(Class<? extends Annotation> annotationClass) {
return accessibleObject.isAnnotationPresent(annotationClass);
}
@Override public final <A extends Annotation> A getAnnotation(Class<A> annotationClass) {
return accessibleObject.getAnnotation(annotationClass);
}
@Override public final Annotation[] getAnnotations() {
return accessibleObject.getAnnotations();
}
@Override public final Annotation[] getDeclaredAnnotations() {
return accessibleObject.getDeclaredAnnotations();
}
@Override public final void setAccessible(boolean flag) throws SecurityException {
accessibleObject.setAccessible(flag);
}
@Override public final boolean isAccessible() {
return accessibleObject.isAccessible();
}
@Override public Class<?> getDeclaringClass() {
return member.getDeclaringClass();
}
@Override public final String getName() {
return member.getName();
}
@Override public final int getModifiers() {
return member.getModifiers();
}
@Override public final boolean isSynthetic() {
return member.isSynthetic();
}
/** Returns true if the element is public. */
public final boolean isPublic() {
return Modifier.isPublic(getModifiers());
}
/** Returns true if the element is protected. */
public final boolean isProtected() {
return Modifier.isProtected(getModifiers());
}
/** Returns true if the element is package-private. */
public final boolean isPackagePrivate() {
return !isPrivate() && !isPublic() && !isProtected();
}
/** Returns true if the element is private. */
public final boolean isPrivate() {
return Modifier.isPrivate(getModifiers());
}
/** Returns true if the field or method is static. */
public final boolean isStatic() {
return Modifier.isStatic(getModifiers());
}
/**
* Returns {@code true} if this method is final, per {@code Modifier.isFinal(getModifiers())}.
*
* <p>Note that a method may still be effectively "final", or non-overridable when it has no
* {@code final} keyword. For example, it could be private, or it could be declared by a final
* class. To tell whether a method is overridable, use {@link Invokable#isOverridable}.
*/
public final boolean isFinal() {
return Modifier.isFinal(getModifiers());
}
/** Returns true if the method is abstract. */
public final boolean isAbstract() {
return Modifier.isAbstract(getModifiers());
}
/** Returns true if the element is native. */
public final boolean isNative() {
return Modifier.isNative(getModifiers());
}
/** Returns true if the method is synchronized. */
public final boolean isSynchronized() {
return Modifier.isSynchronized(getModifiers());
}
/** Returns true if the field is volatile. */
final boolean isVolatile() {
return Modifier.isVolatile(getModifiers());
}
/** Returns true if the field is transient. */
final boolean isTransient() {
return Modifier.isTransient(getModifiers());
}
@Override public boolean equals(@Nullable Object obj) {
if (obj instanceof Element) {
Element that = (Element) obj;
return member.equals(that.member);
}
return false;
}
@Override public int hashCode() {
return member.hashCode();
}
@Override public String toString() {
return member.toString();
}
}
| Java |
/*
* 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.reflect;
import com.google.common.annotations.Beta;
import com.google.common.collect.ForwardingMap;
import com.google.common.collect.Maps;
import java.util.Map;
import javax.annotation.Nullable;
/**
* A mutable type-to-instance map.
* See also {@link ImmutableTypeToInstanceMap}.
*
* @author Ben Yu
* @since 13.0
*/
@Beta
public final class MutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<? extends B>, B>
implements TypeToInstanceMap<B> {
private final Map<TypeToken<? extends B>, B> backingMap = Maps.newHashMap();
@Nullable
@Override
public <T extends B> T getInstance(Class<T> type) {
return trustedGet(TypeToken.of(type));
}
@Nullable
@Override
public <T extends B> T putInstance(Class<T> type, @Nullable T value) {
return trustedPut(TypeToken.of(type), value);
}
@Nullable
@Override
public <T extends B> T getInstance(TypeToken<T> type) {
return trustedGet(type.rejectTypeVariables());
}
@Nullable
@Override
public <T extends B> T putInstance(TypeToken<T> type, @Nullable T value) {
return trustedPut(type.rejectTypeVariables(), value);
}
/** Not supported. Use {@link #putInstance} instead. */
@Override public B put(TypeToken<? extends B> key, B value) {
throw new UnsupportedOperationException("Please use putInstance() instead.");
}
/** Not supported. Use {@link #putInstance} instead. */
@Override public void putAll(Map<? extends TypeToken<? extends B>, ? extends B> map) {
throw new UnsupportedOperationException("Please use putInstance() instead.");
}
@Override protected Map<TypeToken<? extends B>, B> delegate() {
return backingMap;
}
@SuppressWarnings("unchecked") // value could not get in if not a T
@Nullable
private <T extends B> T trustedPut(TypeToken<T> type, @Nullable T value) {
return (T) backingMap.put(type, value);
}
@SuppressWarnings("unchecked") // value could not get in if not a T
@Nullable
private <T extends B> T trustedGet(TypeToken<T> type) {
return (T) backingMap.get(type);
}
}
| Java |
/*
* 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.reflect;
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 com.google.common.base.Joiner;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.lang.reflect.GenericArrayType;
import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.lang.reflect.TypeVariable;
import java.lang.reflect.WildcardType;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.atomic.AtomicInteger;
import javax.annotation.Nullable;
/**
* An object of this class encapsulates type mappings from type variables. Mappings are established
* with {@link #where} and types are resolved using {@link #resolveType}.
*
* <p>Note that usually type mappings are already implied by the static type hierarchy (for example,
* the {@code E} type variable declared by class {@code List} naturally maps to {@code String} in
* the context of {@code class MyStringList implements List<String>}. In such case, prefer to use
* {@link TypeToken#resolveType} since it's simpler and more type safe. This class should only be
* used when the type mapping isn't implied by the static type hierarchy, but provided through other
* means such as an annotation or external configuration file.
*
* @author Ben Yu
*/
class TypeResolver {
private final ImmutableMap<TypeVariable<?>, Type> typeTable;
public TypeResolver() {
this.typeTable = ImmutableMap.of();
}
private TypeResolver(ImmutableMap<TypeVariable<?>, Type> typeTable) {
this.typeTable = typeTable;
}
static TypeResolver accordingTo(Type type) {
return new TypeResolver().where(TypeMappingIntrospector.getTypeMappings(type));
}
/**
* Returns a new {@code TypeResolver} with type variables in {@code formal} mapping to types in
* {@code actual}.
*
* <p>For example, if {@code formal} is a {@code TypeVariable T}, and {@code actual} is {@code
* String.class}, then {@code new TypeResolver().where(formal, actual)} will {@linkplain
* #resolveType resolve} {@code ParameterizedType List<T>} to {@code List<String>}, and resolve
* {@code Map<T, Something>} to {@code Map<String, Something>} etc. Similarly, {@code formal} and
* {@code actual} can be {@code Map<K, V>} and {@code Map<String, Integer>} respectively, or they
* can be {@code E[]} and {@code String[]} respectively, or even any arbitrary combination
* thereof.
*
* @param formal The type whose type variables or itself is mapped to other type(s). It's almost
* always a bug if {@code formal} isn't a type variable and contains no type variable. Make
* sure you are passing the two parameters in the right order.
* @param actual The type that the formal type variable(s) are mapped to. It can be or contain yet
* other type variables, in which case these type variables will be further resolved if
* corresponding mappings exist in the current {@code TypeResolver} instance.
*/
public final TypeResolver where(Type formal, Type actual) {
Map<TypeVariable<?>, Type> mappings = Maps.newHashMap();
populateTypeMappings(mappings, checkNotNull(formal), checkNotNull(actual));
return where(mappings);
}
/** Returns a new {@code TypeResolver} with {@code variable} mapping to {@code type}. */
final TypeResolver where(Map<? extends TypeVariable<?>, ? extends Type> mappings) {
ImmutableMap.Builder<TypeVariable<?>, Type> builder = ImmutableMap.builder();
builder.putAll(typeTable);
for (Map.Entry<? extends TypeVariable<?>, ? extends Type> mapping : mappings.entrySet()) {
TypeVariable<?> variable = mapping.getKey();
Type type = mapping.getValue();
checkArgument(!variable.equals(type), "Type variable %s bound to itself", variable);
builder.put(variable, type);
}
return new TypeResolver(builder.build());
}
private static void populateTypeMappings(
Map<TypeVariable<?>, Type> mappings, Type from, Type to) {
if (from.equals(to)) {
return;
}
if (from instanceof TypeVariable) {
mappings.put((TypeVariable<?>) from, to);
} else if (from instanceof GenericArrayType) {
populateTypeMappings(mappings,
((GenericArrayType) from).getGenericComponentType(),
checkNonNullArgument(Types.getComponentType(to), "%s is not an array type.", to));
} else if (from instanceof ParameterizedType) {
ParameterizedType fromParameterizedType = (ParameterizedType) from;
ParameterizedType toParameterizedType = expectArgument(ParameterizedType.class, to);
checkArgument(fromParameterizedType.getRawType().equals(toParameterizedType.getRawType()),
"Inconsistent raw type: %s vs. %s", from, to);
Type[] fromArgs = fromParameterizedType.getActualTypeArguments();
Type[] toArgs = toParameterizedType.getActualTypeArguments();
checkArgument(fromArgs.length == toArgs.length);
for (int i = 0; i < fromArgs.length; i++) {
populateTypeMappings(mappings, fromArgs[i], toArgs[i]);
}
} else if (from instanceof WildcardType) {
WildcardType fromWildcardType = (WildcardType) from;
WildcardType toWildcardType = expectArgument(WildcardType.class, to);
Type[] fromUpperBounds = fromWildcardType.getUpperBounds();
Type[] toUpperBounds = toWildcardType.getUpperBounds();
Type[] fromLowerBounds = fromWildcardType.getLowerBounds();
Type[] toLowerBounds = toWildcardType.getLowerBounds();
checkArgument(
fromUpperBounds.length == toUpperBounds.length
&& fromLowerBounds.length == toLowerBounds.length,
"Incompatible type: %s vs. %s", from, to);
for (int i = 0; i < fromUpperBounds.length; i++) {
populateTypeMappings(mappings, fromUpperBounds[i], toUpperBounds[i]);
}
for (int i = 0; i < fromLowerBounds.length; i++) {
populateTypeMappings(mappings, fromLowerBounds[i], toLowerBounds[i]);
}
} else {
throw new IllegalArgumentException("No type mapping from " + from);
}
}
/**
* Resolves all type variables in {@code type} and all downstream types and
* returns a corresponding type with type variables resolved.
*/
public final Type resolveType(Type type) {
checkNotNull(type);
if (type instanceof TypeVariable) {
return resolveTypeVariable((TypeVariable<?>) type);
} else if (type instanceof ParameterizedType) {
return resolveParameterizedType((ParameterizedType) type);
} else if (type instanceof GenericArrayType) {
return resolveGenericArrayType((GenericArrayType) type);
} else if (type instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) type;
return new Types.WildcardTypeImpl(
resolveTypes(wildcardType.getLowerBounds()),
resolveTypes(wildcardType.getUpperBounds()));
} else {
// if Class<?>, no resolution needed, we are done.
return type;
}
}
private Type[] resolveTypes(Type[] types) {
Type[] result = new Type[types.length];
for (int i = 0; i < types.length; i++) {
result[i] = resolveType(types[i]);
}
return result;
}
private Type resolveGenericArrayType(GenericArrayType type) {
Type componentType = resolveType(type.getGenericComponentType());
return Types.newArrayType(componentType);
}
private Type resolveTypeVariable(final TypeVariable<?> var) {
final TypeResolver unguarded = this;
TypeResolver guarded = new TypeResolver(typeTable) {
@Override Type resolveTypeVariable(
TypeVariable<?> intermediateVar, TypeResolver guardedResolver) {
if (intermediateVar.getGenericDeclaration().equals(var.getGenericDeclaration())) {
return intermediateVar;
}
return unguarded.resolveTypeVariable(intermediateVar, guardedResolver);
}
};
return resolveTypeVariable(var, guarded);
}
/**
* Resolves {@code var} using the encapsulated type mapping. If it maps to yet another
* non-reified type, {@code guardedResolver} is used to do further resolution, which doesn't try
* to resolve any type variable on generic declarations that are already being resolved.
*/
Type resolveTypeVariable(TypeVariable<?> var, TypeResolver guardedResolver) {
Type type = typeTable.get(var);
if (type == null) {
Type[] bounds = var.getBounds();
if (bounds.length == 0) {
return var;
}
return Types.newTypeVariable(
var.getGenericDeclaration(),
var.getName(),
guardedResolver.resolveTypes(bounds));
}
return guardedResolver.resolveType(type); // in case the type is yet another type variable.
}
private ParameterizedType resolveParameterizedType(ParameterizedType type) {
Type owner = type.getOwnerType();
Type resolvedOwner = (owner == null) ? null : resolveType(owner);
Type resolvedRawType = resolveType(type.getRawType());
Type[] vars = type.getActualTypeArguments();
Type[] resolvedArgs = new Type[vars.length];
for (int i = 0; i < vars.length; i++) {
resolvedArgs[i] = resolveType(vars[i]);
}
return Types.newParameterizedTypeWithOwner(
resolvedOwner, (Class<?>) resolvedRawType, resolvedArgs);
}
private static <T> T checkNonNullArgument(T arg, String format, Object... messageParams) {
checkArgument(arg != null, format, messageParams);
return arg;
}
private static <T> T expectArgument(Class<T> type, Object arg) {
try {
return type.cast(arg);
} catch (ClassCastException e) {
throw new IllegalArgumentException(arg + " is not a " + type.getSimpleName());
}
}
private static final class TypeMappingIntrospector {
private static final WildcardCapturer wildcardCapturer = new WildcardCapturer();
private final Map<TypeVariable<?>, Type> mappings = Maps.newHashMap();
private final Set<Type> introspectedTypes = Sets.newHashSet();
/**
* Returns type mappings using type parameters and type arguments found in
* the generic superclass and the super interfaces of {@code contextClass}.
*/
static ImmutableMap<TypeVariable<?>, Type> getTypeMappings(
Type contextType) {
TypeMappingIntrospector introspector = new TypeMappingIntrospector();
introspector.introspect(wildcardCapturer.capture(contextType));
return ImmutableMap.copyOf(introspector.mappings);
}
private void introspect(Type type) {
if (!introspectedTypes.add(type)) {
return;
}
if (type instanceof ParameterizedType) {
introspectParameterizedType((ParameterizedType) type);
} else if (type instanceof Class) {
introspectClass((Class<?>) type);
} else if (type instanceof TypeVariable) {
for (Type bound : ((TypeVariable<?>) type).getBounds()) {
introspect(bound);
}
} else if (type instanceof WildcardType) {
for (Type bound : ((WildcardType) type).getUpperBounds()) {
introspect(bound);
}
}
}
private void introspectClass(Class<?> clazz) {
introspect(clazz.getGenericSuperclass());
for (Type interfaceType : clazz.getGenericInterfaces()) {
introspect(interfaceType);
}
}
private void introspectParameterizedType(
ParameterizedType parameterizedType) {
Class<?> rawClass = (Class<?>) parameterizedType.getRawType();
TypeVariable<?>[] vars = rawClass.getTypeParameters();
Type[] typeArgs = parameterizedType.getActualTypeArguments();
checkState(vars.length == typeArgs.length);
for (int i = 0; i < vars.length; i++) {
map(vars[i], typeArgs[i]);
}
introspectClass(rawClass);
introspect(parameterizedType.getOwnerType());
}
private void map(final TypeVariable<?> var, final Type arg) {
if (mappings.containsKey(var)) {
// Mapping already established
// This is possible when following both superClass -> enclosingClass
// and enclosingclass -> superClass paths.
// Since we follow the path of superclass first, enclosing second,
// superclass mapping should take precedence.
return;
}
// First, check whether var -> arg forms a cycle
for (Type t = arg; t != null; t = mappings.get(t)) {
if (var.equals(t)) {
// cycle detected, remove the entire cycle from the mapping so that
// each type variable resolves deterministically to itself.
// Otherwise, a F -> T cycle will end up resolving both F and T
// nondeterministically to either F or T.
for (Type x = arg; x != null; x = mappings.remove(x)) {}
return;
}
}
mappings.put(var, arg);
}
}
// This is needed when resolving types against a context with wildcards
// For example:
// class Holder<T> {
// void set(T data) {...}
// }
// Holder<List<?>> should *not* resolve the set() method to set(List<?> data).
// Instead, it should create a capture of the wildcard so that set() rejects any List<T>.
private static final class WildcardCapturer {
private final AtomicInteger id = new AtomicInteger();
Type capture(Type type) {
checkNotNull(type);
if (type instanceof Class) {
return type;
}
if (type instanceof TypeVariable) {
return type;
}
if (type instanceof GenericArrayType) {
GenericArrayType arrayType = (GenericArrayType) type;
return Types.newArrayType(capture(arrayType.getGenericComponentType()));
}
if (type instanceof ParameterizedType) {
ParameterizedType parameterizedType = (ParameterizedType) type;
return Types.newParameterizedTypeWithOwner(
captureNullable(parameterizedType.getOwnerType()),
(Class<?>) parameterizedType.getRawType(),
capture(parameterizedType.getActualTypeArguments()));
}
if (type instanceof WildcardType) {
WildcardType wildcardType = (WildcardType) type;
Type[] lowerBounds = wildcardType.getLowerBounds();
if (lowerBounds.length == 0) { // ? extends something changes to capture-of
Type[] upperBounds = wildcardType.getUpperBounds();
String name = "capture#" + id.incrementAndGet() + "-of ? extends "
+ Joiner.on('&').join(upperBounds);
return Types.newTypeVariable(
WildcardCapturer.class, name, wildcardType.getUpperBounds());
} else {
// TODO(benyu): handle ? super T somehow.
return type;
}
}
throw new AssertionError("must have been one of the known types");
}
private Type captureNullable(@Nullable Type type) {
if (type == null) {
return null;
}
return capture(type);
}
private Type[] capture(Type[] types) {
Type[] result = new Type[types.length];
for (int i = 0; i < types.length; i++) {
result[i] = capture(types[i]);
}
return result;
}
}
}
| Java |
/*
* 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.reflect;
import com.google.common.annotations.Beta;
import com.google.common.collect.ForwardingMap;
import com.google.common.collect.ImmutableMap;
import java.util.Map;
/**
* A type-to-instance map backed by an {@link ImmutableMap}. See also {@link
* MutableTypeToInstanceMap}.
*
* @author Ben Yu
* @since 13.0
*/
@Beta
public final class ImmutableTypeToInstanceMap<B> extends ForwardingMap<TypeToken<? extends B>, B>
implements TypeToInstanceMap<B> {
/** Returns an empty type to instance map. */
public static <B> ImmutableTypeToInstanceMap<B> of() {
return new ImmutableTypeToInstanceMap<B>(ImmutableMap.<TypeToken<? extends B>, B>of());
}
/** Returns a new builder. */
public static <B> Builder<B> builder() {
return new Builder<B>();
}
/**
* A builder for creating immutable type-to-instance maps. Example:
* <pre> {@code
*
* static final ImmutableTypeToInstanceMap<Handler<?>> HANDLERS =
* ImmutableTypeToInstanceMap.<Handler<?>>builder()
* .put(new TypeToken<Handler<Foo>>() {}, new FooHandler())
* .put(new TypeToken<Handler<Bar>>() {}, new SubBarHandler())
* .build();}</pre>
*
* After invoking {@link #build()} it is still possible to add more entries
* and build again. Thus each map generated by this builder will be a superset
* of any map generated before it.
*
* @since 13.0
*/
@Beta
public static final class Builder<B> {
private final ImmutableMap.Builder<TypeToken<? extends B>, B> mapBuilder
= ImmutableMap.builder();
private Builder() {}
/**
* Associates {@code key} with {@code value} in the built map. Duplicate
* keys are not allowed, and will cause {@link #build} to fail.
*/
public <T extends B> Builder<B> put(Class<T> key, T value) {
mapBuilder.put(TypeToken.of(key), value);
return this;
}
/**
* Associates {@code key} with {@code value} in the built map. Duplicate
* keys are not allowed, and will cause {@link #build} to fail.
*/
public <T extends B> Builder<B> put(TypeToken<T> key, T value) {
mapBuilder.put(key.rejectTypeVariables(), value);
return this;
}
/**
* Returns a new immutable type-to-instance map containing the entries
* provided to this builder.
*
* @throws IllegalArgumentException if duplicate keys were added
*/
public ImmutableTypeToInstanceMap<B> build() {
return new ImmutableTypeToInstanceMap<B>(mapBuilder.build());
}
}
private final ImmutableMap<TypeToken<? extends B>, B> delegate;
private ImmutableTypeToInstanceMap(ImmutableMap<TypeToken<? extends B>, B> delegate) {
this.delegate = delegate;
}
@Override public <T extends B> T getInstance(TypeToken<T> type) {
return trustedGet(type.rejectTypeVariables());
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override public <T extends B> T putInstance(TypeToken<T> type, T value) {
throw new UnsupportedOperationException();
}
@Override public <T extends B> T getInstance(Class<T> type) {
return trustedGet(TypeToken.of(type));
}
/**
* Guaranteed to throw an exception and leave the map unmodified.
*
* @throws UnsupportedOperationException always
*/
@Override public <T extends B> T putInstance(Class<T> type, T value) {
throw new UnsupportedOperationException();
}
@Override protected Map<TypeToken<? extends B>, B> delegate() {
return delegate;
}
@SuppressWarnings("unchecked") // value could not get in if not a T
private <T extends B> T trustedGet(TypeToken<T> type) {
return (T) delegate.get(type);
}
}
| Java |
/*
* 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.net;
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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Ascii;
import com.google.common.base.CharMatcher;
import com.google.common.base.Joiner;
import com.google.common.base.Objects;
import com.google.common.base.Splitter;
import com.google.common.collect.ImmutableList;
import java.util.List;
import javax.annotation.Nullable;
/**
* An immutable well-formed internet domain name, such as {@code com} or {@code
* foo.co.uk}. Only syntactic analysis is performed; no DNS lookups or other
* network interactions take place. Thus there is no guarantee that the domain
* actually exists on the internet.
*
* <p>One common use of this class is to determine whether a given string is
* likely to represent an addressable domain on the web -- that is, for a
* candidate string {@code "xxx"}, might browsing to {@code "http://xxx/"}
* result in a webpage being displayed? In the past, this test was frequently
* done by determining whether the domain ended with a {@linkplain
* #isPublicSuffix() public suffix} but was not itself a public suffix. However,
* this test is no longer accurate. There are many domains which are both public
* suffixes and addressable as hosts; {@code "uk.com"} is one example. As a
* result, the only useful test to determine if a domain is a plausible web host
* is {@link #hasPublicSuffix()}. This will return {@code true} for many domains
* which (currently) are not hosts, such as {@code "com"}), but given that any
* public suffix may become a host without warning, it is better to err on the
* side of permissiveness and thus avoid spurious rejection of valid sites.
*
* <p>During construction, names are normalized in two ways:
* <ol>
* <li>ASCII uppercase characters are converted to lowercase.
* <li>Unicode dot separators other than the ASCII period ({@code '.'}) are
* converted to the ASCII period.
* </ol>
* The normalized values will be returned from {@link #name()} and
* {@link #parts()}, and will be reflected in the result of
* {@link #equals(Object)}.
*
* <p><a href="http://en.wikipedia.org/wiki/Internationalized_domain_name">
* internationalized domain names</a> such as {@code 网络.cn} are supported, as
* are the equivalent <a
* href="http://en.wikipedia.org/wiki/Internationalized_domain_name">IDNA
* Punycode-encoded</a> versions.
*
* @author Craig Berry
* @since 5.0
*/
@Beta
@GwtCompatible(emulated = true)
public final class InternetDomainName {
private static final CharMatcher DOTS_MATCHER =
CharMatcher.anyOf(".\u3002\uFF0E\uFF61");
private static final Splitter DOT_SPLITTER = Splitter.on('.');
private static final Joiner DOT_JOINER = Joiner.on('.');
/**
* Value of {@link #publicSuffixIndex} which indicates that no public suffix
* was found.
*/
private static final int NO_PUBLIC_SUFFIX_FOUND = -1;
private static final String DOT_REGEX = "\\.";
/**
* Maximum parts (labels) in a domain name. This value arises from
* the 255-octet limit described in
* <a href="http://www.ietf.org/rfc/rfc2181.txt">RFC 2181</a> part 11 with
* the fact that the encoding of each part occupies at least two bytes
* (dot plus label externally, length byte plus label internally). Thus, if
* all labels have the minimum size of one byte, 127 of them will fit.
*/
private static final int MAX_PARTS = 127;
/**
* Maximum length of a full domain name, including separators, and
* leaving room for the root label. See
* <a href="http://www.ietf.org/rfc/rfc2181.txt">RFC 2181</a> part 11.
*/
private static final int MAX_LENGTH = 253;
/**
* Maximum size of a single part of a domain name. See
* <a href="http://www.ietf.org/rfc/rfc2181.txt">RFC 2181</a> part 11.
*/
private static final int MAX_DOMAIN_PART_LENGTH = 63;
/**
* The full domain name, converted to lower case.
*/
private final String name;
/**
* The parts of the domain name, converted to lower case.
*/
private final ImmutableList<String> parts;
/**
* The index in the {@link #parts()} list at which the public suffix begins.
* For example, for the domain name {@code www.google.co.uk}, the value would
* be 2 (the index of the {@code co} part). The value is negative
* (specifically, {@link #NO_PUBLIC_SUFFIX_FOUND}) if no public suffix was
* found.
*/
private final int publicSuffixIndex;
/**
* Constructor used to implement {@link #from(String)}, and from subclasses.
*/
InternetDomainName(String name) {
// Normalize:
// * ASCII characters to lowercase
// * All dot-like characters to '.'
// * Strip trailing '.'
name = Ascii.toLowerCase(DOTS_MATCHER.replaceFrom(name, '.'));
if (name.endsWith(".")) {
name = name.substring(0, name.length() - 1);
}
checkArgument(name.length() <= MAX_LENGTH,
"Domain name too long: '%s':", name);
this.name = name;
this.parts = ImmutableList.copyOf(DOT_SPLITTER.split(name));
checkArgument(parts.size() <= MAX_PARTS,
"Domain has too many parts: '%s'", name);
checkArgument(validateSyntax(parts), "Not a valid domain name: '%s'", name);
this.publicSuffixIndex = findPublicSuffix();
}
/**
* Returns the index of the leftmost part of the public suffix, or -1 if not
* found. Note that the value defined as the "public suffix" may not be a
* public suffix according to {@link #isPublicSuffix()} if the domain ends
* with an excluded domain pattern such as {@code "nhs.uk"}.
*/
private int findPublicSuffix() {
final int partsSize = parts.size();
for (int i = 0; i < partsSize; i++) {
String ancestorName = DOT_JOINER.join(parts.subList(i, partsSize));
if (TldPatterns.EXACT.contains(ancestorName)) {
return i;
}
// Excluded domains (e.g. !nhs.uk) use the next highest
// domain as the effective public suffix (e.g. uk).
if (TldPatterns.EXCLUDED.contains(ancestorName)) {
return i + 1;
}
if (matchesWildcardPublicSuffix(ancestorName)) {
return i;
}
}
return NO_PUBLIC_SUFFIX_FOUND;
}
/**
* A deprecated synonym for {@link #from(String)}.
*
* @param domain A domain name (not IP address)
* @throws IllegalArgumentException if {@code name} is not syntactically valid
* according to {@link #isValid}
* @since 8.0 (previously named {@code from})
* @deprecated Use {@link #from(String)}
*/
@Deprecated
public static InternetDomainName fromLenient(String domain) {
return from(domain);
}
/**
* Returns an instance of {@link InternetDomainName} after lenient
* validation. Specifically, validation against <a
* href="http://www.ietf.org/rfc/rfc3490.txt">RFC 3490</a>
* ("Internationalizing Domain Names in Applications") is skipped, while
* validation against <a
* href="http://www.ietf.org/rfc/rfc1035.txt">RFC 1035</a> is relaxed in
* the following ways:
* <ul>
* <li>Any part containing non-ASCII characters is considered valid.
* <li>Underscores ('_') are permitted wherever dashes ('-') are permitted.
* <li>Parts other than the final part may start with a digit.
* </ul>
*
*
* @param domain A domain name (not IP address)
* @throws IllegalArgumentException if {@code name} is not syntactically valid
* according to {@link #isValid}
* @since 10.0 (previously named {@code fromLenient})
*/
public static InternetDomainName from(String domain) {
return new InternetDomainName(checkNotNull(domain));
}
/**
* Validation method used by {@from} to ensure that the domain name is
* syntactically valid according to RFC 1035.
*
* @return Is the domain name syntactically valid?
*/
private static boolean validateSyntax(List<String> parts) {
final int lastIndex = parts.size() - 1;
// Validate the last part specially, as it has different syntax rules.
if (!validatePart(parts.get(lastIndex), true)) {
return false;
}
for (int i = 0; i < lastIndex; i++) {
String part = parts.get(i);
if (!validatePart(part, false)) {
return false;
}
}
return true;
}
private static final CharMatcher DASH_MATCHER = CharMatcher.anyOf("-_");
private static final CharMatcher PART_CHAR_MATCHER =
CharMatcher.JAVA_LETTER_OR_DIGIT.or(DASH_MATCHER);
/**
* Helper method for {@link #validateSyntax(List)}. Validates that one part of
* a domain name is valid.
*
* @param part The domain name part to be validated
* @param isFinalPart Is this the final (rightmost) domain part?
* @return Whether the part is valid
*/
private static boolean validatePart(String part, boolean isFinalPart) {
// These tests could be collapsed into one big boolean expression, but
// they have been left as independent tests for clarity.
if (part.length() < 1 || part.length() > MAX_DOMAIN_PART_LENGTH) {
return false;
}
/*
* GWT claims to support java.lang.Character's char-classification methods,
* but it actually only works for ASCII. So for now, assume any non-ASCII
* characters are valid. The only place this seems to be documented is here:
* http://osdir.com/ml/GoogleWebToolkitContributors/2010-03/msg00178.html
*
* <p>ASCII characters in the part are expected to be valid per RFC 1035,
* with underscore also being allowed due to widespread practice.
*/
String asciiChars = CharMatcher.ASCII.retainFrom(part);
if (!PART_CHAR_MATCHER.matchesAllOf(asciiChars)) {
return false;
}
// No initial or final dashes or underscores.
if (DASH_MATCHER.matches(part.charAt(0))
|| DASH_MATCHER.matches(part.charAt(part.length() - 1))) {
return false;
}
/*
* Note that we allow (in contravention of a strict interpretation of the
* relevant RFCs) domain parts other than the last may begin with a digit
* (for example, "3com.com"). It's important to disallow an initial digit in
* the last part; it's the only thing that stops an IPv4 numeric address
* like 127.0.0.1 from looking like a valid domain name.
*/
if (isFinalPart && CharMatcher.DIGIT.matches(part.charAt(0))) {
return false;
}
return true;
}
/**
* Returns the domain name, normalized to all lower case.
*/
public String name() {
return name;
}
/**
* Returns the individual components of this domain name, normalized to all
* lower case. For example, for the domain name {@code mail.google.com}, this
* method returns the list {@code ["mail", "google", "com"]}.
*/
public ImmutableList<String> parts() {
return parts;
}
/**
* Indicates whether this domain name represents a <i>public suffix</i>, as
* defined by the Mozilla Foundation's
* <a href="http://publicsuffix.org/">Public Suffix List</a> (PSL). A public
* suffix is one under which Internet users can directly register names, such
* as {@code com}, {@code co.uk} or {@code pvt.k12.wy.us}. Examples of domain
* names that are <i>not</i> public suffixes include {@code google}, {@code
* google.com} and {@code foo.co.uk}.
*
* @return {@code true} if this domain name appears exactly on the public
* suffix list
* @since 6.0
*/
public boolean isPublicSuffix() {
return publicSuffixIndex == 0;
}
/**
* Indicates whether this domain name ends in a {@linkplain #isPublicSuffix()
* public suffix}, including if it is a public suffix itself. For example,
* returns {@code true} for {@code www.google.com}, {@code foo.co.uk} and
* {@code com}, but not for {@code google} or {@code google.foo}. This is
* the recommended method for determining whether a domain is potentially an
* addressable host.
*
* @since 6.0
*/
public boolean hasPublicSuffix() {
return publicSuffixIndex != NO_PUBLIC_SUFFIX_FOUND;
}
/**
* Returns the {@linkplain #isPublicSuffix() public suffix} portion of the
* domain name, or {@code null} if no public suffix is present.
*
* @since 6.0
*/
public InternetDomainName publicSuffix() {
return hasPublicSuffix() ? ancestor(publicSuffixIndex) : null;
}
/**
* Indicates whether this domain name ends in a {@linkplain #isPublicSuffix()
* public suffix}, while not being a public suffix itself. For example,
* returns {@code true} for {@code www.google.com}, {@code foo.co.uk} and
* {@code bar.ca.us}, but not for {@code google}, {@code com}, or {@code
* google.foo}.
*
* <p><b>Warning:</b> a {@code false} result from this method does not imply
* that the domain does not represent an addressable host, as many public
* suffixes are also addressable hosts. Use {@link #hasPublicSuffix()} for
* that test.
*
* <p>This method can be used to determine whether it will probably be
* possible to set cookies on the domain, though even that depends on
* individual browsers' implementations of cookie controls. See
* <a href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a> for details.
*
* @since 6.0
*/
public boolean isUnderPublicSuffix() {
return publicSuffixIndex > 0;
}
/**
* Indicates whether this domain name is composed of exactly one subdomain
* component followed by a {@linkplain #isPublicSuffix() public suffix}. For
* example, returns {@code true} for {@code google.com} and {@code foo.co.uk},
* but not for {@code www.google.com} or {@code co.uk}.
*
* <p><b>Warning:</b> A {@code true} result from this method does not imply
* that the domain is at the highest level which is addressable as a host, as
* many public suffixes are also addressable hosts. For example, the domain
* {@code bar.uk.com} has a public suffix of {@code uk.com}, so it would
* return {@code true} from this method. But {@code uk.com} is itself an
* addressable host.
*
* <p>This method can be used to determine whether a domain is probably the
* highest level for which cookies may be set, though even that depends on
* individual browsers' implementations of cookie controls. See
* <a href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a> for details.
*
* @since 6.0
*/
public boolean isTopPrivateDomain() {
return publicSuffixIndex == 1;
}
/**
* Returns the portion of this domain name that is one level beneath the
* public suffix. For example, for {@code x.adwords.google.co.uk} it returns
* {@code google.co.uk}, since {@code co.uk} is a public suffix.
*
* <p>If {@link #isTopPrivateDomain()} is true, the current domain name
* instance is returned.
*
* <p>This method should not be used to determine the topmost parent domain
* which is addressable as a host, as many public suffixes are also
* addressable hosts. For example, the domain {@code foo.bar.uk.com} has
* a public suffix of {@code uk.com}, so it would return {@code bar.uk.com}
* from this method. But {@code uk.com} is itself an addressable host.
*
* <p>This method can be used to determine the probable highest level parent
* domain for which cookies may be set, though even that depends on individual
* browsers' implementations of cookie controls.
*
* @throws IllegalStateException if this domain does not end with a
* public suffix
* @since 6.0
*/
public InternetDomainName topPrivateDomain() {
if (isTopPrivateDomain()) {
return this;
}
checkState(isUnderPublicSuffix(), "Not under a public suffix: %s", name);
return ancestor(publicSuffixIndex - 1);
}
/**
* Indicates whether this domain is composed of two or more parts.
*/
public boolean hasParent() {
return parts.size() > 1;
}
/**
* Returns an {@code InternetDomainName} that is the immediate ancestor of
* this one; that is, the current domain with the leftmost part removed. For
* example, the parent of {@code www.google.com} is {@code google.com}.
*
* @throws IllegalStateException if the domain has no parent, as determined
* by {@link #hasParent}
*/
public InternetDomainName parent() {
checkState(hasParent(), "Domain '%s' has no parent", name);
return ancestor(1);
}
/**
* Returns the ancestor of the current domain at the given number of levels
* "higher" (rightward) in the subdomain list. The number of levels must be
* non-negative, and less than {@code N-1}, where {@code N} is the number of
* parts in the domain.
*
* <p>TODO: Reasonable candidate for addition to public API.
*/
private InternetDomainName ancestor(int levels) {
return from(DOT_JOINER.join(parts.subList(levels, parts.size())));
}
/**
* Creates and returns a new {@code InternetDomainName} by prepending the
* argument and a dot to the current name. For example, {@code
* InternetDomainName.from("foo.com").child("www.bar")} returns a new
* {@code InternetDomainName} with the value {@code www.bar.foo.com}. Only
* lenient validation is performed, as described {@link #from(String) here}.
*
* @throws NullPointerException if leftParts is null
* @throws IllegalArgumentException if the resulting name is not valid
*/
public InternetDomainName child(String leftParts) {
return from(checkNotNull(leftParts) + "." + name);
}
/**
* A deprecated synonym for {@link #isValid(String)}.
*
* @since 8.0 (previously named {@code isValid})
* @deprecated Use {@link #isValid(String)} instead
*/
@Deprecated
public static boolean isValidLenient(String name) {
return isValid(name);
}
/**
* Indicates whether the argument is a syntactically valid domain name using
* lenient validation. Specifically, validation against <a
* href="http://www.ietf.org/rfc/rfc3490.txt">RFC 3490</a>
* ("Internationalizing Domain Names in Applications") is skipped.
*
* <p>The following two code snippets are equivalent:
*
* <pre> {@code
*
* domainName = InternetDomainName.isValid(name)
* ? InternetDomainName.from(name)
* : DEFAULT_DOMAIN;
* }</pre>
*
* <pre> {@code
*
* try {
* domainName = InternetDomainName.from(name);
* } catch (IllegalArgumentException e) {
* domainName = DEFAULT_DOMAIN;
* }}</pre>
*
* @since 8.0 (previously named {@code isValidLenient})
*/
public static boolean isValid(String name) {
try {
from(name);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Does the domain name match one of the "wildcard" patterns (e.g.
* {@code "*.ar"})?
*/
private static boolean matchesWildcardPublicSuffix(String domain) {
final String[] pieces = domain.split(DOT_REGEX, 2);
return pieces.length == 2 && TldPatterns.UNDER.contains(pieces[1]);
}
// TODO: specify this to return the same as name(); remove name()
@Override
public String toString() {
return Objects.toStringHelper(this).add("name", name).toString();
}
/**
* Equality testing is based on the text supplied by the caller,
* after normalization as described in the class documentation. For
* example, a non-ASCII Unicode domain name and the Punycode version
* of the same domain name would not be considered equal.
*
*/
@Override
public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof InternetDomainName) {
InternetDomainName that = (InternetDomainName) object;
return this.name.equals(that.name);
}
return false;
}
@Override
public int hashCode() {
return name.hashCode();
}
}
| Java |
/*
* 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.net;
import static com.google.common.base.CharMatcher.ASCII;
import static com.google.common.base.CharMatcher.JAVA_ISO_CONTROL;
import static com.google.common.base.Charsets.UTF_8;
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 com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Ascii;
import com.google.common.base.CharMatcher;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import com.google.common.base.Joiner.MapJoiner;
import com.google.common.base.Objects;
import com.google.common.base.Optional;
import com.google.common.collect.ImmutableListMultimap;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableMultiset;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Multimap;
import com.google.common.collect.Multimaps;
import java.nio.charset.Charset;
import java.nio.charset.IllegalCharsetNameException;
import java.nio.charset.UnsupportedCharsetException;
import java.util.Collection;
import java.util.Map;
import java.util.Map.Entry;
import javax.annotation.Nullable;
import javax.annotation.concurrent.Immutable;
/**
* Represents an <a href="http://en.wikipedia.org/wiki/Internet_media_type">Internet Media Type</a>
* (also known as a MIME Type or Content Type). This class also supports the concept of media ranges
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.1">defined by HTTP/1.1</a>.
* As such, the {@code *} character is treated as a wildcard and is used to represent any acceptable
* type or subtype value. A media type may not have wildcard type with a declared subtype. The
* {@code *} character has no special meaning as part of a parameter. All values for type, subtype,
* parameter attributes or parameter values must be valid according to RFCs
* <a href="http://www.ietf.org/rfc/rfc2045.txt">2045</a> and
* <a href="http://www.ietf.org/rfc/rfc2046.txt">2046</a>.
*
* <p>All portions of the media type that are case-insensitive (type, subtype, parameter attributes)
* are normalized to lowercase. The value of the {@code charset} parameter is normalized to
* lowercase, but all others are left as-is.
*
* <p>Note that this specifically does <strong>not</strong> represent the value of the MIME
* {@code Content-Type} header and as such has no support for header-specific considerations such as
* line folding and comments.
*
* <p>For media types that take a charset the predefined constants default to UTF-8 and have a
* "_UTF_8" suffix. To get a version without a character set, use {@link #withoutParameters}.
*
* @since 12.0
*
* @author Gregory Kick
*/
@Beta
@GwtCompatible
@Immutable
public final class MediaType {
private static final String CHARSET_ATTRIBUTE = "charset";
private static final ImmutableListMultimap<String, String> UTF_8_CONSTANT_PARAMETERS =
ImmutableListMultimap.of(CHARSET_ATTRIBUTE, Ascii.toLowerCase(UTF_8.name()));
/** Matcher for type, subtype and attributes. */
private static final CharMatcher TOKEN_MATCHER = ASCII.and(JAVA_ISO_CONTROL.negate())
.and(CharMatcher.isNot(' '))
.and(CharMatcher.noneOf("()<>@,;:\\\"/[]?="));
private static final CharMatcher QUOTED_TEXT_MATCHER = ASCII
.and(CharMatcher.noneOf("\"\\\r"));
/*
* This matches the same characters as linear-white-space from RFC 822, but we make no effort to
* enforce any particular rules with regards to line folding as stated in the class docs.
*/
private static final CharMatcher LINEAR_WHITE_SPACE = CharMatcher.anyOf(" \t\r\n");
// TODO(gak): make these public?
private static final String APPLICATION_TYPE = "application";
private static final String AUDIO_TYPE = "audio";
private static final String IMAGE_TYPE = "image";
private static final String TEXT_TYPE = "text";
private static final String VIDEO_TYPE = "video";
private static final String WILDCARD = "*";
/*
* The following constants are grouped by their type and ordered alphabetically by the constant
* name within that type. The constant name should be a sensible identifier that is closest to the
* "common name" of the media. This is often, but not necessarily the same as the subtype.
*
* Be sure to declare all constants with the type and subtype in all lowercase.
*
* When adding constants, be sure to add an entry into the KNOWN_TYPES map. For types that
* take a charset (e.g. all text/* types), default to UTF-8 and suffix with "_UTF_8".
*/
public static final MediaType ANY_TYPE = createConstant(WILDCARD, WILDCARD);
public static final MediaType ANY_TEXT_TYPE = createConstant(TEXT_TYPE, WILDCARD);
public static final MediaType ANY_IMAGE_TYPE = createConstant(IMAGE_TYPE, WILDCARD);
public static final MediaType ANY_AUDIO_TYPE = createConstant(AUDIO_TYPE, WILDCARD);
public static final MediaType ANY_VIDEO_TYPE = createConstant(VIDEO_TYPE, WILDCARD);
public static final MediaType ANY_APPLICATION_TYPE = createConstant(APPLICATION_TYPE, WILDCARD);
/* text types */
public static final MediaType CACHE_MANIFEST_UTF_8 =
createConstantUtf8(TEXT_TYPE, "cache-manifest");
public static final MediaType CSS_UTF_8 = createConstantUtf8(TEXT_TYPE, "css");
public static final MediaType CSV_UTF_8 = createConstantUtf8(TEXT_TYPE, "csv");
public static final MediaType HTML_UTF_8 = createConstantUtf8(TEXT_TYPE, "html");
public static final MediaType I_CALENDAR_UTF_8 = createConstantUtf8(TEXT_TYPE, "calendar");
public static final MediaType PLAIN_TEXT_UTF_8 = createConstantUtf8(TEXT_TYPE, "plain");
/**
* <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares
* {@link #JAVASCRIPT_UTF_8 application/javascript} to be the correct media type for JavaScript,
* but this may be necessary in certain situations for compatibility.
*/
public static final MediaType TEXT_JAVASCRIPT_UTF_8 = createConstantUtf8(TEXT_TYPE, "javascript");
public static final MediaType VCARD_UTF_8 = createConstantUtf8(TEXT_TYPE, "vcard");
public static final MediaType WML_UTF_8 = createConstantUtf8(TEXT_TYPE, "vnd.wap.wml");
public static final MediaType XML_UTF_8 = createConstantUtf8(TEXT_TYPE, "xml");
/* image types */
public static final MediaType BMP = createConstant(IMAGE_TYPE, "bmp");
public static final MediaType GIF = createConstant(IMAGE_TYPE, "gif");
public static final MediaType ICO = createConstant(IMAGE_TYPE, "vnd.microsoft.icon");
public static final MediaType JPEG = createConstant(IMAGE_TYPE, "jpeg");
public static final MediaType PNG = createConstant(IMAGE_TYPE, "png");
public static final MediaType SVG_UTF_8 = createConstantUtf8(IMAGE_TYPE, "svg+xml");
public static final MediaType TIFF = createConstant(IMAGE_TYPE, "tiff");
public static final MediaType WEBP = createConstant(IMAGE_TYPE, "webp");
/* audio types */
public static final MediaType MP4_AUDIO = createConstant(AUDIO_TYPE, "mp4");
public static final MediaType MPEG_AUDIO = createConstant(AUDIO_TYPE, "mpeg");
public static final MediaType OGG_AUDIO = createConstant(AUDIO_TYPE, "ogg");
public static final MediaType WEBM_AUDIO = createConstant(AUDIO_TYPE, "webm");
/* video types */
public static final MediaType MP4_VIDEO = createConstant(VIDEO_TYPE, "mp4");
public static final MediaType MPEG_VIDEO = createConstant(VIDEO_TYPE, "mpeg");
public static final MediaType OGG_VIDEO = createConstant(VIDEO_TYPE, "ogg");
public static final MediaType QUICKTIME = createConstant(VIDEO_TYPE, "quicktime");
public static final MediaType WEBM_VIDEO = createConstant(VIDEO_TYPE, "webm");
public static final MediaType WMV = createConstant(VIDEO_TYPE, "x-ms-wmv");
/* application types */
public static final MediaType ATOM_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "atom+xml");
public static final MediaType BZIP2 = createConstant(APPLICATION_TYPE, "x-bzip2");
public static final MediaType FORM_DATA = createConstant(APPLICATION_TYPE,
"x-www-form-urlencoded");
public static final MediaType GZIP = createConstant(APPLICATION_TYPE, "x-gzip");
/**
* <a href="http://www.rfc-editor.org/rfc/rfc4329.txt">RFC 4329</a> declares this to be the
* correct media type for JavaScript, but {@link #TEXT_JAVASCRIPT_UTF_8 text/javascript} may be
* necessary in certain situations for compatibility.
*/
public static final MediaType JAVASCRIPT_UTF_8 =
createConstantUtf8(APPLICATION_TYPE, "javascript");
public static final MediaType JSON_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "json");
public static final MediaType KML = createConstant(APPLICATION_TYPE, "vnd.google-earth.kml+xml");
public static final MediaType KMZ = createConstant(APPLICATION_TYPE, "vnd.google-earth.kmz");
public static final MediaType MBOX = createConstant(APPLICATION_TYPE, "mbox");
public static final MediaType MICROSOFT_EXCEL = createConstant(APPLICATION_TYPE, "vnd.ms-excel");
public static final MediaType MICROSOFT_POWERPOINT =
createConstant(APPLICATION_TYPE, "vnd.ms-powerpoint");
public static final MediaType MICROSOFT_WORD = createConstant(APPLICATION_TYPE, "msword");
public static final MediaType OCTET_STREAM = createConstant(APPLICATION_TYPE, "octet-stream");
public static final MediaType OGG_CONTAINER = createConstant(APPLICATION_TYPE, "ogg");
public static final MediaType OOXML_DOCUMENT = createConstant(APPLICATION_TYPE,
"vnd.openxmlformats-officedocument.wordprocessingml.document");
public static final MediaType OOXML_PRESENTATION = createConstant(APPLICATION_TYPE,
"vnd.openxmlformats-officedocument.presentationml.presentation");
public static final MediaType OOXML_SHEET =
createConstant(APPLICATION_TYPE, "vnd.openxmlformats-officedocument.spreadsheetml.sheet");
public static final MediaType OPENDOCUMENT_GRAPHICS =
createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.graphics");
public static final MediaType OPENDOCUMENT_PRESENTATION =
createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.presentation");
public static final MediaType OPENDOCUMENT_SPREADSHEET =
createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.spreadsheet");
public static final MediaType OPENDOCUMENT_TEXT =
createConstant(APPLICATION_TYPE, "vnd.oasis.opendocument.text");
public static final MediaType PDF = createConstant(APPLICATION_TYPE, "pdf");
public static final MediaType POSTSCRIPT = createConstant(APPLICATION_TYPE, "postscript");
public static final MediaType RTF_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rtf");
public static final MediaType SHOCKWAVE_FLASH = createConstant(APPLICATION_TYPE,
"x-shockwave-flash");
public static final MediaType SKETCHUP = createConstant(APPLICATION_TYPE, "vnd.sketchup.skp");
public static final MediaType TAR = createConstant(APPLICATION_TYPE, "x-tar");
public static final MediaType XHTML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xhtml+xml");
public static final MediaType ZIP = createConstant(APPLICATION_TYPE, "zip");
private static final ImmutableMap<MediaType, MediaType> KNOWN_TYPES =
new ImmutableMap.Builder<MediaType, MediaType>()
.put(ANY_TYPE, ANY_TYPE)
.put(ANY_TEXT_TYPE, ANY_TEXT_TYPE)
.put(ANY_IMAGE_TYPE, ANY_IMAGE_TYPE)
.put(ANY_AUDIO_TYPE, ANY_AUDIO_TYPE)
.put(ANY_VIDEO_TYPE, ANY_VIDEO_TYPE)
.put(ANY_APPLICATION_TYPE, ANY_APPLICATION_TYPE)
/* text types */
.put(CACHE_MANIFEST_UTF_8, CACHE_MANIFEST_UTF_8)
.put(CSS_UTF_8, CSS_UTF_8)
.put(CSV_UTF_8, CSV_UTF_8)
.put(HTML_UTF_8, HTML_UTF_8)
.put(I_CALENDAR_UTF_8, I_CALENDAR_UTF_8)
.put(PLAIN_TEXT_UTF_8, PLAIN_TEXT_UTF_8)
.put(TEXT_JAVASCRIPT_UTF_8, TEXT_JAVASCRIPT_UTF_8)
.put(VCARD_UTF_8, VCARD_UTF_8)
.put(WML_UTF_8, WML_UTF_8)
.put(XML_UTF_8, XML_UTF_8)
/* image types */
.put(BMP, BMP)
.put(GIF, GIF)
.put(ICO, ICO)
.put(JPEG, JPEG)
.put(PNG, PNG)
.put(SVG_UTF_8, SVG_UTF_8)
.put(TIFF, TIFF)
.put(WEBP, WEBP)
/* audio types */
.put(MP4_AUDIO, MP4_AUDIO)
.put(MPEG_AUDIO, MPEG_AUDIO)
.put(OGG_AUDIO, OGG_AUDIO)
.put(WEBM_AUDIO, WEBM_AUDIO)
/* video types */
.put(MP4_VIDEO, MP4_VIDEO)
.put(MPEG_VIDEO, MPEG_VIDEO)
.put(OGG_VIDEO, OGG_VIDEO)
.put(QUICKTIME, QUICKTIME)
.put(WEBM_VIDEO, WEBM_VIDEO)
.put(WMV, WMV)
/* application types */
.put(ATOM_UTF_8, ATOM_UTF_8)
.put(BZIP2, BZIP2)
.put(FORM_DATA, FORM_DATA)
.put(GZIP, GZIP)
.put(JAVASCRIPT_UTF_8, JAVASCRIPT_UTF_8)
.put(JSON_UTF_8, JSON_UTF_8)
.put(KML, KML)
.put(KMZ, KMZ)
.put(MBOX, MBOX)
.put(MICROSOFT_EXCEL, MICROSOFT_EXCEL)
.put(MICROSOFT_POWERPOINT, MICROSOFT_POWERPOINT)
.put(MICROSOFT_WORD, MICROSOFT_WORD)
.put(OCTET_STREAM, OCTET_STREAM)
.put(OGG_CONTAINER, OGG_CONTAINER)
.put(OOXML_DOCUMENT, OOXML_DOCUMENT)
.put(OOXML_PRESENTATION, OOXML_PRESENTATION)
.put(OOXML_SHEET, OOXML_SHEET)
.put(OPENDOCUMENT_GRAPHICS, OPENDOCUMENT_GRAPHICS)
.put(OPENDOCUMENT_PRESENTATION, OPENDOCUMENT_PRESENTATION)
.put(OPENDOCUMENT_SPREADSHEET, OPENDOCUMENT_SPREADSHEET)
.put(OPENDOCUMENT_TEXT, OPENDOCUMENT_TEXT)
.put(PDF, PDF)
.put(POSTSCRIPT, POSTSCRIPT)
.put(RTF_UTF_8, RTF_UTF_8)
.put(SHOCKWAVE_FLASH, SHOCKWAVE_FLASH)
.put(SKETCHUP, SKETCHUP)
.put(TAR, TAR)
.put(XHTML_UTF_8, XHTML_UTF_8)
.put(ZIP, ZIP)
.build();
private final String type;
private final String subtype;
private final ImmutableListMultimap<String, String> parameters;
private MediaType(String type, String subtype,
ImmutableListMultimap<String, String> parameters) {
this.type = type;
this.subtype = subtype;
this.parameters = parameters;
}
private static MediaType createConstant(String type, String subtype) {
return new MediaType(type, subtype, ImmutableListMultimap.<String, String>of());
}
private static MediaType createConstantUtf8(String type, String subtype) {
return new MediaType(type, subtype, UTF_8_CONSTANT_PARAMETERS);
}
/** Returns the top-level media type. For example, {@code "text"} in {@code "text/plain"}. */
public String type() {
return type;
}
/** Returns the media subtype. For example, {@code "plain"} in {@code "text/plain"}. */
public String subtype() {
return subtype;
}
/** Returns a multimap containing the parameters of this media type. */
public ImmutableListMultimap<String, String> parameters() {
return parameters;
}
private Map<String, ImmutableMultiset<String>> parametersAsMap() {
return Maps.transformValues(parameters.asMap(),
new Function<Collection<String>, ImmutableMultiset<String>>() {
@Override public ImmutableMultiset<String> apply(Collection<String> input) {
return ImmutableMultiset.copyOf(input);
}
});
}
/**
* Returns an optional charset for the value of the charset parameter if it is specified.
*
* @throws IllegalStateException if multiple charset values have been set for this media type
* @throws IllegalCharsetNameException if a charset value is present, but illegal
* @throws UnsupportedCharsetException if a charset value is present, but no support is available
* in this instance of the Java virtual machine
*/
public Optional<Charset> charset() {
ImmutableSet<String> charsetValues = ImmutableSet.copyOf(parameters.get(CHARSET_ATTRIBUTE));
switch (charsetValues.size()) {
case 0:
return Optional.absent();
case 1:
return Optional.of(Charset.forName(Iterables.getOnlyElement(charsetValues)));
default:
throw new IllegalStateException("Multiple charset values defined: " + charsetValues);
}
}
/**
* Returns a new instance with the same type and subtype as this instance, but without any
* parameters.
*/
public MediaType withoutParameters() {
return parameters.isEmpty() ? this : create(type, subtype);
}
/**
* <em>Replaces</em> all parameters with the given parameters.
*
* @throws IllegalArgumentException if any parameter or value is invalid
*/
public MediaType withParameters(Multimap<String, String> parameters) {
return create(type, subtype, parameters);
}
/**
* <em>Replaces</em> all parameters with the given attribute with a single parameter with the
* given value. If multiple parameters with the same attributes are necessary use
* {@link #withParameters}. Prefer {@link #withCharset} for setting the {@code charset} parameter
* when using a {@link Charset} object.
*
* @throws IllegalArgumentException if either {@code attribute} or {@code value} is invalid
*/
public MediaType withParameter(String attribute, String value) {
checkNotNull(attribute);
checkNotNull(value);
String normalizedAttribute = normalizeToken(attribute);
ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
for (Entry<String, String> entry : parameters.entries()) {
String key = entry.getKey();
if (!normalizedAttribute.equals(key)) {
builder.put(key, entry.getValue());
}
}
builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value));
MediaType mediaType = new MediaType(type, subtype, builder.build());
// Return one of the constants if the media type is a known type.
return Objects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
/**
* Returns a new instance with the same type and subtype as this instance, with the
* {@code charset} parameter set to the {@link Charset#name name} of the given charset. Only one
* {@code charset} parameter will be present on the new instance regardless of the number set on
* this one.
*
* <p>If a charset must be specified that is not supported on this JVM (and thus is not
* representable as a {@link Charset} instance, use {@link #withParameter}.
*/
public MediaType withCharset(Charset charset) {
checkNotNull(charset);
return withParameter(CHARSET_ATTRIBUTE, charset.name());
}
/** Returns true if either the type or subtype is the wildcard. */
public boolean hasWildcard() {
return WILDCARD.equals(type) || WILDCARD.equals(subtype);
}
/**
* Returns {@code true} if this instance falls within the range (as defined by
* <a href="http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html">the HTTP Accept header</a>)
* given by the argument according to three criteria:
*
* <ol>
* <li>The type of the argument is the wildcard or equal to the type of this instance.
* <li>The subtype of the argument is the wildcard or equal to the subtype of this instance.
* <li>All of the parameters present in the argument are present in this instance.
* </ol>
*
* For example: <pre> {@code
* PLAIN_TEXT_UTF_8.is(PLAIN_TEXT_UTF_8) // true
* PLAIN_TEXT_UTF_8.is(HTML_UTF_8) // false
* PLAIN_TEXT_UTF_8.is(ANY_TYPE) // true
* PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE) // true
* PLAIN_TEXT_UTF_8.is(ANY_IMAGE_TYPE) // false
* PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_8)) // true
* PLAIN_TEXT_UTF_8.withoutParameters().is(ANY_TEXT_TYPE.withCharset(UTF_8)) // false
* PLAIN_TEXT_UTF_8.is(ANY_TEXT_TYPE.withCharset(UTF_16)) // false}</pre>
*
* <p>Note that while it is possible to have the same parameter declared multiple times within a
* media type this method does not consider the number of occurrences of a parameter. For
* example, {@code "text/plain; charset=UTF-8"} satisfies
* {@code "text/plain; charset=UTF-8; charset=UTF-8"}.
*/
public boolean is(MediaType mediaTypeRange) {
return (mediaTypeRange.type.equals(WILDCARD) || mediaTypeRange.type.equals(this.type))
&& (mediaTypeRange.subtype.equals(WILDCARD) || mediaTypeRange.subtype.equals(this.subtype))
&& this.parameters.entries().containsAll(mediaTypeRange.parameters.entries());
}
/**
* Creates a new media type with the given type and subtype.
*
* @throws IllegalArgumentException if type or subtype is invalid or if a wildcard is used for the
* type, but not the subtype.
*/
public static MediaType create(String type, String subtype) {
return create(type, subtype, ImmutableListMultimap.<String, String>of());
}
/**
* Creates a media type with the "application" type and the given subtype.
*
* @throws IllegalArgumentException if subtype is invalid
*/
static MediaType createApplicationType(String subtype) {
return create(APPLICATION_TYPE, subtype);
}
/**
* Creates a media type with the "audio" type and the given subtype.
*
* @throws IllegalArgumentException if subtype is invalid
*/
static MediaType createAudioType(String subtype) {
return create(AUDIO_TYPE, subtype);
}
/**
* Creates a media type with the "image" type and the given subtype.
*
* @throws IllegalArgumentException if subtype is invalid
*/
static MediaType createImageType(String subtype) {
return create(IMAGE_TYPE, subtype);
}
/**
* Creates a media type with the "text" type and the given subtype.
*
* @throws IllegalArgumentException if subtype is invalid
*/
static MediaType createTextType(String subtype) {
return create(TEXT_TYPE, subtype);
}
/**
* Creates a media type with the "video" type and the given subtype.
*
* @throws IllegalArgumentException if subtype is invalid
*/
static MediaType createVideoType(String subtype) {
return create(VIDEO_TYPE, subtype);
}
private static MediaType create(String type, String subtype,
Multimap<String, String> parameters) {
checkNotNull(type);
checkNotNull(subtype);
checkNotNull(parameters);
String normalizedType = normalizeToken(type);
String normalizedSubtype = normalizeToken(subtype);
checkArgument(!WILDCARD.equals(normalizedType) || WILDCARD.equals(normalizedSubtype),
"A wildcard type cannot be used with a non-wildcard subtype");
ImmutableListMultimap.Builder<String, String> builder = ImmutableListMultimap.builder();
for (Entry<String, String> entry : parameters.entries()) {
String attribute = normalizeToken(entry.getKey());
builder.put(attribute, normalizeParameterValue(attribute, entry.getValue()));
}
MediaType mediaType = new MediaType(normalizedType, normalizedSubtype, builder.build());
// Return one of the constants if the media type is a known type.
return Objects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType);
}
private static String normalizeToken(String token) {
checkArgument(TOKEN_MATCHER.matchesAllOf(token));
return Ascii.toLowerCase(token);
}
private static String normalizeParameterValue(String attribute, String value) {
return CHARSET_ATTRIBUTE.equals(attribute) ? Ascii.toLowerCase(value) : value;
}
/**
* Parses a media type from its string representation.
*
* @throws IllegalArgumentException if the input is not parsable
*/
public static MediaType parse(String input) {
checkNotNull(input);
Tokenizer tokenizer = new Tokenizer(input);
try {
String type = tokenizer.consumeToken(TOKEN_MATCHER);
tokenizer.consumeCharacter('/');
String subtype = tokenizer.consumeToken(TOKEN_MATCHER);
ImmutableListMultimap.Builder<String, String> parameters = ImmutableListMultimap.builder();
while (tokenizer.hasMore()) {
tokenizer.consumeCharacter(';');
tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE);
String attribute = tokenizer.consumeToken(TOKEN_MATCHER);
tokenizer.consumeCharacter('=');
final String value;
if ('"' == tokenizer.previewChar()) {
tokenizer.consumeCharacter('"');
StringBuilder valueBuilder = new StringBuilder();
while ('"' != tokenizer.previewChar()) {
if ('\\' == tokenizer.previewChar()) {
tokenizer.consumeCharacter('\\');
valueBuilder.append(tokenizer.consumeCharacter(ASCII));
} else {
valueBuilder.append(tokenizer.consumeToken(QUOTED_TEXT_MATCHER));
}
}
value = valueBuilder.toString();
tokenizer.consumeCharacter('"');
} else {
value = tokenizer.consumeToken(TOKEN_MATCHER);
}
parameters.put(attribute, value);
}
return create(type, subtype, parameters.build());
} catch (IllegalStateException e) {
throw new IllegalArgumentException(e);
}
}
private static final class Tokenizer {
final String input;
int position = 0;
Tokenizer(String input) {
this.input = input;
}
String consumeTokenIfPresent(CharMatcher matcher) {
checkState(hasMore());
int startPosition = position;
position = matcher.negate().indexIn(input, startPosition);
return hasMore() ? input.substring(startPosition, position) : input.substring(startPosition);
}
String consumeToken(CharMatcher matcher) {
int startPosition = position;
String token = consumeTokenIfPresent(matcher);
checkState(position != startPosition);
return token;
}
char consumeCharacter(CharMatcher matcher) {
checkState(hasMore());
char c = previewChar();
checkState(matcher.matches(c));
position++;
return c;
}
char consumeCharacter(char c) {
checkState(hasMore());
checkState(previewChar() == c);
position++;
return c;
}
char previewChar() {
checkState(hasMore());
return input.charAt(position);
}
boolean hasMore() {
return (position >= 0) && (position < input.length());
}
}
@Override public boolean equals(@Nullable Object obj) {
if (obj == this) {
return true;
} else if (obj instanceof MediaType) {
MediaType that = (MediaType) obj;
return this.type.equals(that.type)
&& this.subtype.equals(that.subtype)
// compare parameters regardless of order
&& this.parametersAsMap().equals(that.parametersAsMap());
} else {
return false;
}
}
@Override public int hashCode() {
return Objects.hashCode(type, subtype, parametersAsMap());
}
private static final MapJoiner PARAMETER_JOINER = Joiner.on("; ").withKeyValueSeparator("=");
/**
* Returns the string representation of this media type in the format described in <a
* href="http://www.ietf.org/rfc/rfc2045.txt">RFC 2045</a>.
*/
@Override public String toString() {
StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype);
if (!parameters.isEmpty()) {
builder.append("; ");
Multimap<String, String> quotedParameters = Multimaps.transformValues(parameters,
new Function<String, String>() {
@Override public String apply(String value) {
return TOKEN_MATCHER.matchesAllOf(value) ? value : escapeAndQuote(value);
}
});
PARAMETER_JOINER.appendTo(builder, quotedParameters.entries());
}
return builder.toString();
}
private static String escapeAndQuote(String value) {
StringBuilder escaped = new StringBuilder(value.length() + 16).append('"');
for (char ch : value.toCharArray()) {
if (ch == '\r' || ch == '\\' || ch == '"') {
escaped.append('\\');
}
escaped.append(ch);
}
return escaped.append('"').toString();
}
}
| Java |
/*
* 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.
*/
/**
* This package contains utility methods and classes for working with net
* addresses (numeric IP and domain names).
*
* <p>This package is a part of the open-source
* <a href="http://guava-libraries.googlecode.com">Guava libraries</a>.
*
* @author Craig Berry
*/
@ParametersAreNonnullByDefault
package com.google.common.net;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
/*
* 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.net;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
* Contains constant definitions for the HTTP header field names. See:
* <ul>
* <li><a href="http://www.ietf.org/rfc/rfc2109.txt">RFC 2109</a>
* <li><a href="http://www.ietf.org/rfc/rfc2183.txt">RFC 2183</a>
* <li><a href="http://www.ietf.org/rfc/rfc2616.txt">RFC 2616</a>
* <li><a href="http://www.ietf.org/rfc/rfc2965.txt">RFC 2965</a>
* <li><a href="http://www.ietf.org/rfc/rfc5988.txt">RFC 5988</a>
* </ul>
*
* @author Kurt Alfred Kluever
* @since 11.0
*/
@Beta
@GwtCompatible
public final class HttpHeaders {
private HttpHeaders() {}
// HTTP Request and Response header fields
/** The HTTP Cache-Control header field name. */
public static final String CACHE_CONTROL = "Cache-Control";
/** The HTTP Content-Length header field name. */
public static final String CONTENT_LENGTH = "Content-Length";
/** The HTTP Content-Type header field name. */
public static final String CONTENT_TYPE = "Content-Type";
/** The HTTP Date header field name. */
public static final String DATE = "Date";
/** The HTTP Pragma header field name. */
public static final String PRAGMA = "Pragma";
/** The HTTP Via header field name. */
public static final String VIA = "Via";
/** The HTTP Warning header field name. */
public static final String WARNING = "Warning";
// HTTP Request header fields
/** The HTTP Accept header field name. */
public static final String ACCEPT = "Accept";
/** The HTTP Accept-Charset header field name. */
public static final String ACCEPT_CHARSET = "Accept-Charset";
/** The HTTP Accept-Encoding header field name. */
public static final String ACCEPT_ENCODING = "Accept-Encoding";
/** The HTTP Accept-Language header field name. */
public static final String ACCEPT_LANGUAGE = "Accept-Language";
/** The HTTP Access-Control-Request-Headers header field name. */
public static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers";
/** The HTTP Access-Control-Request-Method header field name. */
public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method";
/** The HTTP Authorization header field name. */
public static final String AUTHORIZATION = "Authorization";
/** The HTTP Connection header field name. */
public static final String CONNECTION = "Connection";
/** The HTTP Cookie header field name. */
public static final String COOKIE = "Cookie";
/** The HTTP Expect header field name. */
public static final String EXPECT = "Expect";
/** The HTTP From header field name. */
public static final String FROM = "From";
/** The HTTP Host header field name. */
public static final String HOST = "Host";
/** The HTTP If-Match header field name. */
public static final String IF_MATCH = "If-Match";
/** The HTTP If-Modified-Since header field name. */
public static final String IF_MODIFIED_SINCE = "If-Modified-Since";
/** The HTTP If-None-Match header field name. */
public static final String IF_NONE_MATCH = "If-None-Match";
/** The HTTP If-Range header field name. */
public static final String IF_RANGE = "If-Range";
/** The HTTP If-Unmodified-Since header field name. */
public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since";
/** The HTTP Last-Event-ID header field name. */
public static final String LAST_EVENT_ID = "Last-Event-ID";
/** The HTTP Max-Forwards header field name. */
public static final String MAX_FORWARDS = "Max-Forwards";
/** The HTTP Origin header field name. */
public static final String ORIGIN = "Origin";
/** The HTTP Proxy-Authorization header field name. */
public static final String PROXY_AUTHORIZATION = "Proxy-Authorization";
/** The HTTP Range header field name. */
public static final String RANGE = "Range";
/** The HTTP Referer header field name. */
public static final String REFERER = "Referer";
/** The HTTP TE header field name. */
public static final String TE = "TE";
/** The HTTP Upgrade header field name. */
public static final String UPGRADE = "Upgrade";
/** The HTTP User-Agent header field name. */
public static final String USER_AGENT = "User-Agent";
// HTTP Response header fields
/** The HTTP Accept-Ranges header field name. */
public static final String ACCEPT_RANGES = "Accept-Ranges";
/** The HTTP Access-Control-Allow-Headers header field name. */
public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers";
/** The HTTP Access-Control-Allow-Methods header field name. */
public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods";
/** The HTTP Access-Control-Allow-Origin header field name. */
public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin";
/** The HTTP Access-Control-Allow-Credentials header field name. */
public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials";
/** The HTTP Access-Control-Expose-Headers header field name. */
public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers";
/** The HTTP Access-Control-Max-Age header field name. */
public static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age";
/** The HTTP Age header field name. */
public static final String AGE = "Age";
/** The HTTP Allow header field name. */
public static final String ALLOW = "Allow";
/** The HTTP Content-Disposition header field name. */
public static final String CONTENT_DISPOSITION = "Content-Disposition";
/** The HTTP Content-Encoding header field name. */
public static final String CONTENT_ENCODING = "Content-Encoding";
/** The HTTP Content-Language header field name. */
public static final String CONTENT_LANGUAGE = "Content-Language";
/** The HTTP Content-Location header field name. */
public static final String CONTENT_LOCATION = "Content-Location";
/** The HTTP Content-MD5 header field name. */
public static final String CONTENT_MD5 = "Content-MD5";
/** The HTTP Content-Range header field name. */
public static final String CONTENT_RANGE = "Content-Range";
/** The HTTP ETag header field name. */
public static final String ETAG = "ETag";
/** The HTTP Expires header field name. */
public static final String EXPIRES = "Expires";
/** The HTTP Last-Modified header field name. */
public static final String LAST_MODIFIED = "Last-Modified";
/** The HTTP Link header field name. */
public static final String LINK = "Link";
/** The HTTP Location header field name. */
public static final String LOCATION = "Location";
/** The HTTP P3P header field name. Limited browser support. */
public static final String P3P = "P3P";
/** The HTTP Proxy-Authenticate header field name. */
public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate";
/** The HTTP Refresh header field name. Non-standard header supported by most browsers. */
public static final String REFRESH = "Refresh";
/** The HTTP Retry-After header field name. */
public static final String RETRY_AFTER = "Retry-After";
/** The HTTP Server header field name. */
public static final String SERVER = "Server";
/** The HTTP Set-Cookie header field name. */
public static final String SET_COOKIE = "Set-Cookie";
/** The HTTP Set-Cookie2 header field name. */
public static final String SET_COOKIE2 = "Set-Cookie2";
/** The HTTP Trailer header field name. */
public static final String TRAILER = "Trailer";
/** The HTTP Transfer-Encoding header field name. */
public static final String TRANSFER_ENCODING = "Transfer-Encoding";
/** The HTTP Vary header field name. */
public static final String VARY = "Vary";
/** The HTTP WWW-Authenticate header field name. */
public static final String WWW_AUTHENTICATE = "WWW-Authenticate";
// Common, non-standard HTTP header fields
/** The HTTP DNT header field name. */
public static final String DNT = "DNT";
/** The HTTP X-Content-Type-Options header field name. */
public static final String X_CONTENT_TYPE_OPTIONS = "X-Content-Type-Options";
/** The HTTP X-Do-Not-Track header field name. */
public static final String X_DO_NOT_TRACK = "X-Do-Not-Track";
/** The HTTP X-Forwarded-For header field name. */
public static final String X_FORWARDED_FOR = "X-Forwarded-For";
/** The HTTP X-Forwarded-Proto header field name. */
public static final String X_FORWARDED_PROTO = "X-Forwarded-Proto";
/** The HTTP X-Frame-Options header field name. */
public static final String X_FRAME_OPTIONS = "X-Frame-Options";
/** The HTTP X-Powered-By header field name. */
public static final String X_POWERED_BY = "X-Powered-By";
/** The HTTP X-Requested-With header field name. */
public static final String X_REQUESTED_WITH = "X-Requested-With";
/** The HTTP X-User-IP header field name. */
public static final String X_USER_IP = "X-User-IP";
/** The HTTP X-XSS-Protection header field name. */
public static final String X_XSS_PROTECTION = "X-XSS-Protection";
}
| Java |
/*
* 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.net;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.net.InetAddress;
import java.text.ParseException;
import javax.annotation.Nullable;
/**
* A syntactically valid host specifier, suitable for use in a URI.
* This may be either a numeric IP address in IPv4 or IPv6 notation, or a
* domain name.
*
* <p>Because this class is intended to represent host specifiers which can
* reasonably be used in a URI, the domain name case is further restricted to
* include only those domain names which end in a recognized public suffix; see
* {@link InternetDomainName#isPublicSuffix()} for details.
*
* <p>Note that no network lookups are performed by any {@code HostSpecifier}
* methods. No attempt is made to verify that a provided specifier corresponds
* to a real or accessible host. Only syntactic and pattern-based checks are
* performed.
*
* <p>If you know that a given string represents a numeric IP address, use
* {@link InetAddresses} to obtain and manipulate a
* {@link java.net.InetAddress} instance from it rather than using this class.
* Similarly, if you know that a given string represents a domain name, use
* {@link InternetDomainName} rather than this class.
*
* @author Craig Berry
* @since 5.0
*/
@Beta
public final class HostSpecifier {
private final String canonicalForm;
private HostSpecifier(String canonicalForm) {
this.canonicalForm = canonicalForm;
}
/**
* Returns a {@code HostSpecifier} built from the provided {@code specifier},
* which is already known to be valid. If the {@code specifier} might be
* invalid, use {@link #from(String)} instead.
*
* <p>The specifier must be in one of these formats:
* <ul>
* <li>A domain name, like {@code google.com}
* <li>A IPv4 address string, like {@code 127.0.0.1}
* <li>An IPv6 address string with or without brackets, like
* {@code [2001:db8::1]} or {@code 2001:db8::1}
* </ul>
*
* @throws IllegalArgumentException if the specifier is not valid.
*/
public static HostSpecifier fromValid(String specifier) {
// Verify that no port was specified, and strip optional brackets from
// IPv6 literals.
final HostAndPort parsedHost = HostAndPort.fromString(specifier);
Preconditions.checkArgument(!parsedHost.hasPort());
final String host = parsedHost.getHostText();
// Try to interpret the specifier as an IP address. Note we build
// the address rather than using the .is* methods because we want to
// use InetAddresses.toUriString to convert the result to a string in
// canonical form.
InetAddress addr = null;
try {
addr = InetAddresses.forString(host);
} catch (IllegalArgumentException e) {
// It is not an IPv4 or IPv6 literal
}
if (addr != null) {
return new HostSpecifier(InetAddresses.toUriString(addr));
}
// It is not any kind of IP address; must be a domain name or invalid.
// TODO(user): different versions of this for different factories?
final InternetDomainName domain = InternetDomainName.from(host);
if (domain.hasPublicSuffix()) {
return new HostSpecifier(domain.name());
}
throw new IllegalArgumentException(
"Domain name does not have a recognized public suffix: " + host);
}
/**
* Attempts to return a {@code HostSpecifier} for the given string, throwing
* an exception if parsing fails. Always use this method in preference to
* {@link #fromValid(String)} for a specifier that is not already known to be
* valid.
*
* @throws ParseException if the specifier is not valid.
*/
public static HostSpecifier from(String specifier)
throws ParseException {
try {
return fromValid(specifier);
} catch (IllegalArgumentException e) {
// Since the IAE can originate at several different points inside
// fromValid(), we implement this method in terms of that one rather
// than the reverse.
ParseException parseException =
new ParseException("Invalid host specifier: " + specifier, 0);
parseException.initCause(e);
throw parseException;
}
}
/**
* Determines whether {@code specifier} represents a valid
* {@link HostSpecifier} as described in the documentation for
* {@link #fromValid(String)}.
*/
public static boolean isValid(String specifier) {
try {
fromValid(specifier);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
@Override
public boolean equals(@Nullable Object other) {
if (this == other) {
return true;
}
if (other instanceof HostSpecifier) {
final HostSpecifier that = (HostSpecifier) other;
return this.canonicalForm.equals(that.canonicalForm);
}
return false;
}
@Override
public int hashCode() {
return canonicalForm.hashCode();
}
/**
* Returns a string representation of the host specifier suitable for
* inclusion in a URI. If the host specifier is a domain name, the
* string will be normalized to all lower case. If the specifier was
* an IPv6 address without brackets, brackets are added so that the
* result will be usable in the host part of a URI.
*/
@Override
public String toString() {
return canonicalForm;
}
}
| Java |
/*
* 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.net;
import com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;
import com.google.common.hash.Hashing;
import com.google.common.io.ByteStreams;
import com.google.common.primitives.Ints;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.nio.ByteBuffer;
import java.util.Arrays;
import javax.annotation.Nullable;
/**
* Static utility methods pertaining to {@link InetAddress} instances.
*
* <p><b>Important note:</b> Unlike {@code InetAddress.getByName()}, the
* methods of this class never cause DNS services to be accessed. For
* this reason, you should prefer these methods as much as possible over
* their JDK equivalents whenever you are expecting to handle only
* IP address string literals -- there is no blocking DNS penalty for a
* malformed string.
*
* <p>When dealing with {@link Inet4Address} and {@link Inet6Address}
* objects as byte arrays (vis. {@code InetAddress.getAddress()}) they
* are 4 and 16 bytes in length, respectively, and represent the address
* in network byte order.
*
* <p>Examples of IP addresses and their byte representations:
* <ul>
* <li>The IPv4 loopback address, {@code "127.0.0.1"}.<br/>
* {@code 7f 00 00 01}
*
* <li>The IPv6 loopback address, {@code "::1"}.<br/>
* {@code 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 01}
*
* <li>From the IPv6 reserved documentation prefix ({@code 2001:db8::/32}),
* {@code "2001:db8::1"}.<br/>
* {@code 20 01 0d b8 00 00 00 00 00 00 00 00 00 00 00 01}
*
* <li>An IPv6 "IPv4 compatible" (or "compat") address,
* {@code "::192.168.0.1"}.<br/>
* {@code 00 00 00 00 00 00 00 00 00 00 00 00 c0 a8 00 01}
*
* <li>An IPv6 "IPv4 mapped" address, {@code "::ffff:192.168.0.1"}.<br/>
* {@code 00 00 00 00 00 00 00 00 00 00 ff ff c0 a8 00 01}
* </ul>
*
* <p>A few notes about IPv6 "IPv4 mapped" addresses and their observed
* use in Java.
* <br><br>
* "IPv4 mapped" addresses were originally a representation of IPv4
* addresses for use on an IPv6 socket that could receive both IPv4
* and IPv6 connections (by disabling the {@code IPV6_V6ONLY} socket
* option on an IPv6 socket). Yes, it's confusing. Nevertheless,
* these "mapped" addresses were never supposed to be seen on the
* wire. That assumption was dropped, some say mistakenly, in later
* RFCs with the apparent aim of making IPv4-to-IPv6 transition simpler.
*
* <p>Technically one <i>can</i> create a 128bit IPv6 address with the wire
* format of a "mapped" address, as shown above, and transmit it in an
* IPv6 packet header. However, Java's InetAddress creation methods
* appear to adhere doggedly to the original intent of the "mapped"
* address: all "mapped" addresses return {@link Inet4Address} objects.
*
* <p>For added safety, it is common for IPv6 network operators to filter
* all packets where either the source or destination address appears to
* be a "compat" or "mapped" address. Filtering suggestions usually
* recommend discarding any packets with source or destination addresses
* in the invalid range {@code ::/3}, which includes both of these bizarre
* address formats. For more information on "bogons", including lists
* of IPv6 bogon space, see:
*
* <ul>
* <li><a target="_parent"
* href="http://en.wikipedia.org/wiki/Bogon_filtering"
* >http://en.wikipedia.org/wiki/Bogon_filtering</a>
* <li><a target="_parent"
* href="http://www.cymru.com/Bogons/ipv6.txt"
* >http://www.cymru.com/Bogons/ipv6.txt</a>
* <li><a target="_parent"
* href="http://www.cymru.com/Bogons/v6bogon.html"
* >http://www.cymru.com/Bogons/v6bogon.html</a>
* <li><a target="_parent"
* href="http://www.space.net/~gert/RIPE/ipv6-filters.html"
* >http://www.space.net/~gert/RIPE/ipv6-filters.html</a>
* </ul>
*
* @author Erik Kline
* @since 5.0
*/
@Beta
public final class InetAddresses {
private static final int IPV4_PART_COUNT = 4;
private static final int IPV6_PART_COUNT = 8;
private static final Inet4Address LOOPBACK4 = (Inet4Address) forString("127.0.0.1");
private static final Inet4Address ANY4 = (Inet4Address) forString("0.0.0.0");
private InetAddresses() {}
/**
* Returns an {@link Inet4Address}, given a byte array representation of the IPv4 address.
*
* @param bytes byte array representing an IPv4 address (should be of length 4)
* @return {@link Inet4Address} corresponding to the supplied byte array
* @throws IllegalArgumentException if a valid {@link Inet4Address} can not be created
*/
private static Inet4Address getInet4Address(byte[] bytes) {
Preconditions.checkArgument(bytes.length == 4,
"Byte array has invalid length for an IPv4 address: %s != 4.",
bytes.length);
// Given a 4-byte array, this cast should always succeed.
return (Inet4Address) bytesToInetAddress(bytes);
}
/**
* Returns the {@link InetAddress} having the given string representation.
*
* <p>This deliberately avoids all nameservice lookups (e.g. no DNS).
*
* @param ipString {@code String} containing an IPv4 or IPv6 string literal, e.g.
* {@code "192.168.0.1"} or {@code "2001:db8::1"}
* @return {@link InetAddress} representing the argument
* @throws IllegalArgumentException if the argument is not a valid IP string literal
*/
public static InetAddress forString(String ipString) {
byte[] addr = ipStringToBytes(ipString);
// The argument was malformed, i.e. not an IP string literal.
if (addr == null) {
throw new IllegalArgumentException(
String.format("'%s' is not an IP string literal.", ipString));
}
return bytesToInetAddress(addr);
}
/**
* Returns {@code true} if the supplied string is a valid IP string
* literal, {@code false} otherwise.
*
* @param ipString {@code String} to evaluated as an IP string literal
* @return {@code true} if the argument is a valid IP string literal
*/
public static boolean isInetAddress(String ipString) {
return ipStringToBytes(ipString) != null;
}
private static byte[] ipStringToBytes(String ipString) {
// Make a first pass to categorize the characters in this string.
boolean hasColon = false;
boolean hasDot = false;
for (int i = 0; i < ipString.length(); i++) {
char c = ipString.charAt(i);
if (c == '.') {
hasDot = true;
} else if (c == ':') {
if (hasDot) {
return null; // Colons must not appear after dots.
}
hasColon = true;
} else if (Character.digit(c, 16) == -1) {
return null; // Everything else must be a decimal or hex digit.
}
}
// Now decide which address family to parse.
if (hasColon) {
if (hasDot) {
ipString = convertDottedQuadToHex(ipString);
if (ipString == null) {
return null;
}
}
return textToNumericFormatV6(ipString);
} else if (hasDot) {
return textToNumericFormatV4(ipString);
}
return null;
}
private static byte[] textToNumericFormatV4(String ipString) {
String[] address = ipString.split("\\.", IPV4_PART_COUNT + 1);
if (address.length != IPV4_PART_COUNT) {
return null;
}
byte[] bytes = new byte[IPV4_PART_COUNT];
try {
for (int i = 0; i < bytes.length; i++) {
bytes[i] = parseOctet(address[i]);
}
} catch (NumberFormatException ex) {
return null;
}
return bytes;
}
private static byte[] textToNumericFormatV6(String ipString) {
// An address can have [2..8] colons, and N colons make N+1 parts.
String[] parts = ipString.split(":", IPV6_PART_COUNT + 2);
if (parts.length < 3 || parts.length > IPV6_PART_COUNT + 1) {
return null;
}
// Disregarding the endpoints, find "::" with nothing in between.
// This indicates that a run of zeroes has been skipped.
int skipIndex = -1;
for (int i = 1; i < parts.length - 1; i++) {
if (parts[i].length() == 0) {
if (skipIndex >= 0) {
return null; // Can't have more than one ::
}
skipIndex = i;
}
}
int partsHi; // Number of parts to copy from above/before the "::"
int partsLo; // Number of parts to copy from below/after the "::"
if (skipIndex >= 0) {
// If we found a "::", then check if it also covers the endpoints.
partsHi = skipIndex;
partsLo = parts.length - skipIndex - 1;
if (parts[0].length() == 0 && --partsHi != 0) {
return null; // ^: requires ^::
}
if (parts[parts.length - 1].length() == 0 && --partsLo != 0) {
return null; // :$ requires ::$
}
} else {
// Otherwise, allocate the entire address to partsHi. The endpoints
// could still be empty, but parseHextet() will check for that.
partsHi = parts.length;
partsLo = 0;
}
// If we found a ::, then we must have skipped at least one part.
// Otherwise, we must have exactly the right number of parts.
int partsSkipped = IPV6_PART_COUNT - (partsHi + partsLo);
if (!(skipIndex >= 0 ? partsSkipped >= 1 : partsSkipped == 0)) {
return null;
}
// Now parse the hextets into a byte array.
ByteBuffer rawBytes = ByteBuffer.allocate(2 * IPV6_PART_COUNT);
try {
for (int i = 0; i < partsHi; i++) {
rawBytes.putShort(parseHextet(parts[i]));
}
for (int i = 0; i < partsSkipped; i++) {
rawBytes.putShort((short) 0);
}
for (int i = partsLo; i > 0; i--) {
rawBytes.putShort(parseHextet(parts[parts.length - i]));
}
} catch (NumberFormatException ex) {
return null;
}
return rawBytes.array();
}
private static String convertDottedQuadToHex(String ipString) {
int lastColon = ipString.lastIndexOf(':');
String initialPart = ipString.substring(0, lastColon + 1);
String dottedQuad = ipString.substring(lastColon + 1);
byte[] quad = textToNumericFormatV4(dottedQuad);
if (quad == null) {
return null;
}
String penultimate = Integer.toHexString(((quad[0] & 0xff) << 8) | (quad[1] & 0xff));
String ultimate = Integer.toHexString(((quad[2] & 0xff) << 8) | (quad[3] & 0xff));
return initialPart + penultimate + ":" + ultimate;
}
private static byte parseOctet(String ipPart) {
// Note: we already verified that this string contains only hex digits.
int octet = Integer.parseInt(ipPart);
// Disallow leading zeroes, because no clear standard exists on
// whether these should be interpreted as decimal or octal.
if (octet > 255 || (ipPart.startsWith("0") && ipPart.length() > 1)) {
throw new NumberFormatException();
}
return (byte) octet;
}
private static short parseHextet(String ipPart) {
// Note: we already verified that this string contains only hex digits.
int hextet = Integer.parseInt(ipPart, 16);
if (hextet > 0xffff) {
throw new NumberFormatException();
}
return (short) hextet;
}
/**
* Convert a byte array into an InetAddress.
*
* {@link InetAddress#getByAddress} is documented as throwing a checked
* exception "if IP address if of illegal length." We replace it with
* an unchecked exception, for use by callers who already know that addr
* is an array of length 4 or 16.
*
* @param addr the raw 4-byte or 16-byte IP address in big-endian order
* @return an InetAddress object created from the raw IP address
*/
private static InetAddress bytesToInetAddress(byte[] addr) {
try {
return InetAddress.getByAddress(addr);
} catch (UnknownHostException e) {
throw new AssertionError(e);
}
}
/**
* Returns the string representation of an {@link InetAddress}.
*
* <p>For IPv4 addresses, this is identical to
* {@link InetAddress#getHostAddress()}, but for IPv6 addresses, the output
* follows <a href="http://tools.ietf.org/html/rfc5952">RFC 5952</a>
* section 4. The main difference is that this method uses "::" for zero
* compression, while Java's version uses the uncompressed form.
*
* <p>This method uses hexadecimal for all IPv6 addresses, including
* IPv4-mapped IPv6 addresses such as "::c000:201". The output does not
* include a Scope ID.
*
* @param ip {@link InetAddress} to be converted to an address string
* @return {@code String} containing the text-formatted IP address
* @since 10.0
*/
public static String toAddrString(InetAddress ip) {
Preconditions.checkNotNull(ip);
if (ip instanceof Inet4Address) {
// For IPv4, Java's formatting is good enough.
return ip.getHostAddress();
}
Preconditions.checkArgument(ip instanceof Inet6Address);
byte[] bytes = ip.getAddress();
int[] hextets = new int[IPV6_PART_COUNT];
for (int i = 0; i < hextets.length; i++) {
hextets[i] = Ints.fromBytes(
(byte) 0, (byte) 0, bytes[2 * i], bytes[2 * i + 1]);
}
compressLongestRunOfZeroes(hextets);
return hextetsToIPv6String(hextets);
}
/**
* Identify and mark the longest run of zeroes in an IPv6 address.
*
* <p>Only runs of two or more hextets are considered. In case of a tie, the
* leftmost run wins. If a qualifying run is found, its hextets are replaced
* by the sentinel value -1.
*
* @param hextets {@code int[]} mutable array of eight 16-bit hextets
*/
private static void compressLongestRunOfZeroes(int[] hextets) {
int bestRunStart = -1;
int bestRunLength = -1;
int runStart = -1;
for (int i = 0; i < hextets.length + 1; i++) {
if (i < hextets.length && hextets[i] == 0) {
if (runStart < 0) {
runStart = i;
}
} else if (runStart >= 0) {
int runLength = i - runStart;
if (runLength > bestRunLength) {
bestRunStart = runStart;
bestRunLength = runLength;
}
runStart = -1;
}
}
if (bestRunLength >= 2) {
Arrays.fill(hextets, bestRunStart, bestRunStart + bestRunLength, -1);
}
}
/**
* Convert a list of hextets into a human-readable IPv6 address.
*
* <p>In order for "::" compression to work, the input should contain negative
* sentinel values in place of the elided zeroes.
*
* @param hextets {@code int[]} array of eight 16-bit hextets, or -1s
*/
private static String hextetsToIPv6String(int[] hextets) {
/*
* While scanning the array, handle these state transitions:
* start->num => "num" start->gap => "::"
* num->num => ":num" num->gap => "::"
* gap->num => "num" gap->gap => ""
*/
StringBuilder buf = new StringBuilder(39);
boolean lastWasNumber = false;
for (int i = 0; i < hextets.length; i++) {
boolean thisIsNumber = hextets[i] >= 0;
if (thisIsNumber) {
if (lastWasNumber) {
buf.append(':');
}
buf.append(Integer.toHexString(hextets[i]));
} else {
if (i == 0 || lastWasNumber) {
buf.append("::");
}
}
lastWasNumber = thisIsNumber;
}
return buf.toString();
}
/**
* Returns the string representation of an {@link InetAddress} suitable
* for inclusion in a URI.
*
* <p>For IPv4 addresses, this is identical to
* {@link InetAddress#getHostAddress()}, but for IPv6 addresses it
* compresses zeroes and surrounds the text with square brackets; for example
* {@code "[2001:db8::1]"}.
*
* <p>Per section 3.2.2 of
* <a target="_parent"
* href="http://tools.ietf.org/html/rfc3986#section-3.2.2"
* >http://tools.ietf.org/html/rfc3986</a>,
* a URI containing an IPv6 string literal is of the form
* {@code "http://[2001:db8::1]:8888/index.html"}.
*
* <p>Use of either {@link InetAddresses#toAddrString},
* {@link InetAddress#getHostAddress()}, or this method is recommended over
* {@link InetAddress#toString()} when an IP address string literal is
* desired. This is because {@link InetAddress#toString()} prints the
* hostname and the IP address string joined by a "/".
*
* @param ip {@link InetAddress} to be converted to URI string literal
* @return {@code String} containing URI-safe string literal
*/
public static String toUriString(InetAddress ip) {
if (ip instanceof Inet6Address) {
return "[" + toAddrString(ip) + "]";
}
return toAddrString(ip);
}
/**
* Returns an InetAddress representing the literal IPv4 or IPv6 host
* portion of a URL, encoded in the format specified by RFC 3986 section 3.2.2.
*
* <p>This function is similar to {@link InetAddresses#forString(String)},
* however, it requires that IPv6 addresses are surrounded by square brackets.
*
* <p>This function is the inverse of
* {@link InetAddresses#toUriString(java.net.InetAddress)}.
*
* @param hostAddr A RFC 3986 section 3.2.2 encoded IPv4 or IPv6 address
* @return an InetAddress representing the address in {@code hostAddr}
* @throws IllegalArgumentException if {@code hostAddr} is not a valid
* IPv4 address, or IPv6 address surrounded by square brackets
*/
public static InetAddress forUriString(String hostAddr) {
Preconditions.checkNotNull(hostAddr);
// Decide if this should be an IPv6 or IPv4 address.
String ipString;
int expectBytes;
if (hostAddr.startsWith("[") && hostAddr.endsWith("]")) {
ipString = hostAddr.substring(1, hostAddr.length() - 1);
expectBytes = 16;
} else {
ipString = hostAddr;
expectBytes = 4;
}
// Parse the address, and make sure the length/version is correct.
byte[] addr = ipStringToBytes(ipString);
if (addr == null || addr.length != expectBytes) {
throw new IllegalArgumentException(
String.format("Not a valid URI IP literal: '%s'", hostAddr));
}
return bytesToInetAddress(addr);
}
/**
* Returns {@code true} if the supplied string is a valid URI IP string
* literal, {@code false} otherwise.
*
* @param ipString {@code String} to evaluated as an IP URI host string literal
* @return {@code true} if the argument is a valid IP URI host
*/
public static boolean isUriInetAddress(String ipString) {
try {
forUriString(ipString);
return true;
} catch (IllegalArgumentException e) {
return false;
}
}
/**
* Evaluates whether the argument is an IPv6 "compat" address.
*
* <p>An "IPv4 compatible", or "compat", address is one with 96 leading
* bits of zero, with the remaining 32 bits interpreted as an
* IPv4 address. These are conventionally represented in string
* literals as {@code "::192.168.0.1"}, though {@code "::c0a8:1"} is
* also considered an IPv4 compatible address (and equivalent to
* {@code "::192.168.0.1"}).
*
* <p>For more on IPv4 compatible addresses see section 2.5.5.1 of
* <a target="_parent"
* href="http://tools.ietf.org/html/rfc4291#section-2.5.5.1"
* >http://tools.ietf.org/html/rfc4291</a>
*
* <p>NOTE: This method is different from
* {@link Inet6Address#isIPv4CompatibleAddress} in that it more
* correctly classifies {@code "::"} and {@code "::1"} as
* proper IPv6 addresses (which they are), NOT IPv4 compatible
* addresses (which they are generally NOT considered to be).
*
* @param ip {@link Inet6Address} to be examined for embedded IPv4 compatible address format
* @return {@code true} if the argument is a valid "compat" address
*/
public static boolean isCompatIPv4Address(Inet6Address ip) {
if (!ip.isIPv4CompatibleAddress()) {
return false;
}
byte[] bytes = ip.getAddress();
if ((bytes[12] == 0) && (bytes[13] == 0) && (bytes[14] == 0)
&& ((bytes[15] == 0) || (bytes[15] == 1))) {
return false;
}
return true;
}
/**
* Returns the IPv4 address embedded in an IPv4 compatible address.
*
* @param ip {@link Inet6Address} to be examined for an embedded IPv4 address
* @return {@link Inet4Address} of the embedded IPv4 address
* @throws IllegalArgumentException if the argument is not a valid IPv4 compatible address
*/
public static Inet4Address getCompatIPv4Address(Inet6Address ip) {
Preconditions.checkArgument(isCompatIPv4Address(ip),
"Address '%s' is not IPv4-compatible.", toAddrString(ip));
return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16));
}
/**
* Evaluates whether the argument is a 6to4 address.
*
* <p>6to4 addresses begin with the {@code "2002::/16"} prefix.
* The next 32 bits are the IPv4 address of the host to which
* IPv6-in-IPv4 tunneled packets should be routed.
*
* <p>For more on 6to4 addresses see section 2 of
* <a target="_parent" href="http://tools.ietf.org/html/rfc3056#section-2"
* >http://tools.ietf.org/html/rfc3056</a>
*
* @param ip {@link Inet6Address} to be examined for 6to4 address format
* @return {@code true} if the argument is a 6to4 address
*/
public static boolean is6to4Address(Inet6Address ip) {
byte[] bytes = ip.getAddress();
return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x02);
}
/**
* Returns the IPv4 address embedded in a 6to4 address.
*
* @param ip {@link Inet6Address} to be examined for embedded IPv4 in 6to4 address
* @return {@link Inet4Address} of embedded IPv4 in 6to4 address
* @throws IllegalArgumentException if the argument is not a valid IPv6 6to4 address
*/
public static Inet4Address get6to4IPv4Address(Inet6Address ip) {
Preconditions.checkArgument(is6to4Address(ip),
"Address '%s' is not a 6to4 address.", toAddrString(ip));
return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 2, 6));
}
/**
* A simple immutable data class to encapsulate the information to be found in a
* Teredo address.
*
* <p>All of the fields in this class are encoded in various portions
* of the IPv6 address as part of the protocol. More protocols details
* can be found at:
* <a target="_parent" href="http://en.wikipedia.org/wiki/Teredo_tunneling"
* >http://en.wikipedia.org/wiki/Teredo_tunneling</a>.
*
* <p>The RFC can be found here:
* <a target="_parent" href="http://tools.ietf.org/html/rfc4380"
* >http://tools.ietf.org/html/rfc4380</a>.
*
* @since 5.0
*/
@Beta
public static final class TeredoInfo {
private final Inet4Address server;
private final Inet4Address client;
private final int port;
private final int flags;
/**
* Constructs a TeredoInfo instance.
*
* <p>Both server and client can be {@code null}, in which case the
* value {@code "0.0.0.0"} will be assumed.
*
* @throws IllegalArgumentException if either of the {@code port} or the {@code flags}
* arguments are out of range of an unsigned short
*/
// TODO: why is this public?
public TeredoInfo(
@Nullable Inet4Address server, @Nullable Inet4Address client, int port, int flags) {
Preconditions.checkArgument((port >= 0) && (port <= 0xffff),
"port '%s' is out of range (0 <= port <= 0xffff)", port);
Preconditions.checkArgument((flags >= 0) && (flags <= 0xffff),
"flags '%s' is out of range (0 <= flags <= 0xffff)", flags);
this.server = Objects.firstNonNull(server, ANY4);
this.client = Objects.firstNonNull(client, ANY4);
this.port = port;
this.flags = flags;
}
public Inet4Address getServer() {
return server;
}
public Inet4Address getClient() {
return client;
}
public int getPort() {
return port;
}
public int getFlags() {
return flags;
}
}
/**
* Evaluates whether the argument is a Teredo address.
*
* <p>Teredo addresses begin with the {@code "2001::/32"} prefix.
*
* @param ip {@link Inet6Address} to be examined for Teredo address format
* @return {@code true} if the argument is a Teredo address
*/
public static boolean isTeredoAddress(Inet6Address ip) {
byte[] bytes = ip.getAddress();
return (bytes[0] == (byte) 0x20) && (bytes[1] == (byte) 0x01)
&& (bytes[2] == 0) && (bytes[3] == 0);
}
/**
* Returns the Teredo information embedded in a Teredo address.
*
* @param ip {@link Inet6Address} to be examined for embedded Teredo information
* @return extracted {@code TeredoInfo}
* @throws IllegalArgumentException if the argument is not a valid IPv6 Teredo address
*/
public static TeredoInfo getTeredoInfo(Inet6Address ip) {
Preconditions.checkArgument(isTeredoAddress(ip),
"Address '%s' is not a Teredo address.", toAddrString(ip));
byte[] bytes = ip.getAddress();
Inet4Address server = getInet4Address(Arrays.copyOfRange(bytes, 4, 8));
int flags = ByteStreams.newDataInput(bytes, 8).readShort() & 0xffff;
// Teredo obfuscates the mapped client port, per section 4 of the RFC.
int port = ~ByteStreams.newDataInput(bytes, 10).readShort() & 0xffff;
byte[] clientBytes = Arrays.copyOfRange(bytes, 12, 16);
for (int i = 0; i < clientBytes.length; i++) {
// Teredo obfuscates the mapped client IP, per section 4 of the RFC.
clientBytes[i] = (byte) ~clientBytes[i];
}
Inet4Address client = getInet4Address(clientBytes);
return new TeredoInfo(server, client, port, flags);
}
/**
* Evaluates whether the argument is an ISATAP address.
*
* <p>From RFC 5214: "ISATAP interface identifiers are constructed in
* Modified EUI-64 format [...] by concatenating the 24-bit IANA OUI
* (00-00-5E), the 8-bit hexadecimal value 0xFE, and a 32-bit IPv4
* address in network byte order [...]"
*
* <p>For more on ISATAP addresses see section 6.1 of
* <a target="_parent" href="http://tools.ietf.org/html/rfc5214#section-6.1"
* >http://tools.ietf.org/html/rfc5214</a>
*
* @param ip {@link Inet6Address} to be examined for ISATAP address format
* @return {@code true} if the argument is an ISATAP address
*/
public static boolean isIsatapAddress(Inet6Address ip) {
// If it's a Teredo address with the right port (41217, or 0xa101)
// which would be encoded as 0x5efe then it can't be an ISATAP address.
if (isTeredoAddress(ip)) {
return false;
}
byte[] bytes = ip.getAddress();
if ((bytes[8] | (byte) 0x03) != (byte) 0x03) {
// Verify that high byte of the 64 bit identifier is zero, modulo
// the U/L and G bits, with which we are not concerned.
return false;
}
return (bytes[9] == (byte) 0x00) && (bytes[10] == (byte) 0x5e)
&& (bytes[11] == (byte) 0xfe);
}
/**
* Returns the IPv4 address embedded in an ISATAP address.
*
* @param ip {@link Inet6Address} to be examined for embedded IPv4 in ISATAP address
* @return {@link Inet4Address} of embedded IPv4 in an ISATAP address
* @throws IllegalArgumentException if the argument is not a valid IPv6 ISATAP address
*/
public static Inet4Address getIsatapIPv4Address(Inet6Address ip) {
Preconditions.checkArgument(isIsatapAddress(ip),
"Address '%s' is not an ISATAP address.", toAddrString(ip));
return getInet4Address(Arrays.copyOfRange(ip.getAddress(), 12, 16));
}
/**
* Examines the Inet6Address to determine if it is an IPv6 address of one
* of the specified address types that contain an embedded IPv4 address.
*
* <p>NOTE: ISATAP addresses are explicitly excluded from this method
* due to their trivial spoofability. With other transition addresses
* spoofing involves (at least) infection of one's BGP routing table.
*
* @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
* @return {@code true} if there is an embedded IPv4 client address
* @since 7.0
*/
public static boolean hasEmbeddedIPv4ClientAddress(Inet6Address ip) {
return isCompatIPv4Address(ip) || is6to4Address(ip) || isTeredoAddress(ip);
}
/**
* Examines the Inet6Address to extract the embedded IPv4 client address
* if the InetAddress is an IPv6 address of one of the specified address
* types that contain an embedded IPv4 address.
*
* <p>NOTE: ISATAP addresses are explicitly excluded from this method
* due to their trivial spoofability. With other transition addresses
* spoofing involves (at least) infection of one's BGP routing table.
*
* @param ip {@link Inet6Address} to be examined for embedded IPv4 client address
* @return {@link Inet4Address} of embedded IPv4 client address
* @throws IllegalArgumentException if the argument does not have a valid embedded IPv4 address
*/
public static Inet4Address getEmbeddedIPv4ClientAddress(Inet6Address ip) {
if (isCompatIPv4Address(ip)) {
return getCompatIPv4Address(ip);
}
if (is6to4Address(ip)) {
return get6to4IPv4Address(ip);
}
if (isTeredoAddress(ip)) {
return getTeredoInfo(ip).getClient();
}
throw new IllegalArgumentException(
String.format("'%s' has no embedded IPv4 address.", toAddrString(ip)));
}
/**
* Evaluates whether the argument is an "IPv4 mapped" IPv6 address.
*
* <p>An "IPv4 mapped" address is anything in the range ::ffff:0:0/96
* (sometimes written as ::ffff:0.0.0.0/96), with the last 32 bits
* interpreted as an IPv4 address.
*
* <p>For more on IPv4 mapped addresses see section 2.5.5.2 of
* <a target="_parent"
* href="http://tools.ietf.org/html/rfc4291#section-2.5.5.2"
* >http://tools.ietf.org/html/rfc4291</a>
*
* <p>Note: This method takes a {@code String} argument because
* {@link InetAddress} automatically collapses mapped addresses to IPv4.
* (It is actually possible to avoid this using one of the obscure
* {@link Inet6Address} methods, but it would be unwise to depend on such
* a poorly-documented feature.)
*
* @param ipString {@code String} to be examined for embedded IPv4-mapped IPv6 address format
* @return {@code true} if the argument is a valid "mapped" address
* @since 10.0
*/
public static boolean isMappedIPv4Address(String ipString) {
byte[] bytes = ipStringToBytes(ipString);
if (bytes != null && bytes.length == 16) {
for (int i = 0; i < 10; i++) {
if (bytes[i] != 0) {
return false;
}
}
for (int i = 10; i < 12; i++) {
if (bytes[i] != (byte) 0xff) {
return false;
}
}
return true;
}
return false;
}
/**
* Coerces an IPv6 address into an IPv4 address.
*
* <p>HACK: As long as applications continue to use IPv4 addresses for
* indexing into tables, accounting, et cetera, it may be necessary to
* <b>coerce</b> IPv6 addresses into IPv4 addresses. This function does
* so by hashing the upper 64 bits into {@code 224.0.0.0/3}
* (64 bits into 29 bits).
*
* <p>A "coerced" IPv4 address is equivalent to itself.
*
* <p>NOTE: This function is failsafe for security purposes: ALL IPv6
* addresses (except localhost (::1)) are hashed to avoid the security
* risk associated with extracting an embedded IPv4 address that might
* permit elevated privileges.
*
* @param ip {@link InetAddress} to "coerce"
* @return {@link Inet4Address} represented "coerced" address
* @since 7.0
*/
public static Inet4Address getCoercedIPv4Address(InetAddress ip) {
if (ip instanceof Inet4Address) {
return (Inet4Address) ip;
}
// Special cases:
byte[] bytes = ip.getAddress();
boolean leadingBytesOfZero = true;
for (int i = 0; i < 15; ++i) {
if (bytes[i] != 0) {
leadingBytesOfZero = false;
break;
}
}
if (leadingBytesOfZero && (bytes[15] == 1)) {
return LOOPBACK4; // ::1
} else if (leadingBytesOfZero && (bytes[15] == 0)) {
return ANY4; // ::0
}
Inet6Address ip6 = (Inet6Address) ip;
long addressAsLong = 0;
if (hasEmbeddedIPv4ClientAddress(ip6)) {
addressAsLong = getEmbeddedIPv4ClientAddress(ip6).hashCode();
} else {
// Just extract the high 64 bits (assuming the rest is user-modifiable).
addressAsLong = ByteBuffer.wrap(ip6.getAddress(), 0, 8).getLong();
}
// Many strategies for hashing are possible. This might suffice for now.
int coercedHash = Hashing.murmur3_32().hashLong(addressAsLong).asInt();
// Squash into 224/4 Multicast and 240/4 Reserved space (i.e. 224/3).
coercedHash |= 0xe0000000;
// Fixup to avoid some "illegal" values. Currently the only potential
// illegal value is 255.255.255.255.
if (coercedHash == 0xffffffff) {
coercedHash = 0xfffffffe;
}
return getInet4Address(Ints.toByteArray(coercedHash));
}
/**
* Returns an integer representing an IPv4 address regardless of
* whether the supplied argument is an IPv4 address or not.
*
* <p>IPv6 addresses are <b>coerced</b> to IPv4 addresses before being
* converted to integers.
*
* <p>As long as there are applications that assume that all IP addresses
* are IPv4 addresses and can therefore be converted safely to integers
* (for whatever purpose) this function can be used to handle IPv6
* addresses as well until the application is suitably fixed.
*
* <p>NOTE: an IPv6 address coerced to an IPv4 address can only be used
* for such purposes as rudimentary identification or indexing into a
* collection of real {@link InetAddress}es. They cannot be used as
* real addresses for the purposes of network communication.
*
* @param ip {@link InetAddress} to convert
* @return {@code int}, "coerced" if ip is not an IPv4 address
* @since 7.0
*/
public static int coerceToInteger(InetAddress ip) {
return ByteStreams.newDataInput(getCoercedIPv4Address(ip).getAddress()).readInt();
}
/**
* Returns an Inet4Address having the integer value specified by
* the argument.
*
* @param address {@code int}, the 32bit integer address to be converted
* @return {@link Inet4Address} equivalent of the argument
*/
public static Inet4Address fromInteger(int address) {
return getInet4Address(Ints.toByteArray(address));
}
/**
* Returns an address from a <b>little-endian ordered</b> byte array
* (the opposite of what {@link InetAddress#getByAddress} expects).
*
* <p>IPv4 address byte array must be 4 bytes long and IPv6 byte array
* must be 16 bytes long.
*
* @param addr the raw IP address in little-endian byte order
* @return an InetAddress object created from the raw IP address
* @throws UnknownHostException if IP address is of illegal length
*/
public static InetAddress fromLittleEndianByteArray(byte[] addr) throws UnknownHostException {
byte[] reversed = new byte[addr.length];
for (int i = 0; i < addr.length; i++) {
reversed[i] = addr[addr.length - i - 1];
}
return InetAddress.getByAddress(reversed);
}
/**
* Returns a new InetAddress that is one more than the passed in address.
* This method works for both IPv4 and IPv6 addresses.
*
* @param address the InetAddress to increment
* @return a new InetAddress that is one more than the passed in address
* @throws IllegalArgumentException if InetAddress is at the end of its range
* @since 10.0
*/
public static InetAddress increment(InetAddress address) {
byte[] addr = address.getAddress();
int i = addr.length - 1;
while (i >= 0 && addr[i] == (byte) 0xff) {
addr[i] = 0;
i--;
}
Preconditions.checkArgument(i >= 0, "Incrementing %s would wrap.", address);
addr[i]++;
return bytesToInetAddress(addr);
}
/**
* Returns true if the InetAddress is either 255.255.255.255 for IPv4 or
* ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6.
*
* @return true if the InetAddress is either 255.255.255.255 for IPv4 or
* ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff for IPv6
* @since 10.0
*/
public static boolean isMaximum(InetAddress address) {
byte[] addr = address.getAddress();
for (int i = 0; i < addr.length; i++) {
if (addr[i] != (byte) 0xff) {
return false;
}
}
return true;
}
}
| Java |
/*
* 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.net;
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 com.google.common.annotations.Beta;
import com.google.common.base.Objects;
import java.io.Serializable;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.annotation.concurrent.Immutable;
/**
* An immutable representation of a host and port.
*
* <p>Example usage:
* <pre>
* HostAndPort hp = HostAndPort.fromString("[2001:db8::1]")
* .withDefaultPort(80)
* .requireBracketsForIPv6();
* hp.getHostText(); // returns "2001:db8::1"
* hp.getPort(); // returns 80
* hp.toString(); // returns "[2001:db8::1]:80"
* </pre>
*
* <p>Here are some examples of recognized formats:
* <ul>
* <li>example.com
* <li>example.com:80
* <li>192.0.2.1
* <li>192.0.2.1:80
* <li>[2001:db8::1] - {@link #getHostText()} omits brackets
* <li>[2001:db8::1]:80 - {@link #getHostText()} omits brackets
* <li>2001:db8::1 - Use {@link #requireBracketsForIPv6()} to prohibit this
* </ul>
*
* <p>Note that this is not an exhaustive list, because these methods are only
* concerned with brackets, colons, and port numbers. Full validation of the
* host field (if desired) is the caller's responsibility.
*
* @author Paul Marks
* @since 10.0
*/
@Beta @Immutable
public final class HostAndPort implements Serializable {
/** Magic value indicating the absence of a port number. */
private static final int NO_PORT = -1;
/** Hostname, IPv4/IPv6 literal, or unvalidated nonsense. */
private final String host;
/** Validated port number in the range [0..65535], or NO_PORT */
private final int port;
/** True if the parsed host has colons, but no surrounding brackets. */
private final boolean hasBracketlessColons;
private HostAndPort(String host, int port, boolean hasBracketlessColons) {
this.host = host;
this.port = port;
this.hasBracketlessColons = hasBracketlessColons;
}
/**
* Returns the portion of this {@code HostAndPort} instance that should
* represent the hostname or IPv4/IPv6 literal.
*
* A successful parse does not imply any degree of sanity in this field.
* For additional validation, see the {@link HostSpecifier} class.
*/
public String getHostText() {
return host;
}
/** Return true if this instance has a defined port. */
public boolean hasPort() {
return port >= 0;
}
/**
* Get the current port number, failing if no port is defined.
*
* @return a validated port number, in the range [0..65535]
* @throws IllegalStateException if no port is defined. You can use
* {@link #withDefaultPort(int)} to prevent this from occurring.
*/
public int getPort() {
checkState(hasPort());
return port;
}
/**
* Returns the current port number, with a default if no port is defined.
*/
public int getPortOrDefault(int defaultPort) {
return hasPort() ? port : defaultPort;
}
/**
* Build a HostAndPort instance from separate host and port values.
*
* <p>Note: Non-bracketed IPv6 literals are allowed.
* Use {@link #requireBracketsForIPv6()} to prohibit these.
*
* @param host the host string to parse. Must not contain a port number.
* @param port a port number from [0..65535]
* @return if parsing was successful, a populated HostAndPort object.
* @throws IllegalArgumentException if {@code host} contains a port number,
* or {@code port} is out of range.
*/
public static HostAndPort fromParts(String host, int port) {
checkArgument(isValidPort(port));
HostAndPort parsedHost = fromString(host);
checkArgument(!parsedHost.hasPort());
return new HostAndPort(parsedHost.host, port, parsedHost.hasBracketlessColons);
}
private static final Pattern BRACKET_PATTERN = Pattern.compile("^\\[(.*:.*)\\](?::(\\d*))?$");
/**
* Split a freeform string into a host and port, without strict validation.
*
* Note that the host-only formats will leave the port field undefined. You
* can use {@link #withDefaultPort(int)} to patch in a default value.
*
* @param hostPortString the input string to parse.
* @return if parsing was successful, a populated HostAndPort object.
* @throws IllegalArgumentException if nothing meaningful could be parsed.
*/
public static HostAndPort fromString(String hostPortString) {
checkNotNull(hostPortString);
String host;
String portString = null;
boolean hasBracketlessColons = false;
if (hostPortString.startsWith("[")) {
// Parse a bracketed host, typically an IPv6 literal.
Matcher matcher = BRACKET_PATTERN.matcher(hostPortString);
checkArgument(matcher.matches(), "Invalid bracketed host/port: %s", hostPortString);
host = matcher.group(1);
portString = matcher.group(2); // could be null
} else {
int colonPos = hostPortString.indexOf(':');
if (colonPos >= 0 && hostPortString.indexOf(':', colonPos + 1) == -1) {
// Exactly 1 colon. Split into host:port.
host = hostPortString.substring(0, colonPos);
portString = hostPortString.substring(colonPos + 1);
} else {
// 0 or 2+ colons. Bare hostname or IPv6 literal.
host = hostPortString;
hasBracketlessColons = (colonPos >= 0);
}
}
int port = NO_PORT;
if (portString != null) {
// Try to parse the whole port string as a number.
// JDK7 accepts leading plus signs. We don't want to.
checkArgument(!portString.startsWith("+"), "Unparseable port number: %s", hostPortString);
try {
port = Integer.parseInt(portString);
} catch (NumberFormatException e) {
throw new IllegalArgumentException("Unparseable port number: " + hostPortString);
}
checkArgument(isValidPort(port), "Port number out of range: %s", hostPortString);
}
return new HostAndPort(host, port, hasBracketlessColons);
}
/**
* Provide a default port if the parsed string contained only a host.
*
* You can chain this after {@link #fromString(String)} to include a port in
* case the port was omitted from the input string. If a port was already
* provided, then this method is a no-op.
*
* @param defaultPort a port number, from [0..65535]
* @return a HostAndPort instance, guaranteed to have a defined port.
*/
public HostAndPort withDefaultPort(int defaultPort) {
checkArgument(isValidPort(defaultPort));
if (hasPort() || port == defaultPort) {
return this;
}
return new HostAndPort(host, defaultPort, hasBracketlessColons);
}
/**
* Generate an error if the host might be a non-bracketed IPv6 literal.
*
* <p>URI formatting requires that IPv6 literals be surrounded by brackets,
* like "[2001:db8::1]". Chain this call after {@link #fromString(String)}
* to increase the strictness of the parser, and disallow IPv6 literals
* that don't contain these brackets.
*
* <p>Note that this parser identifies IPv6 literals solely based on the
* presence of a colon. To perform actual validation of IP addresses, see
* the {@link InetAddresses#forString(String)} method.
*
* @return {@code this}, to enable chaining of calls.
* @throws IllegalArgumentException if bracketless IPv6 is detected.
*/
public HostAndPort requireBracketsForIPv6() {
checkArgument(!hasBracketlessColons, "Possible bracketless IPv6 literal: %s", host);
return this;
}
@Override
public boolean equals(Object other) {
if (this == other) {
return true;
}
if (other instanceof HostAndPort) {
HostAndPort that = (HostAndPort) other;
return Objects.equal(this.host, that.host)
&& this.port == that.port
&& this.hasBracketlessColons == that.hasBracketlessColons;
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(host, port, hasBracketlessColons);
}
/** Rebuild the host:port string, including brackets if necessary. */
@Override
public String toString() {
StringBuilder builder = new StringBuilder(host.length() + 7);
if (host.indexOf(':') >= 0) {
builder.append('[').append(host).append(']');
} else {
builder.append(host);
}
if (hasPort()) {
builder.append(':').append(port);
}
return builder.toString();
}
/** Return true for valid port numbers. */
private static boolean isValidPort(int port) {
return port >= 0 && port <= 65535;
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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.
*/
// TODO(user): when things stabilize, flesh this out
/**
* Hash functions and related structures.
*
* <p>See the Guava User Guide article on <a href=
* "http://code.google.com/p/guava-libraries/wiki/HashingExplained">
* hashing</a>.
*/
@ParametersAreNonnullByDefault
package com.google.common.hash;
import javax.annotation.ParametersAreNonnullByDefault;
| Java |
/*
* 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.hash;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import java.io.OutputStream;
/**
* Funnels for common types. All implementations are serializable.
*
* @author Dimitris Andreou
* @since 11.0
*/
@Beta
public final class Funnels {
private Funnels() {}
/**
* Returns a funnel that extracts the bytes from a {@code byte} array.
*/
public static Funnel<byte[]> byteArrayFunnel() {
return ByteArrayFunnel.INSTANCE;
}
private enum ByteArrayFunnel implements Funnel<byte[]> {
INSTANCE;
public void funnel(byte[] from, PrimitiveSink into) {
into.putBytes(from);
}
@Override public String toString() {
return "Funnels.byteArrayFunnel()";
}
}
/**
* Returns a funnel that extracts the characters from a {@code CharSequence}.
*/
public static Funnel<CharSequence> stringFunnel() {
return StringFunnel.INSTANCE;
}
private enum StringFunnel implements Funnel<CharSequence> {
INSTANCE;
public void funnel(CharSequence from, PrimitiveSink into) {
into.putString(from);
}
@Override public String toString() {
return "Funnels.stringFunnel()";
}
}
/**
* Returns a funnel for integers.
*
* @since 13.0
*/
public static Funnel<Integer> integerFunnel() {
return IntegerFunnel.INSTANCE;
}
private enum IntegerFunnel implements Funnel<Integer> {
INSTANCE;
public void funnel(Integer from, PrimitiveSink into) {
into.putInt(from);
}
@Override public String toString() {
return "Funnels.integerFunnel()";
}
}
/**
* Returns a funnel for longs.
*
* @since 13.0
*/
public static Funnel<Long> longFunnel() {
return LongFunnel.INSTANCE;
}
private enum LongFunnel implements Funnel<Long> {
INSTANCE;
public void funnel(Long from, PrimitiveSink into) {
into.putLong(from);
}
@Override public String toString() {
return "Funnels.longFunnel()";
}
}
/**
* Wraps a {@code PrimitiveSink} as an {@link OutputStream}, so it is easy to
* {@link Funnel#funnel funnel} an object to a {@code PrimitiveSink}
* if there is already a way to write the contents of the object to an {@code OutputStream}.
*
* <p>The {@code close} and {@code flush} methods of the returned {@code OutputStream}
* do nothing, and no method throws {@code IOException}.
*
* @since 13.0
*/
public static OutputStream asOutputStream(PrimitiveSink sink) {
return new SinkAsStream(sink);
}
private static class SinkAsStream extends OutputStream {
final PrimitiveSink sink;
SinkAsStream(PrimitiveSink sink) {
this.sink = Preconditions.checkNotNull(sink);
}
@Override public void write(int b) {
sink.putByte((byte) b);
}
@Override public void write(byte[] bytes) {
sink.putBytes(bytes);
}
@Override public void write(byte[] bytes, int off, int len) {
sink.putBytes(bytes, off, len);
}
@Override public String toString() {
return "Funnels.asOutputStream(" + sink + ")";
}
}
}
| Java |
/*
* 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.hash;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.base.Preconditions;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
/**
* Skeleton implementation of {@link HashFunction}. Provides default implementations which
* invokes the appropriate method on {@link #newHasher()}, then return the result of
* {@link Hasher#hash}.
*
* <p>Invocations of {@link #newHasher(int)} also delegate to {@linkplain #newHasher()}, ignoring
* the expected input size parameter.
*
* @author Kevin Bourrillion
*/
abstract class AbstractStreamingHashFunction implements HashFunction {
@Override public HashCode hashString(CharSequence input) {
return newHasher().putString(input).hash();
}
@Override public HashCode hashString(CharSequence input, Charset charset) {
return newHasher().putString(input, charset).hash();
}
@Override public HashCode hashInt(int input) {
return newHasher().putInt(input).hash();
}
@Override public HashCode hashLong(long input) {
return newHasher().putLong(input).hash();
}
@Override public HashCode hashBytes(byte[] input) {
return newHasher().putBytes(input).hash();
}
@Override public HashCode hashBytes(byte[] input, int off, int len) {
return newHasher().putBytes(input, off, len).hash();
}
@Override public Hasher newHasher(int expectedInputSize) {
Preconditions.checkArgument(expectedInputSize >= 0);
return newHasher();
}
/**
* A convenience base class for implementors of {@code Hasher}; handles accumulating data
* until an entire "chunk" (of implementation-dependent length) is ready to be hashed.
*
* @author Kevin Bourrillion
* @author Dimitris Andreou
*/
// TODO(kevinb): this class still needs some design-and-document-for-inheritance love
protected static abstract class AbstractStreamingHasher extends AbstractHasher {
/** Buffer via which we pass data to the hash algorithm (the implementor) */
private final ByteBuffer buffer;
/** Number of bytes to be filled before process() invocation(s). */
private final int bufferSize;
/** Number of bytes processed per process() invocation. */
private final int chunkSize;
/**
* Constructor for use by subclasses. This hasher instance will process chunks of the specified
* size.
*
* @param chunkSize the number of bytes available per {@link #process(ByteBuffer)} invocation;
* must be at least 4
*/
protected AbstractStreamingHasher(int chunkSize) {
this(chunkSize, chunkSize);
}
/**
* Constructor for use by subclasses. This hasher instance will process chunks of the specified
* size, using an internal buffer of {@code bufferSize} size, which must be a multiple of
* {@code chunkSize}.
*
* @param chunkSize the number of bytes available per {@link #process(ByteBuffer)} invocation;
* must be at least 4
* @param bufferSize the size of the internal buffer. Must be a multiple of chunkSize
*/
protected AbstractStreamingHasher(int chunkSize, int bufferSize) {
// TODO(kevinb): check more preconditions (as bufferSize >= chunkSize) if this is ever public
checkArgument(bufferSize % chunkSize == 0);
// TODO(user): benchmark performance difference with longer buffer
this.buffer = ByteBuffer
.allocate(bufferSize + 7) // always space for a single primitive
.order(ByteOrder.LITTLE_ENDIAN);
this.bufferSize = bufferSize;
this.chunkSize = chunkSize;
}
/**
* Processes the available bytes of the buffer (at most {@code chunk} bytes).
*/
protected abstract void process(ByteBuffer bb);
/**
* This is invoked for the last bytes of the input, which are not enough to
* fill a whole chunk. The passed {@code ByteBuffer} is guaranteed to be
* non-empty.
*
* <p>This implementation simply pads with zeros and delegates to
* {@link #process(ByteBuffer)}.
*/
protected void processRemaining(ByteBuffer bb) {
bb.position(bb.limit()); // move at the end
bb.limit(chunkSize + 7); // get ready to pad with longs
while (bb.position() < chunkSize) {
bb.putLong(0);
}
bb.limit(chunkSize);
bb.flip();
process(bb);
}
@Override
public final Hasher putBytes(byte[] bytes) {
return putBytes(bytes, 0, bytes.length);
}
@Override
public final Hasher putBytes(byte[] bytes, int off, int len) {
return putBytes(ByteBuffer.wrap(bytes, off, len).order(ByteOrder.LITTLE_ENDIAN));
}
private final Hasher putBytes(ByteBuffer readBuffer) {
// If we have room for all of it, this is easy
if (readBuffer.remaining() <= buffer.remaining()) {
buffer.put(readBuffer);
munchIfFull();
return this;
}
// First add just enough to fill buffer size, and munch that
int bytesToCopy = bufferSize - buffer.position();
for (int i = 0; i < bytesToCopy; i++) {
buffer.put(readBuffer.get());
}
munch(); // buffer becomes empty here, since chunkSize divides bufferSize
// Now process directly from the rest of the input buffer
while (readBuffer.remaining() >= chunkSize) {
process(readBuffer);
}
// Finally stick the remainder back in our usual buffer
buffer.put(readBuffer);
return this;
}
@Override
public final Hasher putString(CharSequence charSequence) {
for (int i = 0; i < charSequence.length(); i++) {
putChar(charSequence.charAt(i));
}
return this;
}
@Override
public final Hasher putByte(byte b) {
buffer.put(b);
munchIfFull();
return this;
}
@Override
public final Hasher putShort(short s) {
buffer.putShort(s);
munchIfFull();
return this;
}
@Override
public final Hasher putChar(char c) {
buffer.putChar(c);
munchIfFull();
return this;
}
@Override
public final Hasher putInt(int i) {
buffer.putInt(i);
munchIfFull();
return this;
}
@Override
public final Hasher putLong(long l) {
buffer.putLong(l);
munchIfFull();
return this;
}
@Override
public final <T> Hasher putObject(T instance, Funnel<? super T> funnel) {
funnel.funnel(instance, this);
return this;
}
@Override
public final HashCode hash() {
munch();
buffer.flip();
if (buffer.remaining() > 0) {
processRemaining(buffer);
}
return makeHash();
}
abstract HashCode makeHash();
// Process pent-up data in chunks
private void munchIfFull() {
if (buffer.remaining() < 8) {
// buffer is full; not enough room for a primitive. We have at least one full chunk.
munch();
}
}
private void munch() {
buffer.flip();
while (buffer.remaining() >= chunkSize) {
// we could limit the buffer to ensure process() does not read more than
// chunkSize number of bytes, but we trust the implementations
process(buffer);
}
buffer.compact(); // preserve any remaining data that do not make a full chunk
}
}
}
| Java |
/*
* 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.hash;
import static com.google.common.primitives.UnsignedBytes.toInt;
import java.io.Serializable;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
/**
* See http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp
* MurmurHash3_x64_128
*
* @author Austin Appleby
* @author Dimitris Andreou
*/
final class Murmur3_128HashFunction extends AbstractStreamingHashFunction implements Serializable {
// TODO(user): when the shortcuts are implemented, update BloomFilterStrategies
private final int seed;
Murmur3_128HashFunction(int seed) {
this.seed = seed;
}
@Override public int bits() {
return 128;
}
@Override public Hasher newHasher() {
return new Murmur3_128Hasher(seed);
}
private static final class Murmur3_128Hasher extends AbstractStreamingHasher {
private static final int CHUNK_SIZE = 16;
private static final long C1 = 0x87c37b91114253d5L;
private static final long C2 = 0x4cf5ad432745937fL;
private long h1;
private long h2;
private int length;
Murmur3_128Hasher(int seed) {
super(CHUNK_SIZE);
this.h1 = seed;
this.h2 = seed;
this.length = 0;
}
@Override protected void process(ByteBuffer bb) {
long k1 = bb.getLong();
long k2 = bb.getLong();
bmix64(k1, k2);
length += CHUNK_SIZE;
}
private void bmix64(long k1, long k2) {
h1 ^= mixK1(k1);
h1 = Long.rotateLeft(h1, 27);
h1 += h2;
h1 = h1 * 5 + 0x52dce729;
h2 ^= mixK2(k2);
h2 = Long.rotateLeft(h2, 31);
h2 += h1;
h2 = h2 * 5 + 0x38495ab5;
}
@Override protected void processRemaining(ByteBuffer bb) {
long k1 = 0;
long k2 = 0;
length += bb.remaining();
switch (bb.remaining()) {
case 15:
k2 ^= (long) toInt(bb.get(14)) << 48; // fall through
case 14:
k2 ^= (long) toInt(bb.get(13)) << 40; // fall through
case 13:
k2 ^= (long) toInt(bb.get(12)) << 32; // fall through
case 12:
k2 ^= (long) toInt(bb.get(11)) << 24; // fall through
case 11:
k2 ^= (long) toInt(bb.get(10)) << 16; // fall through
case 10:
k2 ^= (long) toInt(bb.get(9)) << 8; // fall through
case 9:
k2 ^= (long) toInt(bb.get(8)); // fall through
case 8:
k1 ^= bb.getLong();
break;
case 7:
k1 ^= (long) toInt(bb.get(6)) << 48; // fall through
case 6:
k1 ^= (long) toInt(bb.get(5)) << 40; // fall through
case 5:
k1 ^= (long) toInt(bb.get(4)) << 32; // fall through
case 4:
k1 ^= (long) toInt(bb.get(3)) << 24; // fall through
case 3:
k1 ^= (long) toInt(bb.get(2)) << 16; // fall through
case 2:
k1 ^= (long) toInt(bb.get(1)) << 8; // fall through
case 1:
k1 ^= (long) toInt(bb.get(0));
break;
default:
throw new AssertionError("Should never get here.");
}
h1 ^= mixK1(k1);
h2 ^= mixK2(k2);
}
@Override public HashCode makeHash() {
h1 ^= length;
h2 ^= length;
h1 += h2;
h2 += h1;
h1 = fmix64(h1);
h2 = fmix64(h2);
h1 += h2;
h2 += h1;
return HashCodes.fromBytesNoCopy(ByteBuffer
.wrap(new byte[CHUNK_SIZE])
.order(ByteOrder.LITTLE_ENDIAN)
.putLong(h1)
.putLong(h2)
.array());
}
private static long fmix64(long k) {
k ^= k >>> 33;
k *= 0xff51afd7ed558ccdL;
k ^= k >>> 33;
k *= 0xc4ceb9fe1a85ec53L;
k ^= k >>> 33;
return k;
}
private static long mixK1(long k1) {
k1 *= C1;
k1 = Long.rotateLeft(k1, 31);
k1 *= C2;
return k1;
}
private static long mixK2(long k2) {
k2 *= C2;
k2 = Long.rotateLeft(k2, 33);
k2 *= C1;
return k2;
}
}
private static final long serialVersionUID = 0L;
}
| Java |
/*
* 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.hash;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.math.LongMath;
import com.google.common.primitives.Ints;
import java.math.RoundingMode;
import java.util.Arrays;
/**
* Collections of strategies of generating the k * log(M) bits required for an element to
* be mapped to a BloomFilter of M bits and k hash functions. These
* strategies are part of the serialized form of the Bloom filters that use them, thus they must be
* preserved as is (no updates allowed, only introduction of new versions).
*
* Important: the order of the constants cannot change, and they cannot be deleted - we depend
* on their ordinal for BloomFilter serialization.
*
* @author Dimitris Andreou
*/
enum BloomFilterStrategies implements BloomFilter.Strategy {
/**
* See "Less Hashing, Same Performance: Building a Better Bloom Filter" by Adam Kirsch and
* Michael Mitzenmacher. The paper argues that this trick doesn't significantly deteriorate the
* performance of a Bloom filter (yet only needs two 32bit hash functions).
*/
MURMUR128_MITZ_32() {
@Override public <T> boolean put(T object, Funnel<? super T> funnel,
int numHashFunctions, BitArray bits) {
// TODO(user): when the murmur's shortcuts are implemented, update this code
long hash64 = Hashing.murmur3_128().newHasher().putObject(object, funnel).hash().asLong();
int hash1 = (int) hash64;
int hash2 = (int) (hash64 >>> 32);
boolean bitsChanged = false;
for (int i = 1; i <= numHashFunctions; i++) {
int nextHash = hash1 + i * hash2;
if (nextHash < 0) {
nextHash = ~nextHash;
}
bitsChanged |= bits.set(nextHash % bits.size());
}
return bitsChanged;
}
@Override public <T> boolean mightContain(T object, Funnel<? super T> funnel,
int numHashFunctions, BitArray bits) {
long hash64 = Hashing.murmur3_128().newHasher().putObject(object, funnel).hash().asLong();
int hash1 = (int) hash64;
int hash2 = (int) (hash64 >>> 32);
for (int i = 1; i <= numHashFunctions; i++) {
int nextHash = hash1 + i * hash2;
if (nextHash < 0) {
nextHash = ~nextHash;
}
if (!bits.get(nextHash % bits.size())) {
return false;
}
}
return true;
}
};
// Note: We use this instead of java.util.BitSet because we need access to the long[] data field
static class BitArray {
final long[] data;
int bitCount;
BitArray(long bits) {
this(new long[Ints.checkedCast(LongMath.divide(bits, 64, RoundingMode.CEILING))]);
}
// Used by serialization
BitArray(long[] data) {
checkArgument(data.length > 0, "data length is zero!");
this.data = data;
int bitCount = 0;
for (long value : data) {
bitCount += Long.bitCount(value);
}
this.bitCount = bitCount;
}
/** Returns true if the bit changed value. */
boolean set(int index) {
if (!get(index)) {
data[index >> 6] |= (1L << index);
bitCount++;
return true;
}
return false;
}
boolean get(int index) {
return (data[index >> 6] & (1L << index)) != 0;
}
/** Number of bits */
int size() {
return data.length * Long.SIZE;
}
/** Number of set bits (1s) */
int bitCount() {
return bitCount;
}
BitArray copy() {
return new BitArray(data.clone());
}
@Override public boolean equals(Object o) {
if (o instanceof BitArray) {
BitArray bitArray = (BitArray) o;
return Arrays.equals(data, bitArray.data);
}
return false;
}
@Override public int hashCode() {
return Arrays.hashCode(data);
}
}
}
| Java |
/*
* 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.hash;
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.Objects;
import com.google.common.base.Predicate;
import com.google.common.hash.BloomFilterStrategies.BitArray;
import java.io.Serializable;
import javax.annotation.Nullable;
/**
* A Bloom filter for instances of {@code T}. A Bloom filter offers an approximate containment test
* with one-sided error: if it claims that an element is contained in it, this might be in error,
* but if it claims that an element is <i>not</i> contained in it, then this is definitely true.
*
* <p>If you are unfamiliar with Bloom filters, this nice
* <a href="http://llimllib.github.com/bloomfilter-tutorial/">tutorial</a> may help you understand
* how they work.
*
* <p>The false positive probability ({@code FPP}) of a bloom filter is defined as the probability
* that {@linkplain #mightContain(Object)} will erroneously return {@code true} for an object that
* has not actually been put in the {@code BloomFilter}.
*
*
* @param <T> the type of instances that the {@code BloomFilter} accepts
* @author Dimitris Andreou
* @author Kevin Bourrillion
* @since 11.0
*/
@Beta
public final class BloomFilter<T> implements Predicate<T>, Serializable {
/**
* A strategy to translate T instances, to {@code numHashFunctions} bit indexes.
*
* <p>Implementations should be collections of pure functions (i.e. stateless).
*/
interface Strategy extends java.io.Serializable {
/**
* Sets {@code numHashFunctions} bits of the given bit array, by hashing a user element.
*
* <p>Returns whether any bits changed as a result of this operation.
*/
<T> boolean put(T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits);
/**
* Queries {@code numHashFunctions} bits of the given bit array, by hashing a user element;
* returns {@code true} if and only if all selected bits are set.
*/
<T> boolean mightContain(
T object, Funnel<? super T> funnel, int numHashFunctions, BitArray bits);
/**
* Identifier used to encode this strategy, when marshalled as part of a BloomFilter.
* Only values in the [-128, 127] range are valid for the compact serial form.
* Non-negative values are reserved for enums defined in BloomFilterStrategies;
* negative values are reserved for any custom, stateful strategy we may define
* (e.g. any kind of strategy that would depend on user input).
*/
int ordinal();
}
/** The bit set of the BloomFilter (not necessarily power of 2!)*/
private final BitArray bits;
/** Number of hashes per element */
private final int numHashFunctions;
/** The funnel to translate Ts to bytes */
private final Funnel<T> funnel;
/**
* The strategy we employ to map an element T to {@code numHashFunctions} bit indexes.
*/
private final Strategy strategy;
/**
* Creates a BloomFilter.
*/
private BloomFilter(BitArray bits, int numHashFunctions, Funnel<T> funnel,
Strategy strategy) {
checkArgument(numHashFunctions > 0,
"numHashFunctions (%s) must be > 0", numHashFunctions);
checkArgument(numHashFunctions <= 255,
"numHashFunctions (%s) must be <= 255", numHashFunctions);
this.bits = checkNotNull(bits);
this.numHashFunctions = numHashFunctions;
this.funnel = checkNotNull(funnel);
this.strategy = checkNotNull(strategy);
}
/**
* Creates a new {@code BloomFilter} that's a copy of this instance. The new instance is equal to
* this instance but shares no mutable state.
*
* @since 12.0
*/
public BloomFilter<T> copy() {
return new BloomFilter<T>(bits.copy(), numHashFunctions, funnel, strategy);
}
/**
* Returns {@code true} if the element <i>might</i> have been put in this Bloom filter,
* {@code false} if this is <i>definitely</i> not the case.
*/
public boolean mightContain(T object) {
return strategy.mightContain(object, funnel, numHashFunctions, bits);
}
/**
* Equivalent to {@link #mightContain}; provided only to satisfy the {@link Predicate} interface.
* When using a reference of type {@code BloomFilter}, always invoke {@link #mightContain}
* directly instead.
*/
@Override public boolean apply(T input) {
return mightContain(input);
}
/**
* Puts an element into this {@code BloomFilter}. Ensures that subsequent invocations of
* {@link #mightContain(Object)} with the same element will always return {@code true}.
*
* @return true if the bloom filter's bits changed as a result of this operation. If the bits
* changed, this is <i>definitely</i> the first time {@code object} has been added to the
* filter. If the bits haven't changed, this <i>might</i> be the first time {@code object}
* has been added to the filter. Note that {@code put(t)} always returns the
* <i>opposite</i> result to what {@code mightContain(t)} would have returned at the time
* it is called."
* @since 12.0 (present in 11.0 with {@code void} return type})
*/
public boolean put(T object) {
return strategy.put(object, funnel, numHashFunctions, bits);
}
/**
* Returns the probability that {@linkplain #mightContain(Object)} will erroneously return
* {@code true} for an object that has not actually been put in the {@code BloomFilter}.
*
* <p>Ideally, this number should be close to the {@code fpp} parameter
* passed in {@linkplain #create(Funnel, int, double)}, or smaller. If it is
* significantly higher, it is usually the case that too many elements (more than
* expected) have been put in the {@code BloomFilter}, degenerating it.
*
* @since 14.0 (since 11.0 as expectedFalsePositiveProbability())
*/
public double expectedFpp() {
// You down with FPP? (Yeah you know me!) Who's down with FPP? (Every last homie!)
return Math.pow((double) bits.bitCount() / bits.size(), numHashFunctions);
}
/**
* @deprecated Use {@link #expectedFpp} instead.
*/
@Deprecated
public double expectedFalsePositiveProbability() {
return expectedFpp();
}
@Override
public boolean equals(@Nullable Object object) {
if (object == this) {
return true;
}
if (object instanceof BloomFilter) {
BloomFilter<?> that = (BloomFilter<?>) object;
return this.numHashFunctions == that.numHashFunctions
&& this.funnel.equals(that.funnel)
&& this.bits.equals(that.bits)
&& this.strategy.equals(that.strategy);
}
return false;
}
@Override
public int hashCode() {
return Objects.hashCode(numHashFunctions, funnel, strategy, bits);
}
/**
* Creates a {@code Builder} of a {@link BloomFilter BloomFilter<T>}, with the expected number
* of insertions and expected false positive probability.
*
* <p>Note that overflowing a {@code BloomFilter} with significantly more elements
* than specified, will result in its saturation, and a sharp deterioration of its
* false positive probability.
*
* <p>The constructed {@code BloomFilter<T>} will be serializable if the provided
* {@code Funnel<T>} is.
*
* <p>It is recommended the funnel is implemented as a Java enum. This has the benefit of ensuring
* proper serialization and deserialization, which is important since {@link #equals} also relies
* on object identity of funnels.
*
* @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use
* @param expectedInsertions the number of expected insertions to the constructed
* {@code BloomFilter<T>}; must be positive
* @param fpp the desired false positive probability (must be positive and less than 1.0)
* @return a {@code BloomFilter}
*/
public static <T> BloomFilter<T> create(
Funnel<T> funnel, int expectedInsertions /* n */, double fpp) {
checkNotNull(funnel);
checkArgument(expectedInsertions >= 0, "Expected insertions (%s) must be >= 0",
expectedInsertions);
checkArgument(fpp > 0.0, "False positive probability (%s) must be > 0.0", fpp);
checkArgument(fpp < 1.0, "False positive probability (%s) must be < 1.0", fpp);
if (expectedInsertions == 0) {
expectedInsertions = 1;
}
/*
* TODO(user): Put a warning in the javadoc about tiny fpp values,
* since the resulting size is proportional to -log(p), but there is not
* much of a point after all, e.g. optimalM(1000, 0.0000000000000001) = 76680
* which is less that 10kb. Who cares!
*/
long numBits = optimalNumOfBits(expectedInsertions, fpp);
int numHashFunctions = optimalNumOfHashFunctions(expectedInsertions, numBits);
try {
return new BloomFilter<T>(new BitArray(numBits), numHashFunctions, funnel,
BloomFilterStrategies.MURMUR128_MITZ_32);
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Could not create BloomFilter of " + numBits + " bits", e);
}
}
/**
* Creates a {@code Builder} of a {@link BloomFilter BloomFilter<T>}, with the expected number
* of insertions, and a default expected false positive probability of 3%.
*
* <p>Note that overflowing a {@code BloomFilter} with significantly more elements
* than specified, will result in its saturation, and a sharp deterioration of its
* false positive probability.
*
* <p>The constructed {@code BloomFilter<T>} will be serializable if the provided
* {@code Funnel<T>} is.
*
* @param funnel the funnel of T's that the constructed {@code BloomFilter<T>} will use
* @param expectedInsertions the number of expected insertions to the constructed
* {@code BloomFilter<T>}; must be positive
* @return a {@code BloomFilter}
*/
public static <T> BloomFilter<T> create(Funnel<T> funnel, int expectedInsertions /* n */) {
return create(funnel, expectedInsertions, 0.03); // FYI, for 3%, we always get 5 hash functions
}
/*
* Cheat sheet:
*
* m: total bits
* n: expected insertions
* b: m/n, bits per insertion
* p: expected false positive probability
*
* 1) Optimal k = b * ln2
* 2) p = (1 - e ^ (-kn/m))^k
* 3) For optimal k: p = 2 ^ (-k) ~= 0.6185^b
* 4) For optimal k: m = -nlnp / ((ln2) ^ 2)
*/
/**
* Computes the optimal k (number of hashes per element inserted in Bloom filter), given the
* expected insertions and total number of bits in the Bloom filter.
*
* See http://en.wikipedia.org/wiki/File:Bloom_filter_fp_probability.svg for the formula.
*
* @param n expected insertions (must be positive)
* @param m total number of bits in Bloom filter (must be positive)
*/
@VisibleForTesting
static int optimalNumOfHashFunctions(long n, long m) {
return Math.max(1, (int) Math.round(m / n * Math.log(2)));
}
/**
* Computes m (total bits of Bloom filter) which is expected to achieve, for the specified
* expected insertions, the required false positive probability.
*
* See http://en.wikipedia.org/wiki/Bloom_filter#Probability_of_false_positives for the formula.
*
* @param n expected insertions (must be positive)
* @param p false positive rate (must be 0 < p < 1)
*/
@VisibleForTesting
static long optimalNumOfBits(long n, double p) {
if (p == 0) {
p = Double.MIN_VALUE;
}
return (long) (-n * Math.log(p) / (Math.log(2) * Math.log(2)));
}
private Object writeReplace() {
return new SerialForm<T>(this);
}
private static class SerialForm<T> implements Serializable {
final long[] data;
final int numHashFunctions;
final Funnel<T> funnel;
final Strategy strategy;
SerialForm(BloomFilter<T> bf) {
this.data = bf.bits.data;
this.numHashFunctions = bf.numHashFunctions;
this.funnel = bf.funnel;
this.strategy = bf.strategy;
}
Object readResolve() {
return new BloomFilter<T>(new BitArray(data), numHashFunctions, funnel, strategy);
}
private static final long serialVersionUID = 1;
}
}
| Java |
/*
* 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.hash;
import com.google.common.annotations.Beta;
import java.nio.charset.Charset;
/**
* A {@link PrimitiveSink} that can compute a hash code after reading the input. Each hasher should
* translate all multibyte values ({@link #putInt(int)}, {@link #putLong(long)}, etc) to bytes
* in little-endian order.
*
* @author Kevin Bourrillion
* @since 11.0
*/
@Beta
public interface Hasher extends PrimitiveSink {
@Override Hasher putByte(byte b);
@Override Hasher putBytes(byte[] bytes);
@Override Hasher putBytes(byte[] bytes, int off, int len);
@Override Hasher putShort(short s);
@Override Hasher putInt(int i);
@Override Hasher putLong(long l);
/**
* Equivalent to {@code putInt(Float.floatToRawIntBits(f))}.
*/
@Override Hasher putFloat(float f);
/**
* Equivalent to {@code putLong(Double.doubleToRawLongBits(d))}.
*/
@Override Hasher putDouble(double d);
/**
* Equivalent to {@code putByte(b ? (byte) 1 : (byte) 0)}.
*/
@Override Hasher putBoolean(boolean b);
@Override Hasher putChar(char c);
/**
* Equivalent to processing each {@code char} value in the {@code CharSequence}, in order.
* The input must not be updated while this method is in progress.
*/
@Override Hasher putString(CharSequence charSequence);
/**
* Equivalent to {@code putBytes(charSequence.toString().getBytes(charset))}.
*/
@Override Hasher putString(CharSequence charSequence, Charset charset);
/**
* A simple convenience for {@code funnel.funnel(object, this)}.
*/
<T> Hasher putObject(T instance, Funnel<? super T> funnel);
/**
* Computes a hash code based on the data that have been provided to this hasher. The result is
* unspecified if this method is called more than once on the same instance.
*/
HashCode hash();
}
| Java |
/*
* 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.hash;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.Beta;
import java.io.Serializable;
/**
* Static factories for creating {@link HashCode} instances; most users should never have to use
* this. All returned instances are {@link Serializable}.
*
* @author Dimitris Andreou
* @since 12.0
*/
@Beta
public final class HashCodes {
private HashCodes() {}
/**
* Creates a 32-bit {@code HashCode}, of which the bytes will form the passed int, interpreted
* in little endian order.
*/
public static HashCode fromInt(int hash) {
return new IntHashCode(hash);
}
private static final class IntHashCode extends HashCode implements Serializable {
final int hash;
IntHashCode(int hash) {
this.hash = hash;
}
@Override public int bits() {
return 32;
}
@Override public byte[] asBytes() {
return new byte[] {
(byte) hash,
(byte) (hash >> 8),
(byte) (hash >> 16),
(byte) (hash >> 24)};
}
@Override public int asInt() {
return hash;
}
@Override public long asLong() {
throw new IllegalStateException("this HashCode only has 32 bits; cannot create a long");
}
private static final long serialVersionUID = 0;
}
/**
* Creates a 64-bit {@code HashCode}, of which the bytes will form the passed long, interpreted
* in little endian order.
*/
public static HashCode fromLong(long hash) {
return new LongHashCode(hash);
}
private static final class LongHashCode extends HashCode implements Serializable {
final long hash;
LongHashCode(long hash) {
this.hash = hash;
}
@Override public int bits() {
return 64;
}
@Override public byte[] asBytes() {
return new byte[] {
(byte) hash,
(byte) (hash >> 8),
(byte) (hash >> 16),
(byte) (hash >> 24),
(byte) (hash >> 32),
(byte) (hash >> 40),
(byte) (hash >> 48),
(byte) (hash >> 56)};
}
@Override public int asInt() {
return (int) hash;
}
@Override public long asLong() {
return hash;
}
private static final long serialVersionUID = 0;
}
/**
* Creates a {@code HashCode} from a byte array. The array is defensively copied to preserve
* the immutability contract of {@code HashCode}. The array must be at least of length 4.
*/
public static HashCode fromBytes(byte[] bytes) {
checkArgument(bytes.length >= 4, "A HashCode must contain at least 4 bytes.");
return fromBytesNoCopy(bytes.clone());
}
/**
* Creates a {@code HashCode} from a byte array. The array is <i>not</i> copied defensively,
* so it must be handed-off so as to preserve the immutability contract of {@code HashCode}.
* The array must be at least of length 4 (not checked).
*/
static HashCode fromBytesNoCopy(byte[] bytes) {
return new BytesHashCode(bytes);
}
private static final class BytesHashCode extends HashCode implements Serializable {
final byte[] bytes;
BytesHashCode(byte[] bytes) {
this.bytes = bytes;
}
@Override public int bits() {
return bytes.length * 8;
}
@Override public byte[] asBytes() {
return bytes.clone();
}
@Override public int asInt() {
return (bytes[0] & 0xFF)
| ((bytes[1] & 0xFF) << 8)
| ((bytes[2] & 0xFF) << 16)
| ((bytes[3] & 0xFF) << 24);
}
@Override public long asLong() {
if (bytes.length < 8) {
// Checking this to throw the correct type of exception
throw new IllegalStateException("Not enough bytes");
}
return (bytes[0] & 0xFFL)
| ((bytes[1] & 0xFFL) << 8)
| ((bytes[2] & 0xFFL) << 16)
| ((bytes[3] & 0xFFL) << 24)
| ((bytes[4] & 0xFFL) << 32)
| ((bytes[5] & 0xFFL) << 40)
| ((bytes[6] & 0xFFL) << 48)
| ((bytes[7] & 0xFFL) << 56);
}
private static final long serialVersionUID = 0;
}
}
| Java |
/*
* 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.hash;
import com.google.common.annotations.Beta;
import java.nio.charset.Charset;
/**
* An object which can receive a stream of primitive values.
*
* @author Kevin Bourrillion
* @since 12.0 (in 11.0 as {@code Sink})
*/
@Beta
public interface PrimitiveSink {
/**
* Puts a byte into this sink.
*
* @param b a byte
* @return this instance
*/
PrimitiveSink putByte(byte b);
/**
* Puts an array of bytes into this sink.
*
* @param bytes a byte array
* @return this instance
*/
PrimitiveSink putBytes(byte[] bytes);
/**
* Puts a chunk of an array of bytes into this sink. {@code bytes[off]} is the first byte written,
* {@code bytes[off + len - 1]} is the last.
*
* @param bytes a byte array
* @param off the start offset in the array
* @param len the number of bytes to write
* @return this instance
* @throws IndexOutOfBoundsException if {@code off < 0} or {@code off + len > bytes.length} or
* {@code len < 0}
*/
PrimitiveSink putBytes(byte[] bytes, int off, int len);
/**
* Puts a short into this sink.
*/
PrimitiveSink putShort(short s);
/**
* Puts an int into this sink.
*/
PrimitiveSink putInt(int i);
/**
* Puts a long into this sink.
*/
PrimitiveSink putLong(long l);
/**
* Puts a float into this sink.
*/
PrimitiveSink putFloat(float f);
/**
* Puts a double into this sink.
*/
PrimitiveSink putDouble(double d);
/**
* Puts a boolean into this sink.
*/
PrimitiveSink putBoolean(boolean b);
/**
* Puts a character into this sink.
*/
PrimitiveSink putChar(char c);
/**
* Puts a string into this sink.
*/
PrimitiveSink putString(CharSequence charSequence);
/**
* Puts a string into this sink using the given charset.
*/
PrimitiveSink putString(CharSequence charSequence, Charset charset);
}
| Java |
/*
* 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.hash;
import static com.google.common.primitives.UnsignedBytes.toInt;
import com.google.common.primitives.Chars;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import java.io.Serializable;
import java.nio.ByteBuffer;
/**
* See http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp
* MurmurHash3_x86_32
*
* @author Austin Appleby
* @author Dimitris Andreou
* @author Kurt Alfred Kluever
*/
final class Murmur3_32HashFunction extends AbstractStreamingHashFunction implements Serializable {
private static final int C1 = 0xcc9e2d51;
private static final int C2 = 0x1b873593;
private final int seed;
Murmur3_32HashFunction(int seed) {
this.seed = seed;
}
@Override public int bits() {
return 32;
}
@Override public Hasher newHasher() {
return new Murmur3_32Hasher(seed);
}
@Override public HashCode hashInt(int input) {
int k1 = mixK1(input);
int h1 = mixH1(seed, k1);
return fmix(h1, Ints.BYTES);
}
@Override public HashCode hashLong(long input) {
int low = (int) input;
int high = (int) (input >>> 32);
int k1 = mixK1(low);
int h1 = mixH1(seed, k1);
k1 = mixK1(high);
h1 = mixH1(h1, k1);
return fmix(h1, Longs.BYTES);
}
// TODO(user): Maybe implement #hashBytes instead?
@Override public HashCode hashString(CharSequence input) {
int h1 = seed;
// step through the CharSequence 2 chars at a time
for (int i = 1; i < input.length(); i += 2) {
int k1 = input.charAt(i - 1) | (input.charAt(i) << 16);
k1 = mixK1(k1);
h1 = mixH1(h1, k1);
}
// deal with any remaining characters
if ((input.length() & 1) == 1) {
int k1 = input.charAt(input.length() - 1);
k1 = mixK1(k1);
h1 ^= k1;
}
return fmix(h1, Chars.BYTES * input.length());
}
private static int mixK1(int k1) {
k1 *= C1;
k1 = Integer.rotateLeft(k1, 15);
k1 *= C2;
return k1;
}
private static int mixH1(int h1, int k1) {
h1 ^= k1;
h1 = Integer.rotateLeft(h1, 13);
h1 = h1 * 5 + 0xe6546b64;
return h1;
}
// Finalization mix - force all bits of a hash block to avalanche
private static HashCode fmix(int h1, int length) {
h1 ^= length;
h1 ^= h1 >>> 16;
h1 *= 0x85ebca6b;
h1 ^= h1 >>> 13;
h1 *= 0xc2b2ae35;
h1 ^= h1 >>> 16;
return HashCodes.fromInt(h1);
}
private static final class Murmur3_32Hasher extends AbstractStreamingHasher {
private static final int CHUNK_SIZE = 4;
private int h1;
private int length;
Murmur3_32Hasher(int seed) {
super(CHUNK_SIZE);
this.h1 = seed;
this.length = 0;
}
@Override protected void process(ByteBuffer bb) {
int k1 = Murmur3_32HashFunction.mixK1(bb.getInt());
h1 = Murmur3_32HashFunction.mixH1(h1, k1);
length += CHUNK_SIZE;
}
@Override protected void processRemaining(ByteBuffer bb) {
length += bb.remaining();
int k1 = 0;
switch (bb.remaining()) {
case 3:
k1 ^= toInt(bb.get(2)) << 16; // fall through
case 2:
k1 ^= toInt(bb.get(1)) << 8; // fall through
case 1:
k1 ^= toInt(bb.get(0));
break;
default:
throw new AssertionError("Should never get here.");
}
h1 ^= Murmur3_32HashFunction.mixK1(k1);
}
@Override public HashCode makeHash() {
return Murmur3_32HashFunction.fmix(h1, length);
}
}
private static final long serialVersionUID = 0L;
}
| Java |
/*
* 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.hash;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.Beta;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.UnsignedInts;
import java.nio.ByteBuffer;
import java.security.MessageDigest;
import java.util.Iterator;
/**
* Static methods to obtain {@link HashFunction} instances, and other static
* hashing-related utilities.
*
* @author Kevin Bourrillion
* @author Dimitris Andreou
* @author Kurt Alfred Kluever
* @since 11.0
*/
@Beta
public final class Hashing {
private Hashing() {}
/**
* Used to randomize {@link #goodFastHash} instances, so that programs which persist anything
* dependent on hashcodes of those, will fail sooner than later.
*/
private static final int GOOD_FAST_HASH_SEED = (int) System.currentTimeMillis();
// Used by goodFastHash when minimumBits == 32.
private static final HashFunction GOOD_FAST_HASH_FUNCTION_32 = murmur3_32(GOOD_FAST_HASH_SEED);
// Used by goodFastHash when 32 < minimumBits <= 128.
private static final HashFunction GOOD_FAST_HASH_FUNCTION_128 = murmur3_128(GOOD_FAST_HASH_SEED);
/**
* Returns a general-purpose, <b>non-cryptographic-strength</b>, streaming hash function that
* produces hash codes of length at least {@code minimumBits}. Users without specific
* compatibility requirements and who do not persist the hash codes are encouraged to
* choose this hash function.
*
* <p>Repeated calls to {@link #goodFastHash} with the same {@code minimumBits} value will
* return {@link HashFunction} instances with identical behavior (but not necessarily the
* same instance) for the duration of the current virtual machine.
*
* <p><b>Warning: the implementation is unspecified and is subject to change.</b>
*
* @throws IllegalArgumentException if {@code minimumBits} is not positive
*/
public static HashFunction goodFastHash(int minimumBits) {
int bits = checkPositiveAndMakeMultipleOf32(minimumBits);
if (bits == 32) {
return GOOD_FAST_HASH_FUNCTION_32;
}
if (bits <= 128) {
return GOOD_FAST_HASH_FUNCTION_128;
}
// Otherwise, join together some 128-bit murmur3s
int hashFunctionsNeeded = (bits + 127) / 128;
HashFunction[] hashFunctions = new HashFunction[hashFunctionsNeeded];
hashFunctions[0] = GOOD_FAST_HASH_FUNCTION_128;
int seed = GOOD_FAST_HASH_SEED;
for (int i = 1; i < hashFunctionsNeeded; i++) {
seed += 1500450271; // a prime; shouldn't matter
hashFunctions[i] = murmur3_128(seed);
}
return new ConcatenatedHashFunction(hashFunctions);
}
/**
* Returns a hash function implementing the
* <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp">32-bit murmur3
* algorithm</a> (little-endian variant), using the given seed value.
*/
public static HashFunction murmur3_32(int seed) {
return new Murmur3_32HashFunction(seed);
}
/**
* Returns a hash function implementing the
* <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp">32-bit murmur3
* algorithm</a> (little-endian variant), using a seed value of zero.
*/
public static HashFunction murmur3_32() {
return MURMUR3_32;
}
private static final Murmur3_32HashFunction MURMUR3_32 = new Murmur3_32HashFunction(0);
/**
* Returns a hash function implementing the
* <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp">
* 128-bit murmur3 algorithm, x64 variant</a> (little-endian variant), using the given seed
* value.
*/
public static HashFunction murmur3_128(int seed) {
return new Murmur3_128HashFunction(seed);
}
/**
* Returns a hash function implementing the
* <a href="http://smhasher.googlecode.com/svn/trunk/MurmurHash3.cpp">
* 128-bit murmur3 algorithm, x64 variant</a> (little-endian variant), using a seed value
* of zero.
*/
public static HashFunction murmur3_128() {
return MURMUR3_128;
}
private static final Murmur3_128HashFunction MURMUR3_128 = new Murmur3_128HashFunction(0);
/**
* Returns a hash function implementing the MD5 hash algorithm (128 hash bits) by delegating to
* the MD5 {@link MessageDigest}.
*/
public static HashFunction md5() {
return MD5;
}
private static final HashFunction MD5 = new MessageDigestHashFunction("MD5");
/**
* Returns a hash function implementing the SHA-1 algorithm (160 hash bits) by delegating to the
* SHA-1 {@link MessageDigest}.
*/
public static HashFunction sha1() {
return SHA_1;
}
private static final HashFunction SHA_1 = new MessageDigestHashFunction("SHA-1");
/**
* Returns a hash function implementing the SHA-256 algorithm (256 hash bits) by delegating to
* the SHA-256 {@link MessageDigest}.
*/
public static HashFunction sha256() {
return SHA_256;
}
private static final HashFunction SHA_256 = new MessageDigestHashFunction("SHA-256");
/**
* Returns a hash function implementing the SHA-512 algorithm (512 hash bits) by delegating to the
* SHA-512 {@link MessageDigest}.
*/
public static HashFunction sha512() {
return SHA_512;
}
private static final HashFunction SHA_512 = new MessageDigestHashFunction("SHA-512");
// Lazy initiliazation holder class idiom.
/**
* If {@code hashCode} has enough bits, returns {@code hashCode.asLong()}, otherwise
* returns a {@code long} value with {@code hashCode.asInt()} as the least-significant
* four bytes and {@code 0x00} as each of the most-significant four bytes.
*/
public static long padToLong(HashCode hashCode) {
return (hashCode.bits() < 64) ? UnsignedInts.toLong(hashCode.asInt()) : hashCode.asLong();
}
/**
* Assigns to {@code hashCode} a "bucket" in the range {@code [0, buckets)}, in a uniform
* manner that minimizes the need for remapping as {@code buckets} grows. That is,
* {@code consistentHash(h, n)} equals:
*
* <ul>
* <li>{@code n - 1}, with approximate probability {@code 1/n}
* <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n})
* </ul>
*
* <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">wikipedia
* article on consistent hashing</a> for more information.
* <p>
* If you might want to have weights for the buckets in the future, take a look at
* {@code weightedConsistentHash}.
*/
public static int consistentHash(HashCode hashCode, int buckets) {
return consistentHash(padToLong(hashCode), buckets);
}
/**
* Assigns to {@code input} a "bucket" in the range {@code [0, buckets)}, in a uniform
* manner that minimizes the need for remapping as {@code buckets} grows. That is,
* {@code consistentHash(h, n)} equals:
*
* <ul>
* <li>{@code n - 1}, with approximate probability {@code 1/n}
* <li>{@code consistentHash(h, n - 1)}, otherwise (probability {@code 1 - 1/n})
* </ul>
*
* <p>See the <a href="http://en.wikipedia.org/wiki/Consistent_hashing">wikipedia
* article on consistent hashing</a> for more information.
* <p>
* If you might want to have weights for the buckets in the future, take a look at
* {@code weightedConsistentHash}.
*/
public static int consistentHash(long input, int buckets) {
checkArgument(buckets > 0, "buckets must be positive: %s", buckets);
LinearCongruentialGenerator generator = new LinearCongruentialGenerator(input);
int candidate = 0;
int next;
// Jump from bucket to bucket until we go out of range
while (true) {
next = (int) ((candidate + 1) / generator.nextDouble());
if (next >= 0 && next < buckets) {
candidate = next;
} else {
return candidate;
}
}
}
/**
* Returns a hash code, having the same bit length as each of the input hash codes,
* that combines the information of these hash codes in an ordered fashion. That
* is, whenever two equal hash codes are produced by two calls to this method, it
* is <i>as likely as possible</i> that each was computed from the <i>same</i>
* input hash codes in the <i>same</i> order.
*
* @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes
* do not all have the same bit length
*/
public static HashCode combineOrdered(Iterable<HashCode> hashCodes) {
Iterator<HashCode> iterator = hashCodes.iterator();
checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine.");
int bits = iterator.next().bits();
byte[] resultBytes = new byte[bits / 8];
for (HashCode hashCode : hashCodes) {
byte[] nextBytes = hashCode.asBytes();
checkArgument(nextBytes.length == resultBytes.length,
"All hashcodes must have the same bit length.");
for (int i = 0; i < nextBytes.length; i++) {
resultBytes[i] = (byte) (resultBytes[i] * 37 ^ nextBytes[i]);
}
}
return HashCodes.fromBytesNoCopy(resultBytes);
}
/**
* Returns a hash code, having the same bit length as each of the input hash codes,
* that combines the information of these hash codes in an unordered fashion. That
* is, whenever two equal hash codes are produced by two calls to this method, it
* is <i>as likely as possible</i> that each was computed from the <i>same</i>
* input hash codes in <i>some</i> order.
*
* @throws IllegalArgumentException if {@code hashCodes} is empty, or the hash codes
* do not all have the same bit length
*/
public static HashCode combineUnordered(Iterable<HashCode> hashCodes) {
Iterator<HashCode> iterator = hashCodes.iterator();
checkArgument(iterator.hasNext(), "Must be at least 1 hash code to combine.");
byte[] resultBytes = new byte[iterator.next().bits() / 8];
for (HashCode hashCode : hashCodes) {
byte[] nextBytes = hashCode.asBytes();
checkArgument(nextBytes.length == resultBytes.length,
"All hashcodes must have the same bit length.");
for (int i = 0; i < nextBytes.length; i++) {
resultBytes[i] += nextBytes[i];
}
}
return HashCodes.fromBytesNoCopy(resultBytes);
}
/**
* Checks that the passed argument is positive, and ceils it to a multiple of 32.
*/
static int checkPositiveAndMakeMultipleOf32(int bits) {
checkArgument(bits > 0, "Number of bits must be positive");
return (bits + 31) & ~31;
}
// TODO(kevinb): Maybe expose this class via a static Hashing method?
@VisibleForTesting
static final class ConcatenatedHashFunction extends AbstractCompositeHashFunction {
private final int bits;
ConcatenatedHashFunction(HashFunction... functions) {
super(functions);
int bitSum = 0;
for (HashFunction function : functions) {
bitSum += function.bits();
}
this.bits = bitSum;
}
@Override
HashCode makeHash(Hasher[] hashers) {
// TODO(user): Get rid of the ByteBuffer here?
byte[] bytes = new byte[bits / 8];
ByteBuffer buffer = ByteBuffer.wrap(bytes);
for (Hasher hasher : hashers) {
buffer.put(hasher.hash().asBytes());
}
return HashCodes.fromBytesNoCopy(bytes);
}
@Override
public int bits() {
return bits;
}
}
private static final class LinearCongruentialGenerator {
private long state;
public LinearCongruentialGenerator(long seed) {
this.state = seed;
}
public double nextDouble() {
state = 2862933555777941757L * state + 1;
return ((double) ((int) (state >>> 33) + 1)) / (0x1.0p31);
}
}
}
| Java |
/*
* 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.hash;
import com.google.common.base.Preconditions;
import com.google.common.base.Throwables;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
/**
* Skeleton implementation of {@link HashFunction}, appropriate for non-streaming algorithms.
* All the hash computation done using {@linkplain #newHasher()} are delegated to the {@linkplain
* #hashBytes(byte[], int, int)} method.
*
* @author Dimitris Andreou
*/
abstract class AbstractNonStreamingHashFunction implements HashFunction {
@Override
public Hasher newHasher() {
return new BufferingHasher(32);
}
@Override
public Hasher newHasher(int expectedInputSize) {
Preconditions.checkArgument(expectedInputSize >= 0);
return new BufferingHasher(expectedInputSize);
}
@Override public HashCode hashString(CharSequence input) {
int len = input.length();
Hasher hasher = newHasher(len * 2);
for (int i = 0; i < len; i++) {
hasher.putChar(input.charAt(i));
}
return hasher.hash();
}
@Override public HashCode hashString(CharSequence input, Charset charset) {
return hashBytes(input.toString().getBytes(charset));
}
@Override public HashCode hashInt(int input) {
return newHasher(4).putInt(input).hash();
}
@Override public HashCode hashLong(long input) {
return newHasher(8).putLong(input).hash();
}
@Override public HashCode hashBytes(byte[] input) {
return hashBytes(input, 0, input.length);
}
/**
* In-memory stream-based implementation of Hasher.
*/
private final class BufferingHasher extends AbstractHasher {
final ExposedByteArrayOutputStream stream;
static final int BOTTOM_BYTE = 0xFF;
BufferingHasher(int expectedInputSize) {
this.stream = new ExposedByteArrayOutputStream(expectedInputSize);
}
@Override
public Hasher putByte(byte b) {
stream.write(b);
return this;
}
@Override
public Hasher putBytes(byte[] bytes) {
try {
stream.write(bytes);
} catch (IOException e) {
throw Throwables.propagate(e);
}
return this;
}
@Override
public Hasher putBytes(byte[] bytes, int off, int len) {
stream.write(bytes, off, len);
return this;
}
@Override
public Hasher putShort(short s) {
stream.write(s & BOTTOM_BYTE);
stream.write((s >>> 8) & BOTTOM_BYTE);
return this;
}
@Override
public Hasher putInt(int i) {
stream.write(i & BOTTOM_BYTE);
stream.write((i >>> 8) & BOTTOM_BYTE);
stream.write((i >>> 16) & BOTTOM_BYTE);
stream.write((i >>> 24) & BOTTOM_BYTE);
return this;
}
@Override
public Hasher putLong(long l) {
for (int i = 0; i < 64; i += 8) {
stream.write((byte) ((l >>> i) & BOTTOM_BYTE));
}
return this;
}
@Override
public Hasher putChar(char c) {
stream.write(c & BOTTOM_BYTE);
stream.write((c >>> 8) & BOTTOM_BYTE);
return this;
}
@Override
public <T> Hasher putObject(T instance, Funnel<? super T> funnel) {
funnel.funnel(instance, this);
return this;
}
@Override
public HashCode hash() {
return hashBytes(stream.byteArray(), 0, stream.length());
}
}
// Just to access the byte[] without introducing an unnecessary copy
private static final class ExposedByteArrayOutputStream extends ByteArrayOutputStream {
ExposedByteArrayOutputStream(int expectedInputSize) {
super(expectedInputSize);
}
byte[] byteArray() {
return buf;
}
int length() {
return count;
}
}
}
| Java |
/*
* 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.hash;
import static com.google.common.base.Preconditions.checkPositionIndexes;
import static com.google.common.base.Preconditions.checkState;
import com.google.common.primitives.Chars;
import com.google.common.primitives.Ints;
import com.google.common.primitives.Longs;
import com.google.common.primitives.Shorts;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* {@link HashFunction} adapter for {@link MessageDigest}s.
*
* @author Kevin Bourrillion
* @author Dimitris Andreou
*/
final class MessageDigestHashFunction extends AbstractStreamingHashFunction {
private final String algorithmName;
private final int bits;
MessageDigestHashFunction(String algorithmName) {
this.algorithmName = algorithmName;
this.bits = getMessageDigest(algorithmName).getDigestLength() * 8;
}
@Override public int bits() {
return bits;
}
private static MessageDigest getMessageDigest(String algorithmName) {
try {
return MessageDigest.getInstance(algorithmName);
} catch (NoSuchAlgorithmException e) {
throw new AssertionError(e);
}
}
@Override public Hasher newHasher() {
return new MessageDigestHasher(getMessageDigest(algorithmName));
}
private static class MessageDigestHasher implements Hasher {
private final MessageDigest digest;
private final ByteBuffer scratch; // lazy convenience
private boolean done;
private MessageDigestHasher(MessageDigest digest) {
this.digest = digest;
this.scratch = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
}
@Override public Hasher putByte(byte b) {
checkNotDone();
digest.update(b);
return this;
}
@Override public Hasher putBytes(byte[] bytes) {
checkNotDone();
digest.update(bytes);
return this;
}
@Override public Hasher putBytes(byte[] bytes, int off, int len) {
checkNotDone();
checkPositionIndexes(off, off + len, bytes.length);
digest.update(bytes, off, len);
return this;
}
@Override public Hasher putShort(short s) {
checkNotDone();
scratch.putShort(s);
digest.update(scratch.array(), 0, Shorts.BYTES);
scratch.clear();
return this;
}
@Override public Hasher putInt(int i) {
checkNotDone();
scratch.putInt(i);
digest.update(scratch.array(), 0, Ints.BYTES);
scratch.clear();
return this;
}
@Override public Hasher putLong(long l) {
checkNotDone();
scratch.putLong(l);
digest.update(scratch.array(), 0, Longs.BYTES);
scratch.clear();
return this;
}
@Override public Hasher putFloat(float f) {
checkNotDone();
scratch.putFloat(f);
digest.update(scratch.array(), 0, 4);
scratch.clear();
return this;
}
@Override public Hasher putDouble(double d) {
checkNotDone();
scratch.putDouble(d);
digest.update(scratch.array(), 0, 8);
scratch.clear();
return this;
}
@Override public Hasher putBoolean(boolean b) {
return putByte(b ? (byte) 1 : (byte) 0);
}
@Override public Hasher putChar(char c) {
checkNotDone();
scratch.putChar(c);
digest.update(scratch.array(), 0, Chars.BYTES);
scratch.clear();
return this;
}
@Override public Hasher putString(CharSequence charSequence) {
for (int i = 0; i < charSequence.length(); i++) {
putChar(charSequence.charAt(i));
}
return this;
}
@Override public Hasher putString(CharSequence charSequence, Charset charset) {
return putBytes(charSequence.toString().getBytes(charset));
}
@Override public <T> Hasher putObject(T instance, Funnel<? super T> funnel) {
checkNotDone();
funnel.funnel(instance, this);
return this;
}
private void checkNotDone() {
checkState(!done, "Cannot use Hasher after calling #hash() on it");
}
public HashCode hash() {
done = true;
return HashCodes.fromBytesNoCopy(digest.digest());
}
}
}
| Java |
/*
* 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.hash;
import java.nio.charset.Charset;
/**
* An abstract composition of multiple hash functions. {@linkplain #newHasher()} delegates to the
* {@code Hasher} objects of the delegate hash functions, and in the end, they are used by
* {@linkplain #makeHash(Hasher[])} that constructs the final {@code HashCode}.
*
* @author Dimitris Andreou
*/
abstract class AbstractCompositeHashFunction extends AbstractStreamingHashFunction {
final HashFunction[] functions;
AbstractCompositeHashFunction(HashFunction... functions) {
this.functions = functions;
}
/**
* Constructs a {@code HashCode} from the {@code Hasher} objects of the functions. Each of them
* has consumed the entire input and they are ready to output a {@code HashCode}. The order of
* the hashers are the same order as the functions given to the constructor.
*/
// this could be cleaner if it passed HashCode[], but that would create yet another array...
/* protected */ abstract HashCode makeHash(Hasher[] hashers);
@Override
public Hasher newHasher() {
final Hasher[] hashers = new Hasher[functions.length];
for (int i = 0; i < hashers.length; i++) {
hashers[i] = functions[i].newHasher();
}
return new Hasher() {
@Override public Hasher putByte(byte b) {
for (Hasher hasher : hashers) {
hasher.putByte(b);
}
return this;
}
@Override public Hasher putBytes(byte[] bytes) {
for (Hasher hasher : hashers) {
hasher.putBytes(bytes);
}
return this;
}
@Override public Hasher putBytes(byte[] bytes, int off, int len) {
for (Hasher hasher : hashers) {
hasher.putBytes(bytes, off, len);
}
return this;
}
@Override public Hasher putShort(short s) {
for (Hasher hasher : hashers) {
hasher.putShort(s);
}
return this;
}
@Override public Hasher putInt(int i) {
for (Hasher hasher : hashers) {
hasher.putInt(i);
}
return this;
}
@Override public Hasher putLong(long l) {
for (Hasher hasher : hashers) {
hasher.putLong(l);
}
return this;
}
@Override public Hasher putFloat(float f) {
for (Hasher hasher : hashers) {
hasher.putFloat(f);
}
return this;
}
@Override public Hasher putDouble(double d) {
for (Hasher hasher : hashers) {
hasher.putDouble(d);
}
return this;
}
@Override public Hasher putBoolean(boolean b) {
for (Hasher hasher : hashers) {
hasher.putBoolean(b);
}
return this;
}
@Override public Hasher putChar(char c) {
for (Hasher hasher : hashers) {
hasher.putChar(c);
}
return this;
}
@Override public Hasher putString(CharSequence chars) {
for (Hasher hasher : hashers) {
hasher.putString(chars);
}
return this;
}
@Override public Hasher putString(CharSequence chars, Charset charset) {
for (Hasher hasher : hashers) {
hasher.putString(chars, charset);
}
return this;
}
@Override public <T> Hasher putObject(T instance, Funnel<? super T> funnel) {
for (Hasher hasher : hashers) {
hasher.putObject(instance, funnel);
}
return this;
}
@Override public HashCode hash() {
return makeHash(hashers);
}
};
}
private static final long serialVersionUID = 0L;
}
| Java |
/*
* 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.hash;
import com.google.common.annotations.Beta;
import com.google.common.primitives.Ints;
import java.nio.charset.Charset;
/**
* A hash function is a collision-averse pure function that maps an arbitrary block of
* data to a number called a <i>hash code</i>.
*
* <h3>Definition</h3>
*
* <p>Unpacking this definition:
*
* <ul>
* <li><b>block of data:</b> the input for a hash function is always, in concept, an
* ordered byte array. This hashing API accepts an arbitrary sequence of byte and
* multibyte values (via {@link Hasher}), but this is merely a convenience; these are
* always translated into raw byte sequences under the covers.
*
* <li><b>hash code:</b> each hash function always yields hash codes of the same fixed bit
* length (given by {@link #bits}). For example, {@link Hashing#sha1} produces a
* 160-bit number, while {@link Hashing#murmur3_32()} yields only 32 bits. Because a
* {@code long} value is clearly insufficient to hold all hash code values, this API
* represents a hash code as an instance of {@link HashCode}.
*
* <li><b>pure function:</b> the value produced must depend only on the input bytes, in
* the order they appear. Input data is never modified. {@link HashFunction} instances
* should always be stateless, and therefore thread-safe.
*
* <li><b>collision-averse:</b> while it can't be helped that a hash function will
* sometimes produce the same hash code for distinct inputs (a "collision"), every
* hash function strives to <i>some</i> degree to make this unlikely. (Without this
* condition, a function that always returns zero could be called a hash function. It
* is not.)
* </ul>
*
* <p>Summarizing the last two points: "equal yield equal <i>always</i>; unequal yield
* unequal <i>often</i>." This is the most important characteristic of all hash functions.
*
* <h3>Desirable properties</h3>
*
* <p>A high-quality hash function strives for some subset of the following virtues:
*
* <ul>
* <li><b>collision-resistant:</b> while the definition above requires making at least
* <i>some</i> token attempt, one measure of the quality of a hash function is <i>how
* well</i> it succeeds at this goal. Important note: it may be easy to achieve the
* theoretical minimum collision rate when using completely <i>random</i> sample
* input. The true test of a hash function is how it performs on representative
* real-world data, which tends to contain many hidden patterns and clumps. The goal
* of a good hash function is to stamp these patterns out as thoroughly as possible.
*
* <li><b>bit-dispersing:</b> masking out any <i>single bit</i> from a hash code should
* yield only the expected <i>twofold</i> increase to all collision rates. Informally,
* the "information" in the hash code should be as evenly "spread out" through the
* hash code's bits as possible. The result is that, for example, when choosing a
* bucket in a hash table of size 2^8, <i>any</i> eight bits could be consistently
* used.
*
* <li><b>cryptographic:</b> certain hash functions such as {@link Hashing#sha512} are
* designed to make it as infeasible as possible to reverse-engineer the input that
* produced a given hash code, or even to discover <i>any</i> two distinct inputs that
* yield the same result. These are called <i>cryptographic hash functions</i>. But,
* whenever it is learned that either of these feats has become computationally
* feasible, the function is deemed "broken" and should no longer be used for secure
* purposes. (This is the likely eventual fate of <i>all</i> cryptographic hashes.)
*
* <li><b>fast:</b> perhaps self-explanatory, but often the most important consideration.
* We have published <a href="#noWeHaventYet">microbenchmark results</a> for many
* common hash functions.
* </ul>
*
* <h3>Providing input to a hash function</h3>
*
* <p>The primary way to provide the data that your hash function should act on is via a
* {@link Hasher}. Obtain a new hasher from the hash function using {@link #newHasher},
* "push" the relevant data into it using methods like {@link Hasher#putBytes(byte[])},
* and finally ask for the {@code HashCode} when finished using {@link Hasher#hash}. (See
* an {@linkplain #newHasher example} of this.)
*
* <p>If all you want to hash is a single byte array, string or {@code long} value, there
* are convenient shortcut methods defined directly on {@link HashFunction} to make this
* easier.
*
* <p>Hasher accepts primitive data types, but can also accept any Object of type {@code
* T} provided that you implement a {@link Funnel Funnel<T>} to specify how to "feed" data
* from that object into the function. (See {@linkplain Hasher#putObject an example} of
* this.)
*
* <p><b>Compatibility note:</b> Throughout this API, multibyte values are always
* interpreted in <i>little-endian</i> order. That is, hashing the byte array {@code
* {0x01, 0x02, 0x03, 0x04}} is equivalent to hashing the {@code int} value {@code
* 0x04030201}. If this isn't what you need, methods such as {@link Integer#reverseBytes}
* and {@link Ints#toByteArray} will help.
*
* <h3>Relationship to {@link Object#hashCode}</h3>
*
* <p>Java's baked-in concept of hash codes is constrained to 32 bits, and provides no
* separation between hash algorithms and the data they act on, so alternate hash
* algorithms can't be easily substituted. Also, implementations of {@code hashCode} tend
* to be poor-quality, in part because they end up depending on <i>other</i> existing
* poor-quality {@code hashCode} implementations, including those in many JDK classes.
*
* <p>{@code Object.hashCode} implementations tend to be very fast, but have weak
* collision prevention and <i>no</i> expectation of bit dispersion. This leaves them
* perfectly suitable for use in hash tables, because extra collisions cause only a slight
* performance hit, while poor bit dispersion is easily corrected using a secondary hash
* function (which all reasonable hash table implementations in Java use). For the many
* uses of hash functions beyond data structures, however, {@code Object.hashCode} almost
* always falls short -- hence this library.
*
* @author Kevin Bourrillion
* @since 11.0
*/
@Beta
public interface HashFunction {
/**
* Begins a new hash code computation by returning an initialized, stateful {@code
* Hasher} instance that is ready to receive data. Example: <pre> {@code
*
* HashFunction hf = Hashing.md5();
* HashCode hc = hf.newHasher()
* .putLong(id)
* .putString(name)
* .hash();}</pre>
*/
Hasher newHasher();
/**
* Begins a new hash code computation as {@link #newHasher()}, but provides a hint of the
* expected size of the input (in bytes). This is only important for non-streaming hash
* functions (hash functions that need to buffer their whole input before processing any
* of it).
*/
Hasher newHasher(int expectedInputSize);
/**
* Shortcut for {@code newHasher().putInt(input).hash()}; returns the hash code for the given
* {@code int} value, interpreted in little-endian byte order. The implementation <i>might</i>
* perform better than its longhand equivalent, but should not perform worse.
*
* @since 12.0
*/
HashCode hashInt(int input);
/**
* Shortcut for {@code newHasher().putLong(input).hash()}; returns the hash code for the
* given {@code long} value, interpreted in little-endian byte order. The implementation
* <i>might</i> perform better than its longhand equivalent, but should not perform worse.
*/
HashCode hashLong(long input);
/**
* Shortcut for {@code newHasher().putBytes(input).hash()}. The implementation
* <i>might</i> perform better than its longhand equivalent, but should not perform
* worse.
*/
HashCode hashBytes(byte[] input);
/**
* Shortcut for {@code newHasher().putBytes(input, off, len).hash()}. The implementation
* <i>might</i> perform better than its longhand equivalent, but should not perform
* worse.
*
* @throws IndexOutOfBoundsException if {@code off < 0} or {@code off + len > bytes.length}
* or {@code len < 0}
*/
HashCode hashBytes(byte[] input, int off, int len);
/**
* Shortcut for {@code newHasher().putString(input).hash()}. The implementation <i>might</i>
* perform better than its longhand equivalent, but should not perform worse. Note that no
* character encoding is performed; the low byte and high byte of each character are hashed
* directly (in that order). This is equivalent to using
* {@code hashString(input, Charsets.UTF_16LE)}.
*/
HashCode hashString(CharSequence input);
/**
* Shortcut for {@code newHasher().putString(input, charset).hash()}. Characters are encoded
* using the given {@link Charset}. The implementation <i>might</i> perform better than its
* longhand equivalent, but should not perform worse.
*/
HashCode hashString(CharSequence input, Charset charset);
/**
* Returns the number of bits (a multiple of 32) that each hash code produced by this
* hash function has.
*/
int bits();
}
| Java |
/*
* 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.hash;
import com.google.common.annotations.Beta;
import java.io.Serializable;
/**
* An object which can send data from an object of type {@code T} into a {@code PrimitiveSink}.
*
* <p>Note that serialization of {@linkplain BloomFilter bloom filters} requires the proper
* serialization of funnels. When possible, it is recommended that funnels be implemented as a
* single-element enum to maintain serialization guarantees. See Effective Java (2nd Edition),
* Item 3: "Enforce the singleton property with a private constructor or an enum type". For example:
* <pre> {@code
* public enum PersonFunnel implements Funnel<Person> {
* INSTANCE;
* public void funnel(Person person, PrimitiveSink into) {
* into.putString(person.getFirstName())
* .putString(person.getLastName())
* .putInt(person.getAge());
* }
* }}</pre>
*
* @author Dimitris Andreou
* @since 11.0
*/
@Beta
public interface Funnel<T> extends Serializable {
/**
* Sends a stream of data from the {@code from} object into the sink {@code into}. There
* is no requirement that this data be complete enough to fully reconstitute the object
* later.
*
* @since 12.0 (in Guava 11.0, {@code PrimitiveSink} was named {@code Sink})
*/
void funnel(T from, PrimitiveSink into);
}
| Java |
/*
* 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.hash;
import java.nio.charset.Charset;
/**
* An abstract hasher, implementing {@link #putBoolean(boolean)}, {@link #putDouble(double)},
* {@link #putFloat(float)}, {@link #putString(CharSequence)}, and
* {@link #putString(CharSequence, Charset)} as prescribed by {@link Hasher}.
*
* @author Dimitris Andreou
*/
abstract class AbstractHasher implements Hasher {
@Override public final Hasher putBoolean(boolean b) {
return putByte(b ? (byte) 1 : (byte) 0);
}
@Override public final Hasher putDouble(double d) {
return putLong(Double.doubleToRawLongBits(d));
}
@Override public final Hasher putFloat(float f) {
return putInt(Float.floatToRawIntBits(f));
}
@Override public Hasher putString(CharSequence charSequence) {
for (int i = 0, len = charSequence.length(); i < len; i++) {
putChar(charSequence.charAt(i));
}
return this;
}
@Override public Hasher putString(CharSequence charSequence, Charset charset) {
return putBytes(charSequence.toString().getBytes(charset));
}
}
| Java |
/*
* 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.hash;
import com.google.common.annotations.Beta;
import com.google.common.base.Preconditions;
import com.google.common.primitives.Ints;
import java.security.MessageDigest;
/**
* An immutable hash code of arbitrary bit length.
*
* @author Dimitris Andreou
* @since 11.0
*/
@Beta
public abstract class HashCode {
HashCode() {}
/**
* Returns the first four bytes of {@linkplain #asBytes() this hashcode's bytes}, converted to
* an {@code int} value in little-endian order.
*/
public abstract int asInt();
/**
* Returns the first eight bytes of {@linkplain #asBytes() this hashcode's bytes}, converted to
* a {@code long} value in little-endian order.
*
* @throws IllegalStateException if {@code bits() < 64}
*/
public abstract long asLong();
/**
* Returns the value of this hash code as a byte array. The caller may modify the byte array;
* changes to it will <i>not</i> be reflected in this {@code HashCode} object or any other arrays
* returned by this method.
*/
// TODO(user): consider ByteString here, when that is available
public abstract byte[] asBytes();
/**
* Copies bytes from this hash code into {@code dest}.
*
* @param dest the byte array into which the hash code will be written
* @param offset the start offset in the data
* @param maxLength the maximum number of bytes to write
* @return the number of bytes written to {@code dest}
* @throws IndexOutOfBoundsException if there is not enough room in {@code dest}
*/
public int writeBytesTo(byte[] dest, int offset, int maxLength) {
byte[] hash = asBytes();
maxLength = Ints.min(maxLength, hash.length);
Preconditions.checkPositionIndexes(offset, offset + maxLength, dest.length);
System.arraycopy(hash, 0, dest, offset, maxLength);
return maxLength;
}
/**
* Returns the number of bits in this hash code; a positive multiple of 32.
*/
public abstract int bits();
@Override public boolean equals(Object object) {
if (object instanceof HashCode) {
HashCode that = (HashCode) object;
// Undocumented: this is a non-short-circuiting equals(), in case this is a cryptographic
// hash code, in which case we don't want to leak timing information
return MessageDigest.isEqual(this.asBytes(), that.asBytes());
}
return false;
}
/**
* Returns a "Java hash code" for this {@code HashCode} instance; this is well-defined
* (so, for example, you can safely put {@code HashCode} instances into a {@code
* HashSet}) but is otherwise probably not what you want to use.
*/
@Override public int hashCode() {
/*
* As long as the hash function that produced this isn't of horrible quality, this
* won't be of horrible quality either.
*/
return asInt();
}
/**
* Returns a string containing each byte of {@link #asBytes}, in order, as a two-digit unsigned
* hexadecimal number in lower case.
*
* <p>Note that if the output is considered to be a single hexadecimal number, this hash code's
* bytes are the <i>big-endian</i> representation of that number. This may be surprising since
* everything else in the hashing API uniformly treats multibyte values as little-endian. But
* this format conveniently matches that of utilities such as the UNIX {@code md5sum} command.
*/
@Override public String toString() {
byte[] bytes = asBytes();
// TODO(user): Use c.g.common.base.ByteArrays once it is open sourced.
StringBuilder sb = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {
sb.append(hexDigits[(b >> 4) & 0xf]).append(hexDigits[b & 0xf]);
}
return sb.toString();
}
private static final char[] hexDigits = "0123456789abcdef".toCharArray();
}
| Java |
/*
* 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.io;
import com.google.common.collect.Sets;
import java.io.IOException;
import java.util.Set;
/**
* The purpose of the CheckCloseSupplier is to report when all closeable objects
* supplied by the delegate supplier are closed. To do this, the factory method
* returns a decorated version of the {@code delegate} supplied in the
* constructor. The decoration mechanism is left up to the subclass via the
* abstract {@link #wrap} method.
*
* <p>The decorated object returned from {@link #wrap} should ideally override
* its {@code close} method to not only call {@code super.close()} but to also
* call {@code callback.delegateClosed()}.
*
* @author Chris Nokleberg
*/
abstract class CheckCloseSupplier<T> {
private final Set<Callback> open = Sets.newHashSet();
abstract static class Input<T> extends CheckCloseSupplier<T>
implements InputSupplier<T> {
private final InputSupplier<? extends T> delegate;
public Input(InputSupplier<? extends T> delegate) {
this.delegate = delegate;
}
@Override public T getInput() throws IOException {
return wrap(delegate.getInput(), newCallback());
}
}
abstract static class Output<T> extends CheckCloseSupplier<T>
implements OutputSupplier<T> {
private final OutputSupplier<? extends T> delegate;
public Output(OutputSupplier<? extends T> delegate) {
this.delegate = delegate;
}
@Override public T getOutput() throws IOException {
return wrap(delegate.getOutput(), newCallback());
}
}
public final class Callback {
public void delegateClosed() {
open.remove(this);
}
}
protected Callback newCallback() {
Callback callback = new Callback();
open.add(callback);
return callback;
}
/**
* Subclasses should wrap the given object and call
* {@link Callback#delegateClosed} when the close method of the delegate is
* called, to inform the supplier that the underlying
* {@code Closeable} is not longer open.
*
* @param object the object to wrap.
* @param callback the object that the wrapper should call to signal that the
*/
protected abstract T wrap(T object, Callback callback);
/** Returns true if all the closeables have been closed closed */
public boolean areClosed() {
return open.isEmpty();
}
}
| Java |
/*
* 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.io;
import junit.framework.TestCase;
/**
* Base test case class for I/O tests.
*
* @author Chris Nokleberg
*/
public abstract class IoTestCase extends TestCase {
static final String I18N
= "\u00CE\u00F1\u0163\u00E9\u0072\u00F1\u00E5\u0163\u00EE\u00F6"
+ "\u00F1\u00E5\u013C\u00EE\u017E\u00E5\u0163\u00EE\u00F6\u00F1";
static final String ASCII
= " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"
+ "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
/** Returns a byte array of length size that has values 0 .. size - 1. */
protected static byte[] newPreFilledByteArray(int size) {
return newPreFilledByteArray(0, size);
}
/**
* Returns a byte array of length size that has values
* offset .. offset + size - 1.
*/
protected static byte[] newPreFilledByteArray(int offset, int size) {
byte[] array = new byte[size];
for (int i = 0; i < size; i++) {
array[i] = (byte) (offset + i);
}
return array;
}
}
| Java |
/*
* 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.io;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Random;
/** Returns a random portion of the requested bytes on each call. */
class RandomAmountInputStream extends FilterInputStream {
private final Random random;
public RandomAmountInputStream(InputStream in, Random random) {
super(in);
this.random = random;
}
@Override public int read(byte[] b, int off, int len) throws IOException {
return super.read(b, off, random.nextInt(len) + 1);
}
}
| Java |
/*
* 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.
*/
/*
* Source:
* http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/test/tck/JSR166TestCase.java?revision=1.90
* (We have made some trivial local modifications (commented out
* uncompilable code).)
*/
package com.google.common.util.concurrent;
import static java.util.concurrent.TimeUnit.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import junit.framework.*;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.Policy;
import java.security.ProtectionDomain;
import java.security.SecurityPermission;
import java.util.Arrays;
import java.util.Date;
import java.util.NoSuchElementException;
import java.util.PropertyPermission;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
/**
* Base class for JSR166 Junit TCK tests. Defines some constants,
* utility methods and classes, as well as a simple framework for
* helping to make sure that assertions failing in generated threads
* cause the associated test that generated them to itself fail (which
* JUnit does not otherwise arrange). The rules for creating such
* tests are:
*
* <ol>
*
* <li> All assertions in code running in generated threads must use
* the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link
* #threadAssertEquals}, or {@link #threadAssertNull}, (not
* {@code fail}, {@code assertTrue}, etc.) It is OK (but not
* particularly recommended) for other code to use these forms too.
* Only the most typically used JUnit assertion methods are defined
* this way, but enough to live with.</li>
*
* <li> If you override {@link #setUp} or {@link #tearDown}, make sure
* to invoke {@code super.setUp} and {@code super.tearDown} within
* them. These methods are used to clear and check for thread
* assertion failures.</li>
*
* <li>All delays and timeouts must use one of the constants {@code
* SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS},
* {@code LONG_DELAY_MS}. The idea here is that a SHORT is always
* discriminable from zero time, and always allows enough time for the
* small amounts of computation (creating a thread, calling a few
* methods, etc) needed to reach a timeout point. Similarly, a SMALL
* is always discriminable as larger than SHORT and smaller than
* MEDIUM. And so on. These constants are set to conservative values,
* but even so, if there is ever any doubt, they can all be increased
* in one spot to rerun tests on slower platforms.</li>
*
* <li> All threads generated must be joined inside each test case
* method (or {@code fail} to do so) before returning from the
* method. The {@code joinPool} method can be used to do this when
* using Executors.</li>
*
* </ol>
*
* <p> <b>Other notes</b>
* <ul>
*
* <li> Usually, there is one testcase method per JSR166 method
* covering "normal" operation, and then as many exception-testing
* methods as there are exceptions the method can throw. Sometimes
* there are multiple tests per JSR166 method when the different
* "normal" behaviors differ significantly. And sometimes testcases
* cover multiple methods when they cannot be tested in
* isolation.</li>
*
* <li> The documentation style for testcases is to provide as javadoc
* a simple sentence or two describing the property that the testcase
* method purports to test. The javadocs do not say anything about how
* the property is tested. To find out, read the code.</li>
*
* <li> These tests are "conformance tests", and do not attempt to
* test throughput, latency, scalability or other performance factors
* (see the separate "jtreg" tests for a set intended to check these
* for the most central aspects of functionality.) So, most tests use
* the smallest sensible numbers of threads, collection sizes, etc
* needed to check basic conformance.</li>
*
* <li>The test classes currently do not declare inclusion in
* any particular package to simplify things for people integrating
* them in TCK test suites.</li>
*
* <li> As a convenience, the {@code main} of this class (JSR166TestCase)
* runs all JSR166 unit tests.</li>
*
* </ul>
*/
abstract class JSR166TestCase extends TestCase {
private static final boolean useSecurityManager =
Boolean.getBoolean("jsr166.useSecurityManager");
protected static final boolean expensiveTests =
Boolean.getBoolean("jsr166.expensiveTests");
/**
* If true, report on stdout all "slow" tests, that is, ones that
* take more than profileThreshold milliseconds to execute.
*/
private static final boolean profileTests =
Boolean.getBoolean("jsr166.profileTests");
/**
* The number of milliseconds that tests are permitted for
* execution without being reported, when profileTests is set.
*/
private static final long profileThreshold =
Long.getLong("jsr166.profileThreshold", 100);
protected void runTest() throws Throwable {
if (profileTests)
runTestProfiled();
else
super.runTest();
}
protected void runTestProfiled() throws Throwable {
long t0 = System.nanoTime();
try {
super.runTest();
} finally {
long elapsedMillis =
(System.nanoTime() - t0) / (1000L * 1000L);
if (elapsedMillis >= profileThreshold)
System.out.printf("%n%s: %d%n", toString(), elapsedMillis);
}
}
// /**
// * Runs all JSR166 unit tests using junit.textui.TestRunner
// */
// public static void main(String[] args) {
// if (useSecurityManager) {
// System.err.println("Setting a permissive security manager");
// Policy.setPolicy(permissivePolicy());
// System.setSecurityManager(new SecurityManager());
// }
// int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]);
// Test s = suite();
// for (int i = 0; i < iters; ++i) {
// junit.textui.TestRunner.run(s);
// System.gc();
// System.runFinalization();
// }
// System.exit(0);
// }
// public static TestSuite newTestSuite(Object... suiteOrClasses) {
// TestSuite suite = new TestSuite();
// for (Object suiteOrClass : suiteOrClasses) {
// if (suiteOrClass instanceof TestSuite)
// suite.addTest((TestSuite) suiteOrClass);
// else if (suiteOrClass instanceof Class)
// suite.addTest(new TestSuite((Class<?>) suiteOrClass));
// else
// throw new ClassCastException("not a test suite or class");
// }
// return suite;
// }
// /**
// * Collects all JSR166 unit tests as one suite.
// */
// public static Test suite() {
// return newTestSuite(
// ForkJoinPoolTest.suite(),
// ForkJoinTaskTest.suite(),
// RecursiveActionTest.suite(),
// RecursiveTaskTest.suite(),
// LinkedTransferQueueTest.suite(),
// PhaserTest.suite(),
// ThreadLocalRandomTest.suite(),
// AbstractExecutorServiceTest.suite(),
// AbstractQueueTest.suite(),
// AbstractQueuedSynchronizerTest.suite(),
// AbstractQueuedLongSynchronizerTest.suite(),
// ArrayBlockingQueueTest.suite(),
// ArrayDequeTest.suite(),
// AtomicBooleanTest.suite(),
// AtomicIntegerArrayTest.suite(),
// AtomicIntegerFieldUpdaterTest.suite(),
// AtomicIntegerTest.suite(),
// AtomicLongArrayTest.suite(),
// AtomicLongFieldUpdaterTest.suite(),
// AtomicLongTest.suite(),
// AtomicMarkableReferenceTest.suite(),
// AtomicReferenceArrayTest.suite(),
// AtomicReferenceFieldUpdaterTest.suite(),
// AtomicReferenceTest.suite(),
// AtomicStampedReferenceTest.suite(),
// ConcurrentHashMapTest.suite(),
// ConcurrentLinkedDequeTest.suite(),
// ConcurrentLinkedQueueTest.suite(),
// ConcurrentSkipListMapTest.suite(),
// ConcurrentSkipListSubMapTest.suite(),
// ConcurrentSkipListSetTest.suite(),
// ConcurrentSkipListSubSetTest.suite(),
// CopyOnWriteArrayListTest.suite(),
// CopyOnWriteArraySetTest.suite(),
// CountDownLatchTest.suite(),
// CyclicBarrierTest.suite(),
// DelayQueueTest.suite(),
// EntryTest.suite(),
// ExchangerTest.suite(),
// ExecutorsTest.suite(),
// ExecutorCompletionServiceTest.suite(),
// FutureTaskTest.suite(),
// LinkedBlockingDequeTest.suite(),
// LinkedBlockingQueueTest.suite(),
// LinkedListTest.suite(),
// LockSupportTest.suite(),
// PriorityBlockingQueueTest.suite(),
// PriorityQueueTest.suite(),
// ReentrantLockTest.suite(),
// ReentrantReadWriteLockTest.suite(),
// ScheduledExecutorTest.suite(),
// ScheduledExecutorSubclassTest.suite(),
// SemaphoreTest.suite(),
// SynchronousQueueTest.suite(),
// SystemTest.suite(),
// ThreadLocalTest.suite(),
// ThreadPoolExecutorTest.suite(),
// ThreadPoolExecutorSubclassTest.suite(),
// ThreadTest.suite(),
// TimeUnitTest.suite(),
// TreeMapTest.suite(),
// TreeSetTest.suite(),
// TreeSubMapTest.suite(),
// TreeSubSetTest.suite());
// }
public static long SHORT_DELAY_MS;
public static long SMALL_DELAY_MS;
public static long MEDIUM_DELAY_MS;
public static long LONG_DELAY_MS;
/**
* Returns the shortest timed delay. This could
* be reimplemented to use for example a Property.
*/
protected long getShortDelay() {
return 50;
}
/**
* Sets delays as multiples of SHORT_DELAY.
*/
protected void setDelays() {
SHORT_DELAY_MS = getShortDelay();
SMALL_DELAY_MS = SHORT_DELAY_MS * 5;
MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10;
LONG_DELAY_MS = SHORT_DELAY_MS * 200;
}
/**
* Returns a timeout in milliseconds to be used in tests that
* verify that operations block or time out.
*/
long timeoutMillis() {
return SHORT_DELAY_MS / 4;
}
/**
* Returns a new Date instance representing a time delayMillis
* milliseconds in the future.
*/
Date delayedDate(long delayMillis) {
return new Date(System.currentTimeMillis() + delayMillis);
}
/**
* The first exception encountered if any threadAssertXXX method fails.
*/
private final AtomicReference<Throwable> threadFailure
= new AtomicReference<Throwable>(null);
/**
* Records an exception so that it can be rethrown later in the test
* harness thread, triggering a test case failure. Only the first
* failure is recorded; subsequent calls to this method from within
* the same test have no effect.
*/
public void threadRecordFailure(Throwable t) {
threadFailure.compareAndSet(null, t);
}
public void setUp() {
setDelays();
}
/**
* Extra checks that get done for all test cases.
*
* Triggers test case failure if any thread assertions have failed,
* by rethrowing, in the test harness thread, any exception recorded
* earlier by threadRecordFailure.
*
* Triggers test case failure if interrupt status is set in the main thread.
*/
public void tearDown() throws Exception {
Throwable t = threadFailure.getAndSet(null);
if (t != null) {
if (t instanceof Error)
throw (Error) t;
else if (t instanceof RuntimeException)
throw (RuntimeException) t;
else if (t instanceof Exception)
throw (Exception) t;
else {
AssertionFailedError afe =
new AssertionFailedError(t.toString());
afe.initCause(t);
throw afe;
}
}
if (Thread.interrupted())
throw new AssertionFailedError("interrupt status set in main thread");
}
/**
* Just like fail(reason), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadFail(String reason) {
try {
fail(reason);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
fail(reason);
}
}
/**
* Just like assertTrue(b), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadAssertTrue(boolean b) {
try {
assertTrue(b);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
throw t;
}
}
/**
* Just like assertFalse(b), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadAssertFalse(boolean b) {
try {
assertFalse(b);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
throw t;
}
}
/**
* Just like assertNull(x), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadAssertNull(Object x) {
try {
assertNull(x);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
throw t;
}
}
/**
* Just like assertEquals(x, y), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadAssertEquals(long x, long y) {
try {
assertEquals(x, y);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
throw t;
}
}
/**
* Just like assertEquals(x, y), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadAssertEquals(Object x, Object y) {
try {
assertEquals(x, y);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
throw t;
} catch (Throwable t) {
threadUnexpectedException(t);
}
}
/**
* Just like assertSame(x, y), but additionally recording (using
* threadRecordFailure) any AssertionFailedError thrown, so that
* the current testcase will fail.
*/
public void threadAssertSame(Object x, Object y) {
try {
assertSame(x, y);
} catch (AssertionFailedError t) {
threadRecordFailure(t);
throw t;
}
}
/**
* Calls threadFail with message "should throw exception".
*/
public void threadShouldThrow() {
threadFail("should throw exception");
}
/**
* Calls threadFail with message "should throw" + exceptionName.
*/
public void threadShouldThrow(String exceptionName) {
threadFail("should throw " + exceptionName);
}
/**
* Records the given exception using {@link #threadRecordFailure},
* then rethrows the exception, wrapping it in an
* AssertionFailedError if necessary.
*/
public void threadUnexpectedException(Throwable t) {
threadRecordFailure(t);
t.printStackTrace();
if (t instanceof RuntimeException)
throw (RuntimeException) t;
else if (t instanceof Error)
throw (Error) t;
else {
AssertionFailedError afe =
new AssertionFailedError("unexpected exception: " + t);
afe.initCause(t);
throw afe;
}
}
/**
* Delays, via Thread.sleep, for the given millisecond delay, but
* if the sleep is shorter than specified, may re-sleep or yield
* until time elapses.
*/
static void delay(long millis) throws InterruptedException {
long startTime = System.nanoTime();
long ns = millis * 1000 * 1000;
for (;;) {
if (millis > 0L)
Thread.sleep(millis);
else // too short to sleep
Thread.yield();
long d = ns - (System.nanoTime() - startTime);
if (d > 0L)
millis = d / (1000 * 1000);
else
break;
}
}
/**
* Waits out termination of a thread pool or fails doing so.
*/
void joinPool(ExecutorService exec) {
try {
exec.shutdown();
assertTrue("ExecutorService did not terminate in a timely manner",
exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS));
} catch (SecurityException ok) {
// Allowed in case test doesn't have privs
} catch (InterruptedException ie) {
fail("Unexpected InterruptedException");
}
}
/**
* Checks that thread does not terminate within the default
* millisecond delay of {@code timeoutMillis()}.
*/
void assertThreadStaysAlive(Thread thread) {
assertThreadStaysAlive(thread, timeoutMillis());
}
/**
* Checks that thread does not terminate within the given millisecond delay.
*/
void assertThreadStaysAlive(Thread thread, long millis) {
try {
// No need to optimize the failing case via Thread.join.
delay(millis);
assertTrue(thread.isAlive());
} catch (InterruptedException ie) {
fail("Unexpected InterruptedException");
}
}
/**
* Checks that the threads do not terminate within the default
* millisecond delay of {@code timeoutMillis()}.
*/
void assertThreadsStayAlive(Thread... threads) {
assertThreadsStayAlive(timeoutMillis(), threads);
}
/**
* Checks that the threads do not terminate within the given millisecond delay.
*/
void assertThreadsStayAlive(long millis, Thread... threads) {
try {
// No need to optimize the failing case via Thread.join.
delay(millis);
for (Thread thread : threads)
assertTrue(thread.isAlive());
} catch (InterruptedException ie) {
fail("Unexpected InterruptedException");
}
}
/**
* Checks that future.get times out, with the default timeout of
* {@code timeoutMillis()}.
*/
void assertFutureTimesOut(Future future) {
assertFutureTimesOut(future, timeoutMillis());
}
/**
* Checks that future.get times out, with the given millisecond timeout.
*/
void assertFutureTimesOut(Future future, long timeoutMillis) {
long startTime = System.nanoTime();
try {
future.get(timeoutMillis, MILLISECONDS);
shouldThrow();
} catch (TimeoutException success) {
} catch (Exception e) {
threadUnexpectedException(e);
} finally { future.cancel(true); }
assertTrue(millisElapsedSince(startTime) >= timeoutMillis);
}
/**
* Fails with message "should throw exception".
*/
public void shouldThrow() {
fail("Should throw exception");
}
/**
* Fails with message "should throw " + exceptionName.
*/
public void shouldThrow(String exceptionName) {
fail("Should throw " + exceptionName);
}
/**
* The number of elements to place in collections, arrays, etc.
*/
public static final int SIZE = 20;
// Some convenient Integer constants
public static final Integer zero = new Integer(0);
public static final Integer one = new Integer(1);
public static final Integer two = new Integer(2);
public static final Integer three = new Integer(3);
public static final Integer four = new Integer(4);
public static final Integer five = new Integer(5);
public static final Integer six = new Integer(6);
public static final Integer seven = new Integer(7);
public static final Integer eight = new Integer(8);
public static final Integer nine = new Integer(9);
public static final Integer m1 = new Integer(-1);
public static final Integer m2 = new Integer(-2);
public static final Integer m3 = new Integer(-3);
public static final Integer m4 = new Integer(-4);
public static final Integer m5 = new Integer(-5);
public static final Integer m6 = new Integer(-6);
public static final Integer m10 = new Integer(-10);
/**
* Runs Runnable r with a security policy that permits precisely
* the specified permissions. If there is no current security
* manager, the runnable is run twice, both with and without a
* security manager. We require that any security manager permit
* getPolicy/setPolicy.
*/
public void runWithPermissions(Runnable r, Permission... permissions) {
SecurityManager sm = System.getSecurityManager();
if (sm == null) {
r.run();
Policy savedPolicy = Policy.getPolicy();
try {
Policy.setPolicy(permissivePolicy());
System.setSecurityManager(new SecurityManager());
runWithPermissions(r, permissions);
} finally {
System.setSecurityManager(null);
Policy.setPolicy(savedPolicy);
}
} else {
Policy savedPolicy = Policy.getPolicy();
AdjustablePolicy policy = new AdjustablePolicy(permissions);
Policy.setPolicy(policy);
try {
r.run();
} finally {
policy.addPermission(new SecurityPermission("setPolicy"));
Policy.setPolicy(savedPolicy);
}
}
}
/**
* Runs a runnable without any permissions.
*/
public void runWithoutPermissions(Runnable r) {
runWithPermissions(r);
}
/**
* A security policy where new permissions can be dynamically added
* or all cleared.
*/
public static class AdjustablePolicy extends java.security.Policy {
Permissions perms = new Permissions();
AdjustablePolicy(Permission... permissions) {
for (Permission permission : permissions)
perms.add(permission);
}
void addPermission(Permission perm) { perms.add(perm); }
void clearPermissions() { perms = new Permissions(); }
public PermissionCollection getPermissions(CodeSource cs) {
return perms;
}
public PermissionCollection getPermissions(ProtectionDomain pd) {
return perms;
}
public boolean implies(ProtectionDomain pd, Permission p) {
return perms.implies(p);
}
public void refresh() {}
}
/**
* Returns a policy containing all the permissions we ever need.
*/
public static Policy permissivePolicy() {
return new AdjustablePolicy
// Permissions j.u.c. needs directly
(new RuntimePermission("modifyThread"),
new RuntimePermission("getClassLoader"),
new RuntimePermission("setContextClassLoader"),
// Permissions needed to change permissions!
new SecurityPermission("getPolicy"),
new SecurityPermission("setPolicy"),
new RuntimePermission("setSecurityManager"),
// Permissions needed by the junit test harness
new RuntimePermission("accessDeclaredMembers"),
new PropertyPermission("*", "read"),
new java.io.FilePermission("<<ALL FILES>>", "read"));
}
/**
* Sleeps until the given time has elapsed.
* Throws AssertionFailedError if interrupted.
*/
void sleep(long millis) {
try {
delay(millis);
} catch (InterruptedException ie) {
AssertionFailedError afe =
new AssertionFailedError("Unexpected InterruptedException");
afe.initCause(ie);
throw afe;
}
}
/**
* Spin-waits up to the specified number of milliseconds for the given
* thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING.
*/
void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) {
long startTime = System.nanoTime();
for (;;) {
Thread.State s = thread.getState();
if (s == Thread.State.BLOCKED ||
s == Thread.State.WAITING ||
s == Thread.State.TIMED_WAITING)
return;
else if (s == Thread.State.TERMINATED)
fail("Unexpected thread termination");
else if (millisElapsedSince(startTime) > timeoutMillis) {
threadAssertTrue(thread.isAlive());
return;
}
Thread.yield();
}
}
/**
* Waits up to LONG_DELAY_MS for the given thread to enter a wait
* state: BLOCKED, WAITING, or TIMED_WAITING.
*/
void waitForThreadToEnterWaitState(Thread thread) {
waitForThreadToEnterWaitState(thread, LONG_DELAY_MS);
}
/**
* Returns the number of milliseconds since time given by
* startNanoTime, which must have been previously returned from a
* call to {@link System.nanoTime()}.
*/
long millisElapsedSince(long startNanoTime) {
return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime);
}
/**
* Returns a new started daemon Thread running the given runnable.
*/
Thread newStartedThread(Runnable runnable) {
Thread t = new Thread(runnable);
t.setDaemon(true);
t.start();
return t;
}
/**
* Waits for the specified time (in milliseconds) for the thread
* to terminate (using {@link Thread#join(long)}), else interrupts
* the thread (in the hope that it may terminate later) and fails.
*/
void awaitTermination(Thread t, long timeoutMillis) {
try {
t.join(timeoutMillis);
} catch (InterruptedException ie) {
threadUnexpectedException(ie);
} finally {
if (t.getState() != Thread.State.TERMINATED) {
t.interrupt();
fail("Test timed out");
}
}
}
/**
* Waits for LONG_DELAY_MS milliseconds for the thread to
* terminate (using {@link Thread#join(long)}), else interrupts
* the thread (in the hope that it may terminate later) and fails.
*/
void awaitTermination(Thread t) {
awaitTermination(t, LONG_DELAY_MS);
}
// Some convenient Runnable classes
public abstract class CheckedRunnable implements Runnable {
protected abstract void realRun() throws Throwable;
public final void run() {
try {
realRun();
} catch (Throwable t) {
threadUnexpectedException(t);
}
}
}
public abstract class RunnableShouldThrow implements Runnable {
protected abstract void realRun() throws Throwable;
final Class<?> exceptionClass;
<T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) {
this.exceptionClass = exceptionClass;
}
public final void run() {
try {
realRun();
threadShouldThrow(exceptionClass.getSimpleName());
} catch (Throwable t) {
if (! exceptionClass.isInstance(t))
threadUnexpectedException(t);
}
}
}
public abstract class ThreadShouldThrow extends Thread {
protected abstract void realRun() throws Throwable;
final Class<?> exceptionClass;
<T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) {
this.exceptionClass = exceptionClass;
}
public final void run() {
try {
realRun();
threadShouldThrow(exceptionClass.getSimpleName());
} catch (Throwable t) {
if (! exceptionClass.isInstance(t))
threadUnexpectedException(t);
}
}
}
public abstract class CheckedInterruptedRunnable implements Runnable {
protected abstract void realRun() throws Throwable;
public final void run() {
try {
realRun();
threadShouldThrow("InterruptedException");
} catch (InterruptedException success) {
threadAssertFalse(Thread.interrupted());
} catch (Throwable t) {
threadUnexpectedException(t);
}
}
}
public abstract class CheckedCallable<T> implements Callable<T> {
protected abstract T realCall() throws Throwable;
public final T call() {
try {
return realCall();
} catch (Throwable t) {
threadUnexpectedException(t);
return null;
}
}
}
public abstract class CheckedInterruptedCallable<T>
implements Callable<T> {
protected abstract T realCall() throws Throwable;
public final T call() {
try {
T result = realCall();
threadShouldThrow("InterruptedException");
return result;
} catch (InterruptedException success) {
threadAssertFalse(Thread.interrupted());
} catch (Throwable t) {
threadUnexpectedException(t);
}
return null;
}
}
public static class NoOpRunnable implements Runnable {
public void run() {}
}
public static class NoOpCallable implements Callable {
public Object call() { return Boolean.TRUE; }
}
public static final String TEST_STRING = "a test string";
public static class StringTask implements Callable<String> {
public String call() { return TEST_STRING; }
}
public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) {
return new CheckedCallable<String>() {
protected String realCall() {
try {
latch.await();
} catch (InterruptedException quittingTime) {}
return TEST_STRING;
}};
}
public Runnable awaiter(final CountDownLatch latch) {
return new CheckedRunnable() {
public void realRun() throws InterruptedException {
await(latch);
}};
}
public void await(CountDownLatch latch) {
try {
assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS));
} catch (Throwable t) {
threadUnexpectedException(t);
}
}
public void await(Semaphore semaphore) {
try {
assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS));
} catch (Throwable t) {
threadUnexpectedException(t);
}
}
// /**
// * Spin-waits up to LONG_DELAY_MS until flag becomes true.
// */
// public void await(AtomicBoolean flag) {
// await(flag, LONG_DELAY_MS);
// }
// /**
// * Spin-waits up to the specified timeout until flag becomes true.
// */
// public void await(AtomicBoolean flag, long timeoutMillis) {
// long startTime = System.nanoTime();
// while (!flag.get()) {
// if (millisElapsedSince(startTime) > timeoutMillis)
// throw new AssertionFailedError("timed out");
// Thread.yield();
// }
// }
public static class NPETask implements Callable<String> {
public String call() { throw new NullPointerException(); }
}
public static class CallableOne implements Callable<Integer> {
public Integer call() { return one; }
}
public class ShortRunnable extends CheckedRunnable {
protected void realRun() throws Throwable {
delay(SHORT_DELAY_MS);
}
}
public class ShortInterruptedRunnable extends CheckedInterruptedRunnable {
protected void realRun() throws InterruptedException {
delay(SHORT_DELAY_MS);
}
}
public class SmallRunnable extends CheckedRunnable {
protected void realRun() throws Throwable {
delay(SMALL_DELAY_MS);
}
}
public class SmallPossiblyInterruptedRunnable extends CheckedRunnable {
protected void realRun() {
try {
delay(SMALL_DELAY_MS);
} catch (InterruptedException ok) {}
}
}
public class SmallCallable extends CheckedCallable {
protected Object realCall() throws InterruptedException {
delay(SMALL_DELAY_MS);
return Boolean.TRUE;
}
}
public class MediumRunnable extends CheckedRunnable {
protected void realRun() throws Throwable {
delay(MEDIUM_DELAY_MS);
}
}
public class MediumInterruptedRunnable extends CheckedInterruptedRunnable {
protected void realRun() throws InterruptedException {
delay(MEDIUM_DELAY_MS);
}
}
public Runnable possiblyInterruptedRunnable(final long timeoutMillis) {
return new CheckedRunnable() {
protected void realRun() {
try {
delay(timeoutMillis);
} catch (InterruptedException ok) {}
}};
}
public class MediumPossiblyInterruptedRunnable extends CheckedRunnable {
protected void realRun() {
try {
delay(MEDIUM_DELAY_MS);
} catch (InterruptedException ok) {}
}
}
public class LongPossiblyInterruptedRunnable extends CheckedRunnable {
protected void realRun() {
try {
delay(LONG_DELAY_MS);
} catch (InterruptedException ok) {}
}
}
/**
* For use as ThreadFactory in constructors
*/
public static class SimpleThreadFactory implements ThreadFactory {
public Thread newThread(Runnable r) {
return new Thread(r);
}
}
public interface TrackedRunnable extends Runnable {
boolean isDone();
}
public static TrackedRunnable trackedRunnable(final long timeoutMillis) {
return new TrackedRunnable() {
private volatile boolean done = false;
public boolean isDone() { return done; }
public void run() {
try {
delay(timeoutMillis);
done = true;
} catch (InterruptedException ok) {}
}
};
}
public static class TrackedShortRunnable implements Runnable {
public volatile boolean done = false;
public void run() {
try {
delay(SHORT_DELAY_MS);
done = true;
} catch (InterruptedException ok) {}
}
}
public static class TrackedSmallRunnable implements Runnable {
public volatile boolean done = false;
public void run() {
try {
delay(SMALL_DELAY_MS);
done = true;
} catch (InterruptedException ok) {}
}
}
public static class TrackedMediumRunnable implements Runnable {
public volatile boolean done = false;
public void run() {
try {
delay(MEDIUM_DELAY_MS);
done = true;
} catch (InterruptedException ok) {}
}
}
public static class TrackedLongRunnable implements Runnable {
public volatile boolean done = false;
public void run() {
try {
delay(LONG_DELAY_MS);
done = true;
} catch (InterruptedException ok) {}
}
}
public static class TrackedNoOpRunnable implements Runnable {
public volatile boolean done = false;
public void run() {
done = true;
}
}
public static class TrackedCallable implements Callable {
public volatile boolean done = false;
public Object call() {
try {
delay(SMALL_DELAY_MS);
done = true;
} catch (InterruptedException ok) {}
return Boolean.TRUE;
}
}
// /**
// * Analog of CheckedRunnable for RecursiveAction
// */
// public abstract class CheckedRecursiveAction extends RecursiveAction {
// protected abstract void realCompute() throws Throwable;
// public final void compute() {
// try {
// realCompute();
// } catch (Throwable t) {
// threadUnexpectedException(t);
// }
// }
// }
// /**
// * Analog of CheckedCallable for RecursiveTask
// */
// public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> {
// protected abstract T realCompute() throws Throwable;
// public final T compute() {
// try {
// return realCompute();
// } catch (Throwable t) {
// threadUnexpectedException(t);
// return null;
// }
// }
// }
/**
* For use as RejectedExecutionHandler in constructors
*/
public static class NoOpREHandler implements RejectedExecutionHandler {
public void rejectedExecution(Runnable r,
ThreadPoolExecutor executor) {}
}
/**
* A CyclicBarrier that uses timed await and fails with
* AssertionFailedErrors instead of throwing checked exceptions.
*/
public class CheckedBarrier extends CyclicBarrier {
public CheckedBarrier(int parties) { super(parties); }
public int await() {
try {
return super.await(2 * LONG_DELAY_MS, MILLISECONDS);
} catch (TimeoutException e) {
throw new AssertionFailedError("timed out");
} catch (Exception e) {
AssertionFailedError afe =
new AssertionFailedError("Unexpected exception: " + e);
afe.initCause(e);
throw afe;
}
}
}
void checkEmpty(BlockingQueue q) {
try {
assertTrue(q.isEmpty());
assertEquals(0, q.size());
assertNull(q.peek());
assertNull(q.poll());
assertNull(q.poll(0, MILLISECONDS));
assertEquals(q.toString(), "[]");
assertTrue(Arrays.equals(q.toArray(), new Object[0]));
assertFalse(q.iterator().hasNext());
try {
q.element();
shouldThrow();
} catch (NoSuchElementException success) {}
try {
q.iterator().next();
shouldThrow();
} catch (NoSuchElementException success) {}
try {
q.remove();
shouldThrow();
} catch (NoSuchElementException success) {}
} catch (InterruptedException ie) {
threadUnexpectedException(ie);
}
}
@SuppressWarnings("unchecked")
<T> T serialClone(T o) {
try {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(bos);
oos.writeObject(o);
oos.flush();
oos.close();
ObjectInputStream ois = new ObjectInputStream
(new ByteArrayInputStream(bos.toByteArray()));
T clone = (T) ois.readObject();
assertSame(o.getClass(), clone.getClass());
return clone;
} catch (Throwable t) {
threadUnexpectedException(t);
return null;
}
}
}
| Java |
/*
* 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.MILLISECONDS;
import static java.util.concurrent.TimeUnit.NANOSECONDS;
import static junit.framework.Assert.fail;
import com.google.common.testing.TearDown;
import com.google.common.testing.TearDownAccepter;
import java.util.concurrent.TimeUnit;
import java.util.logging.Logger;
/**
* Utilities for performing thread interruption in tests
*
* @author Kevin Bourrillion
* @author Chris Povirk
*/
final class InterruptionUtil {
private static final Logger logger =
Logger.getLogger(InterruptionUtil.class.getName());
/**
* Runnable which will interrupt the target thread repeatedly when run.
*/
private static final class Interruptenator implements Runnable {
private final long everyMillis;
private final Thread interruptee;
private volatile boolean shouldStop = false;
Interruptenator(Thread interruptee, long everyMillis) {
this.everyMillis = everyMillis;
this.interruptee = interruptee;
}
@Override
public void run() {
while (true) {
try {
Thread.sleep(everyMillis);
} catch (InterruptedException e) {
// ok. just stop sleeping.
}
if (shouldStop) {
break;
}
interruptee.interrupt();
}
}
void stopInterrupting() {
shouldStop = true;
}
}
/**
* Interrupts the current thread after sleeping for the specified delay.
*/
static void requestInterruptIn(final long time, final TimeUnit unit) {
final Thread interruptee = Thread.currentThread();
new Thread(new Runnable() {
@Override
public void run() {
try {
unit.sleep(time);
} catch (InterruptedException wontHappen) {
throw new AssertionError(wontHappen);
}
interruptee.interrupt();
}
}).start();
}
static void repeatedlyInterruptTestThread(
long interruptPeriodMillis, TearDownAccepter tearDownAccepter) {
final Interruptenator interruptingTask =
new Interruptenator(Thread.currentThread(), interruptPeriodMillis);
final Thread interruptingThread = new Thread(interruptingTask);
interruptingThread.start();
tearDownAccepter.addTearDown(new TearDown() {
@Override public void tearDown() throws Exception {
interruptingTask.stopInterrupting();
interruptingThread.interrupt();
joinUninterruptibly(interruptingThread, 2500, MILLISECONDS);
Thread.interrupted();
if (interruptingThread.isAlive()) {
// This will be hidden by test-output redirection:
logger.severe(
"InterruptenatorTask did not exit; future tests may be affected");
/*
* This won't do any good under JUnit 3, but I'll leave it around in
* case we ever switch to JUnit 4:
*/
fail();
}
}
});
}
// TODO(cpovirk): promote to Uninterruptibles, and add untimed version
private static void joinUninterruptibly(
Thread thread, long timeout, TimeUnit unit) {
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(thread, remainingNanos);
return;
} catch (InterruptedException e) {
interrupted = true;
remainingNanos = end - System.nanoTime();
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}
}
| Java |
/*
* 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 com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.ForwardingObject;
import com.google.common.collect.Iterables;
import com.google.common.testing.ForwardingWrapperTester;
import org.easymock.EasyMock;
import java.lang.reflect.Method;
import java.util.Arrays;
/**
* Tester for typical subclass of {@link ForwardingObject} by using EasyMock partial mocks.
*
* @author Ben Yu
*/
final class ForwardingObjectTester {
private static final Method DELEGATE_METHOD;
static {
try {
DELEGATE_METHOD = ForwardingObject.class.getDeclaredMethod("delegate");
DELEGATE_METHOD.setAccessible(true);
} catch (SecurityException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new AssertionError(e);
}
}
/**
* Ensures that all interface methods of {@code forwarderClass} are forwarded to the
* {@link ForwardingObject#delegate}. {@code forwarderClass} is assumed to only implement one
* interface.
*/
static <T extends ForwardingObject> void testForwardingObject(final Class<T> forwarderClass) {
@SuppressWarnings("unchecked") // super interface type of T
Class<? super T> interfaceType = (Class<? super T>)
Iterables.getOnlyElement(Arrays.asList(forwarderClass.getInterfaces()));
new ForwardingWrapperTester().testForwarding(interfaceType, new Function<Object, T>() {
@Override public T apply(Object delegate) {
T mock = EasyMock.createMockBuilder(forwarderClass)
.addMockedMethod(DELEGATE_METHOD)
.createMock();
try {
DELEGATE_METHOD.invoke(mock);
} catch (Exception e) {
throw Throwables.propagate(e);
}
EasyMock.expectLastCall().andStubReturn(delegate);
EasyMock.replay(mock);
return mock;
}
});
}
}
| Java |
/*
* 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 junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertFalse;
import static junit.framework.Assert.assertTrue;
import static junit.framework.Assert.fail;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
/**
* Used to test listenable future implementations.
*
* @author Sven Mawson
*/
public class ListenableFutureTester {
private final ExecutorService exec;
private final ListenableFuture<?> future;
private final CountDownLatch latch;
public ListenableFutureTester(ListenableFuture<?> future) {
this.exec = Executors.newCachedThreadPool();
this.future = future;
this.latch = new CountDownLatch(1);
}
public void setUp() {
future.addListener(new Runnable() {
@Override public void run() {
latch.countDown();
}
}, exec);
assertEquals(1, latch.getCount());
assertFalse(future.isDone());
assertFalse(future.isCancelled());
}
public void tearDown() {
exec.shutdown();
}
public void testCompletedFuture(Object expectedValue)
throws InterruptedException, ExecutionException {
assertTrue(future.isDone());
assertFalse(future.isCancelled());
assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(future.isDone());
assertFalse(future.isCancelled());
assertEquals(expectedValue, future.get());
}
public void testCancelledFuture()
throws InterruptedException, ExecutionException {
assertTrue(future.isDone());
assertTrue(future.isCancelled());
assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(future.isDone());
assertTrue(future.isCancelled());
try {
future.get();
fail("Future should throw CancellationException on cancel.");
} catch (CancellationException expected) {}
}
public void testFailedFuture(String message)
throws InterruptedException {
assertTrue(future.isDone());
assertFalse(future.isCancelled());
assertTrue(latch.await(5, TimeUnit.SECONDS));
assertTrue(future.isDone());
assertFalse(future.isCancelled());
try {
future.get();
fail("Future should rethrow the exception.");
} catch (ExecutionException e) {
assertEquals(message, e.getCause().getMessage());
}
}
}
| Java |
/*
* 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 java.math.BigInteger.ONE;
import static java.math.BigInteger.ZERO;
import static java.math.RoundingMode.CEILING;
import static java.math.RoundingMode.DOWN;
import static java.math.RoundingMode.FLOOR;
import static java.math.RoundingMode.HALF_DOWN;
import static java.math.RoundingMode.HALF_EVEN;
import static java.math.RoundingMode.HALF_UP;
import static java.math.RoundingMode.UP;
import static java.util.Arrays.asList;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Function;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.primitives.Doubles;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* Exhaustive input sets for every integral type.
*
* @author Louis Wasserman
*/
@GwtCompatible
public class MathTesting {
static final ImmutableSet<RoundingMode> ALL_ROUNDING_MODES = ImmutableSet.copyOf(RoundingMode
.values());
static final ImmutableList<RoundingMode> ALL_SAFE_ROUNDING_MODES = ImmutableList.of(DOWN, UP,
FLOOR, CEILING, HALF_EVEN, HALF_UP, HALF_DOWN);
// Exponents to test for the pow() function.
static final ImmutableList<Integer> EXPONENTS = ImmutableList.of(0, 1, 2, 3, 4, 5, 6, 7, 10, 15,
20, 25, 30, 40, 70);
/* Helper function to make a Long value from an Integer. */
private static final Function<Integer, Long> TO_LONG = new Function<Integer, Long>() {
@Override
public Long apply(Integer n) {
return Long.valueOf(n);
}
};
/* Helper function to make a BigInteger value from a Long. */
private static final Function<Long, BigInteger> TO_BIGINTEGER =
new Function<Long, BigInteger>() {
@Override
public BigInteger apply(Long n) {
return BigInteger.valueOf(n);
}
};
private static final Function<Integer, Integer> NEGATE_INT = new Function<Integer, Integer>() {
@Override
public Integer apply(Integer x) {
return -x;
}
};
private static final Function<Long, Long> NEGATE_LONG = new Function<Long, Long>() {
@Override
public Long apply(Long x) {
return -x;
}
};
private static final Function<BigInteger, BigInteger> NEGATE_BIGINT =
new Function<BigInteger, BigInteger>() {
@Override
public BigInteger apply(BigInteger x) {
return x.negate();
}
};
/*
* This list contains values that attempt to provoke overflow in integer operations. It contains
* positive values on or near 2^N for N near multiples of 8 (near byte boundaries).
*/
static final ImmutableSet<Integer> POSITIVE_INTEGER_CANDIDATES;
static final Iterable<Integer> NEGATIVE_INTEGER_CANDIDATES;
static final Iterable<Integer> NONZERO_INTEGER_CANDIDATES;
static final Iterable<Integer> ALL_INTEGER_CANDIDATES;
static {
ImmutableSet.Builder<Integer> intValues = ImmutableSet.builder();
// Add boundary values manually to avoid over/under flow (this covers 2^N for 0 and 31).
intValues.add(Integer.MAX_VALUE - 1, Integer.MAX_VALUE);
// Add values up to 64. This covers cases like "square of a prime" and such.
for (int i = 1; i <= 64; i++) {
intValues.add(i);
}
// Now add values near 2^N for lots of values of N.
for (int exponent : asList(2, 3, 4, 5, 6, 7, 8, 9, 15, 16, 17, 23, 24, 25, 30)) {
int x = 1 << exponent;
intValues.add(x, x + 1, x - 1);
}
intValues.add(9999).add(10000).add(10001).add(1000000); // near powers of 10
intValues.add(5792).add(5793); // sqrt(2^25) rounded up and down
POSITIVE_INTEGER_CANDIDATES = intValues.build();
NEGATIVE_INTEGER_CANDIDATES =
Iterables.concat(Iterables.transform(POSITIVE_INTEGER_CANDIDATES, NEGATE_INT),
ImmutableList.of(Integer.MIN_VALUE));
NONZERO_INTEGER_CANDIDATES =
Iterables.concat(POSITIVE_INTEGER_CANDIDATES, NEGATIVE_INTEGER_CANDIDATES);
ALL_INTEGER_CANDIDATES = Iterables.concat(NONZERO_INTEGER_CANDIDATES, ImmutableList.of(0));
}
/*
* This list contains values that attempt to provoke overflow in long operations. It contains
* positive values on or near 2^N for N near multiples of 8 (near byte boundaries). This list is
* a superset of POSITIVE_INTEGER_CANDIDATES.
*/
static final ImmutableSet<Long> POSITIVE_LONG_CANDIDATES;
static final Iterable<Long> NEGATIVE_LONG_CANDIDATES;
static final Iterable<Long> NONZERO_LONG_CANDIDATES;
static final Iterable<Long> ALL_LONG_CANDIDATES;
static {
ImmutableSet.Builder<Long> longValues = ImmutableSet.builder();
// First of all add all the integer candidate values.
longValues.addAll(Iterables.transform(POSITIVE_INTEGER_CANDIDATES, TO_LONG));
// Add boundary values manually to avoid over/under flow (this covers 2^N for 31 and 63).
longValues.add(Integer.MAX_VALUE + 1L, Long.MAX_VALUE - 1L, Long.MAX_VALUE);
// Now add values near 2^N for lots of values of N.
for (int exponent : asList(32, 33, 39, 40, 41, 47, 48, 49, 55, 56, 57)) {
long x = 1L << exponent;
longValues.add(x, x + 1, x - 1);
}
longValues.add(194368031998L).add(194368031999L); // sqrt(2^75) rounded up and down
POSITIVE_LONG_CANDIDATES = longValues.build();
NEGATIVE_LONG_CANDIDATES =
Iterables.concat(Iterables.transform(POSITIVE_LONG_CANDIDATES, NEGATE_LONG),
ImmutableList.of(Long.MIN_VALUE));
NONZERO_LONG_CANDIDATES = Iterables.concat(POSITIVE_LONG_CANDIDATES, NEGATIVE_LONG_CANDIDATES);
ALL_LONG_CANDIDATES = Iterables.concat(NONZERO_LONG_CANDIDATES, ImmutableList.of(0L));
}
/*
* This list contains values that attempt to provoke overflow in big integer operations. It
* contains positive values on or near 2^N for N near multiples of 8 (near byte boundaries). This
* list is a superset of POSITIVE_LONG_CANDIDATES.
*/
static final ImmutableSet<BigInteger> POSITIVE_BIGINTEGER_CANDIDATES;
static final Iterable<BigInteger> NEGATIVE_BIGINTEGER_CANDIDATES;
static final Iterable<BigInteger> NONZERO_BIGINTEGER_CANDIDATES;
static final Iterable<BigInteger> ALL_BIGINTEGER_CANDIDATES;
static {
ImmutableSet.Builder<BigInteger> bigValues = ImmutableSet.builder();
// First of all add all the long candidate values.
bigValues.addAll(Iterables.transform(POSITIVE_LONG_CANDIDATES, TO_BIGINTEGER));
// Add boundary values manually to avoid over/under flow.
bigValues.add(BigInteger.valueOf(Long.MAX_VALUE).add(ONE));
// Now add values near 2^N for lots of values of N.
for (int exponent : asList(64, 65, 71, 72, 73, 79, 80, 81, 255, 256, 257, 511, 512, 513,
Double.MAX_EXPONENT - 1, Double.MAX_EXPONENT, Double.MAX_EXPONENT + 1)) {
BigInteger x = ONE.shiftLeft(exponent);
bigValues.add(x, x.add(ONE), x.subtract(ONE));
}
bigValues.add(new BigInteger("218838949120258359057546633")); // sqrt(2^175) rounded up and
// down
bigValues.add(new BigInteger("218838949120258359057546634"));
POSITIVE_BIGINTEGER_CANDIDATES = bigValues.build();
NEGATIVE_BIGINTEGER_CANDIDATES =
Iterables.transform(POSITIVE_BIGINTEGER_CANDIDATES, NEGATE_BIGINT);
NONZERO_BIGINTEGER_CANDIDATES =
Iterables.concat(POSITIVE_BIGINTEGER_CANDIDATES, NEGATIVE_BIGINTEGER_CANDIDATES);
ALL_BIGINTEGER_CANDIDATES =
Iterables.concat(NONZERO_BIGINTEGER_CANDIDATES, ImmutableList.of(ZERO));
}
static final ImmutableSet<Double> INTEGRAL_DOUBLE_CANDIDATES;
static final ImmutableSet<Double> FRACTIONAL_DOUBLE_CANDIDATES;
static final Iterable<Double> INFINITIES = Doubles.asList(
Double.POSITIVE_INFINITY,
Double.NEGATIVE_INFINITY);
static final Iterable<Double> FINITE_DOUBLE_CANDIDATES;
static final Iterable<Double> POSITIVE_FINITE_DOUBLE_CANDIDATES;
static final Iterable<Double> ALL_DOUBLE_CANDIDATES;
static final Iterable<Double> DOUBLE_CANDIDATES_EXCEPT_NAN;
static {
ImmutableSet.Builder<Double> integralBuilder = ImmutableSet.builder();
ImmutableSet.Builder<Double> fractionalBuilder = ImmutableSet.builder();
integralBuilder.addAll(Doubles.asList(0.0, -0.0, Double.MAX_VALUE, -Double.MAX_VALUE));
// Add small multiples of MIN_VALUE and MIN_NORMAL
for (int scale = 1; scale <= 4; scale++) {
for (double d : Doubles.asList(Double.MIN_VALUE, Double.MIN_NORMAL)) {
fractionalBuilder.add(d * scale).add(-d * scale);
}
}
for (double d : Doubles.asList(0, 1, 2, 7, 51, 102, Math.scalb(1.0, 53), Integer.MIN_VALUE,
Integer.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE)) {
for (double delta : Doubles.asList(0.0, 1.0, 2.0)) {
integralBuilder.addAll(Doubles.asList(d + delta, d - delta, -d - delta, -d + delta));
}
for (double delta : Doubles.asList(0.01, 0.1, 0.25, 0.499, 0.5, 0.501, 0.7, 0.8)) {
double x = d + delta;
if (x != Math.round(x)) {
fractionalBuilder.add(x);
}
}
}
INTEGRAL_DOUBLE_CANDIDATES = integralBuilder.build();
fractionalBuilder.add(1.414).add(1.415).add(Math.sqrt(2));
fractionalBuilder.add(5.656).add(5.657).add(4 * Math.sqrt(2));
for (double d : INTEGRAL_DOUBLE_CANDIDATES) {
double x = 1 / d;
if (x != Math.rint(x)) {
fractionalBuilder.add(x);
}
}
FRACTIONAL_DOUBLE_CANDIDATES = fractionalBuilder.build();
FINITE_DOUBLE_CANDIDATES =
Iterables.concat(FRACTIONAL_DOUBLE_CANDIDATES, INTEGRAL_DOUBLE_CANDIDATES);
POSITIVE_FINITE_DOUBLE_CANDIDATES =
Iterables.filter(FINITE_DOUBLE_CANDIDATES, new Predicate<Double>() {
@Override
public boolean apply(Double input) {
return input.doubleValue() > 0.0;
}
});
DOUBLE_CANDIDATES_EXCEPT_NAN = Iterables.concat(FINITE_DOUBLE_CANDIDATES, INFINITIES);
ALL_DOUBLE_CANDIDATES =
Iterables.concat(DOUBLE_CANDIDATES_EXCEPT_NAN, asList(Double.NaN));
}
}
| Java |
/*
* 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 java.math.BigInteger;
import java.util.Random;
/**
* Utilities for benchmarks.
*
* @author Louis Wasserman
*/
final class MathBenchmarking {
static final int ARRAY_SIZE = 0x10000;
static final int ARRAY_MASK = 0x0ffff;
static final Random RANDOM_SOURCE = new Random(314159265358979L);
static final int MAX_EXPONENT = 100;
/*
* Duplicated from LongMath.
* binomial(BIGGEST_BINOMIALS[k], k) fits in a long, but not
* binomial(BIGGEST_BINOMIALS[k] + 1, k).
*/
static final int[] BIGGEST_BINOMIALS =
{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};
static BigInteger randomPositiveBigInteger(int numBits) {
int digits = RANDOM_SOURCE.nextInt(numBits) + 1;
return new BigInteger(digits, RANDOM_SOURCE).add(BigInteger.ONE);
}
static BigInteger randomNonNegativeBigInteger(int numBits) {
int digits = RANDOM_SOURCE.nextInt(numBits) + 1;
return new BigInteger(digits, RANDOM_SOURCE);
}
static BigInteger randomNonZeroBigInteger(int numBits) {
BigInteger result = randomPositiveBigInteger(numBits);
return RANDOM_SOURCE.nextBoolean() ? result : result.negate();
}
static BigInteger randomBigInteger(int numBits) {
BigInteger result = randomNonNegativeBigInteger(numBits);
return RANDOM_SOURCE.nextBoolean() ? result : result.negate();
}
static double randomDouble(int maxExponent) {
double result = RANDOM_SOURCE.nextDouble();
result = Math.scalb(result, RANDOM_SOURCE.nextInt(maxExponent + 1));
return RANDOM_SOURCE.nextBoolean() ? result : -result;
}
/**
* Returns a random integer between zero and {@code MAX_EXPONENT}.
*/
static int randomExponent() {
return RANDOM_SOURCE.nextInt(MAX_EXPONENT + 1);
}
static double randomPositiveDouble() {
return Math.exp(randomDouble(6));
}
}
| Java |
/*
* 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.Lists;
import junit.framework.Assert;
import java.util.List;
/**
* A simple EventHandler mock that records Strings.
*
* For testing fun, also includes a landmine method that EventBus tests are
* required <em>not</em> to call ({@link #methodWithoutAnnotation(String)}).
*
* @author Cliff Biffle
*/
public class StringCatcher {
private List<String> events = Lists.newArrayList();
@Subscribe
public void hereHaveAString(String string) {
events.add(string);
}
public void methodWithoutAnnotation(String string) {
Assert.fail("Event bus must not call methods without @Subscribe!");
}
public List<String> getEvents() {
return events;
}
}
| Java |
/*
* 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.collect;
import com.google.common.base.Function;
import com.google.common.base.Joiner;
import junit.framework.TestCase;
import java.lang.reflect.Array;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
/**
* Base test case for testing the variety of forwarding classes.
*
* @author Robert Konigsberg
* @author Louis Wasserman
*/
public abstract class ForwardingTestCase extends TestCase {
private final List<String> calls = new ArrayList<String>();
private void called(String id) {
calls.add(id);
}
protected String getCalls() {
return calls.toString();
}
protected boolean isCalled() {
return !calls.isEmpty();
}
@SuppressWarnings("unchecked")
protected <T> T createProxyInstance(Class<T> c) {
/*
* This invocation handler only registers that a method was called,
* and then returns a bogus, but acceptable, value.
*/
InvocationHandler handler = new InvocationHandler() {
@Override
public Object invoke(Object proxy, Method method, Object[] args)
throws Throwable {
called(asString(method));
return getDefaultValue(method.getReturnType());
}
};
return (T) Proxy.newProxyInstance(c.getClassLoader(),
new Class[] { c }, handler);
}
private static final Joiner COMMA_JOINER = Joiner.on(",");
/*
* Returns string representation of a method.
*
* If the method takes no parameters, it returns the name (e.g.
* "isEmpty". If the method takes parameters, it returns the simple names
* of the parameters (e.g. "put(Object,Object)".)
*/
private String asString(Method method) {
String methodName = method.getName();
Class<?>[] parameterTypes = method.getParameterTypes();
if (parameterTypes.length == 0) {
return methodName;
}
Iterable<String> parameterNames = Iterables.transform(
Arrays.asList(parameterTypes),
new Function<Class<?>, String>() {
@Override
public String apply(Class<?> from) {
return from.getSimpleName();
}
});
return methodName + "(" + COMMA_JOINER.join(parameterNames) + ")";
}
private static Object getDefaultValue(Class<?> returnType) {
if (returnType == boolean.class || returnType == Boolean.class) {
return Boolean.FALSE;
} else if (returnType == int.class || returnType == Integer.class) {
return 0;
} else if ((returnType == Set.class) || (returnType == Collection.class)) {
return Collections.emptySet();
} else if (returnType == Iterator.class){
return Iterators.emptyModifiableIterator();
} else if (returnType.isArray()) {
return Array.newInstance(returnType.getComponentType(), 0);
} else {
return null;
}
}
protected static <T> void callAllPublicMethods(Class<T> theClass, T object)
throws InvocationTargetException {
for (Method method : theClass.getMethods()) {
Class<?>[] parameterTypes = method.getParameterTypes();
Object[] parameters = new Object[parameterTypes.length];
for (int i = 0; i < parameterTypes.length; i++) {
parameters[i] = getDefaultValue(parameterTypes[i]);
}
try {
try {
method.invoke(object, parameters);
} catch (InvocationTargetException ex) {
try {
throw ex.getCause();
} catch (UnsupportedOperationException unsupported) {
// this is a legit exception
}
}
} catch (Throwable cause) {
throw new InvocationTargetException(cause,
method.toString() + " with args: " + Arrays.toString(parameters));
}
}
}
}
| Java |
/*
* 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.collect;
import static com.google.common.base.Preconditions.checkNotNull;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
import java.util.Collections;
import java.util.List;
import java.util.Set;
/**
* Package up sample data for common collections benchmarking.
*
* @author Nicholaus Shupe
*/
class CollectionBenchmarkSampleData {
private final boolean isUserTypeFast;
private final SpecialRandom random;
private final double hitRate;
private final int size;
private final Set<Element> valuesInSet;
private final Element[] queries;
CollectionBenchmarkSampleData(
boolean isUserTypeFast,
SpecialRandom random,
double hitRate,
int size) {
this.isUserTypeFast = isUserTypeFast;
this.random = checkNotNull(random);
this.hitRate = hitRate;
this.size = size;
this.valuesInSet = createData();
this.queries = createQueries(valuesInSet, 1024);
}
Set<Element> getValuesInSet() {
return valuesInSet;
}
Element[] getQueries() {
return queries;
}
private Element[] createQueries(Set<Element> elementsInSet, int numQueries) {
List<Element> queryList = Lists.newArrayListWithCapacity(numQueries);
int numGoodQueries = (int) (numQueries * hitRate + 0.5);
// add good queries
int size = elementsInSet.size();
int minCopiesOfEachGoodQuery = numGoodQueries / size;
int extras = numGoodQueries % size;
for (int i = 0; i < minCopiesOfEachGoodQuery; i++) {
queryList.addAll(elementsInSet);
}
List<Element> tmp = Lists.newArrayList(elementsInSet);
Collections.shuffle(tmp, random);
queryList.addAll(tmp.subList(0, extras));
// now add bad queries
while (queryList.size() < numQueries) {
Element candidate = newElement();
if (!elementsInSet.contains(candidate)) {
queryList.add(candidate);
}
}
Collections.shuffle(queryList, random);
return queryList.toArray(new Element[0]);
}
private Set<Element> createData() {
Set<Element> set = Sets.newHashSetWithExpectedSize(size);
while (set.size() < size) {
set.add(newElement());
}
return set;
}
private Element newElement() {
int value = random.nextInt();
return isUserTypeFast
? new Element(value)
: new SlowElement(value);
}
static class Element implements Comparable<Element> {
final int hash;
Element(int hash) {
this.hash = hash;
}
@Override public boolean equals(Object obj) {
return this == obj
|| (obj instanceof Element && ((Element) obj).hash == hash);
}
@Override public int hashCode() {
return hash;
}
@Override
public int compareTo(Element that) {
return (hash < that.hash) ? -1 : (hash > that.hash) ? 1 : 0;
}
@Override public String toString() {
return String.valueOf(hash);
}
}
static class SlowElement extends Element {
SlowElement(int hash) {
super(hash);
}
@Override public boolean equals(Object obj) {
return slowItDown() != 1 && super.equals(obj);
}
@Override public int hashCode() {
return slowItDown() + hash;
}
@Override public int compareTo(Element e) {
int x = slowItDown();
return x + super.compareTo(e) - x; // silly attempt to prevent opt
}
static int slowItDown() {
int result = 0;
for (int i = 1; i <= 1000; i++) {
result += i;
}
return result;
}
}
}
| Java |
/*
* 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.collect;
import static com.google.common.testing.SerializableTester.reserialize;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.GwtCompatible;
import com.google.common.annotations.GwtIncompatible;
import com.google.common.testing.SerializableTester;
import java.util.Set;
/**
* Variant of {@link SerializableTester} that does not require the reserialized object's class to be
* identical to the original.
*
* @author Chris Povirk
*/
/*
* The whole thing is really @GwtIncompatible, but GwtJUnitConvertedTestModule doesn't have a
* parameter for non-GWT, non-test files, and it didn't seem worth adding one for this unusual case.
*/
@GwtCompatible(emulated = true)
final class LenientSerializableTester {
/*
* TODO(cpovirk): move this to c.g.c.testing if we allow for c.g.c.annotations dependencies so
* that it can be GWTified?
*/
@GwtIncompatible("SerializableTester")
static <E> Set<E> reserializeAndAssertLenient(Set<E> original) {
Set<E> copy = reserialize(original);
assertEquals(original, copy);
assertTrue(copy instanceof ImmutableSet);
return copy;
}
@GwtIncompatible("SerializableTester")
static <E> Multiset<E> reserializeAndAssertLenient(Multiset<E> original) {
Multiset<E> copy = reserialize(original);
assertEquals(original, copy);
assertTrue(copy instanceof ImmutableMultiset);
return copy;
}
private LenientSerializableTester() {}
}
| Java |
/*
* 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.collect;
import com.google.common.annotations.GwtCompatible;
import java.io.Serializable;
import java.util.Arrays;
/**
* A class that implements {@code Comparable} without generics, such as those
* found in libraries that support Java 1.4 and before. Our library needs to
* do the bare minimum to accommodate such types, though their use may still
* require an explicit type parameter and/or warning suppression.
*
* @author Kevin Bourrillion
*/
@GwtCompatible
class LegacyComparable implements Comparable, Serializable {
static final LegacyComparable X = new LegacyComparable("x");
static final LegacyComparable Y = new LegacyComparable("y");
static final LegacyComparable Z = new LegacyComparable("z");
static final Iterable<LegacyComparable> VALUES_FORWARD
= Arrays.asList(X, Y, Z);
static final Iterable<LegacyComparable> VALUES_BACKWARD
= Arrays.asList(Z, Y, X);
private final String value;
LegacyComparable(String value) {
this.value = value;
}
@Override
public int compareTo(Object object) {
// This method is spec'd to throw CCE if object is of the wrong type
LegacyComparable that = (LegacyComparable) object;
return this.value.compareTo(that.value);
}
@Override public boolean equals(Object object) {
if (object instanceof LegacyComparable) {
LegacyComparable that = (LegacyComparable) object;
return this.value.equals(that.value);
}
return false;
}
@Override public int hashCode() {
return value.hashCode();
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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.collect;
import java.util.Random;
/**
* Utility class for being able to seed a {@link Random} value with a passed
* in seed from a benchmark parameter.
*
* TODO: Remove this class once Caliper has a better way.
*
* @author Nicholaus Shupe
*/
public final class SpecialRandom extends Random {
public static SpecialRandom valueOf(String s) {
return (s.length() == 0)
? new SpecialRandom()
: new SpecialRandom(Long.parseLong(s));
}
private final boolean hasSeed;
private final long seed;
public SpecialRandom() {
this.hasSeed = false;
this.seed = 0;
}
public SpecialRandom(long seed) {
super(seed);
this.hasSeed = true;
this.seed = seed;
}
@Override public String toString() {
return hasSeed ? "(seed:" + seed : "(default seed)";
}
private static final long serialVersionUID = 0;
}
| Java |
/*
* 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.collect;
import com.google.common.collect.CollectionBenchmarkSampleData.Element;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.TreeSet;
/**
* Helper classes for various benchmarks.
*
* @author Christopher Swenson
*/
final class BenchmarkHelpers {
/**
* So far, this is the best way to test various implementations of {@link Set} subclasses.
*/
public enum SetImpl {
Hash {
@Override Set<Element> create(Collection<Element> contents) {
return new HashSet<Element>(contents);
}
},
LinkedHash {
@Override Set<Element> create(Collection<Element> contents) {
return new LinkedHashSet<Element>(contents);
}
},
Tree {
@Override Set<Element> create(Collection<Element> contents) {
return new TreeSet<Element>(contents);
}
},
Unmodifiable {
@Override Set<Element> create(Collection<Element> contents) {
return Collections.unmodifiableSet(new HashSet<Element>(contents));
}
},
Synchronized {
@Override Set<Element> create(Collection<Element> contents) {
return Collections.synchronizedSet(new HashSet<Element>(contents));
}
},
Immutable {
@Override Set<Element> create(Collection<Element> contents) {
return ImmutableSet.copyOf(contents);
}
},
;
abstract Set<Element> create(Collection<Element> contents);
}
}
| Java |
/*
* 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.reflect.subpackage;
public class ClassInSubPackage {}
| Java |
/*
* 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.hash;
import static org.junit.Assert.assertEquals;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Sets;
import com.google.common.primitives.Ints;
import org.junit.Assert;
import java.nio.charset.Charset;
import java.util.Arrays;
import java.util.Random;
import java.util.Set;
/**
* Various utilities for testing {@link HashFunction}s.
*
* @author Dimitris Andreou
* @author Kurt Alfred Kluever
*/
final class HashTestUtils {
private HashTestUtils() {}
/**
* Converts a string, which should contain only ascii-representable characters, to a byte[].
*/
static byte[] ascii(String string) {
byte[] bytes = new byte[string.length()];
for (int i = 0; i < string.length(); i++) {
bytes[i] = (byte) string.charAt(i);
}
return bytes;
}
interface HashFn {
byte[] hash(byte[] input, int seed);
}
static void verifyHashFunction(HashFn hashFunction, int hashbits, int expected) {
int hashBytes = hashbits / 8;
byte[] key = new byte[256];
byte[] hashes = new byte[hashBytes * 256];
// Hash keys of the form {}, {0}, {0,1}, {0,1,2}... up to N=255,using 256-N as the seed
for (int i = 0; i < 256; i++) {
key[i] = (byte) i;
int seed = 256 - i;
byte[] hash = hashFunction.hash(Arrays.copyOf(key, i), seed);
System.arraycopy(hash, 0, hashes, i * hashBytes, hash.length);
}
// Then hash the result array
byte[] result = hashFunction.hash(hashes, 0);
// interpreted in little-endian order.
int verification = Integer.reverseBytes(Ints.fromByteArray(result));
if (expected != verification) {
throw new AssertionError("Expected: " + Integer.toHexString(expected)
+ " got: " + Integer.toHexString(verification));
}
}
static final Funnel<Object> BAD_FUNNEL = new Funnel<Object>() {
@Override public void funnel(Object object, PrimitiveSink bytePrimitiveSink) {
bytePrimitiveSink.putInt(object.hashCode());
}
};
static enum RandomHasherAction {
PUT_BOOLEAN() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
boolean value = random.nextBoolean();
for (PrimitiveSink sink : sinks) {
sink.putBoolean(value);
}
}
},
PUT_BYTE() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
int value = random.nextInt();
for (PrimitiveSink sink : sinks) {
sink.putByte((byte) value);
}
}
},
PUT_SHORT() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
short value = (short) random.nextInt();
for (PrimitiveSink sink : sinks) {
sink.putShort(value);
}
}
},
PUT_CHAR() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
char value = (char) random.nextInt();
for (PrimitiveSink sink : sinks) {
sink.putChar(value);
}
}
},
PUT_INT() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
int value = random.nextInt();
for (PrimitiveSink sink : sinks) {
sink.putInt(value);
}
}
},
PUT_LONG() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
long value = random.nextLong();
for (PrimitiveSink sink : sinks) {
sink.putLong(value);
}
}
},
PUT_FLOAT() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
float value = random.nextFloat();
for (PrimitiveSink sink : sinks) {
sink.putFloat(value);
}
}
},
PUT_DOUBLE() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
double value = random.nextDouble();
for (PrimitiveSink sink : sinks) {
sink.putDouble(value);
}
}
},
PUT_BYTES() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
byte[] value = new byte[random.nextInt(128)];
random.nextBytes(value);
for (PrimitiveSink sink : sinks) {
sink.putBytes(value);
}
}
},
PUT_BYTES_INT_INT() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
byte[] value = new byte[random.nextInt(128)];
random.nextBytes(value);
int off = random.nextInt(value.length + 1);
int len = random.nextInt(value.length - off + 1);
for (PrimitiveSink sink : sinks) {
sink.putBytes(value);
}
}
},
PUT_STRING() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
char[] value = new char[random.nextInt(128)];
for (int i = 0; i < value.length; i++) {
value[i] = (char) random.nextInt();
}
String s = new String(value);
for (PrimitiveSink sink : sinks) {
sink.putString(s);
}
}
},
PUT_STRING_LOW_SURROGATE() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
String s = new String(new char[] { randomLowSurrogate(random) });
for (PrimitiveSink sink : sinks) {
sink.putString(s);
}
}
},
PUT_STRING_HIGH_SURROGATE() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
String s = new String(new char[] { randomHighSurrogate(random) });
for (PrimitiveSink sink : sinks) {
sink.putString(s);
}
}
},
PUT_STRING_LOW_HIGH_SURROGATE() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
String s = new String(new char[] {
randomLowSurrogate(random), randomHighSurrogate(random)});
for (PrimitiveSink sink : sinks) {
sink.putString(s);
}
}
},
PUT_STRING_HIGH_LOW_SURROGATE() {
@Override void performAction(Random random, Iterable<? extends PrimitiveSink> sinks) {
String s = new String(new char[] {
randomHighSurrogate(random), randomLowSurrogate(random)});
for (PrimitiveSink sink : sinks) {
sink.putString(s);
}
}
};
abstract void performAction(Random random, Iterable<? extends PrimitiveSink> sinks);
private static final RandomHasherAction[] actions = values();
static RandomHasherAction pickAtRandom(Random random) {
return actions[random.nextInt(actions.length)];
}
}
/**
* Test that the hash function contains no funnels. A funnel is a situation where a set of input
* (key) bits 'affects' a strictly smaller set of output bits. Funneling is bad because it can
* result in more-than-ideal collisions for a non-uniformly distributed key space. In practice,
* most key spaces are ANYTHING BUT uniformly distributed. A bit(i) in the input is said to
* 'affect' a bit(j) in the output if two inputs, identical but for bit(i), will differ at output
* bit(j) about half the time
*
* <p>Funneling is pretty simple to detect. The key idea is to find example keys which
* unequivocably demonstrate that funneling cannot be occuring. This is done bit-by-bit. For
* each input bit(i) and output bit(j), two pairs of keys must be found with all bits identical
* except bit(i). One pair must differ in output bit(j), and one pair must not. This proves that
* input bit(i) can alter output bit(j).
*/
static void checkNoFunnels(HashFunction function) {
Random rand = new Random(0);
int keyBits = 32;
int hashBits = function.bits();
// output loop tests input bit
for (int i = 0; i < keyBits; i++) {
int same = 0x0; // bitset for output bits with same values
int diff = 0x0; // bitset for output bits with different values
int count = 0;
// originally was 2 * Math.log(...), making it try more times to avoid flakiness issues
int maxCount = (int) (4 * Math.log(2 * keyBits * hashBits) + 1);
while (same != 0xffffffff || diff != 0xffffffff) {
int key1 = rand.nextInt();
// flip input bit for key2
int key2 = key1 ^ (1 << i);
// get hashes
int hash1 = function.newHasher().putInt(key1).hash().asInt();
int hash2 = function.newHasher().putInt(key2).hash().asInt();
// test whether the hash values have same output bits
same |= ~(hash1 ^ hash2);
// test whether the hash values have different output bits
diff |= (hash1 ^ hash2);
count++;
// check whether we've exceeded the probabilistically
// likely number of trials to have proven no funneling
if (count > maxCount) {
Assert.fail("input bit(" + i + ") was found not to affect all " +
hashBits + " output bits; The unaffected bits are " +
"as follows: " + ~(same & diff) + ". This was " +
"determined after " + count + " trials.");
}
}
}
}
/**
* Test for avalanche. Avalanche means that output bits differ with roughly 1/2 probability on
* different input keys. This test verifies that each possible 1-bit key delta achieves avalanche.
*
* <p>For more information: http://burtleburtle.net/bob/hash/avalanche.html
*/
static void checkAvalanche(HashFunction function, int trials, double epsilon) {
Random rand = new Random(0);
int keyBits = 32;
int hashBits = function.bits();
for (int i = 0; i < keyBits; i++) {
int[] same = new int[hashBits];
int[] diff = new int[hashBits];
// go through trials to compute probability
for (int j = 0; j < trials; j++) {
int key1 = rand.nextInt();
// flip input bit for key2
int key2 = key1 ^ (1 << i);
// compute hash values
int hash1 = function.newHasher().putInt(key1).hash().asInt();
int hash2 = function.newHasher().putInt(key2).hash().asInt();
for (int k = 0; k < hashBits; k++) {
if ((hash1 & (1 << k)) == (hash2 & (1 << k))) {
same[k] += 1;
} else {
diff[k] += 1;
}
}
}
// measure probability and assert it's within margin of error
for (int j = 0; j < hashBits; j++) {
double prob = (double) diff[j] / (double) (diff[j] + same[j]);
Assert.assertEquals(0.50d, prob, epsilon);
}
}
}
/**
* Test for 2-bit characteristics. A characteristic is a delta in the input which is repeated in
* the output. For example, if f() is a block cipher and c is a characteristic, then
* f(x^c) = f(x)^c with greater than expected probability. The test for funneling is merely a test
* for 1-bit characteristics.
*
* <p>There is more general code provided by Bob Jenkins to test arbitrarily sized characteristics
* using the magic of gaussian elimination: http://burtleburtle.net/bob/crypto/findingc.html.
*/
static void checkNo2BitCharacteristics(HashFunction function) {
Random rand = new Random(0);
int keyBits = 32;
// get every one of (keyBits choose 2) deltas:
for (int i = 0; i < keyBits; i++) {
for (int j = 0; j < keyBits; j++) {
if (j <= i) continue;
int count = 0;
int maxCount = 20; // the probability of error here is miniscule
boolean diff = false;
while (diff == false) {
int delta = (1 << i) | (1 << j);
int key1 = rand.nextInt();
// apply delta
int key2 = key1 ^ delta;
// get hashes
int hash1 = function.newHasher().putInt(key1).hash().asInt();
int hash2 = function.newHasher().putInt(key2).hash().asInt();
// this 2-bit candidate delta is not a characteristic
// if deltas are different
if ((hash1 ^ hash2) != delta) {
diff = true;
continue;
}
// check if we've exceeded the probabilistically
// likely number of trials to have proven 2-bit candidate
// is not a characteristic
count++;
if (count > maxCount) {
Assert.fail("2-bit delta (" + i + ", " + j + ") is likely a " +
"characteristic for this hash. This was " +
"determined after " + count + " trials");
}
}
}
}
}
/**
* Test for avalanche with 2-bit deltas. Most probabilities of output bit(j) differing are well
* within 50%.
*/
static void check2BitAvalanche(HashFunction function, int trials, double epsilon) {
Random rand = new Random(0);
int keyBits = 32;
int hashBits = function.bits();
for (int bit1 = 0; bit1 < keyBits; bit1++) {
for (int bit2 = 0; bit2 < keyBits; bit2++) {
if (bit2 <= bit1) continue;
int delta = (1 << bit1) | (1 << bit2);
int[] same = new int[hashBits];
int[] diff = new int[hashBits];
// go through trials to compute probability
for (int j = 0; j < trials; j++) {
int key1 = rand.nextInt();
// flip input bit for key2
int key2 = key1 ^ delta;
// compute hash values
int hash1 = function.newHasher().putInt(key1).hash().asInt();
int hash2 = function.newHasher().putInt(key2).hash().asInt();
for (int k = 0; k < hashBits; k++) {
if ((hash1 & (1 << k)) == (hash2 & (1 << k))) {
same[k] += 1;
} else {
diff[k] += 1;
}
}
}
// measure probability and assert it's within margin of error
for (int j = 0; j < hashBits; j++) {
double prob = (double) diff[j] / (double) (diff[j] + same[j]);
Assert.assertEquals(0.50d, prob, epsilon);
}
}
}
}
/**
* Checks that a Hasher returns the same HashCode when given the same input, and also
* that the collision rate looks sane.
*/
static void assertInvariants(HashFunction hashFunction) {
int objects = 100;
Set<HashCode> hashcodes = Sets.newHashSetWithExpectedSize(objects);
for (int i = 0; i < objects; i++) {
Object o = new Object();
HashCode hashcode1 = hashFunction.newHasher().putObject(o, HashTestUtils.BAD_FUNNEL).hash();
HashCode hashcode2 = hashFunction.newHasher().putObject(o, HashTestUtils.BAD_FUNNEL).hash();
Assert.assertEquals(hashcode1, hashcode2); // idempotent
Assert.assertEquals(hashFunction.bits(), hashcode1.bits());
Assert.assertEquals(hashFunction.bits(), hashcode1.asBytes().length * 8);
hashcodes.add(hashcode1);
}
Assert.assertTrue(hashcodes.size() > objects * 0.95); // quite relaxed test
assertHashBytesThrowsCorrectExceptions(hashFunction);
assertIndependentHashers(hashFunction);
assertShortcutsAreEquivalent(hashFunction, 512);
}
static void assertHashBytesThrowsCorrectExceptions(HashFunction hashFunction) {
hashFunction.hashBytes(new byte[64], 0, 0);
try {
hashFunction.hashBytes(new byte[128], -1, 128);
Assert.fail();
} catch (IndexOutOfBoundsException expected) {}
try {
hashFunction.hashBytes(new byte[128], 64, 256 /* too long len */);
Assert.fail();
} catch (IndexOutOfBoundsException expected) {}
try {
hashFunction.hashBytes(new byte[64], 0, -1);
Assert.fail();
} catch (IndexOutOfBoundsException expected) {}
}
static void assertIndependentHashers(HashFunction hashFunction) {
int numActions = 100;
// hashcodes from non-overlapping hash computations
HashCode expected1 = randomHash(hashFunction, new Random(1L), numActions);
HashCode expected2 = randomHash(hashFunction, new Random(2L), numActions);
// equivalent, but overlapping, computations (should produce the same results as above)
Random random1 = new Random(1L);
Random random2 = new Random(2L);
Hasher hasher1 = hashFunction.newHasher();
Hasher hasher2 = hashFunction.newHasher();
for (int i = 0; i < numActions; i++) {
RandomHasherAction.pickAtRandom(random1).performAction(random1, ImmutableSet.of(hasher1));
RandomHasherAction.pickAtRandom(random2).performAction(random2, ImmutableSet.of(hasher2));
}
Assert.assertEquals(expected1, hasher1.hash());
Assert.assertEquals(expected2, hasher2.hash());
}
static HashCode randomHash(HashFunction hashFunction, Random random, int numActions) {
Hasher hasher = hashFunction.newHasher();
for (int i = 0; i < numActions; i++) {
RandomHasherAction.pickAtRandom(random).performAction(random, ImmutableSet.of(hasher));
}
return hasher.hash();
}
private static void assertShortcutsAreEquivalent(HashFunction hashFunction, int trials) {
Random random = new Random(42085L);
for (int i = 0; i < trials; i++) {
assertHashBytesEquivalence(hashFunction, random);
assertHashIntEquivalence(hashFunction, random);
assertHashLongEquivalence(hashFunction, random);
assertHashStringEquivalence(hashFunction, random);
assertHashStringWithSurrogatesEquivalence(hashFunction, random);
}
}
private static void assertHashBytesEquivalence(HashFunction hashFunction, Random random) {
int size = random.nextInt(2048);
byte[] bytes = new byte[size];
random.nextBytes(bytes);
assertEquals(hashFunction.hashBytes(bytes),
hashFunction.newHasher(size).putBytes(bytes).hash());
int off = random.nextInt(size);
int len = random.nextInt(size - off);
assertEquals(hashFunction.hashBytes(bytes, off, len),
hashFunction.newHasher(size).putBytes(bytes, off, len).hash());
}
private static void assertHashIntEquivalence(HashFunction hashFunction, Random random) {
int i = random.nextInt();
assertEquals(hashFunction.hashInt(i),
hashFunction.newHasher().putInt(i).hash());
}
private static void assertHashLongEquivalence(HashFunction hashFunction, Random random) {
long l = random.nextLong();
assertEquals(hashFunction.hashLong(l),
hashFunction.newHasher().putLong(l).hash());
}
private static final ImmutableList<Charset> CHARSETS = ImmutableList.of(
Charsets.ISO_8859_1,
Charsets.US_ASCII,
Charsets.UTF_16,
Charsets.UTF_16BE,
Charsets.UTF_16LE,
Charsets.UTF_8);
private static void assertHashStringEquivalence(HashFunction hashFunction, Random random) {
int size = random.nextInt(2048);
byte[] bytes = new byte[size];
random.nextBytes(bytes);
String string = new String(bytes);
assertEquals(hashFunction.hashString(string),
hashFunction.newHasher().putString(string).hash());
// These assertions causes failures when testing with mvn. See b/6657789
// assertEquals(hashFunction.hashString(string),
// hashFunction.hashString(string, Charsets.UTF_16LE));
// assertEquals(hashFunction.hashString(string),
// hashFunction.newHasher().putString(string, Charsets.UTF_16LE).hash());
for (Charset charset : CHARSETS) {
assertEquals(hashFunction.hashString(string, charset),
hashFunction.newHasher().putString(string, charset).hash());
}
}
/**
* This verifies that putString(String) and hashString(String) are equivalent, even for
* funny strings composed by (possibly unmatched, and mostly illegal) surrogate characters.
* (But doesn't test that they do the right thing - just their consistency).
*/
private static void assertHashStringWithSurrogatesEquivalence(
HashFunction hashFunction, Random random) {
int size = random.nextInt(8) + 1;
char[] chars = new char[size];
for (int i = 0; i < chars.length; i++) {
chars[i] = random.nextBoolean() ? randomLowSurrogate(random) : randomHighSurrogate(random);
}
String string = new String(chars);
assertEquals(hashFunction.hashString(string),
hashFunction.newHasher().putString(string).hash());
}
static char randomLowSurrogate(Random random) {
return (char) (Character.MIN_LOW_SURROGATE
+ random.nextInt(Character.MAX_LOW_SURROGATE - Character.MIN_LOW_SURROGATE + 1));
}
static char randomHighSurrogate(Random random) {
return (char) (Character.MIN_HIGH_SURROGATE
+ random.nextInt(Character.MAX_HIGH_SURROGATE - Character.MIN_HIGH_SURROGATE + 1));
}
}
| Java |
/*
* 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.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Benchmarks for {@link CycleDetectingLockFactory}.
*
* @author Darick Tong
*/
public class CycleDetectingLockFactoryBenchmark extends SimpleBenchmark {
@Param({"2","3","4","5","10"}) int lockNestingDepth;
CycleDetectingLockFactory factory;
private Lock[] plainLocks;
private Lock[] detectingLocks;
@Override
protected void setUp() throws Exception {
super.setUp();
this.factory = CycleDetectingLockFactory.newInstance(
CycleDetectingLockFactory.Policies.WARN);
this.plainLocks = new Lock[lockNestingDepth];
for (int i = 0; i < lockNestingDepth; i++) {
plainLocks[i] = new ReentrantLock();
}
this.detectingLocks = new Lock[lockNestingDepth];
for (int i = 0; i < lockNestingDepth; i++) {
detectingLocks[i] = factory.newReentrantLock("Lock" + i);
}
}
public void timeUnorderedPlainLocks(int reps) {
lockAndUnlock(new ReentrantLock(), reps);
}
public void timeUnorderedCycleDetectingLocks(int reps) {
lockAndUnlock(factory.newReentrantLock("foo"), reps);
}
private void lockAndUnlock(Lock lock, int reps) {
for (int i = 0; i < reps; i++) {
lock.lock();
lock.unlock();
}
}
public void timeOrderedPlainLocks(int reps) {
lockAndUnlockNested(plainLocks, reps);
}
public void timeOrderedCycleDetectingLocks(int reps) {
lockAndUnlockNested(detectingLocks, reps);
}
private void lockAndUnlockNested(Lock[] locks, int reps) {
for (int i = 0; i < reps; i++) {
for (int j = 0; j < locks.length; j++) {
locks[j].lock();
}
for (int j = locks.length - 1; j >= 0; j--) {
locks[j].unlock();
}
}
}
public static void main(String[] args) {
Runner.main(CycleDetectingLockFactoryBenchmark.class, args);
}
}
| Java |
/*
* 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.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import java.lang.reflect.Constructor;
import java.util.concurrent.BlockingQueue;
/**
* Benchmarks for {@link Monitor}.
*
* @author Justin T. Sampson
*/
public class MonitorBenchmark extends SimpleBenchmark {
@Param({"10", "100", "1000"}) int capacity;
@Param({"Array", "Priority"}) String queueType;
@Param boolean useMonitor;
private BlockingQueue<String> queue;
private String[] strings;
@Override
@SuppressWarnings("unchecked")
protected void setUp() throws Exception {
String prefix =
(useMonitor ? "com.google.common.util.concurrent.MonitorBased" : "java.util.concurrent.");
String className = prefix + queueType + "BlockingQueue";
Constructor<?> constructor = Class.forName(className).getConstructor(int.class);
queue = (BlockingQueue<String>) constructor.newInstance(capacity);
strings = new String[capacity];
for (int i = 0; i < capacity; i++) {
strings[i] = String.valueOf(Math.random());
}
}
public void timeAddsAndRemoves(int reps) {
int capacity = this.capacity;
BlockingQueue<String> queue = this.queue;
String[] strings = this.strings;
for (int i = 0; i < reps; i++) {
for (int j = 0; j < capacity; j++) {
queue.add(strings[j]);
}
for (int j = 0; j < capacity; j++) {
queue.remove();
}
}
}
public static void main(String[] args) {
Runner.main(MonitorBenchmark.class, args);
}
}
| Java |
/*
* 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.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static com.google.common.math.MathBenchmarking.randomDouble;
import static com.google.common.math.MathBenchmarking.randomPositiveDouble;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
/**
* Tests for the non-rounding methods of {@code DoubleMath}.
*
* @author Louis Wasserman
*/
public class DoubleMathBenchmark extends SimpleBenchmark {
private static final double[] positiveDoubles = new double[ARRAY_SIZE];
private static final int[] factorials = new int[ARRAY_SIZE];
private static final double [] doubles = new double[ARRAY_SIZE];
@Override
protected void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
positiveDoubles[i] = randomPositiveDouble();
doubles[i] = randomDouble(Long.SIZE);
factorials[i] = RANDOM_SOURCE.nextInt(100);
}
}
public long timeLog2(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += Double.doubleToRawLongBits(DoubleMath.log2(positiveDoubles[j]));
}
return tmp;
}
public long timeFactorial(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += Double.doubleToRawLongBits(DoubleMath.factorial(factorials[j]));
}
return tmp;
}
public int timeIsMathematicalInteger(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (DoubleMath.isMathematicalInteger(doubles[j])) {
tmp++;
}
}
return tmp;
}
public int timeIsPowerOfTwo(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (DoubleMath.isPowerOfTwo(doubles[j])) {
tmp++;
}
}
return tmp;
}
public static void main(String[] args) {
Runner.main(DoubleMathBenchmark.class, args);
}
}
| Java |
/*
* 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.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static com.google.common.math.MathBenchmarking.randomBigInteger;
import static com.google.common.math.MathBenchmarking.randomNonNegativeBigInteger;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.math.DoubleMath;
import com.google.common.math.IntMath;
import com.google.common.math.LongMath;
/**
* Benchmarks against the Apache Commons Math utilities.
*
* <p>Note: the Apache benchmarks are not open sourced to avoid the extra dependency.
*
* @author Louis Wasserman
*/
public class ApacheBenchmark extends SimpleBenchmark {
private enum Impl {
GUAVA {
@Override
public double factorialDouble(int n) {
return DoubleMath.factorial(n);
}
@Override
public int gcdInt(int a, int b) {
return IntMath.gcd(a, b);
}
@Override
public long gcdLong(long a, long b) {
return LongMath.gcd(a, b);
}
@Override
public long binomialCoefficient(int n, int k) {
return LongMath.binomial(n, k);
}
@Override
public boolean noAddOverflow(int a, int b) {
try {
IntMath.checkedAdd(a, b);
return true;
} catch (ArithmeticException e) {
return false;
}
}
@Override
public boolean noAddOverflow(long a, long b) {
try {
LongMath.checkedAdd(a, b);
return true;
} catch (ArithmeticException e) {
return false;
}
}
@Override
public boolean noMulOverflow(int a, int b) {
try {
IntMath.checkedMultiply(a, b);
return true;
} catch (ArithmeticException e) {
return false;
}
}
@Override
public boolean noMulOverflow(long a, long b) {
try {
LongMath.checkedMultiply(a, b);
return true;
} catch (ArithmeticException e) {
return false;
}
}
};
public abstract double factorialDouble(int n);
public abstract long binomialCoefficient(int n, int k);
public abstract int gcdInt(int a, int b);
public abstract long gcdLong(long a, long b);
public abstract boolean noAddOverflow(int a, int b);
public abstract boolean noAddOverflow(long a, long b);
public abstract boolean noMulOverflow(int a, int b);
public abstract boolean noMulOverflow(long a, long b);
}
private final int[] factorials = new int[ARRAY_SIZE];
private final int[][] binomials = new int[ARRAY_SIZE][2];
private final int[][] nonnegInt = new int[ARRAY_SIZE][2];
private final long[][] nonnegLong = new long[ARRAY_SIZE][2];
private final int[][] intsToAdd = new int[ARRAY_SIZE][2];
private final int[][] intsToMul = new int[ARRAY_SIZE][2];
private final long[][] longsToAdd = new long[ARRAY_SIZE][2];
private final long[][] longsToMul = new long[ARRAY_SIZE][2];
@Param({"APACHE", "GUAVA"})
Impl impl;
@Override
protected void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
factorials[i] = RANDOM_SOURCE.nextInt(200);
for (int j = 0; j < 2; j++) {
nonnegInt[i][j] = randomNonNegativeBigInteger(Integer.SIZE - 2).intValue();
nonnegLong[i][j] = randomNonNegativeBigInteger(Long.SIZE - 2).longValue();
}
do {
for (int j = 0; j < 2; j++) {
intsToAdd[i][j] = randomBigInteger(Integer.SIZE - 2).intValue();
}
} while (!Impl.GUAVA.noAddOverflow(intsToAdd[i][0], intsToAdd[i][1]));
do {
for (int j = 0; j < 2; j++) {
longsToAdd[i][j] = randomBigInteger(Long.SIZE - 2).longValue();
}
} while (!Impl.GUAVA.noAddOverflow(longsToAdd[i][0], longsToAdd[i][1]));
do {
for (int j = 0; j < 2; j++) {
intsToMul[i][j] = randomBigInteger(Integer.SIZE - 2).intValue();
}
} while (!Impl.GUAVA.noMulOverflow(intsToMul[i][0], intsToMul[i][1]));
do {
for (int j = 0; j < 2; j++) {
longsToMul[i][j] = randomBigInteger(Long.SIZE - 2).longValue();
}
} while (!Impl.GUAVA.noMulOverflow(longsToMul[i][0], longsToMul[i][1]));
int k = binomials[i][1] = RANDOM_SOURCE.nextInt(MathBenchmarking.BIGGEST_BINOMIALS.length);
binomials[i][0] = RANDOM_SOURCE.nextInt(MathBenchmarking.BIGGEST_BINOMIALS[k] - k) + k;
}
}
public long timeFactorialDouble(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += Double.doubleToRawLongBits(impl.factorialDouble(factorials[j]));
}
return tmp;
}
public int timeIntGCD(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += impl.gcdInt(nonnegInt[j][0], nonnegInt[j][1]);
}
return tmp;
}
public long timeLongGCD(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += impl.gcdLong(nonnegLong[j][0], nonnegLong[j][1]);
}
return tmp;
}
public long timeBinomialCoefficient(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += impl.binomialCoefficient(binomials[j][0], binomials[j][1]);
}
return tmp;
}
public int timeIntAddOverflow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (impl.noAddOverflow(intsToAdd[j][0], intsToAdd[j][1])) {
tmp++;
}
}
return tmp;
}
public int timeLongAddOverflow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (impl.noAddOverflow(longsToAdd[j][0], longsToAdd[j][1])) {
tmp++;
}
}
return tmp;
}
public int timeIntMulOverflow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (impl.noMulOverflow(intsToMul[j][0], intsToMul[j][1])) {
tmp++;
}
}
return tmp;
}
public int timeLongMulOverflow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
if (impl.noMulOverflow(longsToMul[j][0], longsToMul[j][1])) {
tmp++;
}
}
return tmp;
}
public static void main(String[] args) {
Runner.main(ApacheBenchmark.class, args);
}
}
| Java |
/*
* 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.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static java.math.RoundingMode.CEILING;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.math.BigIntegerMath;
import com.google.common.math.IntMath;
import com.google.common.math.LongMath;
import java.math.BigInteger;
/**
* Benchmarks for the non-rounding methods of {@code BigIntegerMath}.
*
* @author Louis Wasserman
*/
public class BigIntegerMathBenchmark extends SimpleBenchmark {
private static final int[] factorials = new int[ARRAY_SIZE];
private static final int[] slowFactorials = new int[ARRAY_SIZE];
private static final int[] binomials = new int[ARRAY_SIZE];
@Param({"50", "1000", "10000"})
int factorialBound;
@Override
protected void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
factorials[i] = RANDOM_SOURCE.nextInt(factorialBound);
slowFactorials[i] = RANDOM_SOURCE.nextInt(factorialBound);
binomials[i] = RANDOM_SOURCE.nextInt(factorials[i] + 1);
}
}
/**
* Previous version of BigIntegerMath.factorial, kept for timing purposes.
*/
private static BigInteger slowFactorial(int n) {
if (n <= 20) {
return BigInteger.valueOf(LongMath.factorial(n));
} else {
int k = 20;
return BigInteger.valueOf(LongMath.factorial(k)).multiply(slowFactorial(k, n));
}
}
/**
* Returns the product of {@code n1} exclusive through {@code n2} inclusive.
*/
private static BigInteger slowFactorial(int n1, int n2) {
assert n1 <= n2;
if (IntMath.log2(n2, CEILING) * (n2 - n1) < Long.SIZE - 1) {
// the result will definitely fit into a long
long result = 1;
for (int i = n1 + 1; i <= n2; i++) {
result *= i;
}
return BigInteger.valueOf(result);
}
/*
* We want each multiplication to have both sides with approximately the same number of digits.
* Currently, we just divide the range in half.
*/
int mid = (n1 + n2) >>> 1;
return slowFactorial(n1, mid).multiply(slowFactorial(mid, n2));
}
public int timeSlowFactorial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += slowFactorial(slowFactorials[j]).intValue();
}
return tmp;
}
public int timeFactorial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += BigIntegerMath.factorial(factorials[j]).intValue();
}
return tmp;
}
public int timeBinomial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & 0xffff;
tmp += BigIntegerMath.binomial(factorials[j], binomials[j]).intValue();
}
return tmp;
}
public static void main(String[] args) {
Runner.main(BigIntegerMathBenchmark.class, args);
}
}
| Java |
/*
* 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.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.randomDouble;
import static com.google.common.math.MathBenchmarking.randomPositiveDouble;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.math.DoubleMath;
import java.math.RoundingMode;
/**
* Benchmarks for the rounding methods of {@code DoubleMath}.
*
* @author Louis Wasserman
*/
public class DoubleMathRoundingBenchmark extends SimpleBenchmark {
private static final double[] doubleInIntRange = new double[ARRAY_SIZE];
private static final double[] doubleInLongRange = new double[ARRAY_SIZE];
private static final double[] positiveDoubles = new double[ARRAY_SIZE];
@Param({"DOWN", "UP", "FLOOR", "CEILING", "HALF_EVEN", "HALF_UP", "HALF_DOWN"})
RoundingMode mode;
@Override
protected void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
doubleInIntRange[i] = randomDouble(Integer.SIZE - 2);
doubleInLongRange[i] = randomDouble(Long.SIZE - 2);
positiveDoubles[i] = randomPositiveDouble();
}
}
public int timeRoundToInt(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += DoubleMath.roundToInt(doubleInIntRange[j], mode);
}
return tmp;
}
public long timeRoundToLong(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += DoubleMath.roundToLong(doubleInLongRange[j], mode);
}
return tmp;
}
public int timeRoundToBigInteger(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += DoubleMath.roundToBigInteger(positiveDoubles[j], mode).intValue();
}
return tmp;
}
public int timeLog2Round(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += DoubleMath.log2(positiveDoubles[j], mode);
}
return tmp;
}
public static void main(String[] args) {
Runner.main(DoubleMathRoundingBenchmark.class, args);
}
}
| Java |
/*
* 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.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.randomNonZeroBigInteger;
import static com.google.common.math.MathBenchmarking.randomPositiveBigInteger;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.math.BigIntegerMath;
import java.math.BigInteger;
import java.math.RoundingMode;
/**
* Benchmarks for the rounding methods of {@code BigIntegerMath}.
*
* @author Louis Wasserman
*/
public class BigIntegerMathRoundingBenchmark extends SimpleBenchmark {
private static final BigInteger[] nonzero1 = new BigInteger[ARRAY_SIZE];
private static final BigInteger[] nonzero2 = new BigInteger[ARRAY_SIZE];
private static final BigInteger[] positive = new BigInteger[ARRAY_SIZE];
@Param({"DOWN", "UP", "FLOOR", "CEILING", "HALF_EVEN", "HALF_UP", "HALF_DOWN"})
RoundingMode mode;
@Override
protected void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
positive[i] = randomPositiveBigInteger(1024);
nonzero1[i] = randomNonZeroBigInteger(1024);
nonzero2[i] = randomNonZeroBigInteger(1024);
}
}
public int timeLog2(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += BigIntegerMath.log2(positive[j], mode);
}
return tmp;
}
public int timeLog10(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += BigIntegerMath.log10(positive[j], mode);
}
return tmp;
}
public int timeSqrt(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += BigIntegerMath.sqrt(positive[j], mode).intValue();
}
return tmp;
}
public int timeDivide(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += BigIntegerMath.divide(nonzero1[j], nonzero2[j], mode).intValue();
}
return tmp;
}
public static void main(String[] args) {
Runner.main(BigIntegerMathRoundingBenchmark.class, args);
}
}
| Java |
/*
* 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.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static com.google.common.math.MathBenchmarking.randomExponent;
import static com.google.common.math.MathBenchmarking.randomNonNegativeBigInteger;
import static com.google.common.math.MathBenchmarking.randomPositiveBigInteger;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.math.LongMath;
/**
* Benchmarks for the non-rounding methods of {@code LongMath}.
*
* @author Louis Wasserman
*/
public class LongMathBenchmark extends SimpleBenchmark {
private static final int[] exponents = new int[ARRAY_SIZE];
private static final int[] factorialArguments = new int[ARRAY_SIZE];
private static final int[][] binomialArguments = new int[ARRAY_SIZE][2];
private static final long[] positive = new long[ARRAY_SIZE];
private static final long[] nonnegative = new long[ARRAY_SIZE];
private static final long[] longs = new long[ARRAY_SIZE];
@Override
protected void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
exponents[i] = randomExponent();
positive[i] = randomPositiveBigInteger(Long.SIZE - 2).longValue();
nonnegative[i] = randomNonNegativeBigInteger(Long.SIZE - 2).longValue();
longs[i] = RANDOM_SOURCE.nextLong();
factorialArguments[i] = RANDOM_SOURCE.nextInt(30);
binomialArguments[i][1] = RANDOM_SOURCE.nextInt(MathBenchmarking.BIGGEST_BINOMIALS.length);
int k = binomialArguments[i][1];
binomialArguments[i][0] =
RANDOM_SOURCE.nextInt(MathBenchmarking.BIGGEST_BINOMIALS[k] - k) + k;
}
}
public int timePow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.pow(positive[j], exponents[j]);
}
return tmp;
}
public int timeMod(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.mod(longs[j], positive[j]);
}
return tmp;
}
public int timeGCD(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.mod(nonnegative[j], positive[j]);
}
return tmp;
}
public int timeFactorial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.factorial(factorialArguments[j]);
}
return tmp;
}
public int timeBinomial(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.binomial(binomialArguments[j][0], binomialArguments[j][1]);
}
return tmp;
}
public static void main(String[] args) {
Runner.main(LongMathBenchmark.class, args);
}
}
| Java |
/*
* 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.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static com.google.common.math.MathBenchmarking.randomNonZeroBigInteger;
import static com.google.common.math.MathBenchmarking.randomPositiveBigInteger;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.math.IntMath;
import java.math.RoundingMode;
/**
* Benchmarks for the rounding methods of {@code IntMath}.
*
* @author Louis Wasserman
*/
public class IntMathRoundingBenchmark extends SimpleBenchmark {
private static final int[] positive = new int[ARRAY_SIZE];
private static final int[] nonzero = new int[ARRAY_SIZE];
private static final int[] ints = new int[ARRAY_SIZE];
@Override
protected void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
positive[i] = randomPositiveBigInteger(Integer.SIZE - 2).intValue();
nonzero[i] = randomNonZeroBigInteger(Integer.SIZE - 2).intValue();
ints[i] = RANDOM_SOURCE.nextInt();
}
}
@Param({"DOWN", "UP", "FLOOR", "CEILING", "HALF_EVEN", "HALF_UP", "HALF_DOWN"})
RoundingMode mode;
public int timeLog2(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.log2(positive[j], mode);
}
return tmp;
}
public int timeLog10(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.log10(positive[j], mode);
}
return tmp;
}
public int timeSqrt(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.sqrt(positive[j], mode);
}
return tmp;
}
public int timeDivide(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.divide(ints[j], nonzero[j], mode);
}
return tmp;
}
public static void main(String[] args) {
Runner.main(IntMathRoundingBenchmark.class, args);
}
}
| Java |
/*
* 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.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static com.google.common.math.MathBenchmarking.randomNonZeroBigInteger;
import static com.google.common.math.MathBenchmarking.randomPositiveBigInteger;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.math.LongMath;
import java.math.RoundingMode;
/**
* Benchmarks for the rounding methods of {@code LongMath}.
*
* @author Louis Wasserman
*/
public class LongMathRoundingBenchmark extends SimpleBenchmark {
@Param({"DOWN", "UP", "FLOOR", "CEILING", "HALF_EVEN", "HALF_UP", "HALF_DOWN"})
RoundingMode mode;
private static final long[] positive = new long[ARRAY_SIZE];
private static final long[] nonzero = new long[ARRAY_SIZE];
private static final long[] longs = new long[ARRAY_SIZE];
@Override
protected void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
positive[i] = randomPositiveBigInteger(Long.SIZE - 2).longValue();
nonzero[i] = randomNonZeroBigInteger(Long.SIZE - 2).longValue();
longs[i] = RANDOM_SOURCE.nextLong();
}
}
public int timeLog2(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.log2(positive[j], mode);
}
return tmp;
}
public int timeLog10(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.log10(positive[j], mode);
}
return tmp;
}
public int timeSqrt(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.sqrt(positive[j], mode);
}
return tmp;
}
public int timeDivide(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += LongMath.divide(longs[j], nonzero[j], mode);
}
return tmp;
}
public static void main(String[] args) {
Runner.main(LongMathRoundingBenchmark.class, args);
}
}
| Java |
/*
* 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.math.MathBenchmarking.ARRAY_MASK;
import static com.google.common.math.MathBenchmarking.ARRAY_SIZE;
import static com.google.common.math.MathBenchmarking.RANDOM_SOURCE;
import static com.google.common.math.MathBenchmarking.randomExponent;
import static com.google.common.math.MathBenchmarking.randomNonNegativeBigInteger;
import static com.google.common.math.MathBenchmarking.randomPositiveBigInteger;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.math.IntMath;
/**
* Benchmarks for the non-rounding methods of {@code IntMath}.
*
* @author Louis Wasserman
*/
public class IntMathBenchmark extends SimpleBenchmark {
private static int[] exponent = new int[ARRAY_SIZE];
private static int[] factorial = new int[ARRAY_SIZE];
private static int[] binomial = new int[ARRAY_SIZE];
private static final int[] positive = new int[ARRAY_SIZE];
private static final int[] nonnegative = new int[ARRAY_SIZE];
private static final int[] ints = new int[ARRAY_SIZE];
@Override
protected void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
exponent[i] = randomExponent();
factorial[i] = RANDOM_SOURCE.nextInt(50);
binomial[i] = RANDOM_SOURCE.nextInt(factorial[i] + 1);
positive[i] = randomPositiveBigInteger(Integer.SIZE - 2).intValue();
nonnegative[i] = randomNonNegativeBigInteger(Integer.SIZE - 2).intValue();
ints[i] = RANDOM_SOURCE.nextInt();
}
}
public int timePow(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.pow(positive[j], exponent[j]);
}
return tmp;
}
public int timeMod(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.mod(ints[j], positive[j]);
}
return tmp;
}
public int timeGCD(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.gcd(nonnegative[j], positive[j]);
}
return tmp;
}
public int timeFactorial(int reps){
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.factorial(factorial[j]);
}
return tmp;
}
public int timeBinomial(int reps){
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += IntMath.binomial(factorial[j], binomial[j]);
}
return tmp;
}
public static void main(String[] args) {
Runner.main(IntMathBenchmark.class, args);
}
}
| Java |
/*
* 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.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import java.util.Random;
/**
* Benchmarks for certain methods of {@code UnsignedLongs}.
*
* @author Eamonn McManus
*/
public class UnsignedLongsBenchmark extends SimpleBenchmark {
private static final int ARRAY_SIZE = 0x10000;
private static final int ARRAY_MASK = 0x0ffff;
private static final Random RANDOM_SOURCE = new Random(314159265358979L);
private static final long[] longs = new long[ARRAY_SIZE];
private static final long[] divisors = new long[ARRAY_SIZE];
private static final String[] decimalStrings = new String[ARRAY_SIZE];
private static final String[] binaryStrings = new String[ARRAY_SIZE];
private static final String[] hexStrings = new String[ARRAY_SIZE];
private static final String[] prefixedHexStrings = new String[ARRAY_SIZE];
@Override
protected void setUp() {
for (int i = 0; i < ARRAY_SIZE; i++) {
longs[i] = random();
divisors[i] = randomDivisor(longs[i]);
decimalStrings[i] = UnsignedLongs.toString(longs[i]);
binaryStrings[i] = UnsignedLongs.toString(longs[i], 2);
hexStrings[i] = UnsignedLongs.toString(longs[i], 16);
prefixedHexStrings[i] = "0x" + hexStrings[i];
}
}
public long timeDivide(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += UnsignedLongs.divide(longs[j], divisors[j]);
}
return tmp;
}
public long timeRemainder(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += UnsignedLongs.remainder(longs[j], divisors[j]);
}
return tmp;
}
public long timeParseUnsignedLong(int reps) {
long tmp = 0;
// Given that we make three calls per pass, we scale reps down in order
// to do a comparable amount of work to other measurements.
int scaledReps = reps / 3 + 1;
for (int i = 0; i < scaledReps; i++) {
int j = i & ARRAY_MASK;
tmp += UnsignedLongs.parseUnsignedLong(decimalStrings[j]);
tmp += UnsignedLongs.parseUnsignedLong(hexStrings[j], 16);
tmp += UnsignedLongs.parseUnsignedLong(binaryStrings[j], 2);
}
return tmp;
}
public long timeParseDecode10(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += UnsignedLongs.decode(decimalStrings[j]);
}
return tmp;
}
public long timeParseDecode16(int reps) {
long tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += UnsignedLongs.decode(prefixedHexStrings[j]);
}
return tmp;
}
public int timeToString(int reps) {
int tmp = 0;
// Given that we make three calls per pass, we scale reps down in order
// to do a comparable amount of work to other measurements.
int scaledReps = reps / 3 + 1;
for (int i = 0; i < scaledReps; i++) {
int j = i & ARRAY_MASK;
long x = longs[j];
tmp += UnsignedLongs.toString(x).length();
tmp += UnsignedLongs.toString(x, 16).length();
tmp += UnsignedLongs.toString(x, 2).length();
}
return tmp;
}
private static long random() {
return RANDOM_SOURCE.nextLong();
}
// A random value that cannot be 0 and that is unsigned-less-than or equal
// to the given dividend, so that we don't have half of our divisions being
// trivial because the divisor is bigger than the dividend.
// Using remainder here does not give us a uniform distribution but it should
// not have a big impact on the measurement.
private static long randomDivisor(long dividend) {
long r = RANDOM_SOURCE.nextLong();
if (dividend == -1) {
return r;
} else {
return UnsignedLongs.remainder(r, dividend + 1);
}
}
public static void main(String[] args) {
Runner.main(UnsignedLongsBenchmark.class, args);
}
}
| Java |
/*
* 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.primitives;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Random;
/**
* Microbenchmark for {@link UnsignedBytes}.
*
* @author Hiroshi Yamauchi
*/
public class UnsignedBytesBenchmark extends SimpleBenchmark {
private byte[] ba1;
private byte[] ba2;
private byte[] ba3;
private byte[] ba4;
private Comparator<byte[]> javaImpl;
private Comparator<byte[]> unsafeImpl;
// 4, 8, 64, 1K, 1M, 1M (unaligned), 64M, 64M (unaligned)
//@Param({"4", "8", "64", "1024", "1048576", "1048577", "6710884", "6710883"})
@Param({"4", "8", "64", "1024" })
private int length;
@Override
protected void setUp() throws Exception {
Random r = new Random();
ba1 = new byte[length];
r.nextBytes(ba1);
ba2 = Arrays.copyOf(ba1, ba1.length);
// Differ at the last element
ba3 = Arrays.copyOf(ba1, ba1.length);
ba4 = Arrays.copyOf(ba1, ba1.length);
ba3[ba1.length - 1] = (byte) 43;
ba4[ba1.length - 1] = (byte) 42;
javaImpl = UnsignedBytes.lexicographicalComparatorJavaImpl();
unsafeImpl =
UnsignedBytes.LexicographicalComparatorHolder.UnsafeComparator.INSTANCE;
}
public void timeLongEqualJava(int reps) {
for (int i = 0; i < reps; ++i) {
if (javaImpl.compare(ba1, ba2) != 0) {
throw new Error(); // deoptimization
}
}
}
public void timeLongEqualUnsafe(int reps) {
for (int i = 0; i < reps; ++i) {
if (unsafeImpl.compare(ba1, ba2) != 0) {
throw new Error(); // deoptimization
}
}
}
public void timeDiffLastJava(int reps) {
for (int i = 0; i < reps; ++i) {
if (javaImpl.compare(ba3, ba4) == 0) {
throw new Error(); // deoptimization
}
}
}
public void timeDiffLastUnsafe(int reps) {
for (int i = 0; i < reps; ++i) {
if (unsafeImpl.compare(ba3, ba4) == 0) {
throw new Error(); // deoptimization
}
}
}
public static void main(String[] args) {
/*
try {
UnsignedBytesBenchmark bench = new UnsignedBytesBenchmark();
bench.length = 1024;
bench.setUp();
bench.timeUnsafe(100000);
} catch (Exception e) {
}*/
Runner.main(UnsignedBytesBenchmark.class, args);
}
}
| Java |
/*
* 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 com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.base.Ascii;
import com.google.common.collect.Lists;
import com.google.common.primitives.Chars;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import java.util.Random;
/**
* Benchmarks for the ASCII class.
*
* @author Kevin Bourrillion
*/
public class AsciiBenchmark extends SimpleBenchmark {
private static String ALPHA =
"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
private static String NONALPHA =
"0123456789`~-_=+[]{}|;:',.<>/?!@#$%^&*()\"\\";
@Param({"20", "2000"}) int size;
@Param({"2", "20"}) int nonAlphaRatio; // one non-alpha char per this many chars
@Param boolean noWorkToDo;
Random random;
String testString;
@Override protected void setUp() {
random = new Random();
int nonAlpha = size / nonAlphaRatio;
int alpha = size - nonAlpha;
List<Character> chars = Lists.newArrayListWithCapacity(size);
for (int i = 0; i < alpha; i++) {
chars.add(randomAlpha());
}
for (int i = 0; i < nonAlpha; i++) {
chars.add(randomNonAlpha());
}
Collections.shuffle(chars, random);
char[] array = Chars.toArray(chars);
this.testString = new String(array);
}
private char randomAlpha() {
return ALPHA.charAt(random.nextInt(ALPHA.length()));
}
private char randomNonAlpha() {
return NONALPHA.charAt(random.nextInt(NONALPHA.length()));
}
public int timeAsciiToUpperCase(int reps) {
String string = noWorkToDo
? Ascii.toUpperCase(testString)
: testString;
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += Ascii.toUpperCase(string).length();
}
return dummy;
}
public int timeStringToUpperCase1(int reps) {
String string = noWorkToDo
? testString.toUpperCase()
: testString;
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += string.toUpperCase().length();
}
return dummy;
}
public int timeStringToUpperCase2(int reps) {
String string = noWorkToDo
? testString.toUpperCase(Locale.US)
: testString;
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += string.toUpperCase(Locale.US).length();
}
return dummy;
}
public static void main(String[] args) {
Runner.main(AsciiBenchmark.class, args);
}
}
| Java |
/*
* 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.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.collect.Iterables;
/**
* Microbenchmark for {@link Splitter#on} with char vs String with length == 1.
*
* @author Paul Lindner
*/
public class SplitterBenchmark extends SimpleBenchmark {
// overall size of string
@Param({"1", "10", "100", "1000"}) int length;
// Number of matching strings
@Param({"xxxx", "xxXx", "xXxX", "XXXX"}) String text;
private String input;
private static final Splitter CHAR_SPLITTER = Splitter.on('X');
private static final Splitter STRING_SPLITTER = Splitter.on("X");
@Override protected void setUp() {
input = Strings.repeat(text, length);
}
public void timeCharSplitter(int reps) {
int total = 0;
for (int i = 0; i < reps; i++) {
total += Iterables.size(CHAR_SPLITTER.split(input));
}
}
public void timeStringSplitter(int reps) {
int total = 0;
for (int i = 0; i < reps; i++) {
total += Iterables.size(STRING_SPLITTER.split(input));
}
}
public static void main(String[] args) {
Runner.main(SplitterBenchmark.class, args);
}
}
| Java |
/*
* 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 com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.base.Stopwatch;
import java.util.concurrent.TimeUnit;
/**
* Simple benchmark: create, start, read. This does not currently report the
* most useful result because it's ambiguous to what extent the stopwatch
* benchmark is being affected by GC.
*
* @author Kevin Bourrillion
*/
public class StopwatchBenchmark extends SimpleBenchmark {
public long timeStopwatch(int reps) {
long total = 0;
for (int i = 0; i < reps; i++) {
Stopwatch s = new Stopwatch().start();
// here is where you would do something
total += s.elapsedTime(TimeUnit.NANOSECONDS);
}
return total;
}
public long timeManual(int reps) {
long total = 0;
for (int i = 0; i < reps; i++) {
long start = System.nanoTime();
// here is where you would do something
total += (System.nanoTime() - start);
}
return total;
}
public static void main(String[] args) {
Runner.main(StopwatchBenchmark.class, args);
}
}
| Java |
/*
* 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 com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.collect.Lists;
import java.util.BitSet;
import java.util.Collections;
import java.util.List;
import java.util.Random;
public class CharMatcherBenchmark extends SimpleBenchmark {
private static final String WHITESPACE_CHARACTERS =
"\u00a0\u180e\u202f\t\n\013\f\r \u0085"
+ "\u1680\u2028\u2029\u205f\u3000\u2000\u2001\u2002\u2003\u2004\u2005"
+ "\u2006\u2007\u2008\u2009\u200a";
private static final String ASCII_CHARACTERS;
static {
final int SPACE_IN_ASCII = 32;
final int SEVEN_BIT_ASCII_MAX = 128;
StringBuilder sb = new StringBuilder(SEVEN_BIT_ASCII_MAX - SPACE_IN_ASCII);
for (int ch = SPACE_IN_ASCII; ch < SEVEN_BIT_ASCII_MAX; ch++) {
sb.append((char) ch);
}
ASCII_CHARACTERS = sb.toString();
}
private static final String ALL_DIGITS;
static {
final StringBuilder sb = new StringBuilder();
final String ZEROS =
"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";
for (char base : ZEROS.toCharArray()) {
for (int offset = 0; offset < 10; offset++) {
sb.append((char) (base + offset));
}
}
ALL_DIGITS = sb.toString();
}
// Caliper injects params automatically
// Overall configuration
@Param MatcherConfig config;
// Length of string to match against
@Param({"64", "1024"}) int length;
// Percent of string that the CharMatcher matches
@Param({"0", "10", "50", "100"}) int percent;
// Whether to use a precomputed CharMatcher
@Param("true") boolean precomputed;
@Param({"none", "small", "medium"}) String size;
// Whether to ensure there is a matching character in the first position
// to force the trimming code to run.
@Param("false") boolean forceSlow;
// Use web-derived sampler.
@Param("false") boolean web;
private CharMatcher matcher;
private String string;
// Caliper invokes setUp() after injecting params
@Override protected void setUp() {
this.matcher = precomputed ? config.matcher.precomputed() : config.matcher;
if (size.equals("small") || size.equals("medium")) {
BitSet tmp = new BitSet();
matcher.setBits(tmp);
int matchedCharCount = tmp.cardinality();
if (size.equals("small") && matchedCharCount <= SmallCharMatcher.MAX_SIZE) {
this.matcher = SmallCharMatcher.from(tmp, "");
} else if (size.equals("medium")) {
this.matcher = MediumCharMatcher.from(tmp, "");
}
}
this.string = checkString(length, percent, config.matchingChars,
new Random(), forceSlow, web);
}
// Caliper recognizes int-parameter methods beginning with "time"
public int timeTrimAndCollapseFromString(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += matcher.trimAndCollapseFrom(string, '!').length();
}
return dummy;
}
public int timeMatches(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += matcher.matches(string.charAt(i % string.length())) ? 1 : 0;
}
return dummy;
}
public enum MatcherConfig {
whitespace(CharMatcher.WHITESPACE, WHITESPACE_CHARACTERS),
hash(CharMatcher.is('#'), "#"),
ascii(CharMatcher.ASCII, ASCII_CHARACTERS),
western_digit(CharMatcher.anyOf("0123456789"), "0123456789"),
all_digit(CharMatcher.DIGIT, ALL_DIGITS),
;
public final CharMatcher matcher;
public final String matchingChars;
MatcherConfig(CharMatcher matcher, String matchingChars) {
this.matcher = matcher;
this.matchingChars = matchingChars;
}
}
private static final String NONMATCHING_CHARS =
"abcdefghijklmnopqrstuvwxyz0123456789";
private static String checkString(int length, int percent,
String matchingChars, Random rand, boolean forceSlow, boolean web) {
// Check whether we should ignore everything else and pull from the web.
if (web) {
StringBuilder builder = new StringBuilder(length);
CharSamples sampler = new CharSamples(rand);
for (int i = 0; i < length; i++) {
int cp = sampler.nextCodePoint();
builder.appendCodePoint(cp);
}
return builder.toString();
}
// Use a shuffled index array to ensure constant percentage of matching
// characters
List<Integer> list = Lists.newArrayList();
for (int i = 0; i < length; i++) {
list.add(i);
}
Collections.shuffle(list, rand);
if (forceSlow) {
// Move zero index to front to force a matching character (if percent > 0)
list.set(list.indexOf(0), list.get(0));
list.set(0, 0);
}
// Get threshold in the range [0, length], rounding up to ensure that non
// zero percent values result in a non-zero threshold (so we always have at
// least one matching character).
int threshold = ((percent * length) + 99) / 100;
StringBuilder builder = new StringBuilder(length);
for (int n = 0; n < length; n++) {
builder.append(randomCharFrom(
list.get(n) >= threshold ? NONMATCHING_CHARS : matchingChars, rand));
}
return builder.toString();
}
private static char randomCharFrom(String s, Random rand) {
return s.charAt(rand.nextInt(s.length()));
}
public static void main(String[] args) {
Runner.main(CharMatcherBenchmark.class, args);
}
/**
* Provides samples on a random distribution derived from the web.
*
* Adapted from data provided by Mark Davis.
*
* @author Christopher Swenson
*/
static class CharSamples {
static {
populateProb1();
populateProb2();
populateChars1();
populateChars2();
}
private final Random random;
public CharSamples(Random random) {
this.random = random;
}
public int nextCodePoint() {
int needle = random.nextInt(sum);
int l = 0;
int r = prob.length - 1;
int c = prob.length / 2;
int lv = prob[l];
int rv = prob[r];
int cv = prob[c];
while (true) {
if (needle == cv) {
return chars[c - 1];
} else if ((lv <= needle) && (needle < cv)) {
return chars[l];
} else if (needle == rv) {
return chars[r];
} else if (needle < cv) {
rv = cv;
r = c;
c = l + (r - l) / 2;
cv = prob[c];
} else if (needle == cv) {
return chars[c];
} else {
lv = cv;
l = c;
c = l + (r - l) / 2;
cv = prob[c];
}
}
}
private int sum = 69552218;
private static int[] prob;
private static void populateProb1() {
prob = new int[10003];
int[] temp = new int[] {0, 2998461, 11968276, 18768077, 22489668,
25564867, 28566474, 31178037, 33583728, 35906053, 38220254, 40430228,
42605383, 44136051, 45417665, 46672307, 46782210, 47875442, 48928896,
49849977, 49926463, 50685835, 51384820, 51997588, 52562977, 53114810,
53662681, 54154198, 54201051, 54247649, 54709396, 55150464, 55558189,
55956271, 56255010, 56537443, 56790560, 57034843, 57274138, 57485651,
57690645, 57894136, 58095179, 58290586, 58478703, 58657046, 58833174,
58979618, 59118214, 59252316, 59383011, 59511468, 59616000, 59719717,
59822765, 59924337, 60018141, 60102715, 60103512, 60111276, 60187497,
60261002, 60332050, 60400395, 60463530, 60525044, 60586535, 60592498,
60651542, 60708760, 60765356, 60820799, 60876057, 60926360, 60976475,
61026421, 61074255, 61118922, 61163456, 61207355, 61251147, 61293399,
61334924, 61375951, 61416927, 61457584, 61497222, 61501126, 61539952,
61577967, 61615858, 61652895, 61689599, 61726065, 61762110, 61796817,
61831379, 61865281, 61898336, 61930814, 61963212, 61995571, 62027746,
62059880, 62091953, 62123862, 62155726, 62187494, 62218025, 62247942,
62277854, 62307509, 62336275, 62364822, 62393339, 62421575, 62449112,
62476556, 62503994, 62531165, 62533882, 62536554, 62563178, 62589569,
62615931, 62641977, 62667819, 62670393, 62672941, 62698398, 62723810,
62748828, 62773421, 62773660, 62797528, 62820871, 62823180, 62845858,
62868387, 62890814, 62913180, 62935449, 62957034, 62978440, 62999686,
63020821, 63041849, 63062713, 63082956, 63102958, 63122877, 63142650,
63162263, 63181752, 63201214, 63220472, 63239711, 63258362, 63276998,
63295503, 63313936, 63332203, 63350395, 63368456, 63386448, 63388247,
63405634, 63407359, 63424261, 63441134, 63457698, 63474247, 63490783,
63507308, 63523723, 63539975, 63556168, 63572196, 63587834, 63603467,
63619061, 63634602, 63650139, 63665668, 63681137, 63696535, 63698072,
63713405, 63728710, 63743997, 63759244, 63774378, 63789477, 63804212,
63818898, 63833577, 63848192, 63862616, 63877034, 63891215, 63905360,
63919315, 63933131, 63946873, 63960526, 63974167, 63987674, 64001139,
64014592, 64028011, 64041415, 64054809, 64068126, 64081417, 64094632,
64107536, 64120332, 64133044, 64145616, 64158121, 64170496, 64182865,
64195233, 64207588, 64219849, 64232094, 64244320, 64256504, 64257719,
64269791, 64281807, 64293783, 64305588, 64306765, 64318504, 64330211,
64341904, 64353578, 64365252, 64366419, 64378068, 64389716, 64401322,
64412871, 64424406, 64425552, 64426689, 64437977, 64449132, 64460284,
64471315, 64482340, 64493269, 64503956, 64514601, 64525226, 64535778,
64546326, 64556767, 64567140, 64577453, 64587746, 64598011, 64608256,
64608358, 64618492, 64628579, 64638653, 64648727, 64658764, 64668799,
64678680, 64688543, 64698398, 64708082, 64717757, 64727380, 64736982,
64746557, 64756118, 64765654, 64775155, 64784592, 64794024, 64803433,
64812780, 64822087, 64831283, 64840465, 64849520, 64858567, 64867599,
64876612, 64885585, 64894553, 64903472, 64912373, 64921249, 64930038,
64938750, 64947452, 64948320, 64956991, 64965638, 64974277, 64982885,
64991466, 65000015, 65008563, 65017094, 65025571, 65033995, 65042379,
65050716, 65059035, 65067338, 65075627, 65076455, 65084727, 65092982,
65101144, 65109266, 65117373, 65125479, 65133578, 65141657, 65149726,
65150531, 65158555, 65166553, 65174472, 65182377, 65190260, 65198136,
65205979, 65206763, 65214595, 65222402, 65230135, 65237858, 65245556,
65253253, 65260922, 65261686, 65269318, 65276950, 65284569, 65292163,
65299687, 65307200, 65307275, 65314762, 65322226, 65329664, 65337073,
65344451, 65351800, 65359136, 65366462, 65373775, 65381087, 65388284,
65395469, 65402651, 65409830, 65417003, 65424168, 65431331, 65438487,
65445595, 65452672, 65459721, 65466766, 65473795, 65480823, 65487847,
65494824, 65501797, 65508770, 65515732, 65522693, 65529646, 65536520,
65537207, 65537893, 65538579, 65545430, 65552241, 65559039, 65565814,
65572562, 65579296, 65586020, 65592716, 65593382, 65600037, 65606605,
65613147, 65619640, 65626071, 65632496, 65638918, 65645310, 65645945,
65652280, 65652912, 65659168, 65665415, 65671631, 65677833, 65684025,
65684641, 65690780, 65696909, 65703021, 65709132, 65715239, 65721340,
65727438, 65733535, 65739617, 65745695, 65751753, 65757765, 65763760,
65769744, 65775699, 65781646, 65787588, 65793525, 65799461, 65805374,
65811283, 65817190, 65823078, 65823666, 65824253, 65830101, 65835942,
65841755, 65847563, 65853354, 65859098, 65864810, 65870519, 65876183,
65881822, 65887437, 65893045, 65898651, 65904246, 65909707, 65915151,
65920583, 65925999, 65931410, 65936817, 65942193, 65947567, 65952934,
65958289, 65963637, 65968969, 65974293, 65974825, 65980140, 65985417,
65990672, 65995914, 66001153, 66006392, 66011615, 66012137, 66017334,
66022528, 66027719, 66032905, 66033422, 66038587, 66043749, 66048910,
66054066, 66059218, 66064370, 66069493, 66070005, 66075122, 66080220,
66085315, 66090410, 66095497, 66100582, 66105664, 66110746, 66115813,
66120879, 66125928, 66130971, 66131475, 66136498, 66141516, 66146527,
66151533, 66156526, 66161499, 66166472, 66171429, 66176377, 66181315,
66186228, 66186719, 66191625, 66196528, 66196577, 66201473, 66206365,
66206854, 66211740, 66216606, 66221467, 66226320, 66231162, 66231645,
66236468, 66241285, 66246076, 66250853, 66255621, 66260387, 66265121,
66269852, 66274579, 66279293, 66284006, 66288711, 66293414, 66298061,
66302706, 66307341, 66311963, 66316582, 66321199, 66325797, 66330382,
66334965, 66339540, 66344108, 66348674, 66353233, 66357788, 66362332,
66366874, 66371412, 66375949, 66380462, 66384963, 66385008, 66389507,
66393988, 66398461, 66402913, 66407358, 66411800, 66416227, 66420650,
66421092, 66425506, 66429903, 66434282, 66438657, 66443011, 66447364,
66451711, 66456043, 66460374, 66464695, 66469009, 66473318, 66477619,
66481905, 66486174, 66490433, 66494685, 66498930, 66503172, 66507405,
66511629, 66515843, 66520045, 66524244, 66528437, 66532628, 66536801,
66540968, 66545132, 66549288, 66553436, 66557577, 66561711, 66565840,
66569963, 66570004, 66574103, 66578201, 66582298, 66582707, 66583115,
66587194, 66591270, 66595323, 66599360, 66603386, 66607410, 66611432,
66615421, 66619394, 66623366, 66623763, 66627728, 66631691, 66635652,
66639601, 66643544, 66647482, 66651390, 66655298, 66659177, 66663029,
66666880, 66670725, 66674569, 66678395, 66682219, 66686042, 66689844,
66693646, 66697442, 66701236, 66705023, 66708801, 66712574, 66716338,
66720099, 66723857, 66727581, 66731302, 66735016, 66738729, 66742440,
66746147, 66749838, 66753521, 66757203, 66757571, 66761249, 66764927,
66768604, 66772257, 66775909, 66779541, 66783159, 66786773, 66790376,
66793962, 66797546, 66801127, 66804703, 66808262, 66811818, 66815367,
66818912, 66822449, 66825986, 66829521, 66833055, 66836582, 66840106,
66843624, 66847140, 66850656, 66854170, 66857658, 66861130, 66864598,
66868064, 66871527, 66874984, 66878430, 66881873, 66885312, 66888746,
66892179, 66895608, 66899030, 66902433, 66905822, 66909208, 66912593,
66915978, 66919361, 66922743, 66926120, 66929492, 66932854, 66936205,
66939548, 66942882, 66946210, 66949528, 66949859, 66953164, 66956467,
66959762, 66960091, 66963379, 66966665, 66969950, 66973229, 66976498,
66979762, 66983021, 66986279, 66989531, 66992782, 66996030, 66999275,
67002518, 67005760, 67008993, 67012220, 67015446, 67018671, 67018993,
67022210, 67025425, 67028640, 67031851, 67035058, 67038263, 67041459,
67044653, 67047839, 67051016, 67054190, 67057359, 67060524, 67063687,
67066836, 67069985, 67073112, 67076238, 67079355, 67082471, 67085585,
67088688, 67091790, 67094862, 67095169, 67098228, 67101266, 67101568,
67104586, 67107601, 67110615, 67110618, 67110621, 67113616, 67116609,
67119594, 67122578, 67125559, 67128533, 67131506, 67134473, 67137436,
67140397, 67143358, 67146316, 67149268, 67152216, 67155163, 67158106,
67161049, 67163991, 67166929, 67167222, 67170149, 67173074, 67175993,
67178907, 67181820, 67184732, 67187640, 67190545, 67193440, 67193729,
67196611, 67199490, 67202361, 67205225, 67208088, 67208374, 67211232,
67214088, 67216942, 67219795, 67222648, 67225497, 67228341, 67231184,
67231468, 67231752, 67234590, 67237424, 67240250, 67243069, 67245884,
67248698, 67251505, 67254310, 67257109, 67259903, 67262692, 67265473,
67265751, 67268529, 67271305, 67274079, 67276851, 67279620, 67282388,
67285155, 67287917, 67290675, 67293433, 67296185, 67298937, 67299212,
67301957, 67304700, 67307442, 67310183, 67312919, 67315644, 67318366,
67321087, 67323805, 67326518, 67329224, 67331930, 67331957, 67334652,
67337347, 67340039, 67342725, 67345383, 67348017, 67350646, 67353274,
67355896, 67358502, 67361108, 67363707, 67366305, 67368903, 67371499,
67374088, 67376677, 67379265, 67381850, 67384431, 67384689, 67387266,
67389841, 67392403, 67394964, 67397525, 67397781, 67400338, 67402890,
67405435, 67407979, 67410522, 67413058, 67415590, 67418115, 67420637,
67423158, 67423410, 67425925, 67428434, 67430942, 67433448, 67435952,
67438456, 67440953, 67443448, 67445941, 67446190, 67446439, 67448925,
67451408, 67453886, 67456359, 67458828, 67461289, 67463747, 67466201,
67468640, 67471077, 67473514, 67475948, 67478379, 67478622, 67481044,
67483466, 67485887, 67488300, 67488541, 67490945, 67493342, 67495737,
67498130, 67500519, 67502886, 67505248, 67507610, 67509969, 67512326,
67514681, 67514916, 67517263, 67519605, 67521947, 67524283, 67526618,
67528949, 67531278, 67533606, 67535931, 67538254, 67540576, 67542898,
67545217, 67547535, 67549852, 67552168, 67554484, 67556799, 67559112,
67561425, 67563731, 67566034, 67566057, 67568355, 67570651, 67570880,
67573165, 67575449, 67577733, 67580011, 67582284, 67584546, 67586803,
67589060, 67591315, 67593569, 67595817, 67598064, 67600303, 67602540,
67604776, 67607003, 67609227, 67611449, 67613666, 67615878, 67616099,
67618306, 67620513, 67622701, 67624888, 67627074, 67629256, 67631437,
67631655, 67633831, 67635996, 67636212, 67638368, 67640522, 67642669,
67644814, 67646957, 67649094, 67651228, 67653359, 67655488, 67657613,
67659737, 67659949, 67660161, 67662279, 67664392, 67666501, 67668609,
67670712, 67670733, 67672832, 67674930, 67677025, 67679119, 67679328,
67681415, 67683499, 67685582, 67685790, 67687869, 67689943, 67692016,
67692223, 67694292, 67696359, 67698420, 67700476, 67702531, 67704585,
67704790, 67706839, 67708886, 67710931, 67712976, 67715019, 67717058,
67719096, 67721131, 67723166, 67723369, 67725396, 67727421, 67729443,
67731464, 67733480, 67735496, 67737505, 67737507, 67739505, 67741499,
67743493, 67745487, 67747480, 67749473, 67749672, 67749871, 67751859,
67753842, 67755823, 67757804, 67758002, 67759979, 67761956, 67763927,
67765898, 67767867, 67769836, 67771802, 67773766, 67775729, 67775925,
67777878, 67779822, 67781765, 67783706, 67785645, 67787584, 67789521,
67791457, 67793391, 67795324, 67797256, 67799187, 67801112, 67803035,
67804948, 67805139, 67807046, 67808951, 67810850, 67812744, 67814625,
67814813, 67815001, 67816875, 67818748, 67820620, 67822492, 67822679,
67824547, 67826413, 67828276, 67830137, 67830323, 67832181, 67834039,
67835895, 67837751, 67839606, 67841460, 67843311, 67845160, 67847008,
67848856, 67850698, 67850882, 67852720, 67854558, 67856395, 67856578,
67858405, 67860227, 67862048, 67862230, 67862412, 67864231, 67866048,
67867865, 67869682, 67871486, 67873285, 67875082, 67876877, 67878672,
67880467, 67882261, 67884054, 67885846, 67887635, 67889422, 67891209,
67892994, 67894775, 67896550, 67898323, 67900092, 67901854, 67902030,
67903781, 67905532, 67905707, 67907456, 67909203, 67910949, 67912682,
67914411, 67916139, 67917864, 67919589, 67921312, 67923034, 67924755,
67926471, 67928182, 67928353, 67930062, 67931771, 67933479, 67935181,
67936882, 67936899, 67938598, 67940294, 67941990, 67943685, 67945378,
67947063, 67948746, 67950429, 67952112, 67953785, 67955453, 67955619,
67957277, 67958934, 67960587, 67962238, 67962403, 67962568, 67962733,
67964382, 67966030, 67967676, 67969322, 67970966, 67972608, 67974249,
67974413, 67976046, 67977677, 67977840, 67979467, 67981094, 67982720,
67984338, 67985950, 67987561, 67987722, 67989331, 67990939, 67992547,
67994154, 67995761, 67997368, 67998971, 68000573, 68002174, 68002190,
68003789, 68005388, 68006985, 68008581, 68010176, 68011768, 68013356,
68014940, 68016522, 68016680, 68016838, 68018416, 68019994, 68021571,
68023147, 68024723, 68026296, 68027868, 68029439, 68029596, 68031162,
68032724, 68034286, 68034442, 68034598, 68036157, 68037716, 68039273,
68040827, 68042380, 68043932, 68045481, 68047024, 68048567, 68050106,
68051641, 68051794, 68053323, 68054849, 68056374, 68057898, 68059417,
68060934, 68062451, 68063967, 68065480, 68066991, 68067142, 68068651,
68070157, 68071660, 68071675, 68071690, 68073187, 68074678, 68074827,
68076316, 68077805, 68079293, 68080780, 68082265, 68083750, 68085232,
68086713, 68088194, 68089673, 68091149, 68092623, 68094096, 68095568,
68095715, 68095862, 68097331, 68098796, 68100261, 68101726, 68103190,
68104654, 68106116, 68107575, 68109033, 68110490, 68111945, 68113396,
68114845, 68116294, 68117741, 68119184, 68119328, 68120765, 68122201,
68123633, 68125064, 68125207, 68126633, 68128059, 68129483, 68130906,
68132328, 68133749, 68135154, 68135168, 68136567, 68137966, 68139365,
68140762, 68142156, 68143550, 68144943, 68146336, 68147729, 68149120,
68150511, 68151902, 68152041, 68153429, 68154816, 68156203, 68157588,
68158970, 68160352, 68161731, 68163110, 68164486, 68165861, 68167233,
68167370, 68168738, 68168874, 68170229, 68171584, 68172937, 68174282,
68175625, 68176966, 68177100, 68177234, 68177368, 68177502, 68178839,
68180175, 68181511, 68182844, 68184177, 68185509, 68186838, 68188166,
68189493, 68190819, 68192144, 68193466, 68194788, 68196109, 68197427,
68198744, 68200060, 68201375, 68202688, 68204000, 68205311, 68205442,
68205573, 68206880, 68208187, 68209491, 68210794, 68212097, 68213398,
68214697, 68215996, 68217293, 68218589, 68219885, 68221180, 68222474,
68223766, 68223895, 68225183, 68226470, 68227755, 68229040, 68230324,
68231607, 68232889, 68234167, 68235443, 68236719, 68237994, 68239269,
68240543, 68241817, 68243090, 68244362, 68245634, 68246903, 68248172,
68249441, 68250709, 68251977, 68253245, 68254509, 68255772, 68257035,
68258296, 68259555, 68260813, 68262068, 68263322, 68264576, 68265829,
68267082, 68268335, 68269587, 68270836, 68272083, 68273330, 68274574,
68275817, 68277060, 68278302, 68279543, 68280781, 68282018, 68283253,
68284485, 68285714, 68286943, 68288171, 68289393, 68290615, 68291836,
68293055, 68294272, 68295488, 68296702, 68297916, 68299129, 68300341,
68300462, 68301669, 68302873, 68304077, 68305281, 68306485, 68307687,
68308888, 68310089, 68311290, 68311302, 68312501, 68313699, 68314897,
68316094, 68317291, 68318486, 68318605, 68319793, 68320981, 68322168,
68323354, 68324539, 68325724, 68326909, 68328093, 68329275, 68330457,
68331639, 68331757, 68332935, 68334112, 68335289, 68336466, 68337640,
68338813, 68339982, 68341148, 68342313, 68343474, 68343590, 68344749,
68345908, 68347065, 68348221, 68349377, 68350532, 68351686, 68352840,
68353992, 68354107, 68354222, 68355370, 68356516, 68357654, 68358792,
68359926, 68361053, 68362179, 68363301, 68364423, 68365544, 68366659,
68367772, 68368884, 68368995, 68369106, 68370215, 68371323, 68372430,
68373537, 68374643, 68375749, 68376852, 68377953, 68379052, 68380151,
68381249, 68382346, 68383442, 68384537, 68385632, 68386726, 68387820,
68388913, 68390006, 68391099, 68392191, 68393280, 68394368, 68395455,
68396542, 68397626, 68398710, 68399794, 68400877, 68401959, 68403041,
68404123, 68405204, 68406285, 68407366, 68408447, 68409528, 68409636,
68409744, 68410822, 68411900, 68412978, 68414051, 68415123, 68416192,
68417259, 68418325, 68419391, 68420452, 68421513, 68422572, 68423631,
68424690, 68425749, 68426808, 68427867, 68428924, 68429981, 68431037,
68432093, 68433147, 68434200, 68435249, 68436298, 68437346, 68438394,
68439442, 68440489, 68441533, 68442576, 68443619, 68444657, 68445694,
68446730, 68447764, 68447867, 68447970, 68448998, 68450025, 68451052,
68452077, 68453102, 68454125, 68455147, 68456169, 68457187, 68458205,
68459223, 68460241, 68461258, 68462274, 68463289, 68464303, 68465317,
68466329, 68466430, 68466531, 68467540, 68468548, 68469555, 68470560,
68471565, 68472568, 68473570, 68474572, 68475574, 68475575, 68475576,
68476575, 68477573, 68478570, 68479566, 68480562, 68481557, 68482551,
68483545, 68484539, 68484638, 68484737, 68484836, 68485825, 68486811,
68487796, 68488777, 68488875, 68488973, 68489952, 68490931, 68491908,
68492884, 68493859, 68494834, 68495809, 68496783, 68497756, 68498728,
68498825, 68498922, 68499890, 68500858, 68501825, 68502791, 68503757,
68504720, 68505683, 68506645, 68506741, 68507700, 68508658, 68509611,
68510562, 68511513, 68512464, 68513415, 68514366, 68515317, 68515412,
68515507, 68515602, 68515697, 68515792, 68515887, 68516836, 68517785,
68518734, 68519683, 68520631, 68521578, 68522525, 68523470, 68524413,
68525354, 68526295, 68527236, 68528173, 68529109, 68530045, 68530981,
68531915, 68532849, 68533781, 68534713, 68535645, 68536576, 68537507,
68537600, 68537693, 68538622, 68539550, 68540476, 68541399, 68542320,
68542412, 68542504, 68543423, 68544342, 68545260, 68546176, 68547092,
68548007, 68548922, 68549834, 68550745, 68551656, 68551747, 68552655,
68553560, 68554465, 68555370, 68556274, 68557177, 68558080, 68558982,
68559883, 68560784, 68561685, 68561694, 68562592, 68563490, 68564388,
68565285, 68566181, 68567077, 68567973, 68568869, 68569765, 68570659,
68571552, 68572444, 68573336, 68574228, 68575120, 68576011, 68576902,
68576991, 68577880, 68578768, 68579655, 68580541, 68581427, 68582313,
68583196, 68584078, 68584960, 68585841, 68585929, 68586808, 68587685,
68588561, 68589437, 68590313, 68591189, 68592065, 68592940, 68593027,
68593894, 68594760, 68595626, 68596492, 68597356, 68598218, 68599077,
68599936, 68600795, 68601652, 68602508, 68603363, 68604217, 68605070,
68605922, 68606774, 68607626, 68608477, 68608562, 68609411, 68610260,
68611107, 68611954, 68612800, 68613646, 68614491, 68615336, 68616179,
68617021, 68617862, 68618703, 68618787, 68618871, 68619710, 68620548,
68621386, 68622222, 68623058, 68623893, 68624728, 68625563, 68626397,
68627231, 68628064, 68628896, 68629728, 68630559, 68631390, 68632219,
68633047, 68633875, 68634702, 68635529, 68636356, 68637183, 68638009,
68638833, 68639656, 68640478, 68641299, 68642120, 68642202, 68643021,
68643840, 68644659, 68645477, 68646294, 68647111, 68647927, 68648743,
68649559, 68650373, 68651187, 68651998, 68652803, 68653607, 68654410,
68655213, 68656016, 68656818, 68657620, 68657628, 68658427, 68659226,
68660024, 68660822, 68661620, 68662417, 68663214, 68664010, 68664806,
68665601, 68666395, 68667189, 68667982, 68668774, 68669565, 68670356,
68671147, 68671935, 68672723, 68673509, 68674295, 68675079, 68675862,
68675940, 68676719, 68677498, 68678275, 68679051, 68679826, 68680601,
68681375, 68682149, 68682922, 68683694, 68684466, 68685237, 68685314,
68685391, 68686160, 68686929, 68687697, 68688464, 68689230, 68689996,
68690760, 68691523, 68692285, 68693046, 68693122, 68693198, 68693956,
68694713, 68695468, 68696222, 68696976, 68697730, 68698483, 68699235,
68699986, 68700737, 68701486, 68702235, 68702984, 68703732, 68704480,
68705226, 68705972, 68706718, 68707463, 68708208, 68708953, 68709697,
68710440, 68711183, 68711926, 68712667, 68713408, 68714145, 68714882,
68715618, 68716354, 68717090, 68717825, 68718559, 68719292, 68720024,
68720753, 68721482, 68722209, 68722935, 68723660, 68724384, 68725108,
68725832, 68726555, 68727278, 68728001, 68728723, 68728795, 68729514,
68730233, 68730951, 68731669, 68732385, 68733101, 68733816, 68734528,
68735240, 68735951, 68736022, 68736093, 68736164, 68736235, 68736944,
68737653, 68738362, 68739069, 68739775, 68740481, 68741187, 68741892,
68742597, 68743301, 68744005, 68744707, 68745409, 68746110, 68746811,
68746818, 68746825, 68747524, 68748223, 68748922, 68749620, 68750315,
68751009, 68751703, 68752397, 68753090, 68753783, 68754474, 68755165,
68755856, 68755925, 68755994, 68756683, 68757371, 68758059, 68758746,
68759433, 68760119, 68760805, 68761488, 68762171, 68762852, 68763533,
68764214, 68764893, 68765572, 68766251, 68766930, 68767608, 68768286,
68768963, 68769640, 68770316, 68770992, 68771667, 68772342, 68773015,
68773688, 68774360, 68775032, 68775703, 68776374, 68776441, 68777110,
68777777, 68778444, 68779111, 68779778, 68780444, 68781110, 68781776,
68782441, 68783106, 68783770, 68784432, 68785094, 68785755, 68786416,
68786482, 68786548, 68787207, 68787866, 68788524, 68789182, 68789840,
68790497, 68791154, 68791810, 68792466, 68793122, 68793777, 68794432,
68795087, 68795741, 68796395, 68797048, 68797700, 68798352, 68799004,
68799656, 68800307, 68800372, 68800437, 68801086, 68801735, 68802384,
68803033, 68803681, 68804329, 68804976, 68805621, 68806265, 68806908,
68807551, 68808194, 68808836, 68809477, 68810118, 68810759, 68811400,
68811464, 68811528, 68811592, 68812230, 68812868, 68813506, 68814141,
68814776, 68815411, 68816045, 68816679, 68817311, 68817943, 68818571,
68819199, 68819826, 68820452, 68821078, 68821704, 68822329, 68822954,
68823579, 68824203, 68824826, 68825449, 68826071, 68826133, 68826195,
68826257, 68826319, 68826381, 68827000, 68827619, 68828237, 68828855,
68829473, 68830090, 68830707, 68831323, 68831938, 68832553, 68833167,
68833781, 68834395, 68835008, 68835621, 68836233, 68836842, 68837450,
68838057, 68838663, 68839269, 68839874, 68840479, 68841084, 68841689,
68842293, 68842897, 68843501, 68844105, 68844708, 68845310, 68845912,
68845918, 68845924, 68845930, 68845936, 68846535, 68847134, 68847733,
68848332, 68848930, 68849527, 68850124, 68850720, 68851315, 68851909,
68852503, 68853096, 68853688, 68854280, 68854872, 68855464, 68856056,
68856115, 68856174, 68856233, 68856822, 68857411, 68858000, 68858589,
68859178, 68859766, 68860353, 68860939, 68861523, 68862107, 68862691,
68863274, 68863857, 68864438, 68865019, 68865600, 68865658, 68866237,
68866816, 68867395, 68867973, 68868551, 68869129, 68869706, 68870283,
68870860, 68871437, 68872013, 68872589, 68873164, 68873739, 68874313,
68874887, 68875461, 68876035, 68876609, 68877183, 68877756, 68878329,
68878901, 68879473, 68880045, 68880617, 68881188, 68881759, 68882328,
68882897, 68883465, 68884033, 68884601, 68885169, 68885735, 68886301,
68886865, 68887428, 68887991, 68888554, 68889116, 68889678, 68890239,
68890295, 68890854, 68891412, 68891969, 68892526, 68893083, 68893639,
68894195, 68894751, 68895307, 68895862, 68896416, 68896970, 68897524,
68898078, 68898631, 68899182, 68899733, 68900284, 68900835, 68901386,
68901937, 68902488, 68902543, 68902598, 68902653, 68902708, 68903257,
68903806, 68904354, 68904902, 68905450, 68905996, 68906540, 68907084,
68907628, 68908172, 68908716, 68909260, 68909803, 68910345, 68910887,
68911429, 68911971, 68912512, 68913053, 68913594, 68913648, 68914187,
68914725, 68915262, 68915798, 68916334, 68916870, 68917406, 68917941,
68918475, 68919009, 68919543, 68920076, 68920608, 68921140, 68921672,
68922204, 68922735, 68923266, 68923797, 68924328, 68924859, 68925390,
68925919, 68926448, 68926975, 68927502, 68928029, 68928555, 68929081,
68929606, 68930131, 68930656, 68931180, 68931703, 68932226, 68932749,
68933271, 68933792, 68934313, 68934365, 68934884, 68935403, 68935922,
68936440, 68936957, 68937474, 68937991, 68938507, 68939023, 68939538,
68940053, 68940567, 68941081, 68941595, 68942108, 68942621, 68943133,
68943645, 68944157, 68944669, 68945180, 68945231, 68945282, 68945333,
68945842, 68946351, 68946860, 68947369, 68947877, 68948385, 68948893,
68949400, 68949906, 68950412, 68950918, 68951424, 68951929, 68952434,
68952938, 68953441, 68953944, 68954447, 68954949, 68955450, 68955949,
68956448, 68956947, 68957445, 68957943, 68958441, 68958938, 68959435,
68959932, 68960429, 68960926, 68961422, 68961917, 68962412, 68962907,
68963401, 68963894, 68964387, 68964880, 68965373, 68965866, 68966359,
68966852, 68967345, 68967837, 68968329, 68968821, 68968870, 68968919,
68968968, 68969457, 68969945, 68970432, 68970919, 68971405, 68971891,
68972376, 68972861, 68973346, 68973831, 68974315, 68974797, 68975278,
68975759, 68976240, 68976288, 68976336, 68976815, 68977294, 68977772,
68978250, 68978727, 68979204, 68979680, 68980156, 68980632, 68981108,
68981583, 68982057, 68982530, 68983003, 68983475, 68983947, 68984419,
68984891, 68985363, 68985834, 68986305, 68986352, 68986399, 68986868,
68987337, 68987806, 68988275, 68988743, 68989211, 68989679, 68990147,
68990615, 68991082, 68991549, 68992016, 68992482, 68992948, 68993414,
68993879, 68994344, 68994809, 68995274, 68995739, 68996203, 68996667,
68997131, 68997595, 68998058, 68998521, 68998983, 68999444, 68999905,
69000366, 69000827, 69001288, 69001746, 69002204, 69002661, 69003118,
69003575, 69004032, 69004488, 69004944, 69005400, 69005855, 69006310,
69006765, 69007220, 69007674, 69008128, 69008582, 69009036, 69009489,
69009942, 69010395, 69010847, 69011299, 69011751, 69012203, 69012655,
69013106, 69013557, 69013602, 69013647, 69014096, 69014545, 69014993,
69015441, 69015889, 69016337, 69016785, 69017232, 69017679, 69018126,
69018573, 69019019, 69019465, 69019911, 69020357, 69020802, 69021247,
69021692, 69022137, 69022581, 69023025, 69023469, 69023913, 69024356,
69024798, 69025240, 69025682, 69026124, 69026565, 69027006, 69027447,
69027491, 69027929, 69028366, 69028803, 69029238, 69029673, 69030108,
69030543, 69030977, 69031410, 69031843, 69032275, 69032318, 69032361,
69032404, 69032447, 69032876, 69033305, 69033734, 69034163, 69034592,
69035020, 69035448, 69035876, 69036302, 69036727, 69037152, 69037577,
69038002, 69038427, 69038852, 69039276, 69039699, 69040121, 69040543,
69040964, 69041385, 69041806, 69042227, 69042648, 69042690, 69043109,
69043528, 69043947, 69044366, 69044785, 69045203, 69045619, 69046034,
69046449, 69046863, 69047275, 69047687, 69048099, 69048511, 69048923,
69049335, 69049746, 69050157, 69050198, 69050239, 69050280, 69050689,
69051098, 69051507, 69051916, 69052323, 69052730, 69053137, 69053544,
69053950, 69054356, 69054761, 69055166, 69055570, 69055974, 69056377,
69056780, 69057183, 69057586, 69057989, 69058392, 69058795, 69059197,
69059599, 69060000, 69060401, 69060802, 69061203, 69061600, 69061997,
69062394, 69062790, 69063186, 69063582, 69063978, 69064373, 69064768,
69065163, 69065558, 69065953, 69066348, 69066742, 69067136, 69067530,
69067924, 69068317, 69068710, 69069102, 69069493, 69069884, 69070275,
69070314, 69070353, 69070392, 69070431, 69070820, 69071209, 69071597,
69071985, 69072373, 69072760, 69073146, 69073531, 69073916, 69074301,
69074685, 69075069, 69075453, 69075836, 69076219, 69076602, 69076984,
69077365, 69077746, 69078127, 69078165, 69078203, 69078241, 69078620,
69078999, 69079378, 69079757, 69080136, 69080514, 69080892, 69081270,
69081648, 69082026, 69082404, 69082782, 69083160, 69083538, 69083915,
69084292, 69084669, 69085046, 69085422, 69085798, 69086174, 69086550,
69086925, 69087300, 69087675, 69088050, 69088424, 69088798, 69089172,
69089545, 69089918, 69090291, 69090664, 69091037, 69091409, 69091781,
69092153, 69092525, 69092896, 69093267, 69093638, 69094009, 69094046,
69094083, 69094120, 69094157, 69094194, 69094231, 69094600, 69094969,
69095337, 69095705, 69096073, 69096441, 69096809, 69097177, 69097545,
69097912, 69098279, 69098645, 69099011, 69099377, 69099742, 69100107,
69100472, 69100837, 69101201, 69101565, 69101928, 69102291, 69102654,
69103016, 69103378, 69103740, 69104101, 69104462, 69104823, 69105184,
69105220, 69105256, 69105292, 69105651, 69106010, 69106369, 69106728,
69107087, 69107446, 69107805, 69108163, 69108521, 69108879, 69109237,
69109595, 69109952, 69110309, 69110666, 69111023, 69111380, 69111736,
69112092, 69112448, 69112803, 69113158, 69113513, 69113867, 69114221,
69114574, 69114927, 69115280, 69115633, 69115985, 69116337, 69116689,
69117040, 69117075, 69117110, 69117145, 69117180, 69117215, 69117564,
69117913, 69118262, 69118611, 69118959, 69119307, 69119654, 69120001,
69120348, 69120695, 69121041, 69121387, 69121733, 69122078, 69122422,
69122766, 69123109, 69123452, 69123794, 69124136, 69124478, 69124819,
69125160, 69125501, 69125842, 69126183, 69126217, 69126251, 69126285,
69126319, 69126353, 69126692, 69127031, 69127370, 69127709, 69128047,
69128385, 69128723, 69129060, 69129397, 69129734, 69130070, 69130406,
69130742, 69131077, 69131411, 69131745, 69132079, 69132413, 69132746,
69133079, 69133411, 69133743, 69134075, 69134406, 69134737, 69135068,
69135101, 69135134, 69135167, 69135200, 69135233, 69135266, 69135299,
69135628, 69135957, 69136286, 69136615, 69136944, 69137272, 69137600,
69137927, 69138254, 69138581, 69138908, 69139234, 69139560, 69139886,
69140212, 69140538, 69140863, 69141188, 69141513, 69141838, 69142162,
69142486, 69142810, 69143134, 69143457, 69143780, 69144103, 69144425,
69144747, 69145069, 69145391, 69145713, 69146034, 69146355, 69146676,
69146997, 69147029, 69147061, 69147093, 69147125, 69147157, 69147476,
69147794, 69148112, 69148430, 69148748, 69149066, 69149383, 69149700,
69150017, 69150334, 69150650, 69150966, 69151281, 69151596, 69151911,
69152226, 69152540, 69152854, 69153168, 69153482, 69153796, 69154110,
69154422, 69154734, 69155046, 69155358, 69155670, 69155981, 69156292,
69156603, 69156634, 69156665, 69156696, 69157005, 69157314, 69157623,
69157932, 69158240, 69158548, 69158856, 69159164, 69159472, 69159780,
69160087, 69160394, 69160701, 69161007, 69161313, 69161619, 69161925,
69162230, 69162535, 69162840, 69163145, 69163449, 69163753, 69164057,
69164360, 69164663, 69164966, 69165269, 69165572, 69165875, 69166177,
69166479, 69166781, 69167083, 69167385, 69167687, 69167989, 69168291,
69168593, 69168895, 69169196, 69169497, 69169798, 69170099, 69170400,
69170701, 69170704, 69170707, 69170710, 69171009, 69171308, 69171607,
69171905, 69172203, 69172501, 69172798, 69173095, 69173392, 69173688,
69173984, 69174280, 69174576, 69174872, 69175168, 69175463, 69175758,
69176053, 69176348, 69176643, 69176938, 69177233, 69177528, 69177823,
69178117, 69178411, 69178704, 69178997, 69179290, 69179583, 69179876,
69180168, 69180460, 69180752, 69181044, 69181335, 69181364, 69181393,
69181682, 69181971, 69182260, 69182548, 69182836, 69183124, 69183412,
69183700, 69183988, 69184276, 69184563, 69184850, 69185137, 69185424,
69185711, 69185998, 69186284, 69186570, 69186856, 69187142, 69187428,
69187713, 69187998, 69188283, 69188568, 69188853, 69189138, 69189423,
69189708, 69189993, 69190277, 69190561, 69190845, 69191128, 69191411,
69191693, 69191975, 69192257, 69192539, 69192820, 69193101, 69193382,
69193663, 69193944, 69194225, 69194506, 69194534, 69194562, 69194590,
69194869, 69195148, 69195427, 69195706, 69195985, 69196264, 69196542,
69196820, 69197098, 69197376, 69197653, 69197930, 69198207, 69198484,
69198761, 69199038, 69199314, 69199590, 69199866, 69200140, 69200414,
69200688, 69200962, 69201235, 69201508, 69201781, 69202054, 69202326,
69202598, 69202870, 69203142, 69203414, 69203686, 69203958, 69204230,
69204501, 69204772, 69205043, 69205314, 69205341, 69205368, 69205395,
69205422, 69205449, 69205718, 69205987, 69206256, 69206525, 69206794,
69207063, 69207332, 69207601, 69207869, 69208137, 69208405, 69208672,
69208939, 69209206, 69209473, 69209740, 69210006, 69210272, 69210538,
69210804, 69211070, 69211336, 69211602, 69211867, 69212132, 69212397,
69212662, 69212927, 69213191, 69213455, 69213719, 69213983, 69214247,
69214511, 69214775, 69215038, 69215301, 69215564, 69215827, 69216089,
69216351, 69216613, 69216875, 69217136, 69217397, 69217658, 69217919,
69218180, 69218441, 69218702, 69218963, 69218989, 69219015, 69219041,
69219067, 69219093, 69219352, 69219611, 69219870, 69220129, 69220387,
69220645, 69220903, 69221161, 69221419, 69221677, 69221935, 69222193,
69222450, 69222707, 69222964, 69223221, 69223478, 69223735, 69223991,
69224247, 69224502, 69224757, 69225012, 69225267, 69225522, 69225777,
69226032, 69226287, 69226542, 69226797, 69227051, 69227305, 69227559,
69227812, 69228065, 69228318, 69228571, 69228824, 69229077, 69229330,
69229582, 69229834, 69230086, 69230338, 69230590, 69230842, 69231094,
69231346, 69231597, 69231848, 69232099, 69232350, 69232601, 69232852,
69232877, 69232902, 69232927, 69232952, 69232977, 69233002, 69233251,
69233500, 69233748, 69233996, 69234244, 69234492, 69234739, 69234986,
69235233, 69235480, 69235727, 69235974, 69236220, 69236466, 69236711,
69236956, 69237201, 69237446, 69237690, 69237934, 69238178, 69238421,
69238663, 69238905, 69239147, 69239389, 69239631, 69239873, 69240114,
69240355, 69240596, 69240837, 69241078, 69241319, 69241560, 69241801,
69241825, 69241849, 69241873, 69241897, 69241921, 69241945, 69242184,
69242423, 69242662, 69242901, 69243140, 69243379, 69243618, 69243856,
69244094, 69244332, 69244570, 69244808, 69245045, 69245282, 69245519,
69245756, 69245992, 69246228, 69246463, 69246698, 69246933, 69247168,
69247403, 69247637, 69247871, 69248105, 69248339, 69248573, 69248807,
69249041, 69249275, 69249509, 69249742, 69249975, 69250208, 69250441,
69250674, 69250907, 69251140, 69251372, 69251604, 69251836, 69252068,
69252300, 69252532, 69252764, 69252996, 69253228, 69253460, 69253692,
69253924, 69254155, 69254386, 69254617, 69254848, 69255079, 69255310,
69255541, 69255772, 69256003, 69256234, 69256257, 69256280, 69256303,
69256326, 69256349, 69256372, 69256395, 69256418, 69256647, 69256876,
69257105, 69257333, 69257561, 69257789, 69258016, 69258243, 69258470,
69258697, 69258924, 69259150, 69259376, 69259602, 69259828, 69260054,
69260279, 69260504, 69260729, 69260954, 69261179, 69261404, 69261629,
69261853, 69262077, 69262301, 69262525, 69262749, 69262973, 69263196,
69263419, 69263642, 69263865, 69264088, 69264311, 69264534, 69264757,
69264979, 69265201, 69265423, 69265645, 69265867, 69266089, 69266311,
69266533, 69266754, 69266975, 69267196, 69267417, 69267439, 69267461,
69267483, 69267505, 69267527, 69267549, 69267768, 69267987, 69268206,
69268424, 69268642, 69268860, 69269077, 69269294, 69269511, 69269728,
69269944, 69270160, 69270376, 69270592, 69270808, 69271024, 69271240,
69271456, 69271672, 69271887, 69272102, 69272317, 69272532, 69272747,
69272962, 69273176, 69273390, 69273604, 69273818, 69274032, 69274246,
69274460, 69274674, 69274888, 69275101, 69275314, 69275527, 69275740,
69275953, 69276166, 69276379, 69276592, 69276805, 69277018, 69277231,
69277443, 69277655, 69277867, 69278078, 69278289, 69278500, 69278711,
69278922, 69279133, 69279344, 69279555, 69279766, 69279977, 69279998,
69280019, 69280040, 69280061, 69280082, 69280103, 69280312, 69280521,
69280730, 69280939, 69281148, 69281356, 69281564, 69281772, 69281980,
69282188, 69282396, 69282604, 69282812, 69283020, 69283228, 69283435,
69283642, 69283849, 69284056, 69284263, 69284470, 69284676, 69284882,
69285087, 69285291, 69285495, 69285698, 69285901, 69286104, 69286307,
69286510, 69286713, 69286915, 69287117, 69287319, 69287521, 69287723,
69287925, 69288127, 69288329, 69288531, 69288732, 69288933, 69289134,
69289335, 69289536, 69289737, 69289938, 69290139, 69290141, 69290143,
69290342, 69290541, 69290740, 69290939, 69291138, 69291337, 69291535,
69291733, 69291931, 69292128, 69292325, 69292522, 69292719, 69292916,
69293113, 69293310, 69293507, 69293703, 69293899, 69294095, 69294291,
69294487, 69294683, 69294879, 69295075, 69295270, 69295465, 69295660,
69295855, 69296050, 69296245, 69296440, 69296635, 69296830, 69297024,
69297218, 69297412, 69297606, 69297800, 69297994, 69298188, 69298381,
69298574, 69298767, 69298960, 69299153, 69299346, 69299539, 69299731,
69299923, 69300115, 69300307, 69300498, 69300689, 69300880, 69301071,
69301262, 69301453, 69301644, 69301835, 69302026, 69302217, 69302236,
69302255, 69302274, 69302293, 69302312, 69302501, 69302690, 69302879,
69303068, 69303257, 69303446, 69303635, 69303823, 69304011, 69304199,
69304387, 69304575, 69304763, 69304951, 69305139, 69305327, 69305514,
69305701, 69305888, 69306075, 69306262, 69306449, 69306636, 69306823,
69307009, 69307195, 69307381, 69307567, 69307753, 69307939, 69308125,
69308310, 69308495, 69308680, 69308865, 69309050, 69309235, 69309420,
69309604, 69309788, 69309972, 69310156, 69310340, 69310524, 69310708,
69310892, 69311076, 69311260, 69311444, 69311628, 69311811, 69311994,
69312177, 69312360, 69312543, 69312726, 69312909, 69313092, 69313275,
69313458, 69313641, 69313823, 69314005, 69314187, 69314369, 69314551,
69314733, 69314915, 69315097, 69315279, 69315460, 69315478, 69315496,
69315514, 69315532, 69315550, 69315568, 69315586, 69315604, 69315783,
69315962, 69316141, 69316320, 69316499, 69316678, 69316857, 69317036,
69317215, 69317393, 69317571, 69317749, 69317927, 69318105, 69318283,
69318461, 69318639, 69318817, 69318995, 69319173, 69319351, 69319528,
69319705, 69319882, 69320059, 69320236, 69320413, 69320590, 69320767,
69320944, 69321121, 69321298, 69321475, 69321651, 69321827, 69322003,
69322178, 69322353, 69322528, 69322703, 69322878, 69323053, 69323228,
69323403, 69323578, 69323752, 69323926, 69324100, 69324274, 69324448,
69324622, 69324796, 69324970, 69325144, 69325318, 69325491, 69325664,
69325837, 69326010, 69326183, 69326356, 69326529, 69326702, 69326875,
69327048, 69327221, 69327393, 69327565, 69327737, 69327909, 69328081,
69328253, 69328425, 69328596, 69328767, 69328938, 69329109, 69329280,
69329451, 69329622, 69329793, 69329964, 69329981, 69329998, 69330015,
69330032, 69330049, 69330066, 69330083, 69330100, 69330117, 69330286,
69330455, 69330624, 69330793, 69330962, 69331131, 69331300, 69331468,
69331636, 69331804, 69331972, 69332139, 69332306, 69332473, 69332640,
69332807, 69332974, 69333140, 69333306, 69333472, 69333638, 69333804,
69333970, 69334136, 69334301, 69334466, 69334631, 69334796, 69334961,
69335126, 69335291, 69335456, 69335621, 69335786, 69335951, 69336116,
69336281, 69336446, 69336611, 69336775, 69336939, 69337103, 69337267,
69337431, 69337595, 69337759, 69337922, 69338085, 69338248, 69338411,
69338574, 69338736, 69338898, 69339060, 69339222, 69339384, 69339546,
69339708, 69339870, 69340032, 69340194, 69340356, 69340518, 69340680,
69340841, 69341002, 69341163, 69341324, 69341485, 69341646, 69341807,
69341968, 69342129, 69342290, 69342306, 69342322, 69342338, 69342354,
69342370, 69342386, 69342402, 69342418, 69342434, 69342593, 69342752,
69342911, 69343070, 69343229, 69343388, 69343547, 69343705, 69343863,
69344021, 69344179, 69344337, 69344495, 69344652, 69344809, 69344966,
69345123, 69345280, 69345437, 69345594, 69345751, 69345908, 69346065,
69346222, 69346378, 69346534, 69346690, 69346846, 69347002, 69347158,
69347314, 69347470, 69347626, 69347782, 69347938, 69348094, 69348249,
69348404, 69348559, 69348714, 69348869, 69349024, 69349179, 69349334,
69349489, 69349644, 69349798, 69349952, 69350106, 69350260, 69350414,
69350568, 69350722, 69350876, 69351030, 69351184, 69351338, 69351492,
69351646, 69351800, 69351953, 69352106, 69352259, 69352412, 69352565,
69352718, 69352871, 69353023, 69353175, 69353327, 69353479, 69353631,
69353783, 69353935, 69354087, 69354238, 69354389, 69354540, 69354691,
69354842, 69354993, 69355144, 69355159, 69355174, 69355189, 69355204,
69355219, 69355234, 69355249, 69355264, 69355279, 69355428, 69355577,
69355726, 69355875, 69356024, 69356173, 69356322, 69356471, 69356620,
69356769, 69356918, 69357067, 69357216, 69357365, 69357514, 69357663,
69357811, 69357959, 69358107, 69358255, 69358403, 69358551, 69358699,
69358847, 69358994, 69359141, 69359288, 69359435, 69359582, 69359729,
69359876, 69360023, 69360170, 69360317, 69360464, 69360611, 69360758,
69360905, 69361052, 69361199, 69361346, 69361492, 69361638, 69361784,
69361930, 69362076, 69362222, 69362368, 69362514, 69362659, 69362804,
69362949, 69363094, 69363239, 69363384, 69363529, 69363674, 69363819,
69363964, 69364109, 69364254, 69364399, 69364543, 69364687, 69364831,
69364975, 69365119, 69365263, 69365407, 69365551, 69365695, 69365839,
69365983, 69366126, 69366269, 69366412, 69366555, 69366698, 69366841,
69366984, 69367127, 69367269, 69367411, 69367553, 69367695, 69367837,
69367979, 69368121, 69368263, 69368405, 69368547, 69368688, 69368829,
69368970, 69369111, 69369252, 69369393, 69369534, 69369675, 69369816,
69369957, 69370098, 69370112, 69370126, 69370140, 69370154, 69370168,
69370182, 69370196, 69370335, 69370474, 69370613, 69370752, 69370891,
69371030, 69371169, 69371308, 69371447, 69371585, 69371723, 69371861,
69371999, 69372137, 69372275, 69372412, 69372549, 69372686, 69372823,
69372960, 69373097, 69373234, 69373371, 69373508, 69373645, 69373782,
69373919, 69374056, 69374193, 69374330, 69374467, 69374604, 69374741,
69374878, 69375015, 69375151, 69375287, 69375423, 69375559, 69375695,
69375831, 69375967, 69376103, 69376239, 69376375, 69376511, 69376646,
69376781, 69376916, 69377051, 69377186, 69377321, 69377456, 69377591,
69377726, 69377861, 69377996, 69378131, 69378266, 69378400, 69378534,
69378668, 69378802, 69378936, 69379070, 69379204, 69379338, 69379472,
69379605, 69379738, 69379871, 69380004, 69380137, 69380270, 69380403,
69380536, 69380669, 69380802, 69380935, 69381067, 69381199, 69381331,
69381463, 69381595, 69381727, 69381859, 69381990, 69382121, 69382252,
69382383, 69382514, 69382645, 69382776, 69382907, 69383038, 69383051,
69383064, 69383077, 69383090, 69383103, 69383116, 69383129, 69383142,
69383155, 69383168, 69383181, 69383194, 69383207, 69383336, 69383465,
69383594, 69383723, 69383852, 69383981, 69384110, 69384239, 69384368,
69384497, 69384625, 69384753, 69384881, 69385009, 69385137, 69385265,
69385392, 69385519, 69385646, 69385773, 69385900, 69386027, 69386154,
69386281, 69386408, 69386535, 69386662, 69386789, 69386915, 69387041,
69387167, 69387293, 69387419, 69387545, 69387671, 69387797, 69387923,
69388049, 69388175, 69388301, 69388427, 69388553, 69388678, 69388803,
69388928, 69389053, 69389178, 69389303, 69389428, 69389553, 69389678,
69389803, 69389928, 69390053, 69390178, 69390303, 69390428, 69390553,
69390678, 69390803, 69390927, 69391051, 69391175, 69391299, 69391423,
69391547, 69391671, 69391795, 69391919, 69392042, 69392165, 69392288,
69392411, 69392534, 69392657, 69392780, 69392903, 69393026, 69393149,
69393272, 69393395, 69393518, 69393640, 69393762, 69393884, 69394006,
69394128, 69394250, 69394372, 69394494, 69394616, 69394738, 69394860,
69394982, 69395104, 69395225, 69395346, 69395467, 69395588, 69395709,
69395830, 69395951, 69396072, 69396193, 69396314, 69396435, 69396556,
69396677, 69396798, 69396810, 69396822, 69396834, 69396846, 69396858,
69396870, 69396989, 69397108, 69397227, 69397346, 69397465, 69397584,
69397703, 69397822, 69397941, 69398060, 69398179, 69398297, 69398415,
69398533, 69398651, 69398769, 69398887, 69399005, 69399123, 69399241,
69399359, 69399477, 69399595, 69399712, 69399829, 69399946, 69400063,
69400180, 69400297, 69400414, 69400531, 69400648, 69400765, 69400882,
69400998, 69401114, 69401230, 69401346, 69401462, 69401578, 69401694,
69401810, 69401926, 69402042, 69402158, 69402273, 69402388, 69402503,
69402618, 69402733, 69402848, 69402963, 69403078, 69403193, 69403308,
69403422, 69403536, 69403650, 69403764, 69403878, 69403992, 69404106,
69404220, 69404334, 69404447, 69404560, 69404673, 69404786, 69404899,
69405012, 69405125, 69405238, 69405351, 69405464, 69405577, 69405690,
69405803, 69405915, 69406027, 69406139, 69406251, 69406363, 69406475,
69406587, 69406699, 69406811, 69406923, 69407035, 69407147, 69407259,
69407371, 69407483, 69407595, 69407707, 69407818, 69407929, 69408040,
69408151, 69408262, 69408373, 69408484, 69408595, 69408706, 69408817,
69408928, 69409039, 69409150, 69409161, 69409172, 69409183, 69409194,
69409205, 69409216, 69409227, 69409238, 69409347, 69409456, 69409565,
69409674, 69409783, 69409892, 69410001, 69410110, 69410219, 69410328,
69410437, 69410546, 69410655, 69410764, 69410873, 69410982, 69411091,
69411200, 69411309, 69411418, 69411526, 69411634, 69411742, 69411850,
69411958, 69412066, 69412174, 69412282, 69412390, 69412498, 69412606,
69412714, 69412822, 69412930, 69413037, 69413144, 69413251, 69413358,
69413465, 69413572, 69413679, 69413786, 69413893, 69414000, 69414106,
69414212, 69414318, 69414424, 69414530, 69414636, 69414742, 69414848,
69414954, 69415060, 69415166, 69415272, 69415378, 69415483, 69415588,
69415693, 69415798, 69415903, 69416008, 69416113, 69416218, 69416323,
69416428, 69416533, 69416638, 69416743, 69416847, 69416951, 69417055,
69417159, 69417263, 69417367, 69417471, 69417575, 69417679, 69417783,
69417887, 69417991, 69418095, 69418198, 69418301, 69418404, 69418507,
69418610, 69418713, 69418816, 69418919, 69419022, 69419125, 69419228,
69419331, 69419433, 69419535, 69419637, 69419739, 69419841, 69419943,
69420045, 69420147, 69420249, 69420351, 69420453, 69420555, 69420657,
69420759, 69420860, 69420961, 69421062, 69421163, 69421264, 69421365,
69421466, 69421567, 69421668, 69421769, 69421870, 69421971, 69422072,
69422173, 69422274, 69422375, 69422376, 69422377, 69422378, 69422379,
69422380, 69422381, 69422382, 69422383, 69422384, 69422385, 69422386,
69422387, 69422388, 69422389, 69422390, 69422391, 69422490, 69422589,
69422688, 69422787, 69422886, 69422985, 69423084, 69423183, 69423282,
69423381, 69423480, 69423579, 69423678, 69423777, 69423876, 69423975,
69424073, 69424171, 69424269, 69424367, 69424465, 69424563, 69424661,
69424759, 69424857, 69424954, 69425051, 69425148, 69425245, 69425342,
69425439, 69425536, 69425633, 69425730, 69425827, 69425924, 69426021,
69426118, 69426214, 69426310, 69426406, 69426502, 69426598, 69426694,
69426790, 69426886, 69426982, 69427078, 69427174, 69427270, 69427366,
69427462, 69427558, 69427653, 69427748, 69427843, 69427938, 69428033,
69428128, 69428223, 69428318, 69428413, 69428508, 69428603, 69428698,
69428793, 69428888, 69428982, 69429076, 69429170, 69429264, 69429358,
69429452, 69429546, 69429640, 69429734, 69429828, 69429922, 69430016,
69430110, 69430204, 69430298, 69430392, 69430486, 69430580, 69430673,
69430766, 69430859, 69430952, 69431045, 69431138, 69431231, 69431324,
69431417, 69431510, 69431603, 69431696, 69431789, 69431882, 69431975,
69432068, 69432161, 69432254, 69432347, 69432439, 69432531, 69432623,
69432715, 69432807, 69432899, 69432991, 69433083, 69433175, 69433267,
69433359, 69433450, 69433541, 69433632, 69433723, 69433814, 69433905,
69433996, 69434087, 69434178, 69434269, 69434360, 69434451, 69434542,
69434633, 69434724, 69434733, 69434742, 69434751, 69434760, 69434769,
69434778, 69434787, 69434796, 69434805, 69434814, 69434823, 69434912,
69435001, 69435090, 69435179, 69435268, 69435357, 69435446, 69435535,
69435624, 69435713, 69435801, 69435889, 69435977, 69436065, 69436153,
69436241, 69436329, 69436417, 69436505, 69436593, 69436681, 69436769,
69436857, 69436944, 69437031, 69437118, 69437205, 69437292, 69437379,
69437466, 69437553, 69437640, 69437727, 69437814, 69437901, 69437988,
69438075, 69438161, 69438247, 69438333, 69438419, 69438505, 69438591,
69438677, 69438763, 69438849, 69438935, 69439021, 69439107, 69439193,
69439278, 69439363, 69439448, 69439533, 69439618, 69439703, 69439788,
69439873, 69439958, 69440043, 69440128, 69440213, 69440298, 69440382,
69440466, 69440550, 69440634, 69440718, 69440802, 69440886, 69440970,
69441054, 69441138, 69441222, 69441306, 69441390, 69441474, 69441557,
69441640, 69441723, 69441806, 69441889, 69441972, 69442055, 69442138,
69442221, 69442304, 69442387, 69442470, 69442553, 69442636, 69442719,
69442802, 69442885, 69442967, 69443049, 69443131, 69443213, 69443295,
69443377, 69443459, 69443541, 69443623, 69443705, 69443787, 69443869,
69443951, 69444033, 69444115, 69444197, 69444279, 69444361, 69444443,
69444524, 69444605, 69444686, 69444767, 69444848, 69444929, 69445010,
69445091, 69445172, 69445253, 69445334, 69445415, 69445496, 69445577,
69445585, 69445593, 69445601, 69445609, 69445617, 69445625, 69445633,
69445641, 69445649, 69445657, 69445665, 69445673, 69445681, 69445689,
69445697, 69445705, 69445713, 69445721, 69445729, 69445737, 69445816,
69445895, 69445974, 69446053, 69446132, 69446211, 69446290, 69446369,
69446448, 69446527, 69446606, 69446685, 69446764, 69446843, 69446922,
69447001, 69447080, 69447159, 69447238, 69447317, 69447396, 69447475,
69447553, 69447631, 69447709, 69447787, 69447865, 69447943, 69448021,
69448099, 69448177, 69448255, 69448333, 69448411, 69448489, 69448567,
69448645, 69448722, 69448799, 69448876, 69448953, 69449030, 69449107,
69449184, 69449261, 69449338, 69449415, 69449492, 69449569, 69449646,
69449723, 69449800, 69449876, 69449952, 69450028, 69450104, 69450180,
69450256, 69450332, 69450408, 69450484, 69450560, 69450636, 69450712,
69450788, 69450864, 69450940, 69451016, 69451092, 69451168, 69451244,
69451320, 69451395, 69451470, 69451545, 69451620, 69451695, 69451770,
69451845, 69451920, 69451995, 69452070, 69452145, 69452220, 69452295,
69452370, 69452445, 69452520, 69452595, 69452670, 69452745, 69452820,
69452895, 69452970, 69453044, 69453118, 69453192, 69453266, 69453340,
69453414, 69453488, 69453562, 69453636, 69453710, 69453784, 69453858,
69453932, 69454006, 69454080, 69454154, 69454228, 69454302, 69454376,
69454450, 69454524, 69454598, 69454671, 69454744, 69454817, 69454890,
69454963, 69455036, 69455109, 69455182, 69455255, 69455328, 69455401,
69455474, 69455547, 69455620, 69455693, 69455766, 69455839, 69455912,
69455985, 69456058, 69456130, 69456202, 69456274, 69456346, 69456418,
69456490, 69456562, 69456634, 69456706, 69456778, 69456850, 69456922,
69456994, 69457066, 69457138, 69457210, 69457281, 69457352, 69457423,
69457494, 69457565, 69457636, 69457707, 69457778, 69457849, 69457920,
69457991, 69458062, 69458133, 69458204, 69458275, 69458346, 69458417,
69458488, 69458559, 69458630, 69458701, 69458772, 69458843, 69458850,
69458857, 69458864, 69458871, 69458878, 69458885, 69458892, 69458899,
69458906, 69458913, 69458920, 69458927, 69458934, 69458941, 69459010,
69459079, 69459148, 69459217, 69459286, 69459355, 69459424, 69459493,
69459562, 69459631, 69459700, 69459769, 69459838, 69459907, 69459976,
69460045, 69460114, 69460183, 69460252, 69460321, 69460390, 69460459,
69460528, 69460596, 69460664, 69460732, 69460800, 69460868, 69460936};
System.arraycopy(temp, 0, prob, 0, temp.length);
}
private static void populateProb2() {
int[] temp = new int[] {
69461004, 69461072, 69461140, 69461208, 69461276, 69461344, 69461412,
69461480, 69461548, 69461616, 69461684, 69461751, 69461818, 69461885,
69461952, 69462019, 69462086, 69462153, 69462220, 69462287, 69462354,
69462421, 69462488, 69462555, 69462622, 69462689, 69462756, 69462823,
69462889, 69462955, 69463021, 69463087, 69463153, 69463219, 69463285,
69463351, 69463417, 69463483, 69463549, 69463615, 69463681, 69463747,
69463813, 69463879, 69463945, 69464011, 69464077, 69464143, 69464209,
69464275, 69464341, 69464407, 69464473, 69464539, 69464605, 69464670,
69464735, 69464800, 69464865, 69464930, 69464995, 69465060, 69465125,
69465190, 69465255, 69465320, 69465385, 69465450, 69465515, 69465580,
69465645, 69465710, 69465775, 69465840, 69465905, 69465969, 69466033,
69466097, 69466161, 69466225, 69466289, 69466353, 69466417, 69466481,
69466545, 69466609, 69466673, 69466737, 69466801, 69466864, 69466927,
69466990, 69467053, 69467116, 69467179, 69467242, 69467305, 69467368,
69467431, 69467494, 69467557, 69467620, 69467683, 69467746, 69467809,
69467872, 69467935, 69467998, 69468061, 69468124, 69468187, 69468250,
69468313, 69468375, 69468437, 69468499, 69468561, 69468623, 69468685,
69468747, 69468809, 69468871, 69468933, 69468995, 69469057, 69469119,
69469181, 69469243, 69469305, 69469366, 69469427, 69469488, 69469549,
69469610, 69469671, 69469732, 69469793, 69469854, 69469915, 69469976,
69470037, 69470098, 69470159, 69470220, 69470281, 69470342, 69470403,
69470464, 69470525, 69470586, 69470647, 69470708, 69470714, 69470720,
69470726, 69470732, 69470738, 69470744, 69470750, 69470756, 69470762,
69470768, 69470774, 69470780, 69470786, 69470792, 69470798, 69470804,
69470810, 69470816, 69470822, 69470828, 69470834, 69470840, 69470846,
69470852, 69470858, 69470864, 69470870, 69470876, 69470882, 69470888,
69470894, 69470900, 69470959, 69471018, 69471077, 69471136, 69471195,
69471254, 69471313, 69471372, 69471431, 69471490, 69471549, 69471608,
69471667, 69471726, 69471785, 69471844, 69471903, 69471962, 69472021,
69472080, 69472139, 69472197, 69472255, 69472313, 69472371, 69472429,
69472487, 69472545, 69472603, 69472661, 69472719, 69472777, 69472835,
69472893, 69472951, 69473009, 69473067, 69473125, 69473183, 69473241,
69473299, 69473357, 69473415, 69473473, 69473531, 69473589, 69473647,
69473705, 69473762, 69473819, 69473876, 69473933, 69473990, 69474047,
69474104, 69474161, 69474218, 69474275, 69474332, 69474389, 69474446,
69474503, 69474560, 69474617, 69474674, 69474731, 69474788, 69474845,
69474902, 69474959, 69475016, 69475072, 69475128, 69475184, 69475240,
69475296, 69475352, 69475408, 69475464, 69475520, 69475576, 69475632,
69475688, 69475744, 69475800, 69475856, 69475912, 69475968, 69476024,
69476080, 69476136, 69476192, 69476248, 69476304, 69476360, 69476416,
69476471, 69476526, 69476581, 69476636, 69476691, 69476746, 69476801,
69476856, 69476911, 69476966, 69477021, 69477076, 69477131, 69477186,
69477241, 69477296, 69477351, 69477406, 69477461, 69477516, 69477571,
69477626, 69477681, 69477736, 69477791, 69477846, 69477901, 69477956,
69478010, 69478064, 69478118, 69478172, 69478226, 69478280, 69478334,
69478388, 69478442, 69478496, 69478550, 69478604, 69478658, 69478712,
69478766, 69478820, 69478874, 69478928, 69478982, 69479036, 69479090,
69479144, 69479197, 69479250, 69479303, 69479356, 69479409, 69479462,
69479515, 69479568, 69479621, 69479674, 69479727, 69479780, 69479833,
69479886, 69479939, 69479992, 69480045, 69480098, 69480151, 69480204,
69480257, 69480310, 69480363, 69480416, 69480468, 69480520, 69480572,
69480624, 69480676, 69480728, 69480780, 69480832, 69480884, 69480936,
69480988, 69481040, 69481092, 69481144, 69481196, 69481248, 69481300,
69481352, 69481404, 69481456, 69481508, 69481560, 69481612, 69481664,
69481716, 69481768, 69481820, 69481872, 69481924, 69481976, 69482028,
69482080, 69482132, 69482184, 69482236, 69482288, 69482339, 69482390,
69482441, 69482492, 69482543, 69482594, 69482645, 69482696, 69482747,
69482798, 69482849, 69482900, 69482951, 69483002, 69483053, 69483104,
69483155, 69483206, 69483257, 69483308, 69483359, 69483410, 69483461,
69483512, 69483563, 69483614, 69483665, 69483716, 69483767, 69483772,
69483777, 69483782, 69483787, 69483792, 69483797, 69483802, 69483807,
69483812, 69483817, 69483822, 69483827, 69483832, 69483837, 69483842,
69483847, 69483852, 69483857, 69483862, 69483867, 69483872, 69483877,
69483926, 69483975, 69484024, 69484073, 69484122, 69484171, 69484220,
69484269, 69484318, 69484367, 69484416, 69484465, 69484514, 69484563,
69484612, 69484661, 69484710, 69484759, 69484808, 69484857, 69484906,
69484955, 69485004, 69485053, 69485102, 69485151, 69485200, 69485249,
69485298, 69485347, 69485396, 69485445, 69485494, 69485543, 69485592,
69485641, 69485690, 69485739, 69485788, 69485837, 69485886, 69485935,
69485984, 69486033, 69486082, 69486131, 69486180, 69486229, 69486278,
69486326, 69486374, 69486422, 69486470, 69486518, 69486566, 69486614,
69486662, 69486710, 69486758, 69486806, 69486854, 69486902, 69486950,
69486998, 69487046, 69487094, 69487142, 69487190, 69487238, 69487286,
69487333, 69487380, 69487427, 69487474, 69487521, 69487568, 69487615,
69487662, 69487709, 69487756, 69487803, 69487850, 69487897, 69487944,
69487991, 69488038, 69488085, 69488132, 69488179, 69488226, 69488273,
69488320, 69488366, 69488412, 69488458, 69488504, 69488550, 69488596,
69488642, 69488688, 69488734, 69488780, 69488826, 69488872, 69488918,
69488964, 69489010, 69489056, 69489102, 69489148, 69489194, 69489240,
69489286, 69489332, 69489378, 69489424, 69489470, 69489516, 69489562,
69489608, 69489654, 69489700, 69489746, 69489792, 69489837, 69489882,
69489927, 69489972, 69490017, 69490062, 69490107, 69490152, 69490197,
69490242, 69490287, 69490332, 69490377, 69490422, 69490467, 69490512,
69490557, 69490602, 69490647, 69490692, 69490737, 69490782, 69490827,
69490872, 69490917, 69490962, 69491007, 69491052, 69491097, 69491142,
69491187, 69491232, 69491277, 69491322, 69491367, 69491411, 69491455,
69491499, 69491543, 69491587, 69491631, 69491675, 69491719, 69491763,
69491807, 69491851, 69491895, 69491939, 69491983, 69492027, 69492071,
69492115, 69492159, 69492203, 69492247, 69492291, 69492335, 69492379,
69492423, 69492467, 69492511, 69492555, 69492599, 69492643, 69492686,
69492729, 69492772, 69492815, 69492858, 69492901, 69492944, 69492987,
69493030, 69493073, 69493116, 69493159, 69493202, 69493245, 69493288,
69493331, 69493374, 69493417, 69493460, 69493503, 69493546, 69493589,
69493632, 69493675, 69493718, 69493761, 69493804, 69493847, 69493890,
69493933, 69493976, 69494019, 69494062, 69494105, 69494148, 69494191,
69494234, 69494277, 69494320, 69494363, 69494406, 69494449, 69494492,
69494535, 69494577, 69494619, 69494661, 69494703, 69494745, 69494787,
69494829, 69494871, 69494913, 69494955, 69494997, 69495039, 69495081,
69495123, 69495165, 69495207, 69495249, 69495291, 69495333, 69495375,
69495417, 69495459, 69495501, 69495543, 69495585, 69495627, 69495669,
69495711, 69495753, 69495795, 69495837, 69495879, 69495921, 69495963,
69496005, 69496047, 69496089, 69496131, 69496172, 69496213, 69496254,
69496295, 69496336, 69496377, 69496418, 69496459, 69496500, 69496541,
69496582, 69496623, 69496664, 69496705, 69496746, 69496787, 69496828,
69496869, 69496910, 69496951, 69496992, 69497033, 69497074, 69497115,
69497156, 69497197, 69497238, 69497279, 69497320, 69497361, 69497402,
69497443, 69497484, 69497525, 69497566, 69497607, 69497648, 69497689,
69497693, 69497697, 69497701, 69497705, 69497709, 69497713, 69497717,
69497721, 69497725, 69497729, 69497733, 69497737, 69497741, 69497745,
69497749, 69497753, 69497757, 69497761, 69497765, 69497769, 69497773,
69497777, 69497781, 69497785, 69497789, 69497793, 69497797, 69497801,
69497805, 69497809, 69497813, 69497817, 69497821, 69497825, 69497829,
69497868, 69497907, 69497946, 69497985, 69498024, 69498063, 69498102,
69498141, 69498180, 69498219, 69498258, 69498297, 69498336, 69498375,
69498414, 69498453, 69498492, 69498531, 69498570, 69498609, 69498648,
69498687, 69498726, 69498765, 69498804, 69498843, 69498882, 69498921,
69498960, 69498999, 69499038, 69499077, 69499116, 69499155, 69499193,
69499231, 69499269, 69499307, 69499345, 69499383, 69499421, 69499459,
69499497, 69499535, 69499573, 69499611, 69499649, 69499687, 69499725,
69499763, 69499801, 69499839, 69499877, 69499915, 69499953, 69499991,
69500029, 69500067, 69500105, 69500143, 69500181, 69500219, 69500257,
69500295, 69500333, 69500371, 69500409, 69500447, 69500484, 69500521,
69500558, 69500595, 69500632, 69500669, 69500706, 69500743, 69500780,
69500817, 69500854, 69500891, 69500928, 69500965, 69501002, 69501039,
69501076, 69501113, 69501150, 69501187, 69501224, 69501261, 69501298,
69501335, 69501372, 69501409, 69501446, 69501483, 69501520, 69501557,
69501594, 69501631, 69501667, 69501703, 69501739, 69501775, 69501811,
69501847, 69501883, 69501919, 69501955, 69501991, 69502027, 69502063,
69502099, 69502135, 69502171, 69502207, 69502243, 69502279, 69502315,
69502351, 69502387, 69502423, 69502459, 69502495, 69502531, 69502567,
69502603, 69502639, 69502675, 69502711, 69502747, 69502783, 69502819,
69502855, 69502891, 69502927, 69502963, 69502999, 69503035, 69503071,
69503107, 69503143, 69503179, 69503214, 69503249, 69503284, 69503319,
69503354, 69503389, 69503424, 69503459, 69503494, 69503529, 69503564,
69503599, 69503634, 69503669, 69503704, 69503739, 69503774, 69503809,
69503844, 69503879, 69503914, 69503949, 69503984, 69504019, 69504054,
69504089, 69504124, 69504159, 69504194, 69504229, 69504264, 69504299,
69504334, 69504369, 69504404, 69504439, 69504474, 69504509, 69504544,
69504579, 69504614, 69504649, 69504684, 69504719, 69504754, 69504789,
69504824, 69504859, 69504894, 69504929, 69504964, 69504999, 69505034,
69505068, 69505102, 69505136, 69505170, 69505204, 69505238, 69505272,
69505306, 69505340, 69505374, 69505408, 69505442, 69505476, 69505510,
69505544, 69505578, 69505612, 69505646, 69505680, 69505714, 69505748,
69505782, 69505816, 69505850, 69505884, 69505918, 69505952, 69505986,
69506020, 69506054, 69506088, 69506122, 69506156, 69506190, 69506224,
69506258, 69506292, 69506326, 69506360, 69506394, 69506427, 69506460,
69506493, 69506526, 69506559, 69506592, 69506625, 69506658, 69506691,
69506724, 69506757, 69506790, 69506823, 69506856, 69506889, 69506922,
69506955, 69506988, 69507021, 69507054, 69507087, 69507120, 69507153,
69507186, 69507219, 69507252, 69507285, 69507318, 69507351, 69507384,
69507417, 69507450, 69507483, 69507516, 69507549, 69507582, 69507615,
69507648, 69507681, 69507714, 69507747, 69507780, 69507813, 69507846,
69507879, 69507912, 69507945, 69507978, 69508011, 69508044, 69508077,
69508110, 69508143, 69508176, 69508209, 69508242, 69508275, 69508308,
69508341, 69508373, 69508405, 69508437, 69508469, 69508501, 69508533,
69508565, 69508597, 69508629, 69508661, 69508693, 69508725, 69508757,
69508789, 69508821, 69508853, 69508885, 69508917, 69508949, 69508981,
69509013, 69509045, 69509077, 69509109, 69509141, 69509173, 69509205,
69509237, 69509269, 69509301, 69509333, 69509365, 69509397, 69509429,
69509461, 69509493, 69509525, 69509557, 69509589, 69509621, 69509653,
69509685, 69509717, 69509748, 69509779, 69509810, 69509841, 69509872,
69509903, 69509934, 69509965, 69509996, 69510027, 69510058, 69510089,
69510120, 69510151, 69510182, 69510213, 69510244, 69510275, 69510306,
69510337, 69510368, 69510399, 69510430, 69510461, 69510492, 69510523,
69510554, 69510585, 69510616, 69510647, 69510678, 69510709, 69510740,
69510771, 69510802, 69510833, 69510864, 69510895, 69510926, 69510957,
69510988, 69511019, 69511050, 69511053, 69511056, 69511059, 69511062,
69511065, 69511068, 69511071, 69511074, 69511077, 69511080, 69511083,
69511086, 69511089, 69511092, 69511095, 69511098, 69511101, 69511104,
69511107, 69511110, 69511113, 69511116, 69511119, 69511122, 69511125,
69511128, 69511131, 69511134, 69511137, 69511140, 69511143, 69511146,
69511149, 69511152, 69511155, 69511158, 69511161, 69511164, 69511167,
69511170, 69511173, 69511176, 69511179, 69511182, 69511185, 69511188,
69511191, 69511194, 69511197, 69511200, 69511203, 69511206, 69511209,
69511212, 69511241, 69511270, 69511299, 69511328, 69511357, 69511386,
69511415, 69511444, 69511473, 69511502, 69511531, 69511560, 69511589,
69511618, 69511647, 69511676, 69511705, 69511734, 69511763, 69511792,
69511821, 69511850, 69511879, 69511908, 69511937, 69511966, 69511995,
69512024, 69512053, 69512082, 69512111, 69512140, 69512169, 69512198,
69512227, 69512256, 69512285, 69512314, 69512343, 69512372, 69512401,
69512430, 69512459, 69512488, 69512517, 69512545, 69512573, 69512601,
69512629, 69512657, 69512685, 69512713, 69512741, 69512769, 69512797,
69512825, 69512853, 69512881, 69512909, 69512937, 69512965, 69512993,
69513021, 69513049, 69513077, 69513105, 69513133, 69513161, 69513189,
69513217, 69513245, 69513273, 69513301, 69513329, 69513357, 69513385,
69513413, 69513441, 69513469, 69513497, 69513525, 69513553, 69513581,
69513609, 69513637, 69513665, 69513693, 69513721, 69513749, 69513777,
69513805, 69513833, 69513861, 69513889, 69513916, 69513943, 69513970,
69513997, 69514024, 69514051, 69514078, 69514105, 69514132, 69514159,
69514186, 69514213, 69514240, 69514267, 69514294, 69514321, 69514348,
69514375, 69514402, 69514429, 69514456, 69514483, 69514510, 69514537,
69514564, 69514591, 69514618, 69514645, 69514672, 69514699, 69514726,
69514753, 69514780, 69514807, 69514834, 69514861, 69514888, 69514915,
69514942, 69514969, 69514996, 69515023, 69515050, 69515077, 69515104,
69515131, 69515158, 69515185, 69515212, 69515239, 69515266, 69515293,
69515320, 69515347, 69515374, 69515401, 69515428, 69515455, 69515482,
69515509, 69515536, 69515563, 69515590, 69515617, 69515644, 69515670,
69515696, 69515722, 69515748, 69515774, 69515800, 69515826, 69515852,
69515878, 69515904, 69515930, 69515956, 69515982, 69516008, 69516034,
69516060, 69516086, 69516112, 69516138, 69516164, 69516190, 69516216,
69516242, 69516268, 69516294, 69516320, 69516346, 69516372, 69516398,
69516424, 69516450, 69516476, 69516502, 69516528, 69516554, 69516580,
69516606, 69516632, 69516658, 69516684, 69516710, 69516736, 69516762,
69516788, 69516814, 69516840, 69516866, 69516892, 69516918, 69516944,
69516970, 69516996, 69517022, 69517048, 69517074, 69517100, 69517126,
69517152, 69517178, 69517204, 69517230, 69517256, 69517282, 69517308,
69517334, 69517359, 69517384, 69517409, 69517434, 69517459, 69517484,
69517509, 69517534, 69517559, 69517584, 69517609, 69517634, 69517659,
69517684, 69517709, 69517734, 69517759, 69517784, 69517809, 69517834,
69517859, 69517884, 69517909, 69517934, 69517959, 69517984, 69518009,
69518034, 69518059, 69518084, 69518109, 69518134, 69518159, 69518184,
69518209, 69518234, 69518259, 69518284, 69518309, 69518334, 69518359,
69518384, 69518409, 69518434, 69518459, 69518484, 69518509, 69518534,
69518559, 69518584, 69518609, 69518634, 69518659, 69518684, 69518709,
69518734, 69518759, 69518784, 69518809, 69518834, 69518859, 69518884,
69518909, 69518934, 69518958, 69518982, 69519006, 69519030, 69519054,
69519078, 69519102, 69519126, 69519150, 69519174, 69519198, 69519222,
69519246, 69519270, 69519294, 69519318, 69519342, 69519366, 69519390,
69519414, 69519438, 69519462, 69519486, 69519510, 69519534, 69519558,
69519582, 69519606, 69519630, 69519654, 69519678, 69519702, 69519726,
69519750, 69519774, 69519798, 69519822, 69519846, 69519870, 69519894,
69519918, 69519942, 69519966, 69519990, 69520014, 69520038, 69520062,
69520086, 69520110, 69520134, 69520158, 69520182, 69520206, 69520230,
69520254, 69520278, 69520302, 69520326, 69520350, 69520374, 69520398,
69520422, 69520446, 69520470, 69520494, 69520518, 69520542, 69520566,
69520590, 69520614, 69520638, 69520662, 69520686, 69520710, 69520734,
69520758, 69520781, 69520804, 69520827, 69520850, 69520873, 69520896,
69520919, 69520942, 69520965, 69520988, 69521011, 69521034, 69521057,
69521080, 69521103, 69521126, 69521149, 69521172, 69521195, 69521218,
69521241, 69521264, 69521287, 69521310, 69521333, 69521356, 69521379,
69521402, 69521425, 69521448, 69521471, 69521494, 69521517, 69521540,
69521563, 69521586, 69521609, 69521632, 69521655, 69521678, 69521701,
69521724, 69521747, 69521770, 69521793, 69521816, 69521839, 69521862,
69521885, 69521908, 69521931, 69521954, 69521977, 69522000, 69522023,
69522046, 69522069, 69522092, 69522115, 69522138, 69522160, 69522182,
69522204, 69522226, 69522248, 69522270, 69522292, 69522314, 69522336,
69522358, 69522380, 69522402, 69522424, 69522446, 69522468, 69522490,
69522512, 69522534, 69522556, 69522578, 69522600, 69522622, 69522644,
69522666, 69522688, 69522710, 69522732, 69522754, 69522776, 69522798,
69522820, 69522842, 69522864, 69522886, 69522908, 69522930, 69522952,
69522974, 69522996, 69523018, 69523040, 69523062, 69523084, 69523106,
69523128, 69523150, 69523172, 69523194, 69523216, 69523238, 69523260,
69523282, 69523304, 69523326, 69523348, 69523370, 69523392, 69523414,
69523436, 69523458, 69523480, 69523502, 69523524, 69523546, 69523568,
69523590, 69523612, 69523634, 69523656, 69523678, 69523700, 69523722,
69523744, 69523765, 69523786, 69523807, 69523828, 69523849, 69523870,
69523891, 69523912, 69523933, 69523954, 69523975, 69523996, 69524017,
69524038, 69524059, 69524080, 69524101, 69524122, 69524143, 69524164,
69524185, 69524206, 69524227, 69524248, 69524269, 69524290, 69524311,
69524332, 69524353, 69524374, 69524395, 69524416, 69524437, 69524458,
69524479, 69524500, 69524521, 69524542, 69524563, 69524584, 69524605,
69524626, 69524647, 69524668, 69524689, 69524710, 69524731, 69524752,
69524773, 69524794, 69524815, 69524836, 69524857, 69524878, 69524899,
69524920, 69524941, 69524962, 69524983, 69525004, 69525025, 69525046,
69525067, 69525088, 69525109, 69525130, 69525151, 69525172, 69525193,
69525214, 69525235, 69525256, 69525277, 69525298, 69525319, 69525340,
69525361, 69525382, 69525403, 69525424, 69525445, 69525466, 69525487,
69525508, 69525529, 69525550, 69525571, 69525592, 69525594, 69525596,
69525598, 69525600, 69525602, 69525604, 69525606, 69525608, 69525610,
69525612, 69525614, 69525616, 69525618, 69525620, 69525622, 69525624,
69525626, 69525628, 69525630, 69525632, 69525634, 69525636, 69525638,
69525640, 69525642, 69525644, 69525646, 69525648, 69525650, 69525652,
69525654, 69525656, 69525658, 69525660, 69525662, 69525664, 69525666,
69525668, 69525670, 69525672, 69525674, 69525676, 69525678, 69525680,
69525682, 69525684, 69525686, 69525688, 69525690, 69525692, 69525694,
69525696, 69525698, 69525700, 69525702, 69525704, 69525706, 69525708,
69525710, 69525712, 69525714, 69525716, 69525718, 69525720, 69525722,
69525724, 69525726, 69525728, 69525730, 69525732, 69525734, 69525736,
69525738, 69525740, 69525742, 69525744, 69525746, 69525748, 69525750,
69525752, 69525754, 69525756, 69525758, 69525760, 69525762, 69525764,
69525766, 69525768, 69525770, 69525772, 69525774, 69525776, 69525778,
69525780, 69525782, 69525784, 69525786, 69525788, 69525790, 69525792,
69525794, 69525796, 69525815, 69525834, 69525853, 69525872, 69525891,
69525910, 69525929, 69525948, 69525967, 69525986, 69526005, 69526024,
69526043, 69526062, 69526081, 69526100, 69526119, 69526138, 69526157,
69526176, 69526195, 69526214, 69526233, 69526252, 69526271, 69526290,
69526309, 69526328, 69526347, 69526366, 69526385, 69526404, 69526423,
69526442, 69526461, 69526480, 69526499, 69526518, 69526537, 69526556,
69526575, 69526594, 69526613, 69526632, 69526651, 69526670, 69526689,
69526708, 69526727, 69526746, 69526765, 69526784, 69526803, 69526822,
69526841, 69526860, 69526879, 69526898, 69526917, 69526936, 69526955,
69526974, 69526993, 69527012, 69527031, 69527050, 69527069, 69527088,
69527107, 69527126, 69527145, 69527164, 69527183, 69527202, 69527221,
69527240, 69527259, 69527278, 69527297, 69527316, 69527335, 69527354,
69527373, 69527392, 69527411, 69527429, 69527447, 69527465, 69527483,
69527501, 69527519, 69527537, 69527555, 69527573, 69527591, 69527609,
69527627, 69527645, 69527663, 69527681, 69527699, 69527717, 69527735,
69527753, 69527771, 69527789, 69527807, 69527825, 69527843, 69527861,
69527879, 69527897, 69527915, 69527933, 69527951, 69527969, 69527987,
69528005, 69528023, 69528041, 69528059, 69528077, 69528095, 69528113,
69528131, 69528149, 69528167, 69528185, 69528203, 69528221, 69528239,
69528257, 69528275, 69528293, 69528311, 69528329, 69528347, 69528365,
69528383, 69528401, 69528419, 69528437, 69528455, 69528473, 69528491,
69528509, 69528527, 69528545, 69528563, 69528581, 69528599, 69528617,
69528635, 69528653, 69528671, 69528689, 69528707, 69528725, 69528743,
69528761, 69528779, 69528797, 69528814, 69528831, 69528848, 69528865,
69528882, 69528899, 69528916, 69528933, 69528950, 69528967, 69528984,
69529001, 69529018, 69529035, 69529052, 69529069, 69529086, 69529103,
69529120, 69529137, 69529154, 69529171, 69529188, 69529205, 69529222,
69529239, 69529256, 69529273, 69529290, 69529307, 69529324, 69529341,
69529358, 69529375, 69529392, 69529409, 69529426, 69529443, 69529460,
69529477, 69529494, 69529511, 69529528, 69529545, 69529562, 69529579,
69529596, 69529613, 69529630, 69529647, 69529664, 69529681, 69529698,
69529715, 69529732, 69529749, 69529766, 69529783, 69529800, 69529817,
69529834, 69529851, 69529868, 69529885, 69529902, 69529919, 69529936,
69529953, 69529970, 69529987, 69530004, 69530021, 69530038, 69530055,
69530072, 69530089, 69530106, 69530123, 69530140, 69530157, 69530174,
69530191, 69530208, 69530225, 69530242, 69530259, 69530276, 69530293,
69530310, 69530327, 69530344, 69530361, 69530378, 69530395, 69530412,
69530429, 69530446, 69530463, 69530480, 69530497, 69530514, 69530531,
69530548, 69530565, 69530582, 69530599, 69530616, 69530633, 69530650,
69530666, 69530682, 69530698, 69530714, 69530730, 69530746, 69530762,
69530778, 69530794, 69530810, 69530826, 69530842, 69530858, 69530874,
69530890, 69530906, 69530922, 69530938, 69530954, 69530970, 69530986,
69531002, 69531018, 69531034, 69531050, 69531066, 69531082, 69531098,
69531114, 69531130, 69531146, 69531162, 69531178, 69531194, 69531210,
69531226, 69531242, 69531258, 69531274, 69531290, 69531306, 69531322,
69531338, 69531354, 69531370, 69531386, 69531402, 69531418, 69531434,
69531450, 69531466, 69531482, 69531498, 69531514, 69531530, 69531546,
69531562, 69531578, 69531594, 69531610, 69531626, 69531642, 69531658,
69531674, 69531690, 69531706, 69531722, 69531738, 69531754, 69531770,
69531786, 69531802, 69531818, 69531834, 69531850, 69531866, 69531882,
69531898, 69531914, 69531930, 69531946, 69531962, 69531978, 69531994,
69532010, 69532026, 69532042, 69532058, 69532074, 69532090, 69532106,
69532122, 69532138, 69532154, 69532170, 69532186, 69532202, 69532218,
69532234, 69532250, 69532266, 69532282, 69532298, 69532314, 69532330,
69532346, 69532362, 69532378, 69532394, 69532410, 69532426, 69532442,
69532458, 69532474, 69532490, 69532506, 69532522, 69532538, 69532554,
69532569, 69532584, 69532599, 69532614, 69532629, 69532644, 69532659,
69532674, 69532689, 69532704, 69532719, 69532734, 69532749, 69532764,
69532779, 69532794, 69532809, 69532824, 69532839, 69532854, 69532869,
69532884, 69532899, 69532914, 69532929, 69532944, 69532959, 69532974,
69532989, 69533004, 69533019, 69533034, 69533049, 69533064, 69533079,
69533094, 69533109, 69533124, 69533139, 69533154, 69533169, 69533184,
69533199, 69533214, 69533229, 69533244, 69533259, 69533274, 69533289,
69533304, 69533319, 69533334, 69533349, 69533364, 69533379, 69533394,
69533409, 69533424, 69533439, 69533454, 69533469, 69533484, 69533499,
69533514, 69533529, 69533544, 69533559, 69533574, 69533589, 69533604,
69533619, 69533634, 69533649, 69533664, 69533679, 69533694, 69533709,
69533724, 69533739, 69533754, 69533769, 69533784, 69533799, 69533814,
69533829, 69533844, 69533859, 69533874, 69533889, 69533904, 69533919,
69533934, 69533949, 69533964, 69533979, 69533994, 69534009, 69534024,
69534039, 69534054, 69534069, 69534084, 69534099, 69534114, 69534129,
69534144, 69534159, 69534174, 69534189, 69534204, 69534219, 69534233,
69534247, 69534261, 69534275, 69534289, 69534303, 69534317, 69534331,
69534345, 69534359, 69534373, 69534387, 69534401, 69534415, 69534429,
69534443, 69534457, 69534471, 69534485, 69534499, 69534513, 69534527,
69534541, 69534555, 69534569, 69534583, 69534597, 69534611, 69534625,
69534639, 69534653, 69534667, 69534681, 69534695, 69534709, 69534723,
69534737, 69534751, 69534765, 69534779, 69534793, 69534807, 69534821,
69534835, 69534849, 69534863, 69534877, 69534891, 69534905, 69534919,
69534933, 69534947, 69534961, 69534975, 69534989, 69535003, 69535017,
69535031, 69535045, 69535059, 69535073, 69535087, 69535101, 69535115,
69535129, 69535143, 69535157, 69535171, 69535185, 69535199, 69535213,
69535227, 69535241, 69535255, 69535269, 69535283, 69535297, 69535311,
69535325, 69535339, 69535353, 69535367, 69535381, 69535395, 69535409,
69535423, 69535437, 69535451, 69535465, 69535479, 69535493, 69535507,
69535521, 69535535, 69535549, 69535563, 69535577, 69535591, 69535605,
69535619, 69535633, 69535647, 69535661, 69535675, 69535689, 69535703,
69535717, 69535731, 69535744, 69535757, 69535770, 69535783, 69535796,
69535809, 69535822, 69535835, 69535848, 69535861, 69535874, 69535887,
69535900, 69535913, 69535926, 69535939, 69535952, 69535965, 69535978,
69535991, 69536004, 69536017, 69536030, 69536043, 69536056, 69536069,
69536082, 69536095, 69536108, 69536121, 69536134, 69536147, 69536160,
69536173, 69536186, 69536199, 69536212, 69536225, 69536238, 69536251,
69536264, 69536277, 69536290, 69536303, 69536316, 69536329, 69536342,
69536355, 69536368, 69536381, 69536394, 69536407, 69536420, 69536433,
69536446, 69536459, 69536472, 69536485, 69536498, 69536511, 69536524,
69536537, 69536550, 69536563, 69536576, 69536589, 69536602, 69536615,
69536628, 69536641, 69536654, 69536667, 69536680, 69536693, 69536706,
69536719, 69536732, 69536745, 69536758, 69536771, 69536784, 69536797,
69536810, 69536823, 69536836, 69536849, 69536862, 69536875, 69536888,
69536901, 69536914, 69536927, 69536940, 69536953, 69536966, 69536979,
69536992, 69537005, 69537018, 69537031, 69537044, 69537057, 69537070,
69537083, 69537096, 69537109, 69537122, 69537135, 69537148, 69537161,
69537174, 69537187, 69537200, 69537213, 69537226, 69537239, 69537252,
69537265, 69537278, 69537291, 69537304, 69537317, 69537330, 69537343,
69537356, 69537369, 69537381, 69537393, 69537405, 69537417, 69537429,
69537441, 69537453, 69537465, 69537477, 69537489, 69537501, 69537513,
69537525, 69537537, 69537549, 69537561, 69537573, 69537585, 69537597,
69537609, 69537621, 69537633, 69537645, 69537657, 69537669, 69537681,
69537693, 69537705, 69537717, 69537729, 69537741, 69537753, 69537765,
69537777, 69537789, 69537801, 69537813, 69537825, 69537837, 69537849,
69537861, 69537873, 69537885, 69537897, 69537909, 69537921, 69537933,
69537945, 69537957, 69537969, 69537981, 69537993, 69538005, 69538017,
69538029, 69538041, 69538053, 69538065, 69538077, 69538089, 69538101,
69538113, 69538125, 69538137, 69538149, 69538161, 69538173, 69538185,
69538197, 69538209, 69538221, 69538233, 69538245, 69538257, 69538269,
69538281, 69538293, 69538305, 69538317, 69538329, 69538341, 69538353,
69538365, 69538377, 69538389, 69538401, 69538413, 69538425, 69538437,
69538449, 69538461, 69538473, 69538485, 69538497, 69538509, 69538521,
69538533, 69538545, 69538557, 69538569, 69538581, 69538593, 69538605,
69538617, 69538629, 69538641, 69538653, 69538665, 69538677, 69538689,
69538701, 69538713, 69538725, 69538737, 69538749, 69538761, 69538773,
69538785, 69538797, 69538809, 69538821, 69538833, 69538845, 69538857,
69538869, 69538881, 69538893, 69538904, 69538915, 69538926, 69538937,
69538948, 69538959, 69538970, 69538981, 69538992, 69539003, 69539014,
69539025, 69539036, 69539047, 69539058, 69539069, 69539080, 69539091,
69539102, 69539113, 69539124, 69539135, 69539146, 69539157, 69539168,
69539179, 69539190, 69539201, 69539212, 69539223, 69539234, 69539245,
69539256, 69539267, 69539278, 69539289, 69539300, 69539311, 69539322,
69539333, 69539344, 69539355, 69539366, 69539377, 69539388, 69539399,
69539410, 69539421, 69539432, 69539443, 69539454, 69539465, 69539476,
69539487, 69539498, 69539509, 69539520, 69539531, 69539542, 69539553,
69539564, 69539575, 69539586, 69539597, 69539608, 69539619, 69539630,
69539641, 69539652, 69539663, 69539674, 69539685, 69539696, 69539707,
69539718, 69539729, 69539740, 69539751, 69539762, 69539773, 69539784,
69539795, 69539806, 69539817, 69539828, 69539839, 69539850, 69539861,
69539872, 69539883, 69539894, 69539905, 69539916, 69539927, 69539938,
69539949, 69539960, 69539971, 69539982, 69539993, 69540004, 69540015,
69540026, 69540037, 69540048, 69540059, 69540070, 69540081, 69540092,
69540103, 69540114, 69540125, 69540136, 69540147, 69540158, 69540169,
69540180, 69540191, 69540202, 69540213, 69540224, 69540235, 69540246,
69540257, 69540268, 69540279, 69540290, 69540301, 69540312, 69540323,
69540334, 69540345, 69540356, 69540367, 69540378, 69540389, 69540400,
69540411, 69540422, 69540433, 69540444, 69540455, 69540466, 69540477,
69540488, 69540499, 69540510, 69540521, 69540532, 69540543, 69540554,
69540565, 69540576, 69540587, 69540598, 69540609, 69540620, 69540631,
69540642, 69540653, 69540664, 69540675, 69540686, 69540697, 69540698,
69540699, 69540700, 69540701, 69540702, 69540703, 69540704, 69540705,
69540706, 69540707, 69540708, 69540709, 69540710, 69540711, 69540712,
69540713, 69540714, 69540715, 69540716, 69540717, 69540718, 69540719,
69540720, 69540721, 69540722, 69540723, 69540724, 69540725, 69540726,
69540727, 69540728, 69540729, 69540730, 69540731, 69540732, 69540733,
69540734, 69540735, 69540736, 69540737, 69540738, 69540739, 69540740,
69540741, 69540742, 69540743, 69540744, 69540745, 69540746, 69540747,
69540748, 69540749, 69540750, 69540751, 69540752, 69540753, 69540754,
69540755, 69540756, 69540757, 69540758, 69540759, 69540760, 69540761,
69540762, 69540763, 69540764, 69540765, 69540766, 69540767, 69540768,
69540769, 69540770, 69540771, 69540772, 69540773, 69540774, 69540775,
69540776, 69540777, 69540778, 69540779, 69540780, 69540781, 69540782,
69540783, 69540784, 69540785, 69540786, 69540787, 69540788, 69540789,
69540790, 69540791, 69540792, 69540793, 69540794, 69540795, 69540796,
69540797, 69540798, 69540799, 69540800, 69540801, 69540802, 69540803,
69540804, 69540805, 69540806, 69540807, 69540808, 69540809, 69540810,
69540811, 69540812, 69540813, 69540814, 69540815, 69540816, 69540817,
69540818, 69540819, 69540820, 69540821, 69540822, 69540823, 69540824,
69540825, 69540826, 69540827, 69540828, 69540829, 69540830, 69540831,
69540832, 69540833, 69540834, 69540835, 69540836, 69540837, 69540838,
69540839, 69540840, 69540841, 69540842, 69540843, 69540844, 69540845,
69540846, 69540847, 69540848, 69540849, 69540850, 69540851, 69540852,
69540853, 69540854, 69540855, 69540856, 69540857, 69540858, 69540859,
69540860, 69540861, 69540862, 69540863, 69540864, 69540865, 69540866,
69540867, 69540868, 69540869, 69540870, 69540871, 69540872, 69540873,
69540874, 69540875, 69540876, 69540877, 69540878, 69540879, 69540880,
69540881, 69540882, 69540891, 69540900, 69540909, 69540918, 69540927,
69540936, 69540945, 69540954, 69540963, 69540972, 69540981, 69540990,
69540999, 69541008, 69541017, 69541026, 69541035, 69541044, 69541053,
69541062, 69541071, 69541080, 69541089, 69541098, 69541107, 69541116,
69541125, 69541134, 69541143, 69541152, 69541161, 69541170, 69541179,
69541188, 69541197, 69541206, 69541215, 69541224, 69541233, 69541242,
69541251, 69541260, 69541269, 69541278, 69541287, 69541296, 69541305,
69541314, 69541323, 69541332, 69541341, 69541350, 69541359, 69541368,
69541377, 69541386, 69541395, 69541404, 69541413, 69541422, 69541431,
69541440, 69541449, 69541458, 69541467, 69541476, 69541485, 69541494,
69541503, 69541512, 69541521, 69541530, 69541539, 69541548, 69541557,
69541566, 69541575, 69541584, 69541593, 69541602, 69541611, 69541620,
69541629, 69541638, 69541647, 69541656, 69541665, 69541674, 69541683,
69541692, 69541701, 69541710, 69541719, 69541728, 69541737, 69541746,
69541755, 69541764, 69541773, 69541782, 69541791, 69541800, 69541809,
69541818, 69541827, 69541836, 69541845, 69541854, 69541863, 69541872,
69541881, 69541890, 69541899, 69541908, 69541917, 69541926, 69541935,
69541944, 69541953, 69541962, 69541971, 69541980, 69541989, 69541998,
69542007, 69542016, 69542025, 69542034, 69542043, 69542052, 69542061,
69542070, 69542079, 69542088, 69542097, 69542106, 69542115, 69542124,
69542133, 69542142, 69542151, 69542160, 69542169, 69542178, 69542187,
69542196, 69542205, 69542214, 69542223, 69542232, 69542241, 69542250,
69542259, 69542268, 69542277, 69542286, 69542295, 69542304, 69542313,
69542322, 69542331, 69542340, 69542349, 69542358, 69542367, 69542376,
69542385, 69542394, 69542403, 69542412, 69542421, 69542430, 69542439,
69542448, 69542457, 69542466, 69542475, 69542484, 69542493, 69542502,
69542511, 69542520, 69542529, 69542538, 69542547, 69542556, 69542565,
69542574, 69542583, 69542592, 69542601, 69542610, 69542619, 69542628,
69542637, 69542646, 69542655, 69542664, 69542673, 69542682, 69542691,
69542700, 69542709, 69542718, 69542727, 69542736, 69542745, 69542753,
69542761, 69542769, 69542777, 69542785, 69542793, 69542801, 69542809,
69542817, 69542825, 69542833, 69542841, 69542849, 69542857, 69542865,
69542873, 69542881, 69542889, 69542897, 69542905, 69542913, 69542921,
69542929, 69542937, 69542945, 69542953, 69542961, 69542969, 69542977,
69542985, 69542993, 69543001, 69543009, 69543017, 69543025, 69543033,
69543041, 69543049, 69543057, 69543065, 69543073, 69543081, 69543089,
69543097, 69543105, 69543113, 69543121, 69543129, 69543137, 69543145,
69543153, 69543161, 69543169, 69543177, 69543185, 69543193, 69543201,
69543209, 69543217, 69543225, 69543233, 69543241, 69543249, 69543257,
69543265, 69543273, 69543281, 69543289, 69543297, 69543305, 69543313,
69543321, 69543329, 69543337, 69543345, 69543353, 69543361, 69543369,
69543377, 69543385, 69543393, 69543401, 69543409, 69543417, 69543425,
69543433, 69543441, 69543449, 69543457, 69543465, 69543473, 69543481,
69543489, 69543497, 69543505, 69543513, 69543521, 69543529, 69543537,
69543545, 69543553, 69543561, 69543569, 69543577, 69543585, 69543593,
69543601, 69543609, 69543617, 69543625, 69543633, 69543641, 69543649,
69543657, 69543665, 69543673, 69543681, 69543689, 69543697, 69543705,
69543713, 69543721, 69543729, 69543737, 69543745, 69543753, 69543761,
69543769, 69543777, 69543785, 69543793, 69543801, 69543809, 69543817,
69543825, 69543833, 69543841, 69543849, 69543857, 69543865, 69543873,
69543881, 69543889, 69543897, 69543905, 69543913, 69543921, 69543929,
69543937, 69543945, 69543953, 69543961, 69543969, 69543977, 69543985,
69543993, 69544001, 69544009, 69544017, 69544025, 69544033, 69544041,
69544049, 69544057, 69544065, 69544073, 69544081, 69544089, 69544097,
69544105, 69544113, 69544121, 69544129, 69544137, 69544145, 69544153,
69544161, 69544169, 69544177, 69544185, 69544193, 69544201, 69544209,
69544217, 69544225, 69544233, 69544241, 69544249, 69544257, 69544265,
69544273, 69544281, 69544289, 69544297, 69544305, 69544313, 69544321,
69544329, 69544337, 69544345, 69544353, 69544361, 69544369, 69544377,
69544385, 69544393, 69544401, 69544409, 69544417, 69544425, 69544433,
69544441, 69544449, 69544457, 69544465, 69544473, 69544481, 69544489,
69544497, 69544505, 69544513, 69544521, 69544529, 69544537, 69544545,
69544553, 69544561, 69544569, 69544577, 69544585, 69544593, 69544601,
69544609, 69544617, 69544625, 69544633, 69544641, 69544649, 69544657,
69544665, 69544673, 69544681, 69544689, 69544697, 69544705, 69544713,
69544721, 69544729, 69544737, 69544745, 69544753, 69544761, 69544769,
69544777, 69544785, 69544793, 69544800, 69544807, 69544814, 69544821,
69544828, 69544835, 69544842, 69544849, 69544856, 69544863, 69544870,
69544877, 69544884, 69544891, 69544898, 69544905, 69544912, 69544919,
69544926, 69544933, 69544940, 69544947, 69544954, 69544961, 69544968,
69544975, 69544982, 69544989, 69544996, 69545003, 69545010, 69545017,
69545024, 69545031, 69545038, 69545045, 69545052, 69545059, 69545066,
69545073, 69545080, 69545087, 69545094, 69545101, 69545108, 69545115,
69545122, 69545129, 69545136, 69545143, 69545150, 69545157, 69545164,
69545171, 69545178, 69545185, 69545192, 69545199, 69545206, 69545213,
69545220, 69545227, 69545234, 69545241, 69545248, 69545255, 69545262,
69545269, 69545276, 69545283, 69545290, 69545297, 69545304, 69545311,
69545318, 69545325, 69545332, 69545339, 69545346, 69545353, 69545360,
69545367, 69545374, 69545381, 69545388, 69545395, 69545402, 69545409,
69545416, 69545423, 69545430, 69545437, 69545444, 69545451, 69545458,
69545465, 69545472, 69545479, 69545486, 69545493, 69545500, 69545507,
69545514, 69545521, 69545528, 69545535, 69545542, 69545549, 69545556,
69545563, 69545570, 69545577, 69545584, 69545591, 69545598, 69545605,
69545612, 69545619, 69545626, 69545633, 69545640, 69545647, 69545654,
69545661, 69545668, 69545675, 69545682, 69545689, 69545696, 69545703,
69545710, 69545717, 69545724, 69545731, 69545738, 69545745, 69545752,
69545759, 69545766, 69545773, 69545780, 69545787, 69545794, 69545801,
69545808, 69545815, 69545822, 69545829, 69545836, 69545843, 69545850,
69545857, 69545864, 69545871, 69545878, 69545885, 69545892, 69545899,
69545906, 69545913, 69545920, 69545927, 69545934, 69545941, 69545948,
69545955, 69545962, 69545969, 69545976, 69545983, 69545990, 69545997,
69546004, 69546011, 69546018, 69546025, 69546032, 69546039, 69546046,
69546053, 69546060, 69546067, 69546074, 69546081, 69546088, 69546095,
69546102, 69546109, 69546116, 69546123, 69546130, 69546137, 69546144,
69546151, 69546158, 69546165, 69546172, 69546179, 69546186, 69546193,
69546200, 69546207, 69546214, 69546221, 69546228, 69546235, 69546242,
69546249, 69546256, 69546263, 69546270, 69546277, 69546284, 69546291,
69546298, 69546305, 69546312, 69546319, 69546326, 69546333, 69546340,
69546347, 69546354, 69546361, 69546368, 69546375, 69546382, 69546389,
69546396, 69546403, 69546410, 69546417, 69546424, 69546431, 69546438,
69546445, 69546452, 69546459, 69546466, 69546473, 69546480, 69546487,
69546494, 69546501, 69546508, 69546515, 69546522, 69546529, 69546536,
69546543, 69546550, 69546557, 69546564, 69546571, 69546578, 69546585,
69546592, 69546599, 69546605, 69546611, 69546617, 69546623, 69546629,
69546635, 69546641, 69546647, 69546653, 69546659, 69546665, 69546671,
69546677, 69546683, 69546689, 69546695, 69546701, 69546707, 69546713,
69546719, 69546725, 69546731, 69546737, 69546743, 69546749, 69546755,
69546761, 69546767, 69546773, 69546779, 69546785, 69546791, 69546797,
69546803, 69546809, 69546815, 69546821, 69546827, 69546833, 69546839,
69546845, 69546851, 69546857, 69546863, 69546869, 69546875, 69546881,
69546887, 69546893, 69546899, 69546905, 69546911, 69546917, 69546923,
69546929, 69546935, 69546941, 69546947, 69546953, 69546959, 69546965,
69546971, 69546977, 69546983, 69546989, 69546995, 69547001, 69547007,
69547013, 69547019, 69547025, 69547031, 69547037, 69547043, 69547049,
69547055, 69547061, 69547067, 69547073, 69547079, 69547085, 69547091,
69547097, 69547103, 69547109, 69547115, 69547121, 69547127, 69547133,
69547139, 69547145, 69547151, 69547157, 69547163, 69547169, 69547175,
69547181, 69547187, 69547193, 69547199, 69547205, 69547211, 69547217,
69547223, 69547229, 69547235, 69547241, 69547247, 69547253, 69547259,
69547265, 69547271, 69547277, 69547283, 69547289, 69547295, 69547301,
69547307, 69547313, 69547319, 69547325, 69547331, 69547337, 69547343,
69547349, 69547355, 69547361, 69547367, 69547373, 69547379, 69547385,
69547391, 69547397, 69547403, 69547409, 69547415, 69547421, 69547427,
69547433, 69547439, 69547445, 69547451, 69547457, 69547463, 69547469,
69547475, 69547481, 69547487, 69547493, 69547499, 69547505, 69547511,
69547517, 69547523, 69547529, 69547535, 69547541, 69547547, 69547553,
69547559, 69547565, 69547571, 69547577, 69547583, 69547589, 69547595,
69547601, 69547607, 69547613, 69547619, 69547625, 69547631, 69547637,
69547643, 69547649, 69547655, 69547661, 69547667, 69547673, 69547679,
69547685, 69547691, 69547697, 69547703, 69547709, 69547715, 69547721,
69547727, 69547733, 69547739, 69547745, 69547751, 69547757, 69547763,
69547769, 69547775, 69547781, 69547787, 69547793, 69547799, 69547805,
69547811, 69547817, 69547823, 69547829, 69547835, 69547841, 69547847,
69547853, 69547859, 69547865, 69547871, 69547877, 69547883, 69547889,
69547895, 69547901, 69547907, 69547913, 69547919, 69547925, 69547931,
69547937, 69547943, 69547949, 69547955, 69547961, 69547967, 69547973,
69547979, 69547985, 69547991, 69547997, 69548003, 69548009, 69548015,
69548021, 69548027, 69548033, 69548039, 69548045, 69548051, 69548057,
69548063, 69548069, 69548075, 69548081, 69548087, 69548093, 69548099,
69548105, 69548111, 69548117, 69548123, 69548129, 69548135, 69548141,
69548147, 69548153, 69548159, 69548165, 69548171, 69548177, 69548183,
69548189, 69548195, 69548201, 69548207, 69548213, 69548219, 69548225,
69548231, 69548237, 69548243, 69548249, 69548255, 69548261, 69548267,
69548273, 69548279, 69548285, 69548291, 69548297, 69548303, 69548309,
69548315, 69548321, 69548327, 69548333, 69548339, 69548345, 69548351,
69548357, 69548363, 69548369, 69548375, 69548381, 69548387, 69548393,
69548399, 69548405, 69548411, 69548416, 69548421, 69548426, 69548431,
69548436, 69548441, 69548446, 69548451, 69548456, 69548461, 69548466,
69548471, 69548476, 69548481, 69548486, 69548491, 69548496, 69548501,
69548506, 69548511, 69548516, 69548521, 69548526, 69548531, 69548536,
69548541, 69548546, 69548551, 69548556, 69548561, 69548566, 69548571,
69548576, 69548581, 69548586, 69548591, 69548596, 69548601, 69548606,
69548611, 69548616, 69548621, 69548626, 69548631, 69548636, 69548641,
69548646, 69548651, 69548656, 69548661, 69548666, 69548671, 69548676,
69548681, 69548686, 69548691, 69548696, 69548701, 69548706, 69548711,
69548716, 69548721, 69548726, 69548731, 69548736, 69548741, 69548746,
69548751, 69548756, 69548761, 69548766, 69548771, 69548776, 69548781,
69548786, 69548791, 69548796, 69548801, 69548806, 69548811, 69548816,
69548821, 69548826, 69548831, 69548836, 69548841, 69548846, 69548851,
69548856, 69548861, 69548866, 69548871, 69548876, 69548881, 69548886,
69548891, 69548896, 69548901, 69548906, 69548911, 69548916, 69548921,
69548926, 69548931, 69548936, 69548941, 69548946, 69548951, 69548956,
69548961, 69548966, 69548971, 69548976, 69548981, 69548986, 69548991,
69548996, 69549001, 69549006, 69549011, 69549016, 69549021, 69549026,
69549031, 69549036, 69549041, 69549046, 69549051, 69549056, 69549061,
69549066, 69549071, 69549076, 69549081, 69549086, 69549091, 69549096,
69549101, 69549106, 69549111, 69549116, 69549121, 69549126, 69549131,
69549136, 69549141, 69549146, 69549151, 69549156, 69549161, 69549166,
69549171, 69549176, 69549181, 69549186, 69549191, 69549196, 69549201,
69549206, 69549211, 69549216, 69549221, 69549226, 69549231, 69549236,
69549241, 69549246, 69549251, 69549256, 69549261, 69549266, 69549271,
69549276, 69549281, 69549286, 69549291, 69549296, 69549301, 69549306,
69549311, 69549316, 69549321, 69549326, 69549331, 69549336, 69549341,
69549346, 69549351, 69549356, 69549361, 69549366, 69549371, 69549376,
69549381, 69549386, 69549391, 69549396, 69549401, 69549406, 69549411,
69549416, 69549421, 69549426, 69549431, 69549436, 69549441, 69549446,
69549451, 69549456, 69549461, 69549466, 69549471, 69549476, 69549481,
69549486, 69549491, 69549496, 69549501, 69549506, 69549511, 69549516,
69549521, 69549526, 69549531, 69549536, 69549541, 69549546, 69549551,
69549556, 69549561, 69549566, 69549571, 69549576, 69549581, 69549586,
69549591, 69549596, 69549601, 69549606, 69549611, 69549616, 69549621,
69549626, 69549631, 69549636, 69549641, 69549646, 69549651, 69549656,
69549661, 69549666, 69549671, 69549676, 69549681, 69549686, 69549691,
69549696, 69549701, 69549706, 69549711, 69549716, 69549721, 69549726,
69549731, 69549736, 69549741, 69549746, 69549751, 69549756, 69549761,
69549766, 69549771, 69549776, 69549781, 69549786, 69549791, 69549796,
69549801, 69549806, 69549811, 69549816, 69549821, 69549826, 69549831,
69549836, 69549841, 69549846, 69549851, 69549856, 69549861, 69549866,
69549871, 69549876, 69549881, 69549886, 69549891, 69549896, 69549901,
69549906, 69549911, 69549916, 69549921, 69549926, 69549931, 69549936,
69549941, 69549946, 69549951, 69549956, 69549961, 69549966, 69549971,
69549976, 69549981, 69549986, 69549991, 69549996, 69550001, 69550006,
69550011, 69550016, 69550021, 69550026, 69550031, 69550036, 69550041,
69550046, 69550051, 69550056, 69550061, 69550066, 69550071, 69550076,
69550081, 69550086, 69550091, 69550096, 69550101, 69550106, 69550111,
69550116, 69550121, 69550126, 69550131, 69550136, 69550141, 69550146,
69550151, 69550156, 69550161, 69550166, 69550171, 69550176, 69550181,
69550186, 69550191, 69550196, 69550201, 69550206, 69550211, 69550216,
69550221, 69550226, 69550231, 69550236, 69550241, 69550246, 69550251,
69550256, 69550261, 69550266, 69550271, 69550276, 69550281, 69550286,
69550291, 69550296, 69550301, 69550306, 69550311, 69550316, 69550321,
69550326, 69550331, 69550336, 69550341, 69550346, 69550351, 69550356,
69550361, 69550366, 69550371, 69550376, 69550381, 69550386, 69550390,
69550394, 69550398, 69550402, 69550406, 69550410, 69550414, 69550418,
69550422, 69550426, 69550430, 69550434, 69550438, 69550442, 69550446,
69550450, 69550454, 69550458, 69550462, 69550466, 69550470, 69550474,
69550478, 69550482, 69550486, 69550490, 69550494, 69550498, 69550502,
69550506, 69550510, 69550514, 69550518, 69550522, 69550526, 69550530,
69550534, 69550538, 69550542, 69550546, 69550550, 69550554, 69550558,
69550562, 69550566, 69550570, 69550574, 69550578, 69550582, 69550586,
69550590, 69550594, 69550598, 69550602, 69550606, 69550610, 69550614,
69550618, 69550622, 69550626, 69550630, 69550634, 69550638, 69550642,
69550646, 69550650, 69550654, 69550658, 69550662, 69550666, 69550670,
69550674, 69550678, 69550682, 69550686, 69550690, 69550694, 69550698,
69550702, 69550706, 69550710, 69550714, 69550718, 69550722, 69550726,
69550730, 69550734, 69550738, 69550742, 69550746, 69550750, 69550754,
69550758, 69550762, 69550766, 69550770, 69550774, 69550778, 69550782,
69550786, 69550790, 69550794, 69550798, 69550802, 69550806, 69550810,
69550814, 69550818, 69550822, 69550826, 69550830, 69550834, 69550838,
69550842, 69550846, 69550850, 69550854, 69550858, 69550862, 69550866,
69550870, 69550874, 69550878, 69550882, 69550886, 69550890, 69550894,
69550898, 69550902, 69550906, 69550910, 69550914, 69550918, 69550922,
69550926, 69550930, 69550934, 69550938, 69550942, 69550946, 69550950,
69550954, 69550958, 69550962, 69550966, 69550970, 69550974, 69550978,
69550982, 69550986, 69550990, 69550994, 69550998, 69551002, 69551006,
69551010, 69551014, 69551018, 69551022, 69551026, 69551030, 69551034,
69551038, 69551042, 69551046, 69551050, 69551054, 69551058, 69551062,
69551066, 69551070, 69551074, 69551078, 69551082, 69551086, 69551090,
69551094, 69551098, 69551102, 69551106, 69551110, 69551114, 69551118,
69551122, 69551126, 69551130, 69551134, 69551138, 69551142, 69551146,
69551150, 69551154, 69551158, 69551162, 69551166, 69551170, 69551174,
69551178, 69551182, 69551186, 69551190, 69551194, 69551198, 69551202,
69551206, 69551210, 69551214, 69551218, 69551222, 69551226, 69551230,
69551234, 69551238, 69551242, 69551246, 69551250, 69551254, 69551258,
69551262, 69551266, 69551270, 69551274, 69551278, 69551282, 69551286,
69551290, 69551294, 69551298, 69551302, 69551306, 69551310, 69551314,
69551318, 69551322, 69551326, 69551330, 69551334, 69551338, 69551342,
69551346, 69551350, 69551354, 69551358, 69551362, 69551366, 69551370,
69551374, 69551378, 69551382, 69551386, 69551390, 69551394, 69551398,
69551402, 69551406, 69551410, 69551414, 69551418, 69551422, 69551426,
69551430, 69551434, 69551438, 69551442, 69551446, 69551450, 69551454,
69551458, 69551462, 69551466, 69551470, 69551474, 69551478, 69551482,
69551486, 69551490, 69551494, 69551498, 69551502, 69551506, 69551510,
69551514, 69551518, 69551522, 69551526, 69551530, 69551534, 69551538,
69551542, 69551546, 69551550, 69551554, 69551558, 69551562, 69551566,
69551570, 69551574, 69551578, 69551582, 69551586, 69551590, 69551594,
69551598, 69551602, 69551606, 69551610, 69551614, 69551618, 69551622,
69551626, 69551630, 69551634, 69551638, 69551642, 69551646, 69551650,
69551654, 69551658, 69551662, 69551666, 69551670, 69551674, 69551678,
69551682, 69551686, 69551690, 69551694, 69551698, 69551702, 69551706,
69551710, 69551714, 69551718, 69551722, 69551726, 69551730, 69551734,
69551738, 69551742, 69551746, 69551750, 69551754, 69551758, 69551762,
69551766, 69551770, 69551774, 69551778, 69551782, 69551786, 69551790,
69551794, 69551798, 69551802, 69551806, 69551810, 69551814, 69551818,
69551822, 69551826, 69551830, 69551834, 69551838, 69551842, 69551846,
69551850, 69551854, 69551858, 69551862, 69551866, 69551870, 69551874,
69551878, 69551882, 69551886, 69551890, 69551894, 69551898, 69551902,
69551906, 69551910, 69551914, 69551918, 69551922, 69551926, 69551930,
69551934, 69551938, 69551942, 69551946, 69551950, 69551954, 69551958,
69551962, 69551966, 69551970, 69551974, 69551978, 69551982, 69551986,
69551990, 69551994, 69551998, 69552002, 69552006, 69552010, 69552014,
69552018, 69552022, 69552026, 69552030, 69552034, 69552038, 69552042,
69552046, 69552050, 69552054, 69552058, 69552062, 69552066, 69552070,
69552074, 69552078, 69552082, 69552086, 69552090, 69552094, 69552098,
69552102, 69552106, 69552110, 69552114, 69552118, 69552122, 69552126,
69552130, 69552134, 69552138, 69552142, 69552146, 69552150, 69552154,
69552158, 69552162, 69552166, 69552170, 69552174, 69552178, 69552182,
69552186, 69552190, 69552194, 69552198, 69552202, 69552206, 69552210,
69552214, 69552218};
System.arraycopy(temp, 0, prob, prob.length - temp.length, temp.length);
}
private static int[] chars;
private static void populateChars1() {
chars = new int[10002];
int[] temp = new int[] {32, 9, 10, 101, 97, 13, 105, 111,
110, 116, 114, 115, 108, 100, 99, 117, 109, 104, 112, 103, 48, 46,
98, 49, 160, 102, 50, 118, 121, 107, 44, 119, 45, 58, 51, 53, 52,
57, 56, 106, 54, 122, 55, 47, 41, 40, 124, 120, 1103, 1072, 1086,
113, 1080, 1575, 1077, 1085, 1090, 12540, 1088, 12398, 95, 1089, 39,
1604, 33, 233, 12290, 30340, 1083, 1074, 12289, 12531, 1082, 12356,
34, 3634, 91, 93, 63, 62, 1076, 225, 1605, 1084, 3609, 1610, 12395,
12375, 1585, 1087, 1608, 12391, 12488, 3619, 1091, 12390, 243, 12377,
1606, 61, 3629, 12473, 1578, 12427, 42, 12394, 12452, 12483, 12383,
12539, 3656, 12392, 3648, 12434, 3585, 12414, 12399, 237, 38, 19968,
12523, 1075, 20154, 12463, 252, 3617, 305, 3657, 3591, 59, 12364,
1073, 1583, 1099, 1079, 1576, 20013, 224, 3633, 12363, 26085, 1607,
43, 228, 12522, 12435, 12521, 12426, 12387, 22823, 3623, 24180, 231,
12450, 3621, 3618, 26377, 1100, 3604, 1081, 1587, 1593, 29992, 3637,
12425, 37, 246, 26032, 3588, 19981, 3626, 12373, 12418, 26159, 12371,
60, 21697, 22312, 26376, 3607, 12464, 3636, 3610, 1095, 12471, 12525,
2366, 19978, 12362, 126, 12358, 187, 12503, 227, 12479, 12428, 1577,
3627, 1093, 25105, 12524, 12367, 3605, 945, 20998, 20250, 12489, 26412,
12501, 183, 23398, 12467, 22269, 29983, 1601, 273, 3021, 8220, 8221,
20316, 1602, 1603, 35, 25991, 12472, 20102, 12513, 64, 3632, 12354,
12502, 12365, 22320, 20986, 34892, 23376, 32593, 51060, 21457, 12459,
21517, 8230, 2381, 19979, 1497, 12384, 2352, 1493, 36, 1078, 12486,
1740, 12510, 23567, 8226, 32773, 1600, 1588, 234, 26041, 959, 26368,
3611, 26102, 12496, 12469, 1094, 23478, 1581, 3405, 20837, 3614, 3649,
250, 22238, 964, 20010, 24773, 20844, 24066, 20197, 29702, 953, 1609,
1110, 21512, 949, 34920, 12461, 351, 20840, 21069, 35201, 20107, 33258,
12424, 1580, 232, 1101, 20214, 12481, 12300, 3652, 26009, 3586, 25163,
12301, 3592, 21644, 21487, 33021, 12304, 12451, 21830, 8211, 322,
1096, 2325, 12305, 22825, 25104, 12369, 39640, 21152, 12512, 3660,
12385, 241, 20026, 3639, 20869, 23450, 20449, 1092, 4304, 22909, 25968,
37329, 22810, 12458, 26469, 3640, 30005, 21040, 27861, 24037, 19994,
957, 4312, 12381, 3641, 26426, 30475, 37096, 26178, 2375, 24515, 169,
12491, 92, 3594, 32654, 31532, 12388, 24615, 12517, 28857, 12454,
21306, 2344, 36890, 12415, 65533, 12379, 244, 1492, 1377, 12499, 963,
2367, 28961, 20027, 26399, 32034, 45796, 35770, 255, 432, 12487, 12456,
22899, 20182, 25152, 29289, 12519, 44592, 3277, 1102, 12515, 1582,
226, 1589, 20307, 1586, 30011, 2360, 31995, 353, 29256, 229, 12393,
20851, 21160, 36947, 38388, 1571, 1500, 20110, 8212, 39029, 961, 26126,
12417, 27700, 12360, 2965, 3650, 30456, 36825, 12497, 3651, 26684,
28023, 3149, 1512, 31038, 24230, 24215, 20870, 22577, 1514, 12475,
22270, 12420, 30331, 12511, 30446, 94, 12372, 38754, 26381, 30693,
12431, 25945, 21518, 22806, 26356, 954, 21451, 23665, 35211, 2340,
27880, 21205, 3007, 960, 2350, 21270, 23433, 1591, 2368, 29305, 20301,
20320, 12490, 39064, 32463, 21147, 31034, 51648, 20135, 21033, 23601,
24687, 38382, 19977, 37117, 24335, 44032, 951, 4308, 2354, 21153,
3655, 21516, 12509, 269, 21271, 7841, 8364, 9733, 25237, 31449, 12480,
20204, 2980, 38291, 20445, 1502, 21496, 51032, 3009, 49828, 20803,
36164, 281, 2351, 45716, 12506, 20140, 24403, 36865, 21495, 20043,
20351, 38598, 235, 12474, 7871, 23545, 49324, 24847, 27425, 236, 20195,
24471, 956, 26908, 347, 1488, 31185, 47196, 261, 2346, 1489, 12441,
24320, 171, 20385, 32447, 54616, 35352, 380, 38480, 125, 27963, 50640,
287, 23458, 3635, 1097, 7879, 123, 3263, 22120, 12484, 7843, 601,
955, 19982, 12527, 31561, 39318, 12493, 36710, 31649, 20215, 30495,
20132, 35828, 22914, 27491, 12408, 1398, 21407, 22580, 1590, 25552,
35328, 44256, 21046, 962, 2357, 27671, 2379, 35199, 965, 3248, 257,
20108, 49884, 382, 20063, 36807, 20040, 1513, 51064, 24863, 35780,
23481, 47532, 12455, 26524, 51088, 25216, 2306, 245, 29616, 24314,
35013, 21335, 21462, 29255, 26597, 31572, 37325, 19987, 33394, 54620,
1705, 12465, 21578, 4320, 25151, 35299, 38899, 20170, 21475, 12495,
24179, 31243, 31354, 25253, 21839, 12500, 31934, 30528, 2361, 26989,
35270, 20854, 37324, 27969, 23383, 12514, 12376, 28216, 25910, 24433,
30476, 4153, 3262, 35774, 19975, 2986, 1408, 32852, 22411, 12477,
48372, 22797, 21450, 12419, 23454, 36827, 39135, 9632, 253, 9658,
4321, 259, 25628, 36335, 12460, 240, 2990, 45768, 20687, 32771, 3391,
37327, 21326, 21488, 12507, 248, 223, 24605, 38651, 96, 20855, 12429,
12397, 35745, 3349, 31435, 24819, 49436, 2992, 24191, 24341, 3120,
22522, 51012, 21592, 1400, 50500, 25509, 24212, 12505, 38271, 24405,
7897, 26080, 24030, 24120, 33457, 20809, 22478, 12298, 20876, 27714,
1504, 20184, 7899, 35831, 12299, 3612, 20309, 32423, 3134, 20048,
27665, 36733, 20379, 19990, 28040, 26481, 1574, 3606, 26360, 3135,
23453, 30000, 26415, 7845, 3006, 28982, 24744, 21435, 176, 2750, 1501,
36215, 31070, 30330, 27604, 25512, 36824, 22330, 19996, 30007, 230,
38306, 27231, 51221, 1381, 27005, 2975, 22363, 4317, 21482, 20808,
25345, 35777, 3137, 36523, 32946, 36554, 36817, 21307, 31867, 38376,
51068, 25918, 26143, 947, 3265, 25143, 23637, 26435, 7889, 242, 50612,
12468, 33521, 38498, 26631, 943, 31295, 12400, 35239, 12449, 2342,
24086, 1506, 3368, 21338, 12504, 37682, 20070, 21313, 249, 23569,
25351, 35805, 27809, 30740, 29233, 25903, 49688, 1491, 7901, 7853,
46020, 26408, 24067, 1573, 20171, 37197, 2369, 1594, 2327, 263, 26465,
45824, 25171, 25919, 3603, 28909, 32780, 31456, 28304, 948, 7873,
24460, 26495, 3376, 51204, 37027, 30333, 26696, 3240, 38283, 24456,
12508, 940, 51228, 20877, 30334, 39057, 3624, 4315, 3390, 49345, 238,
36153, 30721, 24029, 9734, 32622, 20225, 20849, 21463, 53944, 22235,
21161, 21543, 36796, 26657, 51008, 25110, 30028, 2332, 27492, 21608,
34255, 20889, 2997, 3221, 21521, 4314, 12494, 30001, 24555, 27004,
27743, 21476, 22770, 30452, 2494, 417, 1495, 969, 46972, 24050, 1569,
3112, 1579, 28779, 1508, 2994, 12409, 2985, 31119, 20219, 21333, 12457,
26053, 165, 44536, 32004, 2348, 35760, 22791, 36899, 3595, 23558,
22240, 9830, 35373, 3615, 31181, 20160, 1511, 35441, 12466, 36141,
3223, 3122, 22763, 1584, 38263, 32769, 12470, 7911, 29579, 4305, 22303,
1199, 21442, 50896, 51452, 20462, 28165, 20256, 35821, 45208, 20813,
24418, 972, 32479, 26448, 39118, 35413, 1387, 3270, 21021, 21015,
46300, 23436, 3608, 3238, 31350, 36895, 1570, 24072, 7875, 35813,
3074, 22768, 1499, 21002, 21253, 1548, 34987, 37326, 4316, 1662, 20303,
3393, 26679, 7847, 4152, 35797, 50836, 38750, 26395, 36896, 21508,
26131, 35835, 3236, 35486, 2335, 24517, 21035, 21029, 44172, 21453,
29699, 12378, 44396, 30149, 39321, 3638, 46041, 7883, 1711, 29694,
12423, 3364, 4140, 32032, 3616, 8222, 3250, 27835, 59179, 36229, 3093,
23627, 25506, 7907, 27468, 54868, 22836, 941, 8594, 22826, 23550,
20491, 23460, 30707, 3256, 27454, 32467, 9679, 20581, 27668, 20415,
31246, 33391, 25165, 26410, 20116, 36873, 3654, 36816, 1410, 12442,
36074, 49457, 38500, 1505, 21019, 25307, 36716, 2480, 21619, 54644,
3625, 24049, 25490, 30701, 47484, 2330, 3016, 2736, 191, 21729, 1257,
1098, 30041, 49548, 25103, 48708, 20570, 31080, 21151, 37202, 31169,
20174, 27169, 49888, 20123, 51109, 25454, 32929, 35215, 4309, 32080,
25972, 25913, 180, 2970, 50689, 38738, 20294, 12302, 2991, 21345,
20104, 32218, 35443, 12403, 23455, 215, 20999, 23548, 31215, 32473,
30058, 30465, 23384, 48512, 28145, 12303, 4307, 47928, 24859, 26519,
2995, 33410, 50857, 24535, 12516, 39564, 32452, 36148, 942, 20004,
27096, 3370, 38988, 36617, 38405, 26149, 28436, 29366, 23798, 38450,
36984, 24635, 21360, 35336, 8250, 966, 24110, 32048, 36820, 2509,
24247, 36861, 3253, 3378, 174, 163, 186, 26449, 36719, 12416, 254,
51080, 36009, 23616, 47560, 1396, 32454, 29031, 31639, 29575, 3597,
3246, 33853, 38395, 2503, 36136, 54924, 35265, 24182, 2622, 24352,
23621, 48120, 2358, 22987, 7885, 44277, 36039, 31505, 3202, 50668,
24425, 4145, 20987, 35268, 952, 25773, 251, 967, 3128, 12411, 7909,
283, 23494, 47564, 32476, 33616, 3851, 2728, 30010, 20799, 33829,
49464, 3375, 24378, 44397, 4323, 4322, 22788, 1749, 2337, 3359, 36023,
9834, 299, 1496, 24590, 31859, 25522, 38144, 7891, 26354, 12462, 36798,
20080, 47924, 26045, 275, 7903, 337, 1391, 22253, 12498, 1490, 32844,
44060, 38656, 21464, 22905, 35843, 7921, 7913, 8251, 2309, 8218, 35758,
20540, 51004, 35753, 50724, 32534, 21209, 38451, 21363, 4096, 44284,
324, 46308, 20139, 239, 20302, 2495, 22495, 22793, 2765, 2759, 8224,
45236, 35069, 3114, 21150, 31616, 3125, 36275, 345, 1112, 44221, 29987,
3247, 33267, 23130, 3384, 21315, 161, 7855, 31163, 40644, 27494, 30424,
36234, 28201, 21806, 22242, 20363, 39532, 3330, 4311, 35501, 25214,
29260, 25226, 2993, 28207, 35748, 3381, 36208, 27599, 20856, 4121,
50976, 24102, 40857, 26223, 35814, 31216, 25928, 35759, 8482, 51312,
35266, 3242, 35937, 24459, 44544, 21448, 3108, 2752, 27833, 25112,
2472, 27770, 23646, 20248, 51652, 27979, 29609, 20934, 30524, 4143,
24195, 2370, 35782, 24453, 4141, 3374, 1735, 50672, 2608, 2984, 32418,
1592, 36942, 12370, 39033, 1510, 4112, 24540, 1397, 54252, 34880,
38463, 27426, 30003, 26413, 8203, 27827, 50864, 36135, 20915, 26222,
36830, 25252, 9670, 31687, 30906, 35272, 3118, 1407, 167, 44288, 12518,
20843, 3377, 33647, 7919, 20845, 39365, 4100, 8249, 53552, 35810,
27515, 26666, 20811, 31665, 25353, 8722, 23500, 35469, 1503, 31574,
4306, 26144, 51077, 21322, 21916, 47784, 22336, 21490, 47732, 29577,
38918, 38469, 24231, 26031, 26089, 7917, 1111, 24503, 12406, 12368,
22659, 946, 24220, 27773, 28858, 23572, 21629, 26681, 32232, 3762,
12402, 33322, 27573, 40657, 26512, 26174, 279, 20891, 31278, 48169,
24577, 26371, 39764, 23427, 33402, 21452, 24211, 12374, 34915, 3110,
1179, 35789, 26494, 35542, 9472, 29615, 27982, 26029, 1614, 9474,
30332, 21834, 50504, 33041, 22812, 2734, 35874, 7893, 23041, 12293,
39080, 9500, 50868, 21548, 27874, 32068, 21382, 3737, 21334, 24052,
20122, 50948, 20241, 25511, 22855, 36939, 36130, 32500, 50556, 22686,
33879, 30382, 3103, 20061, 26446, 20505, 177, 3119, 973, 24065, 31614,
32066, 28246, 25289, 32856, 32154, 20064, 25215, 21547, 28608, 54617,
9660, 33268, 2339, 22833, 181, 26680, 31227, 39044, 32676, 2349, 48148,
37319, 339, 1114, 164, 27597, 36948, 36578, 32887, 27490, 54840, 8225,
32076, 39030, 38134, 23713, 20960, 20030, 47308, 4117, 35282, 20181,
2343, 53356, 21513, 25293, 170, 35519, 19969, 20117, 2709, 50629,
178, 3095, 36092, 24076, 36814, 44368, 38190, 2453, 1405, 21527, 53440,
26063, 1108, 25442, 36131, 35895, 51201, 2616, 20805, 54408, 2376,
51473, 51020, 24613, 39006, 25126, 26397, 22871, 49373, 3257, 33324,
38065, 20892, 24565, 20221, 3379, 54532, 46356, 2319, 23578, 37038,
27493, 49440, 49845, 1406, 12422, 22259, 47588, 27983, 23448, 22827,
30830, 1105, 27611, 3244, 22290, 24235, 36755, 26816, 35768, 22799,
2310, 34899, 30053, 2741, 3251, 21312, 26500, 20778, 21507, 9829,
35746, 32862, 4313, 20859, 31036, 24494, 3231, 38142, 12401, 39208,
31881, 20037, 23487, 2631, 1494, 8240, 22343, 35910, 22283, 1670,
371, 39046, 25925, 1392, 32057, 38431, 3233, 24178, 34903, 28459,
38272, 51076, 3398, 33590, 182, 47112, 19971, 22530, 2476, 32178,
24046, 2763, 27531, 3143, 27915, 3147, 35273, 12366, 2359, 36739,
2724, 21319, 51116, 44228, 2690, 36753, 49892, 25658, 20113, 45380,
20114, 52380, 2326, 52824, 24207, 47749, 1116, 35500, 24111, 21738,
6098, 21942, 22996, 38590, 32207, 1388, 29486, 33756, 21387, 2488,
33487, 48516, 2623, 24375, 30103, 2479, 7863, 46321, 9675, 36949,
44144, 1118, 38609, 49885, 20041, 52852, 23626, 28010, 39134, 54028,
3658, 23416, 36793, 28082, 7915, 49328, 25209, 3015, 21017, 3105,
47785, 45936, 52404, 28168, 29275, 22521, 23475, 30772, 363, 23425,
53664, 1567, 50900, 33865, 51089, 21048, 54633, 33539, 172, 2624,
4334, 45432, 22856, 23395, 4123, 52628, 44036, 21095, 24213, 3098,
31471, 27941, 21378, 1744, 30410, 29677, 21177, 29420, 28120, 4116,
39280, 47084, 25240, 23401, 974, 27721, 50752, 38555, 1107, 28385,
23470, 33310, 38442, 402, 47932, 36187, 36027, 38957, 2744, 20917,
20633, 23429, 27801, 27010, 3271, 21542, 26379, 24651, 39340, 38477,
33609, 3403, 12476, 21355, 36914, 26234, 21336, 35703, 4328, 35838,
25915, 27849, 27704, 38543, 26044, 25321, 25563, 2341, 26497, 35430,
28155, 20284, 21010, 32905, 9473, 23822, 27927, 54032, 31508, 45800,
38169, 35531, 36938, 12532, 21320, 3784, 39443, 184, 22885, 31192,
4126, 47197, 38597, 38745, 3354, 20339, 24198, 20358, 44163, 4129,
33509, 36259, 24107, 2751, 2482, 36913, 162, 31168, 3142, 31105, 1115,
54665, 20029, 20381, 12520, 4124, 35686, 31179, 21028, 24038, 2313,
20852, 44552, 2598, 3785, 3136, 35757, 2979, 2581, 2478, 33719, 31461,
2311, 25805, 19988, 21491, 35222, 21704, 35785, 20146, 20853, 50696,
34276, 51200, 1119, 12353, 20105, 36866, 21439, 27966, 19997, 32422,
2730, 38634, 38505, 32493, 39636, 48156, 2600, 20083, 36828, 24237,
23554, 39000, 20919, 3014, 9492, 1385, 22870, 6070, 21892, 47700,
7887, 21709, 38632, 24202, 26862, 2949, 24373, 36848, 8213, 2738,
188, 47000, 24441, 36889, 38889, 34701, 21454, 46104, 53685, 44053,
12405, 23089, 33464, 35775, 1379, 45224, 27431, 36864, 38081, 45348,
24800, 24184, 36125, 34955, 37504, 35848, 3713, 27178, 49353, 2347,
35468, 31361, 32461, 31199, 54000, 20848, 25285, 9633, 32972, 25588,
2404, 26522, 23618, 27602, 22920, 4154, 44148, 54624, 44160, 38556,
4101, 26434, 22830, 52572, 1409, 38468, 24448, 20551, 33775, 35752,
1729, 20418, 39302, 25147, 2474, 35802, 22323, 32599, 48264, 35527,
49444, 7877, 168, 36731, 20142, 38795, 2951, 48376, 36319, 30828,
38472, 30171, 21602, 45908, 3363, 52264, 27083, 21215, 21183, 20826,
3228, 2468, 4318, 23612, 1380, 1113, 27744, 48176, 8206, 21327, 32508,
30151, 25144, 20247, 21364, 1384, 8658, 20234, 38917, 36794, 28288,
23432, 26641, 3593, 36766, 30002, 23556, 45684, 21560, 21016, 38913,
3116, 7881, 36855, 65279, 25668, 20943, 29190, 1106, 30431, 23519,
3399, 54168, 8195, 48152, 32102, 175, 26800, 32440, 1746, 25391, 9650,
23186, 355, 21628, 21047, 25705, 40635, 20313, 52636, 189, 1616, 32426,
30097, 32026, 32435, 37240, 166, 45817, 26230, 27508, 54788, 21051,
24907, 2996, 35251, 27954, 1611, 22359, 26723, 48660, 33145, 20020,
27719, 26202, 32455, 31309, 37070, 38596, 30274, 2613, 9482, 54588,
32722, 2735, 3732, 50669, 28789, 21672, 2596, 3275, 26411, 30417,
20253, 20196, 7849, 27850, 36884, 20165, 38050, 22260, 1412, 26550,
25480, 27841, 25173, 20260, 21213, 31777, 27497, 38663, 26367, 28783,
48277, 35834, 35841, 54980, 958, 23492, 39184, 3353, 2610, 24449,
52397, 20572, 38706, 44608, 35696, 50630, 3757, 23681, 22266, 27161,
6042, 38647, 3776, 38522, 26790, 20185, 32456, 33287, 3019, 37444,
2617, 23707, 23459, 2753, 8595, 20516, 25239, 48260, 27211, 32477,
38761, 20498, 32933, 25955, 32763, 24187, 3613, 29399, 21531, 53076,
24149, 35388, 34917, 36196, 367, 35762, 27663, 3266, 50577, 21344,
29105, 361, 4330, 30427, 31569, 47476, 27036, 38215, 25551, 40658,
44048, 22992, 37239, 12619, 12382, 36969, 51649, 29238, 772, 22294,
3351, 4325, 2969, 2602, 3226, 21483, 36149, 38989, 35342, 24481, 24536,
4156, 47140, 26432, 3100, 23553, 27810, 24746, 36008, 34013, 36935,
31186, 4097, 4324, 38626, 3366, 3719, 33510, 38364, 20304, 48124,
4151, 3264, 36152, 24322, 7867, 29483, 47568, 9608, 23614, 39154,
23452, 33655, 38470, 27177, 29664, 27507, 3630, 21367, 190, 34382,
2463, 29872, 26579, 51665, 32511, 22971, 26619, 39592, 21103, 2635,
23613, 21478, 27442, 54540, 20202, 36611, 27996, 38381, 28310, 28286,
32113, 32321, 25976, 20493, 3394, 179, 32097, 12412, 3761, 44620,
950, 38138, 25343, 45784, 40670, 36879, 20912, 1394, 26893, 23653,
2606, 28988, 21733, 25937, 47141, 21106, 1617, 21018, 44208, 51333,
21477, 357, 2497, 36127, 23431, 247, 33050, 25774, 33303, 2492, 24444,
2716, 1378, 51216, 3138, 1726, 3751, 22721, 31821, 48149, 24188, 22969,
8593, 25246, 3018, 6035, 29790, 38914, 20006, 49569, 38386, 29087,
24040, 1402, 40060, 1241, 1615, 49549, 35498, 36175, 54364, 2312,
7851, 44428, 2604, 35242, 30343, 1187, 25176, 54664, 27888, 2672,
28814, 53468, 26152, 24930, 378, 32932, 21381, 38544, 2364, 23566,
25033, 22243, 38047, 31069, 20908, 27138, 26292, 22280, 32681, 34507,
32819, 1171, 23721, 28151, 20016, 27993, 23381, 12389, 3745, 31383,
33337, 48652, 24133, 3235, 2562, 21494, 34220, 39035, 2726, 32013,
20419, 21809, 48320, 20816, 31359, 21220, 3942, 23457, 28526, 25324,
20914, 32025, 21862, 30064, 20055, 3254, 44305, 21361, 26757, 35672,
732, 26366, 36339, 185, 29066, 20005, 23546, 3372, 24109, 38627, 35611,
51656, 54632, 3760, 4155, 710, 20276, 31680, 38236, 20497, 2336, 2588,
24466, 3738, 20839, 46108, 1572, 2745, 3205, 53412, 32147, 50557,
35946, 2958, 3077, 3765, 36001, 24693, 53580, 1618, 26576, 33073,
50872, 38996, 21050, 4310, 4157, 27598, 31958, 21551, 23631, 23064,
24310, 24039, 38646, 32858, 24656, 50808, 26087, 6036, 22025, 24618,
20896, 35377, 20315, 26472, 23565, 49900, 303, 22815, 32451, 4332,
50632, 1498, 20081, 12380, 36062, 4146, 26007, 50508, 20065, 20874,
36996, 35442, 33016, 24739, 22919, 35338, 28006, 20992, 20474, 2620,
30342, 32487, 6016, 2719, 54805, 37089, 24196, 29378, 24489, 21402,
7865, 32039, 46160, 48373, 3530, 36317, 6040, 21066, 20652, 54872,
25484, 20729, 25505, 39740, 36024, 20966, 31689, 20024, 297, 47336,
39034, 31526, 32908, 29359, 40092, 2711, 32043, 2732, 23560, 24112,
2507, 39278, 36032, 39069, 6047, 45733, 20861, 36000, 39038, 50528,
25191, 2470, 32117, 51592, 25554, 27402, 52488, 25346, 35823, 12541,
27798, 24576, 25645, 21024, 24351, 26263, 35613, 4122, 31481, 2331,
26477, 21332, 26332, 3600, 48324, 44201, 4106, 38867, 22902, 3356,
4142, 1734, 26725, 39304, 3749, 28020, 36129, 36842, 33180, 7895,
33635, 25630, 36991, 44033, 32000, 33026, 44540, 36012, 55176, 35302,
3906, 22679, 23544, 25463, 25311, 24093, 20159, 23447, 26463, 48520,
47728, 3392, 38281, 52293, 21776, 7869, 34394, 28895, 3255, 9671,
35036, 52376, 46412, 26997, 45804, 22995, 49496, 29273, 295, 36718,
12534, 28966, 26479, 20511, 40575, 27873, 21109, 22256, 29976, 22352,
3129, 32701, 32431, 30784, 8801, 33014, 12316, 2673, 333, 27605, 47536,
8470, 326, 1404, 3659, 32993, 29356, 22918, 24059, 21073, 30070, 1389,
44553, 3954, 26124, 20025, 36028, 25935, 24778, 45572, 3008, 2455,
22609, 12492, 32260, 24464, 51613, 369, 4326, 2742, 2439, 3010, 30563,
23506, 2460, 23792, 50892, 30142, 12478, 8730, 26262, 7857, 30436,
39131, 3333, 32842, 36605, 39749, 36035, 3144, 32570, 3274, 37073,
24895, 49465, 26588, 25276, 39178, 12413, 46988, 21058, 48143, 31085,
36305, 40664, 33080, 22307, 36805, 50506, 46993, 21171, 26071, 32784,
22818, 50728, 26082, 32884, 1709, 53804, 49696, 2625, 35914, 30561,
23485, 21127, 29986, 27784, 23615, 54856, 40165, 38452, 28204, 23551,
54217, 3538, 28771, 318, 3754, 32988, 23467, 3921, 3771, 31454, 25361,
9678, 32618, 35506, 7929, 24377, 45812, 21311, 28187, 35799, 20465,
20596, 45320, 34399, 3964, 9516, 30423, 26242, 21621, 54637, 39068,
33288, 38520, 35387, 12421, 38024, 33150, 46021, 34429, 35504, 21191,
26716, 34180, 26691, 54876, 52964, 24115, 35370, 35379, 29123, 28193,
24402, 3505, 25688, 26480, 36213, 1383, 25481, 26639, 23547, 45216,
9618, 52768, 28369, 32990, 22635, 28287, 26106, 38534, 47492, 38752,
48155, 54200, 36882, 45813, 3385, 8592, 20210, 38542, 52286, 23526,
37636, 49352, 23439, 33945, 50977, 27905, 47549, 1399, 52712, 45212,
6031, 20489, 36960, 21414, 20180, 4139, 24537, 3735, 32118, 36664,
21218, 35023, 25265, 3245, 51339, 24369, 36557, 27973, 44400, 20001,
27794, 27193, 38538, 49437, 25244, 35793, 28595, 30719, 48177, 4150,
20046, 21917, 24694, 20161, 1390, 21556, 38525, 4102, 23736, 34101,
50732, 39277, 28070, 21561, 22362, 29482, 49692, 51456, 3361, 3127,
29645, 52285, 32020, 53364, 52292, 39746, 47448, 36870, 27503, 2953,
3239, 2721, 2371, 25439, 12359, 20961, 20129, 38911, 40481, 48288,
47144, 22612, 31283, 45843, 20860, 21934, 32650, 39770, 53469, 24681,
3383, 32244, 8734, 37030, 34411, 3590, 20804, 54596, 35079, 25317,
3382, 22258, 28798, 40845, 53945, 2566, 4327, 23562, 50416, 50501,
20598, 27427, 48513, 24748, 8804, 28872, 22338, 1722, 9507, 31455,
3926, 38075, 39537, 1739, 54869, 20057, 30913, 26195, 3725, 2489,
25187, 19976, 21063, 37266, 40784, 23456, 25201, 25731, 32210, 24597,
44057, 46976, 24291, 1742, 26580, 30418, 22863, 6020, 1736, 40614,
31478, 54256, 28784, 35226, 4144, 12407, 32553, 40736, 20648, 40065,
20882, 12396, 45376, 47672, 23039, 23380, 20262, 21169, 21807, 22937,
316, 28129, 36786, 30435, 36151, 31563, 50676, 33740, 35009, 20928,
22841, 20255, 24785, 2447, 47548, 27578, 50616, 35044, 45912, 3777,
39151, 32005, 35422, 47480, 24935, 36650, 24452, 20249, 28072, 54056,
4118, 22278, 33437, 2328, 20405, 32536, 25138, 20439, 36067, 22351,
20384, 26157, 2338, 2583, 23517, 3000, 2438, 3342, 25277, 9488, 28903,
1382, 29392, 23559, 35465, 20173, 49332, 29978, 23142, 36020, 28014,
52828, 22622, 23156, 6043, 63243, 26792, 3755, 20964, 3126, 968, 1958,
28271, 24525, 32925, 23385, 23486, 40763, 9642, 1201, 12453, 8805,
8776, 9478, 47566, 3620, 28363, 26564, 24499, 9553, 12307, 32047,
38321, 22681, 31062, 3661, 37322, 39550, 8745, 44152, 38145, 26700,
35786, 20559, 36763, 25196, 26417, 38548, 47200, 21734, 25569, 23610,
26286, 26970, 29748, 27683, 22311, 2486, 34966, 2305, 20280, 24658,
1403, 21162, 27818, 33109, 26834, 1688, 36973, 30952, 9617, 8231,
49468, 2465, 37109, 1507, 8208, 28079, 35386, 25964, 38920, 52280,
21092, 32879, 32489, 21416, 33136, 3938, 22805, 54744, 52840, 22524,
33298, 35206, 49660, 49849, 20685, 3207, 55148, 25250, 26228, 28418,
30422, 33459, 51208, 3520, 36681, 36134, 38972, 20272, 9576, 26364,
38772, 48128, 52629, 20659, 46304, 35712, 26118, 2626, 2694, 29287,
2714, 2565, 30496, 54693, 31077, 32094, 23244, 27785, 48036, 2693,
40599, 23435, 9600, 36867, 27530, 33891, 46608, 2725, 54021, 26333,
2586, 47088, 9578, 29572, 27931, 24754, 33033, 34907, 33104, 26753,
9524, 23563, 3272, 21746, 9619, 33778, 28716, 3400, 26391, 2950, 25581,
22696, 45720, 3631, 24598, 32724, 24080, 22346, 3764, 23043, 3733,
38378, 36741, 49340, 20426, 3739, 23110, 25235, 1401, 25499, 6086,
28508, 38936, 9552, 31890, 36190, 52992, 29980, 29942, 29240, 21009,
32173, 30284, 27839, 3923, 3482, 52980, 21331, 21568, 38915, 21484,
28392, 20599, 44600, 2377, 26611, 2380, 33495, 33151, 58853, 36829,
36133, 38182, 3206, 25313, 32791, 36951, 38454, 31558, 38712, 30246,
2591, 22727, 12685, 63688, 3908, 40636, 1109, 8704, 2355, 47581, 36186,
24321, 24509, 32340, 33618, 24544, 46384, 1169, 48624, 4222, 40723,
33707, 4171, 3512, 3111, 36963, 24745, 2496, 44061, 35037, 23652,
3602, 9496, 27901, 30690, 2723, 2727, 31245, 48337, 38518, 32937,
3535, 54140, 3514, 8811, 63242, 26059, 25954, 32943, 33832, 36341,
3714, 1968, 33406, 25340, 3716, 2458, 12404, 25269, 20206, 50472,
25140, 20693, 3214, 4331, 21172, 9604, 24594, 32854, 2632, 2595, 28009,
28041, 9532, 6071, 22068, 6033, 33395, 27934, 32302, 35889, 12355,
47792, 32974, 3767, 4244, 20975, 24125, 54889, 3515, 38083, 6038,
27171, 25193, 3117, 28431, 20663, 33713, 26690, 25613, 6041, 20391,
47004, 28139, 44200, 6091, 30722, 33261, 38459, 50644, 29141, 3628,
35330, 22900, 30059, 22865, 37347, 328, 2333, 20035, 37101, 36797,
29436, 51217, 30805, 4113, 47100, 34913, 3501, 35029, 20271, 45367,
40479, 36575, 33673, 44192, 3742, 36880, 24382, 20134, 3146, 31348,
50620, 28096, 37341, 3079, 27687, 2324, 26086, 38322, 35064, 3956,
49552, 20094, 38453, 2972, 27748, 711, 28342, 3599, 33694, 27735,
51676, 3371, 39854, 23703, 3373, 46973, 30908, 27807, 3380, 23696,
25973, 30123, 32441, 44760, 8207, 20989, 8236, 35477, 22618, 8451,
39039, 33489, 38155, 26460, 3367, 36104, 3936, 4329, 34588, 50756,
20841, 3115, 3402, 9572, 22934, 28809, 33455, 34425, 29827, 25514,
9312, 44508, 40836, 24518, 37492, 29554, 52509, 34214, 28818, 27946,
6021, 31206, 30130, 28511, 8319, 39166, 13217, 46028, 20223, 2582,
2733, 23019, 20940, 33126, 26694, 2459, 29028, 3335, 26781, 23233,
36857, 26575, 36745, 33836, 28404, 20044, 38642, 32966, 9565, 25106,
36300, 33804, 38428, 27583, 54609, 28034, 27877, 2477, 32963, 9571,
3358, 32209, 30636, 26538, 31908, 34385, 3722, 28748, 44204, 33576,
35731, 29618, 51096, 26216, 3209, 25299, 2703, 38108, 6072, 3789,
9313, 23068, 27396, 35264, 3078, 25429, 4239, 55092, 32442, 9557,
27542, 24324, 29245, 47561, 25381, 9563, 38360, 32531, 26441, 2434,
26628, 20056, 37857, 9564, 3665, 25331, 4017, 34389, 12297, 20957,
25298, 52384, 47553, 25943, 3523, 36367, 48276, 21097, 29916, 32626,
3598, 22633, 25308, 3540, 28176, 31807, 28845, 25026, 52649, 33747,
51313, 47049, 28248, 3334, 21330, 3769, 36843, 1962, 38485, 47803,
1657, 26194, 3962, 36742, 26172, 23588, 30127, 38177, 36214, 32959,
32882, 20982, 36992, 40802, 20179, 27424, 20018, 28450, 25932, 24674,
27745, 9475, 20740, 29627, 48292, 33146, 3928, 32764, 36941, 1927,
32318, 26421, 35722, 35010, 3939, 21193, 44264, 26525, 22296, 3107,
39569, 39658, 2637, 22615, 19992, 28171, 37034, 31684, 39575, 2454,
26609, 26825, 24736, 9559, 6081, 32317, 33529, 20126, 24223, 21365,
31726, 50880, 25130, 21247, 35041, 33293, 22868, 25975, 24422, 38929,
8242, 24500, 32439, 4120, 2715, 34218, 32291, 28330, 27298, 3720,
25671, 1509, 36933, 38928, 12296, 4757, 37291, 26132, 51105, 289,
37228, 24062, 32420, 3302, 25233, 50520, 35261, 9569, 6076, 27713,
21943, 27155, 35033, 37428, 8976, 24163, 12530, 25142, 26049, 12306,
9580, 24069, 36194, 24467, 32958, 54861, 54952, 23531, 45712, 22369,
21368, 49325, 291, 26092, 9654, 25286, 27284, 32645, 8706, 32224,
21170, 36981, 36965, 39376, 24189, 9508, 7923, 24140, 2710, 30416,
26705, 20420, 37969, 4160, 53216, 33777, 47161, 35657, 32153, 25014,
26119, 28860, 25424, 36986, 30244, 2334, 9568, 3780, 28378, 1613,
26001, 24478, 9562, 8729, 4114, 28902, 2696, 23542, 38149, 21654,
9495, 31049, 49836, 51600, 34678, 31895, 27489, 30086, 21696, 54844,
49800, 9567, 21682, 30473, 9661, 50688, 27627, 23396, 9561, 21427,
21443, 3601, 21570, 48380, 29943, 29467, 54728, 27475, 36321, 34349,
3779, 27891, 31896, 48736, 31281, 8194, 3237, 1960, 22218, 27882,
24323, 34183, 33538, 40654, 2451, 6075, 27875, 36724, 32928, 30862,
30555, 3853, 36393, 44275, 36235, 33900, 21576, 36771, 2329, 24742,
33108, 22374, 21514, 29595, 25402, 9574, 38684, 28797, 20937, 23476,
38515, 36801, 32433, 26165, 3123, 32472, 28580, 33256, 50613, 39511,
51316, 29038, 24490, 34269, 12308, 1964, 30899, 24796, 24033, 9577,
29239, 36180, 12361, 20818, 25644, 24708, 23507, 23529, 45576, 3517,
775, 12309, 12640, 21741, 26361, 44480, 23731, 22985, 24551, 36291,
29926, 2323, 23576, 8359, 23449, 25720, 8718, 50529, 28611, 20237,
30196, 2475, 6082, 44257, 22922, 2731, 35258, 22982, 23389, 23195,
21857, 9555, 36776, 36328, 25136, 20141, 2754, 37057, 9484, 25670,
34081, 34923, 28781, 32736, 38517, 24815, 8992, 22475, 2437, 24713,
26885, 53080, 1922, 24344, 50980, 30879, 35859, 49844, 30021, 47592,
39048, 35825, 47101, 31570, 6044, 30865, 23574, 36192, 2603, 33714,
33976, 9558, 2962, 36920, 24904, 8993, 51460, 3086, 20387, 2471, 1683,
33075, 9575, 20239, 9566, 22766, 21223, 48393, 36777, 8721, 3503,
34746, 33738, 9651, 23490, 35492, 3243, 26093, 30887, 7905, 4147,
20538, 9825, 25200, 2441, 23305, 7927, 24573, 29157, 26187, 38519,
23888, 22443, 20607, 47016, 26612, 6050, 9570, 29017, 9612, 36132,
36182, 25195, 9616, 9556, 47533, 21202, 267, 37707, 47582, 32954,
24118, 27836, 9579, 21520, 33251, 51901, 27987, 24190, 2567, 30140,
21098, 35480, 2307, 3508, 6026, 26088, 24735, 2593, 9573, 27867, 36655,
38971, 38613, 32918, 54801, 8978, 26020, 1393, 26827, 24185, 29923,
12357, 39336, 31379, 53588, 28422, 37749, 22661, 26012, 1203, 25369,
35351, 39514, 31911, 21305, 731, 3081, 20124, 1672, 22402, 20820,
4335, 26627, 2406, 28856, 24259, 51256, 44537, 20296, 3758, 35488,
8747, 32416, 40643, 30408, 53596, 51061, 38160, 12622, 8233, 8810,
29454, 8710, 32899, 22859, 44068, 23035, 28059, 32257, 51328, 30406,
25830, 22519, 37002, 46112, 22675, 29747, 32202, 39063, 8201, 22857,
32938, 45436, 47673, 34503, 50773, 47800, 25198, 39536, 2487, 25159,
35980, 48268, 29468, 36784, 37111, 20542, 54060, 21966, 53448, 23611,
1386, 24609, 39128, 25366, 2739, 49905, 2568, 39542, 52880, 3778,
9560, 47017, 25475, 12444, 23815, 21908, 3222, 25806, 20096, 729,
33328, 28388, 36774, 34562, 24171, 37628, 31389, 50420, 39023, 25302,
36394, 1415, 22730, 21931, 1411, 28092, 38599, 7859, 33883, 31282,
50920, 32716, 35832, 38686, 24910, 48296, 54253, 38640, 33311, 8214,
6039, 33039, 22378, 47116, 54812, 21083, 49912, 35806, 38560, 31946,
3267, 31957, 9314, 32768, 52268, 54925, 8202, 26842, 24265, 49492,
8561, 46377, 35433, 1413, 20801, 20625, 49910, 8235, 32982, 24357,
36154, 35576, 26799, 30462, 53441, 271, 26438, 24443, 9554, 32822,
25080, 52272, 45453, 6084, 39438, 54045, 35380, 22528, 311, 21767,
36637, 38109, 2743, 22654, 25300, 32437, 34928, 25169, 20047, 35856,
30990, 4725, 38506, 2469, 20973, 50628, 37257, 21544, 40527, 24724,
30742, 24070, 25496, 24330, 32893, 46121, 21566, 25758, 38592, 29151,
25259, 22771, 26247, 36713, 728, 36093, 8712, 6023, 34909, 38901,
36712, 28415, 20208, 22958, 6017, 29611, 3304, 40511, 31232, 37679,
38400, 33289, 1748, 54413, 35426, 31292, 26647, 51025, 4245, 21351,
6030, 20932, 28504, 45944, 52395, 24950, 39015, 47001, 31918, 2534,
53584, 22561, 2407, 23004, 20976, 32602, 26894, 29246, 38152, 25958,
49689, 26447, 37666, 3768, 2408, 33889, 27133, 47676, 45328, 32874,
33167, 31661, 53444, 1777, 31048, 50883, 36493, 38512, 28900, 33633,
1632, 24505, 21861, 23725, 23229, 27738, 22403, 30165, 47111, 12643,
40718, 28846, 38401, 51340, 22334, 3337, 27893, 2605, 25166, 47579,
44040, 37995, 38393, 40372, 39364, 27972, 63731, 24524, 50937, 51697,
37011, 21350, 50837, 21091, 26607, 51137, 32483, 21563, 31452, 28085,
30896, 53433, 3545, 26257, 3773, 22993, 1563, 54984, 27450, 50526,
31609, 33452, 27852, 34174, 25206, 29808, 28687, 23047, 33294, 40483,
20661, 34972, 23528, 32396, 20658, 22842, 33678, 1769, 24942, 28938,
20667, 20523, 49901, 38617, 23777, 28107, 36891, 52265, 23624, 21449,
54504, 50743, 23849, 3524, 23527, 44867, 35851, 29788, 33292, 23072,
21780, 1717, 51596, 35930, 2707, 3924, 24266, 26704, 24840, 20817,
21674, 32541, 25320, 31298, 4127, 28866, 35440, 27233, 3495, 27974,
22043, 49772, 25539, 23159, 33796, 33988, 24288, 24680, 20918, 25312,
23002, 8743, 3647, 24193, 27779, 30290, 32186, 44596, 4170, 4018,
32466, 40831, 20329, 35676, 1959, 27844, 12310, 23660, 23581, 51424,
22534, 35347, 38577, 24358, 40634, 31258, 20806, 24944, 45149, 47540,
3395, 52968, 1633, 22616, 34989, 4223, 32469, 24685, 27185, 28382,
39547, 51104, 12311, 35868, 25562, 26517, 20052, 27589, 12410, 8764,
39366, 52432, 26224, 33831, 63246, 33469, 20736, 3546, 29422, 19985,
3663, 3094, 3763, 37051, 21195, 25040, 24931, 32922, 36924, 29376,
36898, 37559, 38563, 31150, 34253, 32445, 28113, 36628, 26685, 33485,
28843, 36785, 36143, 20399, 21574, 20002, 1929, 24808, 2467, 25799,
6078, 32190, 1395, 38739, 3218, 29401, 21460, 38666, 50516, 8229,
36212, 27965, 30526, 23273, 38568, 25885, 23391, 32490, 28192, 36808,
1612, 33922, 28357, 6018, 20341, 32501, 733, 6032, 32023, 23608, 36831,
4637, 2569, 50984, 23330, 21208, 33805, 9835, 20175, 26742, 45336,
52860, 3484, 51453, 23884, 9792, 9794, 31351, 39759, 22435, 24676,
40169, 31992, 1923, 3666, 45769, 28024, 24432, 27465, 25220, 1707,
25802, 33178, 30044, 970, 22915, 24917, 44404, 45815, 44984, 47029,
20011, 27511, 36139, 4653, 36156, 24429, 28142, 3664, 45440, 30168,
26689, 34109, 52769, 25764, 38499, 54756, 36629, 34945, 40180, 22570,
35997, 29425, 2695, 33274, 29301, 29421, 33446, 53011, 48716, 34092,
33683, 38307, 34030, 38654, 9674, 28057, 22079, 26801, 44049, 21897,
30861, 24339, 45909, 39292, 29081, 38570, 26097, 29417, 22467, 9426,
25448, 21890, 53360, 46319, 21346, 34900, 28393, 50725, 40560, 28331,
29518, 25342, 3740, 53560, 50772, 50521, 24367, 20767, 1685, 34430,
21340, 36424, 52789, 35698, 36744, 20941, 26197, 38035, 6025, 39164,
2999, 8727, 29237, 25996, 36893, 54400, 21385, 32156, 23067, 63728,
32294, 54260, 32368, 24801, 32434, 33993, 20911, 44417, 20285, 36362,
34277, 8719, 32705, 36649, 2536, 4661, 22882, 29756, 21525, 24616,
27472, 21155, 37255, 24677, 28516, 34924, 48388, 54016, 2535, 29228,
45458, 28548, 25273, 36974, 29539, 39554, 37941, 30827, 51704, 55141,
35947, 20597, 20534, 25135, 3536, 27585, 22739, 4098, 33931, 45180,
25377, 39062, 24085, 20923, 37782, 21280, 34384, 20613, 25243, 52392};
System.arraycopy(temp, 0, chars, 0, temp.length);
}
private static void populateChars2() {
int[] temp = new int[] {
49472, 54732, 38391, 51669, 49556, 20266, 46024, 32617, 21898, 36930,
36600, 25746, 24858, 38620, 36015, 9668, 33550, 23518, 26528, 36562,
50685, 30871, 24311, 32789, 55192, 4148, 4840, 45772, 2652, 47168,
25407, 1926, 50780, 49380, 4621, 35880, 35582, 36066, 21246, 54392,
31844, 1690, 3109, 4224, 29408, 9315, 22916, 47215, 54536, 20670,
3365, 22287, 23014, 32592, 30789, 64257, 27922, 22888, 37528, 37066,
30079, 32191, 4632, 25818, 30033, 29738, 38728, 46989, 24034, 53952,
1784, 63743, 36203, 2974, 27703, 47456, 29544, 23617, 30095, 46301,
25197, 26820, 54036, 33144, 24764, 25242, 1928, 26280, 27675, 1660,
50536, 26539, 730, 28639, 33541, 4768, 34311, 19993, 28316, 37912,
36172, 50648, 37237, 3001, 1211, 27688, 25776, 30683, 50024, 28448,
45392, 32518, 4813, 2959, 21497, 45803, 22904, 46244, 34886, 32564,
34809, 27506, 27754, 3276, 52236, 4704, 50684, 3350, 33970, 28525,
8260, 26352, 28381, 1414, 20995, 53084, 24841, 23947, 48712, 53948,
26114, 53461, 26898, 2599, 33382, 48317, 3346, 50040, 35803, 29281,
54841, 8800, 39540, 1634, 25042, 21472, 27631, 25856, 29282, 29226,
1665, 21187, 3303, 21163, 21796, 20786, 25304, 3232, 25745, 8243,
20513, 12542, 28180, 25582, 4616, 21703, 28322, 32465, 50952, 9758,
21400, 38125, 32930, 50997, 349, 2697, 4333, 54785, 34560, 38797,
46307, 24343, 20390, 36171, 54589, 50517, 39578, 12291, 38397, 4773,
32085, 38742, 20984, 1934, 36002, 29004, 37238, 26420, 52896, 30591,
1673, 3746, 40493, 24055, 36910, 33218, 24825, 36161, 39588, 6034,
52972, 21371, 24088, 26543, 38290, 24043, 19995, 20054, 38062, 37670,
21034, 47589, 50532, 29369, 48279, 49832, 21681, 44512, 33030, 30067,
33433, 38669, 21273, 25384, 20111, 36158, 33821, 20467, 51608, 22894,
6048, 23194, 32330, 21535, 9827, 21693, 38136, 29492, 26179, 34676,
21676, 39442, 29642, 26039, 24688, 6087, 28655, 8234, 25260, 4845,
48744, 37198, 45264, 27832, 26127, 49244, 31056, 28500, 4119, 38464,
37129, 2373, 31067, 45459, 21078, 28189, 39729, 30137, 20305, 54047,
21683, 12295, 30450, 3734, 33235, 51069, 36007, 47605, 8756, 26635,
28044, 22372, 31579, 38041, 51276, 28169, 63729, 3539, 47788, 63730,
33351, 25836, 23403, 32670, 25417, 2717, 49397, 52237, 8739, 21123,
23828, 24217, 21388, 32960, 32737, 29128, 46496, 47160, 24789, 32011,
40863, 35961, 25010, 49512, 3510, 25380, 26151, 20240, 27733, 32160,
24604, 20167, 20605, 24700, 20677, 32114, 265, 29508, 27819, 3937,
47353, 33624, 39282, 24161, 33152, 48400, 32568, 3986, 34542, 46523,
24417, 49604, 26643, 21688, 3461, 20365, 28514, 36874, 4709, 21523,
31966, 48731, 38420, 3669, 1776, 45285, 3139, 37122, 21129, 29229,
7861, 27498, 2791, 24868, 28147, 25447, 37549, 23071, 39041, 36752,
20136, 45789, 36795, 53416, 38886, 30643, 44260, 54057, 30399, 22963,
35850, 3208, 2575, 33909, 33980, 38203, 3215, 33192, 38665, 22949,
37806, 20553, 4149, 22353, 45797, 36138, 285, 33540, 26729, 39281,
20282, 30697, 35186, 25153, 50865, 20711, 24501, 28417, 36059, 22533,
3087, 54792, 32923, 31515, 21049, 38614, 3930, 50656, 33181, 33519,
21093, 8560, 46500, 25088, 21912, 36887, 4133, 28911, 1779, 3905,
25292, 3080, 33086, 37233, 25788, 22942, 32499, 21481, 30385, 1758,
25335, 33290, 36735, 1932, 47952, 6096, 12615, 2314, 35987, 8362,
25793, 36011, 52825, 24833, 47113, 29312, 24962, 31096, 20698, 22602,
54224, 31109, 28792, 35207, 27695, 33426, 45000, 31520, 21855, 22132,
40548, 33606, 37204, 44844, 36758, 22816, 33034, 22285, 27224, 31528,
4720, 48157, 27054, 53581, 46096, 22890, 51320, 31291, 22941, 39378,
22952, 52492, 35475, 32566, 53328, 35598, 3904, 26954, 26217, 21248,
28921, 32752, 29006, 30897, 51092, 25998, 39567, 22774, 25970, 22040,
4232, 30460, 64258, 23541, 23477, 28810, 2960, 27225, 33995, 35776,
21555, 44845, 31909, 36923, 22586, 33032, 48164, 8467, 45397, 32709,
4752, 30776, 32380, 9664, 31712, 21705, 20028, 1635, 24908, 10146,
30770, 4125, 23451, 1931, 3934, 23020, 30967, 22368, 3782, 33018,
27249, 24307, 3224, 50641, 33139, 44648, 21410, 3804, 28907, 35772,
3662, 8711, 53556, 47680, 4843, 32233, 36330, 1920, 3910, 28879, 35920,
3148, 25096, 24807, 40607, 21038, 22122, 35998, 12641, 37772, 36530,
1778, 53748, 38695, 27815, 3667, 54848, 52632, 40441, 49789, 28183,
39173, 28291, 30162, 33721, 35408, 21895, 20022, 40517, 40335, 2412,
45433, 32331, 22581, 28212, 20857, 26976, 21534, 22075, 28317, 38553,
40667, 25674, 30959, 34442, 22564, 37045, 46076, 27778, 33098, 25309,
38053, 31363, 4755, 21999, 4103, 35784, 33905, 45347, 2712, 12445,
36031, 32363, 53456, 31209, 2790, 47551, 47805, 25797, 54784, 53224,
34028, 36016, 24428, 3548, 35885, 33131, 33392, 20137, 28976, 20457,
1961, 54268, 20007, 38748, 46392, 4336, 20985, 32961, 39165, 44054,
23466, 47148, 36720, 2498, 54172, 1936, 26531, 9316, 6077, 20828,
26775, 47704, 33419, 33453, 48064, 6080, 38476, 33334, 37231, 38208,
25513, 12446, 33733, 45927, 8562, 22839, 40509, 3772, 47751, 30703,
27387, 32027, 22317, 38639, 22365, 22247, 52832, 31302, 24245, 28170,
21321, 33031, 29814, 34593, 34468, 1686, 25172, 32610, 36386, 21860,
2464, 37259, 20521, 28577, 51396, 21710, 53020, 38025, 20725, 21329,
54001, 9672, 48165, 20754, 365, 49104, 38156, 51677, 54645, 27760,
30733, 25334, 2963, 36877, 21467, 1641, 52845, 38343, 24392, 29298,
32544, 47217, 29138, 38593, 3347, 34299, 2409, 4161, 8857, 33564,
37041, 37509, 38383, 10084, 23219, 39662, 30174, 40232, 24035, 36126,
1637, 44050, 22291, 39449, 50741, 3343, 36538, 33769, 40179, 22082,
31548, 30185, 26847, 9763, 28460, 37320, 20392, 39556, 24222, 22925,
26623, 30522, 31237, 20901, 24248, 30922, 25436, 38085, 47204, 24717,
23609, 2411, 21375, 38057, 23016, 46888, 24218, 30433, 25615, 23515,
25379, 8629, 49704, 35878, 33216, 35463, 12599, 28251, 36852, 45225,
44340, 25022, 20098, 50473, 21843, 53372, 2584, 54648, 46168, 25684,
29791, 28641, 9702, 29705, 25114, 2415, 25238, 32177, 20062, 25079,
1933, 30126, 2720, 36195, 34203, 1669, 33579, 12443, 33735, 21650,
3747, 48197, 30928, 23472, 30294, 31805, 63736, 32110, 1681, 54764,
31967, 23663, 34432, 2878, 21754, 3352, 25594, 36042, 25993, 26000,
47352, 29993, 47021, 22196, 46504, 33795, 39894, 21465, 8806, 1640,
25545, 4319, 23648, 29563, 23534, 48729, 31929, 28493, 29503, 38587,
37489, 37340, 8210, 34583, 49452, 28103, 37474, 20632, 4848, 50885,
1373, 39047, 2636, 35738, 22777, 28799, 30849, 22887, 34217, 21679,
33203, 20254, 21557, 21295, 33147, 22092, 52524, 3653, 51593, 33184,
38902, 25812, 27146, 50631, 53457, 4162, 1636, 32624, 31623, 1706,
47691, 48709, 4635, 28100, 912, 31165, 25387, 36556, 45228, 48537,
33225, 31364, 8807, 59115, 26028, 52981, 31883, 39635, 29242, 1741,
27682, 26646, 32283, 31469, 27792, 27572, 1930, 37664, 53097, 22756,
34893, 22217, 32016, 25423, 51232, 25001, 24278, 32829, 12636, 33593,
26283, 34957, 20872, 38392, 37218, 47280, 21643, 22840, 55120, 47085,
21397, 21254, 45929, 59017, 1639, 45240, 2607, 22549, 49453, 21947,
24799, 6085, 24359, 2597, 22846, 50633, 24999, 25654, 54008, 40486,
39686, 9080, 31293, 6037, 35140, 4853, 25199, 4877, 48150, 37048,
32903, 26771, 21214, 48757, 54635, 30813, 36452, 20431, 31487, 23596,
2543, 3766, 30571, 2321, 25405, 30008, 25605, 35695, 21000, 25161,
32462, 40665, 2755, 28195, 1638, 45209, 32597, 39192, 28528, 51667,
55064, 4619, 4872, 26586, 6083, 26829, 37230, 21149, 32896, 53092,
10003, 20945, 48121, 27331, 52377, 29432, 2410, 48420, 46907, 37507,
314, 1924, 3668, 37467, 40629, 34521, 36804, 53916, 3227, 45828, 32051,
8834, 1043333, 28572, 35845, 4186, 24041, 38662, 981, 22434, 27575,
47576, 52644, 22484, 39171, 32299, 37676, 23633, 49500, 4776, 38275,
33102, 29863, 26021, 34523, 29734, 25778, 4175, 45230, 51081, 21485,
22869, 44161, 23830, 24427, 34223, 30036, 4134, 20979, 38622, 3984,
37323, 36926, 46832, 38931, 8209, 2952, 29640, 27899, 4733, 3415,
33899, 3305, 31204, 6089, 34509, 20322, 48127, 30050, 49368, 26837,
40680, 39472, 3805, 28073, 1305, 32227, 25325, 32827, 27679, 39295,
38991, 44732, 33436, 3216, 34935, 54592, 27985, 22576, 35065, 35948,
3920, 27085, 30338, 1417, 44052, 52489, 38048, 24426, 44628, 54144,
22750, 28790, 20864, 26869, 23604, 2537, 51229, 37165, 23094, 39072,
51468, 3925, 21769, 3499, 28888, 34433, 23493, 25666, 29076, 24809,
27900, 39286, 2539, 54017, 25472, 1468, 26310, 49341, 28136, 39129,
34196, 20621, 34315, 40637, 28487, 38054, 35854, 35449, 23561, 35875,
37039, 36106, 20314, 39551, 12533, 33948, 30447, 32673, 31391, 12386,
4723, 37723, 38829, 26365, 4019, 30535, 27131, 3219, 51079, 1921,
20177, 26198, 20323, 27694, 45257, 9824, 341, 38567, 36051, 54156,
25296, 12482, 359, 40594, 2499, 35617, 21564, 32781, 26803, 63250,
4648, 51236, 33806, 26025, 36084, 8600, 31177, 34395, 36225, 4651,
34074, 53668, 46405, 23113, 21756, 23532, 52252, 50432, 23234, 2864,
4656, 29279, 37247, 26122, 29477, 27463, 35853, 9487, 32180, 36176,
31108, 49399, 21486, 51564, 27766, 33008, 23835, 30631, 20900, 49334,
46272, 31166, 22604, 20522, 40613, 21290, 8901, 49240, 20955, 37284,
37049, 27197, 25995, 26388, 34067, 45196, 49933, 26632, 51664, 32058,
21059, 33465, 2760, 27667, 21927, 26805, 26530, 47931, 30164, 37026,
27308, 20360, 27495, 31373, 28954, 20446, 55121, 38982, 2457, 12963,
4808, 29241, 21647, 34121, 35088, 3090, 30358, 37112, 47213, 20977,
22030, 65104, 52983, 33492, 4707, 24936, 21633, 2538, 39423, 31783,
20050, 33841, 2794, 44272, 21914, 24051, 28389, 21764, 26278, 33545,
28905, 26454, 2413, 53420, 31072, 2795, 29802, 36276, 26943, 33833,
28068, 32902, 32239, 35558, 29033, 37009, 33029, 8741, 36767, 30889,
26329, 49100, 38389, 45448, 4781, 21936, 12430, 1207, 29509, 3458,
27838, 37085, 45924, 30270, 44852, 33296, 27512, 38582, 36137, 61984,
21980, 50619, 52856, 21577, 38533, 45132, 54804, 22013, 22931, 33729,
1042487, 24420, 22047, 29840, 1185, 22781, 34249, 38055, 39076, 2462,
32428, 12849, 34802, 38604, 2433, 35320, 2837, 32333, 39745, 36145,
3935, 9742, 10047, 34584, 52393, 26311, 3490, 32362, 27726, 26797,
2792, 30116, 21133, 47708, 9499, 24208, 29632, 34453, 39348, 26708,
31545, 1785, 29100, 33674, 3307, 21281, 33589, 4613, 38678, 35223,
21930, 29022, 9317, 45128, 31735, 28467, 33639, 25386, 3096, 39037,
23622, 12596, 40655, 48180, 30031, 2414, 24282, 37832, 30917, 25749,
38043, 2893, 29995, 40778, 22986, 36481, 27741, 22645, 33046, 25318,
30355, 3497, 33631, 4238, 29560, 55137, 47329, 22496, 8744, 3336,
28844, 45516, 2320, 37686, 33067, 30494, 49483, 55124, 39717, 26963,
28689, 51247, 51480, 31397, 36168, 29781, 28657, 28891, 3999, 47092,
34164, 6073, 1463, 52270, 2589, 1464, 21880, 3913, 34722, 2579, 39791,
45140, 53665, 8746, 38619, 23784, 25597, 35584, 27728, 23521, 37221,
33659, 1374, 46980, 45256, 27060, 21505, 29956, 2542, 30702, 28760,
21237, 1524, 20238, 2796, 539, 23706, 36064, 2691, 38180, 27896, 24661,
2510, 21673, 20506, 38997, 31353, 25327, 25438, 3473, 25375, 22350,
22862, 40660, 19998, 26592, 31446, 1251, 36711, 23803, 28796, 1177,
35586, 25487, 36953, 44316, 37304, 30192, 31377, 3909, 35122, 53681,
8660, 39748, 21727, 35090, 34638, 21515, 27264, 45349, 4234, 10065,
25874, 27526, 30699, 21610, 2353, 48764, 20008, 47609, 8758, 27012,
20183, 33307, 50670, 22234, 28179, 24871, 38146, 9491, 9699, 54004,
21585, 1781, 45210, 36983, 38930, 36159, 9698, 37145, 48141, 31398,
35028, 31491, 40077, 9644, 1460, 27712, 21380, 29071, 4240, 28949,
31161, 20051, 20871, 8757, 38449, 1966, 33620, 27975, 33398, 9480,
31581, 39056, 46497, 36420, 4111, 40801, 3306, 21250, 3671, 35359,
30860, 31407, 29306, 44636, 45124, 29792, 38583, 22366, 35609, 9582,
32495, 24794, 21742, 25329, 19984, 36101, 28507, 47337, 35829, 2954,
3670, 31319, 20166, 46385, 34224, 3642, 3525, 22880, 1043296, 34281,
30072, 31459, 29787, 3672, 29053, 21589, 9788, 8786, 46120, 28629,
27014, 34398, 59009, 33125, 32728, 31337, 46181, 331, 47896, 27204,
39180, 51021, 22151, 36245, 33329, 20846, 31869, 21137, 40251, 26999,
9483, 38175, 1041703, 29042, 50584, 2540, 25765, 26023, 26848, 30520,
20336, 1782, 1780, 48145, 27803, 31229, 3452, 38416, 54204, 28210,
55184, 32478, 47019, 28372, 31095, 50424, 34126, 31601, 30219, 2887,
36838, 24758, 30529, 9786, 30505, 23241, 3521, 27777, 26791, 6090,
21815, 29380, 25844, 59114, 21888, 32986, 23081, 6088, 24290, 31964,
33368, 37336, 40858, 28472, 38753, 23649, 48316, 20518, 45916, 31378,
27813, 35070, 48960, 31402, 36090, 28263, 38887, 38501, 23994, 48533,
1456, 28919, 24101, 51536, 4677, 37275, 36468, 22066, 21653, 9547,
25950, 22769, 2879, 23682, 30221, 20398, 39042, 44618, 32438, 31903,
55036, 33099, 30113, 32512, 37210, 47131, 34219, 27953, 38262, 31162,
12828, 26928, 29831, 22107, 33286, 24608, 3308, 37413, 28466, 34850,
9700, 45940, 28065, 2405, 9477, 15142, 9836, 309, 37232, 50476, 45324,
2587, 2541, 21700, 31914, 38446, 30606, 57348, 22404, 28552, 1523,
25504, 21185, 36466, 50812, 3344, 20463, 2456, 45776, 35766, 3088,
4779, 40595, 38082, 22687, 12485, 36077, 31925, 37756, 29712, 61472,
28346, 3673, 22593, 6092, 34157, 26274, 30596, 59131, 40568, 31840,
537, 55180, 3309, 48261, 39381, 33276, 25414, 4115, 23045, 23044,
30691, 38209, 25032, 36249, 26279, 29211, 53300, 35424, 30651, 25170,
29786, 38660, 35363, 37226, 38907, 2592, 29590, 52884, 32865, 1700,
36198, 1965, 20355, 9318, 47156, 31143, 28149, 46609, 34434, 4941,
38230, 33559, 39274, 27579, 38046, 32070, 31296, 47157, 34633, 46164,
28478, 3234, 4196, 28003, 4771, 33009, 3091, 3858, 32920, 21325, 29746,
25771, 26464, 22114, 29254, 24103, 3549, 4225, 23591, 21736, 54760,
30590, 4226, 4829, 21899, 3454, 32504, 38078, 21737, 21992, 12609,
6112, 25441, 1042486, 28558, 31339, 30637, 3106, 38191, 35059, 8563,
36783, 2764, 1940, 27837, 47716, 32680, 28122, 22124, 35269, 45580,
28851, 39881, 34107, 30585, 9581, 3504, 1783, 33592, 2856, 23087,
52897, 33445, 24977, 29614, 22065, 30129, 3587, 28373, 53489, 8736,
5222, 36958, 21104, 33530, 21128, 3940, 4672, 21596, 23077, 30251,
25234, 20045, 3919, 46263, 50694, 21713, 4634, 32735, 30710, 38713,
46629, 30634, 26629, 39539, 35535, 35167, 2570, 6024, 63735, 47693,
28822, 23776, 25622, 48656, 24974, 45229, 20904, 38289, 22383, 8735,
36255, 12553, 21941, 47925, 21235, 3404, 48391, 32831, 23421, 21987,
4004, 37613, 46992, 32907, 26289, 39822, 38605, 24162, 38067, 45734,
29634, 26342, 25074, 65103, 32548, 28435, 24013, 59066, 36988, 31811,
29750, 20887, 33760, 39558, 30307, 36527, 33670, 28953, 29730, 24465,
32517, 8232, 12613, 59100, 44285, 31672, 26577, 22367, 29733, 58566,
38013, 26313, 4901, 20332, 21584, 24867, 30566, 24730, 23679, 26429,
21932, 30802, 59162, 59130, 23344, 28414, 1939, 21359, 3596, 54196,
45588, 26207, 33802, 50967, 3675, 9701, 51222, 38221, 2860, 5509,
6022, 4221, 33643, 44176, 33285, 39045, 38181, 8759, 40104, 9787,
6093, 9655, 28937, 27167, 31499, 49899, 47956, 24246, 55128, 47212,
24803, 38539, 2793, 20502, 25619, 48044, 22057, 59120, 31637, 12529,
3589, 4158, 30414, 45252, 23267, 26133, 9584, 33012, 2946, 27986,
24853, 47120, 3310, 6103, 31716, 1041647, 53132, 9685, 9602, 4851,
35060, 48848, 35607, 32838, 40158, 27048, 49916, 27788, 48389, 38379,
50912, 24315, 45937, 31636, 31809, 32509, 28670, 1808, 38746, 1041734,
38588, 32251, 12294, 53272, 32834, 37108, 29749, 32532, 50136, 37321,
24328, 34656, 32121, 44220, 30115, 21891, 28925, 30300, 50715, 51684,
3872, 36757, 57344, 31961, 65109, 53188, 32474, 46027, 29649, 37351,
4659, 44145, 25703, 35809, 34321, 32453, 38394, 21822, 27029, 35674,
44988, 3230, 39899, 28698, 20448, 2872, 312, 24005, 31406, 20873,
29522, 39269, 35566, 30741, 20130, 34444, 21766, 51260, 38968, 35513,
7952, 28181, 2852, 51082, 21777, 29309, 27814, 27544, 28186, 20308,
32948, 25305, 51117, 31047, 31040, 36286, 49920, 38471, 30544, 2504,
30207, 53812, 25578, 32406, 49632, 34122, 22418, 8054, 4163, 33308,
1043286, 39548, 50745, 25203, 26840, 28359, 44992, 24976, 8835, 7936,
44788, 45244, 38475, 28218, 26462, 53413, 12593, 47585, 40132, 23394,
51687, 24646, 33300, 35565, 21348, 4623, 36764, 2576, 40434, 25850,
23630, 24319, 30732, 4609, 33043, 4936, 29060, 59161, 25098, 45787,
36142, 39493, 8228, 22930, 23724, 1013, 26241, 21242, 44415, 4811,
49847, 9319, 21632, 23013, 34649, 58979, 21076, 31041, 22697, 24623,
900, 30428, 31401, 38414, 34662, 47736, 49455, 52040, 29234, 2880,
3453, 52452, 8481, 26214, 30094, 25947, 39608, 13213, 30977, 22204,
1937, 46524, 8599, 24409, 48140, 36454, 38536, 20814, 50505, 28153,
59091, 25443, 22179, 39290, 27516, 28865, 2551, 26355, 23386, 52196,
53808, 32494, 27088, 4896, 38064, 9756, 2862, 35641, 24275, 49744,
36144, 37758, 25031, 9320, 33302, 29822, 27243, 38225, 29481, 4169,
23913, 57474, 32687, 33275, 22022, 23388, 35715, 30610, 3743, 50560,
59098, 30315, 1925, 21957, 25524, 31264, 46364, 44263, 36264, 24287,
24653, 38255, 31311, 28234, 45331, 46161, 9737, 22039, 25884, 26786,
6027, 26874, 20133, 35438, 37196, 34875, 3311, 32203, 25287, 31001,
20939, 35773, 32608, 54736, 21519, 770, 36174, 28609, 2873, 9635,
9122, 32033, 462, 4250, 8361, 25458, 3463, 39912, 2722, 48596, 35876,
32957, 52740, 22778, 36943, 27774, 29471, 32880, 2947, 4168, 971,
20432, 29557, 22438, 30420, 21971, 51094, 28037, 34914, 52656, 3522,
4824, 25722, 4962, 10070, 20885, 51086, 4617, 47105, 32629, 4650,
59011, 31607, 24458, 22764, 45805, 27194, 9605, 40140, 29277, 8765,
61623, 30439, 51210, 33499, 21474, 51075, 23697, 24439, 3465, 24347,
38816, 23495, 36060, 51788, 49714, 3793, 46944, 39533, 36676, 27945,
32349, 45544, 27603, 35837, 35808, 49356, 31983, 36845, 32371, 25854,
27099, 24472, 28335, 28205, 26191, 3929, 44624, 1724, 52888, 34103,
38774, 27584, 26880, 4165, 26806, 30519, 6113, 27696, 2797, 28196,
33040, 50928, 30872, 29200, 24264, 28654, 36111, 29785, 32098, 12601,
32359, 27513, 22666, 38491, 21256, 25370, 31496, 8200, 9479, 29494,
50740, 32314, 36726, 20278, 47497, 37292, 25410, 22953, 39620, 30133,
36244, 31893, 39052, 23413, 25314, 54049, 38124, 38115, 37586, 27978,
50549, 54663, 1942, 38308, 49707, 33527, 40860, 44216, 5123, 29764,
36010, 3542, 38675, 21480, 31014, 63724, 27580, 22103, 30970, 28154,
3931, 32533, 20451, 37706, 36703, 20406, 45377, 6028, 50519, 40100,
25735, 25794, 30068, 36140, 28051, 477, 1043254, 31482, 28828, 4875,
39050, 32745, 45130, 8855, 26604, 28825, 27147, 36781, 31568, 9504,
21671, 36869, 30504, 39347, 1042479, 24691, 30178, 50734, 35178, 22684,
26865, 55193, 22852, 30208, 21719, 65102, 33515, 23308, 37276, 9585,
6114, 61607, 63732, 2799, 21866, 25602, 28889, 31975, 47344, 22446,
25341, 36049, 24336, 47449, 24971, 33333, 40573, 29701, 35114, 32824,
36994, 50028, 47452, 33688, 22108, 22275, 38643, 25601, 32010, 25358,
39031, 23786, 32538, 38342, 52308, 27527, 4614, 31098, 54660, 38607,
1042482, 50545, 33162, 36995, 21702, 26103, 20440, 21489, 33134, 61550,
3488, 21627, 20031, 22974, 23092, 1041718, 37193, 33463, 29020, 33400,
4173, 8056, 53888, 36929, 24396, 38192, 21874, 609, 26974, 46036,
33706, 769, 4722, 25139, 26485, 23629, 3873, 4167, 53672, 2858, 26726,
33743, 37168, 48977, 29696, 46316, 59106, 4164, 59116, 28780, 27103,
51469, 39607, 26505, 24832, 4763, 8238, 33213, 5251, 25134, 6049,
44081, 36635, 22956, 26866, 22732, 39719, 39314, 24709, 30415, 54943,
3451, 27902, 57347, 45785, 50544, 35905, 23125, 30511, 34003, 32521,
3462, 30361, 26406, 23673, 4001, 34532, 54729, 35435, 20461, 1042478,
48976, 53680, 45143, 3360, 24684, 28053, 35709, 44188, 4961, 24092,
25942, 63348, 23791, 21652, 32843, 38130, 25376, 21827, 8223, 21571,
39285, 34241, 47569, 4726, 32399, 34581, 36070, 8869, 25282, 31310,
21283, 38635, 4209, 9607, 28904, 2798, 27863, 28437, 30403, 2508,
25078, 38808, 33187, 20642, 39301, 37389, 53304, 28465, 8166, 26099,
8853, 25892, 12432, 48184, 2818, 3874, 39387, 35516, 26552, 39464,
1465, 2594, 33491, 2866, 6055, 31388, 34837, 39654, 29344, 36746,
37799, 36447, 59016, 54176, 25810, 26326, 8596, 34690, 57361, 23167,
27762, 32806, 25769, 36978, 1263, 27278, 39612, 5125, 65105, 32697,
44413, 6100, 39059, 55136, 33828, 29835, 6079, 34631, 49480, 45806,
39243, 8239, 35763, 27609, 27859, 22821, 52244, 61548, 24816, 54169,
39108, 28586, 21234, 2761, 21949, 29864, 29001, 35970, 4009, 26161,
46748, 46763, 491, 37619, 37159, 28173, 4850, 23100, 34261, 44191,
39156, 8564, 29096, 821, 20731, 39187, 49709, 1963, 12610, 40779,
52841, 5314, 22767, 33105, 21816, 32666, 59111, 26707, 39621, 33304,
55152, 40786, 40687, 3507, 4197, 13212, 30202, 38990, 5198, 3741,
59109, 22121, 25530, 37675, 59101, 39853, 32485, 12570, 26751, 1941,
44151, 32554, 25467, 3467, 48521, 1042480, 24407, 20369, 30187, 21032,
28711, 31330, 28751, 38788, 1967, 37274, 44180, 9321, 23536, 31820,
40201, 4770, 9523, 5130, 20760, 30757, 39848, 32526, 46360, 21421,
29158, 715, 24199, 45573, 21978, 29824, 25000, 26238, 4826, 20993,
40557, 23254, 1821, 4251, 28699, 31167, 3220, 27022, 62047, 40120,
20490, 57477, 4622, 30179, 22831, 4728, 49481, 8750, 32187, 34065,
6074, 46416, 63685, 47577, 1648, 53472, 21658, 33247, 24119, 4925,
38056, 34153, 46317, 46749, 1175, 4629, 28132, 47960, 44292, 28198,
28340, 39562, 21413, 38179, 25662, 4023, 22999, 4814, 37195, 25294,
33011, 32999, 24958, 21441, 24811, 29796, 38197, 28861, 25102, 21536,
34093, 31267, 23480, 31382, 22016, 1043331, 54800, 50564, 12583, 28416,
28293, 59125, 21617, 63248, 31686, 33725, 47020, 12575, 32341, 33253,
1043212, 699, 24398, 53301, 34137, 32386, 59037, 25087, 36993, 20319,
2891, 7925, 33503, 30201, 1042485, 24571, 4721, 32671, 31252, 21884,
33722, 9837, 52041, 4654, 34691, 32996, 39519, 26578, 23162, 36461,
34811, 466, 47495, 31933, 38170, 24361, 28479, 27018, 30633, 4193,
40442, 9688, 9603, 32503, 21648, 22707, 26570, 20689, 32639, 26541,
36184, 26946, 8048, 35126, 34115, 29626, 3099, 32305, 29801, 37638,
31117, 34071, 3020, 39559, 55016, 25225, 12616, 47104, 61656, 3476,
29184, 36799, 38112, 22021, 25179, 44273, 48173, 20458, 36524, 63234,
57360, 35781, 27292, 48727, 37569, 23522, 4899, 13115, 27607, 47688,
54988, 31513, 37610, 1462, 40367, 37445, 32350, 3338, 31998, 658,
38956, 10006, 52412, 25527, 31713, 9839, 34152, 49296, 23525, 48282,
10048, 34310, 33479, 28156, 818, 45356, 3911, 1816, 22829, 23625,
40633, 32718, 35032, 35538, 24130, 20504, 28644, 25100, 4675, 25248,
55113, 40485, 59020, 31171, 4772, 33454, 31751, 28160, 6063, 2854,
31368, 33580, 26925, 9606, 49939, 32458, 38045, 21553, 4819, 33418,
23143, 36671, 44403, 9501, 20291, 47340, 54029, 25600, 35692, 2863,
8255, 21591, 50969, 5335, 9583, 54184, 33005, 30105, 38497, 28640,
44861, 25319, 29440, 23729, 40284, 4810, 4166, 13095, 30328, 3944,
59113, 8016, 30048, 20970, 12317, 23769, 773, 33502, 24421, 2466,
801, 24760, 50956, 53040, 31627, 27769, 30347, 21526, 48192, 33240,
20120, 54077, 30239, 31174, 34619, 24920, 53428, 59184, 40515, 40023,
3794, 44051, 26112, 20812, 3584, 34558, 24413, 47945, 4821, 26654,
39568, 36294, 30938, 8182, 54044, 27035, 37213, 9643, 24996, 54996,
32519, 23853, 19999, 23700, 38417, 54548, 28297, 35109, 9117, 45068,
44202, 31118, 3797, 21878, 28108, 25488, 27179, 32633, 9476, 44217,
2881, 24822, 26389, 46916, 1719, 55072, 36620, 9438, 38189, 30640,
34645, 4189, 9744, 47926, 28353, 28071, 9728, 25413, 39130, 4706,
28867, 39661, 38893, 1042481, 34986, 36956, 34083, 31629, 20991, 25744,
33100, 30249, 9481, 27742, 40522, 29409, 1470, 22329, 25371, 8601,
39479, 26348, 20060, 52313, 23046, 20916, 31968, 31224, 1723, 36162,
30629, 20433, 53244, 29771, 20273, 33586, 20348, 20478, 32641, 1281,
22134, 3622, 33137, 59087, 20312, 9120, 35427, 32690, 63738, 38126,
33936, 1040426, 65117, 28063, 50784, 28626, 34396, 39535, 4649, 21638,
63727, 27964, 36381, 4638, 51500, 37530, 29605, 30153, 30233, 30910,
22241, 47364, 3511, 31659, 54945, 46388, 59054, 33399, 32496, 21426,
23445, 30717, 45188, 22199, 1041584, 59107, 28174, 36299, 23461, 1826,
9515, 45934, 27595, 4846, 3788, 30090, 28102, 38671, 30746, 47493,
40499, 34367, 4194, 44555, 1041705, 10063, 20356, 23996, 25571, 63723,
1663, 23568, 1461, 1731, 15104, 4618, 617, 28074, 29723, 31146, 21537,
37261, 48981, 27189, 26665, 48195, 12631, 9116, 51692, 46769, 33575,
9119, 27084, 29313, 26185, 23146, 29922, 21646, 53553, 45740, 3203,
2461, 45012, 25653, 40300, 12318, 29469, 63725, 20525, 10004, 46896,
21937, 30778, 21828, 44637, 38086, 27586, 44860, 25212, 28847, 25004,
37150, 6120, 32024, 61647, 31560, 23157, 48374, 33585, 28458, 46280,
33255, 30186, 511, 34506, 63734, 39237, 3210, 9115, 21422, 37397,
50659, 29662, 39545, 8838, 27648, 1042484, 34870, 30844, 47610, 714,
8815, 4213, 21657, 33940, 44557, 24951, 25898, 46357, 4220, 37264,
22718, 45713, 27553, 9531, 59097, 53485, 54072, 33179, 4219, 48852,
39138, 30933, 51900, 39563, 21990, 8814, 34769, 33603, 3104, 36989,
21792, 28540, 26624, 49456, 9539, 21533, 47464, 53431, 44611, 1840,
49256, 4658, 38859, 30180, 12595, 27280, 8150, 53000, 2435, 464, 32104,
4669, 9689, 30518, 38346, 12584, 20500, 5229, 28197, 48307, 40285,
31584, 2844, 27739, 3991, 65118, 29935, 47502, 5456, 28544, 36894,
59104, 33640, 39311, 20472, 29243, 24488, 8052, 20565, 21714, 31899,
21501, 3082, 25824, 27323, 40495, 21269, 9118, 54411, 4003, 3474,
30106, 991, 1042483, 35728, 27028, 28046, 441, 22036, 44865, 32427,
38173, 5319, 12336, 33215, 38133, 20191, 31729, 26727, 53476, 25421,
34905, 27453, 34670, 3355, 28651, 21545, 25944, 34388, 25912, 31384,
59112, 12433, 45235, 38111, 25119, 61501, 28463, 59021, 27053, 38892,
23805, 36944, 21550, 24091, 33660, 26613, 34943, 48904, 12618, 8569,
35892, 24561, 3795, 12579, 31207, 33421, 50277, 35203, 23218, 34851,
46037, 712, 23919, 24596, 592, 31260, 23158, 31806, 335, 34201, 3073,
20149, 31074, 1043330, 2839, 4765, 32286, 65106, 301, 36732, 37532,
22070, 35815, 30655, 37021, 47701, 5200, 38309, 35867, 59108, 61485,
5333, 44225, 31692, 31414, 51132, 22391, 3852, 21473, 63687, 20106,
27529, 39110, 32129, 4135, 25754, 7823, 30923, 12555, 28977, 4627,
54607, 771, 33862, 27016, 21985, 21599, 36487, 30545, 37624, 30154,
9641, 20147, 34383, 32660, 27822, 32482, 25531, 44751, 8565, 31565,
1825, 33750, 5507, 27994, 20034, 45700, 46433, 35819, 34427, 45227,
12623, 38504, 30597, 38171, 33071, 20834, 3792, 29280, 53220, 20127,
8134, 34597, 29854, 52507, 57503, 44900, 39307, 30109, 8254, 59110,
12526, 51796, 23831, 38253, 31725, 30609, 38076, 30352, 28078, 26248,
4231, 25803, 34527, 22948, 33450, 20898, 65110, 1661, 38039, 27067,
27320, 21606, 40550, 561, 20653, 4753, 9601, 49564, 25880, 59126,
36779, 32792, 1041701, 21595, 25891, 15360, 34993, 9332, 30318, 34579,
21342, 32361, 1824, 48531, 50052, 1811, 34407, 34770, 29989, 26855,
21799, 24817, 2384, 52996, 40569, 29165, 40840, 25520, 4708, 34543,
28327, 35331, 25303, 9831, 35183, 38935, 1371, 4108, 31381, 44405,
1041586, 2315, 38425, 35916, 59140, 24698, 36837, 38771, 1041721,
59185, 50489, 29722, 36405, 700, 44749, 24469, 4756, 29599, 1843,
3537, 21119, 46176, 8494, 38107, 32652, 29990, 24812, 24331, 4657,
29898, 596, 22775, 20396, 21582, 22165, 25315, 277, 21894, 47469,
38210, 59025, 39201, 31921, 51219, 23579, 8733, 26212, 40480, 37300,
1041634, 21417, 34829, 24473, 39851, 27795, 23011, 30136, 23138, 40521,
63237, 24257, 53077, 31721, 23018, 20469, 32714, 36418, 36841, 48724,
9711, 38000, 22754, 38924, 3988, 36324, 21173, 1813, 34996, 46516,
34191, 34085, 1043234, 1954, 373, 14592, 3993, 22007, 23059, 25420,
45460, 50924, 29403, 23437, 1949, 7984, 4705, 21670, 47128, 25291,
293, 63238, 49438, 36802, 20164, 34885, 4827, 23270, 30169, 35791,
35881, 13214, 28712, 35884, 34814, 4620, 29088, 28402, 36426, 35866,
50687, 63281, 36761, 30822, 1836, 21310, 26964, 24682, 54148, 31087,
23860, 4873, 46400, 39003, 3502, 50493, 38722, 4777, 32631, 23462,
39995, 4841, 24061, 54161, 55129, 22158, 35098, 50025, 21675, 25431,
3348, 1834, 23408, 30232, 35830, 3881, 24340, 44613, 28805, 9832,
49788, 40107, 35039, 36068, 48139, 23869, 32491, 9760, 53459, 4864,
53960, 38094, 28457, 20608, 31153, 30768, 8050, 4963, 23620, 35559,
9333, 51144, 23789, 29336, 62018, 32997, 35563, 4869, 27462, 1659,
4633, 15872, 33081, 6019, 45139, 50143, 38026, 31824, 4939, 27617,
25344, 23997, 1043188, 28126, 32557, 27781, 1770, 1245, 28167, 49913,
50893, 29641, 27263, 38128, 39253, 28222, 9662, 1789, 4243, 1473,
1679, 45184, 30241, 20800, 28140, 31061, 34015, 4214, 49396, 9130,
28672, 1041707, 4782, 25494, 34568, 31042, 5205, 25558, 29996, 46892,
25326, 1042451, 4758, 4611, 5316, 48730, 50044, 593, 1676, 36955,
33222, 25466, 39342, 8709, 1042391, 21698, 21668, 22244, 32044, 35131,
23628, 1790, 51329, 40063, 38331, 36036, 24813, 29113, 53237, 53568,
37406, 36968, 50760, 48159, 831, 36368, 39089, 63631, 23075, 3092,
33983, 30758, 23504, 31308, 1620, 4192, 24447, 37510, 5285, 39333,
54187, 23781, 57345, 30183, 59094, 37007, 2698, 4608, 25549, 37742,
33193, 22002, 3229, 1946, 33784, 3796, 26686, 35548, 1728, 28407,
5503, 52868, 28625, 9681, 35635, 44641, 4849, 27825, 58999, 21708,
9680, 34758, 26551, 3674, 603, 39087, 29145, 4006, 7747, 33636, 36460,
5290, 22160, 4828, 20769, 38541, 25062, 29179, 65532, 37043, 13199,
31668, 34068, 39600, 20295, 12556, 30394, 1938, 30305, 1195, 24726,
29619, 9586, 51789, 865, 1771, 37555, 45823, 63686, 35057, 26728,
52152, 22809, 28088, 54396, 33600, 24826, 40702, 40848, 47129, 1644,
32703, 22137, 51334, 28227, 24756, 34451, 58980, 4624, 8902, 1041617,
713, 21913, 29462, 22874, 26891, 1658, 63309, 31567, 38358, 44079,
28753, 21863, 6115, 49344, 31071, 515, 53217, 375, 45798, 28228, 31858,
52180, 21277, 1956, 9352, 9125, 3362, 27355, 21655, 21872, 47607,
39825, 52899, 33094, 1209, 25772, 9613, 808, 59038, 21522, 58865,
24980, 45253, 58636, 57346, 23810, 22427, 33449, 50491, 24913, 633,
34417, 38894, 21994, 30402, 38552, 53484, 1945, 24527, 22257, 10877,
48072, 9828, 468, 21057, 32609, 44452, 57812, 8215, 29461, 25711,
37648, 2544, 35988, 21405, 22178, 33323, 26015, 26584, 32753, 62139,
3102, 28000, 33583, 25084, 1041200, 1042433, 3943, 39361, 31434, 720,
9512, 35820, 26487, 35616, 28425, 33107, 24792, 21240, 49808, 22221,
26164, 2849, 2870, 33096, 36040, 20807, 23882, 28538, 33210, 39711,
53825, 1643, 49108, 33615, 59403, 61626, 49928, 2757, 33355, 22139,
4203, 51428, 33205, 28356, 27673, 23005, 33477, 44866, 35924, 53597,
38323, 26003, 34946, 20367, 34022, 38466, 37709, 27153, 59095, 29384,
32761, 34282, 27523, 32381, 9774, 12571, 34314, 26851, 2718, 4132,
28532, 22136, 34728, 33669, 25034, 4673, 35764, 36490, 28950, 37502,
20643, 45231, 27904, 11520, 23090, 26199, 59390, 36343, 30684, 25077,
34784, 8198, 30568, 34044, 29134, 39123, 38150, 30775, 59057, 22163,
37393, 8001, 4645, 49677, 37200, 54747, 33686, 39553, 37219, 25721,
45957, 44361, 320, 37434, 38589, 27821, 5359, 1041223, 34847, 26107,
57759, 21939, 29852, 34612, 34360, 22159, 36409, 618, 39627, 50771,
32475, 4172, 32412, 37001, 15616, 52843, 61483, 26503, 29355, 59023,
31255, 38068, 31103, 28510, 36022, 34948, 63719, 21294, 61372, 61664,
40150, 36163, 12617, 50753, 30820, 1810, 33007, 8566, 28325, 33129,
24186, 59119, 48333, 1041648, 23057, 9745, 12850, 35973, 24124, 21804,
29502, 33074, 48281, 24581, 25642, 51673, 29674, 39850, 35543, 34949,
32181, 26244, 25115, 20112, 4652, 34615, 26017, 33338, 48737, 25620,
26196, 59138, 63333, 23825, 21317, 26839, 45600, 35578, 3075, 9998,
31142, 4710, 6066, 22349, 26719, 44169, 4874, 31428, 59175, 45321,
38096, 58971, 34479, 35754, 39509, 19989, 49567, 21970, 32774, 40157,
2847, 647, 34739, 34496, 40766, 38012, 4809, 1689, 2822, 39993, 8771,
39221, 33894, 9428, 20515, 36347, 4130, 49520, 28497, 50276, 52258,
36759, 31959, 21117, 26965, 2842, 1041702, 977, 58552, 814, 63681,
6116, 24012, 1127, 24337, 49679, 25523, 38649, 34541, 22744, 27311,
30562, 65111, 51923, 31104, 30442, 34647, 28951, 6095, 31786, 10026,
1042476, 29678, 40605, 653, 7956, 61558, 34502, 21707, 24949, 49093,
10061, 25474, 38670, 27075, 34578, 4667, 28593, 36834, 21757, 34553,
307, 21636, 34635, 48528, 38069, 25616, 3801, 2888, 20456, 34222,
21243, 29030, 4731, 507, 21005, 343, 4678, 3799, 4636, 27988, 4938,
36155, 33914, 4965, 25160, 30821, 9334, 5328, 61614, 49360, 58773,
35014, 34563, 59157, 13568, 52405, 23346, 38148, 63683, 4008, 33390,
1041720, 21988, 1649, 32353, 2580, 31418, 40639, 21867, 20762, 52853,
2821, 8568, 32901, 31658, 36961, 26249, 27315, 37036, 4216, 37476,
59032, 3544, 35174, 38051, 4241, 29855, 47943, 31923, 12620, 63233,
21499, 4923, 39589, 27647, 513, 39634, 21541, 22702, 25306, 34623,
1043235, 4013, 35074, 51792, 52600, 38718, 9322, 26722, 25462, 1832,
12319, 766, 20375, 4920, 44621, 23896, 35855, 30874, 30759, 29351,
32942, 57350, 20850, 21500, 26407, 65125, 24751, 1042460, 6121, 22063,
58637, 39214, 36667, 31063, 49573, 63684, 65123, 32679, 40133, 32365,
3489, 39255, 38335, 24380, 12032, 3800, 62719, 38256, 38765, 47159,
21972, 39631, 1041202, 8960, 28396, 26917, 24258, 63682, 38938, 30242,
39405, 30883, 26188, 21471, 21902, 29690, 27001, 32046, 8598, 4230,
49961, 2560, 21085, 59096, 38034, 4754, 29934, 7969, 3798, 32029,
36425, 45845, 1815, 30679, 44609, 24900, 27192, 33830, 63329, 27079,
21558, 38178, 10066, 21510, 22313, 23265, 29744, 63739, 31494, 33065,
40617, 26991, 63337, 22209, 63737, 33907, 28451, 21691, 8895, 53095,
46895, 50032, 35826, 31800, 1040824, 39250, 32184, 501, 20558, 4878,
28821, 26166, 27421, 2025, 4797, 22003, 59191, 23833, 27166, 39557,
63726, 30091, 33630, 59036, 37350, 3879, 54973, 30780, 25288, 3487,
20822, 39582, 25332, 12551, 23539, 20389, 5234, 30818, 27872, 1123,
57720, 39122, 23105, 36495, 30604, 23782, 32236, 995, 26638, 1835,
58942, 35594, 5206, 40843, 34193, 13076, 33335, 30817, 1846, 23418,
944, 39675, 40141, 26688, 59117, 21833, 1715, 39079, 36346, 34978,
8707, 25082, 29647, 48856, 61692, 30071, 37728, 5418, 34552, 35461,
37891, 63280, 3121, 36427, 40510, 26171, 22741, 30777, 44740, 29394,
20721, 12594, 34952, 39585, 47028, 50739, 29317, 52645, 26296, 33848,
28095, 30045, 3916, 45480, 20547, 22462, 38217, 37970, 51674, 25373,
1041680, 3880, 47719, 35628, 58841, 29322, 9519, 24675, 329, 12621,
1043241, 29736, 1104, 44808, 50567, 28270, 36856, 58991, 20486, 36076,
2365, 36479, 9493, 57480, 28635, 21669, 34199, 46375, 21087, 61627,
29029, 23723, 35084, 34108, 37312, 25899, 6102, 58998, 1645, 26060,
25035, 2861, 37225, 9587, 29807, 22592, 53104, 21068, 1043185, 23735,
3787, 40482, 39319, 29136, 30306, 11056, 34849, 824, 8366, 63282,
26137, 49668, 29999, 40748, 36382, 33682, 30652, 29484, 28152, 36740,
49343, 24806, 36118, 4242, 35912, 34162, 28386, 30738, 32377, 23301,
51609, 4917, 8614, 26075, 8748, 34510, 28390, 31546, 33588, 28583,
35357, 28734, 50137, 24814, 50144, 1042399, 36489, 2876, 1763, 28408,
4099, 29130, 31059, 31657, 52240, 5354, 20956, 29166, 25661, 38747,
35281, 30857, 26978, 32895, 21886, 45072, 45352, 47103, 4907, 51908,
8680, 21549, 30350, 22024, 54749, 31631, 62017, 4674, 4612, 39053,
45656, 37396, 38737, 32619, 37032, 31709, 33985, 33393, 37716, 9527,
28399, 50433, 1858, 613, 26717, 37169, 27710, 63289, 27628, 14848,
32552, 33476, 33003, 37000, 22575, 4854, 28061, 46904, 9335, 9424,
46616, 35811, 3875, 58974, 27386, 48289, 52908, 29977, 38967, 59178,
39699, 20594, 26979, 36706, 1042404, 24779, 1042468, 7717, 1458, 9743,
24530, 30663, 35749, 38601, 61669, 21343, 34306, 59201, 27537, 34001,
27887, 776, 30472, 24774, 29585, 20925, 25540, 9615, 39309, 28693,
23049, 28598, 4904, 45339, 30855, 30087, 28766, 49941, 2704, 59018,
28610, 6060, 8725, 38408, 21604, 24575, 32537, 8567, 27929, 30344,
45825, 13312, 1181, 1040826, 34047, 36019, 38860, 37826, 22376, 58661,
32945, 36146, 32171, 58732, 30782, 7779, 12559, 26697, 31287, 37561,
38356, 22138, 39757, 25736, 38224, 38514, 25503, 37711, 25775, 3328,
37928, 1596, 49816, 24665, 33537, 38398, 38328, 52320, 35575, 21981};
System.arraycopy(temp, 0, chars, chars.length - temp.length, temp.length);
}
}
}
| Java |
/*
* 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 com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.base.Objects;
/**
* Some microbenchmarks for the {@link Objects} class.
*
* @author Ben L. Titzer
*/
public class ObjectsBenchmark extends SimpleBenchmark {
private static final Integer I0 = -45;
private static final Integer I1 = -1;
private static final Integer I2 = 3;
private static final String S0 = "3";
private static final String S1 = "Ninety five";
private static final String S2 = "44 one million";
private static final String S3 = "Lowly laundry lefties";
private static final String S4 = "89273487U#*&#";
private static final Double D0 = 9.234d;
private static final Double D1 = -1.2e55;
public int timeHashString_2(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += Objects.hashCode(S0, S1);
}
return dummy;
}
public int timeHashString_3(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += Objects.hashCode(S0, S1, S2);
}
return dummy;
}
public int timeHashString_4(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += Objects.hashCode(S0, S1, S2, S3);
}
return dummy;
}
public int timeHashString_5(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += Objects.hashCode(S0, S1, S2, S3, S4);
}
return dummy;
}
public int timeHashMixed_5(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += Objects.hashCode(I2, S1, D1, S2, I0);
dummy += Objects.hashCode(D0, I1, S3, I2, S0);
}
return dummy;
}
public static void main(String[] args) {
Runner.main(ObjectsBenchmark.class, args);
}
}
| Java |
/*
* 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.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.base.Strings;
/**
* Microbenchmark for {@link Strings#repeat}
*
* @author Mike Cripps
*/
public class StringsRepeatBenchmark extends SimpleBenchmark {
@Param({"1", "5", "25", "125"}) int count;
@Param({"1", "10"}) int length;
private String originalString;
@Override protected void setUp() {
originalString = Strings.repeat("x", length);
}
public void timeOldRepeat(int reps) {
for (int i = 0; i < reps; i++) {
String x = oldRepeat(originalString, count);
if (x.length() != (originalString.length() * count)) {
throw new RuntimeException("Wrong length: "+x);
}
}
}
public void timeMikeRepeat(int reps) {
for (int i = 0; i < reps; i++) {
String x = mikeRepeat(originalString, count);
if (x.length() != (originalString.length() * count)) {
throw new RuntimeException("Wrong length: "+x);
}
}
}
public void timeMartinRepeat(int reps) {
for (int i = 0; i < reps; i++) {
String x = martinRepeat(originalString, count);
if (x.length() != (originalString.length() * count)) {
throw new RuntimeException("Wrong length: "+x);
}
}
}
private static final String mikeRepeat(String string, int count) {
final int len = string.length();
char[] strCopy = new char[len * Integer.highestOneBit(count)];
string.getChars(0, len, strCopy, 0);
char[] array = new char[len * count];
int strCopyLen = len;
int pos = 0;
while (count != 0) {
if ((count & 1) != 0) {
System.arraycopy(strCopy, 0, array, pos,strCopyLen);
pos += strCopyLen;
}
count >>= 1;
if (count != 0) {
System.arraycopy(strCopy, 0, strCopy, strCopyLen, strCopyLen);
strCopyLen <<= 1;
}
}
return new String(array);
}
private static final String oldRepeat(String string, int count) {
// If this multiplication overflows, a NegativeArraySizeException or
// OutOfMemoryError is not far behind
final int len = string.length();
final int size = len * count;
char[] array = new char[size];
for (int i = 0; i < size; i+=len) {
string.getChars(0, len, array, i);
}
return new String(array);
}
private static final String martinRepeat(String string, int count) {
final int len = string.length();
final int size = len * count;
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);
}
public static void main(String[] args) {
Runner.main(StringsRepeatBenchmark.class, args);
}
}
| Java |
/*
* 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.collect;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.collect.CollectionBenchmarkSampleData.Element;
import java.util.Collection;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentSkipListMap;
/**
* A microbenchmark that tests the performance of get() on various map
* implementations. Forked from {@link SetContainsBenchmark}.
*
* @author Nicholaus Shupe
*/
public class MapBenchmark extends SimpleBenchmark {
@Param({"Hash", "LinkedHM", "MapMaker1", "Immutable"})
private Impl impl;
public enum Impl {
Hash {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map = Maps.newHashMap();
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
LinkedHM {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map = Maps.newLinkedHashMap();
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
UnmodHM {
@Override Map<Element, Element> create(Collection<Element> keys) {
return Collections.unmodifiableMap(Hash.create(keys));
}
},
SyncHM {
@Override Map<Element, Element> create(Collection<Element> keys) {
return Collections.synchronizedMap(Hash.create(keys));
}
},
Tree {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map = Maps.newTreeMap();
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
SkipList {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map = new ConcurrentSkipListMap<Element, Element>();
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
ConcurrentHM1 {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map =
new ConcurrentHashMap<Element, Element>(keys.size(), 0.75f, 1);
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
ConcurrentHM16 {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map =
new ConcurrentHashMap<Element, Element>(keys.size(), 0.75f, 16);
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
MapMaker1 {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map = new MapMaker()
.concurrencyLevel(1)
.makeMap();
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
MapMaker16 {
@Override Map<Element, Element> create(Collection<Element> keys) {
Map<Element, Element> map = new MapMaker()
.concurrencyLevel(16)
.makeMap();
for (Element element: keys) {
map.put(element, element);
}
return map;
}
},
Immutable {
@Override Map<Element, Element> create(Collection<Element> keys) {
ImmutableMap.Builder<Element, Element> builder = ImmutableMap.builder();
for (Element element : keys) {
builder.put(element, element);
}
return builder.build();
}
},
ImmutableSorted {
@Override Map<Element, Element> create(Collection<Element> keys) {
ImmutableSortedMap.Builder<Element, Element> builder =
ImmutableSortedMap.naturalOrder();
for (Element element : keys) {
builder.put(element, element);
}
return builder.build();
}
};
abstract Map<Element, Element> create(Collection<Element> contents);
}
@Param({"5", "50", "500", "5000", "50000"})
private int size;
// TODO: look at exact (==) hits vs. equals() hits?
@Param("0.9")
private double hitRate;
@Param("true")
private boolean isUserTypeFast;
// "" means no fixed seed
@Param("")
private SpecialRandom random;
@Param("false")
private boolean sortedData;
// the following must be set during setUp
private Element[] queries;
private Map<Element, Element> mapToTest;
private Collection<Element> values;
@Override public void setUp() {
CollectionBenchmarkSampleData sampleData =
new CollectionBenchmarkSampleData(
isUserTypeFast, random, hitRate, size);
if (sortedData) {
List<Element> valueList = Lists.newArrayList(sampleData.getValuesInSet());
Collections.sort(valueList);
values = valueList;
} else {
values = sampleData.getValuesInSet();
}
this.mapToTest = impl.create(values);
this.queries = sampleData.getQueries();
}
public boolean timeGet(int reps) {
// Paranoia: acting on hearsay that accessing fields might be slow
// Should write a benchmark to test that!
Map<Element, Element> map = mapToTest;
Element[] queries = this.queries;
// Allows us to use & instead of %, acting on hearsay that division
// operators (/%) are disproportionately expensive; should test this too!
int mask = queries.length - 1;
boolean dummy = false;
for (int i = 0; i < reps; i++) {
dummy ^= map.get(queries[i & mask]) != null;
}
return dummy;
}
public int timeCreateAndPopulate(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += impl.create(values).size();
}
return dummy;
}
public static void main(String[] args) throws Exception {
Runner.main(MapBenchmark.class, args);
}
}
| Java |
/*
* 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.collect;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
/**
* Benchmarking interners.
*
* @author Dimitris Andreou
*/
public class InternersBenchmark extends SimpleBenchmark {
public int timeWeakInterner(int reps) {
Interner<String> interner = Interners.newWeakInterner();
for (int i = 0; i < reps; i++) {
interner.intern(Double.toHexString(Math.random()));
}
return reps;
}
public int timeStrongInterner(int reps) {
Interner<String> interner = Interners.newStrongInterner();
for (int i = 0; i < reps; i++) {
interner.intern(Double.toHexString(Math.random()));
}
return reps;
}
public int timeStringIntern(int reps) {
for (int i = 0; i < reps; i++) {
Double.toHexString(Math.random()).intern();
}
return reps;
}
public static void main(String[] args) {
Runner.main(InternersBenchmark.class, args);
}
}
| Java |
/*
* 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.collect;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.collect.BenchmarkHelpers.SetImpl;
import com.google.common.collect.CollectionBenchmarkSampleData.Element;
import java.util.Set;
/**
* A microbenchmark that tests the performance of contains() on various Set
* implementations.
*
* @author Kevin Bourrillion
*/
public class SetContainsBenchmark extends SimpleBenchmark {
// Start at 4.88 then multiply by 2*2^phi <evil cackle> - The goal is be uniform
// yet visit a variety of "values-relative-to-the-next-power-of-2"
@Param({"5", "30", "180", "1100", "6900", "43000", "260000"}) // "1600000", "9800000"
private int size;
// TODO(kevinb): look at exact (==) hits vs. equals() hits?
@Param({"0.2", "0.8"})
private double hitRate;
@Param("true")
private boolean isUserTypeFast;
// "" means no fixed seed
@Param("")
private SpecialRandom random;
@Param({"Hash", "Immutable"})
private SetImpl impl;
// the following must be set during setUp
private Element[] queries;
private Set<Element> setToTest;
@Override public void setUp() {
CollectionBenchmarkSampleData sampleData =
new CollectionBenchmarkSampleData(
isUserTypeFast, random, hitRate, size);
this.setToTest = impl.create(sampleData.getValuesInSet());
this.queries = sampleData.getQueries();
}
public boolean timeContains(int reps) {
// Paranoia: acting on hearsay that accessing fields might be slow
// Should write a benchmark to test that!
Set<Element> set = setToTest;
Element[] queries = this.queries;
int mask = queries.length - 1;
boolean dummy = false;
for (int i = 0; i < reps; i++) {
dummy ^= set.contains(queries[i & mask]);
}
return dummy;
}
public static void main(String[] args) throws Exception {
Runner.main(SetContainsBenchmark.class, args);
}
}
| Java |
/*
* 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.collect;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* Tests the speed of iteration of different iteration methods for collections.
*
* @author David Richter
*/
public class IteratorBenchmark extends SimpleBenchmark {
@Param({"0", "1", "16", "256", "4096", "65536"}) int size;
// use concrete classes to remove any possible polymorphic overhead?
Object[] array;
ArrayList<Object> arrayList;
LinkedList<Object> linkedList;
@Override protected void setUp() {
array = new Object[size];
arrayList = Lists.newArrayListWithCapacity(size);
linkedList = Lists.newLinkedList();
for (int i = 0; i < size; i++) {
Object value = new Object();
array[i] = value;
arrayList.add(value);
linkedList.add(value);
}
}
public int timeArrayIndexed(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (int index = 0; index < size; index++) {
sum += array[index].hashCode();
}
}
return sum;
}
public int timeArrayIndexedLength(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (int index = 0; index < array.length; index++) {
sum += array[index].hashCode();
}
}
return sum;
}
public int timeArrayFor(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : array) {
sum += value.hashCode();
}
}
return sum;
}
public int timeArrayListIndexed(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (int index = 0; index < size; index++) {
sum += arrayList.get(index).hashCode();
}
}
return sum;
}
public int timeArrayListIndexedLength(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (int index = 0; index < arrayList.size(); index++) {
sum += arrayList.get(index).hashCode();
}
}
return sum;
}
public int timeArrayListFor(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : arrayList) {
sum += value.hashCode();
}
}
return sum;
}
public int timeArrayListToArrayFor(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : arrayList.toArray()) {
sum += value.hashCode();
}
}
return sum;
}
public int timeLinkedListFor(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : linkedList) {
sum += value.hashCode();
}
}
return sum;
}
public int timeLinkedListToArrayFor(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : linkedList.toArray()) {
sum += value.hashCode();
}
}
return sum;
}
public static void main(String[] args) {
Runner.main(IteratorBenchmark.class, args);
}
}
| Java |
/*
* 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.collect;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Maps;
import java.util.Collections;
import java.util.Map;
/**
* A Caliper benchmark used to track Builder performance. Currently supports:
* ImmutableMap's copyOf and addAll methods.
*
* @author Paul Lindner
*/
public class ImmutableMapCreationBenchmark extends SimpleBenchmark {
@Param({"0", "1", "5", "50", "500", "5000", "50000"}) private int size;
/** Holds testdata that is inserted into the Builder, populated by setUp() */
Map<String, String> testData = Maps.newHashMap();
/** A map we insert into, in class scope to keep the JVM from optimizing local references */
ImmutableMap<String, String> testMap;
// Preinitialize these to keep them out of the inner benchmark loop
public static final Map<String, String> SINGLETON_MAP = Collections.singletonMap("1", "1");
public static final Map<String, String> EMPTY_MAP = Collections.emptyMap();
@Override
public void setUp() {
if (size == 0) {
testData = EMPTY_MAP;
} else if (size == 1) {
testData = SINGLETON_MAP;
} else {
testData = Maps.newHashMap();
for (int i = 0; i < size; i++) {
String number = Integer.toString(i);
testData.put(number, number);
}
}
}
/**
* Test performance of ImmutableMap.copyOf()
*
* @param reps repetitions (used by Caliper)
* @return a dummy string to ensure that the JVM does not optimize our code
*/
public String timeCopyOf(int reps) {
for (int i = 0; i < reps; i++) {
testMap = ImmutableMap.copyOf(testData);
}
return testMap.get("");
}
/**
* Test performance of the ImmutableMap.Builder putAll method.
*
* @param reps repetitions (used by Caliper)
* @return a dummy string to ensure that the JVM does not optimize our code
*/
public String timeBuilder(int reps) {
for (int i = 0; i < reps; i++) {
ImmutableMap.Builder<String, String> builder = ImmutableMap.builder();
testMap = builder.putAll(testData).build();
}
return testMap.get("");
}
public static void main(String[] args) {
Runner.main(ImmutableMapCreationBenchmark.class, args);
}
}
| Java |
/*
* 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.collect;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.collect.HashMultiset;
import com.google.common.collect.Multiset;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
/**
* Benchmark for HashMultiset.add for an already-present element.
*
* @author Louis Wasserman
*/
public class HashMultisetAddPresentBenchmark extends SimpleBenchmark {
private static final int ARRAY_MASK = 0x0ffff;
private static final int ARRAY_SIZE = 0x10000;
List<Multiset<Integer>> multisets = new ArrayList<Multiset<Integer>>(0x10000);
int[] queries = new int[ARRAY_SIZE];
@Override
protected void setUp() {
Random random = new Random();
multisets.clear();
for (int i = 0; i < ARRAY_SIZE; i++) {
HashMultiset<Integer> multiset = HashMultiset.<Integer>create();
multisets.add(multiset);
queries[i] = random.nextInt();
multiset.add(queries[i]);
}
}
public int timeAdd(int reps) {
int tmp = 0;
for (int i = 0; i < reps; i++) {
int j = i & ARRAY_MASK;
tmp += multisets.get(j).add(queries[j], 4);
}
return tmp;
}
public static void main(String[] args) {
Runner.main(HashMultisetAddPresentBenchmark.class, args);
}
}
| Java |
/*
* 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.collect;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.base.Function;
import com.google.common.collect.MapMaker;
import com.google.common.primitives.Ints;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.atomic.AtomicLong;
/**
* Simple single-threaded benchmark for a computing map with maximum size.
*
* @author Charles Fry
*/
public class MapMakerSingleThreadBenchmark extends SimpleBenchmark {
@Param({"1000", "2000"}) int maximumSize;
@Param("5000") int distinctKeys;
@Param("4") int segments;
// 1 means uniform likelihood of keys; higher means some keys are more popular
// tweak this to control hit rate
@Param("2.5") double concentration;
Random random = new Random();
Map<Integer, Integer> cache;
int max;
static AtomicLong requests = new AtomicLong(0);
static AtomicLong misses = new AtomicLong(0);
@Override protected void setUp() {
// random integers will be generated in this range, then raised to the
// power of (1/concentration) and floor()ed
max = Ints.checkedCast((long) Math.pow(distinctKeys, concentration));
cache = new MapMaker()
.concurrencyLevel(segments)
.maximumSize(maximumSize)
.makeComputingMap(
new Function<Integer, Integer>() {
@Override public Integer apply(Integer from) {
return (int) misses.incrementAndGet();
}
});
// To start, fill up the cache.
// Each miss both increments the counter and causes the map to grow by one,
// so until evictions begin, the size of the map is the greatest return
// value seen so far
while (cache.get(nextRandomKey()) < maximumSize) {}
requests.set(0);
misses.set(0);
}
public int time(int reps) {
int dummy = 0;
for (int i = 0; i < reps; i++) {
dummy += cache.get(nextRandomKey());
}
requests.addAndGet(reps);
return dummy;
}
private int nextRandomKey() {
int a = random.nextInt(max);
/*
* For example, if concentration=2.0, the following takes the square root of
* the uniformly-distributed random integer, then truncates any fractional
* part, so higher integers would appear (in this case linearly) more often
* than lower ones.
*/
return (int) Math.pow(a, 1.0 / concentration);
}
@Override protected void tearDown() {
double req = requests.get();
double hit = req - misses.get();
// Currently, this is going into /dev/null, but I'll fix that
System.out.println("hit rate: " + hit / req);
}
public static void main(String[] args) {
Runner.main(MapMakerSingleThreadBenchmark.class, args);
}
// for proper distributions later:
// import JSci.maths.statistics.ProbabilityDistribution;
// int key = (int) dist.inverse(random.nextDouble());
}
| Java |
/*
* 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.collect;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.base.Preconditions;
import java.util.Random;
/**
* Tests the speed of iteration of different iteration methods for collections.
*
* @author David Richter
*/
public class MultisetIteratorBenchmark extends SimpleBenchmark {
@Param({"0", "1", "16", "256", "4096", "65536"}) int size;
LinkedHashMultiset<Object> linkedHashMultiset;
HashMultiset<Object> hashMultiset;
// TreeMultiset requires a Comparable element.
TreeMultiset<Integer> treeMultiset;
@Override protected void setUp() {
hashMultiset = HashMultiset.create(size);
linkedHashMultiset = LinkedHashMultiset.create(size);
treeMultiset = TreeMultiset.create();
Random random = new Random();
int sizeRemaining = size;
// TODO(kevinb): generate better test contents for multisets
for (int i = 0; sizeRemaining > 0; i++) {
// The JVM will return interned values for small ints.
Integer value = random.nextInt(1000) + 128;
int count = Math.min(random.nextInt(10) + 1, sizeRemaining);
sizeRemaining -= count;
hashMultiset.add(value, count);
linkedHashMultiset.add(value, count);
treeMultiset.add(value, count);
}
//TODO(kevinb): convert to assert once benchmark tests enable asserts by default
Preconditions.checkState(hashMultiset.size() == size);
}
public int timeHashMultiset(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : hashMultiset) {
sum += value.hashCode();
}
}
return sum;
}
public int timeLinkedHashMultiset(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : linkedHashMultiset) {
sum += value.hashCode();
}
}
return sum;
}
public int timeTreeMultiset(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Object value : treeMultiset) {
sum += value.hashCode();
}
}
return sum;
}
public static void main(String[] args) {
Runner.main(MultisetIteratorBenchmark.class, args);
}
}
| Java |
/*
* 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.collect;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.collect.BenchmarkHelpers.SetImpl;
import com.google.common.collect.CollectionBenchmarkSampleData.Element;
import java.util.Set;
/**
* Test iteration speed at various size for {@link Set} instances.
*
* @author Christopher Swenson
*/
public class SetIterationBenchmark extends SimpleBenchmark {
@Param({ "3", "6", "11", "23", "45", "91", "181", "362", "724", "1448",
"2896", "5793", "11585", "23170", "46341", "92682", "185364", "370728",
"741455", "1482910", "2965821", "5931642"})
private int size;
// "" means no fixed seed
@Param("1234")
private SpecialRandom random;
@Param({"Immutable", "Hash"})
private SetImpl impl;
// the following must be set during setUp
private Set<Element> setToTest;
@Override public void setUp() {
CollectionBenchmarkSampleData sampleData =
new CollectionBenchmarkSampleData(true, random, 0.8, size);
setToTest = impl.create(sampleData.getValuesInSet());
}
public int timeIteration(int reps) {
int x = 0;
for (int i = 0; i < reps; i++) {
for (Element y : setToTest) {
x ^= System.identityHashCode(y);
}
}
return x;
}
public static void main(String[] args) throws Exception {
Runner.main(SetIterationBenchmark.class, args);
}
}
| Java |
/*
* 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.collect;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.collect.Multisets.checkNonnegative;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.primitives.Ints;
import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import javax.annotation.Nullable;
/**
* Benchmarks for {@link ConcurrentHashMultiset}.
*
* @author mike nonemacher
*/
public class ConcurrentHashMultisetBenchmark extends SimpleBenchmark {
@Param({"1", "2", "4", "8"}) int threads;
@Param({"3", "30", "300"}) int size;
@Param MultisetSupplier implSupplier;
private Multiset<Integer> multiset;
private ImmutableList<Integer> keys;
private ExecutorService threadPool;
@Override protected void setUp() throws Exception {
super.setUp();
multiset = implSupplier.get();
ImmutableList.Builder<Integer> builder = ImmutableList.builder();
for (int i = 0; i < size; i++) {
builder.add(i);
}
keys = builder.build();
threadPool =
Executors.newFixedThreadPool(threads, new ThreadFactoryBuilder().setDaemon(true).build());
}
public long timeAdd(final int reps) throws ExecutionException, InterruptedException {
return doMultithreadedLoop(
new Callable<Long>() {
@Override public Long call() {
return runAddSingleThread(reps);
}
});
}
public long timeAddRemove(final int reps) throws ExecutionException, InterruptedException {
return doMultithreadedLoop(
new Callable<Long>() {
@Override public Long call() {
return runAddRemoveSingleThread(reps);
}
});
}
private long doMultithreadedLoop(Callable<Long> task)
throws InterruptedException, ExecutionException {
List<Future<Long>> futures = Lists.newArrayListWithCapacity(threads);
for (int i = 0; i < threads; i++) {
futures.add(threadPool.submit(task));
}
long total = 0;
for (Future<Long> future : futures) {
total += future.get();
}
return total;
}
private long runAddSingleThread(int reps) {
Random random = new Random();
int nKeys = keys.size();
long blah = 0;
for (int i = 0; i < reps; i++) {
Integer key = keys.get(random.nextInt(nKeys));
int delta = random.nextInt(5);
blah += delta;
multiset.add(key, delta);
}
return blah;
}
private long runAddRemoveSingleThread(int reps) {
Random random = new Random();
int nKeys = keys.size();
long blah = 0;
for (int i = 0; i < reps; i++) {
Integer key = keys.get(random.nextInt(nKeys));
// This range is [-5, 4] - slight negative bias so we often hit zero, which brings the
// auto-removal of zeroes into play.
int delta = random.nextInt(10) - 5;
blah += delta;
if (delta >= 0) {
multiset.add(key, delta);
} else {
multiset.remove(key, -delta);
}
}
return blah;
}
public static void main(String[] args) {
Runner.main(ConcurrentHashMultisetBenchmark.class, args);
}
private enum MultisetSupplier {
CONCURRENT_HASH_MULTISET() {
@Override Multiset<Integer> get() {
return ConcurrentHashMultiset.create();
}
},
BOXED_ATOMIC_REPLACE() {
@Override Multiset<Integer> get() {
return OldConcurrentHashMultiset.create();
}
},
SYNCHRONIZED_MULTISET() {
@Override Multiset<Integer> get() {
return Synchronized.multiset(HashMultiset.<Integer>create(), null);
}
},
;
abstract Multiset<Integer> get();
}
/**
* Duplication of the old version of ConcurrentHashMultiset (with some unused stuff removed, like
* serialization code) which used a map with boxed integers for the values.
*/
private static final class OldConcurrentHashMultiset<E> extends AbstractMultiset<E> {
/** The number of occurrences of each element. */
private final transient ConcurrentMap<E, Integer> countMap;
/**
* Creates a new, empty {@code OldConcurrentHashMultiset} using the default
* initial capacity, load factor, and concurrency settings.
*/
public static <E> OldConcurrentHashMultiset<E> create() {
return new OldConcurrentHashMultiset<E>(new ConcurrentHashMap<E, Integer>());
}
@VisibleForTesting OldConcurrentHashMultiset(ConcurrentMap<E, Integer> countMap) {
checkArgument(countMap.isEmpty());
this.countMap = countMap;
}
// Query Operations
/**
* Returns the number of occurrences of {@code element} in this multiset.
*
* @param element the element to look for
* @return the nonnegative number of occurrences of the element
*/
@Override public int count(@Nullable Object element) {
try {
return unbox(countMap.get(element));
} catch (NullPointerException e) {
return 0;
} catch (ClassCastException e) {
return 0;
}
}
/**
* {@inheritDoc}
*
* <p>If the data in the multiset is modified by any other threads during this
* method, it is undefined which (if any) of these modifications will be
* reflected in the result.
*/
@Override public int size() {
long sum = 0L;
for (Integer value : countMap.values()) {
sum += value;
}
return Ints.saturatedCast(sum);
}
/*
* Note: the superclass toArray() methods assume that size() gives a correct
* answer, which ours does not.
*/
@Override public Object[] toArray() {
return snapshot().toArray();
}
@Override public <T> T[] toArray(T[] array) {
return snapshot().toArray(array);
}
/*
* We'd love to use 'new ArrayList(this)' or 'list.addAll(this)', but
* either of these would recurse back to us again!
*/
private List<E> snapshot() {
List<E> list = Lists.newArrayListWithExpectedSize(size());
for (Multiset.Entry<E> entry : entrySet()) {
E element = entry.getElement();
for (int i = entry.getCount(); i > 0; i--) {
list.add(element);
}
}
return list;
}
// Modification Operations
/**
* Adds a number of occurrences of the specified element to this multiset.
*
* @param element the element to add
* @param occurrences the number of occurrences to add
* @return the previous count of the element before the operation; possibly
* zero
* @throws IllegalArgumentException if {@code occurrences} is negative, or if
* the resulting amount would exceed {@link Integer#MAX_VALUE}
*/
@Override public int add(E element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);
while (true) {
int current = count(element);
if (current == 0) {
if (countMap.putIfAbsent(element, occurrences) == null) {
return 0;
}
} else {
checkArgument(occurrences <= Integer.MAX_VALUE - current,
"Overflow adding %s occurrences to a count of %s",
occurrences, current);
int next = current + occurrences;
if (countMap.replace(element, current, next)) {
return current;
}
}
// If we're still here, there was a race, so just try again.
}
}
/**
* Removes a number of occurrences of the specified element from this
* multiset. If the multiset contains fewer than this number of occurrences to
* begin with, all occurrences will be removed.
*
* @param element the element whose occurrences should be removed
* @param occurrences the number of occurrences of the element to remove
* @return the count of the element before the operation; possibly zero
* @throws IllegalArgumentException if {@code occurrences} is negative
*/
@Override public int remove(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return count(element);
}
checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);
while (true) {
int current = count(element);
if (current == 0) {
return 0;
}
if (occurrences >= current) {
if (countMap.remove(element, current)) {
return current;
}
} else {
// We know it's an "E" because it already exists in the map.
@SuppressWarnings("unchecked")
E casted = (E) element;
if (countMap.replace(casted, current, current - occurrences)) {
return current;
}
}
// If we're still here, there was a race, so just try again.
}
}
/**
* Removes <b>all</b> occurrences of the specified element from this multiset.
* This method complements {@link Multiset#remove(Object)}, which removes only
* one occurrence at a time.
*
* @param element the element whose occurrences should all be removed
* @return the number of occurrences successfully removed, possibly zero
*/
private int removeAllOccurrences(@Nullable Object element) {
try {
return unbox(countMap.remove(element));
} catch (NullPointerException e) {
return 0;
} catch (ClassCastException e) {
return 0;
}
}
/**
* Removes exactly the specified number of occurrences of {@code element}, or
* makes no change if this is not possible.
*
* <p>This method, in contrast to {@link #remove(Object, int)}, has no effect
* when the element count is smaller than {@code occurrences}.
*
* @param element the element to remove
* @param occurrences the number of occurrences of {@code element} to remove
* @return {@code true} if the removal was possible (including if {@code
* occurrences} is zero)
*/
public boolean removeExactly(@Nullable Object element, int occurrences) {
if (occurrences == 0) {
return true;
}
checkArgument(occurrences > 0, "Invalid occurrences: %s", occurrences);
while (true) {
int current = count(element);
if (occurrences > current) {
return false;
}
if (occurrences == current) {
if (countMap.remove(element, occurrences)) {
return true;
}
} else {
@SuppressWarnings("unchecked") // it's in the map, must be an "E"
E casted = (E) element;
if (countMap.replace(casted, current, current - occurrences)) {
return true;
}
}
// If we're still here, there was a race, so just try again.
}
}
/**
* Adds or removes occurrences of {@code element} such that the {@link #count}
* of the element becomes {@code count}.
*
* @return the count of {@code element} in the multiset before this call
* @throws IllegalArgumentException if {@code count} is negative
*/
@Override public int setCount(E element, int count) {
checkNonnegative(count, "count");
return (count == 0)
? removeAllOccurrences(element)
: unbox(countMap.put(element, count));
}
/**
* Sets the number of occurrences of {@code element} to {@code newCount}, but
* only if the count is currently {@code oldCount}. If {@code element} does
* not appear in the multiset exactly {@code oldCount} times, no changes will
* be made.
*
* @return {@code true} if the change was successful. This usually indicates
* that the multiset has been modified, but not always: in the case that
* {@code oldCount == newCount}, the method will return {@code true} if
* the condition was met.
* @throws IllegalArgumentException if {@code oldCount} or {@code newCount} is
* negative
*/
@Override public boolean setCount(E element, int oldCount, int newCount) {
checkNonnegative(oldCount, "oldCount");
checkNonnegative(newCount, "newCount");
if (newCount == 0) {
if (oldCount == 0) {
// No change to make, but must return true if the element is not present
return !countMap.containsKey(element);
} else {
return countMap.remove(element, oldCount);
}
}
if (oldCount == 0) {
return countMap.putIfAbsent(element, newCount) == null;
}
return countMap.replace(element, oldCount, newCount);
}
// Views
@Override Set<E> createElementSet() {
final Set<E> delegate = countMap.keySet();
return new ForwardingSet<E>() {
@Override protected Set<E> delegate() {
return delegate;
}
@Override public boolean remove(Object object) {
try {
return delegate.remove(object);
} catch (NullPointerException e) {
return false;
} catch (ClassCastException e) {
return false;
}
}
};
}
private transient EntrySet entrySet;
@Override public Set<Multiset.Entry<E>> entrySet() {
EntrySet result = entrySet;
if (result == null) {
entrySet = result = new EntrySet();
}
return result;
}
@Override int distinctElements() {
return countMap.size();
}
@Override public boolean isEmpty() {
return countMap.isEmpty();
}
@Override Iterator<Entry<E>> entryIterator() {
final Iterator<Map.Entry<E, Integer>> backingIterator =
countMap.entrySet().iterator();
return new Iterator<Entry<E>>() {
@Override public boolean hasNext() {
return backingIterator.hasNext();
}
@Override public Multiset.Entry<E> next() {
Map.Entry<E, Integer> backingEntry = backingIterator.next();
return Multisets.immutableEntry(backingEntry.getKey(),
backingEntry.getValue());
}
@Override public void remove() {
backingIterator.remove();
}
};
}
@Override public void clear() {
countMap.clear();
}
private class EntrySet extends AbstractMultiset<E>.EntrySet {
@Override Multiset<E> multiset() {
return OldConcurrentHashMultiset.this;
}
/*
* Note: the superclass toArray() methods assume that size() gives a correct
* answer, which ours does not.
*/
@Override public Object[] toArray() {
return snapshot().toArray();
}
@Override public <T> T[] toArray(T[] array) {
return snapshot().toArray(array);
}
private List<Multiset.Entry<E>> snapshot() {
List<Multiset.Entry<E>> list = Lists.newArrayListWithExpectedSize(size());
// not Iterables.addAll(list, this), because that'll forward back here
Iterators.addAll(list, iterator());
return list;
}
@Override public boolean remove(Object object) {
if (object instanceof Multiset.Entry) {
Multiset.Entry<?> entry = (Multiset.Entry<?>) object;
Object element = entry.getElement();
int entryCount = entry.getCount();
return countMap.remove(element, entryCount);
}
return false;
}
/**
* The hash code is the same as countMap's, though the objects aren't equal.
*/
@Override public int hashCode() {
return countMap.hashCode();
}
}
/**
* We use a special form of unboxing that treats null as zero.
*/
private static int unbox(@Nullable Integer i) {
return (i == null) ? 0 : i;
}
}
}
| Java |
/*
* 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.collect;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.collect.BenchmarkHelpers.SetImpl;
/**
* This is meant to be used with {@code --measureMemory} to measure the memory
* usage of various {@code Set} implementations.
*
* @author Christopher Swenson
*/
public class SetCreationBenchmark extends SimpleBenchmark {
@Param({ "3", "6", "11", "23", "45", "91", "181", "362", "724", "1448",
"2896", "5793", "11585", "23170", "46341", "92682", "185364", "370728",
"741455", "1482910", "2965821", "5931642"})
private int size;
// "" means no fixed seed
@Param("1234")
private SpecialRandom random;
@Param({"Immutable", "Hash"})
private SetImpl impl;
// the following must be set during setUp
private CollectionBenchmarkSampleData sampleData;
@Override public void setUp() {
sampleData = new CollectionBenchmarkSampleData(true, random, 0.8, size);
}
public int timeCreation(int reps) {
int x = 0;
for (int i = 0; i < reps; i++) {
x ^= System.identityHashCode(impl.create(sampleData.getValuesInSet()));
}
return x;
}
public static void main(String[] args) throws Exception {
Runner.main(SetCreationBenchmark.class, args);
}
}
| Java |
/*
* 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.collect;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.base.Function;
import com.google.common.collect.ForwardingQueue;
import com.google.common.collect.MinMaxPriorityQueue;
import com.google.common.collect.Ordering;
import java.math.BigInteger;
import java.util.Comparator;
import java.util.PriorityQueue;
import java.util.Queue;
import java.util.Random;
/**
* Benchmarks to compare performance of MinMaxPriorityQueue and PriorityQueue.
*
* @author Sverre Sundsdal
*/
public class MinMaxPriorityQueueBenchmark extends SimpleBenchmark {
@Param private ComparatorType comparator;
// TODO(kevinb): add 1000000 back when we have the ability to throw
// NotApplicableException in the expensive comparator case.
@Param({"100", "10000"}) private int size;
@Param private HeapType heap;
private Queue<Integer> queue;
private final Random random = new Random();
@Override public void setUp() {
queue = heap.create(comparator.get());
for (int i = 0; i < size; i++) {
queue.add(random.nextInt());
}
}
public void timePollAndAdd(int reps) {
for (int i = 0; i < reps; i++) {
// TODO(kevinb): precompute random #s?
queue.add(queue.poll() ^ random.nextInt());
}
}
public void timePopulate(int reps) {
for (int i = 0; i < reps; i++) {
queue.clear();
for (int j = 0; j < size; j++) {
// TODO(kevinb): precompute random #s?
queue.add(random.nextInt());
}
}
}
/**
* Implementation of the InvertedMinMaxPriorityQueue which forwards all calls to
* a MinMaxPriorityQueue, except poll, which is forwarded to pollMax. That way
* we can benchmark pollMax using the same code that benchmarks poll.
*/
static final class InvertedMinMaxPriorityQueue <T> extends ForwardingQueue<T> {
MinMaxPriorityQueue<T> mmHeap;
public InvertedMinMaxPriorityQueue(Comparator<T> comparator) {
mmHeap = MinMaxPriorityQueue.orderedBy(comparator).create();
}
@Override
protected Queue<T> delegate() {
return mmHeap;
}
@Override
public T poll() {
return mmHeap.pollLast();
}
}
public enum HeapType {
MIN_MAX {
@Override public Queue<Integer> create(Comparator<Integer> comparator) {
return MinMaxPriorityQueue.orderedBy(comparator).create();
}
},
PRIORITY_QUEUE {
@Override public Queue<Integer> create(Comparator<Integer> comparator) {
return new PriorityQueue<Integer>(11, comparator);
}
},
INVERTED_MIN_MAX {
@Override public Queue<Integer> create(Comparator<Integer> comparator) {
return new InvertedMinMaxPriorityQueue<Integer>(comparator);
}
};
public abstract Queue<Integer> create(Comparator<Integer> comparator);
}
/**
* Does a CPU intensive operation on Integer and returns a BigInteger
* Used to implement an ordering that spends a lot of cpu.
*/
static class ExpensiveComputation implements Function<Integer, BigInteger> {
@Override
public BigInteger apply(Integer from) {
BigInteger v = BigInteger.valueOf(from);
// Math.sin is very slow for values outside 4*pi
// Need to take absolute value to avoid inverting the value.
for (double i = 0; i < 100; i += 20) {
v = v.add(v.multiply(
BigInteger.valueOf(
((Double) Math.abs(Math.sin(i) * 10.0)).longValue())));
}
return v;
}
}
public enum ComparatorType {
CHEAP {
@Override public Comparator<Integer> get() {
return Ordering.natural();
}
},
EXPENSIVE {
@Override public Comparator<Integer> get() {
return Ordering.natural().onResultOf(new ExpensiveComputation());
}
};
public abstract Comparator<Integer> get();
}
public static void main(String [] args) {
Runner.main(MinMaxPriorityQueueBenchmark.class, args);
}
}
| Java |
/*
* 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.collect;
import static com.google.common.collect.DiscreteDomains.integers;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import java.util.Set;
/**
* Very simple powerSet iteration benchmark.
*
* @author Kevin Bourrillion
*/
public class PowerSetBenchmark extends SimpleBenchmark {
@Param({"2", "4", "8", "16"}) int elements;
Set<Set<Integer>> powerSet;
@Override protected void setUp() {
Set<Integer> set = Range.closed(1, elements).asSet(integers());
powerSet = Sets.powerSet(set);
}
public int timeIteration(int reps) {
int sum = 0;
for (int i = 0; i < reps; i++) {
for (Set<Integer> subset : powerSet) {
for (Integer value : subset) {
sum += value;
}
}
}
return sum;
}
public static void main(String[] args) {
Runner.main(PowerSetBenchmark.class, args);
}
}
| Java |
/*
* 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.hash;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
/**
* Benchmarks for comparing {@link MessageDigest}s and {@link HashFunction}s that wrap
* {@link MessageDigest}s.
*
* <p>Parameters for the benchmark are:
* <ul>
* <li>size: The length of the byte array to hash.
* </ul>
*
* @author Kurt Alfred Kluever
*/
public class MessageDigestAlgorithmBenchmark extends SimpleBenchmark {
// Use a constant seed for all of the benchmarks to ensure apples to apples comparisons.
private static final int RANDOM_SEED = new Random().nextInt();
@Param({"10", "1000", "100000", "1000000"})
private int size;
private byte[] testBytes;
@Override public void setUp() {
testBytes = new byte[size];
new Random(RANDOM_SEED).nextBytes(testBytes);
}
// MD5
public byte timeMd5HashFunction(int reps) {
return runHashFunction(reps, Hashing.md5());
}
public byte timeMd5MessageDigest(int reps) throws Exception {
return runMessageDigest(reps, "MD5");
}
// SHA-1
public byte timeSha1HashFunction(int reps) {
return runHashFunction(reps, Hashing.sha1());
}
public byte timeSha1MessageDigest(int reps) throws Exception {
return runMessageDigest(reps, "SHA-1");
}
// SHA-256
public byte timeSha256HashFunction(int reps) {
return runHashFunction(reps, Hashing.sha256());
}
public byte timeSha256MessageDigest(int reps) throws Exception {
return runMessageDigest(reps, "SHA-256");
}
// SHA-512
public byte timeSha512HashFunction(int reps) {
return runHashFunction(reps, Hashing.sha512());
}
public byte timeSha512MessageDigest(int reps) throws Exception {
return runMessageDigest(reps, "SHA-512");
}
// Helpers + main
private byte runHashFunction(int reps, HashFunction hashFunction) {
byte result = 0x01;
// Trick the JVM to prevent it from using the hash function non-polymorphically
result ^= Hashing.sha1().hashInt(reps).asBytes()[0];
result ^= Hashing.md5().hashInt(reps).asBytes()[0];
for (int i = 0; i < reps; i++) {
result ^= hashFunction.hashBytes(testBytes).asBytes()[0];
}
return result;
}
private byte runMessageDigest(int reps, String algorithm) throws NoSuchAlgorithmException {
byte result = 0x01;
for (int i = 0; i < reps; i++) {
MessageDigest md = MessageDigest.getInstance(algorithm);
md.update(testBytes);
result ^= md.digest()[0];
}
return result;
}
public static void main(String[] args) {
Runner.main(MessageDigestAlgorithmBenchmark.class, args);
}
}
| Java |
/*
* 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.hash;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import java.util.Random;
/**
* Benchmarks for comparing the various {@link HashFunction functions} that we provide.
*
* <p>Parameters for the benchmark are:
* <ul>
* <li>size: The length of the byte array to hash.
* </ul>
*
* @author Kurt Alfred Kluever
*/
public class HashFunctionBenchmark extends SimpleBenchmark {
// Use a constant seed for all of the benchmarks to ensure apples to apples comparisons.
private static final int RANDOM_SEED = new Random().nextInt();
@Param({"10", "1000", "100000", "1000000"})
private int size;
private byte[] testBytes;
@Override public void setUp() {
testBytes = new byte[size];
new Random(RANDOM_SEED).nextBytes(testBytes);
}
public int timeMurmur32HashFunction(int reps) {
return runHashFunction(reps, Hashing.murmur3_32());
}
public int timeMurmur128HashFunction(int reps) {
return runHashFunction(reps, Hashing.murmur3_128());
}
public int timeMd5HashFunction(int reps) {
return runHashFunction(reps, Hashing.md5());
}
public int timeSha1HashFunction(int reps) {
return runHashFunction(reps, Hashing.sha1());
}
public int timeSha256HashFunction(int reps) {
return runHashFunction(reps, Hashing.sha256());
}
public int timeSha512HashFunction(int reps) {
return runHashFunction(reps, Hashing.sha512());
}
private int runHashFunction(int reps, HashFunction hashFunction) {
int result = 37;
for (int i = 0; i < reps; i++) {
result ^= hashFunction.hashBytes(testBytes).asInt();
}
return result;
}
public static void main(String[] args) {
Runner.main(HashFunctionBenchmark.class, args);
}
}
| Java |
/*
* 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.hash;
import com.google.caliper.Param;
import com.google.caliper.Runner;
import com.google.caliper.SimpleBenchmark;
import java.util.Random;
/**
* Benchmarks for hashing functions. This class benchmarks various hasing functions for a range of
* sizes of byte array. The input data is generated by a call to {@link Random#nextBytes}.
*
* <p>Parameters for the benchmark are:
* <ul>
* <li>size: The length of the byte array to hash.
* <li>function: The name of the function(s) to test (eg, "goodFastHash32" or "murmur3_32")
* </ul>
*
* @author David Beaumont
*/
public class HashBenchmark extends SimpleBenchmark {
@Param({"10", "1000", "1000000"})
private int size;
@Param private HashType function;
private enum HashType {
goodFastHash32() {
@Override public long hash(byte[] data) {
return Hashing.goodFastHash(32).hashBytes(data).asInt();
}
},
goodFastHash64() {
@Override public long hash(byte[] data) {
return Hashing.goodFastHash(64).hashBytes(data).asLong();
}
},
murmur32() {
@Override public long hash(byte[] data) {
return Hashing.murmur3_32().hashBytes(data).asInt();
}
},
murmur128() {
@Override public long hash(byte[] data) {
return Hashing.murmur3_128().hashBytes(data).asLong();
}
},
md5() {
@Override public long hash(byte[] data) {
return Hashing.md5().hashBytes(data).asLong();
}
};
public abstract long hash(byte[] data);
}
private byte[] testData;
@Override
protected void setUp() {
testData = new byte[size];
new Random().nextBytes(testData);
}
public int timeHashFunction(int reps) {
long dummy = 0;
for (int i = 0; i < reps; i++) {
dummy ^= function.hash(testData);
}
return (int) dummy;
}
public static void main(String[] args) {
Runner.main(HashBenchmark.class, args);
}
}
| Java |
/*
* 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.testing.anotherpackage;
/** Does not check null, but should not matter since it's in a different package. */
@SuppressWarnings("unused") // For use by NullPointerTester
public class SomeClassThatDoesNotUseNullable {
void packagePrivateButDoesNotCheckNull(String s) {}
protected void protectedButDoesNotCheckNull(String s) {}
public void publicButDoesNotCheckNull(String s) {}
public static void staticButDoesNotCheckNull(String s) {}
}
| Java |
/*
* 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.testing;
import com.google.common.annotations.Beta;
import com.google.common.util.concurrent.ListenableFuture;
import junit.framework.TestCase;
import java.util.concurrent.CancellationException;
import java.util.concurrent.CountDownLatch;
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;
/**
* Abstract test case parent for anything implementing {@link ListenableFuture}.
* Tests the two get methods and the addListener method.
*
* @author Sven Mawson
* @since 10.0
*/
@Beta
public abstract class AbstractListenableFutureTest extends TestCase {
protected CountDownLatch latch;
protected ListenableFuture<Boolean> future;
@Override
protected void setUp() throws Exception {
// Create a latch and a future that waits on the latch.
latch = new CountDownLatch(1);
future = createListenableFuture(Boolean.TRUE, null, latch);
}
@Override
protected void tearDown() throws Exception {
// Make sure we have no waiting threads.
latch.countDown();
}
/**
* Constructs a listenable future with a value available after the latch
* has counted down.
*/
protected abstract <V> ListenableFuture<V> createListenableFuture(
V value, Exception except, CountDownLatch waitOn);
/**
* Tests that the {@link Future#get()} method blocks until a value is
* available.
*/
public void testGetBlocksUntilValueAvailable() throws Throwable {
assertFalse(future.isDone());
assertFalse(future.isCancelled());
final CountDownLatch successLatch = new CountDownLatch(1);
final Throwable[] badness = new Throwable[1];
// Wait on the future in a separate thread.
new Thread(new Runnable() {
@Override
public void run() {
try {
assertSame(Boolean.TRUE, future.get());
successLatch.countDown();
} catch (Throwable t) {
t.printStackTrace();
badness[0] = t;
}
}}).start();
// Release the future value.
latch.countDown();
assertTrue(successLatch.await(10, TimeUnit.SECONDS));
if (badness[0] != null) {
throw badness[0];
}
assertTrue(future.isDone());
assertFalse(future.isCancelled());
}
/**
* Tests that the {@link Future#get(long, TimeUnit)} method times out
* correctly.
*/
public void testTimeoutOnGetWorksCorrectly() throws InterruptedException,
ExecutionException {
// The task thread waits for the latch, so we expect a timeout here.
try {
future.get(20, TimeUnit.MILLISECONDS);
fail("Should have timed out trying to get the value.");
} catch (TimeoutException expected) {
// Expected.
} finally {
latch.countDown();
}
}
/**
* Tests that a canceled future throws a cancellation exception.
*
* This method checks the cancel, isCancelled, and isDone methods.
*/
public void testCanceledFutureThrowsCancellation() throws Exception {
assertFalse(future.isDone());
assertFalse(future.isCancelled());
final CountDownLatch successLatch = new CountDownLatch(1);
// Run cancellation in a separate thread as an extra thread-safety test.
new Thread(new Runnable() {
@Override
public void run() {
try {
future.get();
} catch (CancellationException expected) {
successLatch.countDown();
} catch (Exception ignored) {
// All other errors are ignored, we expect a cancellation.
}
}
}).start();
assertFalse(future.isDone());
assertFalse(future.isCancelled());
future.cancel(true);
assertTrue(future.isDone());
assertTrue(future.isCancelled());
assertTrue(successLatch.await(200, TimeUnit.MILLISECONDS));
latch.countDown();
}
public void testListenersNotifiedOnError() throws Exception {
final CountDownLatch successLatch = new CountDownLatch(1);
final CountDownLatch listenerLatch = new CountDownLatch(1);
ExecutorService exec = Executors.newCachedThreadPool();
future.addListener(new Runnable() {
@Override
public void run() {
listenerLatch.countDown();
}
}, exec);
new Thread(new Runnable() {
@Override
public void run() {
try {
future.get();
} catch (CancellationException expected) {
successLatch.countDown();
} catch (Exception ignored) {
// No success latch count down.
}
}
}).start();
future.cancel(true);
assertTrue(future.isCancelled());
assertTrue(future.isDone());
assertTrue(successLatch.await(200, TimeUnit.MILLISECONDS));
assertTrue(listenerLatch.await(200, TimeUnit.MILLISECONDS));
latch.countDown();
exec.shutdown();
exec.awaitTermination(100, TimeUnit.MILLISECONDS);
}
/**
* Tests that all listeners complete, even if they were added before or after
* the future was finishing. Also acts as a concurrency test to make sure the
* locking is done correctly when a future is finishing so that no listeners
* can be lost.
*/
public void testAllListenersCompleteSuccessfully()
throws InterruptedException, ExecutionException {
ExecutorService exec = Executors.newCachedThreadPool();
int listenerCount = 20;
final CountDownLatch listenerLatch = new CountDownLatch(listenerCount);
// Test that listeners added both before and after the value is available
// get called correctly.
for (int i = 0; i < 20; i++) {
// Right in the middle start up a thread to close the latch.
if (i == 10) {
new Thread(new Runnable() {
@Override
public void run() {
latch.countDown();
}
}).start();
}
future.addListener(new Runnable() {
@Override
public void run() {
listenerLatch.countDown();
}
}, exec);
}
assertSame(Boolean.TRUE, future.get());
// Wait for the listener latch to complete.
listenerLatch.await(500, TimeUnit.MILLISECONDS);
exec.shutdown();
exec.awaitTermination(500, TimeUnit.MILLISECONDS);
}
}
| Java |
/*
* 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.testing;
import com.google.common.annotations.Beta;
import com.google.common.util.concurrent.CheckedFuture;
import com.google.common.util.concurrent.ListenableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
/**
* Test case to make sure the {@link CheckedFuture#checkedGet()} and
* {@link CheckedFuture#checkedGet(long, TimeUnit)} methods work correctly.
*
* @author Sven Mawson
* @since 10.0
*/
@Beta
public abstract class AbstractCheckedFutureTest
extends AbstractListenableFutureTest {
/**
* More specific type for the create method.
*/
protected abstract <V> CheckedFuture<V, ?> createCheckedFuture(V value,
Exception except, CountDownLatch waitOn);
/**
* Checks that the exception is the correct type of cancellation exception.
*/
protected abstract void checkCancelledException(Exception e);
/**
* Checks that the exception is the correct type of execution exception.
*/
protected abstract void checkExecutionException(Exception e);
/**
* Checks that the exception is the correct type of interruption exception.
*/
protected abstract void checkInterruptedException(Exception e);
@Override
protected <V> ListenableFuture<V> createListenableFuture(V value,
Exception except, CountDownLatch waitOn) {
return createCheckedFuture(value, except, waitOn);
}
/**
* Tests that the {@link CheckedFuture#checkedGet()} method throws the correct
* type of cancellation exception when it is cancelled.
*/
public void testCheckedGetThrowsApplicationExceptionOnCancellation() {
final CheckedFuture<Boolean, ?> future =
createCheckedFuture(Boolean.TRUE, null, latch);
assertFalse(future.isDone());
assertFalse(future.isCancelled());
new Thread(new Runnable() {
@Override
public void run() {
future.cancel(true);
}
}).start();
try {
future.checkedGet();
fail("RPC Should have been cancelled.");
} catch (Exception e) {
checkCancelledException(e);
}
assertTrue(future.isDone());
assertTrue(future.isCancelled());
}
public void testCheckedGetThrowsApplicationExceptionOnInterruption()
throws InterruptedException {
final CheckedFuture<Boolean, ?> future =
createCheckedFuture(Boolean.TRUE, null, latch);
final CountDownLatch startingGate = new CountDownLatch(1);
final CountDownLatch successLatch = new CountDownLatch(1);
assertFalse(future.isDone());
assertFalse(future.isCancelled());
Thread getThread = new Thread(new Runnable() {
@Override
public void run() {
startingGate.countDown();
try {
future.checkedGet();
} catch (Exception e) {
checkInterruptedException(e);
// This only gets hit if the original call throws an exception and
// the check call above passes.
successLatch.countDown();
}
}
});
getThread.start();
assertTrue(startingGate.await(500, TimeUnit.MILLISECONDS));
getThread.interrupt();
assertTrue(successLatch.await(500, TimeUnit.MILLISECONDS));
assertFalse(future.isDone());
assertFalse(future.isCancelled());
}
public void testCheckedGetThrowsApplicationExceptionOnError() {
final CheckedFuture<Boolean, ?> future =
createCheckedFuture(Boolean.TRUE, new Exception("Error"), latch);
assertFalse(future.isDone());
assertFalse(future.isCancelled());
new Thread(new Runnable() {
@Override
public void run() {
latch.countDown();
}
}).start();
try {
future.checkedGet();
fail();
} catch (Exception e) {
checkExecutionException(e);
}
assertTrue(future.isDone());
assertFalse(future.isCancelled());
}
}
| Java |
/*
* 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.util.concurrent.testing;
import com.google.common.annotations.Beta;
import com.google.common.util.concurrent.ListenableFuture;
import com.google.common.util.concurrent.MoreExecutors;
import junit.framework.Assert;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
/**
* A simple mock implementation of {@code Runnable} that can be used for
* testing ListenableFutures.
*
* @author Nishant Thakkar
* @since 10.0
*/
@Beta
public class MockFutureListener implements Runnable {
private final CountDownLatch countDownLatch;
private final ListenableFuture<?> future;
public MockFutureListener(ListenableFuture<?> future) {
this.countDownLatch = new CountDownLatch(1);
this.future = future;
future.addListener(this, MoreExecutors.sameThreadExecutor());
}
@Override
public void run() {
countDownLatch.countDown();
}
/**
* Verify that the listener completes in a reasonable amount of time, and
* Asserts that the future returns the expected data.
* @throws Throwable if the listener isn't called or if it resulted in a
* throwable or if the result doesn't match the expected value.
*/
public void assertSuccess(Object expectedData) throws Throwable {
// Verify that the listener executed in a reasonable amount of time.
Assert.assertTrue(countDownLatch.await(1L, TimeUnit.SECONDS));
try {
Assert.assertEquals(expectedData, future.get());
} catch (ExecutionException e) {
throw e.getCause();
}
}
/**
* Verify that the listener completes in a reasonable amount of time, and
* Asserts that the future throws an {@code ExecutableException} and that the
* cause of the {@code ExecutableException} is {@code expectedCause}.
*/
public void assertException(Throwable expectedCause) throws Exception {
// Verify that the listener executed in a reasonable amount of time.
Assert.assertTrue(countDownLatch.await(1L, TimeUnit.SECONDS));
try {
future.get();
Assert.fail("This call was supposed to throw an ExecutionException");
} catch (ExecutionException expected) {
Assert.assertSame(expectedCause, expected.getCause());
}
}
public void assertTimeout() throws Exception {
// Verify that the listener does not get called in a reasonable amount of
// time.
Assert.assertFalse(countDownLatch.await(1L, TimeUnit.SECONDS));
}
}
| Java |
/*
* 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.testing;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Simple utility for when you want to create a {@link TearDown} that may throw
* an exception but should not fail a test when it does. (The behavior of a
* {@code TearDown} that throws an exception varies; see its documentation for
* details.) Use it just like a {@code TearDown}, except override {@link
* #sloppyTearDown()} instead.
*
* @author Luiz-Otavio Zorzella
* @since 10.0
*/
@Beta
@GwtCompatible
public abstract class SloppyTearDown implements TearDown {
public static final Logger logger =
Logger.getLogger(SloppyTearDown.class.getName());
@Override
public final void tearDown() {
try {
sloppyTearDown();
} catch (Throwable t) {
logger.log(Level.INFO,
"exception thrown during tearDown: " + t.getMessage(), t);
}
}
public abstract void sloppyTearDown() throws Exception;
}
| Java |
/*
* 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.testing;
import static com.google.common.base.Preconditions.checkArgument;
import static com.google.common.base.Preconditions.checkNotNull;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.fail;
import com.google.common.annotations.Beta;
import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.Lists;
import com.google.common.reflect.AbstractInvocationHandler;
import com.google.common.reflect.Reflection;
import java.lang.reflect.AccessibleObject;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;
/**
* Tester to ensure forwarding wrapper works by delegating calls to the corresponding method
* with the same parameters forwarded and return value forwarded back or exception propagated as is.
*
* <p>For example: <pre> {@code
* new ForwardingWrapperTester().testForwarding(Foo.class, new Function<Foo, Foo>() {
* public Foo apply(Foo foo) {
* return ForwardingFoo(foo);
* }
* });}</pre>
*
* @author Ben Yu
* @since 14.0
*/
@Beta
public final class ForwardingWrapperTester {
private boolean testsEquals = false;
/**
* Asks for {@link Object#equals} and {@link Object#hashCode} to be tested.
* That is, forwarding wrappers of equal instances should be equal.
*/
public ForwardingWrapperTester includingEquals() {
this.testsEquals = true;
return this;
}
/**
* Tests that the forwarding wrapper returned by {@code wrapperFunction} properly forwards
* method calls with parameters passed as is, return value returned as is, and exceptions
* propagated as is.
*/
public <T> void testForwarding(
Class<T> interfaceType, Function<? super T, ? extends T> wrapperFunction) {
checkNotNull(wrapperFunction);
checkArgument(interfaceType.isInterface(), "%s isn't an interface", interfaceType);
Method[] methods = getMostConcreteMethods(interfaceType);
AccessibleObject.setAccessible(methods, true);
for (Method method : methods) {
// The interface could be package-private or private.
// filter out equals/hashCode/toString
if (method.getName().equals("equals")
&& method.getParameterTypes().length == 1
&& method.getParameterTypes()[0] == Object.class) {
continue;
}
if (method.getName().equals("hashCode")
&& method.getParameterTypes().length == 0) {
continue;
}
if (method.getName().equals("toString")
&& method.getParameterTypes().length == 0) {
continue;
}
testSuccessfulForwarding(interfaceType, method, wrapperFunction);
testExceptionPropagation(interfaceType, method, wrapperFunction);
}
if (testsEquals) {
testEquals(interfaceType, wrapperFunction);
}
testToString(interfaceType, wrapperFunction);
}
/** Returns the most concrete public methods from {@code type}. */
private static Method[] getMostConcreteMethods(Class<?> type) {
Method[] methods = type.getMethods();
for (int i = 0; i < methods.length; i++) {
try {
methods[i] = type.getMethod(methods[i].getName(), methods[i].getParameterTypes());
} catch (Exception e) {
throw Throwables.propagate(e);
}
}
return methods;
}
private static <T> void testSuccessfulForwarding(
Class<T> interfaceType, Method method, Function<? super T, ? extends T> wrapperFunction) {
new InteractionTester<T>(interfaceType, method).testInteraction(wrapperFunction);
}
private static <T> void testExceptionPropagation(
Class<T> interfaceType, Method method, Function<? super T, ? extends T> wrapperFunction) {
final RuntimeException exception = new RuntimeException();
T proxy = Reflection.newProxy(interfaceType, new AbstractInvocationHandler() {
@Override protected Object handleInvocation(Object p, Method m, Object[] args)
throws Throwable {
throw exception;
}
});
T wrapper = wrapperFunction.apply(proxy);
try {
method.invoke(wrapper, getParameterValues(method));
fail(method + " failed to throw exception as is.");
} catch (InvocationTargetException e) {
if (exception != e.getCause()) {
throw new RuntimeException(e);
}
} catch (IllegalAccessException e) {
throw new AssertionError(e);
}
}
private static <T> void testEquals(
Class<T> interfaceType, Function<? super T, ? extends T> wrapperFunction) {
FreshValueGenerator generator = new FreshValueGenerator();
T instance = generator.newProxy(interfaceType);
new EqualsTester()
.addEqualityGroup(wrapperFunction.apply(instance), wrapperFunction.apply(instance))
.addEqualityGroup(wrapperFunction.apply(generator.newProxy(interfaceType)))
// TODO: add an overload to EqualsTester to print custom error message?
.testEquals();
}
private static <T> void testToString(
Class<T> interfaceType, Function<? super T, ? extends T> wrapperFunction) {
T proxy = new FreshValueGenerator().newProxy(interfaceType);
assertEquals("toString() isn't properly forwarded",
proxy.toString(), wrapperFunction.apply(proxy).toString());
}
private static Object[] getParameterValues(Method method) {
FreshValueGenerator paramValues = new FreshValueGenerator();
final List<Object> passedArgs = Lists.newArrayList();
for (Class<?> paramType : method.getParameterTypes()) {
passedArgs.add(paramValues.generate(paramType));
}
return passedArgs.toArray();
}
/** Tests a single interaction against a method. */
private static final class InteractionTester<T> extends AbstractInvocationHandler {
private final Class<T> interfaceType;
private final Method method;
private final Object[] passedArgs;
private final Object returnValue;
private final AtomicInteger called = new AtomicInteger();
InteractionTester(Class<T> interfaceType, Method method) {
this.interfaceType = interfaceType;
this.method = method;
this.passedArgs = getParameterValues(method);
this.returnValue = new FreshValueGenerator().generate(method.getReturnType());
}
@Override protected Object handleInvocation(Object p, Method calledMethod, Object[] args)
throws Throwable {
assertEquals(method, calledMethod);
assertEquals(method + " invoked more than once.", 0, called.get());
for (int i = 0; i < passedArgs.length; i++) {
assertEquals("Parameter #" + i + " of " + method + " not forwarded",
passedArgs[i], args[i]);
}
called.getAndIncrement();
return returnValue;
}
void testInteraction(Function<? super T, ? extends T> wrapperFunction) {
T proxy = Reflection.newProxy(interfaceType, this);
T wrapper = wrapperFunction.apply(proxy);
try {
assertEquals("Return value of " + method + " not forwarded", returnValue,
method.invoke(wrapper, passedArgs));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw Throwables.propagate(e.getCause());
}
assertEquals("Failed to forward to " + method, 1, called.get());
}
@Override public String toString() {
return "dummy " + interfaceType.getSimpleName();
}
}
}
| Java |
/*
* 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.testing;
import static com.google.common.base.Preconditions.checkArgument;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Ticker;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicLong;
/**
* A Ticker whose value can be advanced programmatically in test.
* <p>
* The ticker can be configured so that the time is incremented whenever {@link #read} is called:
* see {@link #setAutoIncrementStep}.
* <p>
* This class is thread-safe.
*
* @author Jige Yu
* @since 10.0
*/
@Beta
@GwtCompatible
public class FakeTicker extends Ticker {
private final AtomicLong nanos = new AtomicLong();
private volatile long autoIncrementStepNanos;
/** Advances the ticker value by {@code time} in {@code timeUnit}. */
public FakeTicker advance(long time, TimeUnit timeUnit) {
return advance(timeUnit.toNanos(time));
}
/** Advances the ticker value by {@code nanoseconds}. */
public FakeTicker advance(long nanoseconds) {
nanos.addAndGet(nanoseconds);
return this;
}
/**
* Sets the increment applied to the ticker whenever it is queried.
*
* <p>The default behavior is to auto increment by zero. i.e: The ticker is left unchanged when
* queried.
*/
public FakeTicker setAutoIncrementStep(long autoIncrementStep, TimeUnit timeUnit) {
checkArgument(autoIncrementStep >= 0, "May not auto-increment by a negative amount");
this.autoIncrementStepNanos = timeUnit.toNanos(autoIncrementStep);
return this;
}
@Override public long read() {
return nanos.getAndAdd(autoIncrementStepNanos);
}
}
| Java |
/*
* 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.testing;
import static com.google.common.base.Preconditions.checkNotNull;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertTrue;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
import com.google.common.base.Equivalence;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import com.google.common.testing.RelationshipTester.RelationshipAssertion;
import java.util.List;
/**
* Tester for {@link Equivalence} relationships between groups of objects.
*
* <p>
* To use, create a new {@link EquivalenceTester} and add equivalence groups
* where each group contains objects that are supposed to be equal to each
* other. Objects of different groups are expected to be unequal. For example:
*
* <pre>
* {@code
* EquivalenceTester.of(someStringEquivalence)
* .addEquivalenceGroup("hello", "h" + "ello")
* .addEquivalenceGroup("world", "wor" + "ld")
* .test();
* }
* </pre>
*
* <p>
* Note that testing {@link Object#equals(Object)} is more simply done using
* the {@link EqualsTester}. It includes an extra test against an instance of an
* arbitrary class without having to explicitly add another equivalence group.
*
* @author Gregory Kick
* @since 10.0
*
* TODO(gak): turn this into a test suite so that each test can fail
* independently
*/
@Beta
@GwtCompatible public final class EquivalenceTester<T> {
private static final int REPETITIONS = 3;
private final Equivalence<? super T> equivalence;
private final RelationshipTester<T> delegate;
private final List<T> items = Lists.newArrayList();
EquivalenceTester(final Equivalence<? super T> equivalence) {
this.equivalence = checkNotNull(equivalence);
this.delegate = new RelationshipTester<T>(new RelationshipAssertion<T>() {
@Override public void assertRelated(T item, T related) {
assertTrue("$ITEM must be equivalent to $RELATED", equivalence.equivalent(item, related));
int itemHash = equivalence.hash(item);
int relatedHash = equivalence.hash(related);
assertEquals("the hash (" + itemHash + ") of $ITEM must be equal to the hash ("
+ relatedHash + ") of $RELATED", itemHash, relatedHash);
}
@Override public void assertUnrelated(T item, T unrelated) {
assertTrue("$ITEM must be inequivalent to $UNRELATED",
!equivalence.equivalent(item, unrelated));
}
});
}
public static <T> EquivalenceTester<T> of(Equivalence<? super T> equivalence) {
return new EquivalenceTester<T>(equivalence);
}
/**
* Adds a group of objects that are supposed to be equivalent to each other
* and not equivalent to objects in any other equivalence group added to this
* tester.
*/
public EquivalenceTester<T> addEquivalenceGroup(T first, T... rest) {
addEquivalenceGroup(Lists.asList(first, rest));
return this;
}
public EquivalenceTester<T> addEquivalenceGroup(Iterable<T> group) {
delegate.addRelatedGroup(group);
items.addAll(ImmutableList.copyOf(group));
return this;
}
/** Run tests on equivalence methods, throwing a failure on an invalid test */
public EquivalenceTester<T> test() {
for (int run = 0; run < REPETITIONS; run++) {
testItems();
delegate.test();
}
return this;
}
private void testItems() {
for (T item : items) {
assertTrue(item + " must be inequivalent to null", !equivalence.equivalent(item, null));
assertTrue("null must be inequivalent to " + item, !equivalence.equivalent(null, item));
assertTrue(item + " must be equivalent to itself", equivalence.equivalent(item, item));
assertEquals("the hash of " + item + " must be consistent", equivalence.hash(item),
equivalence.hash(item));
}
}
}
| Java |
/*
* 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.testing;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.reflect.AbstractInvocationHandler;
import com.google.common.reflect.Invokable;
import com.google.common.reflect.Parameter;
import com.google.common.reflect.TypeToken;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.Set;
import javax.annotation.Nullable;
/**
* Generates a dummy interface proxy that simply returns a dummy value for each method.
*
* @author Ben Yu
*/
abstract class DummyProxy {
final <T> T newProxy(final TypeToken<T> interfaceType) {
Set<Class<? super T>> interfaceClasses = interfaceType.getTypes().interfaces().rawTypes();
Object dummy = Proxy.newProxyInstance(
interfaceClasses.iterator().next().getClassLoader(),
interfaceClasses.toArray(new Class<?>[interfaceClasses.size()]),
new AbstractInvocationHandler() {
@Override protected Object handleInvocation(
Object proxy, Method method, Object[] args) {
Invokable<?, ?> invokable = interfaceType.method(method);
ImmutableList<Parameter> params = invokable.getParameters();
for (int i = 0; i < args.length; i++) {
Parameter param = params.get(i);
if (!param.isAnnotationPresent(Nullable.class)) {
Preconditions.checkNotNull(args[i]);
}
}
return dummyReturnValue(interfaceType.resolveType(method.getGenericReturnType()));
}
@Override public String toString() {
return "Dummy proxy for " + interfaceType;
}
});
@SuppressWarnings("unchecked") // interfaceType is T
T result = (T) dummy;
return result;
}
/** Returns the dummy return value for {@code returnType}. */
abstract <R> R dummyReturnValue(TypeToken<R> returnType);
}
| Java |
/*
* 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.testing;
import com.google.common.annotations.Beta;
import com.google.common.annotations.GwtCompatible;
/**
* An object that can perform a {@link #tearDown} operation.
*
* @author Kevin Bourrillion
* @since 10.0
*/
@Beta
@GwtCompatible
public interface TearDown {
/**
* Performs a <b>single</b> tear-down operation. See test-libraries-for-java's
* {@code com.google.common.testing.junit3.TearDownTestCase} and
* {@code com.google.common.testing.junit4.TearDownTestCase} for example.
*
* <p>A failing {@link TearDown} may or may not fail a tl4j test, depending on
* the version of JUnit test case you are running under. To avoid failing in
* the face of an exception regardless of JUnit version, implement a {@link
* SloppyTearDown} instead.
*
* <p>tl4j details: For backwards compatibility, {@code
* junit3.TearDownTestCase} currently does not fail a test when an exception
* is thrown from one of its {@link TearDown}s, but this is subject to
* change. Also, {@code junit4.TearDownTestCase} will.
*
* @throws Exception for any reason. {@code TearDownTestCase} ensures that
* any exception thrown will not interfere with other TearDown
* operations.
*/
void tearDown() throws Exception;
}
| Java |
/*
* 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.testing;
import com.google.common.annotations.Beta;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
import javax.annotation.Nullable;
/**
* Tests may use this to intercept messages that are logged by the code under
* test. Example:
* <pre>
* TestLogHandler handler;
*
* protected void setUp() throws Exception {
* super.setUp();
* handler = new TestLogHandler();
* SomeClass.logger.addHandler(handler);
* addTearDown(new TearDown() {
* public void tearDown() throws Exception {
* SomeClass.logger.removeHandler(handler);
* }
* });
* }
*
* public void test() {
* SomeClass.foo();
* LogRecord firstRecord = handler.getStoredLogRecords().get(0);
* assertEquals("some message", firstRecord.getMessage());
* }
* </pre>
*
* @author Kevin Bourrillion
* @since 10.0
*/
@Beta
public class TestLogHandler extends Handler {
/** We will keep a private list of all logged records */
private final List<LogRecord> list =
Collections.synchronizedList(new ArrayList<LogRecord>());
/**
* Adds the most recently logged record to our list.
*/
@Override
public void publish(@Nullable LogRecord record) {
list.add(record);
}
@Override
public void flush() {}
@Override
public void close() {}
public void clear() {
list.clear();
}
/**
* Fetch the list of logged records
* @return unmodifiable LogRecord list of all logged records
*/
public List<LogRecord> getStoredLogRecords() {
List<LogRecord> result = new ArrayList<LogRecord>(list);
return Collections.unmodifiableList(result);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.