file_id
int64
1
180k
content
stringlengths
13
357k
repo
stringlengths
6
109
path
stringlengths
6
1.15k
303
// Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words. You may assume the dictionary does not contain duplicate words. // For example, given // s = "leetcode", // dict = ["leet", "code"]. // Return true because "leetcode" can be segmented as "leet code". public class WordBreak { public boolean wordBreak(String s, Set<String> wordDict) { boolean[] dp = new boolean[s.length() + 1]; dp[0] = true; for(int i = 1; i <= s.length(); i++) { for(int j = 0; j < i; j++) { if(dp[j] && wordDict.contains(s.substring(j, i))) { dp[i] = true; break; } } } return dp[s.length()]; } }
kdn251/interviews
company/uber/WordBreak.java
304
package com.thealgorithms.maths; // POWER (exponentials) Examples (a^b) public final class Pow { private Pow() { } public static void main(String[] args) { assert pow(2, 0) == Math.pow(2, 0); // == 1 assert pow(0, 2) == Math.pow(0, 2); // == 0 assert pow(2, 10) == Math.pow(2, 10); // == 1024 assert pow(10, 2) == Math.pow(10, 2); // == 100 } /** * Returns the value of the first argument raised to the power of the second * argument * * @param a the base. * @param b the exponent. * @return the value {@code a}<sup>{@code b}</sup>. */ public static long pow(int a, int b) { long result = 1; for (int i = 1; i <= b; i++) { result *= a; } return result; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/Pow.java
305
class Solution { public boolean wordPattern(String pattern, String str) { HashMap<Character, String> map = new HashMap<>(); HashSet<String> set = new HashSet<>(); String[] array = str.split(" "); if (pattern.length() != array.length) { return false; } for (int i = 0; i < pattern.length(); i++) { char key = pattern.charAt(i); if (!map.containsKey(key)) { if (set.contains(array[i])) { return false; } map.put(key, array[i]); set.add(array[i]); } else { if (!map.get(key).equals(array[i])) { return false; } } } return true; } }
MisterBooo/LeetCodeAnimation
0290-Word-Pattern/Code/1.java
306
/* * Copyright (C) 2013 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.Iterables.getOnlyElement; import static java.nio.file.LinkOption.NOFOLLOW_LINKS; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.graph.Traverser; import com.google.j2objc.annotations.J2ObjCIncompatible; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.Channels; import java.nio.channels.SeekableByteChannel; import java.nio.charset.Charset; import java.nio.file.DirectoryIteratorException; import java.nio.file.DirectoryStream; import java.nio.file.FileAlreadyExistsException; import java.nio.file.FileSystemException; import java.nio.file.Files; import java.nio.file.LinkOption; import java.nio.file.NoSuchFileException; import java.nio.file.NotDirectoryException; import java.nio.file.OpenOption; import java.nio.file.Path; import java.nio.file.SecureDirectoryStream; import java.nio.file.StandardOpenOption; import java.nio.file.attribute.BasicFileAttributeView; import java.nio.file.attribute.BasicFileAttributes; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.FileTime; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.stream.Stream; import javax.annotation.CheckForNull; /** * Static utilities for use with {@link Path} instances, intended to complement {@link Files}. * * <p>Many methods provided by Guava's {@code Files} class for {@link java.io.File} instances are * now available via the JDK's {@link java.nio.file.Files} class for {@code Path} - check the JDK's * class if a sibling method from {@code Files} appears to be missing from this class. * * @since 21.0 * @author Colin Decker */ @J2ktIncompatible @GwtIncompatible @J2ObjCIncompatible // java.nio.file @ElementTypesAreNonnullByDefault public final class MoreFiles { private MoreFiles() {} /** * Returns a view of the given {@code path} as a {@link ByteSource}. * * <p>Any {@linkplain OpenOption open options} provided are used when opening streams to the file * and may affect the behavior of the returned source and the streams it provides. See {@link * StandardOpenOption} for the standard options that may be provided. Providing no options is * equivalent to providing the {@link StandardOpenOption#READ READ} option. */ public static ByteSource asByteSource(Path path, OpenOption... options) { return new PathByteSource(path, options); } private static final class PathByteSource extends ByteSource { private static final LinkOption[] FOLLOW_LINKS = {}; private final Path path; private final OpenOption[] options; private final boolean followLinks; private PathByteSource(Path path, OpenOption... options) { this.path = checkNotNull(path); this.options = options.clone(); this.followLinks = followLinks(this.options); // TODO(cgdecker): validate the provided options... for example, just WRITE seems wrong } private static boolean followLinks(OpenOption[] options) { for (OpenOption option : options) { if (option == NOFOLLOW_LINKS) { return false; } } return true; } @Override public InputStream openStream() throws IOException { return Files.newInputStream(path, options); } private BasicFileAttributes readAttributes() throws IOException { return Files.readAttributes( path, BasicFileAttributes.class, followLinks ? FOLLOW_LINKS : new LinkOption[] {NOFOLLOW_LINKS}); } @Override public Optional<Long> sizeIfKnown() { BasicFileAttributes attrs; try { attrs = readAttributes(); } catch (IOException e) { // Failed to get attributes; we don't know the size. return Optional.absent(); } // Don't return a size for directories or symbolic links; their sizes are implementation // specific and they can't be read as bytes using the read methods anyway. if (attrs.isDirectory() || attrs.isSymbolicLink()) { return Optional.absent(); } return Optional.of(attrs.size()); } @Override public long size() throws IOException { BasicFileAttributes attrs = readAttributes(); // Don't return a size for directories or symbolic links; their sizes are implementation // specific and they can't be read as bytes using the read methods anyway. if (attrs.isDirectory()) { throw new IOException("can't read: is a directory"); } else if (attrs.isSymbolicLink()) { throw new IOException("can't read: is a symbolic link"); } return attrs.size(); } @Override public byte[] read() throws IOException { try (SeekableByteChannel channel = Files.newByteChannel(path, options)) { return ByteStreams.toByteArray(Channels.newInputStream(channel), channel.size()); } } @Override public CharSource asCharSource(Charset charset) { if (options.length == 0) { // If no OpenOptions were passed, delegate to Files.lines, which could have performance // advantages. (If OpenOptions were passed we can't, because Files.lines doesn't have an // overload taking OpenOptions, meaning we can't guarantee the same behavior w.r.t. things // like following/not following symlinks.) return new AsCharSource(charset) { @SuppressWarnings("FilesLinesLeak") // the user needs to close it in this case @Override public Stream<String> lines() throws IOException { return Files.lines(path, charset); } }; } return super.asCharSource(charset); } @Override public String toString() { return "MoreFiles.asByteSource(" + path + ", " + Arrays.toString(options) + ")"; } } /** * Returns a view of the given {@code path} as a {@link ByteSink}. * * <p>Any {@linkplain OpenOption open options} provided are used when opening streams to the file * and may affect the behavior of the returned sink and the streams it provides. See {@link * StandardOpenOption} for the standard options that may be provided. Providing no options is * equivalent to providing the {@link StandardOpenOption#CREATE CREATE}, {@link * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} and {@link StandardOpenOption#WRITE * WRITE} options. */ public static ByteSink asByteSink(Path path, OpenOption... options) { return new PathByteSink(path, options); } private static final class PathByteSink extends ByteSink { private final Path path; private final OpenOption[] options; private PathByteSink(Path path, OpenOption... options) { this.path = checkNotNull(path); this.options = options.clone(); // TODO(cgdecker): validate the provided options... for example, just READ seems wrong } @Override public OutputStream openStream() throws IOException { return Files.newOutputStream(path, options); } @Override public String toString() { return "MoreFiles.asByteSink(" + path + ", " + Arrays.toString(options) + ")"; } } /** * Returns a view of the given {@code path} as a {@link CharSource} using the given {@code * charset}. * * <p>Any {@linkplain OpenOption open options} provided are used when opening streams to the file * and may affect the behavior of the returned source and the streams it provides. See {@link * StandardOpenOption} for the standard options that may be provided. Providing no options is * equivalent to providing the {@link StandardOpenOption#READ READ} option. */ public static CharSource asCharSource(Path path, Charset charset, OpenOption... options) { return asByteSource(path, options).asCharSource(charset); } /** * Returns a view of the given {@code path} as a {@link CharSink} using the given {@code charset}. * * <p>Any {@linkplain OpenOption open options} provided are used when opening streams to the file * and may affect the behavior of the returned sink and the streams it provides. See {@link * StandardOpenOption} for the standard options that may be provided. Providing no options is * equivalent to providing the {@link StandardOpenOption#CREATE CREATE}, {@link * StandardOpenOption#TRUNCATE_EXISTING TRUNCATE_EXISTING} and {@link StandardOpenOption#WRITE * WRITE} options. */ public static CharSink asCharSink(Path path, Charset charset, OpenOption... options) { return asByteSink(path, options).asCharSink(charset); } /** * Returns an immutable list of paths to the files contained in the given directory. * * @throws NoSuchFileException if the file does not exist <i>(optional specific exception)</i> * @throws NotDirectoryException if the file could not be opened because it is not a directory * <i>(optional specific exception)</i> * @throws IOException if an I/O error occurs */ public static ImmutableList<Path> listFiles(Path dir) throws IOException { try (DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) { return ImmutableList.copyOf(stream); } catch (DirectoryIteratorException e) { throw e.getCause(); } } /** * Returns a {@link Traverser} instance for the file and directory tree. The returned traverser * starts from a {@link Path} and will return all files and directories it encounters. * * <p>The returned traverser attempts to avoid following symbolic links to directories. However, * the traverser cannot guarantee that it will not follow symbolic links to directories as it is * possible for a directory to be replaced with a symbolic link between checking if the file is a * directory and actually reading the contents of that directory. * * <p>If the {@link Path} passed to one of the traversal methods does not exist or is not a * directory, no exception will be thrown and the returned {@link Iterable} will contain a single * element: that path. * * <p>{@link DirectoryIteratorException} may be thrown when iterating {@link Iterable} instances * created by this traverser if an {@link IOException} is thrown by a call to {@link * #listFiles(Path)}. * * <p>Example: {@code MoreFiles.fileTraverser().depthFirstPreOrder(Paths.get("/"))} may return the * following paths: {@code ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home", "/home/alice", * ...]} * * @since 23.5 */ public static Traverser<Path> fileTraverser() { return Traverser.forTree(MoreFiles::fileTreeChildren); } private static Iterable<Path> fileTreeChildren(Path dir) { if (Files.isDirectory(dir, NOFOLLOW_LINKS)) { try { return listFiles(dir); } catch (IOException e) { // the exception thrown when iterating a DirectoryStream if an I/O exception occurs throw new DirectoryIteratorException(e); } } return ImmutableList.of(); } /** * Returns a predicate that returns the result of {@link java.nio.file.Files#isDirectory(Path, * LinkOption...)} on input paths with the given link options. */ public static Predicate<Path> isDirectory(LinkOption... options) { final LinkOption[] optionsCopy = options.clone(); return new Predicate<Path>() { @Override public boolean apply(Path input) { return Files.isDirectory(input, optionsCopy); } @Override public String toString() { return "MoreFiles.isDirectory(" + Arrays.toString(optionsCopy) + ")"; } }; } /** Returns whether or not the file with the given name in the given dir is a directory. */ private static boolean isDirectory( SecureDirectoryStream<Path> dir, Path name, LinkOption... options) throws IOException { return dir.getFileAttributeView(name, BasicFileAttributeView.class, options) .readAttributes() .isDirectory(); } /** * Returns a predicate that returns the result of {@link java.nio.file.Files#isRegularFile(Path, * LinkOption...)} on input paths with the given link options. */ public static Predicate<Path> isRegularFile(LinkOption... options) { final LinkOption[] optionsCopy = options.clone(); return new Predicate<Path>() { @Override public boolean apply(Path input) { return Files.isRegularFile(input, optionsCopy); } @Override public String toString() { return "MoreFiles.isRegularFile(" + Arrays.toString(optionsCopy) + ")"; } }; } /** * Returns true if the files located by the given paths exist, are not directories, and contain * the same bytes. * * @throws IOException if an I/O error occurs * @since 22.0 */ public static boolean equal(Path path1, Path path2) throws IOException { checkNotNull(path1); checkNotNull(path2); if (Files.isSameFile(path1, path2)) { return true; } /* * Some operating systems may return zero as the length for files denoting system-dependent * entities such as devices or pipes, in which case we must fall back on comparing the bytes * directly. */ ByteSource source1 = asByteSource(path1); ByteSource source2 = asByteSource(path2); long len1 = source1.sizeIfKnown().or(0L); long len2 = source2.sizeIfKnown().or(0L); if (len1 != 0 && len2 != 0 && len1 != len2) { return false; } return source1.contentEquals(source2); } /** * Like the unix command of the same name, creates an empty file or updates the last modified * timestamp of the existing file at the given path to the current system time. */ @SuppressWarnings("GoodTime") // reading system time without TimeSource public static void touch(Path path) throws IOException { checkNotNull(path); try { Files.setLastModifiedTime(path, FileTime.fromMillis(System.currentTimeMillis())); } catch (NoSuchFileException e) { try { Files.createFile(path); } catch (FileAlreadyExistsException ignore) { // The file didn't exist when we called setLastModifiedTime, but it did when we called // createFile, so something else created the file in between. The end result is // what we wanted: a new file that probably has its last modified time set to approximately // now. Or it could have an arbitrary last modified time set by the creator, but that's no // different than if another process set its last modified time to something else after we // created it here. } } } /** * Creates any necessary but nonexistent parent directories of the specified path. Note that if * this operation fails, it may have succeeded in creating some (but not all) of the necessary * parent directories. The parent directory is created with the given {@code attrs}. * * @throws IOException if an I/O error occurs, or if any necessary but nonexistent parent * directories of the specified file could not be created. */ public static void createParentDirectories(Path path, FileAttribute<?>... attrs) throws IOException { // Interestingly, unlike File.getCanonicalFile(), Path/Files provides no way of getting the // canonical (absolute, normalized, symlinks resolved, etc.) form of a path to a nonexistent // file. getCanonicalFile() can at least get the canonical form of the part of the path which // actually exists and then append the normalized remainder of the path to that. Path normalizedAbsolutePath = path.toAbsolutePath().normalize(); Path parent = normalizedAbsolutePath.getParent(); if (parent == null) { // The given directory is a filesystem root. All zero of its ancestors exist. This doesn't // mean that the root itself exists -- consider x:\ on a Windows machine without such a // drive -- or even that the caller can create it, but this method makes no such guarantees // even for non-root files. return; } // Check if the parent is a directory first because createDirectories will fail if the parent // exists and is a symlink to a directory... we'd like for this to succeed in that case. // (I'm kind of surprised that createDirectories would fail in that case; doesn't seem like // what you'd want to happen.) if (!Files.isDirectory(parent)) { Files.createDirectories(parent, attrs); if (!Files.isDirectory(parent)) { throw new IOException("Unable to create parent directories of " + path); } } } /** * Returns the <a href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> for * the file at the given path, or the empty string if the file has no extension. The result does * not include the '{@code .}'. * * <p><b>Note:</b> This method simply returns everything after the last '{@code .}' in the file's * name as determined by {@link Path#getFileName}. It does not account for any filesystem-specific * behavior that the {@link Path} API does not already account for. For example, on NTFS it will * report {@code "txt"} as the extension for the filename {@code "foo.exe:.txt"} even though NTFS * will drop the {@code ":.txt"} part of the name when the file is actually created on the * filesystem due to NTFS's <a href="https://goo.gl/vTpJi4">Alternate Data Streams</a>. */ public static String getFileExtension(Path path) { Path name = path.getFileName(); // null for empty paths and root-only paths if (name == null) { return ""; } String fileName = name.toString(); int dotIndex = fileName.lastIndexOf('.'); return dotIndex == -1 ? "" : fileName.substring(dotIndex + 1); } /** * Returns the file name without its <a * href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> or path. This is * similar to the {@code basename} unix command. The result does not include the '{@code .}'. */ public static String getNameWithoutExtension(Path path) { Path name = path.getFileName(); // null for empty paths and root-only paths if (name == null) { return ""; } String fileName = name.toString(); int dotIndex = fileName.lastIndexOf('.'); return dotIndex == -1 ? fileName : fileName.substring(0, dotIndex); } /** * Deletes the file or directory at the given {@code path} recursively. Deletes symbolic links, * not their targets (subject to the caveat below). * * <p>If an I/O exception occurs attempting to read, open or delete any file under the given * directory, this method skips that file and continues. All such exceptions are collected and, * after attempting to delete all files, an {@code IOException} is thrown containing those * exceptions as {@linkplain Throwable#getSuppressed() suppressed exceptions}. * * <h2>Warning: Security of recursive deletes</h2> * * <p>On a file system that supports symbolic links and does <i>not</i> support {@link * SecureDirectoryStream}, it is possible for a recursive delete to delete files and directories * that are <i>outside</i> the directory being deleted. This can happen if, after checking that a * file is a directory (and not a symbolic link), that directory is replaced by a symbolic link to * an outside directory before the call that opens the directory to read its entries. * * <p>By default, this method throws {@link InsecureRecursiveDeleteException} if it can't * guarantee the security of recursive deletes. If you wish to allow the recursive deletes anyway, * pass {@link RecursiveDeleteOption#ALLOW_INSECURE} to this method to override that behavior. * * @throws NoSuchFileException if {@code path} does not exist <i>(optional specific exception)</i> * @throws InsecureRecursiveDeleteException if the security of recursive deletes can't be * guaranteed for the file system and {@link RecursiveDeleteOption#ALLOW_INSECURE} was not * specified * @throws IOException if {@code path} or any file in the subtree rooted at it can't be deleted * for any reason */ public static void deleteRecursively(Path path, RecursiveDeleteOption... options) throws IOException { Path parentPath = getParentPath(path); if (parentPath == null) { throw new FileSystemException(path.toString(), null, "can't delete recursively"); } Collection<IOException> exceptions = null; // created lazily if needed try { boolean sdsSupported = false; try (DirectoryStream<Path> parent = Files.newDirectoryStream(parentPath)) { if (parent instanceof SecureDirectoryStream) { sdsSupported = true; exceptions = deleteRecursivelySecure( (SecureDirectoryStream<Path>) parent, /* * requireNonNull is safe because paths have file names when they have parents, * and we checked for a parent at the beginning of the method. */ requireNonNull(path.getFileName())); } } if (!sdsSupported) { checkAllowsInsecure(path, options); exceptions = deleteRecursivelyInsecure(path); } } catch (IOException e) { if (exceptions == null) { throw e; } else { exceptions.add(e); } } if (exceptions != null) { throwDeleteFailed(path, exceptions); } } /** * Deletes all files within the directory at the given {@code path} {@linkplain #deleteRecursively * recursively}. Does not delete the directory itself. Deletes symbolic links, not their targets * (subject to the caveat below). If {@code path} itself is a symbolic link to a directory, that * link is followed and the contents of the directory it targets are deleted. * * <p>If an I/O exception occurs attempting to read, open or delete any file under the given * directory, this method skips that file and continues. All such exceptions are collected and, * after attempting to delete all files, an {@code IOException} is thrown containing those * exceptions as {@linkplain Throwable#getSuppressed() suppressed exceptions}. * * <h2>Warning: Security of recursive deletes</h2> * * <p>On a file system that supports symbolic links and does <i>not</i> support {@link * SecureDirectoryStream}, it is possible for a recursive delete to delete files and directories * that are <i>outside</i> the directory being deleted. This can happen if, after checking that a * file is a directory (and not a symbolic link), that directory is replaced by a symbolic link to * an outside directory before the call that opens the directory to read its entries. * * <p>By default, this method throws {@link InsecureRecursiveDeleteException} if it can't * guarantee the security of recursive deletes. If you wish to allow the recursive deletes anyway, * pass {@link RecursiveDeleteOption#ALLOW_INSECURE} to this method to override that behavior. * * @throws NoSuchFileException if {@code path} does not exist <i>(optional specific exception)</i> * @throws NotDirectoryException if the file at {@code path} is not a directory <i>(optional * specific exception)</i> * @throws InsecureRecursiveDeleteException if the security of recursive deletes can't be * guaranteed for the file system and {@link RecursiveDeleteOption#ALLOW_INSECURE} was not * specified * @throws IOException if one or more files can't be deleted for any reason */ public static void deleteDirectoryContents(Path path, RecursiveDeleteOption... options) throws IOException { Collection<IOException> exceptions = null; // created lazily if needed try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) { if (stream instanceof SecureDirectoryStream) { SecureDirectoryStream<Path> sds = (SecureDirectoryStream<Path>) stream; exceptions = deleteDirectoryContentsSecure(sds); } else { checkAllowsInsecure(path, options); exceptions = deleteDirectoryContentsInsecure(stream); } } catch (IOException e) { if (exceptions == null) { throw e; } else { exceptions.add(e); } } if (exceptions != null) { throwDeleteFailed(path, exceptions); } } /** * Secure recursive delete using {@code SecureDirectoryStream}. Returns a collection of exceptions * that occurred or null if no exceptions were thrown. */ @CheckForNull private static Collection<IOException> deleteRecursivelySecure( SecureDirectoryStream<Path> dir, Path path) { Collection<IOException> exceptions = null; try { if (isDirectory(dir, path, NOFOLLOW_LINKS)) { try (SecureDirectoryStream<Path> childDir = dir.newDirectoryStream(path, NOFOLLOW_LINKS)) { exceptions = deleteDirectoryContentsSecure(childDir); } // If exceptions is not null, something went wrong trying to delete the contents of the // directory, so we shouldn't try to delete the directory as it will probably fail. if (exceptions == null) { dir.deleteDirectory(path); } } else { dir.deleteFile(path); } return exceptions; } catch (IOException e) { return addException(exceptions, e); } } /** * Secure method for deleting the contents of a directory using {@code SecureDirectoryStream}. * Returns a collection of exceptions that occurred or null if no exceptions were thrown. */ @CheckForNull private static Collection<IOException> deleteDirectoryContentsSecure( SecureDirectoryStream<Path> dir) { Collection<IOException> exceptions = null; try { for (Path path : dir) { exceptions = concat(exceptions, deleteRecursivelySecure(dir, path.getFileName())); } return exceptions; } catch (DirectoryIteratorException e) { return addException(exceptions, e.getCause()); } } /** * Insecure recursive delete for file systems that don't support {@code SecureDirectoryStream}. * Returns a collection of exceptions that occurred or null if no exceptions were thrown. */ @CheckForNull private static Collection<IOException> deleteRecursivelyInsecure(Path path) { Collection<IOException> exceptions = null; try { if (Files.isDirectory(path, NOFOLLOW_LINKS)) { try (DirectoryStream<Path> stream = Files.newDirectoryStream(path)) { exceptions = deleteDirectoryContentsInsecure(stream); } } // If exceptions is not null, something went wrong trying to delete the contents of the // directory, so we shouldn't try to delete the directory as it will probably fail. if (exceptions == null) { Files.delete(path); } return exceptions; } catch (IOException e) { return addException(exceptions, e); } } /** * Simple, insecure method for deleting the contents of a directory for file systems that don't * support {@code SecureDirectoryStream}. Returns a collection of exceptions that occurred or null * if no exceptions were thrown. */ @CheckForNull private static Collection<IOException> deleteDirectoryContentsInsecure( DirectoryStream<Path> dir) { Collection<IOException> exceptions = null; try { for (Path entry : dir) { exceptions = concat(exceptions, deleteRecursivelyInsecure(entry)); } return exceptions; } catch (DirectoryIteratorException e) { return addException(exceptions, e.getCause()); } } /** * Returns a path to the parent directory of the given path. If the path actually has a parent * path, this is simple. Otherwise, we need to do some trickier things. Returns null if the path * is a root or is the empty path. */ @CheckForNull private static Path getParentPath(Path path) { Path parent = path.getParent(); // Paths that have a parent: if (parent != null) { // "/foo" ("/") // "foo/bar" ("foo") // "C:\foo" ("C:\") // "\foo" ("\" - current drive for process on Windows) // "C:foo" ("C:" - working dir of drive C on Windows) return parent; } // Paths that don't have a parent: if (path.getNameCount() == 0) { // "/", "C:\", "\" (no parent) // "" (undefined, though typically parent of working dir) // "C:" (parent of working dir of drive C on Windows) // // For working dir paths ("" and "C:"), return null because: // A) it's not specified that "" is the path to the working directory. // B) if we're getting this path for recursive delete, it's typically not possible to // delete the working dir with a relative path anyway, so it's ok to fail. // C) if we're getting it for opening a new SecureDirectoryStream, there's no need to get // the parent path anyway since we can safely open a DirectoryStream to the path without // worrying about a symlink. return null; } else { // "foo" (working dir) return path.getFileSystem().getPath("."); } } /** Checks that the given options allow an insecure delete, throwing an exception if not. */ private static void checkAllowsInsecure(Path path, RecursiveDeleteOption[] options) throws InsecureRecursiveDeleteException { if (!Arrays.asList(options).contains(RecursiveDeleteOption.ALLOW_INSECURE)) { throw new InsecureRecursiveDeleteException(path.toString()); } } /** * Adds the given exception to the given collection, creating the collection if it's null. Returns * the collection. */ private static Collection<IOException> addException( @CheckForNull Collection<IOException> exceptions, IOException e) { if (exceptions == null) { exceptions = new ArrayList<>(); // don't need Set semantics } exceptions.add(e); return exceptions; } /** * Concatenates the contents of the two given collections of exceptions. If either collection is * null, the other collection is returned. Otherwise, the elements of {@code other} are added to * {@code exceptions} and {@code exceptions} is returned. */ @CheckForNull private static Collection<IOException> concat( @CheckForNull Collection<IOException> exceptions, @CheckForNull Collection<IOException> other) { if (exceptions == null) { return other; } else if (other != null) { exceptions.addAll(other); } return exceptions; } /** * Throws an exception indicating that one or more files couldn't be deleted when deleting {@code * path} or its contents. * * <p>If there is only one exception in the collection, and it is a {@link NoSuchFileException} * thrown because {@code path} itself didn't exist, then throws that exception. Otherwise, the * thrown exception contains all the exceptions in the given collection as suppressed exceptions. */ private static void throwDeleteFailed(Path path, Collection<IOException> exceptions) throws FileSystemException { NoSuchFileException pathNotFound = pathNotFound(path, exceptions); if (pathNotFound != null) { throw pathNotFound; } // TODO(cgdecker): Should there be a custom exception type for this? // Also, should we try to include the Path of each file we may have failed to delete rather // than just the exceptions that occurred? FileSystemException deleteFailed = new FileSystemException( path.toString(), null, "failed to delete one or more files; see suppressed exceptions for details"); for (IOException e : exceptions) { deleteFailed.addSuppressed(e); } throw deleteFailed; } @CheckForNull private static NoSuchFileException pathNotFound(Path path, Collection<IOException> exceptions) { if (exceptions.size() != 1) { return null; } IOException exception = getOnlyElement(exceptions); if (!(exception instanceof NoSuchFileException)) { return null; } NoSuchFileException noSuchFileException = (NoSuchFileException) exception; String exceptionFile = noSuchFileException.getFile(); if (exceptionFile == null) { /* * It's not clear whether this happens in practice, especially with the filesystem * implementations that are built into java.nio. */ return null; } Path parentPath = getParentPath(path); if (parentPath == null) { /* * This is probably impossible: * * - In deleteRecursively, we require the path argument to have a parent. * * - In deleteDirectoryContents, the path argument may have no parent. Fortunately, all the * *other* paths we process will be descendants of that. That leaves only the original path * argument for us to consider. And the only place we call pathNotFound is from * throwDeleteFailed, and the other place that we call throwDeleteFailed inside * deleteDirectoryContents is when an exception is thrown during the recursive steps. Any * failure during the initial lookup of the path argument itself is rethrown directly. So * any exception that we're seeing here is from a descendant, which naturally has a parent. * I think. * * Still, if this can happen somehow (a weird filesystem implementation that lets callers * change its working directly concurrently with a call to deleteDirectoryContents?), it makes * more sense for us to fall back to a generic FileSystemException (by returning null here) * than to dereference parentPath and end up producing NullPointerException. */ return null; } // requireNonNull is safe because paths have file names when they have parents. Path pathResolvedFromParent = parentPath.resolve(requireNonNull(path.getFileName())); if (exceptionFile.equals(pathResolvedFromParent.toString())) { return noSuchFileException; } return null; } }
google/guava
guava/src/com/google/common/io/MoreFiles.java
307
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer; import lombok.Getter; /** * WeatherType enumeration. */ public enum WeatherType { SUNNY("Sunny"), RAINY("Rainy"), WINDY("Windy"), COLD("Cold"); @Getter private final String description; WeatherType(String description) { this.description = description; } @Override public String toString() { return this.name().toLowerCase(); } }
iluwatar/java-design-patterns
observer/src/main/java/com/iluwatar/observer/WeatherType.java
308
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd import com.google.protobuf.AbstractMessageLite; import com.google.protobuf.ByteString; import com.google.protobuf.CodedInputStream; import com.google.protobuf.ExtensionRegistryLite; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.MessageLite; import com.google.protobuf.Parser; import com.google.protobuf.conformance.Conformance; import com.google.protobuf_test_messages.edition2023.TestAllTypesEdition2023; import com.google.protobuf_test_messages.edition2023.TestMessagesEdition2023; import com.google.protobuf_test_messages.editions.proto2.TestMessagesProto2Editions; import com.google.protobuf_test_messages.editions.proto3.TestMessagesProto3Editions; import com.google.protobuf_test_messages.proto2.TestMessagesProto2; import com.google.protobuf_test_messages.proto2.TestMessagesProto2.TestAllTypesProto2; import com.google.protobuf_test_messages.proto3.TestMessagesProto3; import com.google.protobuf_test_messages.proto3.TestMessagesProto3.TestAllTypesProto3; import java.nio.ByteBuffer; import java.util.ArrayList; class ConformanceJavaLite { private int testCount = 0; private boolean readFromStdin(byte[] buf, int len) throws Exception { int ofs = 0; while (len > 0) { int read = System.in.read(buf, ofs, len); if (read == -1) { return false; // EOF } ofs += read; len -= read; } return true; } private void writeToStdout(byte[] buf) throws Exception { System.out.write(buf); } // Returns -1 on EOF (the actual values will always be positive). private int readLittleEndianIntFromStdin() throws Exception { byte[] buf = new byte[4]; if (!readFromStdin(buf, 4)) { return -1; } return (buf[0] & 0xff) | ((buf[1] & 0xff) << 8) | ((buf[2] & 0xff) << 16) | ((buf[3] & 0xff) << 24); } private void writeLittleEndianIntToStdout(int val) throws Exception { byte[] buf = new byte[4]; buf[0] = (byte) val; buf[1] = (byte) (val >> 8); buf[2] = (byte) (val >> 16); buf[3] = (byte) (val >> 24); writeToStdout(buf); } private enum BinaryDecoderType { BTYE_STRING_DECODER, BYTE_ARRAY_DECODER, ARRAY_BYTE_BUFFER_DECODER, READONLY_ARRAY_BYTE_BUFFER_DECODER, DIRECT_BYTE_BUFFER_DECODER, READONLY_DIRECT_BYTE_BUFFER_DECODER, INPUT_STREAM_DECODER; } private static class BinaryDecoder<T extends MessageLite> { public T decode( ByteString bytes, BinaryDecoderType type, Parser<T> parser, ExtensionRegistryLite extensions) throws InvalidProtocolBufferException { switch (type) { case BTYE_STRING_DECODER: case BYTE_ARRAY_DECODER: return parser.parseFrom(bytes, extensions); case ARRAY_BYTE_BUFFER_DECODER: { ByteBuffer buffer = ByteBuffer.allocate(bytes.size()); bytes.copyTo(buffer); buffer.flip(); return parser.parseFrom(CodedInputStream.newInstance(buffer), extensions); } case READONLY_ARRAY_BYTE_BUFFER_DECODER: { return parser.parseFrom( CodedInputStream.newInstance(bytes.asReadOnlyByteBuffer()), extensions); } case DIRECT_BYTE_BUFFER_DECODER: { ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size()); bytes.copyTo(buffer); buffer.flip(); return parser.parseFrom(CodedInputStream.newInstance(buffer), extensions); } case READONLY_DIRECT_BYTE_BUFFER_DECODER: { ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size()); bytes.copyTo(buffer); buffer.flip(); return parser.parseFrom( CodedInputStream.newInstance(buffer.asReadOnlyBuffer()), extensions); } case INPUT_STREAM_DECODER: { return parser.parseFrom(bytes.newInput(), extensions); } } return null; } } private <T extends MessageLite> T parseBinary( ByteString bytes, Parser<T> parser, ExtensionRegistryLite extensions) throws InvalidProtocolBufferException { ArrayList<T> messages = new ArrayList<>(); ArrayList<InvalidProtocolBufferException> exceptions = new ArrayList<>(); for (int i = 0; i < BinaryDecoderType.values().length; i++) { messages.add(null); exceptions.add(null); } if (messages.isEmpty()) { throw new RuntimeException("binary decoder types missing"); } BinaryDecoder<T> decoder = new BinaryDecoder<>(); boolean hasMessage = false; boolean hasException = false; for (int i = 0; i < BinaryDecoderType.values().length; ++i) { try { messages.set(i, decoder.decode(bytes, BinaryDecoderType.values()[i], parser, extensions)); hasMessage = true; } catch (InvalidProtocolBufferException e) { exceptions.set(i, e); hasException = true; } } if (hasMessage && hasException) { StringBuilder sb = new StringBuilder("Binary decoders disagreed on whether the payload was valid.\n"); for (int i = 0; i < BinaryDecoderType.values().length; ++i) { sb.append(BinaryDecoderType.values()[i].name()); if (messages.get(i) != null) { sb.append(" accepted the payload.\n"); } else { sb.append(" rejected the payload.\n"); } } throw new RuntimeException(sb.toString()); } if (hasException) { // We do not check if exceptions are equal. Different implementations may return different // exception messages. Throw an arbitrary one out instead. InvalidProtocolBufferException exception = null; for (InvalidProtocolBufferException e : exceptions) { if (exception != null) { exception.addSuppressed(e); } else { exception = e; } } throw exception; } // Fast path comparing all the messages with the first message, assuming equality being // symmetric and transitive. boolean allEqual = true; for (int i = 1; i < messages.size(); ++i) { if (!messages.get(0).equals(messages.get(i))) { allEqual = false; break; } } // Slow path: compare and find out all unequal pairs. if (!allEqual) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < messages.size() - 1; ++i) { for (int j = i + 1; j < messages.size(); ++j) { if (!messages.get(i).equals(messages.get(j))) { sb.append(BinaryDecoderType.values()[i].name()) .append(" and ") .append(BinaryDecoderType.values()[j].name()) .append(" parsed the payload differently.\n"); } } } throw new RuntimeException(sb.toString()); } return messages.get(0); } private Class<? extends AbstractMessageLite> createTestMessage(String messageType) { switch (messageType) { case "protobuf_test_messages.proto3.TestAllTypesProto3": return TestAllTypesProto3.class; case "protobuf_test_messages.proto2.TestAllTypesProto2": return TestAllTypesProto2.class; case "protobuf_test_messages.editions.TestAllTypesEdition2023": return TestAllTypesEdition2023.class; case "protobuf_test_messages.editions.proto3.TestAllTypesProto3": return TestMessagesProto3Editions.TestAllTypesProto3.class; case "protobuf_test_messages.editions.proto2.TestAllTypesProto2": return TestMessagesProto2Editions.TestAllTypesProto2.class; default: throw new IllegalArgumentException( "Protobuf request has unexpected payload type: " + messageType); } } private Class<?> createTestFile(String messageType) { switch (messageType) { case "protobuf_test_messages.proto3.TestAllTypesProto3": return TestMessagesProto3.class; case "protobuf_test_messages.proto2.TestAllTypesProto2": return TestMessagesProto2.class; case "protobuf_test_messages.editions.TestAllTypesEdition2023": return TestMessagesEdition2023.class; case "protobuf_test_messages.editions.proto3.TestAllTypesProto3": return TestMessagesProto3Editions.class; case "protobuf_test_messages.editions.proto2.TestAllTypesProto2": return TestMessagesProto2Editions.class; default: throw new IllegalArgumentException( "Protobuf request has unexpected payload type: " + messageType); } } @SuppressWarnings("unchecked") private Conformance.ConformanceResponse doTest(Conformance.ConformanceRequest request) { com.google.protobuf.MessageLite testMessage; String messageType = request.getMessageType(); switch (request.getPayloadCase()) { case PROTOBUF_PAYLOAD: { try { ExtensionRegistryLite extensions = ExtensionRegistryLite.newInstance(); createTestFile(messageType) .getMethod("registerAllExtensions", ExtensionRegistryLite.class) .invoke(null, extensions); testMessage = parseBinary( request.getProtobufPayload(), (Parser<AbstractMessageLite>) createTestMessage(messageType).getMethod("parser").invoke(null), extensions); } catch (InvalidProtocolBufferException e) { return Conformance.ConformanceResponse.newBuilder() .setParseError(e.getMessage()) .build(); } catch (Exception e) { throw new RuntimeException(e); } break; } case JSON_PAYLOAD: { return Conformance.ConformanceResponse.newBuilder() .setSkipped("Lite runtime does not support JSON format.") .build(); } case TEXT_PAYLOAD: { return Conformance.ConformanceResponse.newBuilder() .setSkipped("Lite runtime does not support Text format.") .build(); } case PAYLOAD_NOT_SET: { throw new RuntimeException("Request didn't have payload."); } default: { throw new RuntimeException("Unexpected payload case."); } } switch (request.getRequestedOutputFormat()) { case UNSPECIFIED: throw new RuntimeException("Unspecified output format."); case PROTOBUF: return Conformance.ConformanceResponse.newBuilder() .setProtobufPayload(testMessage.toByteString()) .build(); case JSON: return Conformance.ConformanceResponse.newBuilder() .setSkipped("Lite runtime does not support JSON format.") .build(); case TEXT_FORMAT: return Conformance.ConformanceResponse.newBuilder() .setSkipped("Lite runtime does not support Text format.") .build(); default: { throw new RuntimeException("Unexpected request output."); } } } private boolean doTestIo() throws Exception { int bytes = readLittleEndianIntFromStdin(); if (bytes == -1) { return false; // EOF } byte[] serializedInput = new byte[bytes]; if (!readFromStdin(serializedInput, bytes)) { throw new RuntimeException("Unexpected EOF from test program."); } Conformance.ConformanceRequest request = Conformance.ConformanceRequest.parseFrom(serializedInput); Conformance.ConformanceResponse response = doTest(request); byte[] serializedOutput = response.toByteArray(); writeLittleEndianIntToStdout(serializedOutput.length); writeToStdout(serializedOutput); return true; } public void run() throws Exception { while (doTestIo()) { this.testCount++; } System.err.println( "ConformanceJavaLite: received EOF from test runner after " + this.testCount + " tests"); } public static void main(String[] args) throws Exception { new ConformanceJavaLite().run(); } }
protocolbuffers/protobuf
conformance/ConformanceJavaLite.java
310
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you 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 project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2018, 2020 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Functions that can be applied to an H3 index. */ final class H3Index { /** * Gets the integer base cell of h3. */ public static int H3_get_base_cell(long h3) { return ((int) ((((h3) & H3_BC_MASK) >> H3_BC_OFFSET))); } /** * Returns <code>true</code> if this index is one of twelve pentagons per resolution. */ public static boolean H3_is_pentagon(long h3) { return BaseCells.isBaseCellPentagon(H3Index.H3_get_base_cell(h3)) && H3Index.h3LeadingNonZeroDigit(h3) == 0; } public static long H3_INIT = 35184372088831L; /** * The bit offset of the mode in an H3 index. */ public static int H3_MODE_OFFSET = 59; /** * 1's in the 4 mode bits, 0's everywhere else. */ public static long H3_MODE_MASK = 15L << H3_MODE_OFFSET; /** * 0's in the 4 mode bits, 1's everywhere else. */ public static long H3_MODE_MASK_NEGATIVE = ~H3_MODE_MASK; public static long H3_set_mode(long h3, long mode) { return (h3 & H3_MODE_MASK_NEGATIVE) | (mode << H3_MODE_OFFSET); } /** * The bit offset of the base cell in an H3 index. */ public static int H3_BC_OFFSET = 45; /** * 1's in the 7 base cell bits, 0's everywhere else. */ public static long H3_BC_MASK = 127L << H3_BC_OFFSET; /** * 0's in the 7 base cell bits, 1's everywhere else. */ public static long H3_BC_MASK_NEGATIVE = ~H3_BC_MASK; /** * Sets the integer base cell of h3 to bc. */ public static long H3_set_base_cell(long h3, long bc) { return (h3 & H3_BC_MASK_NEGATIVE) | (bc << H3_BC_OFFSET); } public static int H3_RES_OFFSET = 52; /** * 1's in the 4 resolution bits, 0's everywhere else. */ public static long H3_RES_MASK = 15L << H3_RES_OFFSET; /** * 0's in the 4 resolution bits, 1's everywhere else. */ public static long H3_RES_MASK_NEGATIVE = ~H3_RES_MASK; /** * The bit offset of the max resolution digit in an H3 index. */ public static int H3_MAX_OFFSET = 63; /** * 1 in the highest bit, 0's everywhere else. */ public static long H3_HIGH_BIT_MASK = (1L << H3_MAX_OFFSET); /** * Gets the highest bit of the H3 index. */ public static int H3_get_high_bit(long h3) { return ((int) ((((h3) & H3_HIGH_BIT_MASK) >> H3_MAX_OFFSET))); } /** * Sets the long resolution of h3. */ public static long H3_set_resolution(long h3, long res) { return (((h3) & H3_RES_MASK_NEGATIVE) | (((res)) << H3_RES_OFFSET)); } /** * The bit offset of the reserved bits in an H3 index. */ public static int H3_RESERVED_OFFSET = 56; /** * 1's in the 3 reserved bits, 0's everywhere else. */ public static long H3_RESERVED_MASK = (7L << H3_RESERVED_OFFSET); /** * Gets a value in the reserved space. Should always be zero for valid indexes. */ public static int H3_get_reserved_bits(long h3) { return ((int) ((((h3) & H3_RESERVED_MASK) >> H3_RESERVED_OFFSET))); } public static int H3_get_mode(long h3) { return ((int) ((((h3) & H3_MODE_MASK) >> H3_MODE_OFFSET))); } /** * Gets the integer resolution of h3. */ public static int H3_get_resolution(long h3) { return (int) ((h3 & H3_RES_MASK) >> H3_RES_OFFSET); } /** * The number of bits in a single H3 resolution digit. */ public static int H3_PER_DIGIT_OFFSET = 3; /** * 1's in the 3 bits of res 15 digit bits, 0's everywhere else. */ public static long H3_DIGIT_MASK = 7L; /** * Gets the resolution res integer digit (0-7) of h3. */ public static int H3_get_index_digit(long h3, int res) { return ((int) ((((h3) >> ((Constants.MAX_H3_RES - (res)) * H3_PER_DIGIT_OFFSET)) & H3_DIGIT_MASK))); } /** * Sets the resolution res digit of h3 to the integer digit (0-7) */ public static long H3_set_index_digit(long h3, int res, long digit) { int x = (Constants.MAX_H3_RES - res) * H3_PER_DIGIT_OFFSET; return (((h3) & ~((H3_DIGIT_MASK << (x)))) | (((digit)) << x)); } /** * Returns whether or not a resolution is a Class III grid. Note that odd * resolutions are Class III and even resolutions are Class II. * @param res The H3 resolution. * @return 1 if the resolution is a Class III grid, and 0 if the resolution is * a Class II grid. */ public static boolean isResolutionClassIII(int res) { return (res & 1) == 1; } /** * Convert an H3Index to a FaceIJK address. * @param h3 The H3Index. */ public static FaceIJK h3ToFaceIjk(long h3) { int baseCell = H3Index.H3_get_base_cell(h3); if (baseCell < 0 || baseCell >= Constants.NUM_BASE_CELLS) { // LCOV_EXCL_BR_LINE // Base cells less than zero can not be represented in an index // To prevent reading uninitialized memory, we zero the output. throw new IllegalArgumentException(); } // adjust for the pentagonal missing sequence; all of sub-sequence 5 needs // to be adjusted (and some of sub-sequence 4 below) if (BaseCells.isBaseCellPentagon(baseCell) && h3LeadingNonZeroDigit(h3) == 5) { h3 = h3Rotate60cw(h3); } // start with the "home" face and ijk+ coordinates for the base cell of c FaceIJK fijk = BaseCells.getBaseFaceIJK(baseCell); if (h3ToFaceIjkWithInitializedFijk(h3, fijk) == false) { return fijk; // no overage is possible; h lies on this face } // if we're here we have the potential for an "overage"; i.e., it is // possible that c lies on an adjacent face int origI = fijk.coord.i; int origJ = fijk.coord.j; int origK = fijk.coord.k; // if we're in Class III, drop into the next finer Class II grid int res = H3Index.H3_get_resolution(h3); if (isResolutionClassIII(res)) { // Class III fijk.coord.downAp7r(); res++; } // adjust for overage if needed // a pentagon base cell with a leading 4 digit requires special handling boolean pentLeading4 = (BaseCells.isBaseCellPentagon(baseCell) && h3LeadingNonZeroDigit(h3) == 4); if (fijk.adjustOverageClassII(res, pentLeading4, false) != FaceIJK.Overage.NO_OVERAGE) { // if the base cell is a pentagon we have the potential for secondary // overages if (BaseCells.isBaseCellPentagon(baseCell)) { FaceIJK.Overage overage; do { overage = fijk.adjustOverageClassII(res, false, false); } while (overage != FaceIJK.Overage.NO_OVERAGE); } if (res != H3Index.H3_get_resolution(h3)) { fijk.coord.upAp7r(); } } else if (res != H3Index.H3_get_resolution(h3)) { fijk.coord.reset(origI, origJ, origK); } return fijk; } /** * Returns the highest resolution non-zero digit in an H3Index. * @param h The H3Index. * @return The highest resolution non-zero digit in the H3Index. */ public static int h3LeadingNonZeroDigit(long h) { for (int r = 1; r <= H3Index.H3_get_resolution(h); r++) { final int dir = H3Index.H3_get_index_digit(h, r); if (dir != CoordIJK.Direction.CENTER_DIGIT.digit()) { return dir; } } // if we're here it's all 0's return CoordIJK.Direction.CENTER_DIGIT.digit(); } /** * Convert an H3Index to the FaceIJK address on a specified icosahedral face. * @param h The H3Index. * @param fijk The FaceIJK address, initialized with the desired face * and normalized base cell coordinates. * @return Returns true if the possibility of overage exists, otherwise false. */ private static boolean h3ToFaceIjkWithInitializedFijk(long h, FaceIJK fijk) { final int res = H3Index.H3_get_resolution(h); // center base cell hierarchy is entirely on this face final boolean possibleOverage = BaseCells.isBaseCellPentagon(H3_get_base_cell(h)) || (res != 0 && (fijk.coord.i != 0 || fijk.coord.j != 0 || fijk.coord.k != 0)); for (int r = 1; r <= res; r++) { if (isResolutionClassIII(r)) { // Class III == rotate ccw fijk.coord.downAp7(); } else { // Class II == rotate cw fijk.coord.downAp7r(); } fijk.coord.neighbor(H3_get_index_digit(h, r)); } return possibleOverage; } /** * Rotate an H3Index 60 degrees clockwise. * @param h The H3Index. */ public static long h3Rotate60cw(long h) { for (int r = 1, res = H3_get_resolution(h); r <= res; r++) { h = H3_set_index_digit(h, r, CoordIJK.rotate60cw(H3_get_index_digit(h, r))); } return h; } /** * Rotate an H3Index 60 degrees counter-clockwise. * @param h The H3Index. */ public static long h3Rotate60ccw(long h) { for (int r = 1, res = H3_get_resolution(h); r <= res; r++) { h = H3_set_index_digit(h, r, CoordIJK.rotate60ccw(H3_get_index_digit(h, r))); } return h; } /** * Rotate an H3Index 60 degrees counter-clockwise about a pentagonal center. * @param h The H3Index. */ public static long h3RotatePent60ccw(long h) { // skips any leading 1 digits (k-axis) boolean foundFirstNonZeroDigit = false; for (int r = 1, res = H3_get_resolution(h); r <= res; r++) { // rotate this digit h = H3_set_index_digit(h, r, CoordIJK.rotate60ccw(H3_get_index_digit(h, r))); // look for the first non-zero digit so we // can adjust for deleted k-axes sequence // if necessary if (foundFirstNonZeroDigit == false && H3_get_index_digit(h, r) != 0) { foundFirstNonZeroDigit = true; // adjust for deleted k-axes sequence if (h3LeadingNonZeroDigit(h) == CoordIJK.Direction.K_AXES_DIGIT.digit()) h = h3Rotate60ccw(h); } } return h; } }
elastic/elasticsearch
libs/h3/src/main/java/org/elasticsearch/h3/H3Index.java
312
import java.net.*; import java.io.*; public class FuckingCoffee{ private static final String MY_USERNAME = "my_username"; private static final String PASSWORD_PROMPT = "Password: "; private static final String PASSWORD = "1234"; private static final String COFFEE_MACHINE_IP = "10.10.42.42"; private static int DELAY_BEFORE_BREW = 17; private static int DELAY = 24; public static void main(String[] args)throws Exception{ for(int i = 1; i< args.length ; i++){ if(!args[i].contains(MY_USERNAME)){ return; } } Socket telnet = new Socket(COFFEE_MACHINE_IP, 23); PrintWriter out = new PrintWriter(telnet.getOutputStream(), true); BufferedReader in = new BufferedReader(new InputStreamReader(telnet.getInputStream())); Thread.sleep(DELAY_BEFORE_BREW*1000); if(!in.readLine().equals(PASSWORD_PROMPT)){ return ; } out.println(PASSWORD); out.println("sys brew"); Thread.sleep(DELAY*1000); out.println("sys pour"); out.close(); in.close(); telnet.close(); } }
NARKOZ/hacker-scripts
java/FuckingCoffee.java
314
import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class Utils *****/ class Utils implements Debuggable { int domain_id; public static Random R = new Random(); public static String NOW; public static Vector ALL_NON_TRIVIAL_SUBSETS(Vector v) { Vector ret = new Vector(); Vector copycat = new Vector(); int i; for (i = 0; i < v.size(); i++) copycat.addElement(new String((String) v.elementAt(i))); MOVE_IN(ret, copycat); ret.removeElementAt(0); ret.removeElementAt(ret.size() - 1); return ret; } public static void MOVE_IN(Vector grow, Vector shrink) { if ((shrink == null) || (shrink.size() == 0)) Dataset.perror("Utils.class :: MOVE_IN impossible because empty list of values"); if (grow == null) Dataset.perror("Utils.class :: MOVE_IN impossible because empty grow list"); String s = (String) shrink.elementAt(0); Vector v, vv; if (grow.size() == 0) { v = new Vector(); grow.addElement(v); } int i, sinit = grow.size(), j; for (i = 0; i < sinit; i++) { vv = (Vector) grow.elementAt(i); v = new Vector(); if (vv.size() > 0) for (j = 0; j < vv.size(); j++) v.addElement(new String((String) vv.elementAt(j))); v.addElement(new String(s)); grow.addElement(v); } shrink.removeElementAt(0); if (shrink.size() > 0) MOVE_IN(grow, shrink); } public static void INIT() { Calendar cal = Calendar.getInstance(); R = new Random(); NOW = Algorithm.MONTHS[cal.get(Calendar.MONTH)] + "_" + cal.get(Calendar.DAY_OF_MONTH) + "th__" + cal.get(Calendar.HOUR_OF_DAY) + "h_" + cal.get(Calendar.MINUTE) + "m_" + cal.get(Calendar.SECOND) + "s"; } public static double COMPUTE_P(double wp, double wn) { double val; if (wp + wn > 0.0) val = (wp / (wp + wn)); else val = 0.5; if (val != 0.5) return val; double vv = RANDOM_P_NOT_HALF(); if (vv < 0.5) val -= EPS2; else val += EPS2; return val; } public static double RANDOM_P_NOT_HALF() { double vv; do { vv = R.nextDouble(); } while (vv == 0.5); return vv; } }
google-research/google-research
tempered_boosting/Utils.java
316
// Given a set of words (without duplicates), find all word squares you can build from them. // A sequence of words forms a valid word square if the kth row and column read the exact same string, where 0 ≤ k < max(numRows, numColumns). // For example, the word sequence ["ball","area","lead","lady"] forms a word square because each word reads the same both horizontally and vertically. // b a l l // a r e a // l e a d // l a d y // Note: // There are at least 1 and at most 1000 words. // All words will have the exact same length. // Word length is at least 1 and at most 5. // Each word contains only lowercase English alphabet a-z. public class WordSquares { public List<List<String>> wordSquares(String[] words) { List<List<String>> ret = new ArrayList<List<String>>(); if(words.length==0 || words[0].length()==0) { return ret; } Map<String, Set<String>> map = new HashMap<>(); int squareLen = words[0].length(); // create all prefix for(int i=0;i<words.length;i++){ for(int j=-1;j<words[0].length();j++){ if(!map.containsKey(words[i].substring(0, j+1))) { map.put(words[i].substring(0, j+1), new HashSet<String>()); } map.get(words[i].substring(0, j+1)).add(words[i]); } } helper(ret, new ArrayList<String>(), 0, squareLen, map); return ret; } public void helper(List<List<String>> ret, List<String> cur, int matched, int total, Map<String, Set<String>> map){ if(matched == total) { ret.add(new ArrayList<String>(cur)); return; } // build search string StringBuilder sb = new StringBuilder(); for(int i=0;i<=matched-1;i++) { sb.append(cur.get(i).charAt(matched)); } // bachtracking Set<String> cand = map.get(sb.toString()); if(cand==null) { return; } for(String str:cand){ cur.add(str); helper(ret, cur, matched+1, total, map); cur.remove(cur.size()-1); } } }
kdn251/interviews
leetcode/trie/WordSquares.java
318
package com.thealgorithms.maths; public final class BinaryPow { private BinaryPow() { } /** * Calculate a^p using binary exponentiation * [Binary-Exponentiation](https://cp-algorithms.com/algebra/binary-exp.html) * * @param a the base for exponentiation * @param p the exponent - must be greater than 0 * @return a^p */ public static int binPow(int a, int p) { int res = 1; while (p > 0) { if ((p & 1) == 1) { res = res * a; } a = a * a; p >>>= 1; } return res; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/BinaryPow.java
320
/** * File: PrintUtil.java * Created Time: 2022-11-25 * Author: krahets ([email protected]) */ package utils; import java.util.*; class Trunk { Trunk prev; String str; Trunk(Trunk prev, String str) { this.prev = prev; this.str = str; } }; public class PrintUtil { /* 打印矩阵(Array) */ public static <T> void printMatrix(T[][] matrix) { System.out.println("["); for (T[] row : matrix) { System.out.println(" " + row + ","); } System.out.println("]"); } /* 打印矩阵(List) */ public static <T> void printMatrix(List<List<T>> matrix) { System.out.println("["); for (List<T> row : matrix) { System.out.println(" " + row + ","); } System.out.println("]"); } /* 打印链表 */ public static void printLinkedList(ListNode head) { List<String> list = new ArrayList<>(); while (head != null) { list.add(String.valueOf(head.val)); head = head.next; } System.out.println(String.join(" -> ", list)); } /* 打印二叉树 */ public static void printTree(TreeNode root) { printTree(root, null, false); } /** * 打印二叉树 * This tree printer is borrowed from TECHIE DELIGHT * https://www.techiedelight.com/c-program-print-binary-tree/ */ public static void printTree(TreeNode root, Trunk prev, boolean isRight) { if (root == null) { return; } String prev_str = " "; Trunk trunk = new Trunk(prev, prev_str); printTree(root.right, trunk, true); if (prev == null) { trunk.str = "———"; } else if (isRight) { trunk.str = "/———"; prev_str = " |"; } else { trunk.str = "\\———"; prev.str = prev_str; } showTrunks(trunk); System.out.println(" " + root.val); if (prev != null) { prev.str = prev_str; } trunk.str = " |"; printTree(root.left, trunk, false); } public static void showTrunks(Trunk p) { if (p == null) { return; } showTrunks(p.prev); System.out.print(p.str); } /* 打印哈希表 */ public static <K, V> void printHashMap(Map<K, V> map) { for (Map.Entry<K, V> kv : map.entrySet()) { System.out.println(kv.getKey() + " -> " + kv.getValue()); } } /* 打印堆(优先队列) */ public static void printHeap(Queue<Integer> queue) { List<Integer> list = new ArrayList<>(queue); System.out.print("堆的数组表示:"); System.out.println(list); System.out.println("堆的树状表示:"); TreeNode root = TreeNode.listToTree(list); printTree(root); } }
krahets/hello-algo
codes/java/utils/PrintUtil.java
321
///usr/bin/env jbang "$0" "$@" ; exit $? //DEPS info.picocli:picocli:4.5.0 import picocli.CommandLine; import picocli.CommandLine.Command; import picocli.CommandLine.Parameters; import java.util.concurrent.Callable; @Command(name = "hellocli", mixinStandardHelpOptions = true, version = "hellocli 0.1", description = "hellocli made with jbang") class hellocli implements Callable<Integer> { @Parameters(index = "0", description = "The greeting to print", defaultValue = "World!") private String greeting; public static void main(String... args) { int exitCode = new CommandLine(new hellocli()).execute(args); System.exit(exitCode); } @Override public Integer call() throws Exception { // your business logic goes here... System.out.println("Hello " + greeting); return 0; } }
eugenp/tutorials
jbang/hellocli.java
324
/* * 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.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.CompatibleWith; import com.google.errorprone.annotations.DoNotMock; import java.util.Collection; import java.util.Map; import java.util.Set; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A collection that associates an ordered pair of keys, called a row key and a column key, with a * single value. A table may be sparse, with only a small fraction of row key / column key pairs * possessing a corresponding value. * * <p>The mappings corresponding to a given row key may be viewed as a {@link Map} whose keys are * the columns. The reverse is also available, associating a column with a row key / value map. Note * that, in some implementations, data access by column key may have fewer supported operations or * worse performance than data access by row key. * * <p>The methods returning collections or maps always return views of the underlying table. * Updating the table can change the contents of those collections, and updating the collections * will change the table. * * <p>All methods that modify the table are optional, and the views returned by the table may or may * not be modifiable. When modification isn't supported, those methods will throw an {@link * UnsupportedOperationException}. * * <h3>Implementations</h3> * * <ul> * <li>{@link ImmutableTable} * <li>{@link HashBasedTable} * <li>{@link TreeBasedTable} * <li>{@link ArrayTable} * <li>{@link Tables#newCustomTable Tables.newCustomTable} * </ul> * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">{@code Table}</a>. * * @author Jared Levy * @param <R> the type of the table row keys * @param <C> the type of the table column keys * @param <V> the type of the mapped values * @since 7.0 */ @DoNotMock("Use ImmutableTable, HashBasedTable, or another implementation") @GwtCompatible @ElementTypesAreNonnullByDefault public interface Table< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> { // TODO(jlevy): Consider adding methods similar to ConcurrentMap methods. // Accessors /** * Returns {@code true} if the table contains a mapping with the specified row and column keys. * * @param rowKey key of row to search for * @param columnKey key of column to search for */ boolean contains( @CompatibleWith("R") @CheckForNull Object rowKey, @CompatibleWith("C") @CheckForNull Object columnKey); /** * Returns {@code true} if the table contains a mapping with the specified row key. * * @param rowKey key of row to search for */ boolean containsRow(@CompatibleWith("R") @CheckForNull Object rowKey); /** * Returns {@code true} if the table contains a mapping with the specified column. * * @param columnKey key of column to search for */ boolean containsColumn(@CompatibleWith("C") @CheckForNull Object columnKey); /** * Returns {@code true} if the table contains a mapping with the specified value. * * @param value value to search for */ boolean containsValue(@CompatibleWith("V") @CheckForNull Object value); /** * Returns the value corresponding to the given row and column keys, or {@code null} if no such * mapping exists. * * @param rowKey key of row to search for * @param columnKey key of column to search for */ @CheckForNull V get( @CompatibleWith("R") @CheckForNull Object rowKey, @CompatibleWith("C") @CheckForNull Object columnKey); /** Returns {@code true} if the table contains no mappings. */ boolean isEmpty(); /** Returns the number of row key / column key / value mappings in the table. */ int size(); /** * Compares the specified object with this table for equality. Two tables are equal when their * cell views, as returned by {@link #cellSet}, are equal. */ @Override boolean equals(@CheckForNull Object obj); /** * Returns the hash code for this table. The hash code of a table is defined as the hash code of * its cell view, as returned by {@link #cellSet}. */ @Override int hashCode(); // Mutators /** Removes all mappings from the table. */ void clear(); /** * Associates the specified value with the specified keys. If the table already contained a * mapping for those keys, the old value is replaced with the specified value. * * @param rowKey row key that the value should be associated with * @param columnKey column key that the value should be associated with * @param value value to be associated with the specified keys * @return the value previously associated with the keys, or {@code null} if no mapping existed * for the keys */ @CanIgnoreReturnValue @CheckForNull V put(@ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value); /** * Copies all mappings from the specified table to this table. The effect is equivalent to calling * {@link #put} with each row key / column key / value mapping in {@code table}. * * @param table the table to add to this table */ void putAll(Table<? extends R, ? extends C, ? extends V> table); /** * Removes the mapping, if any, associated with the given keys. * * @param rowKey row key of mapping to be removed * @param columnKey column key of mapping to be removed * @return the value previously associated with the keys, or {@code null} if no such value existed */ @CanIgnoreReturnValue @CheckForNull V remove( @CompatibleWith("R") @CheckForNull Object rowKey, @CompatibleWith("C") @CheckForNull Object columnKey); // Views /** * Returns a view of all mappings that have the given row key. For each row key / column key / * value mapping in the table with that row key, the returned map associates the column key with * the value. If no mappings in the table have the provided row key, an empty map is returned. * * <p>Changes to the returned map will update the underlying table, and vice versa. * * @param rowKey key of row to search for in the table * @return the corresponding map from column keys to values */ Map<C, V> row(@ParametricNullness R rowKey); /** * Returns a view of all mappings that have the given column key. For each row key / column key / * value mapping in the table with that column key, the returned map associates the row key with * the value. If no mappings in the table have the provided column key, an empty map is returned. * * <p>Changes to the returned map will update the underlying table, and vice versa. * * @param columnKey key of column to search for in the table * @return the corresponding map from row keys to values */ Map<R, V> column(@ParametricNullness C columnKey); /** * Returns a set of all row key / column key / value triplets. Changes to the returned set will * update the underlying table, and vice versa. The cell set does not support the {@code add} or * {@code addAll} methods. * * @return set of table cells consisting of row key / column key / value triplets */ Set<Cell<R, C, V>> cellSet(); /** * Returns a set of row keys that have one or more values in the table. Changes to the set will * update the underlying table, and vice versa. * * @return set of row keys */ Set<R> rowKeySet(); /** * Returns a set of column keys that have one or more values in the table. Changes to the set will * update the underlying table, and vice versa. * * @return set of column keys */ Set<C> columnKeySet(); /** * Returns a collection of all values, which may contain duplicates. Changes to the returned * collection will update the underlying table, and vice versa. * * @return collection of values */ Collection<V> values(); /** * Returns a view that associates each row key with the corresponding map from column keys to * values. Changes to the returned map will update this table. The returned map does not support * {@code put()} or {@code putAll()}, or {@code setValue()} on its entries. * * <p>In contrast, the maps returned by {@code rowMap().get()} have the same behavior as those * returned by {@link #row}. Those maps may support {@code setValue()}, {@code put()}, and {@code * putAll()}. * * @return a map view from each row key to a secondary map from column keys to values */ Map<R, Map<C, V>> rowMap(); /** * Returns a view that associates each column key with the corresponding map from row keys to * values. Changes to the returned map will update this table. The returned map does not support * {@code put()} or {@code putAll()}, or {@code setValue()} on its entries. * * <p>In contrast, the maps returned by {@code columnMap().get()} have the same behavior as those * returned by {@link #column}. Those maps may support {@code setValue()}, {@code put()}, and * {@code putAll()}. * * @return a map view from each column key to a secondary map from row keys to values */ Map<C, Map<R, V>> columnMap(); /** * Row key / column key / value triplet corresponding to a mapping in a table. * * @since 7.0 */ interface Cell< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> { /** Returns the row key of this cell. */ @ParametricNullness R getRowKey(); /** Returns the column key of this cell. */ @ParametricNullness C getColumnKey(); /** Returns the value of this cell. */ @ParametricNullness V getValue(); /** * Compares the specified object with this cell for equality. Two cells are equal when they have * equal row keys, column keys, and values. */ @Override boolean equals(@CheckForNull Object obj); /** * Returns the hash code of this cell. * * <p>The hash code of a table cell is equal to {@link Objects#hashCode}{@code (e.getRowKey(), * e.getColumnKey(), e.getValue())}. */ @Override int hashCode(); } }
google/guava
guava/src/com/google/common/collect/Table.java
326
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.http; import org.elasticsearch.common.collect.Iterators; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.xcontent.ChunkedToXContent; import org.elasticsearch.xcontent.ToXContent; import org.elasticsearch.xcontent.ToXContentFragment; import org.elasticsearch.xcontent.XContentBuilder; import java.io.IOException; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.stream.Collectors; import java.util.stream.Stream; import static org.elasticsearch.TransportVersions.V_8_12_0; public record HttpStats(long serverOpen, long totalOpen, List<ClientStats> clientStats, Map<String, HttpRouteStats> httpRouteStats) implements Writeable, ChunkedToXContent { public static final HttpStats IDENTITY = new HttpStats(0, 0, List.of(), Map.of()); public HttpStats(long serverOpen, long totalOpened) { this(serverOpen, totalOpened, List.of(), Map.of()); } public HttpStats(StreamInput in) throws IOException { this( in.readVLong(), in.readVLong(), in.readCollectionAsList(ClientStats::new), in.getTransportVersion().onOrAfter(V_8_12_0) ? in.readMap(HttpRouteStats::new) : Map.of() ); } @Override public void writeTo(StreamOutput out) throws IOException { out.writeVLong(serverOpen); out.writeVLong(totalOpen); out.writeCollection(clientStats); if (out.getTransportVersion().onOrAfter(V_8_12_0)) { out.writeMap(httpRouteStats, StreamOutput::writeWriteable); } } public long getServerOpen() { return this.serverOpen; } public long getTotalOpen() { return this.totalOpen; } public List<ClientStats> getClientStats() { return this.clientStats; } public static HttpStats merge(HttpStats first, HttpStats second) { return new HttpStats( first.serverOpen + second.serverOpen, first.totalOpen + second.totalOpen, Stream.concat(first.clientStats.stream(), second.clientStats.stream()).toList(), Stream.concat(first.httpRouteStats.entrySet().stream(), second.httpRouteStats.entrySet().stream()) .collect(Collectors.toUnmodifiableMap(Map.Entry::getKey, Map.Entry::getValue, HttpRouteStats::merge)) ); } static final class Fields { static final String HTTP = "http"; static final String CURRENT_OPEN = "current_open"; static final String TOTAL_OPENED = "total_opened"; static final String CLIENTS = "clients"; static final String CLIENT_ID = "id"; static final String CLIENT_AGENT = "agent"; static final String CLIENT_LOCAL_ADDRESS = "local_address"; static final String CLIENT_REMOTE_ADDRESS = "remote_address"; static final String CLIENT_LAST_URI = "last_uri"; static final String CLIENT_OPENED_TIME_MILLIS = "opened_time_millis"; static final String CLIENT_CLOSED_TIME_MILLIS = "closed_time_millis"; static final String CLIENT_LAST_REQUEST_TIME_MILLIS = "last_request_time_millis"; static final String CLIENT_REQUEST_COUNT = "request_count"; static final String CLIENT_REQUEST_SIZE_BYTES = "request_size_bytes"; static final String CLIENT_FORWARDED_FOR = "x_forwarded_for"; static final String CLIENT_OPAQUE_ID = "x_opaque_id"; static final String ROUTES = "routes"; } @Override public Iterator<? extends ToXContent> toXContentChunked(ToXContent.Params outerParams) { return Iterators.<ToXContent>concat( Iterators.single( (builder, params) -> builder.startObject(Fields.HTTP) .field(Fields.CURRENT_OPEN, serverOpen) .field(Fields.TOTAL_OPENED, totalOpen) .startArray(Fields.CLIENTS) ), clientStats.iterator(), Iterators.single((builder, params) -> { builder.endArray(); builder.startObject(Fields.ROUTES); return builder; }), Iterators.map(httpRouteStats.entrySet().iterator(), entry -> (builder, params) -> { builder.field(entry.getKey()); entry.getValue().toXContent(builder, params); return builder; }), Iterators.single((builder, params) -> builder.endObject().endObject()) ); } public record ClientStats( int id, String agent, String localAddress, String remoteAddress, String lastUri, String forwardedFor, String opaqueId, long openedTimeMillis, long closedTimeMillis, long lastRequestTimeMillis, long requestCount, long requestSizeBytes ) implements Writeable, ToXContentFragment { public static final long NOT_CLOSED = -1L; ClientStats(StreamInput in) throws IOException { this( in.readInt(), in.readOptionalString(), in.readOptionalString(), in.readOptionalString(), in.readOptionalString(), in.readOptionalString(), in.readOptionalString(), in.readLong(), in.readLong(), in.readLong(), in.readLong(), in.readLong() ); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.startObject(); builder.field(Fields.CLIENT_ID, id); if (agent != null) { builder.field(Fields.CLIENT_AGENT, agent); } if (localAddress != null) { builder.field(Fields.CLIENT_LOCAL_ADDRESS, localAddress); } if (remoteAddress != null) { builder.field(Fields.CLIENT_REMOTE_ADDRESS, remoteAddress); } if (lastUri != null) { builder.field(Fields.CLIENT_LAST_URI, lastUri); } if (forwardedFor != null) { builder.field(Fields.CLIENT_FORWARDED_FOR, forwardedFor); } if (opaqueId != null) { builder.field(Fields.CLIENT_OPAQUE_ID, opaqueId); } builder.field(Fields.CLIENT_OPENED_TIME_MILLIS, openedTimeMillis); if (closedTimeMillis != NOT_CLOSED) { builder.field(Fields.CLIENT_CLOSED_TIME_MILLIS, closedTimeMillis); } builder.field(Fields.CLIENT_LAST_REQUEST_TIME_MILLIS, lastRequestTimeMillis); builder.field(Fields.CLIENT_REQUEST_COUNT, requestCount); builder.field(Fields.CLIENT_REQUEST_SIZE_BYTES, requestSizeBytes); builder.endObject(); return builder; } @Override public void writeTo(StreamOutput out) throws IOException { out.writeInt(id); out.writeOptionalString(agent); out.writeOptionalString(localAddress); out.writeOptionalString(remoteAddress); out.writeOptionalString(lastUri); out.writeOptionalString(forwardedFor); out.writeOptionalString(opaqueId); out.writeLong(openedTimeMillis); out.writeLong(closedTimeMillis); out.writeLong(lastRequestTimeMillis); out.writeLong(requestCount); out.writeLong(requestSizeBytes); } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/http/HttpStats.java
327
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.IOException; import java.util.AbstractList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * An object which joins pieces of text (specified as an array, {@link Iterable}, varargs or even a * {@link Map}) with a separator. It either appends the results to an {@link Appendable} or returns * them as a {@link String}. Example: * * <pre>{@code * Joiner joiner = Joiner.on("; ").skipNulls(); * . . . * return joiner.join("Harry", null, "Ron", "Hermione"); * }</pre> * * <p>This returns the string {@code "Harry; Ron; Hermione"}. Note that all input elements are * converted to strings using {@link Object#toString()} before being appended. * * <p>If neither {@link #skipNulls()} nor {@link #useForNull(String)} is specified, the joining * methods will throw {@link NullPointerException} if any given element is null. * * <p><b>Warning: joiner instances are always immutable</b>; a configuration method such as {@code * useForNull} has no effect on the instance it is invoked on! You must store and use the new joiner * instance returned by the method. This makes joiners thread-safe, and safe to store as {@code * static final} constants. * * <pre>{@code * // Bad! Do not do this! * Joiner joiner = Joiner.on(','); * joiner.skipNulls(); // does nothing! * return joiner.join("wrong", null, "wrong"); * }</pre> * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/StringsExplained#joiner">{@code Joiner}</a>. * * @author Kevin Bourrillion * @since 2.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public class Joiner { /** Returns a joiner which automatically places {@code separator} between consecutive elements. */ public static Joiner on(String separator) { return new Joiner(separator); } /** Returns a joiner which automatically places {@code separator} between consecutive elements. */ public static Joiner on(char separator) { return new Joiner(String.valueOf(separator)); } private final String separator; private Joiner(String separator) { this.separator = checkNotNull(separator); } private Joiner(Joiner prototype) { this.separator = prototype.separator; } /* * In this file, we use <? extends @Nullable Object> instead of <?> to work around a Kotlin bug * (see b/189937072 until we file a bug against Kotlin itself). (The two should be equivalent, so * we normally prefer the shorter one.) */ /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code appendable}. */ @CanIgnoreReturnValue public <A extends Appendable> A appendTo(A appendable, Iterable<? extends @Nullable Object> parts) throws IOException { return appendTo(appendable, parts.iterator()); } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code appendable}. * * @since 11.0 */ @CanIgnoreReturnValue public <A extends Appendable> A appendTo(A appendable, Iterator<? extends @Nullable Object> parts) throws IOException { checkNotNull(appendable); if (parts.hasNext()) { appendable.append(toString(parts.next())); while (parts.hasNext()) { appendable.append(separator); appendable.append(toString(parts.next())); } } return appendable; } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code appendable}. */ @CanIgnoreReturnValue public final <A extends Appendable> A appendTo(A appendable, @Nullable Object[] parts) throws IOException { @SuppressWarnings("nullness") // TODO: b/316358623 - Remove suppression after fixing checker List<?> partsList = Arrays.<@Nullable Object>asList(parts); return appendTo(appendable, partsList); } /** Appends to {@code appendable} the string representation of each of the remaining arguments. */ @CanIgnoreReturnValue public final <A extends Appendable> A appendTo( A appendable, @CheckForNull Object first, @CheckForNull Object second, @Nullable Object... rest) throws IOException { return appendTo(appendable, iterable(first, second, rest)); } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable, * Iterable)}, except that it does not throw {@link IOException}. */ @CanIgnoreReturnValue public final StringBuilder appendTo( StringBuilder builder, Iterable<? extends @Nullable Object> parts) { return appendTo(builder, parts.iterator()); } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable, * Iterable)}, except that it does not throw {@link IOException}. * * @since 11.0 */ @CanIgnoreReturnValue public final StringBuilder appendTo( StringBuilder builder, Iterator<? extends @Nullable Object> parts) { try { appendTo((Appendable) builder, parts); } catch (IOException impossible) { throw new AssertionError(impossible); } return builder; } /** * Appends the string representation of each of {@code parts}, using the previously configured * separator between each, to {@code builder}. Identical to {@link #appendTo(Appendable, * Iterable)}, except that it does not throw {@link IOException}. */ @CanIgnoreReturnValue public final StringBuilder appendTo(StringBuilder builder, @Nullable Object[] parts) { @SuppressWarnings("nullness") // TODO: b/316358623 - Remove suppression after fixing checker List<?> partsList = Arrays.<@Nullable Object>asList(parts); return appendTo(builder, partsList); } /** * Appends to {@code builder} the string representation of each of the remaining arguments. * Identical to {@link #appendTo(Appendable, Object, Object, Object...)}, except that it does not * throw {@link IOException}. */ @CanIgnoreReturnValue public final StringBuilder appendTo( StringBuilder builder, @CheckForNull Object first, @CheckForNull Object second, @Nullable Object... rest) { return appendTo(builder, iterable(first, second, rest)); } /** * Returns a string containing the string representation of each of {@code parts}, using the * previously configured separator between each. */ public final String join(Iterable<? extends @Nullable Object> parts) { return join(parts.iterator()); } /** * Returns a string containing the string representation of each of {@code parts}, using the * previously configured separator between each. * * @since 11.0 */ public final String join(Iterator<? extends @Nullable Object> parts) { return appendTo(new StringBuilder(), parts).toString(); } /** * Returns a string containing the string representation of each of {@code parts}, using the * previously configured separator between each. */ public final String join(@Nullable Object[] parts) { @SuppressWarnings("nullness") // TODO: b/316358623 - Remove suppression after fixing checker List<?> partsList = Arrays.<@Nullable Object>asList(parts); return join(partsList); } /** * Returns a string containing the string representation of each argument, using the previously * configured separator between each. */ public final String join( @CheckForNull Object first, @CheckForNull Object second, @Nullable Object... rest) { return join(iterable(first, second, rest)); } /** * Returns a joiner with the same behavior as this one, except automatically substituting {@code * nullText} for any provided null elements. */ public Joiner useForNull(String nullText) { checkNotNull(nullText); return new Joiner(this) { @Override CharSequence toString(@CheckForNull Object part) { return (part == null) ? nullText : Joiner.this.toString(part); } @Override public Joiner useForNull(String nullText) { throw new UnsupportedOperationException("already specified useForNull"); } @Override public Joiner skipNulls() { throw new UnsupportedOperationException("already specified useForNull"); } }; } /** * Returns a joiner with the same behavior as this joiner, except automatically skipping over any * provided null elements. */ public Joiner skipNulls() { return new Joiner(this) { @Override public <A extends Appendable> A appendTo( A appendable, Iterator<? extends @Nullable Object> parts) throws IOException { checkNotNull(appendable, "appendable"); checkNotNull(parts, "parts"); while (parts.hasNext()) { Object part = parts.next(); if (part != null) { appendable.append(Joiner.this.toString(part)); break; } } while (parts.hasNext()) { Object part = parts.next(); if (part != null) { appendable.append(separator); appendable.append(Joiner.this.toString(part)); } } return appendable; } @Override public Joiner useForNull(String nullText) { throw new UnsupportedOperationException("already specified skipNulls"); } @Override public MapJoiner withKeyValueSeparator(String kvs) { throw new UnsupportedOperationException("can't use .skipNulls() with maps"); } }; } /** * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as * this {@code Joiner} otherwise. * * @since 20.0 */ public MapJoiner withKeyValueSeparator(char keyValueSeparator) { return withKeyValueSeparator(String.valueOf(keyValueSeparator)); } /** * Returns a {@code MapJoiner} using the given key-value separator, and the same configuration as * this {@code Joiner} otherwise. */ public MapJoiner withKeyValueSeparator(String keyValueSeparator) { return new MapJoiner(this, keyValueSeparator); } /** * An object that joins map entries in the same manner as {@code Joiner} joins iterables and * arrays. Like {@code Joiner}, it is thread-safe and immutable. * * <p>In addition to operating on {@code Map} instances, {@code MapJoiner} can operate on {@code * Multimap} entries in two distinct modes: * * <ul> * <li>To output a separate entry for each key-value pair, pass {@code multimap.entries()} to a * {@code MapJoiner} method that accepts entries as input, and receive output of the form * {@code key1=A&key1=B&key2=C}. * <li>To output a single entry for each key, pass {@code multimap.asMap()} to a {@code * MapJoiner} method that accepts a map as input, and receive output of the form {@code * key1=[A, B]&key2=C}. * </ul> * * @since 2.0 */ public static final class MapJoiner { private final Joiner joiner; private final String keyValueSeparator; private MapJoiner(Joiner joiner, String keyValueSeparator) { this.joiner = joiner; // only "this" is ever passed, so don't checkNotNull this.keyValueSeparator = checkNotNull(keyValueSeparator); } /** * Appends the string representation of each entry of {@code map}, using the previously * configured separator and key-value separator, to {@code appendable}. */ @CanIgnoreReturnValue public <A extends Appendable> A appendTo(A appendable, Map<?, ?> map) throws IOException { return appendTo(appendable, map.entrySet()); } /** * Appends the string representation of each entry of {@code map}, using the previously * configured separator and key-value separator, to {@code builder}. Identical to {@link * #appendTo(Appendable, Map)}, except that it does not throw {@link IOException}. */ @CanIgnoreReturnValue public StringBuilder appendTo(StringBuilder builder, Map<?, ?> map) { return appendTo(builder, map.entrySet()); } /** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code appendable}. * * @since 10.0 */ @CanIgnoreReturnValue public <A extends Appendable> A appendTo(A appendable, Iterable<? extends Entry<?, ?>> entries) throws IOException { return appendTo(appendable, entries.iterator()); } /** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code appendable}. * * @since 11.0 */ @CanIgnoreReturnValue public <A extends Appendable> A appendTo(A appendable, Iterator<? extends Entry<?, ?>> parts) throws IOException { checkNotNull(appendable); if (parts.hasNext()) { Entry<?, ?> entry = parts.next(); appendable.append(joiner.toString(entry.getKey())); appendable.append(keyValueSeparator); appendable.append(joiner.toString(entry.getValue())); while (parts.hasNext()) { appendable.append(joiner.separator); Entry<?, ?> e = parts.next(); appendable.append(joiner.toString(e.getKey())); appendable.append(keyValueSeparator); appendable.append(joiner.toString(e.getValue())); } } return appendable; } /** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code builder}. Identical to {@link * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}. * * @since 10.0 */ @CanIgnoreReturnValue public StringBuilder appendTo(StringBuilder builder, Iterable<? extends Entry<?, ?>> entries) { return appendTo(builder, entries.iterator()); } /** * Appends the string representation of each entry in {@code entries}, using the previously * configured separator and key-value separator, to {@code builder}. Identical to {@link * #appendTo(Appendable, Iterable)}, except that it does not throw {@link IOException}. * * @since 11.0 */ @CanIgnoreReturnValue public StringBuilder appendTo(StringBuilder builder, Iterator<? extends Entry<?, ?>> entries) { try { appendTo((Appendable) builder, entries); } catch (IOException impossible) { throw new AssertionError(impossible); } return builder; } /** * Returns a string containing the string representation of each entry of {@code map}, using the * previously configured separator and key-value separator. */ public String join(Map<?, ?> map) { return join(map.entrySet()); } /** * Returns a string containing the string representation of each entry in {@code entries}, using * the previously configured separator and key-value separator. * * @since 10.0 */ public String join(Iterable<? extends Entry<?, ?>> entries) { return join(entries.iterator()); } /** * Returns a string containing the string representation of each entry in {@code entries}, using * the previously configured separator and key-value separator. * * @since 11.0 */ public String join(Iterator<? extends Entry<?, ?>> entries) { return appendTo(new StringBuilder(), entries).toString(); } /** * Returns a map joiner with the same behavior as this one, except automatically substituting * {@code nullText} for any provided null keys or values. */ public MapJoiner useForNull(String nullText) { return new MapJoiner(joiner.useForNull(nullText), keyValueSeparator); } } CharSequence toString(@CheckForNull Object part) { /* * requireNonNull is not safe: Joiner.on(...).join(somethingThatContainsNull) will indeed throw. * However, Joiner.on(...).useForNull(...).join(somethingThatContainsNull) *is* safe -- because * it returns a subclass of Joiner that overrides this method to tolerate null inputs. * * Unfortunately, we don't distinguish between these two cases in our public API: Joiner.on(...) * and Joiner.on(...).useForNull(...) both declare the same return type: plain Joiner. To ensure * that users *can* pass null arguments to Joiner, we annotate it as if it always tolerates null * inputs, rather than as if it never tolerates them. * * We rely on checkers to implement special cases to catch dangerous calls to join(), etc. based * on what they know about the particular Joiner instances the calls are performed on. * * (In addition to useForNull, we also offer skipNulls. It, too, tolerates null inputs, but its * tolerance is implemented differently: Its implementation avoids calling this toString(Object) * method in the first place.) */ requireNonNull(part); return (part instanceof CharSequence) ? (CharSequence) part : part.toString(); } private static Iterable<@Nullable Object> iterable( @CheckForNull Object first, @CheckForNull Object second, @Nullable Object[] rest) { checkNotNull(rest); return new AbstractList<@Nullable Object>() { @Override public int size() { return rest.length + 2; } @Override @CheckForNull public Object get(int index) { switch (index) { case 0: return first; case 1: return second; default: return rest[index - 2]; } } }; } }
google/guava
android/guava/src/com/google/common/base/Joiner.java
328
/* * 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.io; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.BufferedWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; /** * A destination to which characters can be written, such as a text file. Unlike a {@link Writer}, a * {@code CharSink} is not an open, stateful stream that can be written to and closed. Instead, it * is an immutable <i>supplier</i> of {@code Writer} instances. * * <p>{@code CharSink} provides two kinds of methods: * * <ul> * <li><b>Methods that return a writer:</b> These methods should return a <i>new</i>, independent * instance each time they are called. The caller is responsible for ensuring that the * returned writer is closed. * <li><b>Convenience methods:</b> These are implementations of common operations that are * typically implemented by opening a writer using one of the methods in the first category, * doing something and finally closing the writer that was opened. * </ul> * * <p>Any {@link ByteSink} may be viewed as a {@code CharSink} with a specific {@linkplain Charset * character encoding} using {@link ByteSink#asCharSink(Charset)}. Characters written to the * resulting {@code CharSink} will written to the {@code ByteSink} as encoded bytes. * * @since 14.0 * @author Colin Decker */ @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public abstract class CharSink { /** Constructor for use by subclasses. */ protected CharSink() {} /** * Opens a new {@link Writer} for writing to this sink. This method returns a new, independent * writer each time it is called. * * <p>The caller is responsible for ensuring that the returned writer is closed. * * @throws IOException if an I/O error occurs while opening the writer */ public abstract Writer openStream() throws IOException; /** * Opens a new buffered {@link Writer} for writing to this sink. The returned stream is not * required to be a {@link BufferedWriter} in order to allow implementations to simply delegate to * {@link #openStream()} when the stream returned by that method does not benefit from additional * buffering. This method returns a new, independent writer each time it is called. * * <p>The caller is responsible for ensuring that the returned writer is closed. * * @throws IOException if an I/O error occurs while opening the writer * @since 15.0 (in 14.0 with return type {@link BufferedWriter}) */ public Writer openBufferedStream() throws IOException { Writer writer = openStream(); return (writer instanceof BufferedWriter) ? (BufferedWriter) writer : new BufferedWriter(writer); } /** * Writes the given character sequence to this sink. * * @throws IOException if an I/O error while writing to this sink */ public void write(CharSequence charSequence) throws IOException { checkNotNull(charSequence); Closer closer = Closer.create(); try { Writer out = closer.register(openStream()); out.append(charSequence); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Writes the given lines of text to this sink with each line (including the last) terminated with * the operating system's default line separator. This method is equivalent to {@code * writeLines(lines, System.getProperty("line.separator"))}. * * @throws IOException if an I/O error occurs while writing to this sink */ public void writeLines(Iterable<? extends CharSequence> lines) throws IOException { writeLines(lines, System.getProperty("line.separator")); } /** * Writes the given lines of text to this sink with each line (including the last) terminated with * the given line separator. * * @throws IOException if an I/O error occurs while writing to this sink */ public void writeLines(Iterable<? extends CharSequence> lines, String lineSeparator) throws IOException { checkNotNull(lines); checkNotNull(lineSeparator); Closer closer = Closer.create(); try { Writer out = closer.register(openBufferedStream()); for (CharSequence line : lines) { out.append(line).append(lineSeparator); } out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Writes all the text from the given {@link Readable} (such as a {@link Reader}) to this sink. * Does not close {@code readable} if it is {@code Closeable}. * * @return the number of characters written * @throws IOException if an I/O error occurs while reading from {@code readable} or writing to * this sink */ @CanIgnoreReturnValue public long writeFrom(Readable readable) throws IOException { checkNotNull(readable); Closer closer = Closer.create(); try { Writer out = closer.register(openStream()); long written = CharStreams.copy(readable, out); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 return written; } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } }
google/guava
android/guava/src/com/google/common/io/CharSink.java
329
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.script; import java.time.Instant; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Objects; import java.util.Set; import java.util.function.BiConsumer; import java.util.stream.Collectors; /** * Ingest and update metadata available to write scripts. * * Provides a map-like interface for backwards compatibility with the ctx map. * - {@link #put(String, Object)} * - {@link #get(String)} * - {@link #remove(String)} * - {@link #containsKey(String)} * - {@link #containsValue(Object)} * - {@link #keySet()} for iteration * - {@link #size()} * - {@link #isAvailable(String)} for determining if a key is a metadata key * * Provides getters and setters for script usage. * * Validates all updates whether originating in map-like interface or setters. */ public class Metadata { protected static final String INDEX = "_index"; protected static final String ID = "_id"; protected static final String ROUTING = "_routing"; protected static final String VERSION_TYPE = "_version_type"; protected static final String VERSION = "_version"; protected static final String TYPE = "_type"; // type is deprecated, so it's supported in the map but not available as a getter protected static final String NOW = "_now"; protected static final String OP = "op"; protected static final String IF_SEQ_NO = "_if_seq_no"; protected static final String IF_PRIMARY_TERM = "_if_primary_term"; protected static final String DYNAMIC_TEMPLATES = "_dynamic_templates"; public static FieldProperty<Object> ObjectField = new FieldProperty<>(Object.class); public static FieldProperty<String> StringField = new FieldProperty<>(String.class); public static FieldProperty<Number> LongField = new FieldProperty<>(Number.class).withValidation(FieldProperty.LONGABLE_NUMBER); protected final Map<String, Object> map; private final Map<String, FieldProperty<?>> properties; protected static final FieldProperty<?> BAD_KEY = new FieldProperty<>(null, false, false, null); /** * Constructs a new Metadata object represented by the given map and properties. * <p> * The passed-in map is used directly -- subsequent modifications to it outside the methods of this class may result in * undefined behavior. Note also that mutation-like methods (e.g. setters, etc) on this class rely on the map being mutable, * which is the expected use for this class. * <p> * The properties map is used directly as well, but we verify at runtime that it <b>must</b> be an immutable map (i.e. constructed * via a call to {@link Map#of()} (or similar) in production, or via {@link Map#copyOf(Map)}} in tests). Since it must be an * immutable map, subsequent modifications are not possible. * * @param map the backing map for this metadata instance * @param properties the immutable map of defined properties for the type of metadata represented by this instance */ @SuppressWarnings("this-escape") protected Metadata(Map<String, Object> map, Map<String, FieldProperty<?>> properties) { this.map = map; // we can't tell the compiler that properties must be a java.util.ImmutableCollections.AbstractImmutableMap, but // we can use this copyOf + assert to verify that at runtime. this.properties = Map.copyOf(properties); assert this.properties == properties : "properties map must be constructed via Map.of(...) or Map.copyOf(...)"; validateMetadata(); } // a 'not found' sentinel value for use in validateMetadata below private static final Object NOT_FOUND = new Object(); /** * Check that all metadata map contains only valid metadata and no extraneous keys */ protected void validateMetadata() { int numMetadata = 0; for (Map.Entry<String, FieldProperty<?>> entry : properties.entrySet()) { String key = entry.getKey(); Object value = map.getOrDefault(key, NOT_FOUND); // getOrDefault is faster than containsKey + get if (value == NOT_FOUND) { // check whether it's permissible to *not* have a value for the property entry.getValue().check(MapOperation.INIT, key, null); } else { numMetadata++; entry.getValue().check(MapOperation.INIT, key, value); } } if (numMetadata < map.size()) { Set<String> keys = new HashSet<>(map.keySet()); keys.removeAll(properties.keySet()); throw new IllegalArgumentException( "Unexpected metadata keys [" + keys.stream().sorted().map(k -> k + ":" + map.get(k)).collect(Collectors.joining(", ")) + "]" ); } } // These are available to scripts public String getIndex() { return getString(INDEX); } public void setIndex(String index) { put(INDEX, index); } public String getId() { return getString(ID); } public void setId(String id) { put(ID, id); } public String getRouting() { return getString(ROUTING); } public void setRouting(String routing) { put(ROUTING, routing); } public String getVersionType() { return getString(VERSION_TYPE); } public void setVersionType(String versionType) { put(VERSION_TYPE, versionType); } public long getVersion() { return getNumber(VERSION).longValue(); } public void setVersion(long version) { put(VERSION, version); } public ZonedDateTime getNow() { return ZonedDateTime.ofInstant(Instant.ofEpochMilli(getNumber(NOW).longValue()), ZoneOffset.UTC); } public String getOp() { return getString(OP); } public void setOp(String op) { put(OP, op); } // These are not available to scripts public Number getIfSeqNo() { return getNumber(IF_SEQ_NO); } public Number getIfPrimaryTerm() { return getNumber(IF_PRIMARY_TERM); } @SuppressWarnings("unchecked") public Map<String, String> getDynamicTemplates() { return (Map<String, String>) get(DYNAMIC_TEMPLATES); } /** * Get the String version of the value associated with {@code key}, or null */ protected String getString(String key) { return Objects.toString(get(key), null); } /** * Get the {@link Number} associated with key, or null * @throws IllegalArgumentException if the value is not a {@link Number} */ protected Number getNumber(String key) { Object value = get(key); if (value == null) { return null; } if (value instanceof Number number) { return number; } throw new IllegalStateException( "unexpected type for [" + key + "] with value [" + value + "], expected Number, got [" + value.getClass().getName() + "]" ); } /** * Is this key a Metadata key? A {@link #remove}d key would return false for {@link #containsKey(String)} but true for * this call. */ public boolean isAvailable(String key) { return properties.containsKey(key); } /** * Create the mapping from key to value. * @throws IllegalArgumentException if {@link #isAvailable(String)} is false or the key cannot be updated to the value. */ public Object put(String key, Object value) { properties.getOrDefault(key, Metadata.BAD_KEY).check(MapOperation.UPDATE, key, value); return map.put(key, value); } /** * Does the metadata contain the key? */ public boolean containsKey(String key) { return map.containsKey(key); } /** * Does the metadata contain the value. */ public boolean containsValue(Object value) { return map.containsValue(value); } /** * Get the value associated with {@param key} */ public Object get(String key) { return map.get(key); } /** * Remove the mapping associated with {@param key} * @throws IllegalArgumentException if {@link #isAvailable(String)} is false or the key cannot be removed. */ public Object remove(String key) { properties.getOrDefault(key, Metadata.BAD_KEY).check(MapOperation.REMOVE, key, null); return map.remove(key); } /** * Return the list of keys with mappings */ public Set<String> keySet() { return Collections.unmodifiableSet(map.keySet()); } /** * The number of metadata keys currently mapped. */ public int size() { return map.size(); } @Override public Metadata clone() { // properties is an unmodifiable map, no need to create a copy here return new Metadata(new HashMap<>(map), properties); } /** * Get the backing map, if modified then the guarantees of this class may not hold */ public Map<String, Object> getMap() { return map; } @Override public boolean equals(Object o) { if (this == o) return true; if ((o instanceof Metadata) == false) return false; Metadata metadata = (Metadata) o; return map.equals(metadata.map); } @Override public int hashCode() { return Objects.hash(map); } /** * The operation being performed on the value in the map. * INIT: Initial value - the metadata value as passed into this class * UPDATE: the metadata is being set to a different value * REMOVE: the metadata mapping is being removed */ public enum MapOperation { INIT, UPDATE, REMOVE } /** * The properties of a metadata field. * @param type - the class of the field. Updates must be assignable to this type. If null, no type checking is performed. * @param nullable - can the field value be null and can it be removed * @param writable - can the field be updated after the initial set * @param extendedValidation - value validation after type checking, may be used for values that may be one of a set */ public record FieldProperty<T>(Class<T> type, boolean nullable, boolean writable, BiConsumer<String, T> extendedValidation) { public FieldProperty(Class<T> type) { this(type, false, false, null); } public FieldProperty<T> withNullable() { if (nullable) { return this; } return new FieldProperty<>(type, true, writable, extendedValidation); } public FieldProperty<T> withWritable() { if (writable) { return this; } return new FieldProperty<>(type, nullable, true, extendedValidation); } public FieldProperty<T> withValidation(BiConsumer<String, T> extendedValidation) { if (this.extendedValidation == extendedValidation) { return this; } return new FieldProperty<>(type, nullable, writable, extendedValidation); } public static BiConsumer<String, Number> LONGABLE_NUMBER = (k, v) -> { long version = v.longValue(); // did we round? if (v.doubleValue() == version) { return; } throw new IllegalArgumentException( k + " may only be set to an int or a long but was [" + v + "] with type [" + v.getClass().getName() + "]" ); }; public static FieldProperty<?> ALLOW_ALL = new FieldProperty<>(null, true, true, null); @SuppressWarnings("fallthrough") public void check(MapOperation op, String key, Object value) { switch (op) { case UPDATE: if (writable == false) { throw new IllegalArgumentException(key + " cannot be updated"); } // fall through case INIT: if (value == null) { if (nullable == false) { throw new IllegalArgumentException(key + " cannot be null"); } } else { checkType(key, value); } break; case REMOVE: if (writable == false || nullable == false) { throw new IllegalArgumentException(key + " cannot be removed"); } break; default: throw new IllegalArgumentException("unexpected op [" + op + "] for key [" + key + "] and value [" + value + "]"); } } @SuppressWarnings("unchecked") private void checkType(String key, Object value) { if (type == null) { return; } if (type.isAssignableFrom(value.getClass()) == false) { throw new IllegalArgumentException( key + " [" + value + "] is wrong type, expected assignable to [" + type.getName() + "], not [" + value.getClass().getName() + "]" ); } if (extendedValidation != null) { extendedValidation.accept(key, (T) value); } } } public static BiConsumer<String, String> stringSetValidator(Set<String> valid) { return (k, v) -> { if (valid.contains(v) == false) { throw new IllegalArgumentException( "[" + k + "] must be one of " + valid.stream().sorted().collect(Collectors.joining(", ")) + ", not [" + v + "]" ); } }; } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/script/Metadata.java
330
/* * 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.base.Preconditions.checkNotNull; import static com.google.common.collect.BoundType.CLOSED; import static com.google.common.collect.BoundType.OPEN; import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.errorprone.annotations.concurrent.LazyInit; import java.io.Serializable; import java.util.Comparator; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A generalized interval on any ordering, for internal use. Supports {@code null}. Unlike {@link * Range}, this allows the use of an arbitrary comparator. This is designed for use in the * implementation of subcollections of sorted collection types. * * <p>Whenever possible, use {@code Range} instead, which is better supported. * * @author Louis Wasserman */ @GwtCompatible(serializable = true) @ElementTypesAreNonnullByDefault final class GeneralRange<T extends @Nullable Object> implements Serializable { /** Converts a Range to a GeneralRange. */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 static <T extends Comparable> GeneralRange<T> from(Range<T> range) { T lowerEndpoint = range.hasLowerBound() ? range.lowerEndpoint() : null; BoundType lowerBoundType = range.hasLowerBound() ? range.lowerBoundType() : OPEN; T upperEndpoint = range.hasUpperBound() ? range.upperEndpoint() : null; BoundType upperBoundType = range.hasUpperBound() ? range.upperBoundType() : OPEN; return new GeneralRange<>( Ordering.natural(), range.hasLowerBound(), lowerEndpoint, lowerBoundType, range.hasUpperBound(), upperEndpoint, upperBoundType); } /** Returns the whole range relative to the specified comparator. */ static <T extends @Nullable Object> GeneralRange<T> all(Comparator<? super T> comparator) { return new GeneralRange<>(comparator, false, null, OPEN, false, null, OPEN); } /** * Returns everything above the endpoint relative to the specified comparator, with the specified * endpoint behavior. */ static <T extends @Nullable Object> GeneralRange<T> downTo( Comparator<? super T> comparator, @ParametricNullness T endpoint, BoundType boundType) { return new GeneralRange<>(comparator, true, endpoint, boundType, false, null, OPEN); } /** * Returns everything below the endpoint relative to the specified comparator, with the specified * endpoint behavior. */ static <T extends @Nullable Object> GeneralRange<T> upTo( Comparator<? super T> comparator, @ParametricNullness T endpoint, BoundType boundType) { return new GeneralRange<>(comparator, false, null, OPEN, true, endpoint, boundType); } /** * Returns everything between the endpoints relative to the specified comparator, with the * specified endpoint behavior. */ static <T extends @Nullable Object> GeneralRange<T> range( Comparator<? super T> comparator, @ParametricNullness T lower, BoundType lowerType, @ParametricNullness T upper, BoundType upperType) { return new GeneralRange<>(comparator, true, lower, lowerType, true, upper, upperType); } private final Comparator<? super T> comparator; private final boolean hasLowerBound; @CheckForNull private final T lowerEndpoint; private final BoundType lowerBoundType; private final boolean hasUpperBound; @CheckForNull private final T upperEndpoint; private final BoundType upperBoundType; private GeneralRange( Comparator<? super T> comparator, boolean hasLowerBound, @CheckForNull T lowerEndpoint, BoundType lowerBoundType, boolean hasUpperBound, @CheckForNull T upperEndpoint, BoundType upperBoundType) { this.comparator = checkNotNull(comparator); this.hasLowerBound = hasLowerBound; this.hasUpperBound = hasUpperBound; this.lowerEndpoint = lowerEndpoint; this.lowerBoundType = checkNotNull(lowerBoundType); this.upperEndpoint = upperEndpoint; this.upperBoundType = checkNotNull(upperBoundType); // Trigger any exception that the comparator would throw for the endpoints. /* * uncheckedCastNullableTToT is safe as long as the callers are careful to pass a "real" T * whenever they pass `true` for the matching `has*Bound` parameter. */ if (hasLowerBound) { int unused = comparator.compare( uncheckedCastNullableTToT(lowerEndpoint), uncheckedCastNullableTToT(lowerEndpoint)); } if (hasUpperBound) { int unused = comparator.compare( uncheckedCastNullableTToT(upperEndpoint), uncheckedCastNullableTToT(upperEndpoint)); } if (hasLowerBound && hasUpperBound) { int cmp = comparator.compare( uncheckedCastNullableTToT(lowerEndpoint), uncheckedCastNullableTToT(upperEndpoint)); // be consistent with Range checkArgument( cmp <= 0, "lowerEndpoint (%s) > upperEndpoint (%s)", lowerEndpoint, upperEndpoint); if (cmp == 0) { checkArgument(lowerBoundType != OPEN || upperBoundType != OPEN); } } } Comparator<? super T> comparator() { return comparator; } boolean hasLowerBound() { return hasLowerBound; } boolean hasUpperBound() { return hasUpperBound; } boolean isEmpty() { // The casts are safe because of the has*Bound() checks. return (hasUpperBound() && tooLow(uncheckedCastNullableTToT(getUpperEndpoint()))) || (hasLowerBound() && tooHigh(uncheckedCastNullableTToT(getLowerEndpoint()))); } boolean tooLow(@ParametricNullness T t) { if (!hasLowerBound()) { return false; } // The cast is safe because of the hasLowerBound() check. T lbound = uncheckedCastNullableTToT(getLowerEndpoint()); int cmp = comparator.compare(t, lbound); return cmp < 0 | (cmp == 0 & getLowerBoundType() == OPEN); } boolean tooHigh(@ParametricNullness T t) { if (!hasUpperBound()) { return false; } // The cast is safe because of the hasUpperBound() check. T ubound = uncheckedCastNullableTToT(getUpperEndpoint()); int cmp = comparator.compare(t, ubound); return cmp > 0 | (cmp == 0 & getUpperBoundType() == OPEN); } boolean contains(@ParametricNullness T t) { return !tooLow(t) && !tooHigh(t); } /** * Returns the intersection of the two ranges, or an empty range if their intersection is empty. */ @SuppressWarnings("nullness") // TODO(cpovirk): Add casts as needed. Will be noisy and annoying... GeneralRange<T> intersect(GeneralRange<T> other) { checkNotNull(other); checkArgument(comparator.equals(other.comparator)); boolean hasLowBound = this.hasLowerBound; T lowEnd = getLowerEndpoint(); BoundType lowType = getLowerBoundType(); if (!hasLowerBound()) { hasLowBound = other.hasLowerBound; lowEnd = other.getLowerEndpoint(); lowType = other.getLowerBoundType(); } else if (other.hasLowerBound()) { int cmp = comparator.compare(getLowerEndpoint(), other.getLowerEndpoint()); if (cmp < 0 || (cmp == 0 && other.getLowerBoundType() == OPEN)) { lowEnd = other.getLowerEndpoint(); lowType = other.getLowerBoundType(); } } boolean hasUpBound = this.hasUpperBound; T upEnd = getUpperEndpoint(); BoundType upType = getUpperBoundType(); if (!hasUpperBound()) { hasUpBound = other.hasUpperBound; upEnd = other.getUpperEndpoint(); upType = other.getUpperBoundType(); } else if (other.hasUpperBound()) { int cmp = comparator.compare(getUpperEndpoint(), other.getUpperEndpoint()); if (cmp > 0 || (cmp == 0 && other.getUpperBoundType() == OPEN)) { upEnd = other.getUpperEndpoint(); upType = other.getUpperBoundType(); } } if (hasLowBound && hasUpBound) { int cmp = comparator.compare(lowEnd, upEnd); if (cmp > 0 || (cmp == 0 && lowType == OPEN && upType == OPEN)) { // force allowed empty range lowEnd = upEnd; lowType = OPEN; upType = CLOSED; } } return new GeneralRange<>(comparator, hasLowBound, lowEnd, lowType, hasUpBound, upEnd, upType); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof GeneralRange) { GeneralRange<?> r = (GeneralRange<?>) obj; return comparator.equals(r.comparator) && hasLowerBound == r.hasLowerBound && hasUpperBound == r.hasUpperBound && getLowerBoundType().equals(r.getLowerBoundType()) && getUpperBoundType().equals(r.getUpperBoundType()) && Objects.equal(getLowerEndpoint(), r.getLowerEndpoint()) && Objects.equal(getUpperEndpoint(), r.getUpperEndpoint()); } return false; } @Override public int hashCode() { return Objects.hashCode( comparator, getLowerEndpoint(), getLowerBoundType(), getUpperEndpoint(), getUpperBoundType()); } @LazyInit @CheckForNull private transient GeneralRange<T> reverse; /** Returns the same range relative to the reversed comparator. */ GeneralRange<T> reverse() { GeneralRange<T> result = reverse; if (result == null) { result = new GeneralRange<>( Ordering.from(comparator).reverse(), hasUpperBound, getUpperEndpoint(), getUpperBoundType(), hasLowerBound, getLowerEndpoint(), getLowerBoundType()); result.reverse = this; return this.reverse = result; } return result; } @Override public String toString() { return comparator + ":" + (lowerBoundType == CLOSED ? '[' : '(') + (hasLowerBound ? lowerEndpoint : "-\u221e") + ',' + (hasUpperBound ? upperEndpoint : "\u221e") + (upperBoundType == CLOSED ? ']' : ')'); } @CheckForNull T getLowerEndpoint() { return lowerEndpoint; } BoundType getLowerBoundType() { return lowerBoundType; } @CheckForNull T getUpperEndpoint() { return upperEndpoint; } BoundType getUpperBoundType() { return upperBoundType; } }
google/guava
guava/src/com/google/common/collect/GeneralRange.java
331
/* * @notice * * Copyright 2013 The Netty Project * * The Netty Project licenses this file to you 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. * * ============================================================================= * Modifications copyright Elasticsearch B.V. * * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.http; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.settings.SettingsException; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.RestStatus; import org.elasticsearch.rest.RestUtils; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.time.format.DateTimeFormatter; import java.util.Arrays; import java.util.Collections; import java.util.EnumSet; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.regex.Pattern; import java.util.regex.PatternSyntaxException; import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_CREDENTIALS; import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_HEADERS; import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_METHODS; import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ALLOW_ORIGIN; import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_ENABLED; import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_EXPOSE_HEADERS; import static org.elasticsearch.http.HttpTransportSettings.SETTING_CORS_MAX_AGE; /** * This file is forked from the https://netty.io project. In particular it combines the following three * files: io.netty.handler.codec.http.cors.CorsHandler, io.netty.handler.codec.http.cors.CorsConfig, and * io.netty.handler.codec.http.cors.CorsConfigBuilder. * * It modifies the original netty code to operate on Elasticsearch http request/response abstractions. * Additionally, it removes CORS features that are not used by Elasticsearch. */ public class CorsHandler { public static final String ANY_ORIGIN = "*"; public static final String ORIGIN = "origin"; public static final String DATE = "date"; public static final String VARY = "vary"; public static final String HOST = "host"; public static final String ACCESS_CONTROL_REQUEST_METHOD = "access-control-request-method"; public static final String ACCESS_CONTROL_ALLOW_HEADERS = "access-control-allow-headers"; public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "access-control-allow-credentials"; public static final String ACCESS_CONTROL_ALLOW_METHODS = "access-control-allow-methods"; public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "access-control-allow-origin"; public static final String ACCESS_CONTROL_MAX_AGE = "access-control-max-age"; public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "access-control-expose-headers"; private static final Pattern SCHEME_PATTERN = Pattern.compile("^https?://"); private static final DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("EEE, dd MMM yyyy HH:mm:ss O", Locale.ENGLISH); private final Config config; public CorsHandler(Config config) { this.config = config; } public HttpResponse handleInbound(HttpRequest request) { if (config.isCorsSupportEnabled()) { if (isPreflightRequest(request)) { return handlePreflight(request); } if (validateOrigin(request) == false) { return forbidden(request); } } return null; } public void setCorsResponseHeaders(final HttpRequest httpRequest, final HttpResponse httpResponse) { if (config.isCorsSupportEnabled() == false) { return; } if (setOrigin(httpRequest, httpResponse)) { setAllowCredentials(httpResponse); setExposeHeaders(httpResponse); } } private HttpResponse handlePreflight(final HttpRequest request) { final HttpResponse response = request.createResponse(RestStatus.OK, BytesArray.EMPTY); if (setOrigin(request, response)) { setAllowMethods(response); setAllowHeaders(response); setAllowCredentials(response); setMaxAge(response); setPreflightHeaders(response); return response; } else { return forbidden(request); } } private static HttpResponse forbidden(final HttpRequest request) { HttpResponse response = request.createResponse(RestStatus.FORBIDDEN, BytesArray.EMPTY); response.addHeader("content-length", "0"); return response; } private static boolean isSameOrigin(final String origin, final String host) { if (Strings.isNullOrEmpty(host) == false) { // strip protocol from origin final String originDomain = SCHEME_PATTERN.matcher(origin).replaceFirst(""); if (host.equals(originDomain)) { return true; } } return false; } private static void setPreflightHeaders(final HttpResponse response) { response.addHeader(CorsHandler.DATE, dateTimeFormatter.format(ZonedDateTime.now(ZoneOffset.UTC))); response.addHeader("content-length", "0"); } private boolean setOrigin(final HttpRequest request, final HttpResponse response) { String origin = getOrigin(request); if (Strings.isNullOrEmpty(origin) == false) { if (config.isAnyOriginSupported()) { if (config.isCredentialsAllowed()) { setAllowOrigin(response, origin); setVaryHeader(response); } else { setAllowOrigin(response, ANY_ORIGIN); } return true; } else if (config.isOriginAllowed(origin) || isSameOrigin(origin, getHost(request))) { setAllowOrigin(response, origin); setVaryHeader(response); return true; } } return false; } private boolean validateOrigin(final HttpRequest request) { if (config.isAnyOriginSupported()) { return true; } final String origin = getOrigin(request); if (Strings.isNullOrEmpty(origin)) { // Not a CORS request so we cannot validate it. It may be a non CORS request. return true; } // if the origin is the same as the host of the request, then allow if (isSameOrigin(origin, getHost(request))) { return true; } return config.isOriginAllowed(origin); } private static String getOrigin(HttpRequest request) { List<String> headers = request.getHeaders().get(ORIGIN); if (headers == null || headers.isEmpty()) { return null; } else { return headers.get(0); } } private static String getHost(HttpRequest request) { List<String> headers = request.getHeaders().get(HOST); if (headers == null || headers.isEmpty()) { return null; } else { return headers.get(0); } } private static boolean isPreflightRequest(final HttpRequest request) { final Map<String, List<String>> headers = request.getHeaders(); return request.method().equals(RestRequest.Method.OPTIONS) && headers.containsKey(ORIGIN) && headers.containsKey(ACCESS_CONTROL_REQUEST_METHOD); } private static void setVaryHeader(final HttpResponse response) { response.addHeader(VARY, ORIGIN); } private static void setAllowOrigin(final HttpResponse response, final String origin) { response.addHeader(ACCESS_CONTROL_ALLOW_ORIGIN, origin); } private void setAllowMethods(final HttpResponse response) { for (RestRequest.Method method : config.allowedRequestMethods()) { response.addHeader(ACCESS_CONTROL_ALLOW_METHODS, method.name().trim()); } } private void setAllowHeaders(final HttpResponse response) { for (String header : config.allowedRequestHeaders) { response.addHeader(ACCESS_CONTROL_ALLOW_HEADERS, header); } } private void setExposeHeaders(final HttpResponse response) { for (String header : config.accessControlExposeHeaders) { response.addHeader(ACCESS_CONTROL_EXPOSE_HEADERS, header); } } private void setAllowCredentials(final HttpResponse response) { if (config.isCredentialsAllowed()) { response.addHeader(ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"); } } private void setMaxAge(final HttpResponse response) { response.addHeader(ACCESS_CONTROL_MAX_AGE, Long.toString(config.maxAge)); } public static class Config { private final boolean enabled; private final Optional<Set<String>> origins; private final Optional<Pattern> pattern; private final boolean anyOrigin; private final boolean credentialsAllowed; private final Set<RestRequest.Method> allowedRequestMethods; private final Set<String> allowedRequestHeaders; private final Set<String> accessControlExposeHeaders; private final long maxAge; public Config(Builder builder) { this.enabled = builder.enabled; origins = builder.origins.map(HashSet::new); pattern = builder.pattern; anyOrigin = builder.anyOrigin; this.credentialsAllowed = builder.allowCredentials; this.allowedRequestMethods = Collections.unmodifiableSet(builder.requestMethods); this.allowedRequestHeaders = Collections.unmodifiableSet(builder.requestHeaders); this.accessControlExposeHeaders = Collections.unmodifiableSet(builder.accessControlExposeHeaders); this.maxAge = builder.maxAge; } public boolean isCorsSupportEnabled() { return enabled; } public boolean isAnyOriginSupported() { return anyOrigin; } public boolean isOriginAllowed(String origin) { if (origins.isPresent()) { return origins.get().contains(origin); } else if (pattern.isPresent()) { return pattern.get().matcher(origin).matches(); } return false; } public boolean isCredentialsAllowed() { return credentialsAllowed; } public Set<RestRequest.Method> allowedRequestMethods() { return allowedRequestMethods; } public Set<String> allowedRequestHeaders() { return allowedRequestHeaders; } public long maxAge() { return maxAge; } public Optional<Set<String>> origins() { return origins; } @Override public String toString() { return "Config{" + "enabled=" + enabled + ", origins=" + origins + ", pattern=" + pattern + ", anyOrigin=" + anyOrigin + ", credentialsAllowed=" + credentialsAllowed + ", allowedRequestMethods=" + allowedRequestMethods + ", allowedRequestHeaders=" + allowedRequestHeaders + ", accessControlExposeHeaders=" + accessControlExposeHeaders + ", maxAge=" + maxAge + '}'; } private static class Builder { private boolean enabled = true; private Optional<Set<String>> origins; private Optional<Pattern> pattern; private final boolean anyOrigin; private boolean allowCredentials = false; long maxAge; private final Set<RestRequest.Method> requestMethods = EnumSet.noneOf(RestRequest.Method.class); private final Set<String> requestHeaders = new HashSet<>(); private final Set<String> accessControlExposeHeaders = new HashSet<>(); private Builder() { anyOrigin = true; origins = Optional.empty(); pattern = Optional.empty(); } private Builder(final String... origins) { this.origins = Optional.of(new LinkedHashSet<>(Arrays.asList(origins))); pattern = Optional.empty(); anyOrigin = false; } private Builder(final Pattern pattern) { this.pattern = Optional.of(pattern); origins = Optional.empty(); anyOrigin = false; } static Builder forOrigins(final String... origins) { return new Builder(origins); } static Builder forAnyOrigin() { return new Builder(); } static Builder forPattern(Pattern pattern) { return new Builder(pattern); } Builder allowCredentials() { this.allowCredentials = true; return this; } public Builder allowedRequestMethods(RestRequest.Method[] methods) { requestMethods.addAll(Arrays.asList(methods)); return this; } public Builder maxAge(int maxAge) { this.maxAge = maxAge; return this; } public Builder allowedRequestHeaders(String[] headers) { requestHeaders.addAll(Arrays.asList(headers)); return this; } public Builder accessControlExposeHeaders(String[] headers) { accessControlExposeHeaders.addAll(Arrays.asList(headers)); return this; } public Config build() { return new Config(this); } } } public static CorsHandler disabled() { Config.Builder builder = new Config.Builder(); builder.enabled = false; return new CorsHandler(new Config(builder)); } public static Config buildConfig(Settings settings) { if (SETTING_CORS_ENABLED.get(settings) == false) { Config.Builder builder = new Config.Builder(); builder.enabled = false; return new Config(builder); } String origin = SETTING_CORS_ALLOW_ORIGIN.get(settings); final CorsHandler.Config.Builder builder; if (Strings.isNullOrEmpty(origin)) { builder = CorsHandler.Config.Builder.forOrigins(); } else if (origin.equals(CorsHandler.ANY_ORIGIN)) { builder = CorsHandler.Config.Builder.forAnyOrigin(); } else { try { Pattern p = RestUtils.checkCorsSettingForRegex(origin); if (p == null) { builder = CorsHandler.Config.Builder.forOrigins(RestUtils.corsSettingAsArray(origin)); } else { builder = CorsHandler.Config.Builder.forPattern(p); } } catch (PatternSyntaxException e) { throw new SettingsException("Bad regex in [" + SETTING_CORS_ALLOW_ORIGIN.getKey() + "]: [" + origin + "]", e); } } if (SETTING_CORS_ALLOW_CREDENTIALS.get(settings)) { builder.allowCredentials(); } String[] strMethods = Strings.tokenizeToStringArray(SETTING_CORS_ALLOW_METHODS.get(settings), ","); RestRequest.Method[] methods = Arrays.stream(strMethods) .map(s -> s.toUpperCase(Locale.ENGLISH)) .map(RestRequest.Method::valueOf) .toArray(RestRequest.Method[]::new); Config config = builder.allowedRequestMethods(methods) .maxAge(SETTING_CORS_MAX_AGE.get(settings)) .allowedRequestHeaders(Strings.tokenizeToStringArray(SETTING_CORS_ALLOW_HEADERS.get(settings), ",")) .accessControlExposeHeaders(Strings.tokenizeToStringArray(SETTING_CORS_EXPOSE_HEADERS.get(settings), ",")) .build(); return config; } public static CorsHandler fromSettings(Settings settings) { return new CorsHandler(buildConfig(settings)); } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/http/CorsHandler.java
332
///usr/bin/env jbang "$0" "$@" ; exit $? // //DEPS <dependency1> <dependency2> import static java.lang.System.*; public class hello { public static void main(String... args) { out.println("Hello World"); } }
eugenp/tutorials
jbang/hello.java
333
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.math; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.math.MathPreconditions.checkNoOverflow; import static com.google.common.math.MathPreconditions.checkNonNegative; import static com.google.common.math.MathPreconditions.checkPositive; import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.math.RoundingMode.HALF_EVEN; import static java.math.RoundingMode.HALF_UP; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.primitives.Ints; import java.math.BigInteger; import java.math.RoundingMode; /** * A class for arithmetic on values of type {@code int}. Where possible, methods are defined and * named analogously to their {@code BigInteger} counterparts. * * <p>The implementations of many methods in this class are based on material from Henry S. Warren, * Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002). * * <p>Similar functionality for {@code long} and for {@link BigInteger} can be found in {@link * LongMath} and {@link BigIntegerMath} respectively. For other common operations on {@code int} * values, see {@link com.google.common.primitives.Ints}. * * @author Louis Wasserman * @since 11.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class IntMath { // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, || @VisibleForTesting static final int MAX_SIGNED_POWER_OF_TWO = 1 << (Integer.SIZE - 2); /** * Returns the smallest power of two greater than or equal to {@code x}. This is equivalent to * {@code checkedPow(2, log2(x, CEILING))}. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException of the next-higher power of two is not representable as an {@code * int}, i.e. when {@code x > 2^30} * @since 20.0 */ public static int ceilingPowerOfTwo(int x) { checkPositive("x", x); if (x > MAX_SIGNED_POWER_OF_TWO) { throw new ArithmeticException("ceilingPowerOfTwo(" + x + ") not representable as an int"); } return 1 << -Integer.numberOfLeadingZeros(x - 1); } /** * Returns the largest power of two less than or equal to {@code x}. This is equivalent to {@code * checkedPow(2, log2(x, FLOOR))}. * * @throws IllegalArgumentException if {@code x <= 0} * @since 20.0 */ public static int floorPowerOfTwo(int x) { checkPositive("x", x); return Integer.highestOneBit(x); } /** * Returns {@code true} if {@code x} represents a power of two. * * <p>This differs from {@code Integer.bitCount(x) == 1}, because {@code * Integer.bitCount(Integer.MIN_VALUE) == 1}, but {@link Integer#MIN_VALUE} is not a power of two. */ public static boolean isPowerOfTwo(int x) { return x > 0 & (x & (x - 1)) == 0; } /** * Returns 1 if {@code x < y} as unsigned integers, and 0 otherwise. Assumes that x - y fits into * a signed int. The implementation is branch-free, and benchmarks suggest it is measurably (if * narrowly) faster than the straightforward ternary expression. */ @VisibleForTesting static int lessThanBranchFree(int x, int y) { // The double negation is optimized away by normal Java, but is necessary for GWT // to make sure bit twiddling works as expected. return ~~(x - y) >>> (Integer.SIZE - 1); } /** * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of two */ @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log2(int x, RoundingMode mode) { checkPositive("x", x); switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through case DOWN: case FLOOR: return (Integer.SIZE - 1) - Integer.numberOfLeadingZeros(x); case UP: case CEILING: return Integer.SIZE - Integer.numberOfLeadingZeros(x - 1); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 int leadingZeros = Integer.numberOfLeadingZeros(x); int cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros; // floor(2^(logFloor + 0.5)) int logFloor = (Integer.SIZE - 1) - leadingZeros; return logFloor + lessThanBranchFree(cmp, x); default: throw new AssertionError(); } } /** The biggest half power of two that can fit in an unsigned int. */ @VisibleForTesting static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333; /** * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of ten */ @GwtIncompatible // need BigIntegerMath to adequately test @SuppressWarnings("fallthrough") public static int log10(int x, RoundingMode mode) { checkPositive("x", x); int logFloor = log10Floor(x); int floorPow = powersOf10[logFloor]; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(x == floorPow); // fall through case FLOOR: case DOWN: return logFloor; case CEILING: case UP: return logFloor + lessThanBranchFree(floorPow, x); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // sqrt(10) is irrational, so log10(x) - logFloor is never exactly 0.5 return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x); default: throw new AssertionError(); } } private static int log10Floor(int x) { /* * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation. * * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))), we * can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x)) is 6, * then 64 <= x < 128, so floor(log10(x)) is either 1 or 2. */ int y = maxLog10ForLeadingZeros[Integer.numberOfLeadingZeros(x)]; /* * y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the * lower of the two possible values, or y - 1, otherwise, we want y. */ return y - lessThanBranchFree(x, powersOf10[y]); } // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i))) @VisibleForTesting static final byte[] maxLog10ForLeadingZeros = { 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0, 0 }; @VisibleForTesting static final int[] powersOf10 = { 1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000 }; // halfPowersOf10[i] = largest int less than 10^(i + 0.5) @VisibleForTesting static final int[] halfPowersOf10 = { 3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, Integer.MAX_VALUE }; /** * Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to * {@code BigInteger.valueOf(b).pow(k).intValue()}. This implementation runs in {@code O(log k)} * time. * * <p>Compare {@link #checkedPow}, which throws an {@link ArithmeticException} upon overflow. * * @throws IllegalArgumentException if {@code k < 0} */ @GwtIncompatible // failing tests public static int pow(int b, int k) { checkNonNegative("exponent", k); switch (b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: return (k < Integer.SIZE) ? (1 << k) : 0; case (-2): if (k < Integer.SIZE) { return ((k & 1) == 0) ? (1 << k) : -(1 << k); } else { return 0; } default: // continue below to handle the general case } for (int accum = 1; ; k >>= 1) { switch (k) { case 0: return accum; case 1: return b * accum; default: accum *= ((k & 1) == 0) ? 1 : b; b *= b; } } } /** * Returns the square root of {@code x}, rounded with the specified rounding mode. * * @throws IllegalArgumentException if {@code x < 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code * sqrt(x)} is not an integer */ @GwtIncompatible // need BigIntegerMath to adequately test @SuppressWarnings("fallthrough") public static int sqrt(int x, RoundingMode mode) { checkNonNegative("x", x); int sqrtFloor = sqrtFloor(x); switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(sqrtFloor * sqrtFloor == x); // fall through case FLOOR: case DOWN: return sqrtFloor; case CEILING: case UP: return sqrtFloor + lessThanBranchFree(sqrtFloor * sqrtFloor, x); case HALF_DOWN: case HALF_UP: case HALF_EVEN: int halfSquare = sqrtFloor * sqrtFloor + sqrtFloor; /* * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x * and halfSquare are integers, this is equivalent to testing whether or not x <= * halfSquare. (We have to deal with overflow, though.) * * If we treat halfSquare as an unsigned int, we know that * sqrtFloor^2 <= x < (sqrtFloor + 1)^2 * halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1 * so |x - halfSquare| <= sqrtFloor. Therefore, it's safe to treat x - halfSquare as a * signed int, so lessThanBranchFree is safe for use. */ return sqrtFloor + lessThanBranchFree(halfSquare, x); default: throw new AssertionError(); } } private static int sqrtFloor(int x) { // There is no loss of precision in converting an int to a double, according to // http://java.sun.com/docs/books/jls/third_edition/html/conversions.html#5.1.2 return (int) Math.sqrt(x); } /** * Returns the result of dividing {@code p} by {@code q}, rounding using the specified {@code * RoundingMode}. * * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a} * is not an integer multiple of {@code b} */ @SuppressWarnings("fallthrough") public static int divide(int p, int q, RoundingMode mode) { checkNotNull(mode); if (q == 0) { throw new ArithmeticException("/ by zero"); // for GWT } int div = p / q; int rem = p - q * div; // equal to p % q if (rem == 0) { return div; } /* * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to * deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of * p / q. * * signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise. */ int signum = 1 | ((p ^ q) >> (Integer.SIZE - 1)); boolean increment; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(rem == 0); // fall through case DOWN: increment = false; break; case UP: increment = true; break; case CEILING: increment = signum > 0; break; case FLOOR: increment = signum < 0; break; case HALF_EVEN: case HALF_DOWN: case HALF_UP: int absRem = abs(rem); int cmpRemToHalfDivisor = absRem - (abs(q) - absRem); // subtracting two nonnegative ints can't overflow // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2). if (cmpRemToHalfDivisor == 0) { // exactly on the half mark increment = (mode == HALF_UP || (mode == HALF_EVEN & (div & 1) != 0)); } else { increment = cmpRemToHalfDivisor > 0; // closer to the UP value } break; default: throw new AssertionError(); } return increment ? div + signum : div; } /** * Returns {@code x mod m}, a non-negative value less than {@code m}. This differs from {@code x % * m}, which might be negative. * * <p>For example: * * <pre>{@code * mod(7, 4) == 3 * mod(-7, 4) == 1 * mod(-1, 4) == 3 * mod(-8, 4) == 0 * mod(8, 4) == 0 * }</pre> * * @throws ArithmeticException if {@code m <= 0} * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3"> * Remainder Operator</a> */ public static int mod(int x, int m) { if (m <= 0) { throw new ArithmeticException("Modulus " + m + " must be > 0"); } int result = x % m; return (result >= 0) ? result : result + m; } /** * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if {@code a == 0 && b == * 0}. * * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0} */ public static int gcd(int a, int b) { /* * The reason we require both arguments to be >= 0 is because otherwise, what do you return on * gcd(0, Integer.MIN_VALUE)? BigInteger.gcd would return positive 2^31, but positive 2^31 isn't * an int. */ checkNonNegative("a", a); checkNonNegative("b", b); if (a == 0) { // 0 % b == 0, so b divides a, but the converse doesn't hold. // BigInteger.gcd is consistent with this decision. return b; } else if (b == 0) { return a; // similar logic } /* * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm. This is * >40% faster than the Euclidean algorithm in benchmarks. */ int aTwos = Integer.numberOfTrailingZeros(a); a >>= aTwos; // divide out all 2s int bTwos = Integer.numberOfTrailingZeros(b); b >>= bTwos; // divide out all 2s while (a != b) { // both a, b are odd // The key to the binary GCD algorithm is as follows: // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b). // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two. // We bend over backwards to avoid branching, adapting a technique from // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax int delta = a - b; // can't overflow, since a and b are nonnegative int minDeltaOrZero = delta & (delta >> (Integer.SIZE - 1)); // equivalent to Math.min(delta, 0) a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b) // a is now nonnegative and even b += minDeltaOrZero; // sets b to min(old a, b) a >>= Integer.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b } return a << min(aTwos, bTwos); } /** * Returns the sum of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic */ public static int checkedAdd(int a, int b) { long result = (long) a + b; checkNoOverflow(result == (int) result, "checkedAdd", a, b); return (int) result; } /** * Returns the difference of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a - b} overflows in signed {@code int} arithmetic */ public static int checkedSubtract(int a, int b) { long result = (long) a - b; checkNoOverflow(result == (int) result, "checkedSubtract", a, b); return (int) result; } /** * Returns the product of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a * b} overflows in signed {@code int} arithmetic */ public static int checkedMultiply(int a, int b) { long result = (long) a * b; checkNoOverflow(result == (int) result, "checkedMultiply", a, b); return (int) result; } /** * Returns the {@code b} to the {@code k}th power, provided it does not overflow. * * <p>{@link #pow} may be faster, but does not check for overflow. * * @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed {@code * int} arithmetic */ public static int checkedPow(int b, int k) { checkNonNegative("exponent", k); switch (b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: checkNoOverflow(k < Integer.SIZE - 1, "checkedPow", b, k); return 1 << k; case (-2): checkNoOverflow(k < Integer.SIZE, "checkedPow", b, k); return ((k & 1) == 0) ? 1 << k : -1 << k; default: // continue below to handle the general case } int accum = 1; while (true) { switch (k) { case 0: return accum; case 1: return checkedMultiply(accum, b); default: if ((k & 1) != 0) { accum = checkedMultiply(accum, b); } k >>= 1; if (k > 0) { checkNoOverflow(-FLOOR_SQRT_MAX_INT <= b & b <= FLOOR_SQRT_MAX_INT, "checkedPow", b, k); b *= b; } } } } /** * Returns the sum of {@code a} and {@code b} unless it would overflow or underflow in which case * {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively. * * @since 20.0 */ public static int saturatedAdd(int a, int b) { return Ints.saturatedCast((long) a + b); } /** * Returns the difference of {@code a} and {@code b} unless it would overflow or underflow in * which case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively. * * @since 20.0 */ public static int saturatedSubtract(int a, int b) { return Ints.saturatedCast((long) a - b); } /** * Returns the product of {@code a} and {@code b} unless it would overflow or underflow in which * case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively. * * @since 20.0 */ public static int saturatedMultiply(int a, int b) { return Ints.saturatedCast((long) a * b); } /** * Returns the {@code b} to the {@code k}th power, unless it would overflow or underflow in which * case {@code Integer.MAX_VALUE} or {@code Integer.MIN_VALUE} is returned, respectively. * * @since 20.0 */ public static int saturatedPow(int b, int k) { checkNonNegative("exponent", k); switch (b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: if (k >= Integer.SIZE - 1) { return Integer.MAX_VALUE; } return 1 << k; case (-2): if (k >= Integer.SIZE) { return Integer.MAX_VALUE + (k & 1); } return ((k & 1) == 0) ? 1 << k : -1 << k; default: // continue below to handle the general case } int accum = 1; // if b is negative and k is odd then the limit is MIN otherwise the limit is MAX int limit = Integer.MAX_VALUE + ((b >>> Integer.SIZE - 1) & (k & 1)); while (true) { switch (k) { case 0: return accum; case 1: return saturatedMultiply(accum, b); default: if ((k & 1) != 0) { accum = saturatedMultiply(accum, b); } k >>= 1; if (k > 0) { if (-FLOOR_SQRT_MAX_INT > b | b > FLOOR_SQRT_MAX_INT) { return limit; } b *= b; } } } } @VisibleForTesting static final int FLOOR_SQRT_MAX_INT = 46340; /** * Returns {@code n!}, that is, the product of the first {@code n} positive integers, {@code 1} if * {@code n == 0}, or {@link Integer#MAX_VALUE} if the result does not fit in a {@code int}. * * @throws IllegalArgumentException if {@code n < 0} */ public static int factorial(int n) { checkNonNegative("n", n); return (n < factorials.length) ? factorials[n] : Integer.MAX_VALUE; } private static final int[] factorials = { 1, 1, 1 * 2, 1 * 2 * 3, 1 * 2 * 3 * 4, 1 * 2 * 3 * 4 * 5, 1 * 2 * 3 * 4 * 5 * 6, 1 * 2 * 3 * 4 * 5 * 6 * 7, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 1 * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 }; /** * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and * {@code k}, or {@link Integer#MAX_VALUE} if the result does not fit in an {@code int}. * * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0} or {@code k > n} */ public static int binomial(int n, int k) { checkNonNegative("n", n); checkNonNegative("k", k); checkArgument(k <= n, "k (%s) > n (%s)", k, n); if (k > (n >> 1)) { k = n - k; } if (k >= biggestBinomials.length || n > biggestBinomials[k]) { return Integer.MAX_VALUE; } switch (k) { case 0: return 1; case 1: return n; default: long result = 1; for (int i = 0; i < k; i++) { result *= n - i; result /= i + 1; } return (int) result; } } // binomial(biggestBinomials[k], k) fits in an int, but not binomial(biggestBinomials[k]+1,k). @VisibleForTesting static int[] biggestBinomials = { Integer.MAX_VALUE, Integer.MAX_VALUE, 65536, 2345, 477, 193, 110, 75, 58, 49, 43, 39, 37, 35, 34, 34, 33 }; /** * Returns the arithmetic mean of {@code x} and {@code y}, rounded towards negative infinity. This * method is overflow resilient. * * @since 14.0 */ public static int mean(int x, int y) { // Efficient method for computing the arithmetic mean. // The alternative (x + y) / 2 fails for large values. // The alternative (x + y) >>> 1 fails for negative values. return (x & y) + ((x ^ y) >> 1); } /** * Returns {@code true} if {@code n} is a <a * href="http://mathworld.wolfram.com/PrimeNumber.html">prime number</a>: an integer <i>greater * than one</i> that cannot be factored into a product of <i>smaller</i> positive integers. * Returns {@code false} if {@code n} is zero, one, or a composite number (one which <i>can</i> be * factored into smaller positive integers). * * <p>To test larger numbers, use {@link LongMath#isPrime} or {@link BigInteger#isProbablePrime}. * * @throws IllegalArgumentException if {@code n} is negative * @since 20.0 */ @GwtIncompatible // TODO public static boolean isPrime(int n) { return LongMath.isPrime(n); } private IntMath() {} }
google/guava
android/guava/src/com/google/common/math/IntMath.java
334
/* * 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 static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.io.FileWriteMode.APPEND; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.graph.SuccessorsFunction; import com.google.common.graph.Traverser; import com.google.common.hash.HashCode; import com.google.common.hash.HashFunction; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.InlineMe; import com.google.j2objc.annotations.J2ObjCIncompatible; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.RandomAccessFile; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.charset.Charset; import java.nio.charset.StandardCharsets; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.List; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Provides utility methods for working with {@linkplain File files}. * * <p>{@link java.nio.file.Path} users will find similar utilities in {@link MoreFiles} and the * JDK's {@link java.nio.file.Files} class. * * @author Chris Nokleberg * @author Colin Decker * @since 1.0 */ @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public final class Files { private Files() {} /** * Returns a buffered reader that reads from a file using the given character set. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#newBufferedReader(java.nio.file.Path, Charset)}. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for * helpful predefined constants * @return the buffered reader */ public static BufferedReader newReader(File file, Charset charset) throws FileNotFoundException { checkNotNull(file); checkNotNull(charset); return new BufferedReader(new InputStreamReader(new FileInputStream(file), charset)); } /** * Returns a buffered writer that writes to a file using the given character set. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#newBufferedWriter(java.nio.file.Path, Charset, * java.nio.file.OpenOption...)}. * * @param file the file to write to * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for * helpful predefined constants * @return the buffered writer */ public static BufferedWriter newWriter(File file, Charset charset) throws FileNotFoundException { checkNotNull(file); checkNotNull(charset); return new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file), charset)); } /** * Returns a new {@link ByteSource} for reading bytes from the given file. * * @since 14.0 */ public static ByteSource asByteSource(File file) { return new FileByteSource(file); } private static final class FileByteSource extends ByteSource { private final File file; private FileByteSource(File file) { this.file = checkNotNull(file); } @Override public FileInputStream openStream() throws IOException { return new FileInputStream(file); } @Override public Optional<Long> sizeIfKnown() { if (file.isFile()) { return Optional.of(file.length()); } else { return Optional.absent(); } } @Override public long size() throws IOException { if (!file.isFile()) { throw new FileNotFoundException(file.toString()); } return file.length(); } @Override public byte[] read() throws IOException { Closer closer = Closer.create(); try { FileInputStream in = closer.register(openStream()); return ByteStreams.toByteArray(in, in.getChannel().size()); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } @Override public String toString() { return "Files.asByteSource(" + file + ")"; } } /** * Returns a new {@link ByteSink} for writing bytes to the given file. The given {@code modes} * control how the file is opened for writing. When no mode is provided, the file will be * truncated before writing. When the {@link FileWriteMode#APPEND APPEND} mode is provided, writes * will append to the end of the file without truncating it. * * @since 14.0 */ public static ByteSink asByteSink(File file, FileWriteMode... modes) { return new FileByteSink(file, modes); } private static final class FileByteSink extends ByteSink { private final File file; private final ImmutableSet<FileWriteMode> modes; private FileByteSink(File file, FileWriteMode... modes) { this.file = checkNotNull(file); this.modes = ImmutableSet.copyOf(modes); } @Override public FileOutputStream openStream() throws IOException { return new FileOutputStream(file, modes.contains(APPEND)); } @Override public String toString() { return "Files.asByteSink(" + file + ", " + modes + ")"; } } /** * Returns a new {@link CharSource} for reading character data from the given file using the given * character set. * * @since 14.0 */ public static CharSource asCharSource(File file, Charset charset) { return asByteSource(file).asCharSource(charset); } /** * Returns a new {@link CharSink} for writing character data to the given file using the given * character set. The given {@code modes} control how the file is opened for writing. When no mode * is provided, the file will be truncated before writing. When the {@link FileWriteMode#APPEND * APPEND} mode is provided, writes will append to the end of the file without truncating it. * * @since 14.0 */ public static CharSink asCharSink(File file, Charset charset, FileWriteMode... modes) { return asByteSink(file, modes).asCharSink(charset); } /** * Reads all bytes from a file into a byte array. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#readAllBytes}. * * @param file the file to read from * @return a byte array containing all the bytes from file * @throws IllegalArgumentException if the file is bigger than the largest possible byte array * (2^31 - 1) * @throws IOException if an I/O error occurs */ public static byte[] toByteArray(File file) throws IOException { return asByteSource(file).read(); } /** * Reads all characters from a file into a {@link String}, using the given character set. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for * helpful predefined constants * @return a string containing all the characters from the file * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asCharSource(file, charset).read()}. */ @Deprecated @InlineMe( replacement = "Files.asCharSource(file, charset).read()", imports = "com.google.common.io.Files") public static String toString(File file, Charset charset) throws IOException { return asCharSource(file, charset).read(); } /** * Overwrites a file with the contents of a byte array. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#write(java.nio.file.Path, byte[], java.nio.file.OpenOption...)}. * * @param from the bytes to write * @param to the destination file * @throws IOException if an I/O error occurs */ public static void write(byte[] from, File to) throws IOException { asByteSink(to).write(from); } /** * Writes a character sequence (such as a string) to a file using the given character set. * * @param from the character sequence to write * @param to the destination file * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for * helpful predefined constants * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asCharSink(to, charset).write(from)}. */ @Deprecated @InlineMe( replacement = "Files.asCharSink(to, charset).write(from)", imports = "com.google.common.io.Files") public static void write(CharSequence from, File to, Charset charset) throws IOException { asCharSink(to, charset).write(from); } /** * Copies all bytes from a file to an output stream. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#copy(java.nio.file.Path, OutputStream)}. * * @param from the source file * @param to the output stream * @throws IOException if an I/O error occurs */ public static void copy(File from, OutputStream to) throws IOException { asByteSource(from).copyTo(to); } /** * Copies all the bytes from one file to another. * * <p>Copying is not an atomic operation - in the case of an I/O error, power loss, process * termination, or other problems, {@code to} may not be a complete copy of {@code from}. If you * need to guard against those conditions, you should employ other file-level synchronization. * * <p><b>Warning:</b> If {@code to} represents an existing file, that file will be overwritten * with the contents of {@code from}. If {@code to} and {@code from} refer to the <i>same</i> * file, the contents of that file will be deleted. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#copy(java.nio.file.Path, java.nio.file.Path, java.nio.file.CopyOption...)}. * * @param from the source file * @param to the destination file * @throws IOException if an I/O error occurs * @throws IllegalArgumentException if {@code from.equals(to)} */ public static void copy(File from, File to) throws IOException { checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to); asByteSource(from).copyTo(asByteSink(to)); } /** * Copies all characters from a file to an appendable object, using the given character set. * * @param from the source file * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for * helpful predefined constants * @param to the appendable object * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asCharSource(from, charset).copyTo(to)}. */ @Deprecated @InlineMe( replacement = "Files.asCharSource(from, charset).copyTo(to)", imports = "com.google.common.io.Files") public static void copy(File from, Charset charset, Appendable to) throws IOException { asCharSource(from, charset).copyTo(to); } /** * Appends a character sequence (such as a string) to a file using the given character set. * * @param from the character sequence to append * @param to the destination file * @param charset the charset used to encode the output stream; see {@link StandardCharsets} for * helpful predefined constants * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asCharSink(to, charset, FileWriteMode.APPEND).write(from)}. This * method is scheduled to be removed in October 2019. */ @Deprecated @InlineMe( replacement = "Files.asCharSink(to, charset, FileWriteMode.APPEND).write(from)", imports = {"com.google.common.io.FileWriteMode", "com.google.common.io.Files"}) public static void append(CharSequence from, File to, Charset charset) throws IOException { asCharSink(to, charset, FileWriteMode.APPEND).write(from); } /** * Returns true if the given files exist, are not directories, and contain the same bytes. * * @throws IOException if an I/O error occurs */ public static boolean equal(File file1, File file2) throws IOException { checkNotNull(file1); checkNotNull(file2); if (file1 == file2 || file1.equals(file2)) { return true; } /* * Some operating systems may return zero as the length for files denoting system-dependent * entities such as devices or pipes, in which case we must fall back on comparing the bytes * directly. */ long len1 = file1.length(); long len2 = file2.length(); if (len1 != 0 && len2 != 0 && len1 != len2) { return false; } return asByteSource(file1).contentEquals(asByteSource(file2)); } /** * Atomically creates a new directory somewhere beneath the system's temporary directory (as * defined by the {@code java.io.tmpdir} system property), and returns its name. * * <p>The temporary directory is created with permissions restricted to the current user or, in * the case of Android, the current app. If that is not possible (as is the case under the very * old Android Ice Cream Sandwich release), then this method throws an exception instead of * creating a directory that would be more accessible. (This behavior is new in Guava 32.0.0. * Previous versions would create a directory that is more accessible, as discussed in <a * href="https://github.com/google/guava/issues/4011">CVE-2020-8908</a>.) * * <p>Use this method instead of {@link File#createTempFile(String, String)} when you wish to * create a directory, not a regular file. A common pitfall is to call {@code createTempFile}, * delete the file and create a directory in its place, but this leads a race condition which can * be exploited to create security vulnerabilities, especially when executable files are to be * written into the directory. * * <p>This method assumes that the temporary volume is writable, has free inodes and free blocks, * and that it will not be called thousands of times per second. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#createTempDirectory}. * * @return the newly-created directory * @throws IllegalStateException if the directory could not be created, such as if the system does * not support creating temporary directories securely * @deprecated For Android users, see the <a * href="https://developer.android.com/training/data-storage" target="_blank">Data and File * Storage overview</a> to select an appropriate temporary directory (perhaps {@code * context.getCacheDir()}), and create your own directory under that. (For example, you might * use {@code new File(context.getCacheDir(), "directoryname").mkdir()}, or, if you need an * arbitrary number of temporary directories, you might have to generate multiple directory * names in a loop until {@code mkdir()} returns {@code true}.) For Java 7+ users, prefer * {@link java.nio.file.Files#createTempDirectory}, transforming it to a {@link File} using * {@link java.nio.file.Path#toFile() toFile()} if needed. To restrict permissions as this * method does, pass {@code * PosixFilePermissions.asFileAttribute(PosixFilePermissions.fromString("rwx------"))} to your * call to {@code createTempDirectory}. */ @Beta @Deprecated @J2ObjCIncompatible public static File createTempDir() { return TempFileCreator.INSTANCE.createTempDir(); } /** * Creates an empty file or updates the last updated timestamp on the same as the unix command of * the same name. * * @param file the file to create or update * @throws IOException if an I/O error occurs */ @SuppressWarnings("GoodTime") // reading system time without TimeSource public static void touch(File file) throws IOException { checkNotNull(file); if (!file.createNewFile() && !file.setLastModified(System.currentTimeMillis())) { throw new IOException("Unable to update modification time of " + file); } } /** * Creates any necessary but nonexistent parent directories of the specified file. Note that if * this operation fails it may have succeeded in creating some (but not all) of the necessary * parent directories. * * @throws IOException if an I/O error occurs, or if any necessary but nonexistent parent * directories of the specified file could not be created. * @since 4.0 */ public static void createParentDirs(File file) throws IOException { checkNotNull(file); File parent = file.getCanonicalFile().getParentFile(); if (parent == null) { /* * The given directory is a filesystem root. All zero of its ancestors exist. This doesn't * mean that the root itself exists -- consider x:\ on a Windows machine without such a drive * -- or even that the caller can create it, but this method makes no such guarantees even for * non-root files. */ return; } parent.mkdirs(); if (!parent.isDirectory()) { throw new IOException("Unable to create parent directories of " + file); } } /** * Moves a file from one path to another. This method can rename a file and/or move it to a * different directory. In either case {@code to} must be the target path for the file itself; not * just the new name for the file or the path to the new parent directory. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link java.nio.file.Files#move}. * * @param from the source file * @param to the destination file * @throws IOException if an I/O error occurs * @throws IllegalArgumentException if {@code from.equals(to)} */ public static void move(File from, File to) throws IOException { checkNotNull(from); checkNotNull(to); checkArgument(!from.equals(to), "Source %s and destination %s must be different", from, to); if (!from.renameTo(to)) { copy(from, to); if (!from.delete()) { if (!to.delete()) { throw new IOException("Unable to delete " + to); } throw new IOException("Unable to delete " + from); } } } /** * Reads the first line from a file. The line does not include line-termination characters, but * does include other leading and trailing whitespace. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for * helpful predefined constants * @return the first line, or null if the file is empty * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asCharSource(file, charset).readFirstLine()}. */ @Deprecated @InlineMe( replacement = "Files.asCharSource(file, charset).readFirstLine()", imports = "com.google.common.io.Files") @CheckForNull public static String readFirstLine(File file, Charset charset) throws IOException { return asCharSource(file, charset).readFirstLine(); } /** * Reads all of the lines from a file. The lines do not include line-termination characters, but * do include other leading and trailing whitespace. * * <p>This method returns a mutable {@code List}. For an {@code ImmutableList}, use {@code * Files.asCharSource(file, charset).readLines()}. * * <p><b>{@link java.nio.file.Path} equivalent:</b> {@link * java.nio.file.Files#readAllLines(java.nio.file.Path, Charset)}. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for * helpful predefined constants * @return a mutable {@link List} containing all the lines * @throws IOException if an I/O error occurs */ public static List<String> readLines(File file, Charset charset) throws IOException { // don't use asCharSource(file, charset).readLines() because that returns // an immutable list, which would change the behavior of this method return asCharSource(file, charset) .readLines( new LineProcessor<List<String>>() { final List<String> result = Lists.newArrayList(); @Override public boolean processLine(String line) { result.add(line); return true; } @Override public List<String> getResult() { return result; } }); } /** * Streams lines from a {@link File}, stopping when our callback returns false, or we have read * all of the lines. * * @param file the file to read from * @param charset the charset used to decode the input stream; see {@link StandardCharsets} for * helpful predefined constants * @param callback the {@link LineProcessor} to use to handle the lines * @return the output of processing the lines * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asCharSource(file, charset).readLines(callback)}. */ @Deprecated @InlineMe( replacement = "Files.asCharSource(file, charset).readLines(callback)", imports = "com.google.common.io.Files") @CanIgnoreReturnValue // some processors won't return a useful result @ParametricNullness public static <T extends @Nullable Object> T readLines( File file, Charset charset, LineProcessor<T> callback) throws IOException { return asCharSource(file, charset).readLines(callback); } /** * Process the bytes of a file. * * <p>(If this seems too complicated, maybe you're looking for {@link #toByteArray}.) * * @param file the file to read * @param processor the object to which the bytes of the file are passed. * @return the result of the byte processor * @throws IOException if an I/O error occurs * @deprecated Prefer {@code asByteSource(file).read(processor)}. */ @Deprecated @InlineMe( replacement = "Files.asByteSource(file).read(processor)", imports = "com.google.common.io.Files") @CanIgnoreReturnValue // some processors won't return a useful result @ParametricNullness public static <T extends @Nullable Object> T readBytes(File file, ByteProcessor<T> processor) throws IOException { return asByteSource(file).read(processor); } /** * Computes the hash code of the {@code file} using {@code hashFunction}. * * @param file the file to read * @param hashFunction the hash function to use to hash the data * @return the {@link HashCode} of all of the bytes in the file * @throws IOException if an I/O error occurs * @since 12.0 * @deprecated Prefer {@code asByteSource(file).hash(hashFunction)}. */ @Deprecated @InlineMe( replacement = "Files.asByteSource(file).hash(hashFunction)", imports = "com.google.common.io.Files") public static HashCode hash(File file, HashFunction hashFunction) throws IOException { return asByteSource(file).hash(hashFunction); } /** * Fully maps a file read-only in to memory as per {@link * FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)}. * * <p>Files are mapped from offset 0 to its length. * * <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes. * * @param file the file to map * @return a read-only buffer reflecting {@code file} * @throws FileNotFoundException if the {@code file} does not exist * @throws IOException if an I/O error occurs * @see FileChannel#map(MapMode, long, long) * @since 2.0 */ public static MappedByteBuffer map(File file) throws IOException { checkNotNull(file); return map(file, MapMode.READ_ONLY); } /** * Fully maps a file in to memory as per {@link * FileChannel#map(java.nio.channels.FileChannel.MapMode, long, long)} using the requested {@link * MapMode}. * * <p>Files are mapped from offset 0 to its length. * * <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes. * * @param file the file to map * @param mode the mode to use when mapping {@code file} * @return a buffer reflecting {@code file} * @throws FileNotFoundException if the {@code file} does not exist * @throws IOException if an I/O error occurs * @see FileChannel#map(MapMode, long, long) * @since 2.0 */ public static MappedByteBuffer map(File file, MapMode mode) throws IOException { return mapInternal(file, mode, -1); } /** * Maps a file in to memory as per {@link FileChannel#map(java.nio.channels.FileChannel.MapMode, * long, long)} using the requested {@link MapMode}. * * <p>Files are mapped from offset 0 to {@code size}. * * <p>If the mode is {@link MapMode#READ_WRITE} and the file does not exist, it will be created * with the requested {@code size}. Thus this method is useful for creating memory mapped files * which do not yet exist. * * <p>This only works for files ≤ {@link Integer#MAX_VALUE} bytes. * * @param file the file to map * @param mode the mode to use when mapping {@code file} * @return a buffer reflecting {@code file} * @throws IOException if an I/O error occurs * @see FileChannel#map(MapMode, long, long) * @since 2.0 */ public static MappedByteBuffer map(File file, MapMode mode, long size) throws IOException { checkArgument(size >= 0, "size (%s) may not be negative", size); return mapInternal(file, mode, size); } private static MappedByteBuffer mapInternal(File file, MapMode mode, long size) throws IOException { checkNotNull(file); checkNotNull(mode); Closer closer = Closer.create(); try { RandomAccessFile raf = closer.register(new RandomAccessFile(file, mode == MapMode.READ_ONLY ? "r" : "rw")); FileChannel channel = closer.register(raf.getChannel()); return channel.map(mode, 0, size == -1 ? channel.size() : size); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Returns the lexically cleaned form of the path name, <i>usually</i> (but not always) equivalent * to the original. The following heuristics are used: * * <ul> * <li>empty string becomes . * <li>. stays as . * <li>fold out ./ * <li>fold out ../ when possible * <li>collapse multiple slashes * <li>delete trailing slashes (unless the path is just "/") * </ul> * * <p>These heuristics do not always match the behavior of the filesystem. In particular, consider * the path {@code a/../b}, which {@code simplifyPath} will change to {@code b}. If {@code a} is a * symlink to {@code x}, {@code a/../b} may refer to a sibling of {@code x}, rather than the * sibling of {@code a} referred to by {@code b}. * * @since 11.0 */ public static String simplifyPath(String pathname) { checkNotNull(pathname); if (pathname.length() == 0) { return "."; } // split the path apart Iterable<String> components = Splitter.on('/').omitEmptyStrings().split(pathname); List<String> path = new ArrayList<>(); // resolve ., .., and // for (String component : components) { switch (component) { case ".": continue; case "..": if (path.size() > 0 && !path.get(path.size() - 1).equals("..")) { path.remove(path.size() - 1); } else { path.add(".."); } break; default: path.add(component); break; } } // put it back together String result = Joiner.on('/').join(path); if (pathname.charAt(0) == '/') { result = "/" + result; } while (result.startsWith("/../")) { result = result.substring(3); } if (result.equals("/..")) { result = "/"; } else if ("".equals(result)) { result = "."; } return result; } /** * Returns the <a href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> for * the given file name, or the empty string if the file has no extension. The result does not * include the '{@code .}'. * * <p><b>Note:</b> This method simply returns everything after the last '{@code .}' in the file's * name as determined by {@link File#getName}. It does not account for any filesystem-specific * behavior that the {@link File} API does not already account for. For example, on NTFS it will * report {@code "txt"} as the extension for the filename {@code "foo.exe:.txt"} even though NTFS * will drop the {@code ":.txt"} part of the name when the file is actually created on the * filesystem due to NTFS's <a href="https://goo.gl/vTpJi4">Alternate Data Streams</a>. * * @since 11.0 */ public static String getFileExtension(String fullName) { checkNotNull(fullName); String fileName = new File(fullName).getName(); int dotIndex = fileName.lastIndexOf('.'); return (dotIndex == -1) ? "" : fileName.substring(dotIndex + 1); } /** * Returns the file name without its <a * href="http://en.wikipedia.org/wiki/Filename_extension">file extension</a> or path. This is * similar to the {@code basename} unix command. The result does not include the '{@code .}'. * * @param file The name of the file to trim the extension from. This can be either a fully * qualified file name (including a path) or just a file name. * @return The file name without its path or extension. * @since 14.0 */ public static String getNameWithoutExtension(String file) { checkNotNull(file); String fileName = new File(file).getName(); int dotIndex = fileName.lastIndexOf('.'); return (dotIndex == -1) ? fileName : fileName.substring(0, dotIndex); } /** * Returns a {@link Traverser} instance for the file and directory tree. The returned traverser * starts from a {@link File} and will return all files and directories it encounters. * * <p><b>Warning:</b> {@code File} provides no support for symbolic links, and as such there is no * way to ensure that a symbolic link to a directory is not followed when traversing the tree. In * this case, iterables created by this traverser could contain files that are outside of the * given directory or even be infinite if there is a symbolic link loop. * * <p>If available, consider using {@link MoreFiles#fileTraverser()} instead. It behaves the same * except that it doesn't follow symbolic links and returns {@code Path} instances. * * <p>If the {@link File} passed to one of the {@link Traverser} methods does not exist or is not * a directory, no exception will be thrown and the returned {@link Iterable} will contain a * single element: that file. * * <p>Example: {@code Files.fileTraverser().depthFirstPreOrder(new File("/"))} may return files * with the following paths: {@code ["/", "/etc", "/etc/config.txt", "/etc/fonts", "/home", * "/home/alice", ...]} * * @since 23.5 */ public static Traverser<File> fileTraverser() { return Traverser.forTree(FILE_TREE); } private static final SuccessorsFunction<File> FILE_TREE = new SuccessorsFunction<File>() { @Override public Iterable<File> successors(File file) { // check isDirectory() just because it may be faster than listFiles() on a non-directory if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { return Collections.unmodifiableList(Arrays.asList(files)); } } return ImmutableList.of(); } }; /** * Returns a predicate that returns the result of {@link File#isDirectory} on input files. * * @since 15.0 */ public static Predicate<File> isDirectory() { return FilePredicate.IS_DIRECTORY; } /** * Returns a predicate that returns the result of {@link File#isFile} on input files. * * @since 15.0 */ public static Predicate<File> isFile() { return FilePredicate.IS_FILE; } private enum FilePredicate implements Predicate<File> { IS_DIRECTORY { @Override public boolean apply(File file) { return file.isDirectory(); } @Override public String toString() { return "Files.isDirectory()"; } }, IS_FILE { @Override public boolean apply(File file) { return file.isFile(); } @Override public String toString() { return "Files.isFile()"; } } } }
google/guava
guava/src/com/google/common/io/Files.java
335
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import javax.annotation.CheckForNull; /** * Extracts non-overlapping substrings from an input string, typically by recognizing appearances of * a <i>separator</i> sequence. This separator can be specified as a single {@linkplain #on(char) * character}, fixed {@linkplain #on(String) string}, {@linkplain #onPattern regular expression} or * {@link #on(CharMatcher) CharMatcher} instance. Or, instead of using a separator at all, a * splitter can extract adjacent substrings of a given {@linkplain #fixedLength fixed length}. * * <p>For example, this expression: * * <pre>{@code * Splitter.on(',').split("foo,bar,qux") * }</pre> * * ... produces an {@code Iterable} containing {@code "foo"}, {@code "bar"} and {@code "qux"}, in * that order. * * <p>By default, {@code Splitter}'s behavior is simplistic and unassuming. The following * expression: * * <pre>{@code * Splitter.on(',').split(" foo,,, bar ,") * }</pre> * * ... yields the substrings {@code [" foo", "", "", " bar ", ""]}. If this is not the desired * behavior, use configuration methods to obtain a <i>new</i> splitter instance with modified * behavior: * * <pre>{@code * private static final Splitter MY_SPLITTER = Splitter.on(',') * .trimResults() * .omitEmptyStrings(); * }</pre> * * <p>Now {@code MY_SPLITTER.split("foo,,, bar ,")} returns just {@code ["foo", "bar"]}. Note that * the order in which these configuration methods are called is never significant. * * <p><b>Warning:</b> Splitter instances are immutable. Invoking a configuration method has no * effect on the receiving instance; you must store and use the new splitter instance it returns * instead. * * <pre>{@code * // Do NOT do this * Splitter splitter = Splitter.on('/'); * splitter.trimResults(); // does nothing! * return splitter.split("wrong / wrong / wrong"); * }</pre> * * <p>For separator-based splitters that do not use {@code omitEmptyStrings}, an input string * containing {@code n} occurrences of the separator naturally yields an iterable of size {@code n + * 1}. So if the separator does not occur anywhere in the input, a single substring is returned * containing the entire input. Consequently, all splitters split the empty string to {@code [""]} * (note: even fixed-length splitters). * * <p>Splitter instances are thread-safe immutable, and are therefore safe to store as {@code static * final} constants. * * <p>The {@link Joiner} class provides the inverse operation to splitting, but note that a * round-trip between the two should be assumed to be lossy. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/StringsExplained#splitter">{@code Splitter}</a>. * * @author Julien Silland * @author Jesse Wilson * @author Kevin Bourrillion * @author Louis Wasserman * @since 1.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Splitter { private final CharMatcher trimmer; private final boolean omitEmptyStrings; private final Strategy strategy; private final int limit; private Splitter(Strategy strategy) { this(strategy, false, CharMatcher.none(), Integer.MAX_VALUE); } private Splitter(Strategy strategy, boolean omitEmptyStrings, CharMatcher trimmer, int limit) { this.strategy = strategy; this.omitEmptyStrings = omitEmptyStrings; this.trimmer = trimmer; this.limit = limit; } /** * Returns a splitter that uses the given single-character separator. For example, {@code * Splitter.on(',').split("foo,,bar")} returns an iterable containing {@code ["foo", "", "bar"]}. * * @param separator the character to recognize as a separator * @return a splitter, with default settings, that recognizes that separator */ public static Splitter on(char separator) { return on(CharMatcher.is(separator)); } /** * Returns a splitter that considers any single character matched by the given {@code CharMatcher} * to be a separator. For example, {@code * Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux")} returns an iterable containing * {@code ["foo", "", "bar", "quux"]}. * * @param separatorMatcher a {@link CharMatcher} that determines whether a character is a * separator * @return a splitter, with default settings, that uses this matcher */ public static Splitter on(final CharMatcher separatorMatcher) { checkNotNull(separatorMatcher); return new Splitter( new Strategy() { @Override public SplittingIterator iterator(Splitter splitter, final CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override int separatorStart(int start) { return separatorMatcher.indexIn(toSplit, start); } @Override int separatorEnd(int separatorPosition) { return separatorPosition + 1; } }; } }); } /** * Returns a splitter that uses the given fixed string as a separator. For example, {@code * Splitter.on(", ").split("foo, bar,baz")} returns an iterable containing {@code ["foo", * "bar,baz"]}. * * @param separator the literal, nonempty string to recognize as a separator * @return a splitter, with default settings, that recognizes that separator */ public static Splitter on(final String separator) { checkArgument(separator.length() != 0, "The separator may not be the empty string."); if (separator.length() == 1) { return Splitter.on(separator.charAt(0)); } return new Splitter( new Strategy() { @Override public SplittingIterator iterator(Splitter splitter, CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { int separatorLength = separator.length(); positions: for (int p = start, last = toSplit.length() - separatorLength; p <= last; p++) { for (int i = 0; i < separatorLength; i++) { if (toSplit.charAt(i + p) != separator.charAt(i)) { continue positions; } } return p; } return -1; } @Override public int separatorEnd(int separatorPosition) { return separatorPosition + separator.length(); } }; } }); } /** * Returns a splitter that considers any subsequence matching {@code pattern} to be a separator. * For example, {@code Splitter.on(Pattern.compile("\r?\n")).split(entireFile)} splits a string * into lines whether it uses DOS-style or UNIX-style line terminators. * * @param separatorPattern the pattern that determines whether a subsequence is a separator. This * pattern may not match the empty string. * @return a splitter, with default settings, that uses this pattern * @throws IllegalArgumentException if {@code separatorPattern} matches the empty string */ @GwtIncompatible // java.util.regex public static Splitter on(Pattern separatorPattern) { return onPatternInternal(new JdkPattern(separatorPattern)); } /** Internal utility; see {@link #on(Pattern)} instead. */ static Splitter onPatternInternal(final CommonPattern separatorPattern) { checkArgument( !separatorPattern.matcher("").matches(), "The pattern may not match the empty string: %s", separatorPattern); return new Splitter( new Strategy() { @Override public SplittingIterator iterator(final Splitter splitter, CharSequence toSplit) { final CommonMatcher matcher = separatorPattern.matcher(toSplit); return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { return matcher.find(start) ? matcher.start() : -1; } @Override public int separatorEnd(int separatorPosition) { return matcher.end(); } }; } }); } /** * Returns a splitter that considers any subsequence matching a given pattern (regular expression) * to be a separator. For example, {@code Splitter.onPattern("\r?\n").split(entireFile)} splits a * string into lines whether it uses DOS-style or UNIX-style line terminators. This is equivalent * to {@code Splitter.on(Pattern.compile(pattern))}. * * @param separatorPattern the pattern that determines whether a subsequence is a separator. This * pattern may not match the empty string. * @return a splitter, with default settings, that uses this pattern * @throws IllegalArgumentException if {@code separatorPattern} matches the empty string or is a * malformed expression */ @GwtIncompatible // java.util.regex public static Splitter onPattern(String separatorPattern) { return onPatternInternal(Platform.compilePattern(separatorPattern)); } /** * Returns a splitter that divides strings into pieces of the given length. For example, {@code * Splitter.fixedLength(2).split("abcde")} returns an iterable containing {@code ["ab", "cd", * "e"]}. The last piece can be smaller than {@code length} but will never be empty. * * <p><b>Note:</b> if {@link #fixedLength} is used in conjunction with {@link #limit}, the final * split piece <i>may be longer than the specified fixed length</i>. This is because the splitter * will <i>stop splitting when the limit is reached</i>, and just return the final piece as-is. * * <p><b>Exception:</b> for consistency with separator-based splitters, {@code split("")} does not * yield an empty iterable, but an iterable containing {@code ""}. This is the only case in which * {@code Iterables.size(split(input))} does not equal {@code IntMath.divide(input.length(), * length, CEILING)}. To avoid this behavior, use {@code omitEmptyStrings}. * * @param length the desired length of pieces after splitting, a positive integer * @return a splitter, with default settings, that can split into fixed sized pieces * @throws IllegalArgumentException if {@code length} is zero or negative */ public static Splitter fixedLength(final int length) { checkArgument(length > 0, "The length may not be less than 1"); return new Splitter( new Strategy() { @Override public SplittingIterator iterator(final Splitter splitter, CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { int nextChunkStart = start + length; return (nextChunkStart < toSplit.length() ? nextChunkStart : -1); } @Override public int separatorEnd(int separatorPosition) { return separatorPosition; } }; } }); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but automatically omits * empty strings from the results. For example, {@code * Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,")} returns an iterable containing only * {@code ["a", "b", "c"]}. * * <p>If either {@code trimResults} option is also specified when creating a splitter, that * splitter always trims results first before checking for emptiness. So, for example, {@code * Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ")} returns an empty iterable. * * <p>Note that it is ordinarily not possible for {@link #split(CharSequence)} to return an empty * iterable, but when using this option, it can (if the input sequence consists of nothing but * separators). * * @return a splitter with the desired configuration */ public Splitter omitEmptyStrings() { return new Splitter(strategy, true, trimmer, limit); } /** * Returns a splitter that behaves equivalently to {@code this} splitter but stops splitting after * it reaches the limit. The limit defines the maximum number of items returned by the iterator, * or the maximum size of the list returned by {@link #splitToList}. * * <p>For example, {@code Splitter.on(',').limit(3).split("a,b,c,d")} returns an iterable * containing {@code ["a", "b", "c,d"]}. When omitting empty strings, the omitted strings do not * count. Hence, {@code Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d")} returns * an iterable containing {@code ["a", "b", "c,d"]}. When trim is requested, all entries are * trimmed, including the last. Hence {@code Splitter.on(',').limit(3).trimResults().split(" a , b * , c , d ")} results in {@code ["a", "b", "c , d"]}. * * @param maxItems the maximum number of items returned * @return a splitter with the desired configuration * @since 9.0 */ public Splitter limit(int maxItems) { checkArgument(maxItems > 0, "must be greater than zero: %s", maxItems); return new Splitter(strategy, omitEmptyStrings, trimmer, maxItems); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but automatically * removes leading and trailing {@linkplain CharMatcher#whitespace whitespace} from each returned * substring; equivalent to {@code trimResults(CharMatcher.whitespace())}. For example, {@code * Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable containing {@code ["a", * "b", "c"]}. * * @return a splitter with the desired configuration */ public Splitter trimResults() { return trimResults(CharMatcher.whitespace()); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but removes all leading * or trailing characters matching the given {@code CharMatcher} from each returned substring. For * example, {@code Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")} * returns an iterable containing {@code ["a ", "b_ ", "c"]}. * * @param trimmer a {@link CharMatcher} that determines whether a character should be removed from * the beginning/end of a subsequence * @return a splitter with the desired configuration */ // TODO(kevinb): throw if a trimmer was already specified! public Splitter trimResults(CharMatcher trimmer) { checkNotNull(trimmer); return new Splitter(strategy, omitEmptyStrings, trimmer, limit); } /** * Splits {@code sequence} into string components and makes them available through an {@link * Iterator}, which may be lazily evaluated. If you want an eagerly computed {@link List}, use * {@link #splitToList(CharSequence)}. * * @param sequence the sequence of characters to split * @return an iteration over the segments split from the parameter */ public Iterable<String> split(final CharSequence sequence) { checkNotNull(sequence); return new Iterable<String>() { @Override public Iterator<String> iterator() { return splittingIterator(sequence); } @Override public String toString() { return Joiner.on(", ") .appendTo(new StringBuilder().append('['), this) .append(']') .toString(); } }; } private Iterator<String> splittingIterator(CharSequence sequence) { return strategy.iterator(this, sequence); } /** * Splits {@code sequence} into string components and returns them as an immutable list. If you * want an {@link Iterable} which may be lazily evaluated, use {@link #split(CharSequence)}. * * @param sequence the sequence of characters to split * @return an immutable list of the segments split from the parameter * @since 15.0 */ public List<String> splitToList(CharSequence sequence) { checkNotNull(sequence); Iterator<String> iterator = splittingIterator(sequence); List<String> result = new ArrayList<>(); while (iterator.hasNext()) { result.add(iterator.next()); } return Collections.unmodifiableList(result); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, and splits entries * into keys and values using the specified separator. * * @since 10.0 */ public MapSplitter withKeyValueSeparator(String separator) { return withKeyValueSeparator(on(separator)); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, and splits entries * into keys and values using the specified separator. * * @since 14.0 */ public MapSplitter withKeyValueSeparator(char separator) { return withKeyValueSeparator(on(separator)); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, and splits entries * into keys and values using the specified key-value splitter. * * <p>Note: Any configuration option configured on this splitter, such as {@link #trimResults}, * does not change the behavior of the {@code keyValueSplitter}. * * <p>Example: * * <pre>{@code * String toSplit = " x -> y, z-> a "; * Splitter outerSplitter = Splitter.on(',').trimResults(); * MapSplitter mapSplitter = outerSplitter.withKeyValueSeparator(Splitter.on("->")); * Map<String, String> result = mapSplitter.split(toSplit); * assertThat(result).isEqualTo(ImmutableMap.of("x ", " y", "z", " a")); * }</pre> * * @since 10.0 */ public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) { return new MapSplitter(this, keyValueSplitter); } /** * An object that splits strings into maps as {@code Splitter} splits iterables and lists. Like * {@code Splitter}, it is thread-safe and immutable. The common way to build instances is by * providing an additional {@linkplain Splitter#withKeyValueSeparator key-value separator} to * {@link Splitter}. * * @since 10.0 */ public static final class MapSplitter { private static final String INVALID_ENTRY_MESSAGE = "Chunk [%s] is not a valid entry"; private final Splitter outerSplitter; private final Splitter entrySplitter; private MapSplitter(Splitter outerSplitter, Splitter entrySplitter) { this.outerSplitter = outerSplitter; // only "this" is passed this.entrySplitter = checkNotNull(entrySplitter); } /** * Splits {@code sequence} into substrings, splits each substring into an entry, and returns an * unmodifiable map with each of the entries. For example, {@code * Splitter.on(';').trimResults().withKeyValueSeparator("=>").split("a=>b ; c=>b")} will return * a mapping from {@code "a"} to {@code "b"} and {@code "c"} to {@code "b"}. * * <p>The returned map preserves the order of the entries from {@code sequence}. * * @throws IllegalArgumentException if the specified sequence does not split into valid map * entries, or if there are duplicate keys */ public Map<String, String> split(CharSequence sequence) { Map<String, String> map = new LinkedHashMap<>(); for (String entry : outerSplitter.split(sequence)) { Iterator<String> entryFields = entrySplitter.splittingIterator(entry); checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); String key = entryFields.next(); checkArgument(!map.containsKey(key), "Duplicate key [%s] found.", key); checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); String value = entryFields.next(); map.put(key, value); checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); } return Collections.unmodifiableMap(map); } } private interface Strategy { Iterator<String> iterator(Splitter splitter, CharSequence toSplit); } private abstract static class SplittingIterator extends AbstractIterator<String> { final CharSequence toSplit; final CharMatcher trimmer; final boolean omitEmptyStrings; /** * Returns the first index in {@code toSplit} at or after {@code start} that contains the * separator. */ abstract int separatorStart(int start); /** * Returns the first index in {@code toSplit} after {@code separatorPosition} that does not * contain a separator. This method is only invoked after a call to {@code separatorStart}. */ abstract int separatorEnd(int separatorPosition); int offset = 0; int limit; protected SplittingIterator(Splitter splitter, CharSequence toSplit) { this.trimmer = splitter.trimmer; this.omitEmptyStrings = splitter.omitEmptyStrings; this.limit = splitter.limit; this.toSplit = toSplit; } @CheckForNull @Override protected String computeNext() { /* * The returned string will be from the end of the last match to the beginning of the next * one. nextStart is the start position of the returned substring, while offset is the place * to start looking for a separator. */ int nextStart = offset; while (offset != -1) { int start = nextStart; int end; int separatorPosition = separatorStart(offset); if (separatorPosition == -1) { end = toSplit.length(); offset = -1; } else { end = separatorPosition; offset = separatorEnd(separatorPosition); } if (offset == nextStart) { /* * This occurs when some pattern has an empty match, even if it doesn't match the empty * string -- for example, if it requires lookahead or the like. The offset must be * increased to look for separators beyond this point, without changing the start position * of the next returned substring -- so nextStart stays the same. */ offset++; if (offset > toSplit.length()) { offset = -1; } continue; } while (start < end && trimmer.matches(toSplit.charAt(start))) { start++; } while (end > start && trimmer.matches(toSplit.charAt(end - 1))) { end--; } if (omitEmptyStrings && start == end) { // Don't include the (unused) separator in next split string. nextStart = offset; continue; } if (limit == 1) { // The limit has been reached, return the rest of the string as the // final item. This is tested after empty string removal so that // empty strings do not count towards the limit. end = toSplit.length(); offset = -1; // Since we may have changed the end, we need to trim it again. while (end > start && trimmer.matches(toSplit.charAt(end - 1))) { end--; } } else { limit--; } return toSplit.subSequence(start, end).toString(); } return endOfData(); } } }
google/guava
android/guava/src/com/google/common/base/Splitter.java
337
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.index; import org.elasticsearch.cluster.metadata.IndexMetadata; import org.elasticsearch.cluster.metadata.MetadataCreateDataStreamService; import org.elasticsearch.cluster.routing.IndexRouting; import org.elasticsearch.common.compress.CompressedXContent; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.core.Nullable; import org.elasticsearch.index.mapper.DataStreamTimestampFieldMapper; import org.elasticsearch.index.mapper.DateFieldMapper; import org.elasticsearch.index.mapper.DocumentDimensions; import org.elasticsearch.index.mapper.FieldMapper; import org.elasticsearch.index.mapper.IdFieldMapper; import org.elasticsearch.index.mapper.MapperService; import org.elasticsearch.index.mapper.MappingLookup; import org.elasticsearch.index.mapper.MetadataFieldMapper; import org.elasticsearch.index.mapper.NestedLookup; import org.elasticsearch.index.mapper.ProvidedIdFieldMapper; import org.elasticsearch.index.mapper.RoutingFieldMapper; import org.elasticsearch.index.mapper.SourceFieldMapper; import org.elasticsearch.index.mapper.TimeSeriesIdFieldMapper; import org.elasticsearch.index.mapper.TimeSeriesRoutingHashFieldMapper; import org.elasticsearch.index.mapper.TsidExtractingIdFieldMapper; import java.io.IOException; import java.util.Arrays; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.function.BooleanSupplier; import java.util.stream.Collectors; import java.util.stream.Stream; import static java.util.stream.Collectors.toSet; /** * "Mode" that controls which behaviors and settings an index supports. * <p> * For the most part this class concentrates on validating settings and * mappings. Most different behavior is controlled by forcing settings * to be set or not set and by enabling extra fields in the mapping. */ public enum IndexMode { STANDARD("standard") { @Override void validateWithOtherSettings(Map<Setting<?>, Object> settings) { settingRequiresTimeSeries(settings, IndexMetadata.INDEX_ROUTING_PATH); settingRequiresTimeSeries(settings, IndexSettings.TIME_SERIES_START_TIME); settingRequiresTimeSeries(settings, IndexSettings.TIME_SERIES_END_TIME); } private static void settingRequiresTimeSeries(Map<Setting<?>, Object> settings, Setting<?> setting) { if (false == Objects.equals(setting.getDefault(Settings.EMPTY), settings.get(setting))) { throw new IllegalArgumentException("[" + setting.getKey() + "] requires " + tsdbMode()); } } @Override public void validateMapping(MappingLookup lookup) {}; @Override public void validateAlias(@Nullable String indexRouting, @Nullable String searchRouting) {} @Override public void validateTimestampFieldMapping(boolean isDataStream, MappingLookup mappingLookup) throws IOException { if (isDataStream) { MetadataCreateDataStreamService.validateTimestampFieldMapping(mappingLookup); } } @Override public CompressedXContent getDefaultMapping() { return null; } @Override public TimestampBounds getTimestampBound(IndexMetadata indexMetadata) { return null; } @Override public MetadataFieldMapper timeSeriesIdFieldMapper() { // non time-series indices must not have a TimeSeriesIdFieldMapper return null; } @Override public MetadataFieldMapper timeSeriesRoutingHashFieldMapper() { // non time-series indices must not have a TimeSeriesRoutingIdFieldMapper return null; } @Override public IdFieldMapper idFieldMapperWithoutFieldData() { return ProvidedIdFieldMapper.NO_FIELD_DATA; } @Override public IdFieldMapper buildIdFieldMapper(BooleanSupplier fieldDataEnabled) { return new ProvidedIdFieldMapper(fieldDataEnabled); } @Override public DocumentDimensions buildDocumentDimensions(IndexSettings settings) { return new DocumentDimensions.OnlySingleValueAllowed(); } @Override public boolean shouldValidateTimestamp() { return false; } @Override public void validateSourceFieldMapper(SourceFieldMapper sourceFieldMapper) {} @Override public boolean isSyntheticSourceEnabled() { return false; } }, TIME_SERIES("time_series") { @Override void validateWithOtherSettings(Map<Setting<?>, Object> settings) { if (settings.get(IndexMetadata.INDEX_ROUTING_PARTITION_SIZE_SETTING) != Integer.valueOf(1)) { throw new IllegalArgumentException(error(IndexMetadata.INDEX_ROUTING_PARTITION_SIZE_SETTING)); } for (Setting<?> unsupported : TIME_SERIES_UNSUPPORTED) { if (false == Objects.equals(unsupported.getDefault(Settings.EMPTY), settings.get(unsupported))) { throw new IllegalArgumentException(error(unsupported)); } } checkSetting(settings, IndexMetadata.INDEX_ROUTING_PATH); } private static void checkSetting(Map<Setting<?>, Object> settings, Setting<?> setting) { if (Objects.equals(setting.getDefault(Settings.EMPTY), settings.get(setting))) { throw new IllegalArgumentException(tsdbMode() + " requires a non-empty [" + setting.getKey() + "]"); } } private static String error(Setting<?> unsupported) { return tsdbMode() + " is incompatible with [" + unsupported.getKey() + "]"; } @Override public void validateMapping(MappingLookup lookup) { if (lookup.nestedLookup() != NestedLookup.EMPTY) { throw new IllegalArgumentException("cannot have nested fields when index is in " + tsdbMode()); } if (((RoutingFieldMapper) lookup.getMapper(RoutingFieldMapper.NAME)).required()) { throw new IllegalArgumentException(routingRequiredBad()); } } @Override public void validateAlias(@Nullable String indexRouting, @Nullable String searchRouting) { if (indexRouting != null || searchRouting != null) { throw new IllegalArgumentException(routingRequiredBad()); } } @Override public void validateTimestampFieldMapping(boolean isDataStream, MappingLookup mappingLookup) throws IOException { MetadataCreateDataStreamService.validateTimestampFieldMapping(mappingLookup); } @Override public CompressedXContent getDefaultMapping() { return DEFAULT_TIME_SERIES_TIMESTAMP_MAPPING; } @Override public TimestampBounds getTimestampBound(IndexMetadata indexMetadata) { return new TimestampBounds(indexMetadata.getTimeSeriesStart(), indexMetadata.getTimeSeriesEnd()); } private static String routingRequiredBad() { return "routing is forbidden on CRUD operations that target indices in " + tsdbMode(); } @Override public MetadataFieldMapper timeSeriesIdFieldMapper() { return TimeSeriesIdFieldMapper.INSTANCE; } @Override public MetadataFieldMapper timeSeriesRoutingHashFieldMapper() { return TimeSeriesRoutingHashFieldMapper.INSTANCE; } public IdFieldMapper idFieldMapperWithoutFieldData() { return TsidExtractingIdFieldMapper.INSTANCE; } @Override public IdFieldMapper buildIdFieldMapper(BooleanSupplier fieldDataEnabled) { // We don't support field data on TSDB's _id return TsidExtractingIdFieldMapper.INSTANCE; } @Override public DocumentDimensions buildDocumentDimensions(IndexSettings settings) { IndexRouting.ExtractFromSource routing = (IndexRouting.ExtractFromSource) settings.getIndexRouting(); return new TimeSeriesIdFieldMapper.TimeSeriesIdBuilder(routing.builder()); } @Override public boolean shouldValidateTimestamp() { return true; } @Override public void validateSourceFieldMapper(SourceFieldMapper sourceFieldMapper) { if (sourceFieldMapper.isSynthetic() == false) { throw new IllegalArgumentException("time series indices only support synthetic source"); } } @Override public boolean isSyntheticSourceEnabled() { return true; } }; protected static String tsdbMode() { return "[" + IndexSettings.MODE.getKey() + "=time_series]"; } public static final CompressedXContent DEFAULT_TIME_SERIES_TIMESTAMP_MAPPING; static { try { DEFAULT_TIME_SERIES_TIMESTAMP_MAPPING = new CompressedXContent( ((builder, params) -> builder.startObject(MapperService.SINGLE_MAPPING_NAME) .startObject(DataStreamTimestampFieldMapper.NAME) .field("enabled", true) .endObject() .startObject("properties") .startObject(DataStreamTimestampFieldMapper.DEFAULT_PATH) .field("type", DateFieldMapper.CONTENT_TYPE) .field("ignore_malformed", "false") .endObject() .endObject() .endObject()) ); } catch (IOException e) { throw new AssertionError(e); } } private static final List<Setting<?>> TIME_SERIES_UNSUPPORTED = List.of( IndexSortConfig.INDEX_SORT_FIELD_SETTING, IndexSortConfig.INDEX_SORT_ORDER_SETTING, IndexSortConfig.INDEX_SORT_MODE_SETTING, IndexSortConfig.INDEX_SORT_MISSING_SETTING ); static final List<Setting<?>> VALIDATE_WITH_SETTINGS = List.copyOf( Stream.concat( Stream.of( IndexMetadata.INDEX_ROUTING_PARTITION_SIZE_SETTING, IndexMetadata.INDEX_ROUTING_PATH, IndexSettings.TIME_SERIES_START_TIME, IndexSettings.TIME_SERIES_END_TIME ), TIME_SERIES_UNSUPPORTED.stream() ).collect(toSet()) ); private final String name; IndexMode(String name) { this.name = name; } public String getName() { return name; } abstract void validateWithOtherSettings(Map<Setting<?>, Object> settings); /** * Validate the mapping for this index. */ public abstract void validateMapping(MappingLookup lookup); /** * Validate aliases targeting this index. */ public abstract void validateAlias(@Nullable String indexRouting, @Nullable String searchRouting); /** * validate timestamp mapping for this index. */ public abstract void validateTimestampFieldMapping(boolean isDataStream, MappingLookup mappingLookup) throws IOException; /** * Get default mapping for this index or {@code null} if there is none. */ @Nullable public abstract CompressedXContent getDefaultMapping(); /** * Build the {@link FieldMapper} for {@code _id}. */ public abstract IdFieldMapper buildIdFieldMapper(BooleanSupplier fieldDataEnabled); /** * Get the singleton {@link FieldMapper} for {@code _id}. It can never support * field data. */ public abstract IdFieldMapper idFieldMapperWithoutFieldData(); /** * @return the time range based on the provided index metadata and index mode implementation. * Otherwise <code>null</code> is returned. */ @Nullable public abstract TimestampBounds getTimestampBound(IndexMetadata indexMetadata); /** * Return an instance of the {@link TimeSeriesIdFieldMapper} that generates * the _tsid field. The field mapper will be added to the list of the metadata * field mappers for the index. */ public abstract MetadataFieldMapper timeSeriesIdFieldMapper(); /** * Return an instance of the {@link TimeSeriesRoutingHashFieldMapper} that generates * the _ts_routing_hash field. The field mapper will be added to the list of the metadata * field mappers for the index. */ public abstract MetadataFieldMapper timeSeriesRoutingHashFieldMapper(); /** * How {@code time_series_dimension} fields are handled by indices in this mode. */ public abstract DocumentDimensions buildDocumentDimensions(IndexSettings settings); /** * @return Whether timestamps should be validated for being withing the time range of an index. */ public abstract boolean shouldValidateTimestamp(); /** * Validates the source field mapper */ public abstract void validateSourceFieldMapper(SourceFieldMapper sourceFieldMapper); /** * @return whether synthetic source is the only allowed source mode. */ public abstract boolean isSyntheticSourceEnabled(); /** * Parse a string into an {@link IndexMode}. */ public static IndexMode fromString(String value) { return switch (value) { case "standard" -> IndexMode.STANDARD; case "time_series" -> IndexMode.TIME_SERIES; default -> throw new IllegalArgumentException( "[" + value + "] is an invalid index mode, valid modes are: [" + Arrays.stream(IndexMode.values()).map(IndexMode::toString).collect(Collectors.joining()) + "]" ); }; } @Override public String toString() { return getName(); } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/index/IndexMode.java
338
/* * 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 static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Collections.emptyMap; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Objects; import com.google.common.collect.Maps.IteratorBasedAbstractMap; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.DoNotCall; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.j2objc.annotations.WeakOuter; import java.io.Serializable; import java.lang.reflect.Array; import java.util.Arrays; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.Spliterator; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Fixed-size {@link Table} implementation backed by a two-dimensional array. * * <p><b>Warning:</b> {@code ArrayTable} is rarely the {@link Table} implementation you want. First, * it requires that the complete universe of rows and columns be specified at construction time. * Second, it is always backed by an array large enough to hold a value for every possible * combination of row and column keys. (This is rarely optimal unless the table is extremely dense.) * Finally, every possible combination of row and column keys is always considered to have a value * associated with it: It is not possible to "remove" a value, only to replace it with {@code null}, * which will still appear when iterating over the table's contents in a foreach loop or a call to a * null-hostile method like {@link ImmutableTable#copyOf}. For alternatives, please see <a * href="https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">the wiki</a>. * * <p>The allowed row and column keys must be supplied when the table is created. The table always * contains a mapping for every row key / column pair. The value corresponding to a given row and * column is null unless another value is provided. * * <p>The table's size is constant: the product of the number of supplied row keys and the number of * supplied column keys. The {@code remove} and {@code clear} methods are not supported by the table * or its views. The {@link #erase} and {@link #eraseAll} methods may be used instead. * * <p>The ordering of the row and column keys provided when the table is constructed determines the * iteration ordering across rows and columns in the table's views. None of the view iterators * support {@link Iterator#remove}. If the table is modified after an iterator is created, the * iterator remains valid. * * <p>This class requires less memory than the {@link HashBasedTable} and {@link TreeBasedTable} * implementations, except when the table is sparse. * * <p>Null row keys or column keys are not permitted. * * <p>This class provides methods involving the underlying array structure, where the array indices * correspond to the position of a row or column in the lists of allowed keys and values. See the * {@link #at}, {@link #set}, {@link #toArray}, {@link #rowKeyList}, and {@link #columnKeyList} * methods for more details. * * <p>Note that this implementation is not synchronized. If multiple threads access the same cell of * an {@code ArrayTable} concurrently and one of the threads modifies its value, there is no * guarantee that the new value will be fully visible to the other threads. To guarantee that * modifications are visible, synchronize access to the table. Unlike other {@code Table} * implementations, synchronization is unnecessary between a thread that writes to one cell and a * thread that reads from another. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#table">{@code Table}</a>. * * @author Jared Levy * @since 10.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class ArrayTable<R, C, V> extends AbstractTable<R, C, @Nullable V> implements Serializable { /** * Creates an {@code ArrayTable} filled with {@code null}. * * @param rowKeys row keys that may be stored in the generated table * @param columnKeys column keys that may be stored in the generated table * @throws NullPointerException if any of the provided keys is null * @throws IllegalArgumentException if {@code rowKeys} or {@code columnKeys} contains duplicates * or if exactly one of {@code rowKeys} or {@code columnKeys} is empty. */ public static <R, C, V> ArrayTable<R, C, V> create( Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) { return new ArrayTable<>(rowKeys, columnKeys); } /* * TODO(jlevy): Add factory methods taking an Enum class, instead of an * iterable, to specify the allowed row keys and/or column keys. Note that * custom serialization logic is needed to support different enum sizes during * serialization and deserialization. */ /** * Creates an {@code ArrayTable} with the mappings in the provided table. * * <p>If {@code table} includes a mapping with row key {@code r} and a separate mapping with * column key {@code c}, the returned table contains a mapping with row key {@code r} and column * key {@code c}. If that row key / column key pair in not in {@code table}, the pair maps to * {@code null} in the generated table. * * <p>The returned table allows subsequent {@code put} calls with the row keys in {@code * table.rowKeySet()} and the column keys in {@code table.columnKeySet()}. Calling {@link #put} * with other keys leads to an {@code IllegalArgumentException}. * * <p>The ordering of {@code table.rowKeySet()} and {@code table.columnKeySet()} determines the * row and column iteration ordering of the returned table. * * @throws NullPointerException if {@code table} has a null key */ @SuppressWarnings("unchecked") // TODO(cpovirk): Make constructor accept wildcard types? public static <R, C, V> ArrayTable<R, C, V> create(Table<R, C, ? extends @Nullable V> table) { return (table instanceof ArrayTable) ? new ArrayTable<R, C, V>((ArrayTable<R, C, V>) table) : new ArrayTable<R, C, V>(table); } private final ImmutableList<R> rowList; private final ImmutableList<C> columnList; // TODO(jlevy): Add getters returning rowKeyToIndex and columnKeyToIndex? private final ImmutableMap<R, Integer> rowKeyToIndex; private final ImmutableMap<C, Integer> columnKeyToIndex; private final @Nullable V[][] array; private ArrayTable(Iterable<? extends R> rowKeys, Iterable<? extends C> columnKeys) { this.rowList = ImmutableList.copyOf(rowKeys); this.columnList = ImmutableList.copyOf(columnKeys); checkArgument(rowList.isEmpty() == columnList.isEmpty()); /* * TODO(jlevy): Support only one of rowKey / columnKey being empty? If we * do, when columnKeys is empty but rowKeys isn't, rowKeyList() can contain * elements but rowKeySet() will be empty and containsRow() won't * acknowledge them. */ rowKeyToIndex = Maps.indexMap(rowList); columnKeyToIndex = Maps.indexMap(columnList); @SuppressWarnings("unchecked") @Nullable V[][] tmpArray = (@Nullable V[][]) new Object[rowList.size()][columnList.size()]; array = tmpArray; // Necessary because in GWT the arrays are initialized with "undefined" instead of null. eraseAll(); } private ArrayTable(Table<R, C, ? extends @Nullable V> table) { this(table.rowKeySet(), table.columnKeySet()); putAll(table); } private ArrayTable(ArrayTable<R, C, V> table) { rowList = table.rowList; columnList = table.columnList; rowKeyToIndex = table.rowKeyToIndex; columnKeyToIndex = table.columnKeyToIndex; @SuppressWarnings("unchecked") @Nullable V[][] copy = (@Nullable V[][]) new Object[rowList.size()][columnList.size()]; array = copy; for (int i = 0; i < rowList.size(); i++) { System.arraycopy(table.array[i], 0, copy[i], 0, table.array[i].length); } } private abstract static class ArrayMap<K, V extends @Nullable Object> extends IteratorBasedAbstractMap<K, V> { private final ImmutableMap<K, Integer> keyIndex; private ArrayMap(ImmutableMap<K, Integer> keyIndex) { this.keyIndex = keyIndex; } @Override public Set<K> keySet() { return keyIndex.keySet(); } K getKey(int index) { return keyIndex.keySet().asList().get(index); } abstract String getKeyRole(); @ParametricNullness abstract V getValue(int index); @ParametricNullness abstract V setValue(int index, @ParametricNullness V newValue); @Override public int size() { return keyIndex.size(); } @Override public boolean isEmpty() { return keyIndex.isEmpty(); } Entry<K, V> getEntry(final int index) { checkElementIndex(index, size()); return new AbstractMapEntry<K, V>() { @Override public K getKey() { return ArrayMap.this.getKey(index); } @Override @ParametricNullness public V getValue() { return ArrayMap.this.getValue(index); } @Override @ParametricNullness public V setValue(@ParametricNullness V value) { return ArrayMap.this.setValue(index, value); } }; } @Override Iterator<Entry<K, V>> entryIterator() { return new AbstractIndexedListIterator<Entry<K, V>>(size()) { @Override protected Entry<K, V> get(final int index) { return getEntry(index); } }; } @Override Spliterator<Entry<K, V>> entrySpliterator() { return CollectSpliterators.indexed(size(), Spliterator.ORDERED, this::getEntry); } // TODO(lowasser): consider an optimized values() implementation @Override public boolean containsKey(@CheckForNull Object key) { return keyIndex.containsKey(key); } @CheckForNull @Override public V get(@CheckForNull Object key) { Integer index = keyIndex.get(key); if (index == null) { return null; } else { return getValue(index); } } @Override @CheckForNull public V put(K key, @ParametricNullness V value) { Integer index = keyIndex.get(key); if (index == null) { throw new IllegalArgumentException( getKeyRole() + " " + key + " not in " + keyIndex.keySet()); } return setValue(index, value); } @Override @CheckForNull public V remove(@CheckForNull Object key) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } } /** * Returns, as an immutable list, the row keys provided when the table was constructed, including * those that are mapped to null values only. */ public ImmutableList<R> rowKeyList() { return rowList; } /** * Returns, as an immutable list, the column keys provided when the table was constructed, * including those that are mapped to null values only. */ public ImmutableList<C> columnKeyList() { return columnList; } /** * Returns the value corresponding to the specified row and column indices. The same value is * returned by {@code get(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex))}, but this * method runs more quickly. * * @param rowIndex position of the row key in {@link #rowKeyList()} * @param columnIndex position of the row key in {@link #columnKeyList()} * @return the value with the specified row and column * @throws IndexOutOfBoundsException if either index is negative, {@code rowIndex} is greater than * or equal to the number of allowed row keys, or {@code columnIndex} is greater than or equal * to the number of allowed column keys */ @CheckForNull public V at(int rowIndex, int columnIndex) { // In GWT array access never throws IndexOutOfBoundsException. checkElementIndex(rowIndex, rowList.size()); checkElementIndex(columnIndex, columnList.size()); return array[rowIndex][columnIndex]; } /** * Associates {@code value} with the specified row and column indices. The logic {@code * put(rowKeyList().get(rowIndex), columnKeyList().get(columnIndex), value)} has the same * behavior, but this method runs more quickly. * * @param rowIndex position of the row key in {@link #rowKeyList()} * @param columnIndex position of the row key in {@link #columnKeyList()} * @param value value to store in the table * @return the previous value with the specified row and column * @throws IndexOutOfBoundsException if either index is negative, {@code rowIndex} is greater than * or equal to the number of allowed row keys, or {@code columnIndex} is greater than or equal * to the number of allowed column keys */ @CanIgnoreReturnValue @CheckForNull public V set(int rowIndex, int columnIndex, @CheckForNull V value) { // In GWT array access never throws IndexOutOfBoundsException. checkElementIndex(rowIndex, rowList.size()); checkElementIndex(columnIndex, columnList.size()); V oldValue = array[rowIndex][columnIndex]; array[rowIndex][columnIndex] = value; return oldValue; } /** * Returns a two-dimensional array with the table contents. The row and column indices correspond * to the positions of the row and column in the iterables provided during table construction. If * the table lacks a mapping for a given row and column, the corresponding array element is null. * * <p>Subsequent table changes will not modify the array, and vice versa. * * @param valueClass class of values stored in the returned array */ @GwtIncompatible // reflection public @Nullable V[][] toArray(Class<V> valueClass) { @SuppressWarnings("unchecked") // TODO: safe? @Nullable V[][] copy = (@Nullable V[][]) Array.newInstance(valueClass, rowList.size(), columnList.size()); for (int i = 0; i < rowList.size(); i++) { System.arraycopy(array[i], 0, copy[i], 0, array[i].length); } return copy; } /** * Not supported. Use {@link #eraseAll} instead. * * @throws UnsupportedOperationException always * @deprecated Use {@link #eraseAll} */ @DoNotCall("Always throws UnsupportedOperationException") @Override @Deprecated public void clear() { throw new UnsupportedOperationException(); } /** Associates the value {@code null} with every pair of allowed row and column keys. */ public void eraseAll() { for (@Nullable V[] row : array) { Arrays.fill(row, null); } } /** * Returns {@code true} if the provided keys are among the keys provided when the table was * constructed. */ @Override public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return containsRow(rowKey) && containsColumn(columnKey); } /** * Returns {@code true} if the provided column key is among the column keys provided when the * table was constructed. */ @Override public boolean containsColumn(@CheckForNull Object columnKey) { return columnKeyToIndex.containsKey(columnKey); } /** * Returns {@code true} if the provided row key is among the row keys provided when the table was * constructed. */ @Override public boolean containsRow(@CheckForNull Object rowKey) { return rowKeyToIndex.containsKey(rowKey); } @Override public boolean containsValue(@CheckForNull Object value) { for (@Nullable V[] row : array) { for (V element : row) { if (Objects.equal(value, element)) { return true; } } } return false; } @Override @CheckForNull public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { Integer rowIndex = rowKeyToIndex.get(rowKey); Integer columnIndex = columnKeyToIndex.get(columnKey); return (rowIndex == null || columnIndex == null) ? null : at(rowIndex, columnIndex); } /** * Returns {@code true} if {@code rowKeyList().size == 0} or {@code columnKeyList().size() == 0}. */ @Override public boolean isEmpty() { return rowList.isEmpty() || columnList.isEmpty(); } /** * {@inheritDoc} * * @throws IllegalArgumentException if {@code rowKey} is not in {@link #rowKeySet()} or {@code * columnKey} is not in {@link #columnKeySet()}. */ @CanIgnoreReturnValue @Override @CheckForNull public V put(R rowKey, C columnKey, @CheckForNull V value) { checkNotNull(rowKey); checkNotNull(columnKey); Integer rowIndex = rowKeyToIndex.get(rowKey); checkArgument(rowIndex != null, "Row %s not in %s", rowKey, rowList); Integer columnIndex = columnKeyToIndex.get(columnKey); checkArgument(columnIndex != null, "Column %s not in %s", columnKey, columnList); return set(rowIndex, columnIndex, value); } /* * TODO(jlevy): Consider creating a merge() method, similar to putAll() but * copying non-null values only. */ /** * {@inheritDoc} * * <p>If {@code table} is an {@code ArrayTable}, its null values will be stored in this table, * possibly replacing values that were previously non-null. * * @throws NullPointerException if {@code table} has a null key * @throws IllegalArgumentException if any of the provided table's row keys or column keys is not * in {@link #rowKeySet()} or {@link #columnKeySet()} */ @Override public void putAll(Table<? extends R, ? extends C, ? extends @Nullable V> table) { super.putAll(table); } /** * Not supported. Use {@link #erase} instead. * * @throws UnsupportedOperationException always * @deprecated Use {@link #erase} */ @DoNotCall("Always throws UnsupportedOperationException") @CanIgnoreReturnValue @Override @Deprecated @CheckForNull public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { throw new UnsupportedOperationException(); } /** * Associates the value {@code null} with the specified keys, assuming both keys are valid. If * either key is null or isn't among the keys provided during construction, this method has no * effect. * * <p>This method is equivalent to {@code put(rowKey, columnKey, null)} when both provided keys * are valid. * * @param rowKey row key of mapping to be erased * @param columnKey column key of mapping to be erased * @return the value previously associated with the keys, or {@code null} if no mapping existed * for the keys */ @CanIgnoreReturnValue @CheckForNull public V erase(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { Integer rowIndex = rowKeyToIndex.get(rowKey); Integer columnIndex = columnKeyToIndex.get(columnKey); if (rowIndex == null || columnIndex == null) { return null; } return set(rowIndex, columnIndex, null); } // TODO(jlevy): Add eraseRow and eraseColumn methods? @Override public int size() { return rowList.size() * columnList.size(); } /** * Returns an unmodifiable set of all row key / column key / value triplets. Changes to the table * will update the returned set. * * <p>The returned set's iterator traverses the mappings with the first row key, the mappings with * the second row key, and so on. * * <p>The value in the returned cells may change if the table subsequently changes. * * @return set of table cells consisting of row key / column key / value triplets */ @Override public Set<Cell<R, C, @Nullable V>> cellSet() { return super.cellSet(); } @Override Iterator<Cell<R, C, @Nullable V>> cellIterator() { return new AbstractIndexedListIterator<Cell<R, C, @Nullable V>>(size()) { @Override protected Cell<R, C, @Nullable V> get(final int index) { return getCell(index); } }; } @Override Spliterator<Cell<R, C, @Nullable V>> cellSpliterator() { return CollectSpliterators.<Cell<R, C, @Nullable V>>indexed( size(), Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.DISTINCT, this::getCell); } private Cell<R, C, @Nullable V> getCell(final int index) { return new Tables.AbstractCell<R, C, @Nullable V>() { final int rowIndex = index / columnList.size(); final int columnIndex = index % columnList.size(); @Override public R getRowKey() { return rowList.get(rowIndex); } @Override public C getColumnKey() { return columnList.get(columnIndex); } @Override @CheckForNull public V getValue() { return at(rowIndex, columnIndex); } }; } @CheckForNull private V getValue(int index) { int rowIndex = index / columnList.size(); int columnIndex = index % columnList.size(); return at(rowIndex, columnIndex); } /** * Returns a view of all mappings that have the given column key. If the column key isn't in * {@link #columnKeySet()}, an empty immutable map is returned. * * <p>Otherwise, for each row key in {@link #rowKeySet()}, the returned map associates the row key * with the corresponding value in the table. Changes to the returned map will update the * underlying table, and vice versa. * * @param columnKey key of column to search for in the table * @return the corresponding map from row keys to values */ @Override public Map<R, @Nullable V> column(C columnKey) { checkNotNull(columnKey); Integer columnIndex = columnKeyToIndex.get(columnKey); if (columnIndex == null) { return emptyMap(); } else { return new Column(columnIndex); } } private class Column extends ArrayMap<R, @Nullable V> { final int columnIndex; Column(int columnIndex) { super(rowKeyToIndex); this.columnIndex = columnIndex; } @Override String getKeyRole() { return "Row"; } @Override @CheckForNull V getValue(int index) { return at(index, columnIndex); } @Override @CheckForNull V setValue(int index, @CheckForNull V newValue) { return set(index, columnIndex, newValue); } } /** * Returns an immutable set of the valid column keys, including those that are associated with * null values only. * * @return immutable set of column keys */ @Override public ImmutableSet<C> columnKeySet() { return columnKeyToIndex.keySet(); } @LazyInit @CheckForNull private transient ColumnMap columnMap; @Override public Map<C, Map<R, @Nullable V>> columnMap() { ColumnMap map = columnMap; return (map == null) ? columnMap = new ColumnMap() : map; } @WeakOuter private class ColumnMap extends ArrayMap<C, Map<R, @Nullable V>> { private ColumnMap() { super(columnKeyToIndex); } @Override String getKeyRole() { return "Column"; } @Override Map<R, @Nullable V> getValue(int index) { return new Column(index); } @Override Map<R, @Nullable V> setValue(int index, Map<R, @Nullable V> newValue) { throw new UnsupportedOperationException(); } @Override @CheckForNull public Map<R, @Nullable V> put(C key, Map<R, @Nullable V> value) { throw new UnsupportedOperationException(); } } /** * Returns a view of all mappings that have the given row key. If the row key isn't in {@link * #rowKeySet()}, an empty immutable map is returned. * * <p>Otherwise, for each column key in {@link #columnKeySet()}, the returned map associates the * column key with the corresponding value in the table. Changes to the returned map will update * the underlying table, and vice versa. * * @param rowKey key of row to search for in the table * @return the corresponding map from column keys to values */ @Override public Map<C, @Nullable V> row(R rowKey) { checkNotNull(rowKey); Integer rowIndex = rowKeyToIndex.get(rowKey); if (rowIndex == null) { return emptyMap(); } else { return new Row(rowIndex); } } private class Row extends ArrayMap<C, @Nullable V> { final int rowIndex; Row(int rowIndex) { super(columnKeyToIndex); this.rowIndex = rowIndex; } @Override String getKeyRole() { return "Column"; } @Override @CheckForNull V getValue(int index) { return at(rowIndex, index); } @Override @CheckForNull V setValue(int index, @CheckForNull V newValue) { return set(rowIndex, index, newValue); } } /** * Returns an immutable set of the valid row keys, including those that are associated with null * values only. * * @return immutable set of row keys */ @Override public ImmutableSet<R> rowKeySet() { return rowKeyToIndex.keySet(); } @LazyInit @CheckForNull private transient RowMap rowMap; @Override public Map<R, Map<C, @Nullable V>> rowMap() { RowMap map = rowMap; return (map == null) ? rowMap = new RowMap() : map; } @WeakOuter private class RowMap extends ArrayMap<R, Map<C, @Nullable V>> { private RowMap() { super(rowKeyToIndex); } @Override String getKeyRole() { return "Row"; } @Override Map<C, @Nullable V> getValue(int index) { return new Row(index); } @Override Map<C, @Nullable V> setValue(int index, Map<C, @Nullable V> newValue) { throw new UnsupportedOperationException(); } @Override @CheckForNull public Map<C, @Nullable V> put(R key, Map<C, @Nullable V> value) { throw new UnsupportedOperationException(); } } /** * Returns an unmodifiable collection of all values, which may contain duplicates. Changes to the * table will update the returned collection. * * <p>The returned collection's iterator traverses the values of the first row key, the values of * the second row key, and so on. * * @return collection of values */ @Override public Collection<@Nullable V> values() { return super.values(); } @Override Iterator<@Nullable V> valuesIterator() { return new AbstractIndexedListIterator<@Nullable V>(size()) { @Override @CheckForNull protected V get(int index) { return getValue(index); } }; } @Override Spliterator<@Nullable V> valuesSpliterator() { return CollectSpliterators.<@Nullable V>indexed(size(), Spliterator.ORDERED, this::getValue); } private static final long serialVersionUID = 0; }
google/guava
guava/src/com/google/common/collect/ArrayTable.java
339
/* * 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.io; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Throwables.throwIfInstanceOf; import static com.google.common.base.Throwables.throwIfUnchecked; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.Closeable; import java.io.IOException; import java.util.ArrayDeque; import java.util.Deque; import java.util.logging.Level; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A {@link Closeable} that collects {@code Closeable} resources and closes them all when it is * {@linkplain #close closed}. This was intended to approximately emulate the behavior of Java 7's * <a href="http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html" * >try-with-resources</a> statement in JDK6-compatible code. Code using this should be * approximately equivalent in behavior to the same code written with try-with-resources. * * <p>This class is intended to be used in the following pattern: * * <pre>{@code * Closer closer = Closer.create(); * try { * InputStream in = closer.register(openInputStream()); * OutputStream out = closer.register(openOutputStream()); * // do stuff * } catch (Throwable e) { * // ensure that any checked exception types other than IOException that could be thrown are * // provided here, e.g. throw closer.rethrow(e, CheckedException.class); * throw closer.rethrow(e); * } finally { * closer.close(); * } * }</pre> * * <p>Note that this try-catch-finally block is not equivalent to a try-catch-finally block using * try-with-resources. To get the equivalent of that, you must wrap the above code in <i>another</i> * try block in order to catch any exception that may be thrown (including from the call to {@code * close()}). * * <p>This pattern ensures the following: * * <ul> * <li>Each {@code Closeable} resource that is successfully registered will be closed later. * <li>If a {@code Throwable} is thrown in the try block, no exceptions that occur when attempting * to close resources will be thrown from the finally block. The throwable from the try block * will be thrown. * <li>If no exceptions or errors were thrown in the try block, the <i>first</i> exception thrown * by an attempt to close a resource will be thrown. * <li>Any exception caught when attempting to close a resource that is <i>not</i> thrown (because * another exception is already being thrown) is <i>suppressed</i>. * </ul> * * <p>An exception that is suppressed is added to the exception that <i>will</i> be thrown using * {@code Throwable.addSuppressed(Throwable)}. * * @author Colin Decker * @since 14.0 */ // Coffee's for {@link Closer closers} only. @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public final class Closer implements Closeable { /** Creates a new {@link Closer}. */ public static Closer create() { return new Closer(SUPPRESSING_SUPPRESSOR); } @VisibleForTesting final Suppressor suppressor; // only need space for 2 elements in most cases, so try to use the smallest array possible private final Deque<Closeable> stack = new ArrayDeque<>(4); @CheckForNull private Throwable thrown; @VisibleForTesting Closer(Suppressor suppressor) { this.suppressor = checkNotNull(suppressor); // checkNotNull to satisfy null tests } /** * Registers the given {@code closeable} to be closed when this {@code Closer} is {@linkplain * #close closed}. * * @return the given {@code closeable} */ // close. this word no longer has any meaning to me. @CanIgnoreReturnValue @ParametricNullness public <C extends @Nullable Closeable> C register(@ParametricNullness C closeable) { if (closeable != null) { stack.addFirst(closeable); } return closeable; } /** * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code * IOException}, {@code RuntimeException} or {@code Error}. Otherwise, it will be rethrown wrapped * in a {@code RuntimeException}. <b>Note:</b> Be sure to declare all of the checked exception * types your try block can throw when calling an overload of this method so as to avoid losing * the original exception type. * * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e);} * to ensure the compiler knows that it will throw. * * @return this method does not return; it always throws * @throws IOException when the given throwable is an IOException */ public RuntimeException rethrow(Throwable e) throws IOException { checkNotNull(e); thrown = e; throwIfInstanceOf(e, IOException.class); throwIfUnchecked(e); throw new RuntimeException(e); } /** * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code * IOException}, {@code RuntimeException}, {@code Error} or a checked exception of the given type. * Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b> Be sure to * declare all of the checked exception types your try block can throw when calling an overload of * this method so as to avoid losing the original exception type. * * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e, * ...);} to ensure the compiler knows that it will throw. * * @return this method does not return; it always throws * @throws IOException when the given throwable is an IOException * @throws X when the given throwable is of the declared type X */ public <X extends Exception> RuntimeException rethrow(Throwable e, Class<X> declaredType) throws IOException, X { checkNotNull(e); thrown = e; throwIfInstanceOf(e, IOException.class); throwIfInstanceOf(e, declaredType); throwIfUnchecked(e); throw new RuntimeException(e); } /** * Stores the given throwable and rethrows it. It will be rethrown as is if it is an {@code * IOException}, {@code RuntimeException}, {@code Error} or a checked exception of either of the * given types. Otherwise, it will be rethrown wrapped in a {@code RuntimeException}. <b>Note:</b> * Be sure to declare all of the checked exception types your try block can throw when calling an * overload of this method so as to avoid losing the original exception type. * * <p>This method always throws, and as such should be called as {@code throw closer.rethrow(e, * ...);} to ensure the compiler knows that it will throw. * * @return this method does not return; it always throws * @throws IOException when the given throwable is an IOException * @throws X1 when the given throwable is of the declared type X1 * @throws X2 when the given throwable is of the declared type X2 */ public <X1 extends Exception, X2 extends Exception> RuntimeException rethrow( Throwable e, Class<X1> declaredType1, Class<X2> declaredType2) throws IOException, X1, X2 { checkNotNull(e); thrown = e; throwIfInstanceOf(e, IOException.class); throwIfInstanceOf(e, declaredType1); throwIfInstanceOf(e, declaredType2); throwIfUnchecked(e); throw new RuntimeException(e); } /** * Closes all {@code Closeable} instances that have been added to this {@code Closer}. If an * exception was thrown in the try block and passed to one of the {@code exceptionThrown} methods, * any exceptions thrown when attempting to close a closeable will be suppressed. Otherwise, the * <i>first</i> exception to be thrown from an attempt to close a closeable will be thrown and any * additional exceptions that are thrown after that will be suppressed. */ @Override public void close() throws IOException { Throwable throwable = thrown; // close closeables in LIFO order while (!stack.isEmpty()) { Closeable closeable = stack.removeFirst(); try { closeable.close(); } catch (Throwable e) { if (throwable == null) { throwable = e; } else { suppressor.suppress(closeable, throwable, e); } } } if (thrown == null && throwable != null) { throwIfInstanceOf(throwable, IOException.class); throwIfUnchecked(throwable); throw new AssertionError(throwable); // not possible } } /** Suppression strategy interface. */ @VisibleForTesting interface Suppressor { /** * Suppresses the given exception ({@code suppressed}) which was thrown when attempting to close * the given closeable. {@code thrown} is the exception that is actually being thrown from the * method. Implementations of this method should not throw under any circumstances. */ void suppress(Closeable closeable, Throwable thrown, Throwable suppressed); } /** * Suppresses exceptions by adding them to the exception that will be thrown using the * addSuppressed(Throwable) mechanism. */ private static final Suppressor SUPPRESSING_SUPPRESSOR = (closeable, thrown, suppressed) -> { // ensure no exceptions from addSuppressed if (thrown == suppressed) { return; } try { thrown.addSuppressed(suppressed); } catch (Throwable e) { /* * A Throwable is very unlikely, but we really don't want to throw from a Suppressor, so * we catch everything. (Any Exception is either a RuntimeException or * sneaky checked exception.) With no better options, we log anything to the same * place as Closeables logs. */ Closeables.logger.log( Level.WARNING, "Suppressing exception thrown when closing " + closeable, suppressed); } }; }
google/guava
guava/src/com/google/common/io/Closer.java
341
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.bytecode; import lombok.AllArgsConstructor; import lombok.Getter; import lombok.Setter; import lombok.extern.slf4j.Slf4j; /** * This class represent game objects which properties can be changed by instructions interpreted by * virtual machine. */ @AllArgsConstructor @Setter @Getter @Slf4j public class Wizard { private int health; private int agility; private int wisdom; private int numberOfPlayedSounds; private int numberOfSpawnedParticles; public void playSound() { LOGGER.info("Playing sound"); numberOfPlayedSounds++; } public void spawnParticles() { LOGGER.info("Spawning particles"); numberOfSpawnedParticles++; } }
smedals/java-design-patterns
bytecode/src/main/java/com/iluwatar/bytecode/Wizard.java
342
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.regex.Pattern; import java.util.stream.Stream; import java.util.stream.StreamSupport; import javax.annotation.CheckForNull; /** * Extracts non-overlapping substrings from an input string, typically by recognizing appearances of * a <i>separator</i> sequence. This separator can be specified as a single {@linkplain #on(char) * character}, fixed {@linkplain #on(String) string}, {@linkplain #onPattern regular expression} or * {@link #on(CharMatcher) CharMatcher} instance. Or, instead of using a separator at all, a * splitter can extract adjacent substrings of a given {@linkplain #fixedLength fixed length}. * * <p>For example, this expression: * * <pre>{@code * Splitter.on(',').split("foo,bar,qux") * }</pre> * * ... produces an {@code Iterable} containing {@code "foo"}, {@code "bar"} and {@code "qux"}, in * that order. * * <p>By default, {@code Splitter}'s behavior is simplistic and unassuming. The following * expression: * * <pre>{@code * Splitter.on(',').split(" foo,,, bar ,") * }</pre> * * ... yields the substrings {@code [" foo", "", "", " bar ", ""]}. If this is not the desired * behavior, use configuration methods to obtain a <i>new</i> splitter instance with modified * behavior: * * <pre>{@code * private static final Splitter MY_SPLITTER = Splitter.on(',') * .trimResults() * .omitEmptyStrings(); * }</pre> * * <p>Now {@code MY_SPLITTER.split("foo,,, bar ,")} returns just {@code ["foo", "bar"]}. Note that * the order in which these configuration methods are called is never significant. * * <p><b>Warning:</b> Splitter instances are immutable. Invoking a configuration method has no * effect on the receiving instance; you must store and use the new splitter instance it returns * instead. * * <pre>{@code * // Do NOT do this * Splitter splitter = Splitter.on('/'); * splitter.trimResults(); // does nothing! * return splitter.split("wrong / wrong / wrong"); * }</pre> * * <p>For separator-based splitters that do not use {@code omitEmptyStrings}, an input string * containing {@code n} occurrences of the separator naturally yields an iterable of size {@code n + * 1}. So if the separator does not occur anywhere in the input, a single substring is returned * containing the entire input. Consequently, all splitters split the empty string to {@code [""]} * (note: even fixed-length splitters). * * <p>Splitter instances are thread-safe immutable, and are therefore safe to store as {@code static * final} constants. * * <p>The {@link Joiner} class provides the inverse operation to splitting, but note that a * round-trip between the two should be assumed to be lossy. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/StringsExplained#splitter">{@code Splitter}</a>. * * @author Julien Silland * @author Jesse Wilson * @author Kevin Bourrillion * @author Louis Wasserman * @since 1.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Splitter { private final CharMatcher trimmer; private final boolean omitEmptyStrings; private final Strategy strategy; private final int limit; private Splitter(Strategy strategy) { this(strategy, false, CharMatcher.none(), Integer.MAX_VALUE); } private Splitter(Strategy strategy, boolean omitEmptyStrings, CharMatcher trimmer, int limit) { this.strategy = strategy; this.omitEmptyStrings = omitEmptyStrings; this.trimmer = trimmer; this.limit = limit; } /** * Returns a splitter that uses the given single-character separator. For example, {@code * Splitter.on(',').split("foo,,bar")} returns an iterable containing {@code ["foo", "", "bar"]}. * * @param separator the character to recognize as a separator * @return a splitter, with default settings, that recognizes that separator */ public static Splitter on(char separator) { return on(CharMatcher.is(separator)); } /** * Returns a splitter that considers any single character matched by the given {@code CharMatcher} * to be a separator. For example, {@code * Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux")} returns an iterable containing * {@code ["foo", "", "bar", "quux"]}. * * @param separatorMatcher a {@link CharMatcher} that determines whether a character is a * separator * @return a splitter, with default settings, that uses this matcher */ public static Splitter on(final CharMatcher separatorMatcher) { checkNotNull(separatorMatcher); return new Splitter( new Strategy() { @Override public SplittingIterator iterator(Splitter splitter, final CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override int separatorStart(int start) { return separatorMatcher.indexIn(toSplit, start); } @Override int separatorEnd(int separatorPosition) { return separatorPosition + 1; } }; } }); } /** * Returns a splitter that uses the given fixed string as a separator. For example, {@code * Splitter.on(", ").split("foo, bar,baz")} returns an iterable containing {@code ["foo", * "bar,baz"]}. * * @param separator the literal, nonempty string to recognize as a separator * @return a splitter, with default settings, that recognizes that separator */ public static Splitter on(final String separator) { checkArgument(separator.length() != 0, "The separator may not be the empty string."); if (separator.length() == 1) { return Splitter.on(separator.charAt(0)); } return new Splitter( new Strategy() { @Override public SplittingIterator iterator(Splitter splitter, CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { int separatorLength = separator.length(); positions: for (int p = start, last = toSplit.length() - separatorLength; p <= last; p++) { for (int i = 0; i < separatorLength; i++) { if (toSplit.charAt(i + p) != separator.charAt(i)) { continue positions; } } return p; } return -1; } @Override public int separatorEnd(int separatorPosition) { return separatorPosition + separator.length(); } }; } }); } /** * Returns a splitter that considers any subsequence matching {@code pattern} to be a separator. * For example, {@code Splitter.on(Pattern.compile("\r?\n")).split(entireFile)} splits a string * into lines whether it uses DOS-style or UNIX-style line terminators. * * @param separatorPattern the pattern that determines whether a subsequence is a separator. This * pattern may not match the empty string. * @return a splitter, with default settings, that uses this pattern * @throws IllegalArgumentException if {@code separatorPattern} matches the empty string */ @GwtIncompatible // java.util.regex public static Splitter on(Pattern separatorPattern) { return onPatternInternal(new JdkPattern(separatorPattern)); } /** Internal utility; see {@link #on(Pattern)} instead. */ static Splitter onPatternInternal(final CommonPattern separatorPattern) { checkArgument( !separatorPattern.matcher("").matches(), "The pattern may not match the empty string: %s", separatorPattern); return new Splitter( new Strategy() { @Override public SplittingIterator iterator(final Splitter splitter, CharSequence toSplit) { final CommonMatcher matcher = separatorPattern.matcher(toSplit); return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { return matcher.find(start) ? matcher.start() : -1; } @Override public int separatorEnd(int separatorPosition) { return matcher.end(); } }; } }); } /** * Returns a splitter that considers any subsequence matching a given pattern (regular expression) * to be a separator. For example, {@code Splitter.onPattern("\r?\n").split(entireFile)} splits a * string into lines whether it uses DOS-style or UNIX-style line terminators. This is equivalent * to {@code Splitter.on(Pattern.compile(pattern))}. * * @param separatorPattern the pattern that determines whether a subsequence is a separator. This * pattern may not match the empty string. * @return a splitter, with default settings, that uses this pattern * @throws IllegalArgumentException if {@code separatorPattern} matches the empty string or is a * malformed expression */ @GwtIncompatible // java.util.regex public static Splitter onPattern(String separatorPattern) { return onPatternInternal(Platform.compilePattern(separatorPattern)); } /** * Returns a splitter that divides strings into pieces of the given length. For example, {@code * Splitter.fixedLength(2).split("abcde")} returns an iterable containing {@code ["ab", "cd", * "e"]}. The last piece can be smaller than {@code length} but will never be empty. * * <p><b>Note:</b> if {@link #fixedLength} is used in conjunction with {@link #limit}, the final * split piece <i>may be longer than the specified fixed length</i>. This is because the splitter * will <i>stop splitting when the limit is reached</i>, and just return the final piece as-is. * * <p><b>Exception:</b> for consistency with separator-based splitters, {@code split("")} does not * yield an empty iterable, but an iterable containing {@code ""}. This is the only case in which * {@code Iterables.size(split(input))} does not equal {@code IntMath.divide(input.length(), * length, CEILING)}. To avoid this behavior, use {@code omitEmptyStrings}. * * @param length the desired length of pieces after splitting, a positive integer * @return a splitter, with default settings, that can split into fixed sized pieces * @throws IllegalArgumentException if {@code length} is zero or negative */ public static Splitter fixedLength(final int length) { checkArgument(length > 0, "The length may not be less than 1"); return new Splitter( new Strategy() { @Override public SplittingIterator iterator(final Splitter splitter, CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { int nextChunkStart = start + length; return (nextChunkStart < toSplit.length() ? nextChunkStart : -1); } @Override public int separatorEnd(int separatorPosition) { return separatorPosition; } }; } }); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but automatically omits * empty strings from the results. For example, {@code * Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,")} returns an iterable containing only * {@code ["a", "b", "c"]}. * * <p>If either {@code trimResults} option is also specified when creating a splitter, that * splitter always trims results first before checking for emptiness. So, for example, {@code * Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ")} returns an empty iterable. * * <p>Note that it is ordinarily not possible for {@link #split(CharSequence)} to return an empty * iterable, but when using this option, it can (if the input sequence consists of nothing but * separators). * * @return a splitter with the desired configuration */ public Splitter omitEmptyStrings() { return new Splitter(strategy, true, trimmer, limit); } /** * Returns a splitter that behaves equivalently to {@code this} splitter but stops splitting after * it reaches the limit. The limit defines the maximum number of items returned by the iterator, * or the maximum size of the list returned by {@link #splitToList}. * * <p>For example, {@code Splitter.on(',').limit(3).split("a,b,c,d")} returns an iterable * containing {@code ["a", "b", "c,d"]}. When omitting empty strings, the omitted strings do not * count. Hence, {@code Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d")} returns * an iterable containing {@code ["a", "b", "c,d"]}. When trim is requested, all entries are * trimmed, including the last. Hence {@code Splitter.on(',').limit(3).trimResults().split(" a , b * , c , d ")} results in {@code ["a", "b", "c , d"]}. * * @param maxItems the maximum number of items returned * @return a splitter with the desired configuration * @since 9.0 */ public Splitter limit(int maxItems) { checkArgument(maxItems > 0, "must be greater than zero: %s", maxItems); return new Splitter(strategy, omitEmptyStrings, trimmer, maxItems); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but automatically * removes leading and trailing {@linkplain CharMatcher#whitespace whitespace} from each returned * substring; equivalent to {@code trimResults(CharMatcher.whitespace())}. For example, {@code * Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable containing {@code ["a", * "b", "c"]}. * * @return a splitter with the desired configuration */ public Splitter trimResults() { return trimResults(CharMatcher.whitespace()); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but removes all leading * or trailing characters matching the given {@code CharMatcher} from each returned substring. For * example, {@code Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")} * returns an iterable containing {@code ["a ", "b_ ", "c"]}. * * @param trimmer a {@link CharMatcher} that determines whether a character should be removed from * the beginning/end of a subsequence * @return a splitter with the desired configuration */ // TODO(kevinb): throw if a trimmer was already specified! public Splitter trimResults(CharMatcher trimmer) { checkNotNull(trimmer); return new Splitter(strategy, omitEmptyStrings, trimmer, limit); } /** * Splits {@code sequence} into string components and makes them available through an {@link * Iterator}, which may be lazily evaluated. If you want an eagerly computed {@link List}, use * {@link #splitToList(CharSequence)}. Java 8+ users may prefer {@link #splitToStream} instead. * * @param sequence the sequence of characters to split * @return an iteration over the segments split from the parameter */ public Iterable<String> split(final CharSequence sequence) { checkNotNull(sequence); return new Iterable<String>() { @Override public Iterator<String> iterator() { return splittingIterator(sequence); } @Override public String toString() { return Joiner.on(", ") .appendTo(new StringBuilder().append('['), this) .append(']') .toString(); } }; } private Iterator<String> splittingIterator(CharSequence sequence) { return strategy.iterator(this, sequence); } /** * Splits {@code sequence} into string components and returns them as an immutable list. If you * want an {@link Iterable} which may be lazily evaluated, use {@link #split(CharSequence)}. * * @param sequence the sequence of characters to split * @return an immutable list of the segments split from the parameter * @since 15.0 */ public List<String> splitToList(CharSequence sequence) { checkNotNull(sequence); Iterator<String> iterator = splittingIterator(sequence); List<String> result = new ArrayList<>(); while (iterator.hasNext()) { result.add(iterator.next()); } return Collections.unmodifiableList(result); } /** * Splits {@code sequence} into string components and makes them available through an {@link * Stream}, which may be lazily evaluated. If you want an eagerly computed {@link List}, use * {@link #splitToList(CharSequence)}. * * @param sequence the sequence of characters to split * @return a stream over the segments split from the parameter * @since 28.2 */ public Stream<String> splitToStream(CharSequence sequence) { // Can't use Streams.stream() from base return StreamSupport.stream(split(sequence).spliterator(), false); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, and splits entries * into keys and values using the specified separator. * * @since 10.0 */ public MapSplitter withKeyValueSeparator(String separator) { return withKeyValueSeparator(on(separator)); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, and splits entries * into keys and values using the specified separator. * * @since 14.0 */ public MapSplitter withKeyValueSeparator(char separator) { return withKeyValueSeparator(on(separator)); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, and splits entries * into keys and values using the specified key-value splitter. * * <p>Note: Any configuration option configured on this splitter, such as {@link #trimResults}, * does not change the behavior of the {@code keyValueSplitter}. * * <p>Example: * * <pre>{@code * String toSplit = " x -> y, z-> a "; * Splitter outerSplitter = Splitter.on(',').trimResults(); * MapSplitter mapSplitter = outerSplitter.withKeyValueSeparator(Splitter.on("->")); * Map<String, String> result = mapSplitter.split(toSplit); * assertThat(result).isEqualTo(ImmutableMap.of("x ", " y", "z", " a")); * }</pre> * * @since 10.0 */ public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) { return new MapSplitter(this, keyValueSplitter); } /** * An object that splits strings into maps as {@code Splitter} splits iterables and lists. Like * {@code Splitter}, it is thread-safe and immutable. The common way to build instances is by * providing an additional {@linkplain Splitter#withKeyValueSeparator key-value separator} to * {@link Splitter}. * * @since 10.0 */ public static final class MapSplitter { private static final String INVALID_ENTRY_MESSAGE = "Chunk [%s] is not a valid entry"; private final Splitter outerSplitter; private final Splitter entrySplitter; private MapSplitter(Splitter outerSplitter, Splitter entrySplitter) { this.outerSplitter = outerSplitter; // only "this" is passed this.entrySplitter = checkNotNull(entrySplitter); } /** * Splits {@code sequence} into substrings, splits each substring into an entry, and returns an * unmodifiable map with each of the entries. For example, {@code * Splitter.on(';').trimResults().withKeyValueSeparator("=>").split("a=>b ; c=>b")} will return * a mapping from {@code "a"} to {@code "b"} and {@code "c"} to {@code "b"}. * * <p>The returned map preserves the order of the entries from {@code sequence}. * * @throws IllegalArgumentException if the specified sequence does not split into valid map * entries, or if there are duplicate keys */ public Map<String, String> split(CharSequence sequence) { Map<String, String> map = new LinkedHashMap<>(); for (String entry : outerSplitter.split(sequence)) { Iterator<String> entryFields = entrySplitter.splittingIterator(entry); checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); String key = entryFields.next(); checkArgument(!map.containsKey(key), "Duplicate key [%s] found.", key); checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); String value = entryFields.next(); map.put(key, value); checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); } return Collections.unmodifiableMap(map); } } private interface Strategy { Iterator<String> iterator(Splitter splitter, CharSequence toSplit); } private abstract static class SplittingIterator extends AbstractIterator<String> { final CharSequence toSplit; final CharMatcher trimmer; final boolean omitEmptyStrings; /** * Returns the first index in {@code toSplit} at or after {@code start} that contains the * separator. */ abstract int separatorStart(int start); /** * Returns the first index in {@code toSplit} after {@code separatorPosition} that does not * contain a separator. This method is only invoked after a call to {@code separatorStart}. */ abstract int separatorEnd(int separatorPosition); int offset = 0; int limit; protected SplittingIterator(Splitter splitter, CharSequence toSplit) { this.trimmer = splitter.trimmer; this.omitEmptyStrings = splitter.omitEmptyStrings; this.limit = splitter.limit; this.toSplit = toSplit; } @CheckForNull @Override protected String computeNext() { /* * The returned string will be from the end of the last match to the beginning of the next * one. nextStart is the start position of the returned substring, while offset is the place * to start looking for a separator. */ int nextStart = offset; while (offset != -1) { int start = nextStart; int end; int separatorPosition = separatorStart(offset); if (separatorPosition == -1) { end = toSplit.length(); offset = -1; } else { end = separatorPosition; offset = separatorEnd(separatorPosition); } if (offset == nextStart) { /* * This occurs when some pattern has an empty match, even if it doesn't match the empty * string -- for example, if it requires lookahead or the like. The offset must be * increased to look for separators beyond this point, without changing the start position * of the next returned substring -- so nextStart stays the same. */ offset++; if (offset > toSplit.length()) { offset = -1; } continue; } while (start < end && trimmer.matches(toSplit.charAt(start))) { start++; } while (end > start && trimmer.matches(toSplit.charAt(end - 1))) { end--; } if (omitEmptyStrings && start == end) { // Don't include the (unused) separator in next split string. nextStart = offset; continue; } if (limit == 1) { // The limit has been reached, return the rest of the string as the // final item. This is tested after empty string removal so that // empty strings do not count towards the limit. end = toSplit.length(); offset = -1; // Since we may have changed the end, we need to trim it again. while (end > start && trimmer.matches(toSplit.charAt(end - 1))) { end--; } } else { limit--; } return toSplit.subSequence(start, end).toString(); } return endOfData(); } } }
google/guava
guava/src/com/google/common/base/Splitter.java
343
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.dirtyflag; import java.util.ArrayList; import java.util.List; /** * A middle-layer app that calls/passes along data from the back-end. * * @author swaisuan */ public class World { private List<String> countries; private final DataFetcher df; public World() { this.countries = new ArrayList<>(); this.df = new DataFetcher(); } /** * Calls {@link DataFetcher} to fetch data from back-end. * * @return List of strings */ public List<String> fetch() { var data = df.fetch(); countries = data.isEmpty() ? countries : data; return countries; } }
smedals/java-design-patterns
dirty-flag/src/main/java/com/iluwatar/dirtyflag/World.java
344
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.node; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.apache.lucene.util.SetOnce; import org.elasticsearch.ElasticsearchTimeoutException; import org.elasticsearch.action.search.TransportSearchAction; import org.elasticsearch.bootstrap.BootstrapCheck; import org.elasticsearch.bootstrap.BootstrapContext; import org.elasticsearch.client.internal.Client; import org.elasticsearch.client.internal.node.NodeClient; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.cluster.ClusterStateObserver; import org.elasticsearch.cluster.NodeConnectionsService; import org.elasticsearch.cluster.action.index.MappingUpdatedAction; import org.elasticsearch.cluster.coordination.CoordinationDiagnosticsService; import org.elasticsearch.cluster.coordination.Coordinator; import org.elasticsearch.cluster.metadata.IndexMetadataVerifier; import org.elasticsearch.cluster.metadata.Metadata; import org.elasticsearch.cluster.node.DiscoveryNode; import org.elasticsearch.cluster.service.ClusterService; import org.elasticsearch.cluster.version.CompatibilityVersions; import org.elasticsearch.common.StopWatch; import org.elasticsearch.common.component.Lifecycle; import org.elasticsearch.common.component.LifecycleComponent; import org.elasticsearch.common.inject.Injector; import org.elasticsearch.common.io.stream.NamedWriteableRegistry; import org.elasticsearch.common.logging.NodeAndClusterIdStateListener; import org.elasticsearch.common.network.NetworkAddress; import org.elasticsearch.common.settings.Setting; import org.elasticsearch.common.settings.Setting.Property; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.transport.BoundTransportAddress; import org.elasticsearch.common.transport.TransportAddress; import org.elasticsearch.common.util.concurrent.FutureUtils; import org.elasticsearch.core.Assertions; import org.elasticsearch.core.IOUtils; import org.elasticsearch.core.PathUtils; import org.elasticsearch.core.SuppressForbidden; import org.elasticsearch.core.TimeValue; import org.elasticsearch.env.BuildVersion; import org.elasticsearch.env.Environment; import org.elasticsearch.env.NodeEnvironment; import org.elasticsearch.env.NodeMetadata; import org.elasticsearch.gateway.GatewayMetaState; import org.elasticsearch.gateway.GatewayService; import org.elasticsearch.gateway.MetaStateService; import org.elasticsearch.gateway.PersistedClusterStateService; import org.elasticsearch.health.HealthPeriodicLogger; import org.elasticsearch.http.HttpServerTransport; import org.elasticsearch.indices.IndicesService; import org.elasticsearch.indices.cluster.IndicesClusterStateService; import org.elasticsearch.indices.recovery.PeerRecoverySourceService; import org.elasticsearch.indices.store.IndicesStore; import org.elasticsearch.monitor.fs.FsHealthService; import org.elasticsearch.monitor.jvm.JvmInfo; import org.elasticsearch.monitor.metrics.NodeMetrics; import org.elasticsearch.node.internal.TerminationHandler; import org.elasticsearch.plugins.ClusterCoordinationPlugin; import org.elasticsearch.plugins.ClusterPlugin; import org.elasticsearch.plugins.MetadataUpgrader; import org.elasticsearch.plugins.Plugin; import org.elasticsearch.plugins.PluginsService; import org.elasticsearch.readiness.ReadinessService; import org.elasticsearch.repositories.RepositoriesService; import org.elasticsearch.reservedstate.service.FileSettingsService; import org.elasticsearch.script.ScriptService; import org.elasticsearch.search.SearchService; import org.elasticsearch.snapshots.SnapshotShardsService; import org.elasticsearch.snapshots.SnapshotsService; import org.elasticsearch.tasks.TaskCancellationService; import org.elasticsearch.tasks.TaskManager; import org.elasticsearch.tasks.TaskResultsService; import org.elasticsearch.threadpool.ThreadPool; import org.elasticsearch.transport.RemoteClusterPortSettings; import org.elasticsearch.transport.TransportService; import org.elasticsearch.watcher.ResourceWatcherService; import org.elasticsearch.xcontent.NamedXContentRegistry; import java.io.BufferedWriter; import java.io.Closeable; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.nio.charset.Charset; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.StandardCopyOption; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.function.BiConsumer; import java.util.function.Function; import javax.net.ssl.SNIHostName; import static org.elasticsearch.core.Strings.format; /** * A node represent a node within a cluster ({@code cluster.name}). The {@link #client()} can be used * in order to use a {@link Client} to perform actions/operations against the cluster. */ public class Node implements Closeable { public static final Setting<Boolean> WRITE_PORTS_FILE_SETTING = Setting.boolSetting("node.portsfile", false, Property.NodeScope); public static final Setting<String> NODE_NAME_SETTING = Setting.simpleString("node.name", Property.NodeScope); public static final Setting<String> NODE_EXTERNAL_ID_SETTING = Setting.simpleString( "node.external_id", NODE_NAME_SETTING, Property.NodeScope ); public static final Setting.AffixSetting<String> NODE_ATTRIBUTES = Setting.prefixKeySetting( "node.attr.", (key) -> new Setting<>(key, "", (value) -> { if (value.length() > 0 && (Character.isWhitespace(value.charAt(0)) || Character.isWhitespace(value.charAt(value.length() - 1)))) { throw new IllegalArgumentException(key + " cannot have leading or trailing whitespace [" + value + "]"); } if (value.length() > 0 && "node.attr.server_name".equals(key)) { try { new SNIHostName(value); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("invalid node.attr.server_name [" + value + "]", e); } } return value; }, Property.NodeScope) ); public static final Setting<String> BREAKER_TYPE_KEY = new Setting<>("indices.breaker.type", "hierarchy", (s) -> { return switch (s) { case "hierarchy", "none" -> s; default -> throw new IllegalArgumentException("indices.breaker.type must be one of [hierarchy, none] but was: " + s); }; }, Setting.Property.NodeScope); public static final Setting<TimeValue> INITIAL_STATE_TIMEOUT_SETTING = Setting.positiveTimeSetting( "discovery.initial_state_timeout", TimeValue.timeValueSeconds(30), Property.NodeScope ); public static final Setting<TimeValue> MAXIMUM_SHUTDOWN_TIMEOUT_SETTING = Setting.positiveTimeSetting( "node.maximum_shutdown_grace_period", TimeValue.ZERO, Setting.Property.NodeScope ); private final Lifecycle lifecycle = new Lifecycle(); /** * This logger instance is an instance field as opposed to a static field. This ensures that the field is not * initialized until an instance of Node is constructed, which is sure to happen after the logging infrastructure * has been initialized to include the hostname. If this field were static, then it would be initialized when the * class initializer runs. Alas, this happens too early, before logging is initialized as this class is referred to * in InternalSettingsPreparer#finalizeSettings, which runs when creating the Environment, before logging is * initialized. */ private final Logger logger = LogManager.getLogger(Node.class); private final Injector injector; private final Environment environment; private final NodeEnvironment nodeEnvironment; private final PluginsService pluginsService; private final NodeClient client; private final Collection<LifecycleComponent> pluginLifecycleComponents; private final LocalNodeFactory localNodeFactory; private final NodeService nodeService; private final TerminationHandler terminationHandler; // for testing final NamedWriteableRegistry namedWriteableRegistry; final NamedXContentRegistry namedXContentRegistry; /** * Constructs a node * * @param environment the initial environment for this node, which will be added to by plugins */ public Node(Environment environment) { this(NodeConstruction.prepareConstruction(environment, new NodeServiceProvider(), true)); } /** * Constructs a node using information from {@code construction} */ Node(NodeConstruction construction) { injector = construction.injector(); environment = construction.environment(); nodeEnvironment = construction.nodeEnvironment(); pluginsService = construction.pluginsService(); client = construction.client(); pluginLifecycleComponents = construction.pluginLifecycleComponents(); localNodeFactory = construction.localNodeFactory(); nodeService = construction.nodeService(); terminationHandler = construction.terminationHandler(); namedWriteableRegistry = construction.namedWriteableRegistry(); namedXContentRegistry = construction.namedXContentRegistry(); } /** * If the JVM was started with the Elastic APM agent and a config file argument was specified, then * delete the config file. The agent only reads it once, when supplied in this fashion, and it * may contain a secret token. * <p> * Public for testing only */ @SuppressForbidden(reason = "Cannot guarantee that the temp config path is relative to the environment") public static void deleteTemporaryApmConfig(JvmInfo jvmInfo, BiConsumer<Exception, Path> errorHandler) { for (String inputArgument : jvmInfo.getInputArguments()) { if (inputArgument.startsWith("-javaagent:")) { final String agentArg = inputArgument.substring(11); final String[] parts = agentArg.split("=", 2); String APM_AGENT_CONFIG_FILE_REGEX = String.join( "\\" + File.separator, ".*modules", "apm", "elastic-apm-agent-\\d+\\.\\d+\\.\\d+\\.jar" ); if (parts[0].matches(APM_AGENT_CONFIG_FILE_REGEX)) { if (parts.length == 2 && parts[1].startsWith("c=")) { final Path apmConfig = PathUtils.get(parts[1].substring(2)); if (apmConfig.getFileName().toString().matches("^\\.elstcapm\\..*\\.tmp")) { try { Files.deleteIfExists(apmConfig); } catch (IOException e) { errorHandler.accept(e, apmConfig); } } } return; } } } } /** * The settings that are used by this node. Contains original settings as well as additional settings provided by plugins. */ public Settings settings() { return this.environment.settings(); } /** * A client that can be used to execute actions (operations) against the cluster. */ public Client client() { return client; } /** * Returns the environment of the node */ public Environment getEnvironment() { return environment; } /** * Returns the {@link NodeEnvironment} instance of this node */ public NodeEnvironment getNodeEnvironment() { return nodeEnvironment; } /** * Start the node. If the node is already started, this method is no-op. */ public Node start() throws NodeValidationException { if (lifecycle.moveToStarted() == false) { return this; } logger.info("starting ..."); pluginLifecycleComponents.forEach(LifecycleComponent::start); if (ReadinessService.enabled(environment)) { injector.getInstance(ReadinessService.class).start(); } injector.getInstance(MappingUpdatedAction.class).setClient(client); injector.getInstance(IndicesService.class).start(); injector.getInstance(IndicesClusterStateService.class).start(); injector.getInstance(SnapshotsService.class).start(); injector.getInstance(SnapshotShardsService.class).start(); injector.getInstance(RepositoriesService.class).start(); injector.getInstance(SearchService.class).start(); injector.getInstance(FsHealthService.class).start(); nodeService.getMonitorService().start(); final ClusterService clusterService = injector.getInstance(ClusterService.class); final NodeConnectionsService nodeConnectionsService = injector.getInstance(NodeConnectionsService.class); nodeConnectionsService.start(); clusterService.setNodeConnectionsService(nodeConnectionsService); injector.getInstance(GatewayService.class).start(); final Coordinator coordinator = injector.getInstance(Coordinator.class); clusterService.getMasterService().setClusterStatePublisher(coordinator); // Start the transport service now so the publish address will be added to the local disco node in ClusterService TransportService transportService = injector.getInstance(TransportService.class); transportService.getTaskManager().setTaskResultsService(injector.getInstance(TaskResultsService.class)); transportService.getTaskManager().setTaskCancellationService(new TaskCancellationService(transportService)); transportService.start(); assert localNodeFactory.getNode() != null; assert transportService.getLocalNode().equals(localNodeFactory.getNode()) : "transportService has a different local node than the factory provided"; injector.getInstance(PeerRecoverySourceService.class).start(); // Load (and maybe upgrade) the metadata stored on disk final GatewayMetaState gatewayMetaState = injector.getInstance(GatewayMetaState.class); gatewayMetaState.start( settings(), transportService, clusterService, injector.getInstance(MetaStateService.class), injector.getInstance(IndexMetadataVerifier.class), injector.getInstance(MetadataUpgrader.class), injector.getInstance(PersistedClusterStateService.class), pluginsService.filterPlugins(ClusterCoordinationPlugin.class).toList(), injector.getInstance(CompatibilityVersions.class) ); // TODO: Do not expect that the legacy metadata file is always present https://github.com/elastic/elasticsearch/issues/95211 if (Assertions.ENABLED && DiscoveryNode.isStateless(settings()) == false) { try { assert injector.getInstance(MetaStateService.class).loadFullState().v1().isEmpty(); final NodeMetadata nodeMetadata = NodeMetadata.FORMAT.loadLatestState( logger, NamedXContentRegistry.EMPTY, nodeEnvironment.nodeDataPaths() ); assert nodeMetadata != null; assert nodeMetadata.nodeVersion().equals(BuildVersion.current()); assert nodeMetadata.nodeId().equals(localNodeFactory.getNode().getId()); } catch (IOException e) { assert false : e; } } // we load the global state here (the persistent part of the cluster state stored on disk) to // pass it to the bootstrap checks to allow plugins to enforce certain preconditions based on the recovered state. final Metadata onDiskMetadata = gatewayMetaState.getPersistedState().getLastAcceptedState().metadata(); assert onDiskMetadata != null : "metadata is null but shouldn't"; // this is never null validateNodeBeforeAcceptingRequests( new BootstrapContext(environment, onDiskMetadata), transportService.boundAddress(), pluginsService.flatMap(Plugin::getBootstrapChecks).toList() ); final FileSettingsService fileSettingsService = injector.getInstance(FileSettingsService.class); fileSettingsService.start(); clusterService.addStateApplier(transportService.getTaskManager()); // start after transport service so the local disco is known coordinator.start(); // start before cluster service so that it can set initial state on ClusterApplierService clusterService.start(); assert clusterService.localNode().equals(localNodeFactory.getNode()) : "clusterService has a different local node than the factory provided"; transportService.acceptIncomingRequests(); /* * CoordinationDiagnosticsService expects to be able to send transport requests and use the cluster state, so it is important to * start it here after the clusterService and transportService have been started. */ injector.getInstance(CoordinationDiagnosticsService.class).start(); coordinator.startInitialJoin(); final TimeValue initialStateTimeout = INITIAL_STATE_TIMEOUT_SETTING.get(settings()); configureNodeAndClusterIdStateListener(clusterService); if (initialStateTimeout.millis() > 0) { final ThreadPool thread = injector.getInstance(ThreadPool.class); ClusterState clusterState = clusterService.state(); ClusterStateObserver observer = new ClusterStateObserver(clusterState, clusterService, null, logger, thread.getThreadContext()); if (clusterState.nodes().getMasterNodeId() == null) { logger.debug("waiting to join the cluster. timeout [{}]", initialStateTimeout); final CountDownLatch latch = new CountDownLatch(1); observer.waitForNextChange(new ClusterStateObserver.Listener() { @Override public void onNewClusterState(ClusterState state) { latch.countDown(); } @Override public void onClusterServiceClose() { latch.countDown(); } @Override public void onTimeout(TimeValue timeout) { logger.warn("timed out while waiting for initial discovery state - timeout: {}", initialStateTimeout); latch.countDown(); } }, state -> state.nodes().getMasterNodeId() != null, initialStateTimeout); try { latch.await(); } catch (InterruptedException e) { throw new ElasticsearchTimeoutException("Interrupted while waiting for initial discovery state"); } } } injector.getInstance(HttpServerTransport.class).start(); if (WRITE_PORTS_FILE_SETTING.get(settings())) { TransportService transport = injector.getInstance(TransportService.class); writePortsFile("transport", transport.boundAddress()); HttpServerTransport http = injector.getInstance(HttpServerTransport.class); writePortsFile("http", http.boundAddress()); if (ReadinessService.enabled(environment)) { ReadinessService readiness = injector.getInstance(ReadinessService.class); readiness.addBoundAddressListener(address -> writePortsFile("readiness", address)); } if (RemoteClusterPortSettings.REMOTE_CLUSTER_SERVER_ENABLED.get(environment.settings())) { writePortsFile("remote_cluster", transport.boundRemoteAccessAddress()); } } injector.getInstance(NodeMetrics.class).start(); injector.getInstance(HealthPeriodicLogger.class).start(); logger.info("started {}", transportService.getLocalNode()); pluginsService.filterPlugins(ClusterPlugin.class).forEach(ClusterPlugin::onNodeStarted); return this; } protected void configureNodeAndClusterIdStateListener(ClusterService clusterService) { NodeAndClusterIdStateListener.getAndSetNodeIdAndClusterId( clusterService, injector.getInstance(ThreadPool.class).getThreadContext() ); } private void stop() { if (lifecycle.moveToStopped() == false) { return; } logger.info("stopping ..."); if (ReadinessService.enabled(environment)) { stopIfStarted(ReadinessService.class); } // We stop the health periodic logger first since certain checks won't be possible anyway stopIfStarted(HealthPeriodicLogger.class); stopIfStarted(FileSettingsService.class); injector.getInstance(ResourceWatcherService.class).close(); stopIfStarted(HttpServerTransport.class); stopIfStarted(SnapshotsService.class); stopIfStarted(SnapshotShardsService.class); stopIfStarted(RepositoriesService.class); // stop any changes happening as a result of cluster state changes stopIfStarted(IndicesClusterStateService.class); // close cluster coordinator early to not react to pings anymore. // This can confuse other nodes and delay things - mostly if we're the master and we're running tests. stopIfStarted(Coordinator.class); // we close indices first, so operations won't be allowed on it stopIfStarted(ClusterService.class); stopIfStarted(NodeConnectionsService.class); stopIfStarted(FsHealthService.class); stopIfStarted(nodeService.getMonitorService()); stopIfStarted(GatewayService.class); stopIfStarted(SearchService.class); stopIfStarted(TransportService.class); stopIfStarted(NodeMetrics.class); pluginLifecycleComponents.forEach(Node::stopIfStarted); // we should stop this last since it waits for resources to get released // if we had scroll searchers etc or recovery going on we wait for to finish. stopIfStarted(IndicesService.class); logger.info("stopped"); } private <T extends LifecycleComponent> void stopIfStarted(Class<T> componentClass) { stopIfStarted(injector.getInstance(componentClass)); } private static void stopIfStarted(LifecycleComponent component) { // if we failed during startup then some of our components might not have started yet if (component.lifecycleState() == Lifecycle.State.STARTED) { component.stop(); } } // During concurrent close() calls we want to make sure that all of them return after the node has completed it's shutdown cycle. // If not, the hook that is added in Bootstrap#setup() will be useless: // close() might not be executed, in case another (for example api) call to close() has already set some lifecycles to stopped. // In this case the process will be terminated even if the first call to close() has not finished yet. @Override public synchronized void close() throws IOException { synchronized (lifecycle) { if (lifecycle.started()) { stop(); } if (lifecycle.moveToClosed() == false) { return; } } logger.info("closing ..."); List<Closeable> toClose = new ArrayList<>(); StopWatch stopWatch = new StopWatch("node_close"); toClose.add(() -> stopWatch.start("node_service")); toClose.add(nodeService); toClose.add(() -> stopWatch.stop().start("http")); toClose.add(injector.getInstance(HttpServerTransport.class)); toClose.add(() -> stopWatch.stop().start("snapshot_service")); toClose.add(injector.getInstance(SnapshotsService.class)); toClose.add(injector.getInstance(SnapshotShardsService.class)); toClose.add(injector.getInstance(RepositoriesService.class)); toClose.add(() -> stopWatch.stop().start("indices_cluster")); toClose.add(injector.getInstance(IndicesClusterStateService.class)); toClose.add(() -> stopWatch.stop().start("indices")); toClose.add(injector.getInstance(IndicesService.class)); // close filter/fielddata caches after indices toClose.add(injector.getInstance(IndicesStore.class)); toClose.add(injector.getInstance(PeerRecoverySourceService.class)); toClose.add(() -> stopWatch.stop().start("cluster")); toClose.add(injector.getInstance(ClusterService.class)); toClose.add(() -> stopWatch.stop().start("node_connections_service")); toClose.add(injector.getInstance(NodeConnectionsService.class)); toClose.add(() -> stopWatch.stop().start("cluster_coordinator")); toClose.add(injector.getInstance(Coordinator.class)); toClose.add(() -> stopWatch.stop().start("monitor")); toClose.add(nodeService.getMonitorService()); toClose.add(() -> stopWatch.stop().start("fsHealth")); toClose.add(injector.getInstance(FsHealthService.class)); toClose.add(() -> stopWatch.stop().start("gateway")); toClose.add(injector.getInstance(GatewayService.class)); toClose.add(() -> stopWatch.stop().start("search")); toClose.add(injector.getInstance(SearchService.class)); toClose.add(() -> stopWatch.stop().start("transport")); toClose.add(injector.getInstance(TransportService.class)); toClose.add(injector.getInstance(NodeMetrics.class)); if (ReadinessService.enabled(environment)) { toClose.add(injector.getInstance(ReadinessService.class)); } toClose.add(injector.getInstance(FileSettingsService.class)); toClose.add(injector.getInstance(HealthPeriodicLogger.class)); for (LifecycleComponent plugin : pluginLifecycleComponents) { toClose.add(() -> stopWatch.stop().start("plugin(" + plugin.getClass().getName() + ")")); toClose.add(plugin); } pluginsService.filterPlugins(Plugin.class).forEach(toClose::add); toClose.add(() -> stopWatch.stop().start("script")); toClose.add(injector.getInstance(ScriptService.class)); toClose.add(() -> stopWatch.stop().start("thread_pool")); toClose.add(() -> injector.getInstance(ThreadPool.class).shutdown()); // Don't call shutdownNow here, it might break ongoing operations on Lucene indices. // See https://issues.apache.org/jira/browse/LUCENE-7248. We call shutdownNow in // awaitClose if the node doesn't finish closing within the specified time. toClose.add(() -> stopWatch.stop().start("gateway_meta_state")); toClose.add(injector.getInstance(GatewayMetaState.class)); toClose.add(() -> stopWatch.stop().start("node_environment")); toClose.add(injector.getInstance(NodeEnvironment.class)); toClose.add(stopWatch::stop); if (logger.isTraceEnabled()) { toClose.add(() -> logger.trace("Close times for each service:\n{}", stopWatch.prettyPrint())); } IOUtils.close(toClose); logger.info("closed"); } /** * Invokes hooks to prepare this node to be closed. This should be called when Elasticsearch receives a request to shut down * gracefully from the underlying operating system, before system resources are closed. This method will block * until the node is ready to shut down. * * Note that this class is part of infrastructure to react to signals from the operating system - most graceful shutdown * logic should use Node Shutdown, see {@link org.elasticsearch.cluster.metadata.NodesShutdownMetadata}. */ public void prepareForClose() { HttpServerTransport httpServerTransport = injector.getInstance(HttpServerTransport.class); Map<String, Runnable> stoppers = new HashMap<>(); TimeValue maxTimeout = MAXIMUM_SHUTDOWN_TIMEOUT_SETTING.get(this.settings()); stoppers.put("http-server-transport-stop", httpServerTransport::close); stoppers.put("async-search-stop", () -> this.awaitSearchTasksComplete(maxTimeout)); if (terminationHandler != null) { stoppers.put("termination-handler-stop", terminationHandler::handleTermination); } Map<String, CompletableFuture<Void>> futures = new HashMap<>(stoppers.size()); for (var stopperEntry : stoppers.entrySet()) { var future = new CompletableFuture<Void>(); new Thread(() -> { try { stopperEntry.getValue().run(); } catch (Exception ex) { logger.warn("unexpected exception in shutdown task [" + stopperEntry.getKey() + "]", ex); } finally { future.complete(null); } }, stopperEntry.getKey()).start(); futures.put(stopperEntry.getKey(), future); } @SuppressWarnings(value = "rawtypes") // Can't make an array of parameterized types, but it complains if you leave the type out CompletableFuture<Void> allStoppers = CompletableFuture.allOf(futures.values().toArray(new CompletableFuture[stoppers.size()])); try { if (TimeValue.ZERO.equals(maxTimeout)) { FutureUtils.get(allStoppers); } else { FutureUtils.get(allStoppers, maxTimeout.millis(), TimeUnit.MILLISECONDS); } } catch (ElasticsearchTimeoutException t) { var unfinishedTasks = futures.entrySet() .stream() .filter(entry -> entry.getValue().isDone() == false) .map(Map.Entry::getKey) .toList(); logger.warn("timed out while waiting for graceful shutdown tasks: " + unfinishedTasks); } } private void awaitSearchTasksComplete(TimeValue asyncSearchTimeout) { TaskManager taskManager = injector.getInstance(TransportService.class).getTaskManager(); long millisWaited = 0; while (true) { long searchTasksRemaining = taskManager.getTasks() .values() .stream() .filter(task -> TransportSearchAction.TYPE.name().equals(task.getAction())) .count(); if (searchTasksRemaining == 0) { logger.debug("all search tasks complete"); return; } else { // Let the system work on those searches for a while. We're on a dedicated thread to manage app shutdown, so we // literally just want to wait and not take up resources on this thread for now. Poll period chosen to allow short // response times, but checking the tasks list is relatively expensive, and we don't want to waste CPU time we could // be spending on finishing those searches. final TimeValue pollPeriod = TimeValue.timeValueMillis(500); millisWaited += pollPeriod.millis(); if (TimeValue.ZERO.equals(asyncSearchTimeout) == false && millisWaited >= asyncSearchTimeout.millis()) { logger.warn( format( "timed out after waiting [%s] for [%d] search tasks to finish", asyncSearchTimeout.toString(), searchTasksRemaining ) ); return; } logger.debug(format("waiting for [%s] search tasks to finish, next poll in [%s]", searchTasksRemaining, pollPeriod)); try { Thread.sleep(pollPeriod.millis()); } catch (InterruptedException ex) { logger.warn( format( "interrupted while waiting [%s] for [%d] search tasks to finish", asyncSearchTimeout.toString(), searchTasksRemaining ) ); return; } } } } /** * Wait for this node to be effectively closed. */ // synchronized to prevent running concurrently with close() public synchronized boolean awaitClose(long timeout, TimeUnit timeUnit) throws InterruptedException { if (lifecycle.closed() == false) { // We don't want to shutdown the threadpool or interrupt threads on a node that is not // closed yet. throw new IllegalStateException("Call close() first"); } ThreadPool threadPool = injector.getInstance(ThreadPool.class); final boolean terminated = ThreadPool.terminate(threadPool, timeout, timeUnit); if (terminated) { // All threads terminated successfully. Because search, recovery and all other operations // that run on shards run in the threadpool, indices should be effectively closed by now. if (nodeService.awaitClose(0, TimeUnit.MILLISECONDS) == false) { throw new IllegalStateException( "Some shards are still open after the threadpool terminated. " + "Something is leaking index readers or store references." ); } } return terminated; } /** * Returns {@code true} if the node is closed. */ public boolean isClosed() { return lifecycle.closed(); } public Injector injector() { return this.injector; } /** * Hook for validating the node after network * services are started but before the cluster service is started * and before the network service starts accepting incoming network * requests. * * @param context the bootstrap context for this node * @param boundTransportAddress the network addresses the node is * bound and publishing to */ @SuppressWarnings("unused") protected void validateNodeBeforeAcceptingRequests( final BootstrapContext context, final BoundTransportAddress boundTransportAddress, List<BootstrapCheck> bootstrapChecks ) throws NodeValidationException {} /** * Writes a file to the logs dir containing the ports for the given transport type */ private void writePortsFile(String type, BoundTransportAddress boundAddress) { Path tmpPortsFile = environment.logsFile().resolve(type + ".ports.tmp"); try (BufferedWriter writer = Files.newBufferedWriter(tmpPortsFile, Charset.forName("UTF-8"))) { for (TransportAddress address : boundAddress.boundAddresses()) { InetAddress inetAddress = InetAddress.getByName(address.getAddress()); writer.write(NetworkAddress.format(new InetSocketAddress(inetAddress, address.getPort())) + "\n"); } } catch (IOException e) { throw new RuntimeException("Failed to write ports file", e); } Path portsFile = environment.logsFile().resolve(type + ".ports"); try { Files.move(tmpPortsFile, portsFile, StandardCopyOption.ATOMIC_MOVE); } catch (IOException e) { throw new RuntimeException("Failed to rename ports file", e); } } /** * The {@link PluginsService} used to build this node's components. */ protected PluginsService getPluginsService() { return pluginsService; } /** * Plugins can provide additional settings for the node, but two plugins * cannot provide the same setting. * @param pluginMap A map of plugin names to plugin instances * @param originalSettings The node's original settings, which silently override any setting provided by the plugins. * @return A {@link Settings} with the merged node and plugin settings * @throws IllegalArgumentException if two plugins provide the same additional setting key */ static Settings mergePluginSettings(Map<String, Plugin> pluginMap, Settings originalSettings) { Map<String, String> foundSettings = new HashMap<>(); final Settings.Builder builder = Settings.builder(); for (Map.Entry<String, Plugin> entry : pluginMap.entrySet()) { Settings settings = entry.getValue().additionalSettings(); for (String setting : settings.keySet()) { String oldPlugin = foundSettings.put(setting, entry.getKey()); if (oldPlugin != null) { throw new IllegalArgumentException( "Cannot have additional setting [" + setting + "] " + "in plugin [" + entry.getKey() + "], already added in plugin [" + oldPlugin + "]" ); } } builder.put(settings); } return builder.put(originalSettings).build(); } static class LocalNodeFactory implements Function<BoundTransportAddress, DiscoveryNode> { private final SetOnce<DiscoveryNode> localNode = new SetOnce<>(); private final String persistentNodeId; private final Settings settings; LocalNodeFactory(Settings settings, String persistentNodeId) { this.persistentNodeId = persistentNodeId; this.settings = settings; } @Override public DiscoveryNode apply(BoundTransportAddress boundTransportAddress) { localNode.set(DiscoveryNode.createLocal(settings, boundTransportAddress.publishAddress(), persistentNodeId)); return localNode.get(); } DiscoveryNode getNode() { assert localNode.get() != null; return localNode.get(); } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/node/Node.java
345
/* * 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 static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndex; import static com.google.common.base.Preconditions.checkPositionIndexes; import static java.lang.Math.max; import static java.lang.Math.min; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.math.IntMath; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.DataInput; import java.io.DataInputStream; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.EOFException; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.util.ArrayDeque; import java.util.Arrays; import java.util.Queue; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Provides utility methods for working with byte arrays and I/O streams. * * @author Chris Nokleberg * @author Colin Decker * @since 1.0 */ @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public final class ByteStreams { private static final int BUFFER_SIZE = 8192; /** Creates a new byte array for buffering reads or writes. */ static byte[] createBuffer() { return new byte[BUFFER_SIZE]; } /** * There are three methods to implement {@link FileChannel#transferTo(long, long, * WritableByteChannel)}: * * <ol> * <li>Use sendfile(2) or equivalent. Requires that both the input channel and the output * channel have their own file descriptors. Generally this only happens when both channels * are files or sockets. This performs zero copies - the bytes never enter userspace. * <li>Use mmap(2) or equivalent. Requires that either the input channel or the output channel * have file descriptors. Bytes are copied from the file into a kernel buffer, then directly * into the other buffer (userspace). Note that if the file is very large, a naive * implementation will effectively put the whole file in memory. On many systems with paging * and virtual memory, this is not a problem - because it is mapped read-only, the kernel * can always page it to disk "for free". However, on systems where killing processes * happens all the time in normal conditions (i.e., android) the OS must make a tradeoff * between paging memory and killing other processes - so allocating a gigantic buffer and * then sequentially accessing it could result in other processes dying. This is solvable * via madvise(2), but that obviously doesn't exist in java. * <li>Ordinary copy. Kernel copies bytes into a kernel buffer, from a kernel buffer into a * userspace buffer (byte[] or ByteBuffer), then copies them from that buffer into the * destination channel. * </ol> * * This value is intended to be large enough to make the overhead of system calls negligible, * without being so large that it causes problems for systems with atypical memory management if * approaches 2 or 3 are used. */ private static final int ZERO_COPY_CHUNK_SIZE = 512 * 1024; private ByteStreams() {} /** * Copies all bytes from the input stream to the output stream. Does not close or flush either * stream. * * <p><b>Java 9 users and later:</b> this method should be treated as deprecated; use the * equivalent {@link InputStream#transferTo} method instead. * * @param from the input stream to read from * @param to the output stream to write to * @return the number of bytes copied * @throws IOException if an I/O error occurs */ @CanIgnoreReturnValue public static long copy(InputStream from, OutputStream to) throws IOException { checkNotNull(from); checkNotNull(to); byte[] buf = createBuffer(); long total = 0; while (true) { int r = from.read(buf); if (r == -1) { break; } to.write(buf, 0, r); total += r; } return total; } /** * Copies all bytes from the readable channel to the writable channel. Does not close or flush * either channel. * * @param from the readable channel to read from * @param to the writable channel to write to * @return the number of bytes copied * @throws IOException if an I/O error occurs */ @CanIgnoreReturnValue public static long copy(ReadableByteChannel from, WritableByteChannel to) throws IOException { checkNotNull(from); checkNotNull(to); if (from instanceof FileChannel) { FileChannel sourceChannel = (FileChannel) from; long oldPosition = sourceChannel.position(); long position = oldPosition; long copied; do { copied = sourceChannel.transferTo(position, ZERO_COPY_CHUNK_SIZE, to); position += copied; sourceChannel.position(position); } while (copied > 0 || position < sourceChannel.size()); return position - oldPosition; } ByteBuffer buf = ByteBuffer.wrap(createBuffer()); long total = 0; while (from.read(buf) != -1) { Java8Compatibility.flip(buf); while (buf.hasRemaining()) { total += to.write(buf); } Java8Compatibility.clear(buf); } return total; } /** Max array length on JVM. */ private static final int MAX_ARRAY_LEN = Integer.MAX_VALUE - 8; /** Large enough to never need to expand, given the geometric progression of buffer sizes. */ private static final int TO_BYTE_ARRAY_DEQUE_SIZE = 20; /** * Returns a byte array containing the bytes from the buffers already in {@code bufs} (which have * a total combined length of {@code totalLen} bytes) followed by all bytes remaining in the given * input stream. */ private static byte[] toByteArrayInternal(InputStream in, Queue<byte[]> bufs, int totalLen) throws IOException { // Roughly size to match what has been read already. Some file systems, such as procfs, return 0 // as their length. These files are very small, so it's wasteful to allocate an 8KB buffer. int initialBufferSize = min(BUFFER_SIZE, max(128, Integer.highestOneBit(totalLen) * 2)); // Starting with an 8k buffer, double the size of each successive buffer. Smaller buffers // quadruple in size until they reach 8k, to minimize the number of small reads for longer // streams. Buffers are retained in a deque so that there's no copying between buffers while // reading and so all of the bytes in each new allocated buffer are available for reading from // the stream. for (int bufSize = initialBufferSize; totalLen < MAX_ARRAY_LEN; bufSize = IntMath.saturatedMultiply(bufSize, bufSize < 4096 ? 4 : 2)) { byte[] buf = new byte[min(bufSize, MAX_ARRAY_LEN - totalLen)]; bufs.add(buf); int off = 0; while (off < buf.length) { // always OK to fill buf; its size plus the rest of bufs is never more than MAX_ARRAY_LEN int r = in.read(buf, off, buf.length - off); if (r == -1) { return combineBuffers(bufs, totalLen); } off += r; totalLen += r; } } // read MAX_ARRAY_LEN bytes without seeing end of stream if (in.read() == -1) { // oh, there's the end of the stream return combineBuffers(bufs, MAX_ARRAY_LEN); } else { throw new OutOfMemoryError("input is too large to fit in a byte array"); } } private static byte[] combineBuffers(Queue<byte[]> bufs, int totalLen) { if (bufs.isEmpty()) { return new byte[0]; } byte[] result = bufs.remove(); if (result.length == totalLen) { return result; } int remaining = totalLen - result.length; result = Arrays.copyOf(result, totalLen); while (remaining > 0) { byte[] buf = bufs.remove(); int bytesToCopy = min(remaining, buf.length); int resultOffset = totalLen - remaining; System.arraycopy(buf, 0, result, resultOffset, bytesToCopy); remaining -= bytesToCopy; } return result; } /** * Reads all bytes from an input stream into a byte array. Does not close the stream. * * <p><b>Java 9+ users:</b> use {@code in#readAllBytes()} instead. * * @param in the input stream to read from * @return a byte array containing all the bytes from the stream * @throws IOException if an I/O error occurs */ public static byte[] toByteArray(InputStream in) throws IOException { checkNotNull(in); return toByteArrayInternal(in, new ArrayDeque<byte[]>(TO_BYTE_ARRAY_DEQUE_SIZE), 0); } /** * Reads all bytes from an input stream into a byte array. The given expected size is used to * create an initial byte array, but if the actual number of bytes read from the stream differs, * the correct result will be returned anyway. */ static byte[] toByteArray(InputStream in, long expectedSize) throws IOException { checkArgument(expectedSize >= 0, "expectedSize (%s) must be non-negative", expectedSize); if (expectedSize > MAX_ARRAY_LEN) { throw new OutOfMemoryError(expectedSize + " bytes is too large to fit in a byte array"); } byte[] bytes = new byte[(int) expectedSize]; int remaining = (int) expectedSize; while (remaining > 0) { int off = (int) expectedSize - remaining; int read = in.read(bytes, off, remaining); if (read == -1) { // end of stream before reading expectedSize bytes // just return the bytes read so far return Arrays.copyOf(bytes, off); } remaining -= read; } // bytes is now full int b = in.read(); if (b == -1) { return bytes; } // the stream was longer, so read the rest normally Queue<byte[]> bufs = new ArrayDeque<>(TO_BYTE_ARRAY_DEQUE_SIZE + 2); bufs.add(bytes); bufs.add(new byte[] {(byte) b}); return toByteArrayInternal(in, bufs, bytes.length + 1); } /** * Reads and discards data from the given {@code InputStream} until the end of the stream is * reached. Returns the total number of bytes read. Does not close the stream. * * @since 20.0 */ @CanIgnoreReturnValue public static long exhaust(InputStream in) throws IOException { long total = 0; long read; byte[] buf = createBuffer(); while ((read = in.read(buf)) != -1) { total += read; } return total; } /** * Returns a new {@link ByteArrayDataInput} instance to read from the {@code bytes} array from the * beginning. */ public static ByteArrayDataInput newDataInput(byte[] bytes) { return newDataInput(new ByteArrayInputStream(bytes)); } /** * Returns a new {@link ByteArrayDataInput} instance to read from the {@code bytes} array, * starting at the given position. * * @throws IndexOutOfBoundsException if {@code start} is negative or greater than the length of * the array */ public static ByteArrayDataInput newDataInput(byte[] bytes, int start) { checkPositionIndex(start, bytes.length); return newDataInput(new ByteArrayInputStream(bytes, start, bytes.length - start)); } /** * Returns a new {@link ByteArrayDataInput} instance to read from the given {@code * ByteArrayInputStream}. The given input stream is not reset before being read from by the * returned {@code ByteArrayDataInput}. * * @since 17.0 */ public static ByteArrayDataInput newDataInput(ByteArrayInputStream byteArrayInputStream) { return new ByteArrayDataInputStream(checkNotNull(byteArrayInputStream)); } private static class ByteArrayDataInputStream implements ByteArrayDataInput { final DataInput input; ByteArrayDataInputStream(ByteArrayInputStream byteArrayInputStream) { this.input = new DataInputStream(byteArrayInputStream); } @Override public void readFully(byte b[]) { try { input.readFully(b); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public void readFully(byte b[], int off, int len) { try { input.readFully(b, off, len); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int skipBytes(int n) { try { return input.skipBytes(n); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public boolean readBoolean() { try { return input.readBoolean(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public byte readByte() { try { return input.readByte(); } catch (EOFException e) { throw new IllegalStateException(e); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public int readUnsignedByte() { try { return input.readUnsignedByte(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public short readShort() { try { return input.readShort(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int readUnsignedShort() { try { return input.readUnsignedShort(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public char readChar() { try { return input.readChar(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public int readInt() { try { return input.readInt(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public long readLong() { try { return input.readLong(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public float readFloat() { try { return input.readFloat(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public double readDouble() { try { return input.readDouble(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override @CheckForNull public String readLine() { try { return input.readLine(); } catch (IOException e) { throw new IllegalStateException(e); } } @Override public String readUTF() { try { return input.readUTF(); } catch (IOException e) { throw new IllegalStateException(e); } } } /** Returns a new {@link ByteArrayDataOutput} instance with a default size. */ public static ByteArrayDataOutput newDataOutput() { return newDataOutput(new ByteArrayOutputStream()); } /** * Returns a new {@link ByteArrayDataOutput} instance sized to hold {@code size} bytes before * resizing. * * @throws IllegalArgumentException if {@code size} is negative */ public static ByteArrayDataOutput newDataOutput(int size) { // When called at high frequency, boxing size generates too much garbage, // so avoid doing that if we can. if (size < 0) { throw new IllegalArgumentException(String.format("Invalid size: %s", size)); } return newDataOutput(new ByteArrayOutputStream(size)); } /** * Returns a new {@link ByteArrayDataOutput} instance which writes to the given {@code * ByteArrayOutputStream}. The given output stream is not reset before being written to by the * returned {@code ByteArrayDataOutput} and new data will be appended to any existing content. * * <p>Note that if the given output stream was not empty or is modified after the {@code * ByteArrayDataOutput} is created, the contract for {@link ByteArrayDataOutput#toByteArray} will * not be honored (the bytes returned in the byte array may not be exactly what was written via * calls to {@code ByteArrayDataOutput}). * * @since 17.0 */ public static ByteArrayDataOutput newDataOutput(ByteArrayOutputStream byteArrayOutputStream) { return new ByteArrayDataOutputStream(checkNotNull(byteArrayOutputStream)); } private static class ByteArrayDataOutputStream implements ByteArrayDataOutput { final DataOutput output; final ByteArrayOutputStream byteArrayOutputStream; ByteArrayDataOutputStream(ByteArrayOutputStream byteArrayOutputStream) { this.byteArrayOutputStream = byteArrayOutputStream; output = new DataOutputStream(byteArrayOutputStream); } @Override public void write(int b) { try { output.write(b); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void write(byte[] b) { try { output.write(b); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void write(byte[] b, int off, int len) { try { output.write(b, off, len); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeBoolean(boolean v) { try { output.writeBoolean(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeByte(int v) { try { output.writeByte(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeBytes(String s) { try { output.writeBytes(s); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeChar(int v) { try { output.writeChar(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeChars(String s) { try { output.writeChars(s); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeDouble(double v) { try { output.writeDouble(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeFloat(float v) { try { output.writeFloat(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeInt(int v) { try { output.writeInt(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeLong(long v) { try { output.writeLong(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeShort(int v) { try { output.writeShort(v); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public void writeUTF(String s) { try { output.writeUTF(s); } catch (IOException impossible) { throw new AssertionError(impossible); } } @Override public byte[] toByteArray() { return byteArrayOutputStream.toByteArray(); } } private static final OutputStream NULL_OUTPUT_STREAM = new OutputStream() { /** Discards the specified byte. */ @Override public void write(int b) {} /** Discards the specified byte array. */ @Override public void write(byte[] b) { checkNotNull(b); } /** Discards the specified byte array. */ @Override public void write(byte[] b, int off, int len) { checkNotNull(b); checkPositionIndexes(off, off + len, b.length); } @Override public String toString() { return "ByteStreams.nullOutputStream()"; } }; /** * Returns an {@link OutputStream} that simply discards written bytes. * * @since 14.0 (since 1.0 as com.google.common.io.NullOutputStream) */ public static OutputStream nullOutputStream() { return NULL_OUTPUT_STREAM; } /** * Wraps a {@link InputStream}, limiting the number of bytes which can be read. * * @param in the input stream to be wrapped * @param limit the maximum number of bytes to be read * @return a length-limited {@link InputStream} * @since 14.0 (since 1.0 as com.google.common.io.LimitInputStream) */ public static InputStream limit(InputStream in, long limit) { return new LimitedInputStream(in, limit); } private static final class LimitedInputStream extends FilterInputStream { private long left; private long mark = -1; LimitedInputStream(InputStream in, long limit) { super(in); checkNotNull(in); checkArgument(limit >= 0, "limit must be non-negative"); left = limit; } @Override public int available() throws IOException { return (int) Math.min(in.available(), left); } // it's okay to mark even if mark isn't supported, as reset won't work @Override public synchronized void mark(int readLimit) { in.mark(readLimit); mark = left; } @Override public int read() throws IOException { if (left == 0) { return -1; } int result = in.read(); if (result != -1) { --left; } return result; } @Override public int read(byte[] b, int off, int len) throws IOException { if (left == 0) { return -1; } len = (int) Math.min(len, left); int result = in.read(b, off, len); if (result != -1) { left -= result; } return result; } @Override public synchronized void reset() throws IOException { if (!in.markSupported()) { throw new IOException("Mark not supported"); } if (mark == -1) { throw new IOException("Mark not set"); } in.reset(); left = mark; } @Override public long skip(long n) throws IOException { n = Math.min(n, left); long skipped = in.skip(n); left -= skipped; return skipped; } } /** * Attempts to read enough bytes from the stream to fill the given byte array, with the same * behavior as {@link DataInput#readFully(byte[])}. Does not close the stream. * * @param in the input stream to read from. * @param b the buffer into which the data is read. * @throws EOFException if this stream reaches the end before reading all the bytes. * @throws IOException if an I/O error occurs. */ public static void readFully(InputStream in, byte[] b) throws IOException { readFully(in, b, 0, b.length); } /** * Attempts to read {@code len} bytes from the stream into the given array starting at {@code * off}, with the same behavior as {@link DataInput#readFully(byte[], int, int)}. Does not close * the stream. * * @param in the input stream to read from. * @param b the buffer into which the data is read. * @param off an int specifying the offset into the data. * @param len an int specifying the number of bytes to read. * @throws EOFException if this stream reaches the end before reading all the bytes. * @throws IOException if an I/O error occurs. */ public static void readFully(InputStream in, byte[] b, int off, int len) throws IOException { int read = read(in, b, off, len); if (read != len) { throw new EOFException( "reached end of stream after reading " + read + " bytes; " + len + " bytes expected"); } } /** * Discards {@code n} bytes of data from the input stream. This method will block until the full * amount has been skipped. Does not close the stream. * * @param in the input stream to read from * @param n the number of bytes to skip * @throws EOFException if this stream reaches the end before skipping all the bytes * @throws IOException if an I/O error occurs, or the stream does not support skipping */ public static void skipFully(InputStream in, long n) throws IOException { long skipped = skipUpTo(in, n); if (skipped < n) { throw new EOFException( "reached end of stream after skipping " + skipped + " bytes; " + n + " bytes expected"); } } /** * Discards up to {@code n} bytes of data from the input stream. This method will block until * either the full amount has been skipped or until the end of the stream is reached, whichever * happens first. Returns the total number of bytes skipped. */ static long skipUpTo(InputStream in, long n) throws IOException { long totalSkipped = 0; // A buffer is allocated if skipSafely does not skip any bytes. byte[] buf = null; while (totalSkipped < n) { long remaining = n - totalSkipped; long skipped = skipSafely(in, remaining); if (skipped == 0) { // Do a buffered read since skipSafely could return 0 repeatedly, for example if // in.available() always returns 0 (the default). int skip = (int) Math.min(remaining, BUFFER_SIZE); if (buf == null) { // Allocate a buffer bounded by the maximum size that can be requested, for // example an array of BUFFER_SIZE is unnecessary when the value of remaining // is smaller. buf = new byte[skip]; } if ((skipped = in.read(buf, 0, skip)) == -1) { // Reached EOF break; } } totalSkipped += skipped; } return totalSkipped; } /** * Attempts to skip up to {@code n} bytes from the given input stream, but not more than {@code * in.available()} bytes. This prevents {@code FileInputStream} from skipping more bytes than * actually remain in the file, something that it {@linkplain java.io.FileInputStream#skip(long) * specifies} it can do in its Javadoc despite the fact that it is violating the contract of * {@code InputStream.skip()}. */ private static long skipSafely(InputStream in, long n) throws IOException { int available = in.available(); return available == 0 ? 0 : in.skip(Math.min(available, n)); } /** * Process the bytes of the given input stream using the given processor. * * @param input the input stream to process * @param processor the object to which to pass the bytes of the stream * @return the result of the byte processor * @throws IOException if an I/O error occurs * @since 14.0 */ @CanIgnoreReturnValue // some processors won't return a useful result @ParametricNullness public static <T extends @Nullable Object> T readBytes( InputStream input, ByteProcessor<T> processor) throws IOException { checkNotNull(input); checkNotNull(processor); byte[] buf = createBuffer(); int read; do { read = input.read(buf); } while (read != -1 && processor.processBytes(buf, 0, read)); return processor.getResult(); } /** * Reads some bytes from an input stream and stores them into the buffer array {@code b}. This * method blocks until {@code len} bytes of input data have been read into the array, or end of * file is detected. The number of bytes read is returned, possibly zero. Does not close the * stream. * * <p>A caller can detect EOF if the number of bytes read is less than {@code len}. All subsequent * calls on the same stream will return zero. * * <p>If {@code b} is null, a {@code NullPointerException} is thrown. If {@code off} is negative, * or {@code len} is negative, or {@code off+len} is greater than the length of the array {@code * b}, then an {@code IndexOutOfBoundsException} is thrown. If {@code len} is zero, then no bytes * are read. Otherwise, the first byte read is stored into element {@code b[off]}, the next one * into {@code b[off+1]}, and so on. The number of bytes read is, at most, equal to {@code len}. * * @param in the input stream to read from * @param b the buffer into which the data is read * @param off an int specifying the offset into the data * @param len an int specifying the number of bytes to read * @return the number of bytes read * @throws IOException if an I/O error occurs * @throws IndexOutOfBoundsException if {@code off} is negative, if {@code len} is negative, or if * {@code off + len} is greater than {@code b.length} */ @CanIgnoreReturnValue // Sometimes you don't care how many bytes you actually read, I guess. // (You know that it's either going to read len bytes or stop at EOF.) public static int read(InputStream in, byte[] b, int off, int len) throws IOException { checkNotNull(in); checkNotNull(b); if (len < 0) { throw new IndexOutOfBoundsException(String.format("len (%s) cannot be negative", len)); } checkPositionIndexes(off, off + len, b.length); int total = 0; while (total < len) { int result = in.read(b, off + total, len - total); if (result == -1) { break; } total += result; } return total; } }
google/guava
android/guava/src/com/google/common/io/ByteStreams.java
346
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.promise; import java.util.Map; import java.util.concurrent.CompletableFuture; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import lombok.extern.slf4j.Slf4j; /** * The Promise object is used for asynchronous computations. A Promise represents an operation that * hasn't completed yet, but is expected in the future. * * <p>A Promise represents a proxy for a value not necessarily known when the promise is created. * It allows you to associate dependent promises to an asynchronous action's eventual success value * or failure reason. This lets asynchronous methods return values like synchronous methods: instead * of the final value, the asynchronous method returns a promise of having a value at some point in * the future. * * <p>Promises provide a few advantages over callback objects: * <ul> * <li> Functional composition and error handling * <li> Prevents callback hell and provides callback aggregation * </ul> * * <p>In this application the usage of promise is demonstrated with two examples: * <ul> * <li>Count Lines: In this example a file is downloaded and its line count is calculated. * The calculated line count is then consumed and printed on console. * <li>Lowest Character Frequency: In this example a file is downloaded and its lowest frequency * character is found and printed on console. This happens via a chain of promises, we start with * a file download promise, then a promise of character frequency, then a promise of lowest * frequency character which is finally consumed and result is printed on console. * </ul> * * @see CompletableFuture */ @Slf4j public class App { private static final String DEFAULT_URL = "https://raw.githubusercontent.com/iluwatar/java-design-patterns/master/promise/README.md"; private final ExecutorService executor; private final CountDownLatch stopLatch; private App() { executor = Executors.newFixedThreadPool(2); stopLatch = new CountDownLatch(2); } /** * Program entry point. * * @param args arguments * @throws InterruptedException if main thread is interrupted. */ public static void main(String[] args) throws InterruptedException { var app = new App(); try { app.promiseUsage(); } finally { app.stop(); } } private void promiseUsage() { calculateLineCount(); calculateLowestFrequencyChar(); } /* * Calculate the lowest frequency character and when that promise is fulfilled, * consume the result in a Consumer<Character> */ private void calculateLowestFrequencyChar() { lowestFrequencyChar().thenAccept( charFrequency -> { LOGGER.info("Char with lowest frequency is: {}", charFrequency); taskCompleted(); } ); } /* * Calculate the line count and when that promise is fulfilled, consume the result * in a Consumer<Integer> */ private void calculateLineCount() { countLines().thenAccept( count -> { LOGGER.info("Line count is: {}", count); taskCompleted(); } ); } /* * Calculate the character frequency of a file and when that promise is fulfilled, * then promise to apply function to calculate the lowest character frequency. */ private Promise<Character> lowestFrequencyChar() { return characterFrequency().thenApply(Utility::lowestFrequencyChar); } /* * Download the file at DEFAULT_URL and when that promise is fulfilled, * then promise to apply function to calculate character frequency. */ private Promise<Map<Character, Long>> characterFrequency() { return download(DEFAULT_URL).thenApply(Utility::characterFrequency); } /* * Download the file at DEFAULT_URL and when that promise is fulfilled, * then promise to apply function to count lines in that file. */ private Promise<Integer> countLines() { return download(DEFAULT_URL).thenApply(Utility::countLines); } /* * Return a promise to provide the local absolute path of the file downloaded in background. * This is an async method and does not wait until the file is downloaded. */ private Promise<String> download(String urlString) { return new Promise<String>() .fulfillInAsync( () -> Utility.downloadFile(urlString), executor) .onError( throwable -> { LOGGER.error("An error occurred: ", throwable); taskCompleted(); } ); } private void stop() throws InterruptedException { stopLatch.await(); executor.shutdownNow(); } private void taskCompleted() { stopLatch.countDown(); } }
iluwatar/java-design-patterns
promise/src/main/java/com/iluwatar/promise/App.java
347
/* * 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.io; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.BufferedWriter; import java.io.IOException; import java.io.Reader; import java.io.Writer; import java.nio.charset.Charset; import java.util.Iterator; import java.util.stream.Stream; /** * A destination to which characters can be written, such as a text file. Unlike a {@link Writer}, a * {@code CharSink} is not an open, stateful stream that can be written to and closed. Instead, it * is an immutable <i>supplier</i> of {@code Writer} instances. * * <p>{@code CharSink} provides two kinds of methods: * * <ul> * <li><b>Methods that return a writer:</b> These methods should return a <i>new</i>, independent * instance each time they are called. The caller is responsible for ensuring that the * returned writer is closed. * <li><b>Convenience methods:</b> These are implementations of common operations that are * typically implemented by opening a writer using one of the methods in the first category, * doing something and finally closing the writer that was opened. * </ul> * * <p>Any {@link ByteSink} may be viewed as a {@code CharSink} with a specific {@linkplain Charset * character encoding} using {@link ByteSink#asCharSink(Charset)}. Characters written to the * resulting {@code CharSink} will written to the {@code ByteSink} as encoded bytes. * * @since 14.0 * @author Colin Decker */ @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public abstract class CharSink { /** Constructor for use by subclasses. */ protected CharSink() {} /** * Opens a new {@link Writer} for writing to this sink. This method returns a new, independent * writer each time it is called. * * <p>The caller is responsible for ensuring that the returned writer is closed. * * @throws IOException if an I/O error occurs while opening the writer */ public abstract Writer openStream() throws IOException; /** * Opens a new buffered {@link Writer} for writing to this sink. The returned stream is not * required to be a {@link BufferedWriter} in order to allow implementations to simply delegate to * {@link #openStream()} when the stream returned by that method does not benefit from additional * buffering. This method returns a new, independent writer each time it is called. * * <p>The caller is responsible for ensuring that the returned writer is closed. * * @throws IOException if an I/O error occurs while opening the writer * @since 15.0 (in 14.0 with return type {@link BufferedWriter}) */ public Writer openBufferedStream() throws IOException { Writer writer = openStream(); return (writer instanceof BufferedWriter) ? (BufferedWriter) writer : new BufferedWriter(writer); } /** * Writes the given character sequence to this sink. * * @throws IOException if an I/O error while writing to this sink */ public void write(CharSequence charSequence) throws IOException { checkNotNull(charSequence); Closer closer = Closer.create(); try { Writer out = closer.register(openStream()); out.append(charSequence); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Writes the given lines of text to this sink with each line (including the last) terminated with * the operating system's default line separator. This method is equivalent to {@code * writeLines(lines, System.getProperty("line.separator"))}. * * @throws IOException if an I/O error occurs while writing to this sink */ public void writeLines(Iterable<? extends CharSequence> lines) throws IOException { writeLines(lines, System.getProperty("line.separator")); } /** * Writes the given lines of text to this sink with each line (including the last) terminated with * the given line separator. * * @throws IOException if an I/O error occurs while writing to this sink */ public void writeLines(Iterable<? extends CharSequence> lines, String lineSeparator) throws IOException { writeLines(lines.iterator(), lineSeparator); } /** * Writes the given lines of text to this sink with each line (including the last) terminated with * the operating system's default line separator. This method is equivalent to {@code * writeLines(lines, System.getProperty("line.separator"))}. * * @throws IOException if an I/O error occurs while writing to this sink * @since 22.0 */ public void writeLines(Stream<? extends CharSequence> lines) throws IOException { writeLines(lines, System.getProperty("line.separator")); } /** * Writes the given lines of text to this sink with each line (including the last) terminated with * the given line separator. * * @throws IOException if an I/O error occurs while writing to this sink * @since 22.0 */ public void writeLines(Stream<? extends CharSequence> lines, String lineSeparator) throws IOException { writeLines(lines.iterator(), lineSeparator); } private void writeLines(Iterator<? extends CharSequence> lines, String lineSeparator) throws IOException { checkNotNull(lineSeparator); try (Writer out = openBufferedStream()) { while (lines.hasNext()) { out.append(lines.next()).append(lineSeparator); } } } /** * Writes all the text from the given {@link Readable} (such as a {@link Reader}) to this sink. * Does not close {@code readable} if it is {@code Closeable}. * * @return the number of characters written * @throws IOException if an I/O error occurs while reading from {@code readable} or writing to * this sink */ @CanIgnoreReturnValue public long writeFrom(Readable readable) throws IOException { checkNotNull(readable); Closer closer = Closer.create(); try { Writer out = closer.register(openStream()); long written = CharStreams.copy(readable, out); out.flush(); // https://code.google.com/p/guava-libraries/issues/detail?id=1330 return written; } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } }
google/guava
guava/src/com/google/common/io/CharSink.java
348
// Protocol Buffers - Google's data interchange format // Copyright 2008 Google Inc. All rights reserved. // // Use of this source code is governed by a BSD-style // license that can be found in the LICENSE file or at // https://developers.google.com/open-source/licenses/bsd import com.google.protobuf.AbstractMessage; import com.google.protobuf.ByteString; import com.google.protobuf.CodedInputStream; import com.google.protobuf.ExtensionRegistry; import com.google.protobuf.InvalidProtocolBufferException; import com.google.protobuf.Parser; import com.google.protobuf.TextFormat; import com.google.protobuf.conformance.Conformance; import com.google.protobuf.util.JsonFormat; import com.google.protobuf.util.JsonFormat.TypeRegistry; import com.google.protobuf_test_messages.edition2023.TestAllTypesEdition2023; import com.google.protobuf_test_messages.edition2023.TestMessagesEdition2023; import com.google.protobuf_test_messages.editions.proto2.TestMessagesProto2Editions; import com.google.protobuf_test_messages.editions.proto3.TestMessagesProto3Editions; import com.google.protobuf_test_messages.proto2.TestMessagesProto2; import com.google.protobuf_test_messages.proto2.TestMessagesProto2.TestAllTypesProto2; import com.google.protobuf_test_messages.proto3.TestMessagesProto3; import com.google.protobuf_test_messages.proto3.TestMessagesProto3.TestAllTypesProto3; import java.nio.ByteBuffer; import java.util.ArrayList; class ConformanceJava { private int testCount = 0; private TypeRegistry typeRegistry; private boolean readFromStdin(byte[] buf, int len) throws Exception { int ofs = 0; while (len > 0) { int read = System.in.read(buf, ofs, len); if (read == -1) { return false; // EOF } ofs += read; len -= read; } return true; } private void writeToStdout(byte[] buf) throws Exception { System.out.write(buf); } // Returns -1 on EOF (the actual values will always be positive). private int readLittleEndianIntFromStdin() throws Exception { byte[] buf = new byte[4]; if (!readFromStdin(buf, 4)) { return -1; } return (buf[0] & 0xff) | ((buf[1] & 0xff) << 8) | ((buf[2] & 0xff) << 16) | ((buf[3] & 0xff) << 24); } private void writeLittleEndianIntToStdout(int val) throws Exception { byte[] buf = new byte[4]; buf[0] = (byte) val; buf[1] = (byte) (val >> 8); buf[2] = (byte) (val >> 16); buf[3] = (byte) (val >> 24); writeToStdout(buf); } private enum BinaryDecoderType { BTYE_STRING_DECODER, BYTE_ARRAY_DECODER, ARRAY_BYTE_BUFFER_DECODER, READONLY_ARRAY_BYTE_BUFFER_DECODER, DIRECT_BYTE_BUFFER_DECODER, READONLY_DIRECT_BYTE_BUFFER_DECODER, INPUT_STREAM_DECODER; } private static class BinaryDecoder<T extends AbstractMessage> { public T decode( ByteString bytes, BinaryDecoderType type, Parser<T> parser, ExtensionRegistry extensions) throws InvalidProtocolBufferException { switch (type) { case BTYE_STRING_DECODER: case BYTE_ARRAY_DECODER: return parser.parseFrom(bytes, extensions); case ARRAY_BYTE_BUFFER_DECODER: { ByteBuffer buffer = ByteBuffer.allocate(bytes.size()); bytes.copyTo(buffer); buffer.flip(); return parser.parseFrom(CodedInputStream.newInstance(buffer), extensions); } case READONLY_ARRAY_BYTE_BUFFER_DECODER: { return parser.parseFrom( CodedInputStream.newInstance(bytes.asReadOnlyByteBuffer()), extensions); } case DIRECT_BYTE_BUFFER_DECODER: { ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size()); bytes.copyTo(buffer); buffer.flip(); return parser.parseFrom(CodedInputStream.newInstance(buffer), extensions); } case READONLY_DIRECT_BYTE_BUFFER_DECODER: { ByteBuffer buffer = ByteBuffer.allocateDirect(bytes.size()); bytes.copyTo(buffer); buffer.flip(); return parser.parseFrom( CodedInputStream.newInstance(buffer.asReadOnlyBuffer()), extensions); } case INPUT_STREAM_DECODER: { return parser.parseFrom(bytes.newInput(), extensions); } } return null; } } private <T extends AbstractMessage> T parseBinary( ByteString bytes, Parser<T> parser, ExtensionRegistry extensions) throws InvalidProtocolBufferException { ArrayList<T> messages = new ArrayList<>(); ArrayList<InvalidProtocolBufferException> exceptions = new ArrayList<>(); for (int i = 0; i < BinaryDecoderType.values().length; i++) { messages.add(null); exceptions.add(null); } if (messages.isEmpty()) { throw new RuntimeException("binary decoder types missing"); } BinaryDecoder<T> decoder = new BinaryDecoder<>(); boolean hasMessage = false; boolean hasException = false; for (int i = 0; i < BinaryDecoderType.values().length; ++i) { try { // = BinaryDecoderType.values()[i].parseProto3(bytes); messages.set(i, decoder.decode(bytes, BinaryDecoderType.values()[i], parser, extensions)); hasMessage = true; } catch (InvalidProtocolBufferException e) { exceptions.set(i, e); hasException = true; } } if (hasMessage && hasException) { StringBuilder sb = new StringBuilder("Binary decoders disagreed on whether the payload was valid.\n"); for (int i = 0; i < BinaryDecoderType.values().length; ++i) { sb.append(BinaryDecoderType.values()[i].name()); if (messages.get(i) != null) { sb.append(" accepted the payload.\n"); } else { sb.append(" rejected the payload.\n"); } } throw new RuntimeException(sb.toString()); } if (hasException) { // We do not check if exceptions are equal. Different implementations may return different // exception messages. Throw an arbitrary one out instead. InvalidProtocolBufferException exception = null; for (InvalidProtocolBufferException e : exceptions) { if (exception != null) { exception.addSuppressed(e); } else { exception = e; } } throw exception; } // Fast path comparing all the messages with the first message, assuming equality being // symmetric and transitive. boolean allEqual = true; for (int i = 1; i < messages.size(); ++i) { if (!messages.get(0).equals(messages.get(i))) { allEqual = false; break; } } // Slow path: compare and find out all unequal pairs. if (!allEqual) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < messages.size() - 1; ++i) { for (int j = i + 1; j < messages.size(); ++j) { if (!messages.get(i).equals(messages.get(j))) { sb.append(BinaryDecoderType.values()[i].name()) .append(" and ") .append(BinaryDecoderType.values()[j].name()) .append(" parsed the payload differently.\n"); } } } throw new RuntimeException(sb.toString()); } return messages.get(0); } private Class<? extends AbstractMessage> createTestMessage(String messageType) { switch (messageType) { case "protobuf_test_messages.proto3.TestAllTypesProto3": return TestAllTypesProto3.class; case "protobuf_test_messages.proto2.TestAllTypesProto2": return TestAllTypesProto2.class; case "protobuf_test_messages.editions.TestAllTypesEdition2023": return TestAllTypesEdition2023.class; case "protobuf_test_messages.editions.proto3.TestAllTypesProto3": return TestMessagesProto3Editions.TestAllTypesProto3.class; case "protobuf_test_messages.editions.proto2.TestAllTypesProto2": return TestMessagesProto2Editions.TestAllTypesProto2.class; default: throw new IllegalArgumentException( "Protobuf request has unexpected payload type: " + messageType); } } private Class<?> createTestFile(String messageType) { switch (messageType) { case "protobuf_test_messages.proto3.TestAllTypesProto3": return TestMessagesProto3.class; case "protobuf_test_messages.proto2.TestAllTypesProto2": return TestMessagesProto2.class; case "protobuf_test_messages.editions.TestAllTypesEdition2023": return TestMessagesEdition2023.class; case "protobuf_test_messages.editions.proto3.TestAllTypesProto3": return TestMessagesProto3Editions.class; case "protobuf_test_messages.editions.proto2.TestAllTypesProto2": return TestMessagesProto2Editions.class; default: throw new IllegalArgumentException( "Protobuf request has unexpected payload type: " + messageType); } } @SuppressWarnings("unchecked") private Conformance.ConformanceResponse doTest(Conformance.ConformanceRequest request) { AbstractMessage testMessage; String messageType = request.getMessageType(); ExtensionRegistry extensions = ExtensionRegistry.newInstance(); try { createTestFile(messageType) .getMethod("registerAllExtensions", ExtensionRegistry.class) .invoke(null, extensions); } catch (Exception e) { throw new RuntimeException(e); } switch (request.getPayloadCase()) { case PROTOBUF_PAYLOAD: { try { testMessage = parseBinary( request.getProtobufPayload(), (Parser<AbstractMessage>) createTestMessage(messageType).getMethod("parser").invoke(null), extensions); } catch (InvalidProtocolBufferException e) { return Conformance.ConformanceResponse.newBuilder() .setParseError(e.getMessage()) .build(); } catch (Exception e) { throw new RuntimeException(e); } break; } case JSON_PAYLOAD: { try { JsonFormat.Parser parser = JsonFormat.parser().usingTypeRegistry(typeRegistry); if (request.getTestCategory() == Conformance.TestCategory.JSON_IGNORE_UNKNOWN_PARSING_TEST) { parser = parser.ignoringUnknownFields(); } AbstractMessage.Builder<?> builder = (AbstractMessage.Builder<?>) createTestMessage(messageType).getMethod("newBuilder").invoke(null); parser.merge(request.getJsonPayload(), builder); testMessage = (AbstractMessage) builder.build(); } catch (InvalidProtocolBufferException e) { return Conformance.ConformanceResponse.newBuilder() .setParseError(e.getMessage()) .build(); } catch (Exception e) { throw new RuntimeException(e); } break; } case TEXT_PAYLOAD: { try { AbstractMessage.Builder<?> builder = (AbstractMessage.Builder<?>) createTestMessage(messageType).getMethod("newBuilder").invoke(null); TextFormat.merge(request.getTextPayload(), extensions, builder); testMessage = (AbstractMessage) builder.build(); } catch (TextFormat.ParseException e) { return Conformance.ConformanceResponse.newBuilder() .setParseError(e.getMessage()) .build(); } catch (Exception e) { throw new RuntimeException(e); } break; } case PAYLOAD_NOT_SET: { throw new IllegalArgumentException("Request didn't have payload."); } default: { throw new IllegalArgumentException("Unexpected payload case."); } } switch (request.getRequestedOutputFormat()) { case UNSPECIFIED: throw new IllegalArgumentException("Unspecified output format."); case PROTOBUF: { ByteString messageString = testMessage.toByteString(); return Conformance.ConformanceResponse.newBuilder() .setProtobufPayload(messageString) .build(); } case JSON: try { return Conformance.ConformanceResponse.newBuilder() .setJsonPayload( JsonFormat.printer().usingTypeRegistry(typeRegistry).print(testMessage)) .build(); } catch (InvalidProtocolBufferException | IllegalArgumentException e) { return Conformance.ConformanceResponse.newBuilder() .setSerializeError(e.getMessage()) .build(); } case TEXT_FORMAT: return Conformance.ConformanceResponse.newBuilder() .setTextPayload(TextFormat.printer().printToString(testMessage)) .build(); default: { throw new IllegalArgumentException("Unexpected request output."); } } } private boolean doTestIo() throws Exception { int bytes = readLittleEndianIntFromStdin(); if (bytes == -1) { return false; // EOF } byte[] serializedInput = new byte[bytes]; if (!readFromStdin(serializedInput, bytes)) { throw new RuntimeException("Unexpected EOF from test program."); } Conformance.ConformanceRequest request = Conformance.ConformanceRequest.parseFrom(serializedInput); Conformance.ConformanceResponse response = doTest(request); byte[] serializedOutput = response.toByteArray(); writeLittleEndianIntToStdout(serializedOutput.length); writeToStdout(serializedOutput); return true; } public void run() throws Exception { typeRegistry = TypeRegistry.newBuilder() .add(TestMessagesProto3.TestAllTypesProto3.getDescriptor()) .add( com.google.protobuf_test_messages.editions.proto3.TestMessagesProto3Editions .TestAllTypesProto3.getDescriptor()) .build(); while (doTestIo()) { this.testCount++; } System.err.println( "ConformanceJava: received EOF from test runner after " + this.testCount + " tests"); } public static void main(String[] args) throws Exception { new ConformanceJava().run(); } }
protocolbuffers/protobuf
conformance/ConformanceJava.java
349
// This import checks that the compiler won't parse the "record" word as a soft keyword // and load the non-existing class named "Unresolved" from this Java source. import record.Unresolved; // This class should be resolved correctly. public record Record(String string) {}
JetBrains/kotlin
compiler/testData/cli/jvm/Record.java
350
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.promise; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.FileWriter; import java.io.IOException; import java.io.InputStreamReader; import java.net.URL; import java.util.Collections; import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; import java.util.function.Function; import java.util.stream.Collectors; import lombok.extern.slf4j.Slf4j; /** * Utility to perform various operations. */ @Slf4j public class Utility { /** * Calculates character frequency of the file provided. * * @param fileLocation location of the file. * @return a map of character to its frequency, an empty map if file does not exist. */ public static Map<Character, Long> characterFrequency(String fileLocation) { try (var bufferedReader = new BufferedReader(new FileReader(fileLocation))) { return bufferedReader.lines() .flatMapToInt(String::chars) .mapToObj(x -> (char) x) .collect(Collectors.groupingBy(Function.identity(), Collectors.counting())); } catch (IOException ex) { LOGGER.error("An error occurred: ", ex); } return Collections.emptyMap(); } /** * Return the character with the lowest frequency, if exists. * * @return the character, {@code Optional.empty()} otherwise. */ public static Character lowestFrequencyChar(Map<Character, Long> charFrequency) { return charFrequency .entrySet() .stream() .min(Comparator.comparingLong(Entry::getValue)) .map(Entry::getKey) .orElseThrow(); } /** * Count the number of lines in a file. * * @return number of lines, 0 if file does not exist. */ public static Integer countLines(String fileLocation) { try (var bufferedReader = new BufferedReader(new FileReader(fileLocation))) { return (int) bufferedReader.lines().count(); } catch (IOException ex) { LOGGER.error("An error occurred: ", ex); } return 0; } /** * Downloads the contents from the given urlString, and stores it in a temporary directory. * * @return the absolute path of the file downloaded. */ public static String downloadFile(String urlString) throws IOException { LOGGER.info("Downloading contents from url: {}", urlString); var url = new URL(urlString); var file = File.createTempFile("promise_pattern", null); try (var bufferedReader = new BufferedReader(new InputStreamReader(url.openStream())); var writer = new FileWriter(file)) { String line; while ((line = bufferedReader.readLine()) != null) { writer.write(line); writer.write("\n"); } LOGGER.info("File downloaded at: {}", file.getAbsolutePath()); return file.getAbsolutePath(); } } }
iluwatar/java-design-patterns
promise/src/main/java/com/iluwatar/promise/Utility.java
351
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndex; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import java.util.Arrays; import java.util.BitSet; /** * Determines a true or false value for any Java {@code char} value, just as {@link Predicate} does * for any {@link Object}. Also offers basic text processing methods based on this function. * Implementations are strongly encouraged to be side-effect-free and immutable. * * <p>Throughout the documentation of this class, the phrase "matching character" is used to mean * "any {@code char} value {@code c} for which {@code this.matches(c)} returns {@code true}". * * <p><b>Warning:</b> This class deals only with {@code char} values, that is, <a * href="http://www.unicode.org/glossary/#BMP_character">BMP characters</a>. It does not understand * <a href="http://www.unicode.org/glossary/#supplementary_code_point">supplementary Unicode code * points</a> in the range {@code 0x10000} to {@code 0x10FFFF} which includes the majority of * assigned characters, including important CJK characters and emoji. * * <p>Supplementary characters are <a * href="https://docs.oracle.com/javase/8/docs/api/java/lang/Character.html#supplementary">encoded * into a {@code String} using surrogate pairs</a>, and a {@code CharMatcher} treats these just as * two separate characters. {@link #countIn} counts each supplementary character as 2 {@code char}s. * * <p>For up-to-date Unicode character properties (digit, letter, etc.) and support for * supplementary code points, use ICU4J UCharacter and UnicodeSet (freeze() after building). For * basic text processing based on UnicodeSet use the ICU4J UnicodeSetSpanner. * * <p>Example usages: * * <pre> * String trimmed = {@link #whitespace() whitespace()}.{@link #trimFrom trimFrom}(userInput); * if ({@link #ascii() ascii()}.{@link #matchesAllOf matchesAllOf}(s)) { ... }</pre> * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/StringsExplained#charmatcher">{@code CharMatcher} * </a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public abstract class CharMatcher implements Predicate<Character> { /* * N777777777NO * N7777777777777N * M777777777777777N * $N877777777D77777M * N M77777777ONND777M * MN777777777NN D777 * N7ZN777777777NN ~M7778 * N777777777777MMNN88777N * N777777777777MNZZZ7777O * DZN7777O77777777777777 * N7OONND7777777D77777N * 8$M++++?N???$77777$ * M7++++N+M77777777N * N77O777777777777$ M * DNNM$$$$777777N D * N$N:=N$777N7777M NZ * 77Z::::N777777777 ODZZZ * 77N::::::N77777777M NNZZZ$ * $777:::::::77777777MN ZM8ZZZZZ * 777M::::::Z7777777Z77 N++ZZZZNN * 7777M:::::M7777777$777M $++IZZZZM * M777$:::::N777777$M7777M +++++ZZZDN * NN$::::::7777$$M777777N N+++ZZZZNZ * N::::::N:7$O:77777777 N++++ZZZZN * M::::::::::::N77777777+ +?+++++ZZZM * 8::::::::::::D77777777M O+++++ZZ * ::::::::::::M777777777N O+?D * M:::::::::::M77777777778 77= * D=::::::::::N7777777777N 777 * INN===::::::=77777777777N I777N * ?777N========N7777777777787M N7777 * 77777$D======N77777777777N777N? N777777 * I77777$$$N7===M$$77777777$77777777$MMZ77777777N * $$$$$$$$$$$NIZN$$$$$$$$$M$$7777777777777777ON * M$$$$$$$$M M$$$$$$$$N=N$$$$7777777$$$ND * O77Z$$$$$$$ M$$$$$$$$MNI==$DNNNNM=~N * 7 :N MNN$$$$M$ $$$777$8 8D8I * NMM.:7O 777777778 * 7777777MN * M NO .7: * M : M * 8 */ // Constant matcher factory methods /** * Matches any character. * * @since 19.0 (since 1.0 as constant {@code ANY}) */ public static CharMatcher any() { return Any.INSTANCE; } /** * Matches no characters. * * @since 19.0 (since 1.0 as constant {@code NONE}) */ public static CharMatcher none() { return None.INSTANCE; } /** * Determines whether a character is whitespace according to the latest Unicode standard, as * illustrated <a * href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bwhitespace%7D">here</a>. * This is not the same definition used by other Java APIs. (See a <a * href="https://goo.gl/Y6SLWx">comparison of several definitions of "whitespace"</a>.) * * <p>All Unicode White_Space characters are on the BMP and thus supported by this API. * * <p><b>Note:</b> as the Unicode definition evolves, we will modify this matcher to keep it up to * date. * * @since 19.0 (since 1.0 as constant {@code WHITESPACE}) */ public static CharMatcher whitespace() { return Whitespace.INSTANCE; } /** * Determines whether a character is a breaking whitespace (that is, a whitespace which can be * interpreted as a break between words for formatting purposes). See {@link #whitespace()} for a * discussion of that term. * * @since 19.0 (since 2.0 as constant {@code BREAKING_WHITESPACE}) */ public static CharMatcher breakingWhitespace() { return BreakingWhitespace.INSTANCE; } /** * Determines whether a character is ASCII, meaning that its code point is less than 128. * * @since 19.0 (since 1.0 as constant {@code ASCII}) */ public static CharMatcher ascii() { return Ascii.INSTANCE; } /** * Determines whether a character is a BMP digit according to <a * href="http://unicode.org/cldr/utility/list-unicodeset.jsp?a=%5Cp%7Bdigit%7D">Unicode</a>. If * you only care to match ASCII digits, you can use {@code inRange('0', '9')}. * * @deprecated Many digits are supplementary characters; see the class documentation. * @since 19.0 (since 1.0 as constant {@code DIGIT}) */ @Deprecated public static CharMatcher digit() { return Digit.INSTANCE; } /** * Determines whether a character is a BMP digit according to {@linkplain Character#isDigit(char) * Java's definition}. If you only care to match ASCII digits, you can use {@code inRange('0', * '9')}. * * @deprecated Many digits are supplementary characters; see the class documentation. * @since 19.0 (since 1.0 as constant {@code JAVA_DIGIT}) */ @Deprecated public static CharMatcher javaDigit() { return JavaDigit.INSTANCE; } /** * Determines whether a character is a BMP letter according to {@linkplain * Character#isLetter(char) Java's definition}. If you only care to match letters of the Latin * alphabet, you can use {@code inRange('a', 'z').or(inRange('A', 'Z'))}. * * @deprecated Most letters are supplementary characters; see the class documentation. * @since 19.0 (since 1.0 as constant {@code JAVA_LETTER}) */ @Deprecated public static CharMatcher javaLetter() { return JavaLetter.INSTANCE; } /** * Determines whether a character is a BMP letter or digit according to {@linkplain * Character#isLetterOrDigit(char) Java's definition}. * * @deprecated Most letters and digits are supplementary characters; see the class documentation. * @since 19.0 (since 1.0 as constant {@code JAVA_LETTER_OR_DIGIT}). */ @Deprecated public static CharMatcher javaLetterOrDigit() { return JavaLetterOrDigit.INSTANCE; } /** * Determines whether a BMP character is upper case according to {@linkplain * Character#isUpperCase(char) Java's definition}. * * @deprecated Some uppercase characters are supplementary characters; see the class * documentation. * @since 19.0 (since 1.0 as constant {@code JAVA_UPPER_CASE}) */ @Deprecated public static CharMatcher javaUpperCase() { return JavaUpperCase.INSTANCE; } /** * Determines whether a BMP character is lower case according to {@linkplain * Character#isLowerCase(char) Java's definition}. * * @deprecated Some lowercase characters are supplementary characters; see the class * documentation. * @since 19.0 (since 1.0 as constant {@code JAVA_LOWER_CASE}) */ @Deprecated public static CharMatcher javaLowerCase() { return JavaLowerCase.INSTANCE; } /** * Determines whether a character is an ISO control character as specified by {@link * Character#isISOControl(char)}. * * <p>All ISO control codes are on the BMP and thus supported by this API. * * @since 19.0 (since 1.0 as constant {@code JAVA_ISO_CONTROL}) */ public static CharMatcher javaIsoControl() { return JavaIsoControl.INSTANCE; } /** * Determines whether a character is invisible; that is, if its Unicode category is any of * SPACE_SEPARATOR, LINE_SEPARATOR, PARAGRAPH_SEPARATOR, CONTROL, FORMAT, SURROGATE, and * PRIVATE_USE according to ICU4J. * * <p>See also the Unicode Default_Ignorable_Code_Point property (available via ICU). * * @deprecated Most invisible characters are supplementary characters; see the class * documentation. * @since 19.0 (since 1.0 as constant {@code INVISIBLE}) */ @Deprecated public static CharMatcher invisible() { return Invisible.INSTANCE; } /** * Determines whether a character is single-width (not double-width). When in doubt, this matcher * errs on the side of returning {@code false} (that is, it tends to assume a character is * double-width). * * <p><b>Note:</b> as the reference file evolves, we will modify this matcher to keep it up to * date. * * <p>See also <a href="http://www.unicode.org/reports/tr11/">UAX #11 East Asian Width</a>. * * @deprecated Many such characters are supplementary characters; see the class documentation. * @since 19.0 (since 1.0 as constant {@code SINGLE_WIDTH}) */ @Deprecated public static CharMatcher singleWidth() { return SingleWidth.INSTANCE; } // Static factories /** Returns a {@code char} matcher that matches only one specified BMP character. */ public static CharMatcher is(final char match) { return new Is(match); } /** * Returns a {@code char} matcher that matches any character except the BMP character specified. * * <p>To negate another {@code CharMatcher}, use {@link #negate()}. */ public static CharMatcher isNot(final char match) { return new IsNot(match); } /** * Returns a {@code char} matcher that matches any BMP character present in the given character * sequence. Returns a bogus matcher if the sequence contains supplementary characters. */ public static CharMatcher anyOf(final CharSequence sequence) { switch (sequence.length()) { case 0: return none(); case 1: return is(sequence.charAt(0)); case 2: return isEither(sequence.charAt(0), sequence.charAt(1)); default: // TODO(lowasser): is it potentially worth just going ahead and building a precomputed // matcher? return new AnyOf(sequence); } } /** * Returns a {@code char} matcher that matches any BMP character not present in the given * character sequence. Returns a bogus matcher if the sequence contains supplementary characters. */ public static CharMatcher noneOf(CharSequence sequence) { return anyOf(sequence).negate(); } /** * Returns a {@code char} matcher that matches any character in a given BMP range (both endpoints * are inclusive). For example, to match any lowercase letter of the English alphabet, use {@code * CharMatcher.inRange('a', 'z')}. * * @throws IllegalArgumentException if {@code endInclusive < startInclusive} */ public static CharMatcher inRange(final char startInclusive, final char endInclusive) { return new InRange(startInclusive, endInclusive); } /** * Returns a matcher with identical behavior to the given {@link Character}-based predicate, but * which operates on primitive {@code char} instances instead. */ public static CharMatcher forPredicate(final Predicate<? super Character> predicate) { return predicate instanceof CharMatcher ? (CharMatcher) predicate : new ForPredicate(predicate); } // Constructors /** * Constructor for use by subclasses. When subclassing, you may want to override {@code * toString()} to provide a useful description. */ protected CharMatcher() {} // Abstract methods /** Determines a true or false value for the given character. */ public abstract boolean matches(char c); // Non-static factories /** Returns a matcher that matches any character not matched by this matcher. */ // @Override under Java 8 but not under Java 7 @Override public CharMatcher negate() { return new Negated(this); } /** * Returns a matcher that matches any character matched by both this matcher and {@code other}. */ public CharMatcher and(CharMatcher other) { return new And(this, other); } /** * Returns a matcher that matches any character matched by either this matcher or {@code other}. */ public CharMatcher or(CharMatcher other) { return new Or(this, other); } /** * Returns a {@code char} matcher functionally equivalent to this one, but which may be faster to * query than the original; your mileage may vary. Precomputation takes time and is likely to be * worthwhile only if the precomputed matcher is queried many thousands of times. * * <p>This method has no effect (returns {@code this}) when called in GWT: it's unclear whether a * precomputed matcher is faster, but it certainly consumes more memory, which doesn't seem like a * worthwhile tradeoff in a browser. */ public CharMatcher precomputed() { return Platform.precomputeCharMatcher(this); } private static final int DISTINCT_CHARS = Character.MAX_VALUE - Character.MIN_VALUE + 1; /** * This is the actual implementation of {@link #precomputed}, but we bounce calls through a method * on {@link Platform} so that we can have different behavior in GWT. * * <p>This implementation tries to be smart in a number of ways. It recognizes cases where the * negation is cheaper to precompute than the matcher itself; it tries to build small hash tables * for matchers that only match a few characters, and so on. In the worst-case scenario, it * constructs an eight-kilobyte bit array and queries that. In many situations this produces a * matcher which is faster to query than the original. */ @GwtIncompatible // SmallCharMatcher CharMatcher precomputedInternal() { final BitSet table = new BitSet(); setBits(table); int totalCharacters = table.cardinality(); if (totalCharacters * 2 <= DISTINCT_CHARS) { return precomputedPositive(totalCharacters, table, toString()); } else { // TODO(lowasser): is it worth it to worry about the last character of large matchers? table.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1); int negatedCharacters = DISTINCT_CHARS - totalCharacters; String suffix = ".negate()"; final String description = toString(); String negatedDescription = description.endsWith(suffix) ? description.substring(0, description.length() - suffix.length()) : description + suffix; return new NegatedFastMatcher( precomputedPositive(negatedCharacters, table, negatedDescription)) { @Override public String toString() { return description; } }; } } /** * Helper method for {@link #precomputedInternal} that doesn't test if the negation is cheaper. */ @GwtIncompatible // SmallCharMatcher private static CharMatcher precomputedPositive( int totalCharacters, BitSet table, String description) { switch (totalCharacters) { case 0: return none(); case 1: return is((char) table.nextSetBit(0)); case 2: char c1 = (char) table.nextSetBit(0); char c2 = (char) table.nextSetBit(c1 + 1); return isEither(c1, c2); default: return isSmall(totalCharacters, table.length()) ? SmallCharMatcher.from(table, description) : new BitSetMatcher(table, description); } } @GwtIncompatible // SmallCharMatcher private static boolean isSmall(int totalCharacters, int tableLength) { return totalCharacters <= SmallCharMatcher.MAX_SIZE && tableLength > (totalCharacters * 4 * Character.SIZE); // err on the side of BitSetMatcher } /** Sets bits in {@code table} matched by this matcher. */ @GwtIncompatible // used only from other GwtIncompatible code void setBits(BitSet table) { for (int c = Character.MAX_VALUE; c >= Character.MIN_VALUE; c--) { if (matches((char) c)) { table.set(c); } } } // Text processing routines /** * Returns {@code true} if a character sequence contains at least one matching BMP character. * Equivalent to {@code !matchesNoneOf(sequence)}. * * <p>The default implementation iterates over the sequence, invoking {@link #matches} for each * character, until this returns {@code true} or the end is reached. * * @param sequence the character sequence to examine, possibly empty * @return {@code true} if this matcher matches at least one character in the sequence * @since 8.0 */ public boolean matchesAnyOf(CharSequence sequence) { return !matchesNoneOf(sequence); } /** * Returns {@code true} if a character sequence contains only matching BMP characters. * * <p>The default implementation iterates over the sequence, invoking {@link #matches} for each * character, until this returns {@code false} or the end is reached. * * @param sequence the character sequence to examine, possibly empty * @return {@code true} if this matcher matches every character in the sequence, including when * the sequence is empty */ public boolean matchesAllOf(CharSequence sequence) { for (int i = sequence.length() - 1; i >= 0; i--) { if (!matches(sequence.charAt(i))) { return false; } } return true; } /** * Returns {@code true} if a character sequence contains no matching BMP characters. Equivalent to * {@code !matchesAnyOf(sequence)}. * * <p>The default implementation iterates over the sequence, invoking {@link #matches} for each * character, until this returns {@code true} or the end is reached. * * @param sequence the character sequence to examine, possibly empty * @return {@code true} if this matcher matches no characters in the sequence, including when the * sequence is empty */ public boolean matchesNoneOf(CharSequence sequence) { return indexIn(sequence) == -1; } /** * Returns the index of the first matching BMP character in a character sequence, or {@code -1} if * no matching character is present. * * <p>The default implementation iterates over the sequence in forward order calling {@link * #matches} for each character. * * @param sequence the character sequence to examine from the beginning * @return an index, or {@code -1} if no character matches */ public int indexIn(CharSequence sequence) { return indexIn(sequence, 0); } /** * Returns the index of the first matching BMP character in a character sequence, starting from a * given position, or {@code -1} if no character matches after that position. * * <p>The default implementation iterates over the sequence in forward order, beginning at {@code * start}, calling {@link #matches} for each character. * * @param sequence the character sequence to examine * @param start the first index to examine; must be nonnegative and no greater than {@code * sequence.length()} * @return the index of the first matching character, guaranteed to be no less than {@code start}, * or {@code -1} if no character matches * @throws IndexOutOfBoundsException if start is negative or greater than {@code * sequence.length()} */ public int indexIn(CharSequence sequence, int start) { int length = sequence.length(); checkPositionIndex(start, length); for (int i = start; i < length; i++) { if (matches(sequence.charAt(i))) { return i; } } return -1; } /** * Returns the index of the last matching BMP character in a character sequence, or {@code -1} if * no matching character is present. * * <p>The default implementation iterates over the sequence in reverse order calling {@link * #matches} for each character. * * @param sequence the character sequence to examine from the end * @return an index, or {@code -1} if no character matches */ public int lastIndexIn(CharSequence sequence) { for (int i = sequence.length() - 1; i >= 0; i--) { if (matches(sequence.charAt(i))) { return i; } } return -1; } /** * Returns the number of matching {@code char}s found in a character sequence. * * <p>Counts 2 per supplementary character, such as for {@link #whitespace}().{@link #negate}(). */ public int countIn(CharSequence sequence) { int count = 0; for (int i = 0; i < sequence.length(); i++) { if (matches(sequence.charAt(i))) { count++; } } return count; } /** * Returns a string containing all non-matching characters of a character sequence, in order. For * example: * * <pre>{@code * CharMatcher.is('a').removeFrom("bazaar") * }</pre> * * ... returns {@code "bzr"}. */ public String removeFrom(CharSequence sequence) { String string = sequence.toString(); int pos = indexIn(string); if (pos == -1) { return string; } char[] chars = string.toCharArray(); int spread = 1; // This unusual loop comes from extensive benchmarking OUT: while (true) { pos++; while (true) { if (pos == chars.length) { break OUT; } if (matches(chars[pos])) { break; } chars[pos - spread] = chars[pos]; pos++; } spread++; } return new String(chars, 0, pos - spread); } /** * Returns a string containing all matching BMP characters of a character sequence, in order. For * example: * * <pre>{@code * CharMatcher.is('a').retainFrom("bazaar") * }</pre> * * ... returns {@code "aaa"}. */ public String retainFrom(CharSequence sequence) { return negate().removeFrom(sequence); } /** * Returns a string copy of the input character sequence, with each matching BMP character * replaced by a given replacement character. For example: * * <pre>{@code * CharMatcher.is('a').replaceFrom("radar", 'o') * }</pre> * * ... returns {@code "rodor"}. * * <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching * character, then iterates the remainder of the sequence calling {@link #matches(char)} for each * character. * * @param sequence the character sequence to replace matching characters in * @param replacement the character to append to the result string in place of each matching * character in {@code sequence} * @return the new string */ public String replaceFrom(CharSequence sequence, char replacement) { String string = sequence.toString(); int pos = indexIn(string); if (pos == -1) { return string; } char[] chars = string.toCharArray(); chars[pos] = replacement; for (int i = pos + 1; i < chars.length; i++) { if (matches(chars[i])) { chars[i] = replacement; } } return new String(chars); } /** * Returns a string copy of the input character sequence, with each matching BMP character * replaced by a given replacement sequence. For example: * * <pre>{@code * CharMatcher.is('a').replaceFrom("yaha", "oo") * }</pre> * * ... returns {@code "yoohoo"}. * * <p><b>Note:</b> If the replacement is a fixed string with only one character, you are better * off calling {@link #replaceFrom(CharSequence, char)} directly. * * @param sequence the character sequence to replace matching characters in * @param replacement the characters to append to the result string in place of each matching * character in {@code sequence} * @return the new string */ public String replaceFrom(CharSequence sequence, CharSequence replacement) { int replacementLen = replacement.length(); if (replacementLen == 0) { return removeFrom(sequence); } if (replacementLen == 1) { return replaceFrom(sequence, replacement.charAt(0)); } String string = sequence.toString(); int pos = indexIn(string); if (pos == -1) { return string; } int len = string.length(); StringBuilder buf = new StringBuilder((len * 3 / 2) + 16); int oldpos = 0; do { buf.append(string, oldpos, pos); buf.append(replacement); oldpos = pos + 1; pos = indexIn(string, oldpos); } while (pos != -1); buf.append(string, oldpos, len); return buf.toString(); } /** * Returns a substring of the input character sequence that omits all matching BMP characters from * the beginning and from the end of the string. For example: * * <pre>{@code * CharMatcher.anyOf("ab").trimFrom("abacatbab") * }</pre> * * ... returns {@code "cat"}. * * <p>Note that: * * <pre>{@code * CharMatcher.inRange('\0', ' ').trimFrom(str) * }</pre> * * ... is equivalent to {@link String#trim()}. */ public String trimFrom(CharSequence sequence) { int len = sequence.length(); int first; int last; for (first = 0; first < len; first++) { if (!matches(sequence.charAt(first))) { break; } } for (last = len - 1; last > first; last--) { if (!matches(sequence.charAt(last))) { break; } } return sequence.subSequence(first, last + 1).toString(); } /** * Returns a substring of the input character sequence that omits all matching BMP characters from * the beginning of the string. For example: * * <pre>{@code * CharMatcher.anyOf("ab").trimLeadingFrom("abacatbab") * }</pre> * * ... returns {@code "catbab"}. */ public String trimLeadingFrom(CharSequence sequence) { int len = sequence.length(); for (int first = 0; first < len; first++) { if (!matches(sequence.charAt(first))) { return sequence.subSequence(first, len).toString(); } } return ""; } /** * Returns a substring of the input character sequence that omits all matching BMP characters from * the end of the string. For example: * * <pre>{@code * CharMatcher.anyOf("ab").trimTrailingFrom("abacatbab") * }</pre> * * ... returns {@code "abacat"}. */ public String trimTrailingFrom(CharSequence sequence) { int len = sequence.length(); for (int last = len - 1; last >= 0; last--) { if (!matches(sequence.charAt(last))) { return sequence.subSequence(0, last + 1).toString(); } } return ""; } /** * Returns a string copy of the input character sequence, with each group of consecutive matching * BMP characters replaced by a single replacement character. For example: * * <pre>{@code * CharMatcher.anyOf("eko").collapseFrom("bookkeeper", '-') * }</pre> * * ... returns {@code "b-p-r"}. * * <p>The default implementation uses {@link #indexIn(CharSequence)} to find the first matching * character, then iterates the remainder of the sequence calling {@link #matches(char)} for each * character. * * @param sequence the character sequence to replace matching groups of characters in * @param replacement the character to append to the result string in place of each group of * matching characters in {@code sequence} * @return the new string */ public String collapseFrom(CharSequence sequence, char replacement) { // This implementation avoids unnecessary allocation. int len = sequence.length(); for (int i = 0; i < len; i++) { char c = sequence.charAt(i); if (matches(c)) { if (c == replacement && (i == len - 1 || !matches(sequence.charAt(i + 1)))) { // a no-op replacement i++; } else { StringBuilder builder = new StringBuilder(len).append(sequence, 0, i).append(replacement); return finishCollapseFrom(sequence, i + 1, len, replacement, builder, true); } } } // no replacement needed return sequence.toString(); } /** * Collapses groups of matching characters exactly as {@link #collapseFrom} does, except that * groups of matching BMP characters at the start or end of the sequence are removed without * replacement. */ public String trimAndCollapseFrom(CharSequence sequence, char replacement) { // This implementation avoids unnecessary allocation. int len = sequence.length(); int first = 0; int last = len - 1; while (first < len && matches(sequence.charAt(first))) { first++; } while (last > first && matches(sequence.charAt(last))) { last--; } return (first == 0 && last == len - 1) ? collapseFrom(sequence, replacement) : finishCollapseFrom( sequence, first, last + 1, replacement, new StringBuilder(last + 1 - first), false); } private String finishCollapseFrom( CharSequence sequence, int start, int end, char replacement, StringBuilder builder, boolean inMatchingGroup) { for (int i = start; i < end; i++) { char c = sequence.charAt(i); if (matches(c)) { if (!inMatchingGroup) { builder.append(replacement); inMatchingGroup = true; } } else { builder.append(c); inMatchingGroup = false; } } return builder.toString(); } /** * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #matches} * instead. */ @Deprecated @Override public boolean apply(Character character) { return matches(character); } /** * Returns a string representation of this {@code CharMatcher}, such as {@code * CharMatcher.or(WHITESPACE, JAVA_DIGIT)}. */ @Override public String toString() { return super.toString(); } /** * Returns the Java Unicode escape sequence for the given {@code char}, in the form "\u12AB" where * "12AB" is the four hexadecimal digits representing the 16-bit code unit. */ private static String showCharacter(char c) { String hex = "0123456789ABCDEF"; char[] tmp = {'\\', 'u', '\0', '\0', '\0', '\0'}; for (int i = 0; i < 4; i++) { tmp[5 - i] = hex.charAt(c & 0xF); c = (char) (c >> 4); } return String.copyValueOf(tmp); } // Fast matchers /** A matcher for which precomputation will not yield any significant benefit. */ abstract static class FastMatcher extends CharMatcher { @Override public final CharMatcher precomputed() { return this; } @Override public CharMatcher negate() { return new NegatedFastMatcher(this); } } /** {@link FastMatcher} which overrides {@code toString()} with a custom name. */ abstract static class NamedFastMatcher extends FastMatcher { private final String description; NamedFastMatcher(String description) { this.description = checkNotNull(description); } @Override public final String toString() { return description; } } /** Negation of a {@link FastMatcher}. */ private static class NegatedFastMatcher extends Negated { NegatedFastMatcher(CharMatcher original) { super(original); } @Override public final CharMatcher precomputed() { return this; } } /** Fast matcher using a {@link BitSet} table of matching characters. */ @GwtIncompatible // used only from other GwtIncompatible code private static final class BitSetMatcher extends NamedFastMatcher { private final BitSet table; private BitSetMatcher(BitSet table, String description) { super(description); if (table.length() + Long.SIZE < table.size()) { table = (BitSet) table.clone(); // If only we could actually call BitSet.trimToSize() ourselves... } this.table = table; } @Override public boolean matches(char c) { return table.get(c); } @Override void setBits(BitSet bitSet) { bitSet.or(table); } } // Static constant implementation classes /** Implementation of {@link #any()}. */ private static final class Any extends NamedFastMatcher { static final CharMatcher INSTANCE = new Any(); private Any() { super("CharMatcher.any()"); } @Override public boolean matches(char c) { return true; } @Override public int indexIn(CharSequence sequence) { return (sequence.length() == 0) ? -1 : 0; } @Override public int indexIn(CharSequence sequence, int start) { int length = sequence.length(); checkPositionIndex(start, length); return (start == length) ? -1 : start; } @Override public int lastIndexIn(CharSequence sequence) { return sequence.length() - 1; } @Override public boolean matchesAllOf(CharSequence sequence) { checkNotNull(sequence); return true; } @Override public boolean matchesNoneOf(CharSequence sequence) { return sequence.length() == 0; } @Override public String removeFrom(CharSequence sequence) { checkNotNull(sequence); return ""; } @Override public String replaceFrom(CharSequence sequence, char replacement) { char[] array = new char[sequence.length()]; Arrays.fill(array, replacement); return new String(array); } @Override public String replaceFrom(CharSequence sequence, CharSequence replacement) { StringBuilder result = new StringBuilder(sequence.length() * replacement.length()); for (int i = 0; i < sequence.length(); i++) { result.append(replacement); } return result.toString(); } @Override public String collapseFrom(CharSequence sequence, char replacement) { return (sequence.length() == 0) ? "" : String.valueOf(replacement); } @Override public String trimFrom(CharSequence sequence) { checkNotNull(sequence); return ""; } @Override public int countIn(CharSequence sequence) { return sequence.length(); } @Override public CharMatcher and(CharMatcher other) { return checkNotNull(other); } @Override public CharMatcher or(CharMatcher other) { checkNotNull(other); return this; } @Override public CharMatcher negate() { return none(); } } /** Implementation of {@link #none()}. */ private static final class None extends NamedFastMatcher { static final CharMatcher INSTANCE = new None(); private None() { super("CharMatcher.none()"); } @Override public boolean matches(char c) { return false; } @Override public int indexIn(CharSequence sequence) { checkNotNull(sequence); return -1; } @Override public int indexIn(CharSequence sequence, int start) { int length = sequence.length(); checkPositionIndex(start, length); return -1; } @Override public int lastIndexIn(CharSequence sequence) { checkNotNull(sequence); return -1; } @Override public boolean matchesAllOf(CharSequence sequence) { return sequence.length() == 0; } @Override public boolean matchesNoneOf(CharSequence sequence) { checkNotNull(sequence); return true; } @Override public String removeFrom(CharSequence sequence) { return sequence.toString(); } @Override public String replaceFrom(CharSequence sequence, char replacement) { return sequence.toString(); } @Override public String replaceFrom(CharSequence sequence, CharSequence replacement) { checkNotNull(replacement); return sequence.toString(); } @Override public String collapseFrom(CharSequence sequence, char replacement) { return sequence.toString(); } @Override public String trimFrom(CharSequence sequence) { return sequence.toString(); } @Override public String trimLeadingFrom(CharSequence sequence) { return sequence.toString(); } @Override public String trimTrailingFrom(CharSequence sequence) { return sequence.toString(); } @Override public int countIn(CharSequence sequence) { checkNotNull(sequence); return 0; } @Override public CharMatcher and(CharMatcher other) { checkNotNull(other); return this; } @Override public CharMatcher or(CharMatcher other) { return checkNotNull(other); } @Override public CharMatcher negate() { return any(); } } /** Implementation of {@link #whitespace()}. */ @VisibleForTesting static final class Whitespace extends NamedFastMatcher { // TABLE is a precomputed hashset of whitespace characters. MULTIPLIER serves as a hash function // whose key property is that it maps 25 characters into the 32-slot table without collision. // Basically this is an opportunistic fast implementation as opposed to "good code". For most // other use-cases, the reduction in readability isn't worth it. static final String TABLE = "\u2002\u3000\r\u0085\u200A\u2005\u2000\u3000" + "\u2029\u000B\u3000\u2008\u2003\u205F\u3000\u1680" + "\u0009\u0020\u2006\u2001\u202F\u00A0\u000C\u2009" + "\u3000\u2004\u3000\u3000\u2028\n\u2007\u3000"; static final int MULTIPLIER = 1682554634; static final int SHIFT = Integer.numberOfLeadingZeros(TABLE.length() - 1); static final CharMatcher INSTANCE = new Whitespace(); Whitespace() { super("CharMatcher.whitespace()"); } @Override public boolean matches(char c) { return TABLE.charAt((MULTIPLIER * c) >>> SHIFT) == c; } @GwtIncompatible // used only from other GwtIncompatible code @Override void setBits(BitSet table) { for (int i = 0; i < TABLE.length(); i++) { table.set(TABLE.charAt(i)); } } } /** Implementation of {@link #breakingWhitespace()}. */ private static final class BreakingWhitespace extends CharMatcher { static final CharMatcher INSTANCE = new BreakingWhitespace(); @Override public boolean matches(char c) { switch (c) { case '\t': case '\n': case '\013': case '\f': case '\r': case ' ': case '\u0085': case '\u1680': case '\u2028': case '\u2029': case '\u205f': case '\u3000': return true; case '\u2007': return false; default: return c >= '\u2000' && c <= '\u200a'; } } @Override public String toString() { return "CharMatcher.breakingWhitespace()"; } } /** Implementation of {@link #ascii()}. */ private static final class Ascii extends NamedFastMatcher { static final CharMatcher INSTANCE = new Ascii(); Ascii() { super("CharMatcher.ascii()"); } @Override public boolean matches(char c) { return c <= '\u007f'; } } /** Implementation that matches characters that fall within multiple ranges. */ private static class RangesMatcher extends CharMatcher { private final String description; private final char[] rangeStarts; private final char[] rangeEnds; RangesMatcher(String description, char[] rangeStarts, char[] rangeEnds) { this.description = description; this.rangeStarts = rangeStarts; this.rangeEnds = rangeEnds; checkArgument(rangeStarts.length == rangeEnds.length); for (int i = 0; i < rangeStarts.length; i++) { checkArgument(rangeStarts[i] <= rangeEnds[i]); if (i + 1 < rangeStarts.length) { checkArgument(rangeEnds[i] < rangeStarts[i + 1]); } } } @Override public boolean matches(char c) { int index = Arrays.binarySearch(rangeStarts, c); if (index >= 0) { return true; } else { index = ~index - 1; return index >= 0 && c <= rangeEnds[index]; } } @Override public String toString() { return description; } } /** Implementation of {@link #digit()}. */ private static final class Digit extends RangesMatcher { // Plug the following UnicodeSet pattern into // https://unicode.org/cldr/utility/list-unicodeset.jsp // [[:Nd:]&[:nv=0:]&[\u0000-\uFFFF]] // and get the zeroes from there. // Must be in ascending order. private static final String ZEROES = "0\u0660\u06f0\u07c0\u0966\u09e6\u0a66\u0ae6\u0b66\u0be6\u0c66\u0ce6\u0d66\u0de6" + "\u0e50\u0ed0\u0f20\u1040\u1090\u17e0\u1810\u1946\u19d0\u1a80\u1a90\u1b50\u1bb0" + "\u1c40\u1c50\ua620\ua8d0\ua900\ua9d0\ua9f0\uaa50\uabf0\uff10"; private static char[] zeroes() { return ZEROES.toCharArray(); } private static char[] nines() { char[] nines = new char[ZEROES.length()]; for (int i = 0; i < ZEROES.length(); i++) { nines[i] = (char) (ZEROES.charAt(i) + 9); } return nines; } static final CharMatcher INSTANCE = new Digit(); private Digit() { super("CharMatcher.digit()", zeroes(), nines()); } } /** Implementation of {@link #javaDigit()}. */ private static final class JavaDigit extends CharMatcher { static final CharMatcher INSTANCE = new JavaDigit(); @Override public boolean matches(char c) { return Character.isDigit(c); } @Override public String toString() { return "CharMatcher.javaDigit()"; } } /** Implementation of {@link #javaLetter()}. */ private static final class JavaLetter extends CharMatcher { static final CharMatcher INSTANCE = new JavaLetter(); @Override public boolean matches(char c) { return Character.isLetter(c); } @Override public String toString() { return "CharMatcher.javaLetter()"; } } /** Implementation of {@link #javaLetterOrDigit()}. */ private static final class JavaLetterOrDigit extends CharMatcher { static final CharMatcher INSTANCE = new JavaLetterOrDigit(); @Override public boolean matches(char c) { return Character.isLetterOrDigit(c); } @Override public String toString() { return "CharMatcher.javaLetterOrDigit()"; } } /** Implementation of {@link #javaUpperCase()}. */ private static final class JavaUpperCase extends CharMatcher { static final CharMatcher INSTANCE = new JavaUpperCase(); @Override public boolean matches(char c) { return Character.isUpperCase(c); } @Override public String toString() { return "CharMatcher.javaUpperCase()"; } } /** Implementation of {@link #javaLowerCase()}. */ private static final class JavaLowerCase extends CharMatcher { static final CharMatcher INSTANCE = new JavaLowerCase(); @Override public boolean matches(char c) { return Character.isLowerCase(c); } @Override public String toString() { return "CharMatcher.javaLowerCase()"; } } /** Implementation of {@link #javaIsoControl()}. */ private static final class JavaIsoControl extends NamedFastMatcher { static final CharMatcher INSTANCE = new JavaIsoControl(); private JavaIsoControl() { super("CharMatcher.javaIsoControl()"); } @Override public boolean matches(char c) { return c <= '\u001f' || (c >= '\u007f' && c <= '\u009f'); } } /** Implementation of {@link #invisible()}. */ private static final class Invisible extends RangesMatcher { // Plug the following UnicodeSet pattern into // https://unicode.org/cldr/utility/list-unicodeset.jsp // [[[:Zs:][:Zl:][:Zp:][:Cc:][:Cf:][:Cs:][:Co:]]&[\u0000-\uFFFF]] // with the "Abbreviate" option, and get the ranges from there. private static final String RANGE_STARTS = "\u0000\u007f\u00ad\u0600\u061c\u06dd\u070f\u0890\u08e2\u1680\u180e\u2000\u2028\u205f\u2066" + "\u3000\ud800\ufeff\ufff9"; private static final String RANGE_ENDS = // inclusive ends "\u0020\u00a0\u00ad\u0605\u061c\u06dd\u070f\u0891\u08e2\u1680\u180e\u200f\u202f\u2064\u206f" + "\u3000\uf8ff\ufeff\ufffb"; static final CharMatcher INSTANCE = new Invisible(); private Invisible() { super("CharMatcher.invisible()", RANGE_STARTS.toCharArray(), RANGE_ENDS.toCharArray()); } } /** Implementation of {@link #singleWidth()}. */ private static final class SingleWidth extends RangesMatcher { static final CharMatcher INSTANCE = new SingleWidth(); private SingleWidth() { super( "CharMatcher.singleWidth()", "\u0000\u05be\u05d0\u05f3\u0600\u0750\u0e00\u1e00\u2100\ufb50\ufe70\uff61".toCharArray(), "\u04f9\u05be\u05ea\u05f4\u06ff\u077f\u0e7f\u20af\u213a\ufdff\ufeff\uffdc".toCharArray()); } } // Non-static factory implementation classes /** Implementation of {@link #negate()}. */ private static class Negated extends CharMatcher { final CharMatcher original; Negated(CharMatcher original) { this.original = checkNotNull(original); } @Override public boolean matches(char c) { return !original.matches(c); } @Override public boolean matchesAllOf(CharSequence sequence) { return original.matchesNoneOf(sequence); } @Override public boolean matchesNoneOf(CharSequence sequence) { return original.matchesAllOf(sequence); } @Override public int countIn(CharSequence sequence) { return sequence.length() - original.countIn(sequence); } @GwtIncompatible // used only from other GwtIncompatible code @Override void setBits(BitSet table) { BitSet tmp = new BitSet(); original.setBits(tmp); tmp.flip(Character.MIN_VALUE, Character.MAX_VALUE + 1); table.or(tmp); } @Override public CharMatcher negate() { return original; } @Override public String toString() { return original + ".negate()"; } } /** Implementation of {@link #and(CharMatcher)}. */ private static final class And extends CharMatcher { final CharMatcher first; final CharMatcher second; And(CharMatcher a, CharMatcher b) { first = checkNotNull(a); second = checkNotNull(b); } @Override public boolean matches(char c) { return first.matches(c) && second.matches(c); } @GwtIncompatible // used only from other GwtIncompatible code @Override void setBits(BitSet table) { BitSet tmp1 = new BitSet(); first.setBits(tmp1); BitSet tmp2 = new BitSet(); second.setBits(tmp2); tmp1.and(tmp2); table.or(tmp1); } @Override public String toString() { return "CharMatcher.and(" + first + ", " + second + ")"; } } /** Implementation of {@link #or(CharMatcher)}. */ private static final class Or extends CharMatcher { final CharMatcher first; final CharMatcher second; Or(CharMatcher a, CharMatcher b) { first = checkNotNull(a); second = checkNotNull(b); } @GwtIncompatible // used only from other GwtIncompatible code @Override void setBits(BitSet table) { first.setBits(table); second.setBits(table); } @Override public boolean matches(char c) { return first.matches(c) || second.matches(c); } @Override public String toString() { return "CharMatcher.or(" + first + ", " + second + ")"; } } // Static factory implementations /** Implementation of {@link #is(char)}. */ private static final class Is extends FastMatcher { private final char match; Is(char match) { this.match = match; } @Override public boolean matches(char c) { return c == match; } @Override public String replaceFrom(CharSequence sequence, char replacement) { return sequence.toString().replace(match, replacement); } @Override public CharMatcher and(CharMatcher other) { return other.matches(match) ? this : none(); } @Override public CharMatcher or(CharMatcher other) { return other.matches(match) ? other : super.or(other); } @Override public CharMatcher negate() { return isNot(match); } @GwtIncompatible // used only from other GwtIncompatible code @Override void setBits(BitSet table) { table.set(match); } @Override public String toString() { return "CharMatcher.is('" + showCharacter(match) + "')"; } } /** Implementation of {@link #isNot(char)}. */ private static final class IsNot extends FastMatcher { private final char match; IsNot(char match) { this.match = match; } @Override public boolean matches(char c) { return c != match; } @Override public CharMatcher and(CharMatcher other) { return other.matches(match) ? super.and(other) : other; } @Override public CharMatcher or(CharMatcher other) { return other.matches(match) ? any() : this; } @GwtIncompatible // used only from other GwtIncompatible code @Override void setBits(BitSet table) { table.set(0, match); table.set(match + 1, Character.MAX_VALUE + 1); } @Override public CharMatcher negate() { return is(match); } @Override public String toString() { return "CharMatcher.isNot('" + showCharacter(match) + "')"; } } private static CharMatcher.IsEither isEither(char c1, char c2) { return new CharMatcher.IsEither(c1, c2); } /** Implementation of {@link #anyOf(CharSequence)} for exactly two characters. */ private static final class IsEither extends FastMatcher { private final char match1; private final char match2; IsEither(char match1, char match2) { this.match1 = match1; this.match2 = match2; } @Override public boolean matches(char c) { return c == match1 || c == match2; } @GwtIncompatible // used only from other GwtIncompatible code @Override void setBits(BitSet table) { table.set(match1); table.set(match2); } @Override public String toString() { return "CharMatcher.anyOf(\"" + showCharacter(match1) + showCharacter(match2) + "\")"; } } /** Implementation of {@link #anyOf(CharSequence)} for three or more characters. */ private static final class AnyOf extends CharMatcher { private final char[] chars; public AnyOf(CharSequence chars) { this.chars = chars.toString().toCharArray(); Arrays.sort(this.chars); } @Override public boolean matches(char c) { return Arrays.binarySearch(chars, c) >= 0; } @Override @GwtIncompatible // used only from other GwtIncompatible code void setBits(BitSet table) { for (char c : chars) { table.set(c); } } @Override public String toString() { StringBuilder description = new StringBuilder("CharMatcher.anyOf(\""); for (char c : chars) { description.append(showCharacter(c)); } description.append("\")"); return description.toString(); } } /** Implementation of {@link #inRange(char, char)}. */ private static final class InRange extends FastMatcher { private final char startInclusive; private final char endInclusive; InRange(char startInclusive, char endInclusive) { checkArgument(endInclusive >= startInclusive); this.startInclusive = startInclusive; this.endInclusive = endInclusive; } @Override public boolean matches(char c) { return startInclusive <= c && c <= endInclusive; } @GwtIncompatible // used only from other GwtIncompatible code @Override void setBits(BitSet table) { table.set(startInclusive, endInclusive + 1); } @Override public String toString() { return "CharMatcher.inRange('" + showCharacter(startInclusive) + "', '" + showCharacter(endInclusive) + "')"; } } /** Implementation of {@link #forPredicate(Predicate)}. */ private static final class ForPredicate extends CharMatcher { private final Predicate<? super Character> predicate; ForPredicate(Predicate<? super Character> predicate) { this.predicate = checkNotNull(predicate); } @Override public boolean matches(char c) { return predicate.apply(c); } @SuppressWarnings("deprecation") // intentional; deprecation is for callers primarily @Override public boolean apply(Character character) { return predicate.apply(checkNotNull(character)); } @Override public String toString() { return "CharMatcher.forPredicate(" + predicate + ")"; } } }
google/guava
guava/src/com/google/common/base/CharMatcher.java
352
/* * 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.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Supplier; import com.google.common.collect.Table.Cell; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.Spliterator; import java.util.function.BinaryOperator; import java.util.stream.Collector; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Provides static methods that involve a {@code Table}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#tables">{@code Tables}</a>. * * @author Jared Levy * @author Louis Wasserman * @since 7.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Tables { private Tables() {} /** * Returns a {@link Collector} that accumulates elements into a {@code Table} created using the * specified supplier, whose cells are generated by applying the provided mapping functions to the * input elements. Cells are inserted into the generated {@code Table} in encounter order. * * <p>If multiple input elements map to the same row and column, an {@code IllegalStateException} * is thrown when the collection operation is performed. * * <p>To collect to an {@link ImmutableTable}, use {@link ImmutableTable#toImmutableTable}. * * @since 21.0 */ public static < T extends @Nullable Object, R extends @Nullable Object, C extends @Nullable Object, V, I extends Table<R, C, V>> Collector<T, ?, I> toTable( java.util.function.Function<? super T, ? extends R> rowFunction, java.util.function.Function<? super T, ? extends C> columnFunction, java.util.function.Function<? super T, ? extends V> valueFunction, java.util.function.Supplier<I> tableSupplier) { return TableCollectors.<T, R, C, V, I>toTable( rowFunction, columnFunction, valueFunction, tableSupplier); } /** * Returns a {@link Collector} that accumulates elements into a {@code Table} created using the * specified supplier, whose cells are generated by applying the provided mapping functions to the * input elements. Cells are inserted into the generated {@code Table} in encounter order. * * <p>If multiple input elements map to the same row and column, the specified merging function is * used to combine the values. Like {@link * java.util.stream.Collectors#toMap(java.util.function.Function, java.util.function.Function, * BinaryOperator, java.util.function.Supplier)}, this Collector throws a {@code * NullPointerException} on null values returned from {@code valueFunction}, and treats nulls * returned from {@code mergeFunction} as removals of that row/column pair. * * @since 21.0 */ public static < T extends @Nullable Object, R extends @Nullable Object, C extends @Nullable Object, V, I extends Table<R, C, V>> Collector<T, ?, I> toTable( java.util.function.Function<? super T, ? extends R> rowFunction, java.util.function.Function<? super T, ? extends C> columnFunction, java.util.function.Function<? super T, ? extends V> valueFunction, BinaryOperator<V> mergeFunction, java.util.function.Supplier<I> tableSupplier) { return TableCollectors.<T, R, C, V, I>toTable( rowFunction, columnFunction, valueFunction, mergeFunction, tableSupplier); } /** * Returns an immutable cell with the specified row key, column key, and value. * * <p>The returned cell is serializable. * * @param rowKey the row key to be associated with the returned cell * @param columnKey the column key to be associated with the returned cell * @param value the value to be associated with the returned cell */ public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Cell<R, C, V> immutableCell( @ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value) { return new ImmutableCell<>(rowKey, columnKey, value); } static final class ImmutableCell< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> extends AbstractCell<R, C, V> implements Serializable { @ParametricNullness private final R rowKey; @ParametricNullness private final C columnKey; @ParametricNullness private final V value; ImmutableCell( @ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value) { this.rowKey = rowKey; this.columnKey = columnKey; this.value = value; } @Override @ParametricNullness public R getRowKey() { return rowKey; } @Override @ParametricNullness public C getColumnKey() { return columnKey; } @Override @ParametricNullness public V getValue() { return value; } private static final long serialVersionUID = 0; } abstract static class AbstractCell< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> implements Cell<R, C, V> { // needed for serialization AbstractCell() {} @Override public boolean equals(@CheckForNull Object obj) { if (obj == this) { return true; } if (obj instanceof Cell) { Cell<?, ?, ?> other = (Cell<?, ?, ?>) obj; return Objects.equal(getRowKey(), other.getRowKey()) && Objects.equal(getColumnKey(), other.getColumnKey()) && Objects.equal(getValue(), other.getValue()); } return false; } @Override public int hashCode() { return Objects.hashCode(getRowKey(), getColumnKey(), getValue()); } @Override public String toString() { return "(" + getRowKey() + "," + getColumnKey() + ")=" + getValue(); } } /** * Creates a transposed view of a given table that flips its row and column keys. In other words, * calling {@code get(columnKey, rowKey)} on the generated table always returns the same value as * calling {@code get(rowKey, columnKey)} on the original table. Updating the original table * changes the contents of the transposed table and vice versa. * * <p>The returned table supports update operations as long as the input table supports the * analogous operation with swapped rows and columns. For example, in a {@link HashBasedTable} * instance, {@code rowKeySet().iterator()} supports {@code remove()} but {@code * columnKeySet().iterator()} doesn't. With a transposed {@link HashBasedTable}, it's the other * way around. */ public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Table<C, R, V> transpose(Table<R, C, V> table) { return (table instanceof TransposeTable) ? ((TransposeTable<R, C, V>) table).original : new TransposeTable<C, R, V>(table); } private static class TransposeTable< C extends @Nullable Object, R extends @Nullable Object, V extends @Nullable Object> extends AbstractTable<C, R, V> { final Table<R, C, V> original; TransposeTable(Table<R, C, V> original) { this.original = checkNotNull(original); } @Override public void clear() { original.clear(); } @Override public Map<C, V> column(@ParametricNullness R columnKey) { return original.row(columnKey); } @Override public Set<R> columnKeySet() { return original.rowKeySet(); } @Override public Map<R, Map<C, V>> columnMap() { return original.rowMap(); } @Override public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return original.contains(columnKey, rowKey); } @Override public boolean containsColumn(@CheckForNull Object columnKey) { return original.containsRow(columnKey); } @Override public boolean containsRow(@CheckForNull Object rowKey) { return original.containsColumn(rowKey); } @Override public boolean containsValue(@CheckForNull Object value) { return original.containsValue(value); } @Override @CheckForNull public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return original.get(columnKey, rowKey); } @Override @CheckForNull public V put( @ParametricNullness C rowKey, @ParametricNullness R columnKey, @ParametricNullness V value) { return original.put(columnKey, rowKey, value); } @Override public void putAll(Table<? extends C, ? extends R, ? extends V> table) { original.putAll(transpose(table)); } @Override @CheckForNull public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return original.remove(columnKey, rowKey); } @Override public Map<R, V> row(@ParametricNullness C rowKey) { return original.column(rowKey); } @Override public Set<C> rowKeySet() { return original.columnKeySet(); } @Override public Map<C, Map<R, V>> rowMap() { return original.columnMap(); } @Override public int size() { return original.size(); } @Override public Collection<V> values() { return original.values(); } @Override Iterator<Cell<C, R, V>> cellIterator() { return Iterators.transform(original.cellSet().iterator(), Tables::transposeCell); } @Override Spliterator<Cell<C, R, V>> cellSpliterator() { return CollectSpliterators.map(original.cellSet().spliterator(), Tables::transposeCell); } } private static < R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Cell<C, R, V> transposeCell(Cell<R, C, V> cell) { return immutableCell(cell.getColumnKey(), cell.getRowKey(), cell.getValue()); } /** * Creates a table that uses the specified backing map and factory. It can generate a table based * on arbitrary {@link Map} classes. * * <p>The {@code factory}-generated and {@code backingMap} classes determine the table iteration * order. However, the table's {@code row()} method returns instances of a different class than * {@code factory.get()} does. * * <p>Call this method only when the simpler factory methods in classes like {@link * HashBasedTable} and {@link TreeBasedTable} won't suffice. * * <p>The views returned by the {@code Table} methods {@link Table#column}, {@link * Table#columnKeySet}, and {@link Table#columnMap} have iterators that don't support {@code * remove()}. Otherwise, all optional operations are supported. Null row keys, columns keys, and * values are not supported. * * <p>Lookups by row key are often faster than lookups by column key, because the data is stored * in a {@code Map<R, Map<C, V>>}. A method call like {@code column(columnKey).get(rowKey)} still * runs quickly, since the row key is provided. However, {@code column(columnKey).size()} takes * longer, since an iteration across all row keys occurs. * * <p>Note that this implementation is not synchronized. If multiple threads access this table * concurrently and one of the threads modifies the table, it must be synchronized externally. * * <p>The table is serializable if {@code backingMap}, {@code factory}, the maps generated by * {@code factory}, and the table contents are all serializable. * * <p>Note: the table assumes complete ownership over of {@code backingMap} and the maps returned * by {@code factory}. Those objects should not be manually updated and they should not use soft, * weak, or phantom references. * * @param backingMap place to store the mapping from each row key to its corresponding column key * / value map * @param factory supplier of new, empty maps that will each hold all column key / value mappings * for a given row key * @throws IllegalArgumentException if {@code backingMap} is not empty * @since 10.0 */ public static <R, C, V> Table<R, C, V> newCustomTable( Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) { checkArgument(backingMap.isEmpty()); checkNotNull(factory); // TODO(jlevy): Wrap factory to validate that the supplied maps are empty? return new StandardTable<>(backingMap, factory); } /** * Returns a view of a table where each value is transformed by a function. All other properties * of the table, such as iteration order, are left intact. * * <p>Changes in the underlying table are reflected in this view. Conversely, this view supports * removal operations, and these are reflected in the underlying table. * * <p>It's acceptable for the underlying table to contain null keys, and even null values provided * that the function is capable of accepting null input. The transformed table might contain null * values, if the function sometimes gives a null result. * * <p>The returned table is not thread-safe or serializable, even if the underlying table is. * * <p>The function is applied lazily, invoked when needed. This is necessary for the returned * table to be a view, but it means that the function will be applied many times for bulk * operations like {@link Table#containsValue} and {@code Table.toString()}. For this to perform * well, {@code function} should be fast. To avoid lazy evaluation when the returned table doesn't * need to be a view, copy the returned table into a new table of your choosing. * * @since 10.0 */ public static < R extends @Nullable Object, C extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> Table<R, C, V2> transformValues( Table<R, C, V1> fromTable, Function<? super V1, V2> function) { return new TransformedTable<>(fromTable, function); } private static class TransformedTable< R extends @Nullable Object, C extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> extends AbstractTable<R, C, V2> { final Table<R, C, V1> fromTable; final Function<? super V1, V2> function; TransformedTable(Table<R, C, V1> fromTable, Function<? super V1, V2> function) { this.fromTable = checkNotNull(fromTable); this.function = checkNotNull(function); } @Override public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return fromTable.contains(rowKey, columnKey); } @Override @CheckForNull public V2 get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { // The function is passed a null input only when the table contains a null // value. // The cast is safe because of the contains() check. return contains(rowKey, columnKey) ? function.apply(uncheckedCastNullableTToT(fromTable.get(rowKey, columnKey))) : null; } @Override public int size() { return fromTable.size(); } @Override public void clear() { fromTable.clear(); } @Override @CheckForNull public V2 put( @ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V2 value) { throw new UnsupportedOperationException(); } @Override public void putAll(Table<? extends R, ? extends C, ? extends V2> table) { throw new UnsupportedOperationException(); } @Override @CheckForNull public V2 remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return contains(rowKey, columnKey) // The cast is safe because of the contains() check. ? function.apply(uncheckedCastNullableTToT(fromTable.remove(rowKey, columnKey))) : null; } @Override public Map<C, V2> row(@ParametricNullness R rowKey) { return Maps.transformValues(fromTable.row(rowKey), function); } @Override public Map<R, V2> column(@ParametricNullness C columnKey) { return Maps.transformValues(fromTable.column(columnKey), function); } Function<Cell<R, C, V1>, Cell<R, C, V2>> cellFunction() { return new Function<Cell<R, C, V1>, Cell<R, C, V2>>() { @Override public Cell<R, C, V2> apply(Cell<R, C, V1> cell) { return immutableCell( cell.getRowKey(), cell.getColumnKey(), function.apply(cell.getValue())); } }; } @Override Iterator<Cell<R, C, V2>> cellIterator() { return Iterators.transform(fromTable.cellSet().iterator(), cellFunction()); } @Override Spliterator<Cell<R, C, V2>> cellSpliterator() { return CollectSpliterators.map(fromTable.cellSet().spliterator(), cellFunction()); } @Override public Set<R> rowKeySet() { return fromTable.rowKeySet(); } @Override public Set<C> columnKeySet() { return fromTable.columnKeySet(); } @Override Collection<V2> createValues() { return Collections2.transform(fromTable.values(), function); } @Override public Map<R, Map<C, V2>> rowMap() { Function<Map<C, V1>, Map<C, V2>> rowFunction = new Function<Map<C, V1>, Map<C, V2>>() { @Override public Map<C, V2> apply(Map<C, V1> row) { return Maps.transformValues(row, function); } }; return Maps.transformValues(fromTable.rowMap(), rowFunction); } @Override public Map<C, Map<R, V2>> columnMap() { Function<Map<R, V1>, Map<R, V2>> columnFunction = new Function<Map<R, V1>, Map<R, V2>>() { @Override public Map<R, V2> apply(Map<R, V1> column) { return Maps.transformValues(column, function); } }; return Maps.transformValues(fromTable.columnMap(), columnFunction); } } /** * Returns an unmodifiable view of the specified table. This method allows modules to provide * users with "read-only" access to internal tables. Query operations on the returned table "read * through" to the specified table, and attempts to modify the returned table, whether direct or * via its collection views, result in an {@code UnsupportedOperationException}. * * <p>The returned table will be serializable if the specified table is serializable. * * <p>Consider using an {@link ImmutableTable}, which is guaranteed never to change. * * @since 11.0 */ public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Table<R, C, V> unmodifiableTable(Table<? extends R, ? extends C, ? extends V> table) { return new UnmodifiableTable<>(table); } private static class UnmodifiableTable< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> extends ForwardingTable<R, C, V> implements Serializable { final Table<? extends R, ? extends C, ? extends V> delegate; UnmodifiableTable(Table<? extends R, ? extends C, ? extends V> delegate) { this.delegate = checkNotNull(delegate); } @SuppressWarnings("unchecked") // safe, covariant cast @Override protected Table<R, C, V> delegate() { return (Table<R, C, V>) delegate; } @Override public Set<Cell<R, C, V>> cellSet() { return Collections.unmodifiableSet(super.cellSet()); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Map<R, V> column(@ParametricNullness C columnKey) { return Collections.unmodifiableMap(super.column(columnKey)); } @Override public Set<C> columnKeySet() { return Collections.unmodifiableSet(super.columnKeySet()); } @Override public Map<C, Map<R, V>> columnMap() { Function<Map<R, V>, Map<R, V>> wrapper = unmodifiableWrapper(); return Collections.unmodifiableMap(Maps.transformValues(super.columnMap(), wrapper)); } @Override @CheckForNull public V put( @ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value) { throw new UnsupportedOperationException(); } @Override public void putAll(Table<? extends R, ? extends C, ? extends V> table) { throw new UnsupportedOperationException(); } @Override @CheckForNull public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { throw new UnsupportedOperationException(); } @Override public Map<C, V> row(@ParametricNullness R rowKey) { return Collections.unmodifiableMap(super.row(rowKey)); } @Override public Set<R> rowKeySet() { return Collections.unmodifiableSet(super.rowKeySet()); } @Override public Map<R, Map<C, V>> rowMap() { Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper(); return Collections.unmodifiableMap(Maps.transformValues(super.rowMap(), wrapper)); } @Override public Collection<V> values() { return Collections.unmodifiableCollection(super.values()); } private static final long serialVersionUID = 0; } /** * Returns an unmodifiable view of the specified row-sorted table. This method allows modules to * provide users with "read-only" access to internal tables. Query operations on the returned * table "read through" to the specified table, and attempts to modify the returned table, whether * direct or via its collection views, result in an {@code UnsupportedOperationException}. * * <p>The returned table will be serializable if the specified table is serializable. * * @param table the row-sorted table for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified table * @since 11.0 */ public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> RowSortedTable<R, C, V> unmodifiableRowSortedTable( RowSortedTable<R, ? extends C, ? extends V> table) { /* * It's not ? extends R, because it's technically not covariant in R. Specifically, * table.rowMap().comparator() could return a comparator that only works for the ? extends R. * Collections.unmodifiableSortedMap makes the same distinction. */ return new UnmodifiableRowSortedMap<>(table); } private static final class UnmodifiableRowSortedMap< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> extends UnmodifiableTable<R, C, V> implements RowSortedTable<R, C, V> { public UnmodifiableRowSortedMap(RowSortedTable<R, ? extends C, ? extends V> delegate) { super(delegate); } @Override protected RowSortedTable<R, C, V> delegate() { return (RowSortedTable<R, C, V>) super.delegate(); } @Override public SortedMap<R, Map<C, V>> rowMap() { Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper(); return Collections.unmodifiableSortedMap(Maps.transformValues(delegate().rowMap(), wrapper)); } @Override public SortedSet<R> rowKeySet() { return Collections.unmodifiableSortedSet(delegate().rowKeySet()); } private static final long serialVersionUID = 0; } @SuppressWarnings("unchecked") private static <K extends @Nullable Object, V extends @Nullable Object> Function<Map<K, V>, Map<K, V>> unmodifiableWrapper() { return (Function) UNMODIFIABLE_WRAPPER; } private static final Function<? extends Map<?, ?>, ? extends Map<?, ?>> UNMODIFIABLE_WRAPPER = new Function<Map<Object, Object>, Map<Object, Object>>() { @Override public Map<Object, Object> apply(Map<Object, Object> input) { return Collections.unmodifiableMap(input); } }; /** * Returns a synchronized (thread-safe) table backed by the specified table. In order to guarantee * serial access, it is critical that <b>all</b> access to the backing table is accomplished * through the returned table. * * <p>It is imperative that the user manually synchronize on the returned table when accessing any * of its collection views: * * <pre>{@code * Table<R, C, V> table = Tables.synchronizedTable(HashBasedTable.<R, C, V>create()); * ... * Map<C, V> row = table.row(rowKey); // Needn't be in synchronized block * ... * synchronized (table) { // Synchronizing on table, not row! * Iterator<Entry<C, V>> i = row.entrySet().iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * } * }</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned table will be serializable if the specified table is serializable. * * @param table the table to be wrapped in a synchronized view * @return a synchronized view of the specified table * @since 22.0 */ public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Table<R, C, V> synchronizedTable(Table<R, C, V> table) { return Synchronized.table(table, null); } static boolean equalsImpl(Table<?, ?, ?> table, @CheckForNull Object obj) { if (obj == table) { return true; } else if (obj instanceof Table) { Table<?, ?, ?> that = (Table<?, ?, ?>) obj; return table.cellSet().equals(that.cellSet()); } else { return false; } } }
google/guava
guava/src/com/google/common/collect/Tables.java
353
/* * 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.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 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class HttpHeaders { private HttpHeaders() {} // HTTP Request and Response header fields /** The HTTP {@code Cache-Control} header field name. */ public static final String CACHE_CONTROL = "Cache-Control"; /** The HTTP {@code Content-Length} header field name. */ public static final String CONTENT_LENGTH = "Content-Length"; /** The HTTP {@code Content-Type} header field name. */ public static final String CONTENT_TYPE = "Content-Type"; /** The HTTP {@code Date} header field name. */ public static final String DATE = "Date"; /** The HTTP {@code Pragma} header field name. */ public static final String PRAGMA = "Pragma"; /** The HTTP {@code Via} header field name. */ public static final String VIA = "Via"; /** The HTTP {@code Warning} header field name. */ public static final String WARNING = "Warning"; // HTTP Request header fields /** The HTTP {@code Accept} header field name. */ public static final String ACCEPT = "Accept"; /** The HTTP {@code Accept-Charset} header field name. */ public static final String ACCEPT_CHARSET = "Accept-Charset"; /** The HTTP {@code Accept-Encoding} header field name. */ public static final String ACCEPT_ENCODING = "Accept-Encoding"; /** The HTTP {@code Accept-Language} header field name. */ public static final String ACCEPT_LANGUAGE = "Accept-Language"; /** The HTTP {@code Access-Control-Request-Headers} header field name. */ public static final String ACCESS_CONTROL_REQUEST_HEADERS = "Access-Control-Request-Headers"; /** The HTTP {@code Access-Control-Request-Method} header field name. */ public static final String ACCESS_CONTROL_REQUEST_METHOD = "Access-Control-Request-Method"; /** The HTTP {@code Authorization} header field name. */ public static final String AUTHORIZATION = "Authorization"; /** The HTTP {@code Connection} header field name. */ public static final String CONNECTION = "Connection"; /** The HTTP {@code Cookie} header field name. */ public static final String COOKIE = "Cookie"; /** * The HTTP <a href="https://fetch.spec.whatwg.org/#cross-origin-resource-policy-header">{@code * Cross-Origin-Resource-Policy}</a> header field name. * * @since 28.0 */ public static final String CROSS_ORIGIN_RESOURCE_POLICY = "Cross-Origin-Resource-Policy"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc8470">{@code Early-Data}</a> header field * name. * * @since 27.0 */ public static final String EARLY_DATA = "Early-Data"; /** The HTTP {@code Expect} header field name. */ public static final String EXPECT = "Expect"; /** The HTTP {@code From} header field name. */ public static final String FROM = "From"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc7239">{@code Forwarded}</a> header field name. * * @since 20.0 */ public static final String FORWARDED = "Forwarded"; /** * The HTTP {@code Follow-Only-When-Prerender-Shown} header field name. * * @since 17.0 */ public static final String FOLLOW_ONLY_WHEN_PRERENDER_SHOWN = "Follow-Only-When-Prerender-Shown"; /** The HTTP {@code Host} header field name. */ public static final String HOST = "Host"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc7540#section-3.2.1">{@code HTTP2-Settings} * </a> header field name. * * @since 24.0 */ public static final String HTTP2_SETTINGS = "HTTP2-Settings"; /** The HTTP {@code If-Match} header field name. */ public static final String IF_MATCH = "If-Match"; /** The HTTP {@code If-Modified-Since} header field name. */ public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; /** The HTTP {@code If-None-Match} header field name. */ public static final String IF_NONE_MATCH = "If-None-Match"; /** The HTTP {@code If-Range} header field name. */ public static final String IF_RANGE = "If-Range"; /** The HTTP {@code If-Unmodified-Since} header field name. */ public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; /** The HTTP {@code Last-Event-ID} header field name. */ public static final String LAST_EVENT_ID = "Last-Event-ID"; /** The HTTP {@code Max-Forwards} header field name. */ public static final String MAX_FORWARDS = "Max-Forwards"; /** The HTTP {@code Origin} header field name. */ public static final String ORIGIN = "Origin"; /** * The HTTP <a href="https://github.com/WICG/origin-isolation">{@code Origin-Isolation}</a> header * field name. * * @since 30.1 */ public static final String ORIGIN_ISOLATION = "Origin-Isolation"; /** The HTTP {@code Proxy-Authorization} header field name. */ public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; /** The HTTP {@code Range} header field name. */ public static final String RANGE = "Range"; /** The HTTP {@code Referer} header field name. */ public static final String REFERER = "Referer"; /** * The HTTP <a href="https://www.w3.org/TR/referrer-policy/">{@code Referrer-Policy}</a> header * field name. * * @since 23.4 */ public static final String REFERRER_POLICY = "Referrer-Policy"; /** * Values for the <a href="https://www.w3.org/TR/referrer-policy/">{@code Referrer-Policy}</a> * header. * * @since 23.4 */ public static final class ReferrerPolicyValues { private ReferrerPolicyValues() {} public static final String NO_REFERRER = "no-referrer"; public static final String NO_REFFERER_WHEN_DOWNGRADE = "no-referrer-when-downgrade"; public static final String SAME_ORIGIN = "same-origin"; public static final String ORIGIN = "origin"; public static final String STRICT_ORIGIN = "strict-origin"; public static final String ORIGIN_WHEN_CROSS_ORIGIN = "origin-when-cross-origin"; public static final String STRICT_ORIGIN_WHEN_CROSS_ORIGIN = "strict-origin-when-cross-origin"; public static final String UNSAFE_URL = "unsafe-url"; } /** * The HTTP <a href="https://www.w3.org/TR/service-workers/#update-algorithm">{@code * Service-Worker}</a> header field name. * * @since 20.0 */ public static final String SERVICE_WORKER = "Service-Worker"; /** The HTTP {@code TE} header field name. */ public static final String TE = "TE"; /** The HTTP {@code Upgrade} header field name. */ public static final String UPGRADE = "Upgrade"; /** * The HTTP <a href="https://w3c.github.io/webappsec-upgrade-insecure-requests/#preference">{@code * Upgrade-Insecure-Requests}</a> header field name. * * @since 28.1 */ public static final String UPGRADE_INSECURE_REQUESTS = "Upgrade-Insecure-Requests"; /** The HTTP {@code User-Agent} header field name. */ public static final String USER_AGENT = "User-Agent"; // HTTP Response header fields /** The HTTP {@code Accept-Ranges} header field name. */ public static final String ACCEPT_RANGES = "Accept-Ranges"; /** The HTTP {@code Access-Control-Allow-Headers} header field name. */ public static final String ACCESS_CONTROL_ALLOW_HEADERS = "Access-Control-Allow-Headers"; /** The HTTP {@code Access-Control-Allow-Methods} header field name. */ public static final String ACCESS_CONTROL_ALLOW_METHODS = "Access-Control-Allow-Methods"; /** The HTTP {@code Access-Control-Allow-Origin} header field name. */ public static final String ACCESS_CONTROL_ALLOW_ORIGIN = "Access-Control-Allow-Origin"; /** * The HTTP <a href="https://wicg.github.io/private-network-access/#headers">{@code * Access-Control-Allow-Private-Network}</a> header field name. * * @since 31.1 */ public static final String ACCESS_CONTROL_ALLOW_PRIVATE_NETWORK = "Access-Control-Allow-Private-Network"; /** The HTTP {@code Access-Control-Allow-Credentials} header field name. */ public static final String ACCESS_CONTROL_ALLOW_CREDENTIALS = "Access-Control-Allow-Credentials"; /** The HTTP {@code Access-Control-Expose-Headers} header field name. */ public static final String ACCESS_CONTROL_EXPOSE_HEADERS = "Access-Control-Expose-Headers"; /** The HTTP {@code Access-Control-Max-Age} header field name. */ public static final String ACCESS_CONTROL_MAX_AGE = "Access-Control-Max-Age"; /** The HTTP {@code Age} header field name. */ public static final String AGE = "Age"; /** The HTTP {@code Allow} header field name. */ public static final String ALLOW = "Allow"; /** The HTTP {@code Content-Disposition} header field name. */ public static final String CONTENT_DISPOSITION = "Content-Disposition"; /** The HTTP {@code Content-Encoding} header field name. */ public static final String CONTENT_ENCODING = "Content-Encoding"; /** The HTTP {@code Content-Language} header field name. */ public static final String CONTENT_LANGUAGE = "Content-Language"; /** The HTTP {@code Content-Location} header field name. */ public static final String CONTENT_LOCATION = "Content-Location"; /** The HTTP {@code Content-MD5} header field name. */ public static final String CONTENT_MD5 = "Content-MD5"; /** The HTTP {@code Content-Range} header field name. */ public static final String CONTENT_RANGE = "Content-Range"; /** * The HTTP <a href="http://w3.org/TR/CSP/#content-security-policy-header-field">{@code * Content-Security-Policy}</a> header field name. * * @since 15.0 */ public static final String CONTENT_SECURITY_POLICY = "Content-Security-Policy"; /** * The HTTP <a href="http://w3.org/TR/CSP/#content-security-policy-report-only-header-field"> * {@code Content-Security-Policy-Report-Only}</a> header field name. * * @since 15.0 */ public static final String CONTENT_SECURITY_POLICY_REPORT_ONLY = "Content-Security-Policy-Report-Only"; /** * The HTTP nonstandard {@code X-Content-Security-Policy} header field name. It was introduced in * <a href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the Firefox until * version 23 and the Internet Explorer version 10. Please, use {@link #CONTENT_SECURITY_POLICY} * to pass the CSP. * * @since 20.0 */ public static final String X_CONTENT_SECURITY_POLICY = "X-Content-Security-Policy"; /** * The HTTP nonstandard {@code X-Content-Security-Policy-Report-Only} header field name. It was * introduced in <a href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the * Firefox until version 23 and the Internet Explorer version 10. Please, use {@link * #CONTENT_SECURITY_POLICY_REPORT_ONLY} to pass the CSP. * * @since 20.0 */ public static final String X_CONTENT_SECURITY_POLICY_REPORT_ONLY = "X-Content-Security-Policy-Report-Only"; /** * The HTTP nonstandard {@code X-WebKit-CSP} header field name. It was introduced in <a * href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the Chrome until * version 25. Please, use {@link #CONTENT_SECURITY_POLICY} to pass the CSP. * * @since 20.0 */ public static final String X_WEBKIT_CSP = "X-WebKit-CSP"; /** * The HTTP nonstandard {@code X-WebKit-CSP-Report-Only} header field name. It was introduced in * <a href="https://www.w3.org/TR/2011/WD-CSP-20111129/">CSP v.1</a> and used by the Chrome until * version 25. Please, use {@link #CONTENT_SECURITY_POLICY_REPORT_ONLY} to pass the CSP. * * @since 20.0 */ public static final String X_WEBKIT_CSP_REPORT_ONLY = "X-WebKit-CSP-Report-Only"; /** * The HTTP <a href="https://wicg.github.io/cross-origin-embedder-policy/#COEP">{@code * Cross-Origin-Embedder-Policy}</a> header field name. * * @since 30.0 */ public static final String CROSS_ORIGIN_EMBEDDER_POLICY = "Cross-Origin-Embedder-Policy"; /** * The HTTP <a href="https://wicg.github.io/cross-origin-embedder-policy/#COEP-RO">{@code * Cross-Origin-Embedder-Policy-Report-Only}</a> header field name. * * @since 30.0 */ public static final String CROSS_ORIGIN_EMBEDDER_POLICY_REPORT_ONLY = "Cross-Origin-Embedder-Policy-Report-Only"; /** * The HTTP Cross-Origin-Opener-Policy header field name. * * @since 28.2 */ public static final String CROSS_ORIGIN_OPENER_POLICY = "Cross-Origin-Opener-Policy"; /** The HTTP {@code ETag} header field name. */ public static final String ETAG = "ETag"; /** The HTTP {@code Expires} header field name. */ public static final String EXPIRES = "Expires"; /** The HTTP {@code Last-Modified} header field name. */ public static final String LAST_MODIFIED = "Last-Modified"; /** The HTTP {@code Link} header field name. */ public static final String LINK = "Link"; /** The HTTP {@code Location} header field name. */ public static final String LOCATION = "Location"; /** * The HTTP {@code Keep-Alive} header field name. * * @since 31.0 */ public static final String KEEP_ALIVE = "Keep-Alive"; /** * The HTTP <a href="https://github.com/WICG/nav-speculation/blob/main/no-vary-search.md">{@code * No-Vary-Seearch}</a> header field name. * * @since 32.0.0 */ public static final String NO_VARY_SEARCH = "No-Vary-Search"; /** * The HTTP <a href="https://googlechrome.github.io/OriginTrials/#header">{@code Origin-Trial}</a> * header field name. * * @since 27.1 */ public static final String ORIGIN_TRIAL = "Origin-Trial"; /** The HTTP {@code P3P} header field name. Limited browser support. */ public static final String P3P = "P3P"; /** The HTTP {@code Proxy-Authenticate} header field name. */ public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; /** The HTTP {@code Refresh} header field name. Non-standard header supported by most browsers. */ public static final String REFRESH = "Refresh"; /** * The HTTP <a href="https://www.w3.org/TR/reporting/">{@code Report-To}</a> header field name. * * @since 27.1 */ public static final String REPORT_TO = "Report-To"; /** The HTTP {@code Retry-After} header field name. */ public static final String RETRY_AFTER = "Retry-After"; /** The HTTP {@code Server} header field name. */ public static final String SERVER = "Server"; /** * The HTTP <a href="https://www.w3.org/TR/server-timing/">{@code Server-Timing}</a> header field * name. * * @since 23.6 */ public static final String SERVER_TIMING = "Server-Timing"; /** * The HTTP <a href="https://www.w3.org/TR/service-workers/#update-algorithm">{@code * Service-Worker-Allowed}</a> header field name. * * @since 20.0 */ public static final String SERVICE_WORKER_ALLOWED = "Service-Worker-Allowed"; /** The HTTP {@code Set-Cookie} header field name. */ public static final String SET_COOKIE = "Set-Cookie"; /** The HTTP {@code Set-Cookie2} header field name. */ public static final String SET_COOKIE2 = "Set-Cookie2"; /** * The HTTP <a href="http://goo.gl/Dxx19N">{@code SourceMap}</a> header field name. * * @since 27.1 */ public static final String SOURCE_MAP = "SourceMap"; /** * The HTTP <a href="https://github.com/WICG/nav-speculation/blob/main/opt-in.md">{@code * Supports-Loading-Mode}</a> header field name. This can be used to specify, for example, <a * href="https://developer.chrome.com/docs/privacy-sandbox/fenced-frame/#server-opt-in">fenced * frames</a>. * * @since 32.0.0 */ public static final String SUPPORTS_LOADING_MODE = "Supports-Loading-Mode"; /** * The HTTP <a href="http://tools.ietf.org/html/rfc6797#section-6.1">{@code * Strict-Transport-Security}</a> header field name. * * @since 15.0 */ public static final String STRICT_TRANSPORT_SECURITY = "Strict-Transport-Security"; /** * The HTTP <a href="http://www.w3.org/TR/resource-timing/#cross-origin-resources">{@code * Timing-Allow-Origin}</a> header field name. * * @since 15.0 */ public static final String TIMING_ALLOW_ORIGIN = "Timing-Allow-Origin"; /** The HTTP {@code Trailer} header field name. */ public static final String TRAILER = "Trailer"; /** The HTTP {@code Transfer-Encoding} header field name. */ public static final String TRANSFER_ENCODING = "Transfer-Encoding"; /** The HTTP {@code Vary} header field name. */ public static final String VARY = "Vary"; /** The HTTP {@code WWW-Authenticate} header field name. */ public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; // Common, non-standard HTTP header fields /** The HTTP {@code DNT} header field name. */ public static final String DNT = "DNT"; /** The HTTP {@code X-Content-Type-Options} header field name. */ public static final String X_CONTENT_TYPE_OPTIONS = "X-Content-Type-Options"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-IP}</a> header field name. Header used for VAST requests to provide the IP address of * the device on whose behalf the request is being made. * * @since 31.0 */ public static final String X_DEVICE_IP = "X-Device-IP"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-Referer}</a> header field name. Header used for VAST requests to provide the {@link * #REFERER} header value that the on-behalf-of client would have used when making a request * itself. * * @since 31.0 */ public static final String X_DEVICE_REFERER = "X-Device-Referer"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-Accept-Language}</a> header field name. Header used for VAST requests to provide the * {@link #ACCEPT_LANGUAGE} header value that the on-behalf-of client would have used when making * a request itself. * * @since 31.0 */ public static final String X_DEVICE_ACCEPT_LANGUAGE = "X-Device-Accept-Language"; /** * The HTTP <a * href="https://iabtechlab.com/wp-content/uploads/2019/06/VAST_4.2_final_june26.pdf">{@code * X-Device-Requested-With}</a> header field name. Header used for VAST requests to provide the * {@link #X_REQUESTED_WITH} header value that the on-behalf-of client would have used when making * a request itself. * * @since 31.0 */ public static final String X_DEVICE_REQUESTED_WITH = "X-Device-Requested-With"; /** The HTTP {@code X-Do-Not-Track} header field name. */ public static final String X_DO_NOT_TRACK = "X-Do-Not-Track"; /** The HTTP {@code X-Forwarded-For} header field name (superseded by {@code Forwarded}). */ public static final String X_FORWARDED_FOR = "X-Forwarded-For"; /** The HTTP {@code X-Forwarded-Proto} header field name. */ public static final String X_FORWARDED_PROTO = "X-Forwarded-Proto"; /** * The HTTP <a href="http://goo.gl/lQirAH">{@code X-Forwarded-Host}</a> header field name. * * @since 20.0 */ public static final String X_FORWARDED_HOST = "X-Forwarded-Host"; /** * The HTTP <a href="http://goo.gl/YtV2at">{@code X-Forwarded-Port}</a> header field name. * * @since 20.0 */ public static final String X_FORWARDED_PORT = "X-Forwarded-Port"; /** The HTTP {@code X-Frame-Options} header field name. */ public static final String X_FRAME_OPTIONS = "X-Frame-Options"; /** The HTTP {@code X-Powered-By} header field name. */ public static final String X_POWERED_BY = "X-Powered-By"; /** * The HTTP <a href="http://tools.ietf.org/html/draft-evans-palmer-key-pinning">{@code * Public-Key-Pins}</a> header field name. * * @since 15.0 */ public static final String PUBLIC_KEY_PINS = "Public-Key-Pins"; /** * The HTTP <a href="http://tools.ietf.org/html/draft-evans-palmer-key-pinning">{@code * Public-Key-Pins-Report-Only}</a> header field name. * * @since 15.0 */ public static final String PUBLIC_KEY_PINS_REPORT_ONLY = "Public-Key-Pins-Report-Only"; /** * The HTTP {@code X-Request-ID} header field name. * * @since 30.1 */ public static final String X_REQUEST_ID = "X-Request-ID"; /** The HTTP {@code X-Requested-With} header field name. */ public static final String X_REQUESTED_WITH = "X-Requested-With"; /** The HTTP {@code X-User-IP} header field name. */ public static final String X_USER_IP = "X-User-IP"; /** * The HTTP <a href="https://goo.gl/VKpXxa">{@code X-Download-Options}</a> header field name. * * <p>When the new X-Download-Options header is present with the value {@code noopen}, the user is * prevented from opening a file download directly; instead, they must first save the file * locally. * * @since 24.1 */ public static final String X_DOWNLOAD_OPTIONS = "X-Download-Options"; /** The HTTP {@code X-XSS-Protection} header field name. */ public static final String X_XSS_PROTECTION = "X-XSS-Protection"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/X-DNS-Prefetch-Control">{@code * X-DNS-Prefetch-Control}</a> header controls DNS prefetch behavior. Value can be "on" or "off". * By default, DNS prefetching is "on" for HTTP pages and "off" for HTTPS pages. */ public static final String X_DNS_PREFETCH_CONTROL = "X-DNS-Prefetch-Control"; /** * The HTTP <a href="http://html.spec.whatwg.org/multipage/semantics.html#hyperlink-auditing"> * {@code Ping-From}</a> header field name. * * @since 19.0 */ public static final String PING_FROM = "Ping-From"; /** * The HTTP <a href="http://html.spec.whatwg.org/multipage/semantics.html#hyperlink-auditing"> * {@code Ping-To}</a> header field name. * * @since 19.0 */ public static final String PING_TO = "Ping-To"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ#As_a_server_admin.2C_can_I_distinguish_prefetch_requests_from_normal_requests.3F">{@code * Purpose}</a> header field name. * * @since 28.0 */ public static final String PURPOSE = "Purpose"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ#As_a_server_admin.2C_can_I_distinguish_prefetch_requests_from_normal_requests.3F">{@code * X-Purpose}</a> header field name. * * @since 28.0 */ public static final String X_PURPOSE = "X-Purpose"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Link_prefetching_FAQ#As_a_server_admin.2C_can_I_distinguish_prefetch_requests_from_normal_requests.3F">{@code * X-Moz}</a> header field name. * * @since 28.0 */ public static final String X_MOZ = "X-Moz"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Device-Memory">{@code * Device-Memory}</a> header field name. * * @since 31.0 */ public static final String DEVICE_MEMORY = "Device-Memory"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Downlink">{@code * Downlink}</a> header field name. * * @since 31.0 */ public static final String DOWNLINK = "Downlink"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/ECT">{@code * ECT}</a> header field name. * * @since 31.0 */ public static final String ECT = "ECT"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/RTT">{@code * RTT}</a> header field name. * * @since 31.0 */ public static final String RTT = "RTT"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Save-Data">{@code * Save-Data}</a> header field name. * * @since 31.0 */ public static final String SAVE_DATA = "Save-Data"; /** * The HTTP <a * href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Viewport-Width">{@code * Viewport-Width}</a> header field name. * * @since 31.0 */ public static final String VIEWPORT_WIDTH = "Viewport-Width"; /** * The HTTP <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Width">{@code * Width}</a> header field name. * * @since 31.0 */ public static final String WIDTH = "Width"; /** * The HTTP <a href="https://www.w3.org/TR/permissions-policy-1/">{@code Permissions-Policy}</a> * header field name. * * @since 31.0 */ public static final String PERMISSIONS_POLICY = "Permissions-Policy"; /** * The HTTP <a * href="https://w3c.github.io/webappsec-permissions-policy/#permissions-policy-report-only-http-header-field">{@code * Permissions-Policy-Report-Only}</a> header field name. * * @since 33.2.0 */ public static final String PERMISSIONS_POLICY_REPORT_ONLY = "Permissions-Policy-Report-Only"; /** * The HTTP <a * href="https://wicg.github.io/user-preference-media-features-headers/#sec-ch-prefers-color-scheme">{@code * Sec-CH-Prefers-Color-Scheme}</a> header field name. * * <p>This header is experimental. * * @since 31.0 */ public static final String SEC_CH_PREFERS_COLOR_SCHEME = "Sec-CH-Prefers-Color-Scheme"; /** * The HTTP <a * href="https://www.rfc-editor.org/rfc/rfc8942#name-the-accept-ch-response-head">{@code * Accept-CH}</a> header field name. * * @since 31.0 */ public static final String ACCEPT_CH = "Accept-CH"; /** * The HTTP <a * href="https://datatracker.ietf.org/doc/html/draft-davidben-http-client-hint-reliability-03.txt#section-3">{@code * Critical-CH}</a> header field name. * * @since 31.0 */ public static final String CRITICAL_CH = "Critical-CH"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua">{@code Sec-CH-UA}</a> * header field name. * * @since 30.0 */ public static final String SEC_CH_UA = "Sec-CH-UA"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-arch">{@code * Sec-CH-UA-Arch}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_ARCH = "Sec-CH-UA-Arch"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-model">{@code * Sec-CH-UA-Model}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_MODEL = "Sec-CH-UA-Model"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform">{@code * Sec-CH-UA-Platform}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_PLATFORM = "Sec-CH-UA-Platform"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-platform-version">{@code * Sec-CH-UA-Platform-Version}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_PLATFORM_VERSION = "Sec-CH-UA-Platform-Version"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-full-version">{@code * Sec-CH-UA-Full-Version}</a> header field name. * * @deprecated Prefer {@link SEC_CH_UA_FULL_VERSION_LIST}. * @since 30.0 */ @Deprecated public static final String SEC_CH_UA_FULL_VERSION = "Sec-CH-UA-Full-Version"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-full-version-list">{@code * Sec-CH-UA-Full-Version}</a> header field name. * * @since 31.1 */ public static final String SEC_CH_UA_FULL_VERSION_LIST = "Sec-CH-UA-Full-Version-List"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-mobile">{@code * Sec-CH-UA-Mobile}</a> header field name. * * @since 30.0 */ public static final String SEC_CH_UA_MOBILE = "Sec-CH-UA-Mobile"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-wow64">{@code * Sec-CH-UA-WoW64}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_UA_WOW64 = "Sec-CH-UA-WoW64"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-bitness">{@code * Sec-CH-UA-Bitness}</a> header field name. * * @since 31.0 */ public static final String SEC_CH_UA_BITNESS = "Sec-CH-UA-Bitness"; /** * The HTTP <a href="https://wicg.github.io/ua-client-hints/#sec-ch-ua-form-factor">{@code * Sec-CH-UA-Form-Factor}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_UA_FORM_FACTOR = "Sec-CH-UA-Form-Factor"; /** * The HTTP <a * href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-viewport-width">{@code * Sec-CH-Viewport-Width}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_VIEWPORT_WIDTH = "Sec-CH-Viewport-Width"; /** * The HTTP <a * href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-viewport-height">{@code * Sec-CH-Viewport-Height}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_VIEWPORT_HEIGHT = "Sec-CH-Viewport-Height"; /** * The HTTP <a href="https://wicg.github.io/responsive-image-client-hints/#sec-ch-dpr">{@code * Sec-CH-DPR}</a> header field name. * * @since 32.0.0 */ public static final String SEC_CH_DPR = "Sec-CH-DPR"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Dest}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_DEST = "Sec-Fetch-Dest"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Mode}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_MODE = "Sec-Fetch-Mode"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-Site}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_SITE = "Sec-Fetch-Site"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Fetch-User}</a> * header field name. * * @since 27.1 */ public static final String SEC_FETCH_USER = "Sec-Fetch-User"; /** * The HTTP <a href="https://w3c.github.io/webappsec-fetch-metadata/">{@code Sec-Metadata}</a> * header field name. * * @since 26.0 */ public static final String SEC_METADATA = "Sec-Metadata"; /** * The HTTP <a href="https://tools.ietf.org/html/draft-ietf-tokbind-https">{@code * Sec-Token-Binding}</a> header field name. * * @since 25.1 */ public static final String SEC_TOKEN_BINDING = "Sec-Token-Binding"; /** * The HTTP <a href="https://tools.ietf.org/html/draft-ietf-tokbind-ttrp">{@code * Sec-Provided-Token-Binding-ID}</a> header field name. * * @since 25.1 */ public static final String SEC_PROVIDED_TOKEN_BINDING_ID = "Sec-Provided-Token-Binding-ID"; /** * The HTTP <a href="https://tools.ietf.org/html/draft-ietf-tokbind-ttrp">{@code * Sec-Referred-Token-Binding-ID}</a> header field name. * * @since 25.1 */ public static final String SEC_REFERRED_TOKEN_BINDING_ID = "Sec-Referred-Token-Binding-ID"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc6455">{@code Sec-WebSocket-Accept}</a> header * field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_ACCEPT = "Sec-WebSocket-Accept"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc6455">{@code Sec-WebSocket-Extensions}</a> * header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_EXTENSIONS = "Sec-WebSocket-Extensions"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc6455">{@code Sec-WebSocket-Key}</a> header * field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_KEY = "Sec-WebSocket-Key"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc6455">{@code Sec-WebSocket-Protocol}</a> * header field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_PROTOCOL = "Sec-WebSocket-Protocol"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc6455">{@code Sec-WebSocket-Version}</a> header * field name. * * @since 28.0 */ public static final String SEC_WEBSOCKET_VERSION = "Sec-WebSocket-Version"; /** * The HTTP <a href="https://patcg-individual-drafts.github.io/topics/">{@code * Sec-Browsing-Topics}</a> header field name. * * @since 32.0.0 */ public static final String SEC_BROWSING_TOPICS = "Sec-Browsing-Topics"; /** * The HTTP <a href="https://patcg-individual-drafts.github.io/topics/">{@code * Observe-Browsing-Topics}</a> header field name. * * @since 32.0.0 */ public static final String OBSERVE_BROWSING_TOPICS = "Observe-Browsing-Topics"; /** * The HTTP <a * href="https://wicg.github.io/turtledove/#handling-direct-from-seller-signals">{@code * Sec-Ad-Auction-Fetch}</a> header field name. * * @since 33.0.0 */ public static final String SEC_AD_AUCTION_FETCH = "Sec-Ad-Auction-Fetch"; /** * The HTTP <a * href="https://privacycg.github.io/gpc-spec/#the-sec-gpc-header-field-for-http-requests">{@code * Sec-GPC}</a> header field name. * * @since 33.2.0 */ public static final String SEC_GPC = "Sec-GPC"; /** * The HTTP <a * href="https://wicg.github.io/turtledove/#handling-direct-from-seller-signals">{@code * Ad-Auction-Signals}</a> header field name. * * @since 33.0.0 */ public static final String AD_AUCTION_SIGNALS = "Ad-Auction-Signals"; /** * The HTTP <a href="https://wicg.github.io/turtledove/#http-headerdef-ad-auction-allowed">{@code * Ad-Auction-Allowed}</a> header field name. * * @since 33.2.0 */ public static final String AD_AUCTION_ALLOWED = "Ad-Auction-Allowed"; /** * The HTTP <a href="https://tools.ietf.org/html/rfc8586">{@code CDN-Loop}</a> header field name. * * @since 28.0 */ public static final String CDN_LOOP = "CDN-Loop"; }
google/guava
guava/src/com/google/common/net/HttpHeaders.java
354
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.balking; import java.util.concurrent.TimeUnit; import lombok.Getter; import lombok.extern.slf4j.Slf4j; /** * Washing machine class. */ @Slf4j public class WashingMachine { private final DelayProvider delayProvider; @Getter private WashingMachineState washingMachineState; /** * Creates a new instance of WashingMachine. */ public WashingMachine() { this((interval, timeUnit, task) -> { try { Thread.sleep(timeUnit.toMillis(interval)); } catch (InterruptedException ie) { LOGGER.error("", ie); Thread.currentThread().interrupt(); } task.run(); }); } /** * Creates a new instance of WashingMachine using provided delayProvider. This constructor is used * only for unit testing purposes. */ public WashingMachine(DelayProvider delayProvider) { this.delayProvider = delayProvider; this.washingMachineState = WashingMachineState.ENABLED; } /** * Method responsible for washing if the object is in appropriate state. */ public void wash() { synchronized (this) { var machineState = getWashingMachineState(); LOGGER.info("{}: Actual machine state: {}", Thread.currentThread().getName(), machineState); if (this.washingMachineState == WashingMachineState.WASHING) { LOGGER.error("Cannot wash if the machine has been already washing!"); return; } this.washingMachineState = WashingMachineState.WASHING; } LOGGER.info("{}: Doing the washing", Thread.currentThread().getName()); this.delayProvider.executeAfterDelay(50, TimeUnit.MILLISECONDS, this::endOfWashing); } /** * Method is responsible for ending the washing by changing machine state. */ public synchronized void endOfWashing() { washingMachineState = WashingMachineState.ENABLED; LOGGER.info("{}: Washing completed.", Thread.currentThread().getId()); } }
rajprins/java-design-patterns
balking/src/main/java/com/iluwatar/balking/WashingMachine.java
355
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.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 static java.util.Objects.requireNonNull; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Joiner; import com.google.common.base.Predicate; import com.google.common.collect.FluentIterable; import com.google.common.collect.ForwardingSet; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Ordering; import com.google.common.primitives.Primitives; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.concurrent.LazyInit; import java.io.Serializable; import java.lang.reflect.Constructor; import java.lang.reflect.GenericArrayType; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.util.ArrayList; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.Map; import java.util.Set; import javax.annotation.CheckForNull; /** * A {@link Type} with generics. * * <p>Operations that are otherwise only available in {@link Class} are implemented to support * {@code Type}, for example {@link #isSubtypeOf}, {@link #isArray} and {@link #getComponentType}. * It also provides additional utilities such as {@link #getTypes}, {@link #resolveType}, etc. * * <p>There are three ways to get a {@code TypeToken} instance: * * <ul> * <li>Wrap a {@code Type} obtained via reflection. For example: {@code * TypeToken.of(method.getGenericReturnType())}. * <li>Capture a generic type with a (usually anonymous) subclass. For example: * <pre>{@code * new TypeToken<List<String>>() {} * }</pre> * <p>Note that it's critical that the actual type argument is carried by a subclass. The * following code is wrong because it only captures the {@code <T>} type variable of the * {@code listType()} method signature; while {@code <String>} is lost in erasure: * <pre>{@code * class Util { * static <T> TypeToken<List<T>> listType() { * return new TypeToken<List<T>>() {}; * } * } * * TypeToken<List<String>> stringListType = Util.<String>listType(); * }</pre> * <li>Capture a generic type with a (usually anonymous) subclass and resolve it against a context * class that knows what the type parameters are. For example: * <pre>{@code * abstract class IKnowMyType<T> { * TypeToken<T> type = new TypeToken<T>(getClass()) {}; * } * new IKnowMyType<String>() {}.type => String * }</pre> * </ul> * * <p>{@code TypeToken} is serializable when no type variable is contained in the type. * * <p>Note to Guice users: {@code TypeToken} is similar to Guice's {@code TypeLiteral} class except * that it is serializable and offers numerous additional utility methods. * * @author Bob Lee * @author Sven Mawson * @author Ben Yu * @since 12.0 */ @SuppressWarnings("serial") // SimpleTypeToken is the serialized form. @ElementTypesAreNonnullByDefault public abstract class TypeToken<T> extends TypeCapture<T> implements Serializable { private final Type runtimeType; /** Resolver for resolving parameter and field types with {@link #runtimeType} as context. */ @LazyInit @CheckForNull private transient TypeResolver invariantTypeResolver; /** Resolver for resolving covariant types with {@link #runtimeType} as context. */ @LazyInit @CheckForNull private transient TypeResolver covariantTypeResolver; /** * Constructs a new type token of {@code T}. * * <p>Clients create an empty anonymous subclass. Doing so embeds the type parameter in the * anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure. * * <p>For example: * * <pre>{@code * TypeToken<List<String>> t = new TypeToken<List<String>>() {}; * }</pre> */ protected TypeToken() { this.runtimeType = capture(); checkState( !(runtimeType instanceof TypeVariable), "Cannot construct a TypeToken for a type variable.\n" + "You probably meant to call new TypeToken<%s>(getClass()) " + "that can resolve the type variable for you.\n" + "If you do need to create a TypeToken of a type variable, " + "please use TypeToken.of() instead.", runtimeType); } /** * Constructs a new type token of {@code T} while resolving free type variables in the context of * {@code declaringClass}. * * <p>Clients create an empty anonymous subclass. Doing so embeds the type parameter in the * anonymous class's type hierarchy so we can reconstitute it at runtime despite erasure. * * <p>For example: * * <pre>{@code * abstract class IKnowMyType<T> { * TypeToken<T> getMyType() { * return new TypeToken<T>(getClass()) {}; * } * } * * new IKnowMyType<String>() {}.getMyType() => String * }</pre> */ protected TypeToken(Class<?> declaringClass) { Type captured = super.capture(); if (captured instanceof Class) { this.runtimeType = captured; } else { this.runtimeType = TypeResolver.covariantly(declaringClass).resolveType(captured); } } private TypeToken(Type type) { this.runtimeType = checkNotNull(type); } /** Returns an instance of type token that wraps {@code type}. */ public static <T> TypeToken<T> of(Class<T> type) { return new SimpleTypeToken<>(type); } /** Returns an instance of type token that wraps {@code type}. */ public static TypeToken<?> of(Type type) { return new SimpleTypeToken<>(type); } /** * Returns the raw type of {@code T}. Formally speaking, if {@code T} is returned by {@link * java.lang.reflect.Method#getGenericReturnType}, the raw type is what's returned by {@link * java.lang.reflect.Method#getReturnType} of the same method object. Specifically: * * <ul> * <li>If {@code T} is a {@code Class} itself, {@code T} itself is returned. * <li>If {@code T} is a {@link ParameterizedType}, the raw type of the parameterized type is * returned. * <li>If {@code T} is a {@link GenericArrayType}, the returned type is the corresponding array * class. For example: {@code List<Integer>[] => List[]}. * <li>If {@code T} is a type variable or a wildcard type, the raw type of the first upper bound * is returned. For example: {@code <X extends Foo> => Foo}. * </ul> */ public final Class<? super T> getRawType() { // For wildcard or type variable, the first bound determines the runtime type. Class<?> rawType = getRawTypes().iterator().next(); @SuppressWarnings("unchecked") // raw type is |T| Class<? super T> result = (Class<? super T>) rawType; return result; } /** Returns the represented type. */ public final Type getType() { return runtimeType; } /** * Returns a new {@code TypeToken} where type variables represented by {@code typeParam} are * substituted by {@code typeArg}. For example, it can be used to construct {@code Map<K, V>} for * any {@code K} and {@code V} type: * * <pre>{@code * static <K, V> TypeToken<Map<K, V>> mapOf( * TypeToken<K> keyType, TypeToken<V> valueType) { * return new TypeToken<Map<K, V>>() {} * .where(new TypeParameter<K>() {}, keyType) * .where(new TypeParameter<V>() {}, valueType); * } * }</pre> * * @param <X> The parameter type * @param typeParam the parameter type variable * @param typeArg the actual type to substitute */ /* * TODO(cpovirk): Is there any way for us to support TypeParameter instances for type parameters * that have nullable bounds? Unfortunately, if we change the parameter to TypeParameter<? extends * @Nullable X>, then users might pass a TypeParameter<Y>, where Y is a subtype of X, while still * passing a TypeToken<X>. This would be invalid. Maybe we could accept a TypeParameter<@PolyNull * X> if we support such a thing? It would be weird or misleading for users to be able to pass * `new TypeParameter<@Nullable T>() {}` and have it act as a plain `TypeParameter<T>`, but * hopefully no one would do that, anyway. See also the comment on TypeParameter itself. * * TODO(cpovirk): Elaborate on this / merge with other comment? */ public final <X> TypeToken<T> where(TypeParameter<X> typeParam, TypeToken<X> typeArg) { TypeResolver resolver = new TypeResolver() .where( ImmutableMap.of( new TypeResolver.TypeVariableKey(typeParam.typeVariable), typeArg.runtimeType)); // If there's any type error, we'd report now rather than later. return new SimpleTypeToken<>(resolver.resolveType(runtimeType)); } /** * Returns a new {@code TypeToken} where type variables represented by {@code typeParam} are * substituted by {@code typeArg}. For example, it can be used to construct {@code Map<K, V>} for * any {@code K} and {@code V} type: * * <pre>{@code * static <K, V> TypeToken<Map<K, V>> mapOf( * Class<K> keyType, Class<V> valueType) { * return new TypeToken<Map<K, V>>() {} * .where(new TypeParameter<K>() {}, keyType) * .where(new TypeParameter<V>() {}, valueType); * } * }</pre> * * @param <X> The parameter type * @param typeParam the parameter type variable * @param typeArg the actual type to substitute */ /* * TODO(cpovirk): Is there any way for us to support TypeParameter instances for type parameters * that have nullable bounds? See discussion on the other overload of this method. */ public final <X> TypeToken<T> where(TypeParameter<X> typeParam, Class<X> typeArg) { return where(typeParam, of(typeArg)); } /** * Resolves the given {@code type} against the type context represented by this type. For example: * * <pre>{@code * new TypeToken<List<String>>() {}.resolveType( * List.class.getMethod("get", int.class).getGenericReturnType()) * => String.class * }</pre> */ public final TypeToken<?> resolveType(Type type) { checkNotNull(type); // Being conservative here because the user could use resolveType() to resolve a type in an // invariant context. return of(getInvariantTypeResolver().resolveType(type)); } private TypeToken<?> resolveSupertype(Type type) { TypeToken<?> supertype = of(getCovariantTypeResolver().resolveType(type)); // super types' type mapping is a subset of type mapping of this type. supertype.covariantTypeResolver = covariantTypeResolver; supertype.invariantTypeResolver = invariantTypeResolver; return supertype; } /** * Returns the generic superclass of this type or {@code null} if the type represents {@link * Object} or an interface. This method is similar but different from {@link * Class#getGenericSuperclass}. For example, {@code new TypeToken<StringArrayList>() * {}.getGenericSuperclass()} will return {@code new TypeToken<ArrayList<String>>() {}}; while * {@code StringArrayList.class.getGenericSuperclass()} will return {@code ArrayList<E>}, where * {@code E} is the type variable declared by class {@code ArrayList}. * * <p>If this type is a type variable or wildcard, its first upper bound is examined and returned * if the bound is a class or extends from a class. This means that the returned type could be a * type variable too. */ @CheckForNull final TypeToken<? super T> getGenericSuperclass() { if (runtimeType instanceof TypeVariable) { // First bound is always the super class, if one exists. return boundAsSuperclass(((TypeVariable<?>) runtimeType).getBounds()[0]); } if (runtimeType instanceof WildcardType) { // wildcard has one and only one upper bound. return boundAsSuperclass(((WildcardType) runtimeType).getUpperBounds()[0]); } Type superclass = getRawType().getGenericSuperclass(); if (superclass == null) { return null; } @SuppressWarnings("unchecked") // super class of T TypeToken<? super T> superToken = (TypeToken<? super T>) resolveSupertype(superclass); return superToken; } @CheckForNull private TypeToken<? super T> boundAsSuperclass(Type bound) { TypeToken<?> token = of(bound); if (token.getRawType().isInterface()) { return null; } @SuppressWarnings("unchecked") // only upper bound of T is passed in. TypeToken<? super T> superclass = (TypeToken<? super T>) token; return superclass; } /** * Returns the generic interfaces that this type directly {@code implements}. This method is * similar but different from {@link Class#getGenericInterfaces()}. For example, {@code new * TypeToken<List<String>>() {}.getGenericInterfaces()} will return a list that contains {@code * new TypeToken<Iterable<String>>() {}}; while {@code List.class.getGenericInterfaces()} will * return an array that contains {@code Iterable<T>}, where the {@code T} is the type variable * declared by interface {@code Iterable}. * * <p>If this type is a type variable or wildcard, its upper bounds are examined and those that * are either an interface or upper-bounded only by interfaces are returned. This means that the * returned types could include type variables too. */ final ImmutableList<TypeToken<? super T>> getGenericInterfaces() { if (runtimeType instanceof TypeVariable) { return boundsAsInterfaces(((TypeVariable<?>) runtimeType).getBounds()); } if (runtimeType instanceof WildcardType) { return boundsAsInterfaces(((WildcardType) runtimeType).getUpperBounds()); } ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder(); for (Type interfaceType : getRawType().getGenericInterfaces()) { @SuppressWarnings("unchecked") // interface of T TypeToken<? super T> resolvedInterface = (TypeToken<? super T>) resolveSupertype(interfaceType); builder.add(resolvedInterface); } return builder.build(); } private ImmutableList<TypeToken<? super T>> boundsAsInterfaces(Type[] bounds) { ImmutableList.Builder<TypeToken<? super T>> builder = ImmutableList.builder(); for (Type bound : bounds) { @SuppressWarnings("unchecked") // upper bound of T TypeToken<? super T> boundType = (TypeToken<? super T>) of(bound); if (boundType.getRawType().isInterface()) { builder.add(boundType); } } return builder.build(); } /** * Returns the set of interfaces and classes that this type is or is a subtype of. The returned * types are parameterized with proper type arguments. * * <p>Subtypes are always listed before supertypes. But the reverse is not true. A type isn't * necessarily a subtype of all the types following. Order between types without subtype * relationship is arbitrary and not guaranteed. * * <p>If this type is a type variable or wildcard, upper bounds that are themselves type variables * aren't included (their super interfaces and superclasses are). */ public final TypeSet getTypes() { return new TypeSet(); } /** * Returns the generic form of {@code superclass}. For example, if this is {@code * ArrayList<String>}, {@code Iterable<String>} is returned given the input {@code * Iterable.class}. */ public final TypeToken<? super T> getSupertype(Class<? super T> superclass) { checkArgument( this.someRawTypeIsSubclassOf(superclass), "%s is not a super class of %s", superclass, this); if (runtimeType instanceof TypeVariable) { return getSupertypeFromUpperBounds(superclass, ((TypeVariable<?>) runtimeType).getBounds()); } if (runtimeType instanceof WildcardType) { return getSupertypeFromUpperBounds(superclass, ((WildcardType) runtimeType).getUpperBounds()); } if (superclass.isArray()) { return getArraySupertype(superclass); } @SuppressWarnings("unchecked") // resolved supertype TypeToken<? super T> supertype = (TypeToken<? super T>) resolveSupertype(toGenericType(superclass).runtimeType); return supertype; } /** * Returns subtype of {@code this} with {@code subclass} as the raw class. For example, if this is * {@code Iterable<String>} and {@code subclass} is {@code List}, {@code List<String>} is * returned. */ public final TypeToken<? extends T> getSubtype(Class<?> subclass) { checkArgument( !(runtimeType instanceof TypeVariable), "Cannot get subtype of type variable <%s>", this); if (runtimeType instanceof WildcardType) { return getSubtypeFromLowerBounds(subclass, ((WildcardType) runtimeType).getLowerBounds()); } // unwrap array type if necessary if (isArray()) { return getArraySubtype(subclass); } // At this point, it's either a raw class or parameterized type. checkArgument( getRawType().isAssignableFrom(subclass), "%s isn't a subclass of %s", subclass, this); Type resolvedTypeArgs = resolveTypeArgsForSubclass(subclass); @SuppressWarnings("unchecked") // guarded by the isAssignableFrom() statement above TypeToken<? extends T> subtype = (TypeToken<? extends T>) of(resolvedTypeArgs); checkArgument( subtype.isSubtypeOf(this), "%s does not appear to be a subtype of %s", subtype, this); return subtype; } /** * Returns true if this type is a supertype of the given {@code type}. "Supertype" is defined * according to <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type * arguments</a> introduced with Java generics. * * @since 19.0 */ public final boolean isSupertypeOf(TypeToken<?> type) { return type.isSubtypeOf(getType()); } /** * Returns true if this type is a supertype of the given {@code type}. "Supertype" is defined * according to <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type * arguments</a> introduced with Java generics. * * @since 19.0 */ public final boolean isSupertypeOf(Type type) { return of(type).isSubtypeOf(getType()); } /** * Returns true if this type is a subtype of the given {@code type}. "Subtype" is defined * according to <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type * arguments</a> introduced with Java generics. * * @since 19.0 */ public final boolean isSubtypeOf(TypeToken<?> type) { return isSubtypeOf(type.getType()); } /** * Returns true if this type is a subtype of the given {@code type}. "Subtype" is defined * according to <a * href="http://docs.oracle.com/javase/specs/jls/se8/html/jls-4.html#jls-4.5.1">the rules for type * arguments</a> introduced with Java generics. * * @since 19.0 */ public final boolean isSubtypeOf(Type supertype) { checkNotNull(supertype); if (supertype instanceof WildcardType) { // if 'supertype' is <? super Foo>, 'this' can be: // Foo, SubFoo, <? extends Foo>. // if 'supertype' is <? extends Foo>, nothing is a subtype. return any(((WildcardType) supertype).getLowerBounds()).isSupertypeOf(runtimeType); } // if 'this' is wildcard, it's a suptype of to 'supertype' if any of its "extends" // bounds is a subtype of 'supertype'. if (runtimeType instanceof WildcardType) { // <? super Base> is of no use in checking 'from' being a subtype of 'to'. return any(((WildcardType) runtimeType).getUpperBounds()).isSubtypeOf(supertype); } // if 'this' is type variable, it's a subtype if any of its "extends" // bounds is a subtype of 'supertype'. if (runtimeType instanceof TypeVariable) { return runtimeType.equals(supertype) || any(((TypeVariable<?>) runtimeType).getBounds()).isSubtypeOf(supertype); } if (runtimeType instanceof GenericArrayType) { return of(supertype).isSupertypeOfArray((GenericArrayType) runtimeType); } // Proceed to regular Type subtype check if (supertype instanceof Class) { return this.someRawTypeIsSubclassOf((Class<?>) supertype); } else if (supertype instanceof ParameterizedType) { return this.isSubtypeOfParameterizedType((ParameterizedType) supertype); } else if (supertype instanceof GenericArrayType) { return this.isSubtypeOfArrayType((GenericArrayType) supertype); } else { // to instanceof TypeVariable return false; } } /** * Returns true if this type is known to be an array type, such as {@code int[]}, {@code T[]}, * {@code <? extends Map<String, Integer>[]>} etc. */ public final boolean isArray() { return getComponentType() != null; } /** * Returns true if this type is one of the nine primitive types (including {@code void}). * * @since 15.0 */ public final boolean isPrimitive() { return (runtimeType instanceof Class) && ((Class<?>) runtimeType).isPrimitive(); } /** * Returns the corresponding wrapper type if this is a primitive type; otherwise returns {@code * this} itself. Idempotent. * * @since 15.0 */ public final TypeToken<T> wrap() { if (isPrimitive()) { @SuppressWarnings("unchecked") // this is a primitive class Class<T> type = (Class<T>) runtimeType; return of(Primitives.wrap(type)); } return this; } private boolean isWrapper() { return Primitives.allWrapperTypes().contains(runtimeType); } /** * Returns the corresponding primitive type if this is a wrapper type; otherwise returns {@code * this} itself. Idempotent. * * @since 15.0 */ public final TypeToken<T> unwrap() { if (isWrapper()) { @SuppressWarnings("unchecked") // this is a wrapper class Class<T> type = (Class<T>) runtimeType; return of(Primitives.unwrap(type)); } return this; } /** * Returns the array component type if this type represents an array ({@code int[]}, {@code T[]}, * {@code <? extends Map<String, Integer>[]>} etc.), or else {@code null} is returned. */ @CheckForNull public final TypeToken<?> getComponentType() { Type componentType = Types.getComponentType(runtimeType); if (componentType == null) { return null; } return of(componentType); } /** * Returns the {@link Invokable} for {@code method}, which must be a member of {@code T}. * * @since 14.0 */ public final Invokable<T, Object> method(Method method) { checkArgument( this.someRawTypeIsSubclassOf(method.getDeclaringClass()), "%s not declared by %s", method, this); return new Invokable.MethodInvokable<T>(method) { @Override Type getGenericReturnType() { return getCovariantTypeResolver().resolveType(super.getGenericReturnType()); } @Override Type[] getGenericParameterTypes() { return getInvariantTypeResolver().resolveTypesInPlace(super.getGenericParameterTypes()); } @Override Type[] getGenericExceptionTypes() { return getCovariantTypeResolver().resolveTypesInPlace(super.getGenericExceptionTypes()); } @Override public TypeToken<T> getOwnerType() { return TypeToken.this; } @Override public String toString() { return getOwnerType() + "." + super.toString(); } }; } /** * Returns the {@link Invokable} for {@code constructor}, which must be a member of {@code T}. * * @since 14.0 */ public final Invokable<T, T> constructor(Constructor<?> constructor) { checkArgument( constructor.getDeclaringClass() == getRawType(), "%s not declared by %s", constructor, getRawType()); return new Invokable.ConstructorInvokable<T>(constructor) { @Override Type getGenericReturnType() { return getCovariantTypeResolver().resolveType(super.getGenericReturnType()); } @Override Type[] getGenericParameterTypes() { return getInvariantTypeResolver().resolveTypesInPlace(super.getGenericParameterTypes()); } @Override Type[] getGenericExceptionTypes() { return getCovariantTypeResolver().resolveTypesInPlace(super.getGenericExceptionTypes()); } @Override public TypeToken<T> getOwnerType() { return TypeToken.this; } @Override public String toString() { return getOwnerType() + "(" + Joiner.on(", ").join(getGenericParameterTypes()) + ")"; } }; } /** * The set of interfaces and classes that {@code T} is or is a subtype of. {@link Object} is not * included in the set if this type is an interface. * * @since 13.0 */ public class TypeSet extends ForwardingSet<TypeToken<? super T>> implements Serializable { @CheckForNull private transient ImmutableSet<TypeToken<? super T>> types; TypeSet() {} /** Returns the types that are interfaces implemented by this type. */ public TypeSet interfaces() { return new InterfaceSet(this); } /** Returns the types that are classes. */ public TypeSet classes() { return new ClassSet(); } @Override protected Set<TypeToken<? super T>> delegate() { ImmutableSet<TypeToken<? super T>> filteredTypes = types; if (filteredTypes == null) { // Java has no way to express ? super T when we parameterize TypeToken vs. Class. @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableList<TypeToken<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_GENERIC_TYPE.collectTypes(TypeToken.this); return (types = FluentIterable.from(collectedTypes) .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD) .toSet()); } else { return filteredTypes; } } /** Returns the raw types of the types in this set, in the same order. */ public Set<Class<? super T>> rawTypes() { // Java has no way to express ? super T when we parameterize TypeToken vs. Class. @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableList<Class<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getRawTypes()); return ImmutableSet.copyOf(collectedTypes); } private static final long serialVersionUID = 0; } private final class InterfaceSet extends TypeSet { private final transient TypeSet allTypes; @CheckForNull private transient ImmutableSet<TypeToken<? super T>> interfaces; InterfaceSet(TypeSet allTypes) { this.allTypes = allTypes; } @Override protected Set<TypeToken<? super T>> delegate() { ImmutableSet<TypeToken<? super T>> result = interfaces; if (result == null) { return (interfaces = FluentIterable.from(allTypes).filter(TypeFilter.INTERFACE_ONLY).toSet()); } else { return result; } } @Override public TypeSet interfaces() { return this; } @Override public Set<Class<? super T>> rawTypes() { // Java has no way to express ? super T when we parameterize TypeToken vs. Class. @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableList<Class<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_RAW_TYPE.collectTypes(getRawTypes()); return FluentIterable.from(collectedTypes).filter(Class::isInterface).toSet(); } @Override public TypeSet classes() { throw new UnsupportedOperationException("interfaces().classes() not supported."); } private Object readResolve() { return getTypes().interfaces(); } private static final long serialVersionUID = 0; } private final class ClassSet extends TypeSet { @CheckForNull private transient ImmutableSet<TypeToken<? super T>> classes; @Override protected Set<TypeToken<? super T>> delegate() { ImmutableSet<TypeToken<? super T>> result = classes; if (result == null) { @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableList<TypeToken<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_GENERIC_TYPE.classesOnly().collectTypes(TypeToken.this); return (classes = FluentIterable.from(collectedTypes) .filter(TypeFilter.IGNORE_TYPE_VARIABLE_OR_WILDCARD) .toSet()); } else { return result; } } @Override public TypeSet classes() { return this; } @Override public Set<Class<? super T>> rawTypes() { // Java has no way to express ? super T when we parameterize TypeToken vs. Class. @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableList<Class<? super T>> collectedTypes = (ImmutableList) TypeCollector.FOR_RAW_TYPE.classesOnly().collectTypes(getRawTypes()); return ImmutableSet.copyOf(collectedTypes); } @Override public TypeSet interfaces() { throw new UnsupportedOperationException("classes().interfaces() not supported."); } private Object readResolve() { return getTypes().classes(); } private static final long serialVersionUID = 0; } private enum TypeFilter implements Predicate<TypeToken<?>> { IGNORE_TYPE_VARIABLE_OR_WILDCARD { @Override public boolean apply(TypeToken<?> type) { return !(type.runtimeType instanceof TypeVariable || type.runtimeType instanceof WildcardType); } }, INTERFACE_ONLY { @Override public boolean apply(TypeToken<?> type) { return type.getRawType().isInterface(); } } } /** * Returns true if {@code o} is another {@code TypeToken} that represents the same {@link Type}. */ @Override public boolean equals(@CheckForNull Object o) { if (o instanceof TypeToken) { TypeToken<?> that = (TypeToken<?>) o; return runtimeType.equals(that.runtimeType); } return false; } @Override public int hashCode() { return runtimeType.hashCode(); } @Override public String toString() { return Types.toString(runtimeType); } /** Implemented to support serialization of subclasses. */ protected Object writeReplace() { // TypeResolver just transforms the type to our own impls that are Serializable // except TypeVariable. return of(new TypeResolver().resolveType(runtimeType)); } /** * Ensures that this type token doesn't contain type variables, which can cause unchecked type * errors for callers like {@link TypeToInstanceMap}. */ @CanIgnoreReturnValue final TypeToken<T> rejectTypeVariables() { new TypeVisitor() { @Override void visitTypeVariable(TypeVariable<?> type) { throw new IllegalArgumentException( runtimeType + "contains a type variable and is not safe for the operation"); } @Override void visitWildcardType(WildcardType type) { visit(type.getLowerBounds()); visit(type.getUpperBounds()); } @Override void visitParameterizedType(ParameterizedType type) { visit(type.getActualTypeArguments()); visit(type.getOwnerType()); } @Override void visitGenericArrayType(GenericArrayType type) { visit(type.getGenericComponentType()); } }.visit(runtimeType); return this; } private boolean someRawTypeIsSubclassOf(Class<?> superclass) { for (Class<?> rawType : getRawTypes()) { if (superclass.isAssignableFrom(rawType)) { return true; } } return false; } private boolean isSubtypeOfParameterizedType(ParameterizedType supertype) { Class<?> matchedClass = of(supertype).getRawType(); if (!someRawTypeIsSubclassOf(matchedClass)) { return false; } TypeVariable<?>[] typeVars = matchedClass.getTypeParameters(); Type[] supertypeArgs = supertype.getActualTypeArguments(); for (int i = 0; i < typeVars.length; i++) { Type subtypeParam = getCovariantTypeResolver().resolveType(typeVars[i]); // If 'supertype' is "List<? extends CharSequence>" // and 'this' is StringArrayList, // First step is to figure out StringArrayList "is-a" List<E> where <E> = String. // String is then matched against <? extends CharSequence>, the supertypeArgs[0]. if (!of(subtypeParam).is(supertypeArgs[i], typeVars[i])) { return false; } } // We only care about the case when the supertype is a non-static inner class // in which case we need to make sure the subclass's owner type is a subtype of the // supertype's owner. return Modifier.isStatic(((Class<?>) supertype.getRawType()).getModifiers()) || supertype.getOwnerType() == null || isOwnedBySubtypeOf(supertype.getOwnerType()); } private boolean isSubtypeOfArrayType(GenericArrayType supertype) { if (runtimeType instanceof Class) { Class<?> fromClass = (Class<?>) runtimeType; if (!fromClass.isArray()) { return false; } return of(fromClass.getComponentType()).isSubtypeOf(supertype.getGenericComponentType()); } else if (runtimeType instanceof GenericArrayType) { GenericArrayType fromArrayType = (GenericArrayType) runtimeType; return of(fromArrayType.getGenericComponentType()) .isSubtypeOf(supertype.getGenericComponentType()); } else { return false; } } private boolean isSupertypeOfArray(GenericArrayType subtype) { if (runtimeType instanceof Class) { Class<?> thisClass = (Class<?>) runtimeType; if (!thisClass.isArray()) { return thisClass.isAssignableFrom(Object[].class); } return of(subtype.getGenericComponentType()).isSubtypeOf(thisClass.getComponentType()); } else if (runtimeType instanceof GenericArrayType) { return of(subtype.getGenericComponentType()) .isSubtypeOf(((GenericArrayType) runtimeType).getGenericComponentType()); } else { return false; } } /** * {@code A.is(B)} is defined as {@code Foo<A>.isSubtypeOf(Foo<B>)}. * * <p>Specifically, returns true if any of the following conditions is met: * * <ol> * <li>'this' and {@code formalType} are equal. * <li>'this' and {@code formalType} have equal canonical form. * <li>{@code formalType} is {@code <? extends Foo>} and 'this' is a subtype of {@code Foo}. * <li>{@code formalType} is {@code <? super Foo>} and 'this' is a supertype of {@code Foo}. * </ol> * * Note that condition 2 isn't technically accurate under the context of a recursively bounded * type variables. For example, {@code Enum<? extends Enum<E>>} canonicalizes to {@code Enum<?>} * where {@code E} is the type variable declared on the {@code Enum} class declaration. It's * technically <em>not</em> true that {@code Foo<Enum<? extends Enum<E>>>} is a subtype of {@code * Foo<Enum<?>>} according to JLS. See testRecursiveWildcardSubtypeBug() for a real example. * * <p>It appears that properly handling recursive type bounds in the presence of implicit type * bounds is not easy. For now we punt, hoping that this defect should rarely cause issues in real * code. * * @param formalType is {@code Foo<formalType>} a supertype of {@code Foo<T>}? * @param declaration The type variable in the context of a parameterized type. Used to infer type * bound when {@code formalType} is a wildcard with implicit upper bound. */ private boolean is(Type formalType, TypeVariable<?> declaration) { if (runtimeType.equals(formalType)) { return true; } if (formalType instanceof WildcardType) { WildcardType your = canonicalizeWildcardType(declaration, (WildcardType) formalType); // if "formalType" is <? extends Foo>, "this" can be: // Foo, SubFoo, <? extends Foo>, <? extends SubFoo>, <T extends Foo> or // <T extends SubFoo>. // if "formalType" is <? super Foo>, "this" can be: // Foo, SuperFoo, <? super Foo> or <? super SuperFoo>. return every(your.getUpperBounds()).isSupertypeOf(runtimeType) && every(your.getLowerBounds()).isSubtypeOf(runtimeType); } return canonicalizeWildcardsInType(runtimeType).equals(canonicalizeWildcardsInType(formalType)); } /** * In reflection, {@code Foo<?>.getUpperBounds()[0]} is always {@code Object.class}, even when Foo * is defined as {@code Foo<T extends String>}. Thus directly calling {@code <?>.is(String.class)} * will return false. To mitigate, we canonicalize wildcards by enforcing the following * invariants: * * <ol> * <li>{@code canonicalize(t)} always produces the equal result for equivalent types. For * example both {@code Enum<?>} and {@code Enum<? extends Enum<?>>} canonicalize to {@code * Enum<? extends Enum<E>}. * <li>{@code canonicalize(t)} produces a "literal" supertype of t. For example: {@code Enum<? * extends Enum<?>>} canonicalizes to {@code Enum<?>}, which is a supertype (if we disregard * the upper bound is implicitly an Enum too). * <li>If {@code canonicalize(A) == canonicalize(B)}, then {@code Foo<A>.isSubtypeOf(Foo<B>)} * and vice versa. i.e. {@code A.is(B)} and {@code B.is(A)}. * <li>{@code canonicalize(canonicalize(A)) == canonicalize(A)}. * </ol> */ private static Type canonicalizeTypeArg(TypeVariable<?> declaration, Type typeArg) { return typeArg instanceof WildcardType ? canonicalizeWildcardType(declaration, ((WildcardType) typeArg)) : canonicalizeWildcardsInType(typeArg); } private static Type canonicalizeWildcardsInType(Type type) { if (type instanceof ParameterizedType) { return canonicalizeWildcardsInParameterizedType((ParameterizedType) type); } if (type instanceof GenericArrayType) { return Types.newArrayType( canonicalizeWildcardsInType(((GenericArrayType) type).getGenericComponentType())); } return type; } // WARNING: the returned type may have empty upper bounds, which may violate common expectations // by user code or even some of our own code. It's fine for the purpose of checking subtypes. // Just don't ever let the user access it. private static WildcardType canonicalizeWildcardType( TypeVariable<?> declaration, WildcardType type) { Type[] declared = declaration.getBounds(); List<Type> upperBounds = new ArrayList<>(); for (Type bound : type.getUpperBounds()) { if (!any(declared).isSubtypeOf(bound)) { upperBounds.add(canonicalizeWildcardsInType(bound)); } } return new Types.WildcardTypeImpl(type.getLowerBounds(), upperBounds.toArray(new Type[0])); } private static ParameterizedType canonicalizeWildcardsInParameterizedType( ParameterizedType type) { Class<?> rawType = (Class<?>) type.getRawType(); TypeVariable<?>[] typeVars = rawType.getTypeParameters(); Type[] typeArgs = type.getActualTypeArguments(); for (int i = 0; i < typeArgs.length; i++) { typeArgs[i] = canonicalizeTypeArg(typeVars[i], typeArgs[i]); } return Types.newParameterizedTypeWithOwner(type.getOwnerType(), rawType, typeArgs); } private static Bounds every(Type[] bounds) { // Every bound must match. On any false, result is false. return new Bounds(bounds, false); } private static Bounds any(Type[] bounds) { // Any bound matches. On any true, result is true. return new Bounds(bounds, true); } private static class Bounds { private final Type[] bounds; private final boolean target; Bounds(Type[] bounds, boolean target) { this.bounds = bounds; this.target = target; } boolean isSubtypeOf(Type supertype) { for (Type bound : bounds) { if (of(bound).isSubtypeOf(supertype) == target) { return target; } } return !target; } boolean isSupertypeOf(Type subtype) { TypeToken<?> type = of(subtype); for (Type bound : bounds) { if (type.isSubtypeOf(bound) == target) { return target; } } return !target; } } private ImmutableSet<Class<? super T>> getRawTypes() { ImmutableSet.Builder<Class<?>> builder = ImmutableSet.builder(); new TypeVisitor() { @Override void visitTypeVariable(TypeVariable<?> t) { visit(t.getBounds()); } @Override void visitWildcardType(WildcardType t) { visit(t.getUpperBounds()); } @Override void visitParameterizedType(ParameterizedType t) { builder.add((Class<?>) t.getRawType()); } @Override void visitClass(Class<?> t) { builder.add(t); } @Override void visitGenericArrayType(GenericArrayType t) { builder.add(Types.getArrayClass(of(t.getGenericComponentType()).getRawType())); } }.visit(runtimeType); // Cast from ImmutableSet<Class<?>> to ImmutableSet<Class<? super T>> @SuppressWarnings({"unchecked", "rawtypes"}) ImmutableSet<Class<? super T>> result = (ImmutableSet) builder.build(); return result; } private boolean isOwnedBySubtypeOf(Type supertype) { for (TypeToken<?> type : getTypes()) { Type ownerType = type.getOwnerTypeIfPresent(); if (ownerType != null && of(ownerType).isSubtypeOf(supertype)) { return true; } } return false; } /** * Returns the owner type of a {@link ParameterizedType} or enclosing class of a {@link Class}, or * null otherwise. */ @CheckForNull private Type getOwnerTypeIfPresent() { if (runtimeType instanceof ParameterizedType) { return ((ParameterizedType) runtimeType).getOwnerType(); } else if (runtimeType instanceof Class<?>) { return ((Class<?>) runtimeType).getEnclosingClass(); } else { return null; } } /** * Returns the type token representing the generic type declaration of {@code cls}. For example: * {@code TypeToken.getGenericType(Iterable.class)} returns {@code Iterable<T>}. * * <p>If {@code cls} isn't parameterized and isn't a generic array, the type token of the class is * returned. */ @VisibleForTesting static <T> TypeToken<? extends T> toGenericType(Class<T> cls) { if (cls.isArray()) { Type arrayOfGenericType = Types.newArrayType( // If we are passed with int[].class, don't turn it to GenericArrayType toGenericType(cls.getComponentType()).runtimeType); @SuppressWarnings("unchecked") // array is covariant TypeToken<? extends T> result = (TypeToken<? extends T>) of(arrayOfGenericType); return result; } TypeVariable<Class<T>>[] typeParams = cls.getTypeParameters(); Type ownerType = cls.isMemberClass() && !Modifier.isStatic(cls.getModifiers()) ? toGenericType(cls.getEnclosingClass()).runtimeType : null; if ((typeParams.length > 0) || ((ownerType != null) && ownerType != cls.getEnclosingClass())) { @SuppressWarnings("unchecked") // Like, it's Iterable<T> for Iterable.class TypeToken<? extends T> type = (TypeToken<? extends T>) of(Types.newParameterizedTypeWithOwner(ownerType, cls, typeParams)); return type; } else { return of(cls); } } private TypeResolver getCovariantTypeResolver() { TypeResolver resolver = covariantTypeResolver; if (resolver == null) { resolver = (covariantTypeResolver = TypeResolver.covariantly(runtimeType)); } return resolver; } private TypeResolver getInvariantTypeResolver() { TypeResolver resolver = invariantTypeResolver; if (resolver == null) { resolver = (invariantTypeResolver = TypeResolver.invariantly(runtimeType)); } return resolver; } private TypeToken<? super T> getSupertypeFromUpperBounds( Class<? super T> supertype, Type[] upperBounds) { for (Type upperBound : upperBounds) { @SuppressWarnings("unchecked") // T's upperbound is <? super T>. TypeToken<? super T> bound = (TypeToken<? super T>) of(upperBound); if (bound.isSubtypeOf(supertype)) { @SuppressWarnings({"rawtypes", "unchecked"}) // guarded by the isSubtypeOf check. TypeToken<? super T> result = bound.getSupertype((Class) supertype); return result; } } throw new IllegalArgumentException(supertype + " isn't a super type of " + this); } private TypeToken<? extends T> getSubtypeFromLowerBounds(Class<?> subclass, Type[] lowerBounds) { if (lowerBounds.length > 0) { @SuppressWarnings("unchecked") // T's lower bound is <? extends T> TypeToken<? extends T> bound = (TypeToken<? extends T>) of(lowerBounds[0]); // Java supports only one lowerbound anyway. return bound.getSubtype(subclass); } throw new IllegalArgumentException(subclass + " isn't a subclass of " + this); } private TypeToken<? super T> getArraySupertype(Class<? super T> supertype) { // with component type, we have lost generic type information // Use raw type so that compiler allows us to call getSupertype() @SuppressWarnings("rawtypes") TypeToken componentType = getComponentType(); // TODO(cpovirk): checkArgument? if (componentType == null) { throw new IllegalArgumentException(supertype + " isn't a super type of " + this); } // array is covariant. component type is super type, so is the array type. @SuppressWarnings("unchecked") // going from raw type back to generics /* * requireNonNull is safe because we call getArraySupertype only after checking * supertype.isArray(). */ TypeToken<?> componentSupertype = componentType.getSupertype(requireNonNull(supertype.getComponentType())); @SuppressWarnings("unchecked") // component type is super type, so is array type. TypeToken<? super T> result = (TypeToken<? super T>) // If we are passed with int[].class, don't turn it to GenericArrayType of(newArrayClassOrGenericArrayType(componentSupertype.runtimeType)); return result; } private TypeToken<? extends T> getArraySubtype(Class<?> subclass) { Class<?> subclassComponentType = subclass.getComponentType(); if (subclassComponentType == null) { throw new IllegalArgumentException(subclass + " does not appear to be a subtype of " + this); } // array is covariant. component type is subtype, so is the array type. // requireNonNull is safe because we call getArraySubtype only when isArray(). TypeToken<?> componentSubtype = requireNonNull(getComponentType()).getSubtype(subclassComponentType); @SuppressWarnings("unchecked") // component type is subtype, so is array type. TypeToken<? extends T> result = (TypeToken<? extends T>) // If we are passed with int[].class, don't turn it to GenericArrayType of(newArrayClassOrGenericArrayType(componentSubtype.runtimeType)); return result; } private Type resolveTypeArgsForSubclass(Class<?> subclass) { // If both runtimeType and subclass are not parameterized, return subclass // If runtimeType is not parameterized but subclass is, process subclass as a parameterized type // If runtimeType is a raw type (i.e. is a parameterized type specified as a Class<?>), we // return subclass as a raw type if (runtimeType instanceof Class && ((subclass.getTypeParameters().length == 0) || (getRawType().getTypeParameters().length != 0))) { // no resolution needed return subclass; } // class Base<A, B> {} // class Sub<X, Y> extends Base<X, Y> {} // Base<String, Integer>.subtype(Sub.class): // Sub<X, Y>.getSupertype(Base.class) => Base<X, Y> // => X=String, Y=Integer // => Sub<X, Y>=Sub<String, Integer> TypeToken<?> genericSubtype = toGenericType(subclass); @SuppressWarnings({"rawtypes", "unchecked"}) // subclass isn't <? extends T> Type supertypeWithArgsFromSubtype = genericSubtype.getSupertype((Class) getRawType()).runtimeType; return new TypeResolver() .where(supertypeWithArgsFromSubtype, runtimeType) .resolveType(genericSubtype.runtimeType); } /** * Creates an array class if {@code componentType} is a class, or else, a {@link * GenericArrayType}. This is what Java7 does for generic array type parameters. */ private static Type newArrayClassOrGenericArrayType(Type componentType) { return Types.JavaVersion.JAVA7.newArrayType(componentType); } private static final class SimpleTypeToken<T> extends TypeToken<T> { SimpleTypeToken(Type type) { super(type); } private static final long serialVersionUID = 0; } /** * Collects parent types from a subtype. * * @param <K> The type "kind". Either a TypeToken, or Class. */ private abstract static class TypeCollector<K> { static final TypeCollector<TypeToken<?>> FOR_GENERIC_TYPE = new TypeCollector<TypeToken<?>>() { @Override Class<?> getRawType(TypeToken<?> type) { return type.getRawType(); } @Override Iterable<? extends TypeToken<?>> getInterfaces(TypeToken<?> type) { return type.getGenericInterfaces(); } @Override @CheckForNull TypeToken<?> getSuperclass(TypeToken<?> type) { return type.getGenericSuperclass(); } }; static final TypeCollector<Class<?>> FOR_RAW_TYPE = new TypeCollector<Class<?>>() { @Override Class<?> getRawType(Class<?> type) { return type; } @Override Iterable<? extends Class<?>> getInterfaces(Class<?> type) { return Arrays.asList(type.getInterfaces()); } @Override @CheckForNull Class<?> getSuperclass(Class<?> type) { return type.getSuperclass(); } }; /** For just classes, we don't have to traverse interfaces. */ final TypeCollector<K> classesOnly() { return new ForwardingTypeCollector<K>(this) { @Override Iterable<? extends K> getInterfaces(K type) { return ImmutableSet.of(); } @Override ImmutableList<K> collectTypes(Iterable<? extends K> types) { ImmutableList.Builder<K> builder = ImmutableList.builder(); for (K type : types) { if (!getRawType(type).isInterface()) { builder.add(type); } } return super.collectTypes(builder.build()); } }; } final ImmutableList<K> collectTypes(K type) { return collectTypes(ImmutableList.of(type)); } ImmutableList<K> collectTypes(Iterable<? extends K> types) { // type -> order number. 1 for Object, 2 for anything directly below, so on so forth. Map<K, Integer> map = Maps.newHashMap(); for (K type : types) { collectTypes(type, map); } return sortKeysByValue(map, Ordering.natural().reverse()); } /** Collects all types to map, and returns the total depth from T up to Object. */ @CanIgnoreReturnValue private int collectTypes(K type, Map<? super K, Integer> map) { Integer existing = map.get(type); if (existing != null) { // short circuit: if set contains type it already contains its supertypes return existing; } // Interfaces should be listed before Object. int aboveMe = getRawType(type).isInterface() ? 1 : 0; for (K interfaceType : getInterfaces(type)) { aboveMe = Math.max(aboveMe, collectTypes(interfaceType, map)); } K superclass = getSuperclass(type); if (superclass != null) { aboveMe = Math.max(aboveMe, collectTypes(superclass, map)); } /* * TODO(benyu): should we include Object for interface? Also, CharSequence[] and Object[] for * String[]? * */ map.put(type, aboveMe + 1); return aboveMe + 1; } private static <K, V> ImmutableList<K> sortKeysByValue( Map<K, V> map, Comparator<? super V> valueComparator) { Ordering<K> keyOrdering = new Ordering<K>() { @Override public int compare(K left, K right) { // requireNonNull is safe because we are passing keys in the map. return valueComparator.compare( requireNonNull(map.get(left)), requireNonNull(map.get(right))); } }; return keyOrdering.immutableSortedCopy(map.keySet()); } abstract Class<?> getRawType(K type); abstract Iterable<? extends K> getInterfaces(K type); @CheckForNull abstract K getSuperclass(K type); private static class ForwardingTypeCollector<K> extends TypeCollector<K> { private final TypeCollector<K> delegate; ForwardingTypeCollector(TypeCollector<K> delegate) { this.delegate = delegate; } @Override Class<?> getRawType(K type) { return delegate.getRawType(type); } @Override Iterable<? extends K> getInterfaces(K type) { return delegate.getInterfaces(type); } @Override @CheckForNull K getSuperclass(K type) { return delegate.getSuperclass(type); } } } // This happens to be the hash of the class as of now. So setting it makes a backward compatible // change. Going forward, if any incompatible change is added, we can change the UID back to 1. private static final long serialVersionUID = 3637540370352322684L; }
google/guava
guava/src/com/google/common/reflect/TypeToken.java
356
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.math; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.math.MathPreconditions.checkNoOverflow; import static com.google.common.math.MathPreconditions.checkNonNegative; import static com.google.common.math.MathPreconditions.checkPositive; import static com.google.common.math.MathPreconditions.checkRoundingUnnecessary; import static java.lang.Math.abs; import static java.lang.Math.min; import static java.math.RoundingMode.HALF_EVEN; import static java.math.RoundingMode.HALF_UP; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.primitives.Longs; import com.google.common.primitives.UnsignedLongs; import java.math.BigInteger; import java.math.RoundingMode; /** * A class for arithmetic on values of type {@code long}. Where possible, methods are defined and * named analogously to their {@code BigInteger} counterparts. * * <p>The implementations of many methods in this class are based on material from Henry S. Warren, * Jr.'s <i>Hacker's Delight</i>, (Addison Wesley, 2002). * * <p>Similar functionality for {@code int} and for {@link BigInteger} can be found in {@link * IntMath} and {@link BigIntegerMath} respectively. For other common operations on {@code long} * values, see {@link com.google.common.primitives.Longs}. * * @author Louis Wasserman * @since 11.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class LongMath { // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, || @VisibleForTesting static final long MAX_SIGNED_POWER_OF_TWO = 1L << (Long.SIZE - 2); /** * Returns the smallest power of two greater than or equal to {@code x}. This is equivalent to * {@code checkedPow(2, log2(x, CEILING))}. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException of the next-higher power of two is not representable as a {@code * long}, i.e. when {@code x > 2^62} * @since 20.0 */ public static long ceilingPowerOfTwo(long x) { checkPositive("x", x); if (x > MAX_SIGNED_POWER_OF_TWO) { throw new ArithmeticException("ceilingPowerOfTwo(" + x + ") is not representable as a long"); } return 1L << -Long.numberOfLeadingZeros(x - 1); } /** * Returns the largest power of two less than or equal to {@code x}. This is equivalent to {@code * checkedPow(2, log2(x, FLOOR))}. * * @throws IllegalArgumentException if {@code x <= 0} * @since 20.0 */ public static long floorPowerOfTwo(long x) { checkPositive("x", x); // Long.highestOneBit was buggy on GWT. We've fixed it, but I'm not certain when the fix will // be released. return 1L << ((Long.SIZE - 1) - Long.numberOfLeadingZeros(x)); } /** * Returns {@code true} if {@code x} represents a power of two. * * <p>This differs from {@code Long.bitCount(x) == 1}, because {@code * Long.bitCount(Long.MIN_VALUE) == 1}, but {@link Long#MIN_VALUE} is not a power of two. */ @SuppressWarnings("ShortCircuitBoolean") public static boolean isPowerOfTwo(long x) { return x > 0 & (x & (x - 1)) == 0; } /** * Returns 1 if {@code x < y} as unsigned longs, and 0 otherwise. Assumes that x - y fits into a * signed long. The implementation is branch-free, and benchmarks suggest it is measurably faster * than the straightforward ternary expression. */ @VisibleForTesting static int lessThanBranchFree(long x, long y) { // Returns the sign bit of x - y. return (int) (~~(x - y) >>> (Long.SIZE - 1)); } /** * Returns the base-2 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of two */ @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log2(long x, RoundingMode mode) { checkPositive("x", x); switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(isPowerOfTwo(x)); // fall through case DOWN: case FLOOR: return (Long.SIZE - 1) - Long.numberOfLeadingZeros(x); case UP: case CEILING: return Long.SIZE - Long.numberOfLeadingZeros(x - 1); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // Since sqrt(2) is irrational, log2(x) - logFloor cannot be exactly 0.5 int leadingZeros = Long.numberOfLeadingZeros(x); long cmp = MAX_POWER_OF_SQRT2_UNSIGNED >>> leadingZeros; // floor(2^(logFloor + 0.5)) int logFloor = (Long.SIZE - 1) - leadingZeros; return logFloor + lessThanBranchFree(cmp, x); } throw new AssertionError("impossible"); } /** The biggest half power of two that fits into an unsigned long */ @VisibleForTesting static final long MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333F9DE6484L; /** * Returns the base-10 logarithm of {@code x}, rounded according to the specified rounding mode. * * @throws IllegalArgumentException if {@code x <= 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not a power of ten */ @GwtIncompatible // TODO @SuppressWarnings("fallthrough") // TODO(kevinb): remove after this warning is disabled globally public static int log10(long x, RoundingMode mode) { checkPositive("x", x); int logFloor = log10Floor(x); long floorPow = powersOf10[logFloor]; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(x == floorPow); // fall through case FLOOR: case DOWN: return logFloor; case CEILING: case UP: return logFloor + lessThanBranchFree(floorPow, x); case HALF_DOWN: case HALF_UP: case HALF_EVEN: // sqrt(10) is irrational, so log10(x)-logFloor is never exactly 0.5 return logFloor + lessThanBranchFree(halfPowersOf10[logFloor], x); } throw new AssertionError(); } @GwtIncompatible // TODO static int log10Floor(long x) { /* * Based on Hacker's Delight Fig. 11-5, the two-table-lookup, branch-free implementation. * * The key idea is that based on the number of leading zeros (equivalently, floor(log2(x))), we * can narrow the possible floor(log10(x)) values to two. For example, if floor(log2(x)) is 6, * then 64 <= x < 128, so floor(log10(x)) is either 1 or 2. */ int y = maxLog10ForLeadingZeros[Long.numberOfLeadingZeros(x)]; /* * y is the higher of the two possible values of floor(log10(x)). If x < 10^y, then we want the * lower of the two possible values, or y - 1, otherwise, we want y. */ return y - lessThanBranchFree(x, powersOf10[y]); } // maxLog10ForLeadingZeros[i] == floor(log10(2^(Long.SIZE - i))) @VisibleForTesting static final byte[] maxLog10ForLeadingZeros = { 19, 18, 18, 18, 18, 17, 17, 17, 16, 16, 16, 15, 15, 15, 15, 14, 14, 14, 13, 13, 13, 12, 12, 12, 12, 11, 11, 11, 10, 10, 10, 9, 9, 9, 9, 8, 8, 8, 7, 7, 7, 6, 6, 6, 6, 5, 5, 5, 4, 4, 4, 3, 3, 3, 3, 2, 2, 2, 1, 1, 1, 0, 0, 0 }; @GwtIncompatible // TODO @VisibleForTesting static final long[] powersOf10 = { 1L, 10L, 100L, 1000L, 10000L, 100000L, 1000000L, 10000000L, 100000000L, 1000000000L, 10000000000L, 100000000000L, 1000000000000L, 10000000000000L, 100000000000000L, 1000000000000000L, 10000000000000000L, 100000000000000000L, 1000000000000000000L }; // halfPowersOf10[i] = largest long less than 10^(i + 0.5) @GwtIncompatible // TODO @VisibleForTesting static final long[] halfPowersOf10 = { 3L, 31L, 316L, 3162L, 31622L, 316227L, 3162277L, 31622776L, 316227766L, 3162277660L, 31622776601L, 316227766016L, 3162277660168L, 31622776601683L, 316227766016837L, 3162277660168379L, 31622776601683793L, 316227766016837933L, 3162277660168379331L }; /** * Returns {@code b} to the {@code k}th power. Even if the result overflows, it will be equal to * {@code BigInteger.valueOf(b).pow(k).longValue()}. This implementation runs in {@code O(log k)} * time. * * @throws IllegalArgumentException if {@code k < 0} */ @GwtIncompatible // TODO public static long pow(long b, int k) { checkNonNegative("exponent", k); if (-2 <= b && b <= 2) { switch ((int) b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: return (k < Long.SIZE) ? 1L << k : 0; case (-2): if (k < Long.SIZE) { return ((k & 1) == 0) ? 1L << k : -(1L << k); } else { return 0; } default: throw new AssertionError(); } } for (long accum = 1; ; k >>= 1) { switch (k) { case 0: return accum; case 1: return accum * b; default: accum *= ((k & 1) == 0) ? 1 : b; b *= b; } } } /** * Returns the square root of {@code x}, rounded with the specified rounding mode. * * @throws IllegalArgumentException if {@code x < 0} * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code * sqrt(x)} is not an integer */ @GwtIncompatible // TODO public static long sqrt(long x, RoundingMode mode) { checkNonNegative("x", x); if (fitsInInt(x)) { return IntMath.sqrt((int) x, mode); } /* * Let k be the true value of floor(sqrt(x)), so that * * k * k <= x < (k + 1) * (k + 1) * (double) (k * k) <= (double) x <= (double) ((k + 1) * (k + 1)) * since casting to double is nondecreasing. * Note that the right-hand inequality is no longer strict. * Math.sqrt(k * k) <= Math.sqrt(x) <= Math.sqrt((k + 1) * (k + 1)) * since Math.sqrt is monotonic. * (long) Math.sqrt(k * k) <= (long) Math.sqrt(x) <= (long) Math.sqrt((k + 1) * (k + 1)) * since casting to long is monotonic * k <= (long) Math.sqrt(x) <= k + 1 * since (long) Math.sqrt(k * k) == k, as checked exhaustively in * {@link LongMathTest#testSqrtOfPerfectSquareAsDoubleIsPerfect} */ long guess = (long) Math.sqrt((double) x); // Note: guess is always <= FLOOR_SQRT_MAX_LONG. long guessSquared = guess * guess; // Note (2013-2-26): benchmarks indicate that, inscrutably enough, using if statements is // faster here than using lessThanBranchFree. switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(guessSquared == x); return guess; case FLOOR: case DOWN: if (x < guessSquared) { return guess - 1; } return guess; case CEILING: case UP: if (x > guessSquared) { return guess + 1; } return guess; case HALF_DOWN: case HALF_UP: case HALF_EVEN: long sqrtFloor = guess - ((x < guessSquared) ? 1 : 0); long halfSquare = sqrtFloor * sqrtFloor + sqrtFloor; /* * We wish to test whether or not x <= (sqrtFloor + 0.5)^2 = halfSquare + 0.25. Since both x * and halfSquare are integers, this is equivalent to testing whether or not x <= * halfSquare. (We have to deal with overflow, though.) * * If we treat halfSquare as an unsigned long, we know that * sqrtFloor^2 <= x < (sqrtFloor + 1)^2 * halfSquare - sqrtFloor <= x < halfSquare + sqrtFloor + 1 * so |x - halfSquare| <= sqrtFloor. Therefore, it's safe to treat x - halfSquare as a * signed long, so lessThanBranchFree is safe for use. */ return sqrtFloor + lessThanBranchFree(halfSquare, x); } throw new AssertionError(); } /** * Returns the result of dividing {@code p} by {@code q}, rounding using the specified {@code * RoundingMode}. * * @throws ArithmeticException if {@code q == 0}, or if {@code mode == UNNECESSARY} and {@code a} * is not an integer multiple of {@code b} */ @GwtIncompatible // TODO @SuppressWarnings("fallthrough") public static long divide(long p, long q, RoundingMode mode) { checkNotNull(mode); long div = p / q; // throws if q == 0 long rem = p - q * div; // equals p % q if (rem == 0) { return div; } /* * Normal Java division rounds towards 0, consistently with RoundingMode.DOWN. We just have to * deal with the cases where rounding towards 0 is wrong, which typically depends on the sign of * p / q. * * signum is 1 if p and q are both nonnegative or both negative, and -1 otherwise. */ int signum = 1 | (int) ((p ^ q) >> (Long.SIZE - 1)); boolean increment; switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(rem == 0); // fall through case DOWN: increment = false; break; case UP: increment = true; break; case CEILING: increment = signum > 0; break; case FLOOR: increment = signum < 0; break; case HALF_EVEN: case HALF_DOWN: case HALF_UP: long absRem = abs(rem); long cmpRemToHalfDivisor = absRem - (abs(q) - absRem); // subtracting two nonnegative longs can't overflow // cmpRemToHalfDivisor has the same sign as compare(abs(rem), abs(q) / 2). if (cmpRemToHalfDivisor == 0) { // exactly on the half mark increment = (mode == HALF_UP || (mode == HALF_EVEN && (div & 1) != 0)); } else { increment = cmpRemToHalfDivisor > 0; // closer to the UP value } break; default: throw new AssertionError(); } return increment ? div + signum : div; } /** * Returns {@code x mod m}, a non-negative value less than {@code m}. This differs from {@code x % * m}, which might be negative. * * <p>For example: * * <pre>{@code * mod(7, 4) == 3 * mod(-7, 4) == 1 * mod(-1, 4) == 3 * mod(-8, 4) == 0 * mod(8, 4) == 0 * }</pre> * * @throws ArithmeticException if {@code m <= 0} * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3"> * Remainder Operator</a> */ @GwtIncompatible // TODO public static int mod(long x, int m) { // Cast is safe because the result is guaranteed in the range [0, m) return (int) mod(x, (long) m); } /** * Returns {@code x mod m}, a non-negative value less than {@code m}. This differs from {@code x % * m}, which might be negative. * * <p>For example: * * <pre>{@code * mod(7, 4) == 3 * mod(-7, 4) == 1 * mod(-1, 4) == 3 * mod(-8, 4) == 0 * mod(8, 4) == 0 * }</pre> * * @throws ArithmeticException if {@code m <= 0} * @see <a href="http://docs.oracle.com/javase/specs/jls/se7/html/jls-15.html#jls-15.17.3"> * Remainder Operator</a> */ @GwtIncompatible // TODO public static long mod(long x, long m) { if (m <= 0) { throw new ArithmeticException("Modulus must be positive"); } long result = x % m; return (result >= 0) ? result : result + m; } /** * Returns the greatest common divisor of {@code a, b}. Returns {@code 0} if {@code a == 0 && b == * 0}. * * @throws IllegalArgumentException if {@code a < 0} or {@code b < 0} */ public static long gcd(long a, long b) { /* * The reason we require both arguments to be >= 0 is because otherwise, what do you return on * gcd(0, Long.MIN_VALUE)? BigInteger.gcd would return positive 2^63, but positive 2^63 isn't an * int. */ checkNonNegative("a", a); checkNonNegative("b", b); if (a == 0) { // 0 % b == 0, so b divides a, but the converse doesn't hold. // BigInteger.gcd is consistent with this decision. return b; } else if (b == 0) { return a; // similar logic } /* * Uses the binary GCD algorithm; see http://en.wikipedia.org/wiki/Binary_GCD_algorithm. This is * >60% faster than the Euclidean algorithm in benchmarks. */ int aTwos = Long.numberOfTrailingZeros(a); a >>= aTwos; // divide out all 2s int bTwos = Long.numberOfTrailingZeros(b); b >>= bTwos; // divide out all 2s while (a != b) { // both a, b are odd // The key to the binary GCD algorithm is as follows: // Both a and b are odd. Assume a > b; then gcd(a - b, b) = gcd(a, b). // But in gcd(a - b, b), a - b is even and b is odd, so we can divide out powers of two. // We bend over backwards to avoid branching, adapting a technique from // http://graphics.stanford.edu/~seander/bithacks.html#IntegerMinOrMax long delta = a - b; // can't overflow, since a and b are nonnegative long minDeltaOrZero = delta & (delta >> (Long.SIZE - 1)); // equivalent to Math.min(delta, 0) a = delta - minDeltaOrZero - minDeltaOrZero; // sets a to Math.abs(a - b) // a is now nonnegative and even b += minDeltaOrZero; // sets b to min(old a, b) a >>= Long.numberOfTrailingZeros(a); // divide out all 2s, since 2 doesn't divide b } return a << min(aTwos, bTwos); } /** * Returns the sum of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a + b} overflows in signed {@code long} arithmetic */ @SuppressWarnings("ShortCircuitBoolean") public static long checkedAdd(long a, long b) { long result = a + b; checkNoOverflow((a ^ b) < 0 | (a ^ result) >= 0, "checkedAdd", a, b); return result; } /** * Returns the difference of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a - b} overflows in signed {@code long} arithmetic */ @GwtIncompatible // TODO @SuppressWarnings("ShortCircuitBoolean") public static long checkedSubtract(long a, long b) { long result = a - b; checkNoOverflow((a ^ b) >= 0 | (a ^ result) >= 0, "checkedSubtract", a, b); return result; } /** * Returns the product of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a * b} overflows in signed {@code long} arithmetic */ @SuppressWarnings("ShortCircuitBoolean") public static long checkedMultiply(long a, long b) { // Hacker's Delight, Section 2-12 int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a) + Long.numberOfLeadingZeros(b) + Long.numberOfLeadingZeros(~b); /* * If leadingZeros > Long.SIZE + 1 it's definitely fine, if it's < Long.SIZE it's definitely * bad. We do the leadingZeros check to avoid the division below if at all possible. * * Otherwise, if b == Long.MIN_VALUE, then the only allowed values of a are 0 and 1. We take * care of all a < 0 with their own check, because in particular, the case a == -1 will * incorrectly pass the division check below. * * In all other cases, we check that either a is 0 or the result is consistent with division. */ if (leadingZeros > Long.SIZE + 1) { return a * b; } checkNoOverflow(leadingZeros >= Long.SIZE, "checkedMultiply", a, b); checkNoOverflow(a >= 0 | b != Long.MIN_VALUE, "checkedMultiply", a, b); long result = a * b; checkNoOverflow(a == 0 || result / a == b, "checkedMultiply", a, b); return result; } /** * Returns the {@code b} to the {@code k}th power, provided it does not overflow. * * @throws ArithmeticException if {@code b} to the {@code k}th power overflows in signed {@code * long} arithmetic */ @GwtIncompatible // TODO @SuppressWarnings("ShortCircuitBoolean") public static long checkedPow(long b, int k) { checkNonNegative("exponent", k); if (b >= -2 & b <= 2) { switch ((int) b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: checkNoOverflow(k < Long.SIZE - 1, "checkedPow", b, k); return 1L << k; case (-2): checkNoOverflow(k < Long.SIZE, "checkedPow", b, k); return ((k & 1) == 0) ? (1L << k) : (-1L << k); default: throw new AssertionError(); } } long accum = 1; while (true) { switch (k) { case 0: return accum; case 1: return checkedMultiply(accum, b); default: if ((k & 1) != 0) { accum = checkedMultiply(accum, b); } k >>= 1; if (k > 0) { checkNoOverflow( -FLOOR_SQRT_MAX_LONG <= b && b <= FLOOR_SQRT_MAX_LONG, "checkedPow", b, k); b *= b; } } } } /** * Returns the sum of {@code a} and {@code b} unless it would overflow or underflow in which case * {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively. * * @since 20.0 */ @SuppressWarnings("ShortCircuitBoolean") public static long saturatedAdd(long a, long b) { long naiveSum = a + b; if ((a ^ b) < 0 | (a ^ naiveSum) >= 0) { // If a and b have different signs or a has the same sign as the result then there was no // overflow, return. return naiveSum; } // we did over/under flow, if the sign is negative we should return MAX otherwise MIN return Long.MAX_VALUE + ((naiveSum >>> (Long.SIZE - 1)) ^ 1); } /** * Returns the difference of {@code a} and {@code b} unless it would overflow or underflow in * which case {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively. * * @since 20.0 */ @SuppressWarnings("ShortCircuitBoolean") public static long saturatedSubtract(long a, long b) { long naiveDifference = a - b; if ((a ^ b) >= 0 | (a ^ naiveDifference) >= 0) { // If a and b have the same signs or a has the same sign as the result then there was no // overflow, return. return naiveDifference; } // we did over/under flow return Long.MAX_VALUE + ((naiveDifference >>> (Long.SIZE - 1)) ^ 1); } /** * Returns the product of {@code a} and {@code b} unless it would overflow or underflow in which * case {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively. * * @since 20.0 */ @SuppressWarnings("ShortCircuitBoolean") public static long saturatedMultiply(long a, long b) { // see checkedMultiply for explanation int leadingZeros = Long.numberOfLeadingZeros(a) + Long.numberOfLeadingZeros(~a) + Long.numberOfLeadingZeros(b) + Long.numberOfLeadingZeros(~b); if (leadingZeros > Long.SIZE + 1) { return a * b; } // the return value if we will overflow (which we calculate by overflowing a long :) ) long limit = Long.MAX_VALUE + ((a ^ b) >>> (Long.SIZE - 1)); if (leadingZeros < Long.SIZE | (a < 0 & b == Long.MIN_VALUE)) { // overflow return limit; } long result = a * b; if (a == 0 || result / a == b) { return result; } return limit; } /** * Returns the {@code b} to the {@code k}th power, unless it would overflow or underflow in which * case {@code Long.MAX_VALUE} or {@code Long.MIN_VALUE} is returned, respectively. * * @since 20.0 */ @SuppressWarnings("ShortCircuitBoolean") public static long saturatedPow(long b, int k) { checkNonNegative("exponent", k); if (b >= -2 & b <= 2) { switch ((int) b) { case 0: return (k == 0) ? 1 : 0; case 1: return 1; case (-1): return ((k & 1) == 0) ? 1 : -1; case 2: if (k >= Long.SIZE - 1) { return Long.MAX_VALUE; } return 1L << k; case (-2): if (k >= Long.SIZE) { return Long.MAX_VALUE + (k & 1); } return ((k & 1) == 0) ? (1L << k) : (-1L << k); default: throw new AssertionError(); } } long accum = 1; // if b is negative and k is odd then the limit is MIN otherwise the limit is MAX long limit = Long.MAX_VALUE + ((b >>> (Long.SIZE - 1)) & (k & 1)); while (true) { switch (k) { case 0: return accum; case 1: return saturatedMultiply(accum, b); default: if ((k & 1) != 0) { accum = saturatedMultiply(accum, b); } k >>= 1; if (k > 0) { if (-FLOOR_SQRT_MAX_LONG > b | b > FLOOR_SQRT_MAX_LONG) { return limit; } b *= b; } } } } @VisibleForTesting static final long FLOOR_SQRT_MAX_LONG = 3037000499L; /** * Returns {@code n!}, that is, the product of the first {@code n} positive integers, {@code 1} if * {@code n == 0}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}. * * @throws IllegalArgumentException if {@code n < 0} */ @GwtIncompatible // TODO public static long factorial(int n) { checkNonNegative("n", n); return (n < factorials.length) ? factorials[n] : Long.MAX_VALUE; } static final long[] factorials = { 1L, 1L, 1L * 2, 1L * 2 * 3, 1L * 2 * 3 * 4, 1L * 2 * 3 * 4 * 5, 1L * 2 * 3 * 4 * 5 * 6, 1L * 2 * 3 * 4 * 5 * 6 * 7, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19, 1L * 2 * 3 * 4 * 5 * 6 * 7 * 8 * 9 * 10 * 11 * 12 * 13 * 14 * 15 * 16 * 17 * 18 * 19 * 20 }; /** * Returns {@code n} choose {@code k}, also known as the binomial coefficient of {@code n} and * {@code k}, or {@link Long#MAX_VALUE} if the result does not fit in a {@code long}. * * @throws IllegalArgumentException if {@code n < 0}, {@code k < 0}, or {@code k > n} */ public static long binomial(int n, int k) { checkNonNegative("n", n); checkNonNegative("k", k); checkArgument(k <= n, "k (%s) > n (%s)", k, n); if (k > (n >> 1)) { k = n - k; } switch (k) { case 0: return 1; case 1: return n; default: if (n < factorials.length) { return factorials[n] / (factorials[k] * factorials[n - k]); } else if (k >= biggestBinomials.length || n > biggestBinomials[k]) { return Long.MAX_VALUE; } else if (k < biggestSimpleBinomials.length && n <= biggestSimpleBinomials[k]) { // guaranteed not to overflow long result = n--; for (int i = 2; i <= k; n--, i++) { result *= n; result /= i; } return result; } else { int nBits = LongMath.log2(n, RoundingMode.CEILING); long result = 1; long numerator = n--; long denominator = 1; int numeratorBits = nBits; // This is an upper bound on log2(numerator, ceiling). /* * We want to do this in long math for speed, but want to avoid overflow. We adapt the * technique previously used by BigIntegerMath: maintain separate numerator and * denominator accumulators, multiplying the fraction into result when near overflow. */ for (int i = 2; i <= k; i++, n--) { if (numeratorBits + nBits < Long.SIZE - 1) { // It's definitely safe to multiply into numerator and denominator. numerator *= n; denominator *= i; numeratorBits += nBits; } else { // It might not be safe to multiply into numerator and denominator, // so multiply (numerator / denominator) into result. result = multiplyFraction(result, numerator, denominator); numerator = n; denominator = i; numeratorBits = nBits; } } return multiplyFraction(result, numerator, denominator); } } } /** Returns (x * numerator / denominator), which is assumed to come out to an integral value. */ static long multiplyFraction(long x, long numerator, long denominator) { if (x == 1) { return numerator / denominator; } long commonDivisor = gcd(x, denominator); x /= commonDivisor; denominator /= commonDivisor; // We know gcd(x, denominator) = 1, and x * numerator / denominator is exact, // so denominator must be a divisor of numerator. return x * (numerator / denominator); } /* * binomial(biggestBinomials[k], k) fits in a long, but not binomial(biggestBinomials[k] + 1, k). */ static final int[] biggestBinomials = { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 3810779, 121977, 16175, 4337, 1733, 887, 534, 361, 265, 206, 169, 143, 125, 111, 101, 94, 88, 83, 79, 76, 74, 72, 70, 69, 68, 67, 67, 66, 66, 66, 66 }; /* * binomial(biggestSimpleBinomials[k], k) doesn't need to use the slower GCD-based impl, but * binomial(biggestSimpleBinomials[k] + 1, k) does. */ @VisibleForTesting static final int[] biggestSimpleBinomials = { Integer.MAX_VALUE, Integer.MAX_VALUE, Integer.MAX_VALUE, 2642246, 86251, 11724, 3218, 1313, 684, 419, 287, 214, 169, 139, 119, 105, 95, 87, 81, 76, 73, 70, 68, 66, 64, 63, 62, 62, 61, 61, 61 }; // These values were generated by using checkedMultiply to see when the simple multiply/divide // algorithm would lead to an overflow. static boolean fitsInInt(long x) { return (int) x == x; } /** * Returns the arithmetic mean of {@code x} and {@code y}, rounded toward negative infinity. This * method is resilient to overflow. * * @since 14.0 */ public static long mean(long x, long y) { // Efficient method for computing the arithmetic mean. // The alternative (x + y) / 2 fails for large values. // The alternative (x + y) >>> 1 fails for negative values. return (x & y) + ((x ^ y) >> 1); } /* * This bitmask is used as an optimization for cheaply testing for divisibility by 2, 3, or 5. * Each bit is set to 1 for all remainders that indicate divisibility by 2, 3, or 5, so * 1, 7, 11, 13, 17, 19, 23, 29 are set to 0. 30 and up don't matter because they won't be hit. */ private static final int SIEVE_30 = ~((1 << 1) | (1 << 7) | (1 << 11) | (1 << 13) | (1 << 17) | (1 << 19) | (1 << 23) | (1 << 29)); /** * Returns {@code true} if {@code n} is a <a * href="http://mathworld.wolfram.com/PrimeNumber.html">prime number</a>: an integer <i>greater * than one</i> that cannot be factored into a product of <i>smaller</i> positive integers. * Returns {@code false} if {@code n} is zero, one, or a composite number (one which <i>can</i> be * factored into smaller positive integers). * * <p>To test larger numbers, use {@link BigInteger#isProbablePrime}. * * @throws IllegalArgumentException if {@code n} is negative * @since 20.0 */ @GwtIncompatible // TODO public static boolean isPrime(long n) { if (n < 2) { checkNonNegative("n", n); return false; } if (n < 66) { // Encode all primes less than 66 into mask without 0 and 1. long mask = (1L << (2 - 2)) | (1L << (3 - 2)) | (1L << (5 - 2)) | (1L << (7 - 2)) | (1L << (11 - 2)) | (1L << (13 - 2)) | (1L << (17 - 2)) | (1L << (19 - 2)) | (1L << (23 - 2)) | (1L << (29 - 2)) | (1L << (31 - 2)) | (1L << (37 - 2)) | (1L << (41 - 2)) | (1L << (43 - 2)) | (1L << (47 - 2)) | (1L << (53 - 2)) | (1L << (59 - 2)) | (1L << (61 - 2)); // Look up n within the mask. return ((mask >> ((int) n - 2)) & 1) != 0; } if ((SIEVE_30 & (1 << (n % 30))) != 0) { return false; } if (n % 7 == 0 || n % 11 == 0 || n % 13 == 0) { return false; } if (n < 17 * 17) { return true; } for (long[] baseSet : millerRabinBaseSets) { if (n <= baseSet[0]) { for (int i = 1; i < baseSet.length; i++) { if (!MillerRabinTester.test(baseSet[i], n)) { return false; } } return true; } } throw new AssertionError(); } /* * If n <= millerRabinBases[i][0], then testing n against bases millerRabinBases[i][1..] suffices * to prove its primality. Values from miller-rabin.appspot.com. * * NOTE: We could get slightly better bases that would be treated as unsigned, but benchmarks * showed negligible performance improvements. */ private static final long[][] millerRabinBaseSets = { {291830, 126401071349994536L}, {885594168, 725270293939359937L, 3569819667048198375L}, {273919523040L, 15, 7363882082L, 992620450144556L}, {47636622961200L, 2, 2570940, 211991001, 3749873356L}, { 7999252175582850L, 2, 4130806001517L, 149795463772692060L, 186635894390467037L, 3967304179347715805L }, { 585226005592931976L, 2, 123635709730000L, 9233062284813009L, 43835965440333360L, 761179012939631437L, 1263739024124850375L }, {Long.MAX_VALUE, 2, 325, 9375, 28178, 450775, 9780504, 1795265022} }; private enum MillerRabinTester { /** Works for inputs ≤ FLOOR_SQRT_MAX_LONG. */ SMALL { @Override long mulMod(long a, long b, long m) { /* * lowasser, 2015-Feb-12: Benchmarks suggest that changing this to UnsignedLongs.remainder * and increasing the threshold to 2^32 doesn't pay for itself, and adding another enum * constant hurts performance further -- I suspect because bimorphic implementation is a * sweet spot for the JVM. */ return (a * b) % m; } @Override long squareMod(long a, long m) { return (a * a) % m; } }, /** Works for all nonnegative signed longs. */ LARGE { /** Returns (a + b) mod m. Precondition: {@code 0 <= a}, {@code b < m < 2^63}. */ private long plusMod(long a, long b, long m) { return (a >= m - b) ? (a + b - m) : (a + b); } /** Returns (a * 2^32) mod m. a may be any unsigned long. */ private long times2ToThe32Mod(long a, long m) { int remainingPowersOf2 = 32; do { int shift = min(remainingPowersOf2, Long.numberOfLeadingZeros(a)); // shift is either the number of powers of 2 left to multiply a by, or the biggest shift // possible while keeping a in an unsigned long. a = UnsignedLongs.remainder(a << shift, m); remainingPowersOf2 -= shift; } while (remainingPowersOf2 > 0); return a; } @Override long mulMod(long a, long b, long m) { long aHi = a >>> 32; // < 2^31 long bHi = b >>> 32; // < 2^31 long aLo = a & 0xFFFFFFFFL; // < 2^32 long bLo = b & 0xFFFFFFFFL; // < 2^32 /* * a * b == aHi * bHi * 2^64 + (aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo. * == (aHi * bHi * 2^32 + aHi * bLo + aLo * bHi) * 2^32 + aLo * bLo * * We carry out this computation in modular arithmetic. Since times2ToThe32Mod accepts any * unsigned long, we don't have to do a mod on every operation, only when intermediate * results can exceed 2^63. */ long result = times2ToThe32Mod(aHi * bHi /* < 2^62 */, m); // < m < 2^63 result += aHi * bLo; // aHi * bLo < 2^63, result < 2^64 if (result < 0) { result = UnsignedLongs.remainder(result, m); } // result < 2^63 again result += aLo * bHi; // aLo * bHi < 2^63, result < 2^64 result = times2ToThe32Mod(result, m); // result < m < 2^63 return plusMod(result, UnsignedLongs.remainder(aLo * bLo /* < 2^64 */, m), m); } @Override long squareMod(long a, long m) { long aHi = a >>> 32; // < 2^31 long aLo = a & 0xFFFFFFFFL; // < 2^32 /* * a^2 == aHi^2 * 2^64 + aHi * aLo * 2^33 + aLo^2 * == (aHi^2 * 2^32 + aHi * aLo * 2) * 2^32 + aLo^2 * We carry out this computation in modular arithmetic. Since times2ToThe32Mod accepts any * unsigned long, we don't have to do a mod on every operation, only when intermediate * results can exceed 2^63. */ long result = times2ToThe32Mod(aHi * aHi /* < 2^62 */, m); // < m < 2^63 long hiLo = aHi * aLo * 2; if (hiLo < 0) { hiLo = UnsignedLongs.remainder(hiLo, m); } // hiLo < 2^63 result += hiLo; // result < 2^64 result = times2ToThe32Mod(result, m); // result < m < 2^63 return plusMod(result, UnsignedLongs.remainder(aLo * aLo /* < 2^64 */, m), m); } }; static boolean test(long base, long n) { // Since base will be considered % n, it's okay if base > FLOOR_SQRT_MAX_LONG, // so long as n <= FLOOR_SQRT_MAX_LONG. return ((n <= FLOOR_SQRT_MAX_LONG) ? SMALL : LARGE).testWitness(base, n); } /** Returns a * b mod m. */ abstract long mulMod(long a, long b, long m); /** Returns a^2 mod m. */ abstract long squareMod(long a, long m); /** Returns a^p mod m. */ private long powMod(long a, long p, long m) { long res = 1; for (; p != 0; p >>= 1) { if ((p & 1) != 0) { res = mulMod(res, a, m); } a = squareMod(a, m); } return res; } /** Returns true if n is a strong probable prime relative to the specified base. */ private boolean testWitness(long base, long n) { int r = Long.numberOfTrailingZeros(n - 1); long d = (n - 1) >> r; base %= n; if (base == 0) { return true; } // Calculate a := base^d mod n. long a = powMod(base, d, n); // n passes this test if // base^d = 1 (mod n) // or base^(2^j * d) = -1 (mod n) for some 0 <= j < r. if (a == 1) { return true; } int j = 0; while (a != n - 1) { if (++j == r) { return false; } a = squareMod(a, n); } return true; } } /** * Returns {@code x}, rounded to a {@code double} with the specified rounding mode. If {@code x} * is precisely representable as a {@code double}, its {@code double} value will be returned; * otherwise, the rounding will choose between the two nearest representable values with {@code * mode}. * * <p>For the case of {@link RoundingMode#HALF_EVEN}, this implementation uses the IEEE 754 * default rounding mode: if the two nearest representable values are equally near, the one with * the least significant bit zero is chosen. (In such cases, both of the nearest representable * values are even integers; this method returns the one that is a multiple of a greater power of * two.) * * @throws ArithmeticException if {@code mode} is {@link RoundingMode#UNNECESSARY} and {@code x} * is not precisely representable as a {@code double} * @since 30.0 */ @SuppressWarnings("deprecation") @GwtIncompatible public static double roundToDouble(long x, RoundingMode mode) { // Logic adapted from ToDoubleRounder. double roundArbitrarily = (double) x; long roundArbitrarilyAsLong = (long) roundArbitrarily; int cmpXToRoundArbitrarily; if (roundArbitrarilyAsLong == Long.MAX_VALUE) { /* * For most values, the conversion from roundArbitrarily to roundArbitrarilyAsLong is * lossless. In that case we can compare x to roundArbitrarily using Longs.compare(x, * roundArbitrarilyAsLong). The exception is for values where the conversion to double rounds * up to give roundArbitrarily equal to 2^63, so the conversion back to long overflows and * roundArbitrarilyAsLong is Long.MAX_VALUE. (This is the only way this condition can occur as * otherwise the conversion back to long pads with zero bits.) In this case we know that * roundArbitrarily > x. (This is important when x == Long.MAX_VALUE == * roundArbitrarilyAsLong.) */ cmpXToRoundArbitrarily = -1; } else { cmpXToRoundArbitrarily = Longs.compare(x, roundArbitrarilyAsLong); } switch (mode) { case UNNECESSARY: checkRoundingUnnecessary(cmpXToRoundArbitrarily == 0); return roundArbitrarily; case FLOOR: return (cmpXToRoundArbitrarily >= 0) ? roundArbitrarily : DoubleUtils.nextDown(roundArbitrarily); case CEILING: return (cmpXToRoundArbitrarily <= 0) ? roundArbitrarily : Math.nextUp(roundArbitrarily); case DOWN: if (x >= 0) { return (cmpXToRoundArbitrarily >= 0) ? roundArbitrarily : DoubleUtils.nextDown(roundArbitrarily); } else { return (cmpXToRoundArbitrarily <= 0) ? roundArbitrarily : Math.nextUp(roundArbitrarily); } case UP: if (x >= 0) { return (cmpXToRoundArbitrarily <= 0) ? roundArbitrarily : Math.nextUp(roundArbitrarily); } else { return (cmpXToRoundArbitrarily >= 0) ? roundArbitrarily : DoubleUtils.nextDown(roundArbitrarily); } case HALF_DOWN: case HALF_UP: case HALF_EVEN: { long roundFloor; double roundFloorAsDouble; long roundCeiling; double roundCeilingAsDouble; if (cmpXToRoundArbitrarily >= 0) { roundFloorAsDouble = roundArbitrarily; roundFloor = roundArbitrarilyAsLong; roundCeilingAsDouble = Math.nextUp(roundArbitrarily); roundCeiling = (long) Math.ceil(roundCeilingAsDouble); } else { roundCeilingAsDouble = roundArbitrarily; roundCeiling = roundArbitrarilyAsLong; roundFloorAsDouble = DoubleUtils.nextDown(roundArbitrarily); roundFloor = (long) Math.floor(roundFloorAsDouble); } long deltaToFloor = x - roundFloor; long deltaToCeiling = roundCeiling - x; if (roundCeiling == Long.MAX_VALUE) { // correct for Long.MAX_VALUE as discussed above: roundCeilingAsDouble must be 2^63, but // roundCeiling is 2^63-1. deltaToCeiling++; } int diff = Longs.compare(deltaToFloor, deltaToCeiling); if (diff < 0) { // closer to floor return roundFloorAsDouble; } else if (diff > 0) { // closer to ceiling return roundCeilingAsDouble; } // halfway between the representable values; do the half-whatever logic switch (mode) { case HALF_EVEN: return ((DoubleUtils.getSignificand(roundFloorAsDouble) & 1L) == 0) ? roundFloorAsDouble : roundCeilingAsDouble; case HALF_DOWN: return (x >= 0) ? roundFloorAsDouble : roundCeilingAsDouble; case HALF_UP: return (x >= 0) ? roundCeilingAsDouble : roundFloorAsDouble; default: throw new AssertionError("impossible"); } } } throw new AssertionError("impossible"); } private LongMath() {} }
google/guava
android/guava/src/com/google/common/math/LongMath.java
357
/* * 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.io; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import static com.google.common.base.Preconditions.checkState; import static com.google.common.math.IntMath.divide; import static com.google.common.math.IntMath.log2; import static java.math.RoundingMode.CEILING; import static java.math.RoundingMode.FLOOR; import static java.math.RoundingMode.UNNECESSARY; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Ascii; import com.google.errorprone.annotations.concurrent.LazyInit; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.Arrays; import java.util.Objects; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A binary encoding scheme for reversibly translating between byte sequences and printable ASCII * strings. This class includes several constants for encoding schemes specified by <a * href="http://tools.ietf.org/html/rfc4648">RFC 4648</a>. For example, the expression: * * <pre>{@code * BaseEncoding.base32().encode("foo".getBytes(Charsets.US_ASCII)) * }</pre> * * <p>returns the string {@code "MZXW6==="}, and * * <pre>{@code * byte[] decoded = BaseEncoding.base32().decode("MZXW6==="); * }</pre> * * <p>...returns the ASCII bytes of the string {@code "foo"}. * * <p>By default, {@code BaseEncoding}'s behavior is relatively strict and in accordance with RFC * 4648. Decoding rejects characters in the wrong case, though padding is optional. To modify * encoding and decoding behavior, use configuration methods to obtain a new encoding with modified * behavior: * * <pre>{@code * BaseEncoding.base16().lowerCase().decode("deadbeef"); * }</pre> * * <p>Warning: BaseEncoding instances are immutable. Invoking a configuration method has no effect * on the receiving instance; you must store and use the new encoding instance it returns, instead. * * <pre>{@code * // Do NOT do this * BaseEncoding hex = BaseEncoding.base16(); * hex.lowerCase(); // does nothing! * return hex.decode("deadbeef"); // throws an IllegalArgumentException * }</pre> * * <p>It is guaranteed that {@code encoding.decode(encoding.encode(x))} is always equal to {@code * x}, but the reverse does not necessarily hold. * * <table> * <caption>Encodings</caption> * <tr> * <th>Encoding * <th>Alphabet * <th>{@code char:byte} ratio * <th>Default padding * <th>Comments * <tr> * <td>{@link #base16()} * <td>0-9 A-F * <td>2.00 * <td>N/A * <td>Traditional hexadecimal. Defaults to upper case. * <tr> * <td>{@link #base32()} * <td>A-Z 2-7 * <td>1.60 * <td>= * <td>Human-readable; no possibility of mixing up 0/O or 1/I. Defaults to upper case. * <tr> * <td>{@link #base32Hex()} * <td>0-9 A-V * <td>1.60 * <td>= * <td>"Numerical" base 32; extended from the traditional hex alphabet. Defaults to upper case. * <tr> * <td>{@link #base64()} * <td>A-Z a-z 0-9 + / * <td>1.33 * <td>= * <td> * <tr> * <td>{@link #base64Url()} * <td>A-Z a-z 0-9 - _ * <td>1.33 * <td>= * <td>Safe to use as filenames, or to pass in URLs without escaping * </table> * * <p>All instances of this class are immutable, so they may be stored safely as static constants. * * @author Louis Wasserman * @since 14.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public abstract class BaseEncoding { // TODO(lowasser): consider making encodeTo(Appendable, byte[], int, int) public. BaseEncoding() {} /** * Exception indicating invalid base-encoded input encountered while decoding. * * @author Louis Wasserman * @since 15.0 */ public static final class DecodingException extends IOException { DecodingException(@Nullable String message) { super(message); } } /** Encodes the specified byte array, and returns the encoded {@code String}. */ public String encode(byte[] bytes) { return encode(bytes, 0, bytes.length); } /** * Encodes the specified range of the specified byte array, and returns the encoded {@code * String}. */ public final String encode(byte[] bytes, int off, int len) { checkPositionIndexes(off, off + len, bytes.length); StringBuilder result = new StringBuilder(maxEncodedSize(len)); try { encodeTo(result, bytes, off, len); } catch (IOException impossible) { throw new AssertionError(impossible); } return result.toString(); } /** * Returns an {@code OutputStream} that encodes bytes using this encoding into the specified * {@code Writer}. When the returned {@code OutputStream} is closed, so is the backing {@code * Writer}. */ @J2ktIncompatible @GwtIncompatible // Writer,OutputStream public abstract OutputStream encodingStream(Writer writer); /** * Returns a {@code ByteSink} that writes base-encoded bytes to the specified {@code CharSink}. */ @J2ktIncompatible @GwtIncompatible // ByteSink,CharSink public final ByteSink encodingSink(CharSink encodedSink) { checkNotNull(encodedSink); return new ByteSink() { @Override public OutputStream openStream() throws IOException { return encodingStream(encodedSink.openStream()); } }; } // TODO(lowasser): document the extent of leniency, probably after adding ignore(CharMatcher) private static byte[] extract(byte[] result, int length) { if (length == result.length) { return result; } byte[] trunc = new byte[length]; System.arraycopy(result, 0, trunc, 0, length); return trunc; } /** * Determines whether the specified character sequence is a valid encoded string according to this * encoding. * * @since 20.0 */ public abstract boolean canDecode(CharSequence chars); /** * Decodes the specified character sequence, and returns the resulting {@code byte[]}. This is the * inverse operation to {@link #encode(byte[])}. * * @throws IllegalArgumentException if the input is not a valid encoded string according to this * encoding. */ public final byte[] decode(CharSequence chars) { try { return decodeChecked(chars); } catch (DecodingException badInput) { throw new IllegalArgumentException(badInput); } } /** * Decodes the specified character sequence, and returns the resulting {@code byte[]}. This is the * inverse operation to {@link #encode(byte[])}. * * @throws DecodingException if the input is not a valid encoded string according to this * encoding. */ final byte[] decodeChecked(CharSequence chars) throws DecodingException { chars = trimTrailingPadding(chars); byte[] tmp = new byte[maxDecodedSize(chars.length())]; int len = decodeTo(tmp, chars); return extract(tmp, len); } /** * Returns an {@code InputStream} that decodes base-encoded input from the specified {@code * Reader}. The returned stream throws a {@link DecodingException} upon decoding-specific errors. */ @J2ktIncompatible @GwtIncompatible // Reader,InputStream public abstract InputStream decodingStream(Reader reader); /** * Returns a {@code ByteSource} that reads base-encoded bytes from the specified {@code * CharSource}. */ @J2ktIncompatible @GwtIncompatible // ByteSource,CharSource public final ByteSource decodingSource(CharSource encodedSource) { checkNotNull(encodedSource); return new ByteSource() { @Override public InputStream openStream() throws IOException { return decodingStream(encodedSource.openStream()); } }; } // Implementations for encoding/decoding abstract int maxEncodedSize(int bytes); abstract void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException; abstract int maxDecodedSize(int chars); abstract int decodeTo(byte[] target, CharSequence chars) throws DecodingException; CharSequence trimTrailingPadding(CharSequence chars) { return checkNotNull(chars); } // Modified encoding generators /** * Returns an encoding that behaves equivalently to this encoding, but omits any padding * characters as specified by <a href="http://tools.ietf.org/html/rfc4648#section-3.2">RFC 4648 * section 3.2</a>, Padding of Encoded Data. */ public abstract BaseEncoding omitPadding(); /** * Returns an encoding that behaves equivalently to this encoding, but uses an alternate character * for padding. * * @throws IllegalArgumentException if this padding character is already used in the alphabet or a * separator */ public abstract BaseEncoding withPadChar(char padChar); /** * Returns an encoding that behaves equivalently to this encoding, but adds a separator string * after every {@code n} characters. Any occurrences of any characters that occur in the separator * are skipped over in decoding. * * @throws IllegalArgumentException if any alphabet or padding characters appear in the separator * string, or if {@code n <= 0} * @throws UnsupportedOperationException if this encoding already uses a separator */ public abstract BaseEncoding withSeparator(String separator, int n); /** * Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with * uppercase letters. Padding and separator characters remain in their original case. * * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and * lower-case characters */ public abstract BaseEncoding upperCase(); /** * Returns an encoding that behaves equivalently to this encoding, but encodes and decodes with * lowercase letters. Padding and separator characters remain in their original case. * * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and * lower-case characters */ public abstract BaseEncoding lowerCase(); /** * Returns an encoding that behaves equivalently to this encoding, but decodes letters without * regard to case. * * @throws IllegalStateException if the alphabet used by this encoding contains mixed upper- and * lower-case characters * @since 32.0.0 */ public abstract BaseEncoding ignoreCase(); private static final BaseEncoding BASE64 = new Base64Encoding( "base64()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/", '='); /** * The "base64" base encoding specified by <a * href="http://tools.ietf.org/html/rfc4648#section-4">RFC 4648 section 4</a>, Base 64 Encoding. * (This is the same as the base 64 encoding from <a * href="http://tools.ietf.org/html/rfc3548#section-3">RFC 3548</a>.) * * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding() * omitted} or {@linkplain #withPadChar(char) replaced}. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base64() { return BASE64; } private static final BaseEncoding BASE64_URL = new Base64Encoding( "base64Url()", "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_", '='); /** * The "base64url" encoding specified by <a * href="http://tools.ietf.org/html/rfc4648#section-5">RFC 4648 section 5</a>, Base 64 Encoding * with URL and Filename Safe Alphabet, also sometimes referred to as the "web safe Base64." (This * is the same as the base 64 encoding with URL and filename safe alphabet from <a * href="http://tools.ietf.org/html/rfc3548#section-4">RFC 3548</a>.) * * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding() * omitted} or {@linkplain #withPadChar(char) replaced}. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base64Url() { return BASE64_URL; } private static final BaseEncoding BASE32 = new StandardBaseEncoding("base32()", "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567", '='); /** * The "base32" encoding specified by <a href="http://tools.ietf.org/html/rfc4648#section-6">RFC * 4648 section 6</a>, Base 32 Encoding. (This is the same as the base 32 encoding from <a * href="http://tools.ietf.org/html/rfc3548#section-5">RFC 3548</a>.) * * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding() * omitted} or {@linkplain #withPadChar(char) replaced}. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base32() { return BASE32; } private static final BaseEncoding BASE32_HEX = new StandardBaseEncoding("base32Hex()", "0123456789ABCDEFGHIJKLMNOPQRSTUV", '='); /** * The "base32hex" encoding specified by <a * href="http://tools.ietf.org/html/rfc4648#section-7">RFC 4648 section 7</a>, Base 32 Encoding * with Extended Hex Alphabet. There is no corresponding encoding in RFC 3548. * * <p>The character {@code '='} is used for padding, but can be {@linkplain #omitPadding() * omitted} or {@linkplain #withPadChar(char) replaced}. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base32Hex() { return BASE32_HEX; } private static final BaseEncoding BASE16 = new Base16Encoding("base16()", "0123456789ABCDEF"); /** * The "base16" encoding specified by <a href="http://tools.ietf.org/html/rfc4648#section-8">RFC * 4648 section 8</a>, Base 16 Encoding. (This is the same as the base 16 encoding from <a * href="http://tools.ietf.org/html/rfc3548#section-6">RFC 3548</a>.) This is commonly known as * "hexadecimal" format. * * <p>No padding is necessary in base 16, so {@link #withPadChar(char)} and {@link #omitPadding()} * have no effect. * * <p>No line feeds are added by default, as per <a * href="http://tools.ietf.org/html/rfc4648#section-3.1">RFC 4648 section 3.1</a>, Line Feeds in * Encoded Data. Line feeds may be added using {@link #withSeparator(String, int)}. */ public static BaseEncoding base16() { return BASE16; } static final class Alphabet { private final String name; // this is meant to be immutable -- don't modify it! private final char[] chars; final int mask; final int bitsPerChar; final int charsPerChunk; final int bytesPerChunk; private final byte[] decodabet; private final boolean[] validPadding; private final boolean ignoreCase; Alphabet(String name, char[] chars) { this(name, chars, decodabetFor(chars), /* ignoreCase= */ false); } private Alphabet(String name, char[] chars, byte[] decodabet, boolean ignoreCase) { this.name = checkNotNull(name); this.chars = checkNotNull(chars); try { this.bitsPerChar = log2(chars.length, UNNECESSARY); } catch (ArithmeticException e) { throw new IllegalArgumentException("Illegal alphabet length " + chars.length, e); } // Compute how input bytes are chunked. For example, with base64 we chunk every 3 bytes into // 4 characters. We have bitsPerChar == 6, charsPerChunk == 4, and bytesPerChunk == 3. // We're looking for the smallest charsPerChunk such that bitsPerChar * charsPerChunk is a // multiple of 8. A multiple of 8 has 3 low zero bits, so we just need to figure out how many // extra zero bits we need to add to the end of bitsPerChar to get 3 in total. // The logic here would be wrong for bitsPerChar > 8, but since we require distinct ASCII // characters that can't happen. int zeroesInBitsPerChar = Integer.numberOfTrailingZeros(bitsPerChar); this.charsPerChunk = 1 << (3 - zeroesInBitsPerChar); this.bytesPerChunk = bitsPerChar >> zeroesInBitsPerChar; this.mask = chars.length - 1; this.decodabet = decodabet; boolean[] validPadding = new boolean[charsPerChunk]; for (int i = 0; i < bytesPerChunk; i++) { validPadding[divide(i * 8, bitsPerChar, CEILING)] = true; } this.validPadding = validPadding; this.ignoreCase = ignoreCase; } private static byte[] decodabetFor(char[] chars) { byte[] decodabet = new byte[Ascii.MAX + 1]; Arrays.fill(decodabet, (byte) -1); for (int i = 0; i < chars.length; i++) { char c = chars[i]; checkArgument(c < decodabet.length, "Non-ASCII character: %s", c); checkArgument(decodabet[c] == -1, "Duplicate character: %s", c); decodabet[c] = (byte) i; } return decodabet; } /** Returns an equivalent {@code Alphabet} except it ignores case. */ Alphabet ignoreCase() { if (ignoreCase) { return this; } // We can't use .clone() because of GWT. byte[] newDecodabet = Arrays.copyOf(decodabet, decodabet.length); for (int upper = 'A'; upper <= 'Z'; upper++) { int lower = upper | 0x20; byte decodeUpper = decodabet[upper]; byte decodeLower = decodabet[lower]; if (decodeUpper == -1) { newDecodabet[upper] = decodeLower; } else { checkState( decodeLower == -1, "Can't ignoreCase() since '%s' and '%s' encode different values", (char) upper, (char) lower); newDecodabet[lower] = decodeUpper; } } return new Alphabet(name + ".ignoreCase()", chars, newDecodabet, /* ignoreCase= */ true); } char encode(int bits) { return chars[bits]; } boolean isValidPaddingStartPosition(int index) { return validPadding[index % charsPerChunk]; } boolean canDecode(char ch) { return ch <= Ascii.MAX && decodabet[ch] != -1; } int decode(char ch) throws DecodingException { if (ch > Ascii.MAX) { throw new DecodingException("Unrecognized character: 0x" + Integer.toHexString(ch)); } int result = decodabet[ch]; if (result == -1) { if (ch <= 0x20 || ch == Ascii.MAX) { throw new DecodingException("Unrecognized character: 0x" + Integer.toHexString(ch)); } else { throw new DecodingException("Unrecognized character: " + ch); } } return result; } private boolean hasLowerCase() { for (char c : chars) { if (Ascii.isLowerCase(c)) { return true; } } return false; } private boolean hasUpperCase() { for (char c : chars) { if (Ascii.isUpperCase(c)) { return true; } } return false; } Alphabet upperCase() { if (!hasLowerCase()) { return this; } checkState(!hasUpperCase(), "Cannot call upperCase() on a mixed-case alphabet"); char[] upperCased = new char[chars.length]; for (int i = 0; i < chars.length; i++) { upperCased[i] = Ascii.toUpperCase(chars[i]); } Alphabet upperCase = new Alphabet(name + ".upperCase()", upperCased); return ignoreCase ? upperCase.ignoreCase() : upperCase; } Alphabet lowerCase() { if (!hasUpperCase()) { return this; } checkState(!hasLowerCase(), "Cannot call lowerCase() on a mixed-case alphabet"); char[] lowerCased = new char[chars.length]; for (int i = 0; i < chars.length; i++) { lowerCased[i] = Ascii.toLowerCase(chars[i]); } Alphabet lowerCase = new Alphabet(name + ".lowerCase()", lowerCased); return ignoreCase ? lowerCase.ignoreCase() : lowerCase; } public boolean matches(char c) { return c < decodabet.length && decodabet[c] != -1; } @Override public String toString() { return name; } @Override public boolean equals(@CheckForNull Object other) { if (other instanceof Alphabet) { Alphabet that = (Alphabet) other; return this.ignoreCase == that.ignoreCase && Arrays.equals(this.chars, that.chars); } return false; } @Override public int hashCode() { return Arrays.hashCode(chars) + (ignoreCase ? 1231 : 1237); } } private static class StandardBaseEncoding extends BaseEncoding { final Alphabet alphabet; @CheckForNull final Character paddingChar; StandardBaseEncoding(String name, String alphabetChars, @CheckForNull Character paddingChar) { this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar); } StandardBaseEncoding(Alphabet alphabet, @CheckForNull Character paddingChar) { this.alphabet = checkNotNull(alphabet); checkArgument( paddingChar == null || !alphabet.matches(paddingChar), "Padding character %s was already in alphabet", paddingChar); this.paddingChar = paddingChar; } @Override int maxEncodedSize(int bytes) { return alphabet.charsPerChunk * divide(bytes, alphabet.bytesPerChunk, CEILING); } @J2ktIncompatible @GwtIncompatible // Writer,OutputStream @Override public OutputStream encodingStream(Writer out) { checkNotNull(out); return new OutputStream() { int bitBuffer = 0; int bitBufferLength = 0; int writtenChars = 0; @Override public void write(int b) throws IOException { bitBuffer <<= 8; bitBuffer |= b & 0xFF; bitBufferLength += 8; while (bitBufferLength >= alphabet.bitsPerChar) { int charIndex = (bitBuffer >> (bitBufferLength - alphabet.bitsPerChar)) & alphabet.mask; out.write(alphabet.encode(charIndex)); writtenChars++; bitBufferLength -= alphabet.bitsPerChar; } } @Override public void flush() throws IOException { out.flush(); } @Override public void close() throws IOException { if (bitBufferLength > 0) { int charIndex = (bitBuffer << (alphabet.bitsPerChar - bitBufferLength)) & alphabet.mask; out.write(alphabet.encode(charIndex)); writtenChars++; if (paddingChar != null) { while (writtenChars % alphabet.charsPerChunk != 0) { out.write(paddingChar.charValue()); writtenChars++; } } } out.close(); } }; } @Override void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException { checkNotNull(target); checkPositionIndexes(off, off + len, bytes.length); for (int i = 0; i < len; i += alphabet.bytesPerChunk) { encodeChunkTo(target, bytes, off + i, Math.min(alphabet.bytesPerChunk, len - i)); } } void encodeChunkTo(Appendable target, byte[] bytes, int off, int len) throws IOException { checkNotNull(target); checkPositionIndexes(off, off + len, bytes.length); checkArgument(len <= alphabet.bytesPerChunk); long bitBuffer = 0; for (int i = 0; i < len; ++i) { bitBuffer |= bytes[off + i] & 0xFF; bitBuffer <<= 8; // Add additional zero byte in the end. } // Position of first character is length of bitBuffer minus bitsPerChar. int bitOffset = (len + 1) * 8 - alphabet.bitsPerChar; int bitsProcessed = 0; while (bitsProcessed < len * 8) { int charIndex = (int) (bitBuffer >>> (bitOffset - bitsProcessed)) & alphabet.mask; target.append(alphabet.encode(charIndex)); bitsProcessed += alphabet.bitsPerChar; } if (paddingChar != null) { while (bitsProcessed < alphabet.bytesPerChunk * 8) { target.append(paddingChar.charValue()); bitsProcessed += alphabet.bitsPerChar; } } } @Override int maxDecodedSize(int chars) { return (int) ((alphabet.bitsPerChar * (long) chars + 7L) / 8L); } @Override CharSequence trimTrailingPadding(CharSequence chars) { checkNotNull(chars); if (paddingChar == null) { return chars; } char padChar = paddingChar.charValue(); int l; for (l = chars.length() - 1; l >= 0; l--) { if (chars.charAt(l) != padChar) { break; } } return chars.subSequence(0, l + 1); } @Override public boolean canDecode(CharSequence chars) { checkNotNull(chars); chars = trimTrailingPadding(chars); if (!alphabet.isValidPaddingStartPosition(chars.length())) { return false; } for (int i = 0; i < chars.length(); i++) { if (!alphabet.canDecode(chars.charAt(i))) { return false; } } return true; } @Override int decodeTo(byte[] target, CharSequence chars) throws DecodingException { checkNotNull(target); chars = trimTrailingPadding(chars); if (!alphabet.isValidPaddingStartPosition(chars.length())) { throw new DecodingException("Invalid input length " + chars.length()); } int bytesWritten = 0; for (int charIdx = 0; charIdx < chars.length(); charIdx += alphabet.charsPerChunk) { long chunk = 0; int charsProcessed = 0; for (int i = 0; i < alphabet.charsPerChunk; i++) { chunk <<= alphabet.bitsPerChar; if (charIdx + i < chars.length()) { chunk |= alphabet.decode(chars.charAt(charIdx + charsProcessed++)); } } int minOffset = alphabet.bytesPerChunk * 8 - charsProcessed * alphabet.bitsPerChar; for (int offset = (alphabet.bytesPerChunk - 1) * 8; offset >= minOffset; offset -= 8) { target[bytesWritten++] = (byte) ((chunk >>> offset) & 0xFF); } } return bytesWritten; } @Override @J2ktIncompatible @GwtIncompatible // Reader,InputStream public InputStream decodingStream(Reader reader) { checkNotNull(reader); return new InputStream() { int bitBuffer = 0; int bitBufferLength = 0; int readChars = 0; boolean hitPadding = false; @Override public int read() throws IOException { while (true) { int readChar = reader.read(); if (readChar == -1) { if (!hitPadding && !alphabet.isValidPaddingStartPosition(readChars)) { throw new DecodingException("Invalid input length " + readChars); } return -1; } readChars++; char ch = (char) readChar; if (paddingChar != null && paddingChar.charValue() == ch) { if (!hitPadding && (readChars == 1 || !alphabet.isValidPaddingStartPosition(readChars - 1))) { throw new DecodingException("Padding cannot start at index " + readChars); } hitPadding = true; } else if (hitPadding) { throw new DecodingException( "Expected padding character but found '" + ch + "' at index " + readChars); } else { bitBuffer <<= alphabet.bitsPerChar; bitBuffer |= alphabet.decode(ch); bitBufferLength += alphabet.bitsPerChar; if (bitBufferLength >= 8) { bitBufferLength -= 8; return (bitBuffer >> bitBufferLength) & 0xFF; } } } } @Override public int read(byte[] buf, int off, int len) throws IOException { // Overriding this to work around the fact that InputStream's default implementation of // this method will silently swallow exceptions thrown by the single-byte read() method // (other than on the first call to it), which in this case can cause invalid encoded // strings to not throw an exception. // See https://github.com/google/guava/issues/3542 checkPositionIndexes(off, off + len, buf.length); int i = off; for (; i < off + len; i++) { int b = read(); if (b == -1) { int read = i - off; return read == 0 ? -1 : read; } buf[i] = (byte) b; } return i - off; } @Override public void close() throws IOException { reader.close(); } }; } @Override public BaseEncoding omitPadding() { return (paddingChar == null) ? this : newInstance(alphabet, null); } @Override public BaseEncoding withPadChar(char padChar) { if (8 % alphabet.bitsPerChar == 0 || (paddingChar != null && paddingChar.charValue() == padChar)) { return this; } else { return newInstance(alphabet, padChar); } } @Override public BaseEncoding withSeparator(String separator, int afterEveryChars) { for (int i = 0; i < separator.length(); i++) { checkArgument( !alphabet.matches(separator.charAt(i)), "Separator (%s) cannot contain alphabet characters", separator); } if (paddingChar != null) { checkArgument( separator.indexOf(paddingChar.charValue()) < 0, "Separator (%s) cannot contain padding character", separator); } return new SeparatedBaseEncoding(this, separator, afterEveryChars); } @LazyInit @CheckForNull private volatile BaseEncoding upperCase; @LazyInit @CheckForNull private volatile BaseEncoding lowerCase; @LazyInit @CheckForNull private volatile BaseEncoding ignoreCase; @Override public BaseEncoding upperCase() { BaseEncoding result = upperCase; if (result == null) { Alphabet upper = alphabet.upperCase(); result = upperCase = (upper == alphabet) ? this : newInstance(upper, paddingChar); } return result; } @Override public BaseEncoding lowerCase() { BaseEncoding result = lowerCase; if (result == null) { Alphabet lower = alphabet.lowerCase(); result = lowerCase = (lower == alphabet) ? this : newInstance(lower, paddingChar); } return result; } @Override public BaseEncoding ignoreCase() { BaseEncoding result = ignoreCase; if (result == null) { Alphabet ignore = alphabet.ignoreCase(); result = ignoreCase = (ignore == alphabet) ? this : newInstance(ignore, paddingChar); } return result; } BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) { return new StandardBaseEncoding(alphabet, paddingChar); } @Override public String toString() { StringBuilder builder = new StringBuilder("BaseEncoding."); builder.append(alphabet); if (8 % alphabet.bitsPerChar != 0) { if (paddingChar == null) { builder.append(".omitPadding()"); } else { builder.append(".withPadChar('").append(paddingChar).append("')"); } } return builder.toString(); } @Override public boolean equals(@CheckForNull Object other) { if (other instanceof StandardBaseEncoding) { StandardBaseEncoding that = (StandardBaseEncoding) other; return this.alphabet.equals(that.alphabet) && Objects.equals(this.paddingChar, that.paddingChar); } return false; } @Override public int hashCode() { return alphabet.hashCode() ^ Objects.hashCode(paddingChar); } } private static final class Base16Encoding extends StandardBaseEncoding { final char[] encoding = new char[512]; Base16Encoding(String name, String alphabetChars) { this(new Alphabet(name, alphabetChars.toCharArray())); } private Base16Encoding(Alphabet alphabet) { super(alphabet, null); checkArgument(alphabet.chars.length == 16); for (int i = 0; i < 256; ++i) { encoding[i] = alphabet.encode(i >>> 4); encoding[i | 0x100] = alphabet.encode(i & 0xF); } } @Override void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException { checkNotNull(target); checkPositionIndexes(off, off + len, bytes.length); for (int i = 0; i < len; ++i) { int b = bytes[off + i] & 0xFF; target.append(encoding[b]); target.append(encoding[b | 0x100]); } } @Override int decodeTo(byte[] target, CharSequence chars) throws DecodingException { checkNotNull(target); if (chars.length() % 2 == 1) { throw new DecodingException("Invalid input length " + chars.length()); } int bytesWritten = 0; for (int i = 0; i < chars.length(); i += 2) { int decoded = alphabet.decode(chars.charAt(i)) << 4 | alphabet.decode(chars.charAt(i + 1)); target[bytesWritten++] = (byte) decoded; } return bytesWritten; } @Override BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) { return new Base16Encoding(alphabet); } } private static final class Base64Encoding extends StandardBaseEncoding { Base64Encoding(String name, String alphabetChars, @CheckForNull Character paddingChar) { this(new Alphabet(name, alphabetChars.toCharArray()), paddingChar); } private Base64Encoding(Alphabet alphabet, @CheckForNull Character paddingChar) { super(alphabet, paddingChar); checkArgument(alphabet.chars.length == 64); } @Override void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException { checkNotNull(target); checkPositionIndexes(off, off + len, bytes.length); int i = off; for (int remaining = len; remaining >= 3; remaining -= 3) { int chunk = (bytes[i++] & 0xFF) << 16 | (bytes[i++] & 0xFF) << 8 | bytes[i++] & 0xFF; target.append(alphabet.encode(chunk >>> 18)); target.append(alphabet.encode((chunk >>> 12) & 0x3F)); target.append(alphabet.encode((chunk >>> 6) & 0x3F)); target.append(alphabet.encode(chunk & 0x3F)); } if (i < off + len) { encodeChunkTo(target, bytes, i, off + len - i); } } @Override int decodeTo(byte[] target, CharSequence chars) throws DecodingException { checkNotNull(target); chars = trimTrailingPadding(chars); if (!alphabet.isValidPaddingStartPosition(chars.length())) { throw new DecodingException("Invalid input length " + chars.length()); } int bytesWritten = 0; for (int i = 0; i < chars.length(); ) { int chunk = alphabet.decode(chars.charAt(i++)) << 18; chunk |= alphabet.decode(chars.charAt(i++)) << 12; target[bytesWritten++] = (byte) (chunk >>> 16); if (i < chars.length()) { chunk |= alphabet.decode(chars.charAt(i++)) << 6; target[bytesWritten++] = (byte) ((chunk >>> 8) & 0xFF); if (i < chars.length()) { chunk |= alphabet.decode(chars.charAt(i++)); target[bytesWritten++] = (byte) (chunk & 0xFF); } } } return bytesWritten; } @Override BaseEncoding newInstance(Alphabet alphabet, @CheckForNull Character paddingChar) { return new Base64Encoding(alphabet, paddingChar); } } @J2ktIncompatible @GwtIncompatible static Reader ignoringReader(Reader delegate, String toIgnore) { checkNotNull(delegate); checkNotNull(toIgnore); return new Reader() { @Override public int read() throws IOException { int readChar; do { readChar = delegate.read(); } while (readChar != -1 && toIgnore.indexOf((char) readChar) >= 0); return readChar; } @Override public int read(char[] cbuf, int off, int len) throws IOException { throw new UnsupportedOperationException(); } @Override public void close() throws IOException { delegate.close(); } }; } static Appendable separatingAppendable( Appendable delegate, String separator, int afterEveryChars) { checkNotNull(delegate); checkNotNull(separator); checkArgument(afterEveryChars > 0); return new Appendable() { int charsUntilSeparator = afterEveryChars; @Override public Appendable append(char c) throws IOException { if (charsUntilSeparator == 0) { delegate.append(separator); charsUntilSeparator = afterEveryChars; } delegate.append(c); charsUntilSeparator--; return this; } @Override public Appendable append(@CheckForNull CharSequence chars, int off, int len) { throw new UnsupportedOperationException(); } @Override public Appendable append(@CheckForNull CharSequence chars) { throw new UnsupportedOperationException(); } }; } @J2ktIncompatible @GwtIncompatible // Writer static Writer separatingWriter(Writer delegate, String separator, int afterEveryChars) { Appendable separatingAppendable = separatingAppendable(delegate, separator, afterEveryChars); return new Writer() { @Override public void write(int c) throws IOException { separatingAppendable.append((char) c); } @Override public void write(char[] chars, int off, int len) throws IOException { throw new UnsupportedOperationException(); } @Override public void flush() throws IOException { delegate.flush(); } @Override public void close() throws IOException { delegate.close(); } }; } static final class SeparatedBaseEncoding extends BaseEncoding { private final BaseEncoding delegate; private final String separator; private final int afterEveryChars; SeparatedBaseEncoding(BaseEncoding delegate, String separator, int afterEveryChars) { this.delegate = checkNotNull(delegate); this.separator = checkNotNull(separator); this.afterEveryChars = afterEveryChars; checkArgument( afterEveryChars > 0, "Cannot add a separator after every %s chars", afterEveryChars); } @Override CharSequence trimTrailingPadding(CharSequence chars) { return delegate.trimTrailingPadding(chars); } @Override int maxEncodedSize(int bytes) { int unseparatedSize = delegate.maxEncodedSize(bytes); return unseparatedSize + separator.length() * divide(Math.max(0, unseparatedSize - 1), afterEveryChars, FLOOR); } @J2ktIncompatible @GwtIncompatible // Writer,OutputStream @Override public OutputStream encodingStream(Writer output) { return delegate.encodingStream(separatingWriter(output, separator, afterEveryChars)); } @Override void encodeTo(Appendable target, byte[] bytes, int off, int len) throws IOException { delegate.encodeTo(separatingAppendable(target, separator, afterEveryChars), bytes, off, len); } @Override int maxDecodedSize(int chars) { return delegate.maxDecodedSize(chars); } @Override public boolean canDecode(CharSequence chars) { StringBuilder builder = new StringBuilder(); for (int i = 0; i < chars.length(); i++) { char c = chars.charAt(i); if (separator.indexOf(c) < 0) { builder.append(c); } } return delegate.canDecode(builder); } @Override int decodeTo(byte[] target, CharSequence chars) throws DecodingException { StringBuilder stripped = new StringBuilder(chars.length()); for (int i = 0; i < chars.length(); i++) { char c = chars.charAt(i); if (separator.indexOf(c) < 0) { stripped.append(c); } } return delegate.decodeTo(target, stripped); } @Override @J2ktIncompatible @GwtIncompatible // Reader,InputStream public InputStream decodingStream(Reader reader) { return delegate.decodingStream(ignoringReader(reader, separator)); } @Override public BaseEncoding omitPadding() { return delegate.omitPadding().withSeparator(separator, afterEveryChars); } @Override public BaseEncoding withPadChar(char padChar) { return delegate.withPadChar(padChar).withSeparator(separator, afterEveryChars); } @Override public BaseEncoding withSeparator(String separator, int afterEveryChars) { throw new UnsupportedOperationException("Already have a separator"); } @Override public BaseEncoding upperCase() { return delegate.upperCase().withSeparator(separator, afterEveryChars); } @Override public BaseEncoding lowerCase() { return delegate.lowerCase().withSeparator(separator, afterEveryChars); } @Override public BaseEncoding ignoreCase() { return delegate.ignoreCase().withSeparator(separator, afterEveryChars); } @Override public String toString() { return delegate + ".withSeparator(\"" + separator + "\", " + afterEveryChars + ")"; } } }
google/guava
android/guava/src/com/google/common/io/BaseEncoding.java
358
/* * 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.javaIsoControl; 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.GwtCompatible; import com.google.common.base.Ascii; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Joiner.MapJoiner; import com.google.common.base.MoreObjects; import com.google.common.base.Objects; import com.google.common.base.Optional; import com.google.common.collect.ImmutableListMultimap; import com.google.common.collect.ImmutableMultiset; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Multimap; import com.google.common.collect.Multimaps; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.annotations.concurrent.LazyInit; import java.nio.charset.Charset; import java.nio.charset.IllegalCharsetNameException; import java.nio.charset.UnsupportedCharsetException; import java.util.Map; import java.util.Map.Entry; import javax.annotation.CheckForNull; /** * 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="https://tools.ietf.org/html/rfc2045">2045</a> and <a * href="https://tools.ietf.org/html/rfc2046">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 */ @GwtCompatible @Immutable @ElementTypesAreNonnullByDefault 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(javaIsoControl().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 FONT_TYPE = "font"; private static final String WILDCARD = "*"; private static final Map<MediaType, MediaType> KNOWN_TYPES = Maps.newHashMap(); private static MediaType createConstant(String type, String subtype) { MediaType mediaType = addKnownType(new MediaType(type, subtype, ImmutableListMultimap.<String, String>of())); mediaType.parsedCharset = Optional.absent(); return mediaType; } private static MediaType createConstantUtf8(String type, String subtype) { MediaType mediaType = addKnownType(new MediaType(type, subtype, UTF_8_CONSTANT_PARAMETERS)); mediaType.parsedCharset = Optional.of(UTF_8); return mediaType; } private static MediaType addKnownType(MediaType mediaType) { KNOWN_TYPES.put(mediaType, mediaType); return mediaType; } /* * 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. For types that * take a charset (e.g. all text/* types), default to UTF-8 and suffix the constant name 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); /** * Wildcard matching any "font" top-level media type. * * @since 30.0 */ public static final MediaType ANY_FONT_TYPE = createConstant(FONT_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"); /** * <a href="http://www.iana.org/assignments/media-types/text/tab-separated-values">Tab separated * values</a>. * * @since 15.0 */ public static final MediaType TSV_UTF_8 = createConstantUtf8(TEXT_TYPE, "tab-separated-values"); public static final MediaType VCARD_UTF_8 = createConstantUtf8(TEXT_TYPE, "vcard"); /** * UTF-8 encoded <a href="https://en.wikipedia.org/wiki/Wireless_Markup_Language">Wireless Markup * Language</a>. * * @since 13.0 */ public static final MediaType WML_UTF_8 = createConstantUtf8(TEXT_TYPE, "vnd.wap.wml"); /** * As described in <a href="http://www.ietf.org/rfc/rfc3023.txt">RFC 3023</a>, this constant * ({@code text/xml}) is used for XML documents that are "readable by casual users." {@link * #APPLICATION_XML_UTF_8} is provided for documents that are intended for applications. */ public static final MediaType XML_UTF_8 = createConstantUtf8(TEXT_TYPE, "xml"); /** * As described in <a href="https://w3c.github.io/webvtt/#iana-text-vtt">the VTT spec</a>, this is * used for Web Video Text Tracks (WebVTT) files, used with the HTML5 track element. * * @since 20.0 */ public static final MediaType VTT_UTF_8 = createConstantUtf8(TEXT_TYPE, "vtt"); /* image types */ /** * <a href="https://en.wikipedia.org/wiki/BMP_file_format">Bitmap file format</a> ({@code bmp} * files). * * @since 13.0 */ public static final MediaType BMP = createConstant(IMAGE_TYPE, "bmp"); /** * The <a href="https://en.wikipedia.org/wiki/Camera_Image_File_Format">Canon Image File * Format</a> ({@code crw} files), a widely-used "raw image" format for cameras. It is found in * {@code /etc/mime.types}, e.g. in <a href= * "http://anonscm.debian.org/gitweb/?p=collab-maint/mime-support.git;a=blob;f=mime.types;hb=HEAD" * >Debian 3.48-1</a>. * * @since 15.0 */ public static final MediaType CRW = createConstant(IMAGE_TYPE, "x-canon-crw"); 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"); /** * The Photoshop File Format ({@code psd} files) as defined by <a * href="http://www.iana.org/assignments/media-types/image/vnd.adobe.photoshop">IANA</a>, and * found in {@code /etc/mime.types}, e.g. <a * href="http://svn.apache.org/repos/asf/httpd/httpd/branches/1.3.x/conf/mime.types"></a> of the * Apache <a href="http://httpd.apache.org/">HTTPD project</a>; for the specification, see <a * href="http://www.adobe.com/devnet-apps/photoshop/fileformatashtml/PhotoshopFileFormats.htm"> * Adobe Photoshop Document Format</a> and <a * href="http://en.wikipedia.org/wiki/Adobe_Photoshop#File_format">Wikipedia</a>; this is the * regular output/input of Photoshop (which can also export to various image formats; note that * files with extension "PSB" are in a distinct but related format). * * <p>This is a more recent replacement for the older, experimental type {@code x-photoshop}: <a * href="http://tools.ietf.org/html/rfc2046#section-6">RFC-2046.6</a>. * * @since 15.0 */ public static final MediaType PSD = createConstant(IMAGE_TYPE, "vnd.adobe.photoshop"); public static final MediaType SVG_UTF_8 = createConstantUtf8(IMAGE_TYPE, "svg+xml"); public static final MediaType TIFF = createConstant(IMAGE_TYPE, "tiff"); /** * <a href="https://en.wikipedia.org/wiki/WebP">WebP image format</a>. * * @since 13.0 */ public static final MediaType WEBP = createConstant(IMAGE_TYPE, "webp"); /** * <a href="https://www.iana.org/assignments/media-types/image/heif">HEIF image format</a>. * * @since 28.1 */ public static final MediaType HEIF = createConstant(IMAGE_TYPE, "heif"); /** * <a href="https://tools.ietf.org/html/rfc3745">JP2K image format</a>. * * @since 28.1 */ public static final MediaType JP2K = createConstant(IMAGE_TYPE, "jp2"); /* 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"); /** * L16 audio, as defined by <a href="https://tools.ietf.org/html/rfc2586">RFC 2586</a>. * * @since 24.1 */ public static final MediaType L16_AUDIO = createConstant(AUDIO_TYPE, "l16"); /** * L24 audio, as defined by <a href="https://tools.ietf.org/html/rfc3190">RFC 3190</a>. * * @since 20.0 */ public static final MediaType L24_AUDIO = createConstant(AUDIO_TYPE, "l24"); /** * Basic Audio, as defined by <a href="http://tools.ietf.org/html/rfc2046#section-4.3">RFC * 2046</a>. * * @since 20.0 */ public static final MediaType BASIC_AUDIO = createConstant(AUDIO_TYPE, "basic"); /** * Advanced Audio Coding. For more information, see <a * href="https://en.wikipedia.org/wiki/Advanced_Audio_Coding">Advanced Audio Coding</a>. * * @since 20.0 */ public static final MediaType AAC_AUDIO = createConstant(AUDIO_TYPE, "aac"); /** * Vorbis Audio, as defined by <a href="http://tools.ietf.org/html/rfc5215">RFC 5215</a>. * * @since 20.0 */ public static final MediaType VORBIS_AUDIO = createConstant(AUDIO_TYPE, "vorbis"); /** * Windows Media Audio. For more information, see <a * href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd562994(v=vs.85).aspx">file * name extensions for Windows Media metafiles</a>. * * @since 20.0 */ public static final MediaType WMA_AUDIO = createConstant(AUDIO_TYPE, "x-ms-wma"); /** * Windows Media metafiles. For more information, see <a * href="https://msdn.microsoft.com/en-us/library/windows/desktop/dd562994(v=vs.85).aspx">file * name extensions for Windows Media metafiles</a>. * * @since 20.0 */ public static final MediaType WAX_AUDIO = createConstant(AUDIO_TYPE, "x-ms-wax"); /** * Real Audio. For more information, see <a * href="http://service.real.com/help/faq/rp8/configrp8win.html">this link</a>. * * @since 20.0 */ public static final MediaType VND_REAL_AUDIO = createConstant(AUDIO_TYPE, "vnd.rn-realaudio"); /** * WAVE format, as defined by <a href="https://tools.ietf.org/html/rfc2361">RFC 2361</a>. * * @since 20.0 */ public static final MediaType VND_WAVE_AUDIO = createConstant(AUDIO_TYPE, "vnd.wave"); /* 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"); /** * Flash video. For more information, see <a href= * "http://help.adobe.com/en_US/ActionScript/3.0_ProgrammingAS3/WS5b3ccc516d4fbf351e63e3d118a9b90204-7d48.html" * >this link</a>. * * @since 20.0 */ public static final MediaType FLV_VIDEO = createConstant(VIDEO_TYPE, "x-flv"); /** * The 3GP multimedia container format. For more information, see <a * href="ftp://www.3gpp.org/tsg_sa/TSG_SA/TSGS_23/Docs/PDF/SP-040065.pdf#page=10">3GPP TS * 26.244</a>. * * @since 20.0 */ public static final MediaType THREE_GPP_VIDEO = createConstant(VIDEO_TYPE, "3gpp"); /** * The 3G2 multimedia container format. For more information, see <a * href="http://www.3gpp2.org/Public_html/specs/C.S0050-B_v1.0_070521.pdf#page=16">3GPP2 * C.S0050-B</a>. * * @since 20.0 */ public static final MediaType THREE_GPP2_VIDEO = createConstant(VIDEO_TYPE, "3gpp2"); /* application types */ /** * As described in <a href="http://www.ietf.org/rfc/rfc3023.txt">RFC 3023</a>, this constant * ({@code application/xml}) is used for XML documents that are "unreadable by casual users." * {@link #XML_UTF_8} is provided for documents that may be read by users. * * @since 14.0 */ public static final MediaType APPLICATION_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xml"); public static final MediaType ATOM_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "atom+xml"); public static final MediaType BZIP2 = createConstant(APPLICATION_TYPE, "x-bzip2"); /** * Files in the <a href="https://www.dartlang.org/articles/embedding-in-html/">dart</a> * programming language. * * @since 19.0 */ public static final MediaType DART_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "dart"); /** * <a href="https://goo.gl/2QoMvg">Apple Passbook</a>. * * @since 19.0 */ public static final MediaType APPLE_PASSBOOK = createConstant(APPLICATION_TYPE, "vnd.apple.pkpass"); /** * <a href="http://en.wikipedia.org/wiki/Embedded_OpenType">Embedded OpenType</a> fonts. This is * <a href="http://www.iana.org/assignments/media-types/application/vnd.ms-fontobject">registered * </a> with the IANA. * * @since 17.0 */ public static final MediaType EOT = createConstant(APPLICATION_TYPE, "vnd.ms-fontobject"); /** * As described in the <a href="http://idpf.org/epub">International Digital Publishing Forum</a> * EPUB is the distribution and interchange format standard for digital publications and * documents. This media type is defined in the <a * href="http://www.idpf.org/epub/30/spec/epub30-ocf.html">EPUB Open Container Format</a> * specification. * * @since 15.0 */ public static final MediaType EPUB = createConstant(APPLICATION_TYPE, "epub+zip"); public static final MediaType FORM_DATA = createConstant(APPLICATION_TYPE, "x-www-form-urlencoded"); /** * As described in <a href="https://www.rsa.com/rsalabs/node.asp?id=2138">PKCS #12: Personal * Information Exchange Syntax Standard</a>, PKCS #12 defines an archive file format for storing * many cryptography objects as a single file. * * @since 15.0 */ public static final MediaType KEY_ARCHIVE = createConstant(APPLICATION_TYPE, "pkcs12"); /** * This is a non-standard media type, but is commonly used in serving hosted binary files as it is * <a href="http://code.google.com/p/browsersec/wiki/Part2#Survey_of_content_sniffing_behaviors"> * known not to trigger content sniffing in current browsers</a>. It <i>should not</i> be used in * other situations as it is not specified by any RFC and does not appear in the <a * href="http://www.iana.org/assignments/media-types">/IANA MIME Media Types</a> list. Consider * {@link #OCTET_STREAM} for binary data that is not being served to a browser. * * @since 14.0 */ public static final MediaType APPLICATION_BINARY = createConstant(APPLICATION_TYPE, "binary"); /** * Media type for the <a href="https://tools.ietf.org/html/rfc7946">GeoJSON Format</a>, a * geospatial data interchange format based on JSON. * * @since 28.0 */ public static final MediaType GEO_JSON = createConstant(APPLICATION_TYPE, "geo+json"); public static final MediaType GZIP = createConstant(APPLICATION_TYPE, "x-gzip"); /** * <a href="https://tools.ietf.org/html/draft-kelly-json-hal-08#section-3">JSON Hypertext * Application Language (HAL) documents</a>. * * @since 26.0 */ public static final MediaType HAL_JSON = createConstant(APPLICATION_TYPE, "hal+json"); /** * <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"); /** * For <a href="https://tools.ietf.org/html/rfc7515">JWS or JWE objects using the Compact * Serialization</a>. * * @since 27.1 */ public static final MediaType JOSE = createConstant(APPLICATION_TYPE, "jose"); /** * For <a href="https://tools.ietf.org/html/rfc7515">JWS or JWE objects using the JSON * Serialization</a>. * * @since 27.1 */ public static final MediaType JOSE_JSON = createConstant(APPLICATION_TYPE, "jose+json"); public static final MediaType JSON_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "json"); /** * For <a href="https://tools.ietf.org/html/7519">JWT objects using the compact Serialization</a>. * * @since 32.0.0 */ public static final MediaType JWT = createConstant(APPLICATION_TYPE, "jwt"); /** * The <a href="http://www.w3.org/TR/appmanifest/">Manifest for a web application</a>. * * @since 19.0 */ public static final MediaType MANIFEST_JSON_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "manifest+json"); /** * <a href="http://www.opengeospatial.org/standards/kml/">OGC KML (Keyhole Markup Language)</a>. */ public static final MediaType KML = createConstant(APPLICATION_TYPE, "vnd.google-earth.kml+xml"); /** * <a href="http://www.opengeospatial.org/standards/kml/">OGC KML (Keyhole Markup Language)</a>, * compressed using the ZIP format into KMZ archives. */ public static final MediaType KMZ = createConstant(APPLICATION_TYPE, "vnd.google-earth.kmz"); /** * The <a href="https://tools.ietf.org/html/rfc4155">mbox database format</a>. * * @since 13.0 */ public static final MediaType MBOX = createConstant(APPLICATION_TYPE, "mbox"); /** * <a href="http://goo.gl/1pGBFm">Apple over-the-air mobile configuration profiles</a>. * * @since 18.0 */ public static final MediaType APPLE_MOBILE_CONFIG = createConstant(APPLICATION_TYPE, "x-apple-aspen-config"); /** <a href="http://goo.gl/XDQ1h2">Microsoft Excel</a> spreadsheets. */ public static final MediaType MICROSOFT_EXCEL = createConstant(APPLICATION_TYPE, "vnd.ms-excel"); /** * <a href="http://goo.gl/XrTEqG">Microsoft Outlook</a> items. * * @since 27.1 */ public static final MediaType MICROSOFT_OUTLOOK = createConstant(APPLICATION_TYPE, "vnd.ms-outlook"); /** <a href="http://goo.gl/XDQ1h2">Microsoft Powerpoint</a> presentations. */ public static final MediaType MICROSOFT_POWERPOINT = createConstant(APPLICATION_TYPE, "vnd.ms-powerpoint"); /** <a href="http://goo.gl/XDQ1h2">Microsoft Word</a> documents. */ public static final MediaType MICROSOFT_WORD = createConstant(APPLICATION_TYPE, "msword"); /** * Media type for <a * href="https://en.wikipedia.org/wiki/Dynamic_Adaptive_Streaming_over_HTTP">Dynamic Adaptive * Streaming over HTTP (DASH)</a>. This is <a * href="https://www.iana.org/assignments/media-types/application/dash+xml">registered</a> with * the IANA. * * @since 28.2 */ public static final MediaType MEDIA_PRESENTATION_DESCRIPTION = createConstant(APPLICATION_TYPE, "dash+xml"); /** * WASM applications. For more information see <a href="https://webassembly.org/">the Web Assembly * overview</a>. * * @since 27.0 */ public static final MediaType WASM_APPLICATION = createConstant(APPLICATION_TYPE, "wasm"); /** * NaCl applications. For more information see <a * href="https://developer.chrome.com/native-client/devguide/coding/application-structure">the * Developer Guide for Native Client Application Structure</a>. * * @since 20.0 */ public static final MediaType NACL_APPLICATION = createConstant(APPLICATION_TYPE, "x-nacl"); /** * NaCl portable applications. For more information see <a * href="https://developer.chrome.com/native-client/devguide/coding/application-structure">the * Developer Guide for Native Client Application Structure</a>. * * @since 20.0 */ public static final MediaType NACL_PORTABLE_APPLICATION = createConstant(APPLICATION_TYPE, "x-pnacl"); 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"); /** * <a href="https://tools.ietf.org/id/draft-ellermann-opensearch-01.html">OpenSearch</a> * Description files are XML files that describe how a website can be used as a search engine by * consumers (e.g. web browsers). * * @since 28.2 */ public static final MediaType OPENSEARCH_DESCRIPTION_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "opensearchdescription+xml"); public static final MediaType PDF = createConstant(APPLICATION_TYPE, "pdf"); public static final MediaType POSTSCRIPT = createConstant(APPLICATION_TYPE, "postscript"); /** * <a href="http://tools.ietf.org/html/draft-rfernando-protocol-buffers-00">Protocol buffers</a> * * @since 15.0 */ public static final MediaType PROTOBUF = createConstant(APPLICATION_TYPE, "protobuf"); /** * <a href="https://en.wikipedia.org/wiki/RDF/XML">RDF/XML</a> documents, which are XML * serializations of <a * href="https://en.wikipedia.org/wiki/Resource_Description_Framework">Resource Description * Framework</a> graphs. * * @since 14.0 */ public static final MediaType RDF_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rdf+xml"); public static final MediaType RTF_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "rtf"); /** * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares {@link #FONT_SFNT * font/sfnt} to be the correct media type for SFNT, but this may be necessary in certain * situations for compatibility. * * @since 17.0 */ public static final MediaType SFNT = createConstant(APPLICATION_TYPE, "font-sfnt"); public static final MediaType SHOCKWAVE_FLASH = createConstant(APPLICATION_TYPE, "x-shockwave-flash"); /** * {@code skp} files produced by the 3D Modeling software <a * href="https://www.sketchup.com/">SketchUp</a> * * @since 13.0 */ public static final MediaType SKETCHUP = createConstant(APPLICATION_TYPE, "vnd.sketchup.skp"); /** * As described in <a href="http://www.ietf.org/rfc/rfc3902.txt">RFC 3902</a>, this constant * ({@code application/soap+xml}) is used to identify SOAP 1.2 message envelopes that have been * serialized with XML 1.0. * * <p>For SOAP 1.1 messages, see {@code XML_UTF_8} per <a * href="http://www.w3.org/TR/2000/NOTE-SOAP-20000508/">W3C Note on Simple Object Access Protocol * (SOAP) 1.1</a> * * @since 20.0 */ public static final MediaType SOAP_XML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "soap+xml"); public static final MediaType TAR = createConstant(APPLICATION_TYPE, "x-tar"); /** * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares {@link #FONT_WOFF * font/woff} to be the correct media type for WOFF, but this may be necessary in certain * situations for compatibility. * * @since 17.0 */ public static final MediaType WOFF = createConstant(APPLICATION_TYPE, "font-woff"); /** * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares {@link #FONT_WOFF2 * font/woff2} to be the correct media type for WOFF2, but this may be necessary in certain * situations for compatibility. * * @since 20.0 */ public static final MediaType WOFF2 = createConstant(APPLICATION_TYPE, "font-woff2"); public static final MediaType XHTML_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xhtml+xml"); /** * Extensible Resource Descriptors. This is not yet registered with the IANA, but it is specified * by OASIS in the <a href="http://docs.oasis-open.org/xri/xrd/v1.0/cd02/xrd-1.0-cd02.html">XRD * definition</a> and implemented in projects such as <a * href="http://code.google.com/p/webfinger/">WebFinger</a>. * * @since 14.0 */ public static final MediaType XRD_UTF_8 = createConstantUtf8(APPLICATION_TYPE, "xrd+xml"); public static final MediaType ZIP = createConstant(APPLICATION_TYPE, "zip"); /* font types */ /** * A collection of font outlines as defined by <a href="https://tools.ietf.org/html/rfc8081">RFC * 8081</a>. * * @since 30.0 */ public static final MediaType FONT_COLLECTION = createConstant(FONT_TYPE, "collection"); /** * <a href="https://en.wikipedia.org/wiki/OpenType">Open Type Font Format</a> (OTF) as defined by * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a>. * * @since 30.0 */ public static final MediaType FONT_OTF = createConstant(FONT_TYPE, "otf"); /** * <a href="https://en.wikipedia.org/wiki/SFNT">Spline or Scalable Font Format</a> (SFNT). <a * href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares this to be the correct media * type for SFNT, but {@link #SFNT application/font-sfnt} may be necessary in certain situations * for compatibility. * * @since 30.0 */ public static final MediaType FONT_SFNT = createConstant(FONT_TYPE, "sfnt"); /** * <a href="https://en.wikipedia.org/wiki/TrueType">True Type Font Format</a> (TTF) as defined by * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a>. * * @since 30.0 */ public static final MediaType FONT_TTF = createConstant(FONT_TYPE, "ttf"); /** * <a href="http://en.wikipedia.org/wiki/Web_Open_Font_Format">Web Open Font Format</a> (WOFF). <a * href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares this to be the correct media * type for SFNT, but {@link #WOFF application/font-woff} may be necessary in certain situations * for compatibility. * * @since 30.0 */ public static final MediaType FONT_WOFF = createConstant(FONT_TYPE, "woff"); /** * <a href="http://en.wikipedia.org/wiki/Web_Open_Font_Format">Web Open Font Format</a> (WOFF2). * <a href="https://tools.ietf.org/html/rfc8081">RFC 8081</a> declares this to be the correct * media type for SFNT, but {@link #WOFF2 application/font-woff2} may be necessary in certain * situations for compatibility. * * @since 30.0 */ public static final MediaType FONT_WOFF2 = createConstant(FONT_TYPE, "woff2"); private final String type; private final String subtype; private final ImmutableListMultimap<String, String> parameters; @LazyInit @CheckForNull private String toString; @LazyInit private int hashCode; @LazyInit @CheckForNull private Optional<Charset> parsedCharset; private MediaType(String type, String subtype, ImmutableListMultimap<String, String> parameters) { this.type = type; this.subtype = subtype; this.parameters = 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(), ImmutableMultiset::copyOf); } /** * 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() { // racy single-check idiom, this is safe because Optional is immutable. Optional<Charset> local = parsedCharset; if (local == null) { String value = null; local = Optional.absent(); for (String currentValue : parameters.get(CHARSET_ATTRIBUTE)) { if (value == null) { value = currentValue; local = Optional.of(Charset.forName(value)); } else if (!value.equals(currentValue)) { throw new IllegalStateException( "Multiple charset values defined: " + value + ", " + currentValue); } } parsedCharset = local; } return local; } /** * 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 parameters using the given * values. If there are no values, any existing parameters with the given attribute are removed. * * @throws IllegalArgumentException if either {@code attribute} or {@code values} is invalid * @since 24.0 */ public MediaType withParameters(String attribute, Iterable<String> values) { checkNotNull(attribute); checkNotNull(values); 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()); } } for (String value : values) { builder.put(normalizedAttribute, normalizeParameterValue(normalizedAttribute, value)); } MediaType mediaType = new MediaType(type, subtype, builder.build()); // if the attribute isn't charset, we can just inherit the current parsedCharset if (!normalizedAttribute.equals(CHARSET_ATTRIBUTE)) { mediaType.parsedCharset = this.parsedCharset; } // Return one of the constants if the media type is a known type. return MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType); } /** * <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(String, Iterable)}. 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) { return withParameters(attribute, ImmutableSet.of(value)); } /** * 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); MediaType withCharset = withParameter(CHARSET_ATTRIBUTE, charset.name()); // precache the charset so we don't need to parse it withCharset.parsedCharset = Optional.of(charset); return withCharset; } /** 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> * * <p>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) { MediaType mediaType = create(type, subtype, ImmutableListMultimap.<String, String>of()); mediaType.parsedCharset = Optional.absent(); return mediaType; } 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 MoreObjects.firstNonNull(KNOWN_TYPES.get(mediaType), mediaType); } /** * 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 "font" type and the given subtype. * * @throws IllegalArgumentException if subtype is invalid */ static MediaType createFontType(String subtype) { return create(FONT_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 String normalizeToken(String token) { checkArgument(TOKEN_MATCHER.matchesAllOf(token)); checkArgument(!token.isEmpty()); return Ascii.toLowerCase(token); } private static String normalizeParameterValue(String attribute, String value) { checkNotNull(value); // for GWT checkArgument(ascii().matchesAllOf(value), "parameter values must be ASCII: %s", 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 */ @CanIgnoreReturnValue // TODO(b/219820829): consider removing public static MediaType parse(String input) { checkNotNull(input); Tokenizer tokenizer = new Tokenizer(input); try { String type = tokenizer.consumeToken(TOKEN_MATCHER); consumeSeparator(tokenizer, '/'); String subtype = tokenizer.consumeToken(TOKEN_MATCHER); ImmutableListMultimap.Builder<String, String> parameters = ImmutableListMultimap.builder(); while (tokenizer.hasMore()) { consumeSeparator(tokenizer, ';'); String attribute = tokenizer.consumeToken(TOKEN_MATCHER); consumeSeparator(tokenizer, '='); 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("Could not parse '" + input + "'", e); } } private static void consumeSeparator(Tokenizer tokenizer, char c) { tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE); tokenizer.consumeCharacter(c); tokenizer.consumeTokenIfPresent(LINEAR_WHITE_SPACE); } private static final class Tokenizer { final String input; int position = 0; Tokenizer(String input) { this.input = input; } @CanIgnoreReturnValue 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; } @CanIgnoreReturnValue 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(@CheckForNull 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() { // racy single-check idiom int h = hashCode; if (h == 0) { h = Objects.hashCode(type, subtype, parametersAsMap()); hashCode = h; } return h; } 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() { // racy single-check idiom, safe because String is immutable String result = toString; if (result == null) { result = computeToString(); toString = result; } return result; } private String computeToString() { StringBuilder builder = new StringBuilder().append(type).append('/').append(subtype); if (!parameters.isEmpty()) { builder.append("; "); Multimap<String, String> quotedParameters = Multimaps.transformValues( parameters, (String value) -> (TOKEN_MATCHER.matchesAllOf(value) && !value.isEmpty()) ? 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 (int i = 0; i < value.length(); i++) { char ch = value.charAt(i); if (ch == '\r' || ch == '\\' || ch == '"') { escaped.append('\\'); } escaped.append(ch); } return escaped.append('"').toString(); } }
google/guava
android/guava/src/com/google/common/net/MediaType.java
359
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.rest; import org.apache.lucene.util.SetOnce; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.ElasticsearchStatusException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.unit.ByteSizeValue; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.core.Booleans; import org.elasticsearch.core.CheckedConsumer; import org.elasticsearch.core.Nullable; import org.elasticsearch.core.RestApiVersion; import org.elasticsearch.core.TimeValue; import org.elasticsearch.core.Tuple; import org.elasticsearch.http.HttpChannel; import org.elasticsearch.http.HttpRequest; import org.elasticsearch.telemetry.tracing.Traceable; import org.elasticsearch.xcontent.ParsedMediaType; import org.elasticsearch.xcontent.ToXContent; import org.elasticsearch.xcontent.XContentParser; import org.elasticsearch.xcontent.XContentParserConfiguration; import org.elasticsearch.xcontent.XContentType; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Optional; import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import java.util.regex.Pattern; import static org.elasticsearch.common.unit.ByteSizeValue.parseBytesSizeValue; import static org.elasticsearch.core.TimeValue.parseTimeValue; public class RestRequest implements ToXContent.Params, Traceable { public static final String PATH_RESTRICTED = "pathRestricted"; // tchar pattern as defined by RFC7230 section 3.2.6 private static final Pattern TCHAR_PATTERN = Pattern.compile("[a-zA-Z0-9!#$%&'*+\\-.\\^_`|~]+"); private static final AtomicLong requestIdGenerator = new AtomicLong(); private final XContentParserConfiguration parserConfig; private final Map<String, String> params; private final Map<String, List<String>> headers; private final String rawPath; private final Set<String> consumedParams = new HashSet<>(); private final SetOnce<XContentType> xContentType = new SetOnce<>(); private final HttpChannel httpChannel; private final ParsedMediaType parsedAccept; private final ParsedMediaType parsedContentType; private final Optional<RestApiVersion> restApiVersion; private HttpRequest httpRequest; private boolean contentConsumed = false; private final long requestId; public boolean isContentConsumed() { return contentConsumed; } @SuppressWarnings("this-escape") protected RestRequest( XContentParserConfiguration parserConfig, Map<String, String> params, String path, Map<String, List<String>> headers, HttpRequest httpRequest, HttpChannel httpChannel ) { this(parserConfig, params, path, headers, httpRequest, httpChannel, requestIdGenerator.incrementAndGet()); } @SuppressWarnings("this-escape") private RestRequest( XContentParserConfiguration parserConfig, Map<String, String> params, String path, Map<String, List<String>> headers, HttpRequest httpRequest, HttpChannel httpChannel, long requestId ) { try { this.parsedAccept = parseHeaderWithMediaType(httpRequest.getHeaders(), "Accept"); } catch (IllegalArgumentException e) { throw new MediaTypeHeaderException(e, "Accept"); } try { this.parsedContentType = parseHeaderWithMediaType(httpRequest.getHeaders(), "Content-Type"); if (parsedContentType != null) { this.xContentType.set(parsedContentType.toMediaType(XContentType.MEDIA_TYPE_REGISTRY)); } } catch (IllegalArgumentException e) { throw new MediaTypeHeaderException(e, "Content-Type"); } this.httpRequest = httpRequest; try { this.restApiVersion = RestCompatibleVersionHelper.getCompatibleVersion(parsedAccept, parsedContentType, hasContent()); } catch (ElasticsearchStatusException e) { throw new MediaTypeHeaderException(e, "Accept", "Content-Type"); } var effectiveApiVersion = this.getRestApiVersion(); this.parserConfig = parserConfig.restApiVersion().equals(effectiveApiVersion) ? parserConfig : parserConfig.withRestApiVersion(effectiveApiVersion); this.httpChannel = httpChannel; this.params = params; this.rawPath = path; this.headers = Collections.unmodifiableMap(headers); this.requestId = requestId; } protected RestRequest(RestRequest other) { assert other.parserConfig.restApiVersion().equals(other.getRestApiVersion()); this.parsedAccept = other.parsedAccept; this.parsedContentType = other.parsedContentType; if (other.xContentType.get() != null) { this.xContentType.set(other.xContentType.get()); } this.restApiVersion = other.restApiVersion; this.parserConfig = other.parserConfig; this.httpRequest = other.httpRequest; this.httpChannel = other.httpChannel; this.params = other.params; this.rawPath = other.rawPath; this.headers = other.headers; this.requestId = other.requestId; } private static @Nullable ParsedMediaType parseHeaderWithMediaType(Map<String, List<String>> headers, String headerName) { // TODO: make all usages of headers case-insensitive List<String> header = headers.get(headerName); if (header == null || header.isEmpty()) { return null; } else if (header.size() > 1) { throw new IllegalArgumentException("Incorrect header [" + headerName + "]. Only one value should be provided"); } String rawContentType = header.get(0); if (Strings.hasText(rawContentType)) { return ParsedMediaType.parseMediaType(rawContentType); } else { throw new IllegalArgumentException("Header [" + headerName + "] cannot be empty."); } } /** * Invoke {@link HttpRequest#releaseAndCopy()} on the http request in this instance and replace a pooled http request * with an unpooled copy. This is supposed to be used before passing requests to {@link RestHandler} instances that can not safely * handle http requests that use pooled buffers as determined by {@link RestHandler#allowsUnsafeBuffers()}. */ void ensureSafeBuffers() { httpRequest = httpRequest.releaseAndCopy(); } /** * Creates a new REST request. * * @throws BadParameterException if the parameters can not be decoded * @throws MediaTypeHeaderException if the Content-Type or Accept header can not be parsed */ public static RestRequest request(XContentParserConfiguration parserConfig, HttpRequest httpRequest, HttpChannel httpChannel) { Map<String, String> params = params(httpRequest.uri()); String path = path(httpRequest.uri()); return new RestRequest( parserConfig, params, path, httpRequest.getHeaders(), httpRequest, httpChannel, requestIdGenerator.incrementAndGet() ); } private static Map<String, String> params(final String uri) { final Map<String, String> params = new HashMap<>(); int index = uri.indexOf('?'); if (index >= 0) { try { RestUtils.decodeQueryString(uri, index + 1, params); } catch (final IllegalArgumentException e) { throw new BadParameterException(e); } } return params; } private static String path(final String uri) { final int index = uri.indexOf('?'); if (index >= 0) { return uri.substring(0, index); } else { return uri; } } /** * Creates a new REST request. The path is not decoded so this constructor will not throw a * {@link BadParameterException}. * * @throws MediaTypeHeaderException if the Content-Type or Accept header can not be parsed */ public static RestRequest requestWithoutParameters( XContentParserConfiguration parserConfig, HttpRequest httpRequest, HttpChannel httpChannel ) { Map<String, String> params = Collections.emptyMap(); return new RestRequest( parserConfig, params, httpRequest.uri(), httpRequest.getHeaders(), httpRequest, httpChannel, requestIdGenerator.incrementAndGet() ); } public enum Method { GET, POST, PUT, DELETE, OPTIONS, HEAD, PATCH, TRACE, CONNECT } /** * Returns the HTTP method used in the REST request. * * @return the {@link Method} used in the REST request * @throws IllegalArgumentException if the HTTP method is invalid */ public Method method() { return httpRequest.method(); } /** * The uri of the rest request, with the query string. */ public String uri() { return httpRequest.uri(); } /** * The non decoded, raw path provided. */ public String rawPath() { return rawPath; } /** * The path part of the URI (without the query string), decoded. */ public final String path() { return RestUtils.decodeComponent(rawPath()); } public boolean hasContent() { return contentLength() > 0; } public int contentLength() { return httpRequest.content().length(); } public BytesReference content() { this.contentConsumed = true; return httpRequest.content(); } /** * @return content of the request body or throw an exception if the body or content type is missing */ public final BytesReference requiredContent() { if (hasContent() == false) { throw new ElasticsearchParseException("request body is required"); } else if (xContentType.get() == null) { throw new IllegalStateException("unknown content type"); } return content(); } /** * Get the value of the header or {@code null} if not found. This method only retrieves the first header value if multiple values are * sent. Use of {@link #getAllHeaderValues(String)} should be preferred */ public final String header(String name) { List<String> values = headers.get(name); if (values != null && values.isEmpty() == false) { return values.get(0); } return null; } /** * Get all values for the header or {@code null} if the header was not found */ public final List<String> getAllHeaderValues(String name) { List<String> values = headers.get(name); if (values != null) { return Collections.unmodifiableList(values); } return null; } /** * Get all of the headers and values associated with the headers. Modifications of this map are not supported. */ public final Map<String, List<String>> getHeaders() { return headers; } public final long getRequestId() { return requestId; } /** * The {@link XContentType} that was parsed from the {@code Content-Type} header. This value will be {@code null} in the case of * a request without a valid {@code Content-Type} header, a request without content ({@link #hasContent()}, or a plain text request */ @Nullable public final XContentType getXContentType() { return xContentType.get(); } public HttpChannel getHttpChannel() { return httpChannel; } public HttpRequest getHttpRequest() { return httpRequest; } public final boolean hasParam(String key) { return params.containsKey(key); } @Override public final String param(String key) { consumedParams.add(key); return params.get(key); } @Override public final String param(String key, String defaultValue) { consumedParams.add(key); String value = params.get(key); if (value == null) { return defaultValue; } return value; } public Map<String, String> params() { return params; } /** * Returns a list of parameters that have been consumed. This method returns a copy, callers * are free to modify the returned list. * * @return the list of currently consumed parameters. */ List<String> consumedParams() { return new ArrayList<>(consumedParams); } /** * Returns a list of parameters that have not yet been consumed. This method returns a copy, * callers are free to modify the returned list. * * @return the list of currently unconsumed parameters. */ List<String> unconsumedParams() { return params.keySet().stream().filter(p -> consumedParams.contains(p) == false).toList(); } public float paramAsFloat(String key, float defaultValue) { String sValue = param(key); if (sValue == null) { return defaultValue; } try { return Float.parseFloat(sValue); } catch (NumberFormatException e) { throw new IllegalArgumentException("Failed to parse float parameter [" + key + "] with value [" + sValue + "]", e); } } public double paramAsDouble(String key, double defaultValue) { String sValue = param(key); if (sValue == null) { return defaultValue; } try { return Double.parseDouble(sValue); } catch (NumberFormatException e) { throw new IllegalArgumentException("Failed to parse double parameter [" + key + "] with value [" + sValue + "]", e); } } public int paramAsInt(String key, int defaultValue) { String sValue = param(key); if (sValue == null) { return defaultValue; } try { return Integer.parseInt(sValue); } catch (NumberFormatException e) { throw new IllegalArgumentException("Failed to parse int parameter [" + key + "] with value [" + sValue + "]", e); } } public long paramAsLong(String key, long defaultValue) { String sValue = param(key); if (sValue == null) { return defaultValue; } try { return Long.parseLong(sValue); } catch (NumberFormatException e) { throw new IllegalArgumentException("Failed to parse long parameter [" + key + "] with value [" + sValue + "]", e); } } @Override public boolean paramAsBoolean(String key, boolean defaultValue) { String rawParam = param(key); // Treat empty string as true because that allows the presence of the url parameter to mean "turn this on" if (rawParam != null && rawParam.length() == 0) { return true; } else { return Booleans.parseBoolean(rawParam, defaultValue); } } @Override public Boolean paramAsBoolean(String key, Boolean defaultValue) { return Booleans.parseBoolean(param(key), defaultValue); } public TimeValue paramAsTime(String key, TimeValue defaultValue) { return parseTimeValue(param(key), defaultValue, key); } public ByteSizeValue paramAsSize(String key, ByteSizeValue defaultValue) { return parseBytesSizeValue(param(key), defaultValue, key); } public String[] paramAsStringArray(String key, String[] defaultValue) { String value = param(key); if (value == null) { return defaultValue; } return Strings.splitStringByCommaToArray(value); } public String[] paramAsStringArrayOrEmptyIfAll(String key) { String[] params = paramAsStringArray(key, Strings.EMPTY_ARRAY); if (Strings.isAllOrWildcard(params)) { return Strings.EMPTY_ARRAY; } return params; } /** * Get the configuration that should be used to create {@link XContentParser} from this request. */ public XContentParserConfiguration contentParserConfig() { return parserConfig; } /** * A parser for the contents of this request if there is a body, otherwise throws an {@link ElasticsearchParseException}. Use * {@link #applyContentParser(CheckedConsumer)} if you want to gracefully handle when the request doesn't have any contents. Use * {@link #contentOrSourceParamParser()} for requests that support specifying the request body in the {@code source} param. */ public final XContentParser contentParser() throws IOException { BytesReference content = requiredContent(); // will throw exception if body or content type missing return XContentHelper.createParserNotCompressed(parserConfig, content, xContentType.get()); } /** * If there is any content then call {@code applyParser} with the parser, otherwise do nothing. */ public final void applyContentParser(CheckedConsumer<XContentParser, IOException> applyParser) throws IOException { if (hasContent()) { try (XContentParser parser = contentParser()) { applyParser.accept(parser); } } } /** * Does this request have content or a {@code source} parameter? Use this instead of {@link #hasContent()} if this * {@linkplain RestHandler} treats the {@code source} parameter like the body content. */ public final boolean hasContentOrSourceParam() { return hasContent() || hasParam("source"); } /** * A parser for the contents of this request if it has contents, otherwise a parser for the {@code source} parameter if there is one, * otherwise throws an {@link ElasticsearchParseException}. Use {@link #withContentOrSourceParamParserOrNull(CheckedConsumer)} instead * if you need to handle the absence request content gracefully. */ public final XContentParser contentOrSourceParamParser() throws IOException { Tuple<XContentType, BytesReference> tuple = contentOrSourceParam(); return XContentHelper.createParserNotCompressed(parserConfig, tuple.v2(), tuple.v1().xContent().type()); } /** * Call a consumer with the parser for the contents of this request if it has contents, otherwise with a parser for the {@code source} * parameter if there is one, otherwise with {@code null}. Use {@link #contentOrSourceParamParser()} if you should throw an exception * back to the user when there isn't request content. */ public final void withContentOrSourceParamParserOrNull(CheckedConsumer<XContentParser, IOException> withParser) throws IOException { if (hasContentOrSourceParam()) { Tuple<XContentType, BytesReference> tuple = contentOrSourceParam(); try (XContentParser parser = XContentHelper.createParserNotCompressed(parserConfig, tuple.v2(), tuple.v1())) { withParser.accept(parser); } } else { withParser.accept(null); } } /** * Get the content of the request or the contents of the {@code source} param or throw an exception if both are missing. * Prefer {@link #contentOrSourceParamParser()} or {@link #withContentOrSourceParamParserOrNull(CheckedConsumer)} if you need a parser. */ public final Tuple<XContentType, BytesReference> contentOrSourceParam() { if (hasContentOrSourceParam() == false) { throw new ElasticsearchParseException("request body or source parameter is required"); } else if (hasContent()) { return new Tuple<>(xContentType.get(), requiredContent()); } String source = param("source"); String typeParam = param("source_content_type"); if (source == null || typeParam == null) { throw new IllegalStateException("source and source_content_type parameters are required"); } BytesArray bytes = new BytesArray(source); final XContentType xContentType = parseContentType(Collections.singletonList(typeParam)); if (xContentType == null) { throw new IllegalStateException("Unknown value for source_content_type [" + typeParam + "]"); } return new Tuple<>(xContentType, bytes); } public ParsedMediaType getParsedAccept() { return parsedAccept; } public ParsedMediaType getParsedContentType() { return parsedContentType; } /** * Parses the given content type string for the media type. This method currently ignores parameters. */ // TODO stop ignoring parameters such as charset... public static XContentType parseContentType(List<String> header) { if (header == null || header.isEmpty()) { return null; } else if (header.size() > 1) { throw new IllegalArgumentException("only one Content-Type header should be provided"); } String rawContentType = header.get(0); final String[] elements = rawContentType.split("[ \t]*;"); if (elements.length > 0) { final String[] splitMediaType = elements[0].split("/"); if (splitMediaType.length == 2 && TCHAR_PATTERN.matcher(splitMediaType[0]).matches() && TCHAR_PATTERN.matcher(splitMediaType[1].trim()).matches()) { return XContentType.fromMediaType(elements[0]); } else { throw new IllegalArgumentException("invalid Content-Type header [" + rawContentType + "]"); } } throw new IllegalArgumentException("empty Content-Type header"); } /** * The requested version of the REST API. */ public RestApiVersion getRestApiVersion() { return restApiVersion.orElse(RestApiVersion.current()); } public boolean hasExplicitRestApiVersion() { return restApiVersion.isPresent(); } public void markPathRestricted(String restriction) { if (params.containsKey(PATH_RESTRICTED)) { throw new IllegalArgumentException("The parameter [" + PATH_RESTRICTED + "] is already defined."); } params.put(PATH_RESTRICTED, restriction); // this parameter is intended be consumed via ToXContent.Params.param(..), not this.params(..) so don't require it is consumed here consumedParams.add(PATH_RESTRICTED); } @Override public String getSpanId() { return "rest-" + getRequestId(); } public static class MediaTypeHeaderException extends RuntimeException { private final String message; private final Set<String> failedHeaderNames; MediaTypeHeaderException(final RuntimeException cause, String... failedHeaderNames) { super(cause); this.failedHeaderNames = Set.of(failedHeaderNames); this.message = "Invalid media-type value on headers " + this.failedHeaderNames; } public Set<String> getFailedHeaderNames() { return failedHeaderNames; } @Override public String getMessage() { return message; } } public static class BadParameterException extends RuntimeException { BadParameterException(final IllegalArgumentException cause) { super(cause); } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/rest/RestRequest.java
360
/* * 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 static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndex; import static com.google.common.base.Preconditions.checkPositionIndexes; import static com.google.common.base.Preconditions.checkState; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import static com.google.common.collect.CollectPreconditions.checkRemove; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.math.IntMath; import com.google.common.primitives.Ints; import java.io.Serializable; import java.math.RoundingMode; import java.util.AbstractList; import java.util.AbstractSequentialList; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.ListIterator; import java.util.NoSuchElementException; import java.util.RandomAccess; import java.util.concurrent.CopyOnWriteArrayList; import java.util.function.Predicate; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods pertaining to {@link List} instances. Also see this class's counterparts * {@link Sets}, {@link Maps} and {@link Queues}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#lists">{@code Lists}</a>. * * @author Kevin Bourrillion * @author Mike Bostock * @author Louis Wasserman * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Lists { private Lists() {} // ArrayList /** * Creates a <i>mutable</i>, empty {@code ArrayList} instance (for Java 6 and earlier). * * <p><b>Note:</b> if mutability is not required, use {@link ImmutableList#of()} instead. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code ArrayList} {@linkplain ArrayList#ArrayList() constructor} directly, taking * advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. */ @GwtCompatible(serializable = true) public static <E extends @Nullable Object> ArrayList<E> newArrayList() { return new ArrayList<>(); } /** * Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements. * * <p><b>Note:</b> essentially the only reason to use this method is when you will need to add or * remove elements later. Otherwise, for non-null elements use {@link ImmutableList#of()} (for * varargs) or {@link ImmutableList#copyOf(Object[])} (for an array) instead. If any elements * might be null, or you need support for {@link List#set(int, Object)}, use {@link * Arrays#asList}. * * <p>Note that even when you do need the ability to add or remove, this method provides only a * tiny bit of syntactic sugar for {@code newArrayList(}{@link Arrays#asList asList}{@code * (...))}, or for creating an empty list then calling {@link Collections#addAll}. This method is * not actually very useful and will likely be deprecated in the future. */ @SafeVarargs @GwtCompatible(serializable = true) @SuppressWarnings("nullness") // TODO: b/316358623 - Remove after checker fix. public static <E extends @Nullable Object> ArrayList<E> newArrayList(E... elements) { checkNotNull(elements); // for GWT // Avoid integer overflow when a large array is passed in int capacity = computeArrayListCapacity(elements.length); ArrayList<E> list = new ArrayList<>(capacity); Collections.addAll(list, elements); return list; } /** * Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements; a very thin * shortcut for creating an empty list then calling {@link Iterables#addAll}. * * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link * ImmutableList#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link * FluentIterable} and call {@code elements.toList()}.) * * <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method. Use * the {@code ArrayList} {@linkplain ArrayList#ArrayList(Collection) constructor} directly, taking * advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. */ @GwtCompatible(serializable = true) public static <E extends @Nullable Object> ArrayList<E> newArrayList( Iterable<? extends E> elements) { checkNotNull(elements); // for GWT // Let ArrayList's sizing logic work, if possible return (elements instanceof Collection) ? new ArrayList<>((Collection<? extends E>) elements) : newArrayList(elements.iterator()); } /** * Creates a <i>mutable</i> {@code ArrayList} instance containing the given elements; a very thin * shortcut for creating an empty list and then calling {@link Iterators#addAll}. * * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link * ImmutableList#copyOf(Iterator)} instead. */ @GwtCompatible(serializable = true) public static <E extends @Nullable Object> ArrayList<E> newArrayList( Iterator<? extends E> elements) { ArrayList<E> list = newArrayList(); Iterators.addAll(list, elements); return list; } @VisibleForTesting static int computeArrayListCapacity(int arraySize) { checkNonnegative(arraySize, "arraySize"); // TODO(kevinb): Figure out the right behavior, and document it return Ints.saturatedCast(5L + arraySize + (arraySize / 10)); } /** * Creates an {@code ArrayList} instance backed by an array with the specified initial size; * simply delegates to {@link ArrayList#ArrayList(int)}. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use {@code new }{@link ArrayList#ArrayList(int) ArrayList}{@code <>(int)} directly, taking * advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. (Unlike here, there is no risk * of overload ambiguity, since the {@code ArrayList} constructors very wisely did not accept * varargs.) * * @param initialArraySize the exact size of the initial backing array for the returned array list * ({@code ArrayList} documentation calls this value the "capacity") * @return a new, empty {@code ArrayList} which is guaranteed not to resize itself unless its size * reaches {@code initialArraySize + 1} * @throws IllegalArgumentException if {@code initialArraySize} is negative */ @GwtCompatible(serializable = true) public static <E extends @Nullable Object> ArrayList<E> newArrayListWithCapacity( int initialArraySize) { checkNonnegative(initialArraySize, "initialArraySize"); // for GWT. return new ArrayList<>(initialArraySize); } /** * Creates an {@code ArrayList} instance to hold {@code estimatedSize} elements, <i>plus</i> an * unspecified amount of padding; you almost certainly mean to call {@link * #newArrayListWithCapacity} (see that method for further advice on usage). * * <p><b>Note:</b> This method will soon be deprecated. Even in the rare case that you do want * some amount of padding, it's best if you choose your desired amount explicitly. * * @param estimatedSize an estimate of the eventual {@link List#size()} of the new list * @return a new, empty {@code ArrayList}, sized appropriately to hold the estimated number of * elements * @throws IllegalArgumentException if {@code estimatedSize} is negative */ @GwtCompatible(serializable = true) public static <E extends @Nullable Object> ArrayList<E> newArrayListWithExpectedSize( int estimatedSize) { return new ArrayList<>(computeArrayListCapacity(estimatedSize)); } // LinkedList /** * Creates a <i>mutable</i>, empty {@code LinkedList} instance (for Java 6 and earlier). * * <p><b>Note:</b> if you won't be adding any elements to the list, use {@link ImmutableList#of()} * instead. * * <p><b>Performance note:</b> {@link ArrayList} and {@link java.util.ArrayDeque} consistently * outperform {@code LinkedList} except in certain rare and specific situations. Unless you have * spent a lot of time benchmarking your specific needs, use one of those instead. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code LinkedList} {@linkplain LinkedList#LinkedList() constructor} directly, taking * advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. */ @GwtCompatible(serializable = true) public static <E extends @Nullable Object> LinkedList<E> newLinkedList() { return new LinkedList<>(); } /** * Creates a <i>mutable</i> {@code LinkedList} instance containing the given elements; a very thin * shortcut for creating an empty list then calling {@link Iterables#addAll}. * * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link * ImmutableList#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link * FluentIterable} and call {@code elements.toList()}.) * * <p><b>Performance note:</b> {@link ArrayList} and {@link java.util.ArrayDeque} consistently * outperform {@code LinkedList} except in certain rare and specific situations. Unless you have * spent a lot of time benchmarking your specific needs, use one of those instead. * * <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method. Use * the {@code LinkedList} {@linkplain LinkedList#LinkedList(Collection) constructor} directly, * taking advantage of <a href="http://goo.gl/iz2Wi">"diamond" syntax</a>. */ @GwtCompatible(serializable = true) public static <E extends @Nullable Object> LinkedList<E> newLinkedList( Iterable<? extends E> elements) { LinkedList<E> list = newLinkedList(); Iterables.addAll(list, elements); return list; } /** * Creates an empty {@code CopyOnWriteArrayList} instance. * * <p><b>Note:</b> if you need an immutable empty {@link List}, use {@link Collections#emptyList} * instead. * * @return a new, empty {@code CopyOnWriteArrayList} * @since 12.0 */ @J2ktIncompatible @GwtIncompatible // CopyOnWriteArrayList public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList() { return new CopyOnWriteArrayList<>(); } /** * Creates a {@code CopyOnWriteArrayList} instance containing the given elements. * * @param elements the elements that the list should contain, in order * @return a new {@code CopyOnWriteArrayList} containing those elements * @since 12.0 */ @J2ktIncompatible @GwtIncompatible // CopyOnWriteArrayList public static <E extends @Nullable Object> CopyOnWriteArrayList<E> newCopyOnWriteArrayList( Iterable<? extends E> elements) { // We copy elements to an ArrayList first, rather than incurring the // quadratic cost of adding them to the COWAL directly. Collection<? extends E> elementsCollection = (elements instanceof Collection) ? (Collection<? extends E>) elements : newArrayList(elements); return new CopyOnWriteArrayList<>(elementsCollection); } /** * Returns an unmodifiable list containing the specified first element and backed by the specified * array of additional elements. Changes to the {@code rest} array will be reflected in the * returned list. Unlike {@link Arrays#asList}, the returned list is unmodifiable. * * <p>This is useful when a varargs method needs to use a signature such as {@code (Foo firstFoo, * Foo... moreFoos)}, in order to avoid overload ambiguity or to enforce a minimum argument count. * * <p>The returned list is serializable and implements {@link RandomAccess}. * * @param first the first element * @param rest an array of additional elements, possibly empty * @return an unmodifiable list containing the specified elements */ public static <E extends @Nullable Object> List<E> asList(@ParametricNullness E first, E[] rest) { return new OnePlusArrayList<>(first, rest); } /** * Returns an unmodifiable list containing the specified first and second element, and backed by * the specified array of additional elements. Changes to the {@code rest} array will be reflected * in the returned list. Unlike {@link Arrays#asList}, the returned list is unmodifiable. * * <p>This is useful when a varargs method needs to use a signature such as {@code (Foo firstFoo, * Foo secondFoo, Foo... moreFoos)}, in order to avoid overload ambiguity or to enforce a minimum * argument count. * * <p>The returned list is serializable and implements {@link RandomAccess}. * * @param first the first element * @param second the second element * @param rest an array of additional elements, possibly empty * @return an unmodifiable list containing the specified elements */ public static <E extends @Nullable Object> List<E> asList( @ParametricNullness E first, @ParametricNullness E second, E[] rest) { return new TwoPlusArrayList<>(first, second, rest); } /** @see Lists#asList(Object, Object[]) */ private static class OnePlusArrayList<E extends @Nullable Object> extends AbstractList<E> implements Serializable, RandomAccess { @ParametricNullness final E first; final E[] rest; OnePlusArrayList(@ParametricNullness E first, E[] rest) { this.first = first; this.rest = checkNotNull(rest); } @Override public int size() { return IntMath.saturatedAdd(rest.length, 1); } @Override @ParametricNullness public E get(int index) { // check explicitly so the IOOBE will have the right message checkElementIndex(index, size()); return (index == 0) ? first : rest[index - 1]; } @J2ktIncompatible private static final long serialVersionUID = 0; } /** @see Lists#asList(Object, Object, Object[]) */ private static class TwoPlusArrayList<E extends @Nullable Object> extends AbstractList<E> implements Serializable, RandomAccess { @ParametricNullness final E first; @ParametricNullness final E second; final E[] rest; TwoPlusArrayList(@ParametricNullness E first, @ParametricNullness E second, E[] rest) { this.first = first; this.second = second; this.rest = checkNotNull(rest); } @Override public int size() { return IntMath.saturatedAdd(rest.length, 2); } @Override @ParametricNullness public E get(int index) { switch (index) { case 0: return first; case 1: return second; default: // check explicitly so the IOOBE will have the right message checkElementIndex(index, size()); return rest[index - 2]; } } @J2ktIncompatible private static final long serialVersionUID = 0; } /** * Returns every possible list that can be formed by choosing one element from each of the given * lists in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian * product</a>" of the lists. For example: * * <pre>{@code * Lists.cartesianProduct(ImmutableList.of( * ImmutableList.of(1, 2), * ImmutableList.of("A", "B", "C"))) * }</pre> * * <p>returns a list containing six lists in the following order: * * <ul> * <li>{@code ImmutableList.of(1, "A")} * <li>{@code ImmutableList.of(1, "B")} * <li>{@code ImmutableList.of(1, "C")} * <li>{@code ImmutableList.of(2, "A")} * <li>{@code ImmutableList.of(2, "B")} * <li>{@code ImmutableList.of(2, "C")} * </ul> * * <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian * products that you would get from nesting for loops: * * <pre>{@code * for (B b0 : lists.get(0)) { * for (B b1 : lists.get(1)) { * ... * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); * // operate on tuple * } * } * }</pre> * * <p>Note that if any input list is empty, the Cartesian product will also be empty. If no lists * at all are provided (an empty list), the resulting Cartesian product has one element, an empty * list (counter-intuitive, but mathematically consistent). * * <p><i>Performance notes:</i> while the cartesian product of lists of size {@code m, n, p} is a * list of size {@code m x n x p}, its actual memory consumption is much smaller. When the * cartesian product is constructed, the input lists are merely copied. Only as the resulting list * is iterated are the individual lists created, and these are not retained after iteration. * * @param lists the lists to choose elements from, in the order that the elements chosen from * those lists should appear in the resulting lists * @param <B> any common base class shared by all axes (often just {@link Object}) * @return the Cartesian product, as an immutable list containing immutable lists * @throws IllegalArgumentException if the size of the cartesian product would be greater than * {@link Integer#MAX_VALUE} * @throws NullPointerException if {@code lists}, any one of the {@code lists}, or any element of * a provided list is null * @since 19.0 */ public static <B> List<List<B>> cartesianProduct(List<? extends List<? extends B>> lists) { return CartesianList.create(lists); } /** * Returns every possible list that can be formed by choosing one element from each of the given * lists in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian * product</a>" of the lists. For example: * * <pre>{@code * Lists.cartesianProduct(ImmutableList.of( * ImmutableList.of(1, 2), * ImmutableList.of("A", "B", "C"))) * }</pre> * * <p>returns a list containing six lists in the following order: * * <ul> * <li>{@code ImmutableList.of(1, "A")} * <li>{@code ImmutableList.of(1, "B")} * <li>{@code ImmutableList.of(1, "C")} * <li>{@code ImmutableList.of(2, "A")} * <li>{@code ImmutableList.of(2, "B")} * <li>{@code ImmutableList.of(2, "C")} * </ul> * * <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian * products that you would get from nesting for loops: * * <pre>{@code * for (B b0 : lists.get(0)) { * for (B b1 : lists.get(1)) { * ... * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); * // operate on tuple * } * } * }</pre> * * <p>Note that if any input list is empty, the Cartesian product will also be empty. If no lists * at all are provided (an empty list), the resulting Cartesian product has one element, an empty * list (counter-intuitive, but mathematically consistent). * * <p><i>Performance notes:</i> while the cartesian product of lists of size {@code m, n, p} is a * list of size {@code m x n x p}, its actual memory consumption is much smaller. When the * cartesian product is constructed, the input lists are merely copied. Only as the resulting list * is iterated are the individual lists created, and these are not retained after iteration. * * @param lists the lists to choose elements from, in the order that the elements chosen from * those lists should appear in the resulting lists * @param <B> any common base class shared by all axes (often just {@link Object}) * @return the Cartesian product, as an immutable list containing immutable lists * @throws IllegalArgumentException if the size of the cartesian product would be greater than * {@link Integer#MAX_VALUE} * @throws NullPointerException if {@code lists}, any one of the {@code lists}, or any element of * a provided list is null * @since 19.0 */ @SafeVarargs public static <B> List<List<B>> cartesianProduct(List<? extends B>... lists) { return cartesianProduct(Arrays.asList(lists)); } /** * Returns a list that applies {@code function} to each element of {@code fromList}. The returned * list is a transformed view of {@code fromList}; changes to {@code fromList} will be reflected * in the returned list and vice versa. * * <p>Since functions are not reversible, the transform is one-way and new items cannot be stored * in the returned list. The {@code add}, {@code addAll} and {@code set} methods are unsupported * in the returned list. * * <p>The function is applied lazily, invoked when needed. This is necessary for the returned list * to be a view, but it means that the function will be applied many times for bulk operations * like {@link List#contains} and {@link List#hashCode}. For this to perform well, {@code * function} should be fast. To avoid lazy evaluation when the returned list doesn't need to be a * view, copy the returned list into a new list of your choosing. * * <p>If {@code fromList} implements {@link RandomAccess}, so will the returned list. The returned * list is threadsafe if the supplied list and function are. * * <p>If only a {@code Collection} or {@code Iterable} input is available, use {@link * Collections2#transform} or {@link Iterables#transform}. * * <p><b>Note:</b> serializing the returned list is implemented by serializing {@code fromList}, * its contents, and {@code function} -- <i>not</i> by serializing the transformed values. This * can lead to surprising behavior, so serializing the returned list is <b>not recommended</b>. * Instead, copy the list using {@link ImmutableList#copyOf(Collection)} (for example), then * serialize the copy. Other methods similar to this do not implement serialization at all for * this reason. * * <p><b>Java 8+ users:</b> many use cases for this method are better addressed by {@link * java.util.stream.Stream#map}. This method is not being deprecated, but we gently encourage you * to migrate to streams. */ public static <F extends @Nullable Object, T extends @Nullable Object> List<T> transform( List<F> fromList, Function<? super F, ? extends T> function) { return (fromList instanceof RandomAccess) ? new TransformingRandomAccessList<>(fromList, function) : new TransformingSequentialList<>(fromList, function); } /** * Implementation of a sequential transforming list. * * @see Lists#transform */ private static class TransformingSequentialList< F extends @Nullable Object, T extends @Nullable Object> extends AbstractSequentialList<T> implements Serializable { final List<F> fromList; final Function<? super F, ? extends T> function; TransformingSequentialList(List<F> fromList, Function<? super F, ? extends T> function) { this.fromList = checkNotNull(fromList); this.function = checkNotNull(function); } /** * The default implementation inherited is based on iteration and removal of each element which * can be overkill. That's why we forward this call directly to the backing list. */ @Override protected void removeRange(int fromIndex, int toIndex) { fromList.subList(fromIndex, toIndex).clear(); } @Override public int size() { return fromList.size(); } @Override public boolean isEmpty() { return fromList.isEmpty(); } @Override public ListIterator<T> listIterator(final int index) { return new TransformedListIterator<F, T>(fromList.listIterator(index)) { @Override @ParametricNullness T transform(@ParametricNullness F from) { return function.apply(from); } }; } @Override public boolean removeIf(Predicate<? super T> filter) { checkNotNull(filter); return fromList.removeIf(element -> filter.test(function.apply(element))); } private static final long serialVersionUID = 0; } /** * Implementation of a transforming random access list. We try to make as many of these methods * pass-through to the source list as possible so that the performance characteristics of the * source list and transformed list are similar. * * @see Lists#transform */ private static class TransformingRandomAccessList< F extends @Nullable Object, T extends @Nullable Object> extends AbstractList<T> implements RandomAccess, Serializable { final List<F> fromList; final Function<? super F, ? extends T> function; TransformingRandomAccessList(List<F> fromList, Function<? super F, ? extends T> function) { this.fromList = checkNotNull(fromList); this.function = checkNotNull(function); } /** * The default implementation inherited is based on iteration and removal of each element which * can be overkill. That's why we forward this call directly to the backing list. */ @Override protected void removeRange(int fromIndex, int toIndex) { fromList.subList(fromIndex, toIndex).clear(); } @Override @ParametricNullness public T get(int index) { return function.apply(fromList.get(index)); } @Override public Iterator<T> iterator() { return listIterator(); } @Override public ListIterator<T> listIterator(int index) { return new TransformedListIterator<F, T>(fromList.listIterator(index)) { @Override T transform(F from) { return function.apply(from); } }; } @Override public boolean isEmpty() { return fromList.isEmpty(); } @Override public boolean removeIf(Predicate<? super T> filter) { checkNotNull(filter); return fromList.removeIf(element -> filter.test(function.apply(element))); } @Override @ParametricNullness public T remove(int index) { return function.apply(fromList.remove(index)); } @Override public int size() { return fromList.size(); } private static final long serialVersionUID = 0; } /** * Returns consecutive {@linkplain List#subList(int, int) sublists} of a list, each of the same * size (the final list may be smaller). For example, partitioning a list containing {@code [a, b, * c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer list * containing two inner lists of three and two elements, all in the original order. * * <p>The outer list is unmodifiable, but reflects the latest state of the source list. The inner * lists are sublist views of the original list, produced on demand using {@link List#subList(int, * int)}, and are subject to all the usual caveats about modification as explained in that API. * * @param list the list to return consecutive sublists of * @param size the desired size of each sublist (the last may be smaller) * @return a list of consecutive sublists * @throws IllegalArgumentException if {@code partitionSize} is nonpositive */ public static <T extends @Nullable Object> List<List<T>> partition(List<T> list, int size) { checkNotNull(list); checkArgument(size > 0); return (list instanceof RandomAccess) ? new RandomAccessPartition<>(list, size) : new Partition<>(list, size); } private static class Partition<T extends @Nullable Object> extends AbstractList<List<T>> { final List<T> list; final int size; Partition(List<T> list, int size) { this.list = list; this.size = size; } @Override public List<T> get(int index) { checkElementIndex(index, size()); int start = index * size; int end = Math.min(start + size, list.size()); return list.subList(start, end); } @Override public int size() { return IntMath.divide(list.size(), size, RoundingMode.CEILING); } @Override public boolean isEmpty() { return list.isEmpty(); } } private static class RandomAccessPartition<T extends @Nullable Object> extends Partition<T> implements RandomAccess { RandomAccessPartition(List<T> list, int size) { super(list, size); } } /** * Returns a view of the specified string as an immutable list of {@code Character} values. * * @since 7.0 */ public static ImmutableList<Character> charactersOf(String string) { return new StringAsImmutableList(checkNotNull(string)); } /** * Returns a view of the specified {@code CharSequence} as a {@code List<Character>}, viewing * {@code sequence} as a sequence of Unicode code units. The view does not support any * modification operations, but reflects any changes to the underlying character sequence. * * @param sequence the character sequence to view as a {@code List} of characters * @return an {@code List<Character>} view of the character sequence * @since 7.0 */ public static List<Character> charactersOf(CharSequence sequence) { return new CharSequenceAsList(checkNotNull(sequence)); } @SuppressWarnings("serial") // serialized using ImmutableList serialization private static final class StringAsImmutableList extends ImmutableList<Character> { private final String string; StringAsImmutableList(String string) { this.string = string; } @Override public int indexOf(@CheckForNull Object object) { return (object instanceof Character) ? string.indexOf((Character) object) : -1; } @Override public int lastIndexOf(@CheckForNull Object object) { return (object instanceof Character) ? string.lastIndexOf((Character) object) : -1; } @Override public ImmutableList<Character> subList(int fromIndex, int toIndex) { checkPositionIndexes(fromIndex, toIndex, size()); // for GWT return charactersOf(string.substring(fromIndex, toIndex)); } @Override boolean isPartialView() { return false; } @Override public Character get(int index) { checkElementIndex(index, size()); // for GWT return string.charAt(index); } @Override public int size() { return string.length(); } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible // serialization @GwtIncompatible // serialization Object writeReplace() { return super.writeReplace(); } } private static final class CharSequenceAsList extends AbstractList<Character> { private final CharSequence sequence; CharSequenceAsList(CharSequence sequence) { this.sequence = sequence; } @Override public Character get(int index) { checkElementIndex(index, size()); // for GWT return sequence.charAt(index); } @Override public int size() { return sequence.length(); } } /** * Returns a reversed view of the specified list. For example, {@code * Lists.reverse(Arrays.asList(1, 2, 3))} returns a list containing {@code 3, 2, 1}. The returned * list is backed by this list, so changes in the returned list are reflected in this list, and * vice-versa. The returned list supports all of the optional list operations supported by this * list. * * <p>The returned list is random-access if the specified list is random access. * * @since 7.0 */ public static <T extends @Nullable Object> List<T> reverse(List<T> list) { if (list instanceof ImmutableList) { // Avoid nullness warnings. List<?> reversed = ((ImmutableList<?>) list).reverse(); @SuppressWarnings("unchecked") List<T> result = (List<T>) reversed; return result; } else if (list instanceof ReverseList) { return ((ReverseList<T>) list).getForwardList(); } else if (list instanceof RandomAccess) { return new RandomAccessReverseList<>(list); } else { return new ReverseList<>(list); } } private static class ReverseList<T extends @Nullable Object> extends AbstractList<T> { private final List<T> forwardList; ReverseList(List<T> forwardList) { this.forwardList = checkNotNull(forwardList); } List<T> getForwardList() { return forwardList; } private int reverseIndex(int index) { int size = size(); checkElementIndex(index, size); return (size - 1) - index; } private int reversePosition(int index) { int size = size(); checkPositionIndex(index, size); return size - index; } @Override public void add(int index, @ParametricNullness T element) { forwardList.add(reversePosition(index), element); } @Override public void clear() { forwardList.clear(); } @Override @ParametricNullness public T remove(int index) { return forwardList.remove(reverseIndex(index)); } @Override protected void removeRange(int fromIndex, int toIndex) { subList(fromIndex, toIndex).clear(); } @Override @ParametricNullness public T set(int index, @ParametricNullness T element) { return forwardList.set(reverseIndex(index), element); } @Override @ParametricNullness public T get(int index) { return forwardList.get(reverseIndex(index)); } @Override public int size() { return forwardList.size(); } @Override public List<T> subList(int fromIndex, int toIndex) { checkPositionIndexes(fromIndex, toIndex, size()); return reverse(forwardList.subList(reversePosition(toIndex), reversePosition(fromIndex))); } @Override public Iterator<T> iterator() { return listIterator(); } @Override public ListIterator<T> listIterator(int index) { int start = reversePosition(index); final ListIterator<T> forwardIterator = forwardList.listIterator(start); return new ListIterator<T>() { boolean canRemoveOrSet; @Override public void add(@ParametricNullness T e) { forwardIterator.add(e); forwardIterator.previous(); canRemoveOrSet = false; } @Override public boolean hasNext() { return forwardIterator.hasPrevious(); } @Override public boolean hasPrevious() { return forwardIterator.hasNext(); } @Override @ParametricNullness public T next() { if (!hasNext()) { throw new NoSuchElementException(); } canRemoveOrSet = true; return forwardIterator.previous(); } @Override public int nextIndex() { return reversePosition(forwardIterator.nextIndex()); } @Override @ParametricNullness public T previous() { if (!hasPrevious()) { throw new NoSuchElementException(); } canRemoveOrSet = true; return forwardIterator.next(); } @Override public int previousIndex() { return nextIndex() - 1; } @Override public void remove() { checkRemove(canRemoveOrSet); forwardIterator.remove(); canRemoveOrSet = false; } @Override public void set(@ParametricNullness T e) { checkState(canRemoveOrSet); forwardIterator.set(e); } }; } } private static class RandomAccessReverseList<T extends @Nullable Object> extends ReverseList<T> implements RandomAccess { RandomAccessReverseList(List<T> forwardList) { super(forwardList); } } /** An implementation of {@link List#hashCode()}. */ static int hashCodeImpl(List<?> list) { // TODO(lowasser): worth optimizing for RandomAccess? int hashCode = 1; for (Object o : list) { hashCode = 31 * hashCode + (o == null ? 0 : o.hashCode()); hashCode = ~~hashCode; // needed to deal with GWT integer overflow } return hashCode; } /** An implementation of {@link List#equals(Object)}. */ static boolean equalsImpl(List<?> thisList, @CheckForNull Object other) { if (other == checkNotNull(thisList)) { return true; } if (!(other instanceof List)) { return false; } List<?> otherList = (List<?>) other; int size = thisList.size(); if (size != otherList.size()) { return false; } if (thisList instanceof RandomAccess && otherList instanceof RandomAccess) { // avoid allocation and use the faster loop for (int i = 0; i < size; i++) { if (!Objects.equal(thisList.get(i), otherList.get(i))) { return false; } } return true; } else { return Iterators.elementsEqual(thisList.iterator(), otherList.iterator()); } } /** An implementation of {@link List#addAll(int, Collection)}. */ static <E extends @Nullable Object> boolean addAllImpl( List<E> list, int index, Iterable<? extends E> elements) { boolean changed = false; ListIterator<E> listIterator = list.listIterator(index); for (E e : elements) { listIterator.add(e); changed = true; } return changed; } /** An implementation of {@link List#indexOf(Object)}. */ static int indexOfImpl(List<?> list, @CheckForNull Object element) { if (list instanceof RandomAccess) { return indexOfRandomAccess(list, element); } else { ListIterator<?> listIterator = list.listIterator(); while (listIterator.hasNext()) { if (Objects.equal(element, listIterator.next())) { return listIterator.previousIndex(); } } return -1; } } private static int indexOfRandomAccess(List<?> list, @CheckForNull Object element) { int size = list.size(); if (element == null) { for (int i = 0; i < size; i++) { if (list.get(i) == null) { return i; } } } else { for (int i = 0; i < size; i++) { if (element.equals(list.get(i))) { return i; } } } return -1; } /** An implementation of {@link List#lastIndexOf(Object)}. */ static int lastIndexOfImpl(List<?> list, @CheckForNull Object element) { if (list instanceof RandomAccess) { return lastIndexOfRandomAccess(list, element); } else { ListIterator<?> listIterator = list.listIterator(list.size()); while (listIterator.hasPrevious()) { if (Objects.equal(element, listIterator.previous())) { return listIterator.nextIndex(); } } return -1; } } private static int lastIndexOfRandomAccess(List<?> list, @CheckForNull Object element) { if (element == null) { for (int i = list.size() - 1; i >= 0; i--) { if (list.get(i) == null) { return i; } } } else { for (int i = list.size() - 1; i >= 0; i--) { if (element.equals(list.get(i))) { return i; } } } return -1; } /** Returns an implementation of {@link List#listIterator(int)}. */ static <E extends @Nullable Object> ListIterator<E> listIteratorImpl(List<E> list, int index) { return new AbstractListWrapper<>(list).listIterator(index); } /** An implementation of {@link List#subList(int, int)}. */ static <E extends @Nullable Object> List<E> subListImpl( final List<E> list, int fromIndex, int toIndex) { List<E> wrapper; if (list instanceof RandomAccess) { wrapper = new RandomAccessListWrapper<E>(list) { @Override public ListIterator<E> listIterator(int index) { return backingList.listIterator(index); } @J2ktIncompatible private static final long serialVersionUID = 0; }; } else { wrapper = new AbstractListWrapper<E>(list) { @Override public ListIterator<E> listIterator(int index) { return backingList.listIterator(index); } @J2ktIncompatible private static final long serialVersionUID = 0; }; } return wrapper.subList(fromIndex, toIndex); } private static class AbstractListWrapper<E extends @Nullable Object> extends AbstractList<E> { final List<E> backingList; AbstractListWrapper(List<E> backingList) { this.backingList = checkNotNull(backingList); } @Override public void add(int index, @ParametricNullness E element) { backingList.add(index, element); } @Override public boolean addAll(int index, Collection<? extends E> c) { return backingList.addAll(index, c); } @Override @ParametricNullness public E get(int index) { return backingList.get(index); } @Override @ParametricNullness public E remove(int index) { return backingList.remove(index); } @Override @ParametricNullness public E set(int index, @ParametricNullness E element) { return backingList.set(index, element); } @Override public boolean contains(@CheckForNull Object o) { return backingList.contains(o); } @Override public int size() { return backingList.size(); } } private static class RandomAccessListWrapper<E extends @Nullable Object> extends AbstractListWrapper<E> implements RandomAccess { RandomAccessListWrapper(List<E> backingList) { super(backingList); } } /** Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ static <T extends @Nullable Object> List<T> cast(Iterable<T> iterable) { return (List<T>) iterable; } }
google/guava
guava/src/com/google/common/collect/Lists.java
361
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods pertaining to {@code Predicate} instances. * * <p>All methods return serializable predicates as long as they're given serializable parameters. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/FunctionalExplained">the use of {@code Predicate}</a>. * * @author Kevin Bourrillion * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Predicates { private Predicates() {} // TODO(kevinb): considering having these implement a VisitablePredicate // interface which specifies an accept(PredicateVisitor) method. /** Returns a predicate that always evaluates to {@code true}. */ @GwtCompatible(serializable = true) public static <T extends @Nullable Object> Predicate<T> alwaysTrue() { return ObjectPredicate.ALWAYS_TRUE.withNarrowedType(); } /** Returns a predicate that always evaluates to {@code false}. */ @GwtCompatible(serializable = true) public static <T extends @Nullable Object> Predicate<T> alwaysFalse() { return ObjectPredicate.ALWAYS_FALSE.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the object reference being tested is * null. */ @GwtCompatible(serializable = true) public static <T extends @Nullable Object> Predicate<T> isNull() { return ObjectPredicate.IS_NULL.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the object reference being tested is not * null. */ @GwtCompatible(serializable = true) public static <T extends @Nullable Object> Predicate<T> notNull() { return ObjectPredicate.NOT_NULL.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the given predicate evaluates to {@code * false}. */ public static <T extends @Nullable Object> Predicate<T> not(Predicate<T> predicate) { return new NotPredicate<>(predicate); } /** * Returns a predicate that evaluates to {@code true} if each of its components evaluates to * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" * as soon as a false predicate is found. It defensively copies the iterable passed in, so future * changes to it won't alter the behavior of this predicate. If {@code components} is empty, the * returned predicate will always evaluate to {@code true}. */ public static <T extends @Nullable Object> Predicate<T> and( Iterable<? extends Predicate<? super T>> components) { return new AndPredicate<>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if each of its components evaluates to * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" * as soon as a false predicate is found. It defensively copies the array passed in, so future * changes to it won't alter the behavior of this predicate. If {@code components} is empty, the * returned predicate will always evaluate to {@code true}. */ @SafeVarargs public static <T extends @Nullable Object> Predicate<T> and(Predicate<? super T>... components) { return new AndPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if both of its components evaluate to {@code * true}. The components are evaluated in order, and evaluation will be "short-circuited" as soon * as a false predicate is found. */ public static <T extends @Nullable Object> Predicate<T> and( Predicate<? super T> first, Predicate<? super T> second) { return new AndPredicate<>(Predicates.<T>asList(checkNotNull(first), checkNotNull(second))); } /** * Returns a predicate that evaluates to {@code true} if any one of its components evaluates to * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" * as soon as a true predicate is found. It defensively copies the iterable passed in, so future * changes to it won't alter the behavior of this predicate. If {@code components} is empty, the * returned predicate will always evaluate to {@code false}. */ public static <T extends @Nullable Object> Predicate<T> or( Iterable<? extends Predicate<? super T>> components) { return new OrPredicate<>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if any one of its components evaluates to * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" * as soon as a true predicate is found. It defensively copies the array passed in, so future * changes to it won't alter the behavior of this predicate. If {@code components} is empty, the * returned predicate will always evaluate to {@code false}. */ @SafeVarargs public static <T extends @Nullable Object> Predicate<T> or(Predicate<? super T>... components) { return new OrPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if either of its components evaluates to * {@code true}. The components are evaluated in order, and evaluation will be "short-circuited" * as soon as a true predicate is found. */ public static <T extends @Nullable Object> Predicate<T> or( Predicate<? super T> first, Predicate<? super T> second) { return new OrPredicate<>(Predicates.<T>asList(checkNotNull(first), checkNotNull(second))); } /** * Returns a predicate that evaluates to {@code true} if the object being tested {@code equals()} * the given target or both are null. */ public static <T extends @Nullable Object> Predicate<T> equalTo(@ParametricNullness T target) { return (target == null) ? Predicates.<T>isNull() : new IsEqualToPredicate(target).withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the object being tested is an instance of * the given class. If the object being tested is {@code null} this predicate evaluates to {@code * false}. * * <p>If you want to filter an {@code Iterable} to narrow its type, consider using {@link * com.google.common.collect.Iterables#filter(Iterable, Class)} in preference. * * <p><b>Warning:</b> contrary to the typical assumptions about predicates (as documented at * {@link Predicate#apply}), the returned predicate may not be <i>consistent with equals</i>. For * example, {@code instanceOf(ArrayList.class)} will yield different results for the two equal * instances {@code Lists.newArrayList(1)} and {@code Arrays.asList(1)}. */ @GwtIncompatible // Class.isInstance public static <T extends @Nullable Object> Predicate<T> instanceOf(Class<?> clazz) { return new InstanceOfPredicate<>(clazz); } /** * Returns a predicate that evaluates to {@code true} if the class being tested is assignable to * (is a subtype of) {@code clazz}. Example: * * <pre>{@code * List<Class<?>> classes = Arrays.asList( * Object.class, String.class, Number.class, Long.class); * return Iterables.filter(classes, subtypeOf(Number.class)); * }</pre> * * The code above returns an iterable containing {@code Number.class} and {@code Long.class}. * * @since 20.0 (since 10.0 under the incorrect name {@code assignableFrom}) */ @J2ktIncompatible @GwtIncompatible // Class.isAssignableFrom public static Predicate<Class<?>> subtypeOf(Class<?> clazz) { return new SubtypeOfPredicate(clazz); } /** * Returns a predicate that evaluates to {@code true} if the object reference being tested is a * member of the given collection. It does not defensively copy the collection passed in, so * future changes to it will alter the behavior of the predicate. * * <p>This method can technically accept any {@code Collection<?>}, but using a typed collection * helps prevent bugs. This approach doesn't block any potential users since it is always possible * to use {@code Predicates.<Object>in()}. * * @param target the collection that may contain the function input */ public static <T extends @Nullable Object> Predicate<T> in(Collection<? extends T> target) { return new InPredicate<>(target); } /** * Returns the composition of a function and a predicate. For every {@code x}, the generated * predicate returns {@code predicate(function(x))}. * * @return the composition of the provided function and predicate */ public static <A extends @Nullable Object, B extends @Nullable Object> Predicate<A> compose( Predicate<B> predicate, Function<A, ? extends B> function) { return new CompositionPredicate<>(predicate, function); } /** * Returns a predicate that evaluates to {@code true} if the {@code CharSequence} being tested * contains any match for the given regular expression pattern. The test used is equivalent to * {@code Pattern.compile(pattern).matcher(arg).find()} * * @throws IllegalArgumentException if the pattern is invalid * @since 3.0 */ @GwtIncompatible // Only used by other GWT-incompatible code. public static Predicate<CharSequence> containsPattern(String pattern) { return new ContainsPatternFromStringPredicate(pattern); } /** * Returns a predicate that evaluates to {@code true} if the {@code CharSequence} being tested * contains any match for the given regular expression pattern. The test used is equivalent to * {@code pattern.matcher(arg).find()} * * @since 3.0 */ @GwtIncompatible(value = "java.util.regex.Pattern") public static Predicate<CharSequence> contains(Pattern pattern) { return new ContainsPatternPredicate(new JdkPattern(pattern)); } // End public API, begin private implementation classes. // Package private for GWT serialization. enum ObjectPredicate implements Predicate<@Nullable Object> { /** @see Predicates#alwaysTrue() */ ALWAYS_TRUE { @Override public boolean apply(@CheckForNull Object o) { return true; } @Override public String toString() { return "Predicates.alwaysTrue()"; } }, /** @see Predicates#alwaysFalse() */ ALWAYS_FALSE { @Override public boolean apply(@CheckForNull Object o) { return false; } @Override public String toString() { return "Predicates.alwaysFalse()"; } }, /** @see Predicates#isNull() */ IS_NULL { @Override public boolean apply(@CheckForNull Object o) { return o == null; } @Override public String toString() { return "Predicates.isNull()"; } }, /** @see Predicates#notNull() */ NOT_NULL { @Override public boolean apply(@CheckForNull Object o) { return o != null; } @Override public String toString() { return "Predicates.notNull()"; } }; @SuppressWarnings("unchecked") // safe contravariant cast <T extends @Nullable Object> Predicate<T> withNarrowedType() { return (Predicate<T>) this; } } /** @see Predicates#not(Predicate) */ private static class NotPredicate<T extends @Nullable Object> implements Predicate<T>, Serializable { final Predicate<T> predicate; NotPredicate(Predicate<T> predicate) { this.predicate = checkNotNull(predicate); } @Override public boolean apply(@ParametricNullness T t) { return !predicate.apply(t); } @Override public int hashCode() { return ~predicate.hashCode(); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof NotPredicate) { NotPredicate<?> that = (NotPredicate<?>) obj; return predicate.equals(that.predicate); } return false; } @Override public String toString() { return "Predicates.not(" + predicate + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#and(Iterable) */ private static class AndPredicate<T extends @Nullable Object> implements Predicate<T>, Serializable { private final List<? extends Predicate<? super T>> components; private AndPredicate(List<? extends Predicate<? super T>> components) { this.components = components; } @Override public boolean apply(@ParametricNullness T t) { // Avoid using the Iterator to avoid generating garbage (issue 820). for (int i = 0; i < components.size(); i++) { if (!components.get(i).apply(t)) { return false; } } return true; } @Override public int hashCode() { // add a random number to avoid collisions with OrPredicate return components.hashCode() + 0x12472c2c; } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof AndPredicate) { AndPredicate<?> that = (AndPredicate<?>) obj; return components.equals(that.components); } return false; } @Override public String toString() { return toStringHelper("and", components); } private static final long serialVersionUID = 0; } /** @see Predicates#or(Iterable) */ private static class OrPredicate<T extends @Nullable Object> implements Predicate<T>, Serializable { private final List<? extends Predicate<? super T>> components; private OrPredicate(List<? extends Predicate<? super T>> components) { this.components = components; } @Override public boolean apply(@ParametricNullness T t) { // Avoid using the Iterator to avoid generating garbage (issue 820). for (int i = 0; i < components.size(); i++) { if (components.get(i).apply(t)) { return true; } } return false; } @Override public int hashCode() { // add a random number to avoid collisions with AndPredicate return components.hashCode() + 0x053c91cf; } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof OrPredicate) { OrPredicate<?> that = (OrPredicate<?>) obj; return components.equals(that.components); } return false; } @Override public String toString() { return toStringHelper("or", components); } private static final long serialVersionUID = 0; } private static String toStringHelper(String methodName, Iterable<?> components) { StringBuilder builder = new StringBuilder("Predicates.").append(methodName).append('('); boolean first = true; for (Object o : components) { if (!first) { builder.append(','); } builder.append(o); first = false; } return builder.append(')').toString(); } /** @see Predicates#equalTo(Object) */ private static class IsEqualToPredicate implements Predicate<@Nullable Object>, Serializable { private final Object target; private IsEqualToPredicate(Object target) { this.target = target; } @Override public boolean apply(@CheckForNull Object o) { return target.equals(o); } @Override public int hashCode() { return target.hashCode(); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof IsEqualToPredicate) { IsEqualToPredicate that = (IsEqualToPredicate) obj; return target.equals(that.target); } return false; } @Override public String toString() { return "Predicates.equalTo(" + target + ")"; } private static final long serialVersionUID = 0; @SuppressWarnings("unchecked") // safe contravariant cast <T extends @Nullable Object> Predicate<T> withNarrowedType() { return (Predicate<T>) this; } } /** * @see Predicates#instanceOf(Class) */ @GwtIncompatible // Class.isInstance private static class InstanceOfPredicate<T extends @Nullable Object> implements Predicate<T>, Serializable { private final Class<?> clazz; private InstanceOfPredicate(Class<?> clazz) { this.clazz = checkNotNull(clazz); } @Override public boolean apply(@ParametricNullness T o) { return clazz.isInstance(o); } @Override public int hashCode() { return clazz.hashCode(); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof InstanceOfPredicate) { InstanceOfPredicate<?> that = (InstanceOfPredicate<?>) obj; return clazz == that.clazz; } return false; } @Override public String toString() { return "Predicates.instanceOf(" + clazz.getName() + ")"; } @J2ktIncompatible private static final long serialVersionUID = 0; } /** * @see Predicates#subtypeOf(Class) */ @J2ktIncompatible @GwtIncompatible // Class.isAssignableFrom private static class SubtypeOfPredicate implements Predicate<Class<?>>, Serializable { private final Class<?> clazz; private SubtypeOfPredicate(Class<?> clazz) { this.clazz = checkNotNull(clazz); } @Override public boolean apply(Class<?> input) { return clazz.isAssignableFrom(input); } @Override public int hashCode() { return clazz.hashCode(); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof SubtypeOfPredicate) { SubtypeOfPredicate that = (SubtypeOfPredicate) obj; return clazz == that.clazz; } return false; } @Override public String toString() { return "Predicates.subtypeOf(" + clazz.getName() + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#in(Collection) */ private static class InPredicate<T extends @Nullable Object> implements Predicate<T>, Serializable { private final Collection<?> target; private InPredicate(Collection<?> target) { this.target = checkNotNull(target); } @Override public boolean apply(@ParametricNullness T t) { try { return target.contains(t); } catch (NullPointerException | ClassCastException e) { return false; } } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof InPredicate) { InPredicate<?> that = (InPredicate<?>) obj; return target.equals(that.target); } return false; } @Override public int hashCode() { return target.hashCode(); } @Override public String toString() { return "Predicates.in(" + target + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#compose(Predicate, Function) */ private static class CompositionPredicate<A extends @Nullable Object, B extends @Nullable Object> implements Predicate<A>, Serializable { final Predicate<B> p; final Function<A, ? extends B> f; private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) { this.p = checkNotNull(p); this.f = checkNotNull(f); } @Override public boolean apply(@ParametricNullness A a) { return p.apply(f.apply(a)); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof CompositionPredicate) { CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj; return f.equals(that.f) && p.equals(that.p); } return false; } @Override public int hashCode() { return f.hashCode() ^ p.hashCode(); } @Override public String toString() { // TODO(cpovirk): maybe make this look like the method call does ("Predicates.compose(...)") return p + "(" + f + ")"; } private static final long serialVersionUID = 0; } /** * @see Predicates#contains(Pattern) */ @GwtIncompatible // Only used by other GWT-incompatible code. private static class ContainsPatternPredicate implements Predicate<CharSequence>, Serializable { final CommonPattern pattern; ContainsPatternPredicate(CommonPattern pattern) { this.pattern = checkNotNull(pattern); } @Override public boolean apply(CharSequence t) { return pattern.matcher(t).find(); } @Override public int hashCode() { // Pattern uses Object.hashCode, so we have to reach // inside to build a hashCode consistent with equals. return Objects.hashCode(pattern.pattern(), pattern.flags()); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof ContainsPatternPredicate) { ContainsPatternPredicate that = (ContainsPatternPredicate) obj; // Pattern uses Object (identity) equality, so we have to reach // inside to compare individual fields. return Objects.equal(pattern.pattern(), that.pattern.pattern()) && pattern.flags() == that.pattern.flags(); } return false; } @Override public String toString() { String patternString = MoreObjects.toStringHelper(pattern) .add("pattern", pattern.pattern()) .add("pattern.flags", pattern.flags()) .toString(); return "Predicates.contains(" + patternString + ")"; } private static final long serialVersionUID = 0; } /** * @see Predicates#containsPattern(String) */ @GwtIncompatible // Only used by other GWT-incompatible code. private static class ContainsPatternFromStringPredicate extends ContainsPatternPredicate { ContainsPatternFromStringPredicate(String string) { super(Platform.compilePattern(string)); } @Override public String toString() { return "Predicates.containsPattern(" + pattern.pattern() + ")"; } private static final long serialVersionUID = 0; } private static <T extends @Nullable Object> List<Predicate<? super T>> asList( Predicate<? super T> first, Predicate<? super T> second) { // TODO(kevinb): understand why we still get a warning despite @SafeVarargs! return Arrays.<Predicate<? super T>>asList(first, second); } private static <T> List<T> defensiveCopy(T... array) { return defensiveCopy(Arrays.asList(array)); } static <T> List<T> defensiveCopy(Iterable<T> iterable) { ArrayList<T> list = new ArrayList<>(); for (T element : iterable) { list.add(checkNotNull(element)); } return list; } }
google/guava
android/guava/src/com/google/common/base/Predicates.java
362
/* * 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 static java.util.Objects.requireNonNull; import com.google.common.annotations.VisibleForTesting; 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.ImmutableMap; import com.google.common.collect.Iterables; import java.io.Serializable; import java.lang.reflect.AnnotatedElement; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.GenericDeclaration; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Proxy; import java.lang.reflect.Type; import java.lang.reflect.TypeVariable; import java.lang.reflect.WildcardType; import java.security.AccessControlException; import java.util.Arrays; import java.util.Collection; import java.util.Map.Entry; import java.util.concurrent.atomic.AtomicReference; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Utilities for working with {@link Type}. * * @author Ben Yu */ @ElementTypesAreNonnullByDefault final class Types { /** Class#toString without the "class " and "interface " prefixes */ 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( @CheckForNull 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 { @Override @CheckForNull Class<?> getOwnerType(Class<?> rawType) { return rawType.getEnclosingClass(); } }, LOCAL_CLASS_HAS_NO_OWNER { @Override @CheckForNull Class<?> getOwnerType(Class<?> rawType) { if (rawType.isLocalClass()) { return null; } else { return rawType.getEnclosingClass(); } } }; @CheckForNull abstract Class<?> getOwnerType(Class<?> rawType); static final ClassOwnership JVM_BEHAVIOR = detectJvmBehavior(); private static ClassOwnership detectJvmBehavior() { class LocalClass<T> {} Class<?> subclass = new LocalClass<String>() {}.getClass(); // requireNonNull is safe because we're examining a type that's known to have a superclass. ParameterizedType parameterizedType = requireNonNull((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> newArtificialTypeVariable( D declaration, String name, Type... bounds) { return newTypeVariableImpl( 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 a human-readable string representation of {@code type}. * * <p>The format is subject to change. */ static String toString(Type type) { return (type instanceof Class) ? ((Class<?>) type).getName() : type.toString(); } @CheckForNull static Type getComponentType(Type type) { checkNotNull(type); AtomicReference<@Nullable Type> result = new AtomicReference<>(); new TypeVisitor() { @Override void visitTypeVariable(TypeVariable<?> t) { result.set(subtypeOfComponentType(t.getBounds())); } @Override void visitWildcardType(WildcardType t) { result.set(subtypeOfComponentType(t.getUpperBounds())); } @Override void visitGenericArrayType(GenericArrayType t) { result.set(t.getGenericComponentType()); } @Override void visitClass(Class<?> t) { result.set(t.getComponentType()); } }.visit(type); return result.get(); } /** * Returns {@code ? extends X} if any of {@code bounds} is a subtype of {@code X[]}; or null * otherwise. */ @CheckForNull 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; } 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(@CheckForNull 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 { @CheckForNull private final Type ownerType; private final ImmutableList<Type> argumentsList; private final Class<?> rawType; ParameterizedTypeImpl(@CheckForNull 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 @CheckForNull public Type getOwnerType() { return ownerType; } @Override public String toString() { StringBuilder builder = new StringBuilder(); if (ownerType != null && JavaVersion.CURRENT.jdkTypeDuplicatesOwnerName()) { builder.append(JavaVersion.CURRENT.typeName(ownerType)).append('.'); } return builder .append(rawType.getName()) .append('<') .append(COMMA_JOINER.join(transform(argumentsList, JavaVersion.CURRENT::typeName))) .append('>') .toString(); } @Override public int hashCode() { return (ownerType == null ? 0 : ownerType.hashCode()) ^ argumentsList.hashCode() ^ rawType.hashCode(); } @Override public boolean equals(@CheckForNull 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 <D extends GenericDeclaration> TypeVariable<D> newTypeVariableImpl( D genericDeclaration, String name, Type[] bounds) { TypeVariableImpl<D> typeVariableImpl = new TypeVariableImpl<>(genericDeclaration, name, bounds); @SuppressWarnings("unchecked") TypeVariable<D> typeVariable = Reflection.newProxy( TypeVariable.class, new TypeVariableInvocationHandler(typeVariableImpl)); return typeVariable; } /** * Invocation handler to work around a compatibility problem between Java 7 and Java 8. * * <p>Java 8 introduced a new method {@code getAnnotatedBounds()} in the {@link TypeVariable} * interface, whose return type {@code AnnotatedType[]} is also new in Java 8. That means that we * cannot implement that interface in source code in a way that will compile on both Java 7 and * Java 8. If we include the {@code getAnnotatedBounds()} method then its return type means it * won't compile on Java 7, while if we don't include the method then the compiler will complain * that an abstract method is unimplemented. So instead we use a dynamic proxy to get an * implementation. If the method being called on the {@code TypeVariable} instance has the same * name as one of the public methods of {@link TypeVariableImpl}, the proxy calls the same method * on its instance of {@code TypeVariableImpl}. Otherwise it throws {@link * UnsupportedOperationException}; this should only apply to {@code getAnnotatedBounds()}. This * does mean that users on Java 8 who obtain an instance of {@code TypeVariable} from {@link * TypeResolver#resolveType} will not be able to call {@code getAnnotatedBounds()} on it, but that * should hopefully be rare. * * <p>TODO(b/147144588): We are currently also missing the methods inherited from {@link * AnnotatedElement}, which {@code TypeVariable} began to extend only in Java 8. Those methods * refer only to types present in Java 7, so we could implement them in {@code TypeVariableImpl} * today. (We could probably then make {@code TypeVariableImpl} implement {@code AnnotatedElement} * so that we get partial compile-time checking.) * * <p>This workaround should be removed at a distant future time when we no longer support Java * versions earlier than 8. */ @SuppressWarnings("removal") // b/318391980 private static final class TypeVariableInvocationHandler implements InvocationHandler { private static final ImmutableMap<String, Method> typeVariableMethods; static { ImmutableMap.Builder<String, Method> builder = ImmutableMap.builder(); for (Method method : TypeVariableImpl.class.getMethods()) { if (method.getDeclaringClass().equals(TypeVariableImpl.class)) { try { method.setAccessible(true); } catch (AccessControlException e) { // OK: the method is accessible to us anyway. The setAccessible call is only for // unusual execution environments where that might not be true. } builder.put(method.getName(), method); } } typeVariableMethods = builder.buildKeepingLast(); } private final TypeVariableImpl<?> typeVariableImpl; TypeVariableInvocationHandler(TypeVariableImpl<?> typeVariableImpl) { this.typeVariableImpl = typeVariableImpl; } @Override @CheckForNull public Object invoke(Object proxy, Method method, @CheckForNull @Nullable Object[] args) throws Throwable { String methodName = method.getName(); Method typeVariableMethod = typeVariableMethods.get(methodName); if (typeVariableMethod == null) { throw new UnsupportedOperationException(methodName); } else { try { return typeVariableMethod.invoke(typeVariableImpl, args); } catch (InvocationTargetException e) { throw e.getCause(); } } } } private static final class TypeVariableImpl<D extends GenericDeclaration> { 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); } public Type[] getBounds() { return toArray(bounds); } public D getGenericDeclaration() { return genericDeclaration; } public String getName() { return name; } public String getTypeName() { return name; } @Override public String toString() { return name; } @Override public int hashCode() { return genericDeclaration.hashCode() ^ name.hashCode(); } @Override public boolean equals(@CheckForNull Object obj) { if (NativeTypeVariableEquals.NATIVE_TYPE_VARIABLE_ONLY) { // equal only to our TypeVariable implementation with identical bounds if (obj != null && Proxy.isProxyClass(obj.getClass()) && Proxy.getInvocationHandler(obj) instanceof TypeVariableInvocationHandler) { TypeVariableInvocationHandler typeVariableInvocationHandler = (TypeVariableInvocationHandler) Proxy.getInvocationHandler(obj); TypeVariableImpl<?> that = typeVariableInvocationHandler.typeVariableImpl; return name.equals(that.getName()) && genericDeclaration.equals(that.getGenericDeclaration()) && bounds.equals(that.bounds); } return false; } else { // equal to any TypeVariable implementation regardless of bounds 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(@CheckForNull 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(JavaVersion.CURRENT.typeName(lowerBound)); } for (Type upperBound : filterUpperBounds(upperBounds)) { builder.append(" extends ").append(JavaVersion.CURRENT.typeName(upperBound)); } return builder.toString(); } private static final long serialVersionUID = 0; } private static Type[] toArray(Collection<Type> types) { return types.toArray(new Type[0]); } 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 behavior is the same for all Java versions we support, delete this. 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); } }, JAVA8 { @Override Type newArrayType(Type componentType) { return JAVA7.newArrayType(componentType); } @Override Type usedInGenericType(Type type) { return JAVA7.usedInGenericType(type); } @Override String typeName(Type type) { try { Method getTypeName = Type.class.getMethod("getTypeName"); return (String) getTypeName.invoke(type); } catch (NoSuchMethodException e) { throw new AssertionError("Type.getTypeName should be available in Java 8"); } catch (InvocationTargetException | IllegalAccessException e) { throw new RuntimeException(e); } } }, JAVA9 { @Override Type newArrayType(Type componentType) { return JAVA8.newArrayType(componentType); } @Override Type usedInGenericType(Type type) { return JAVA8.usedInGenericType(type); } @Override String typeName(Type type) { return JAVA8.typeName(type); } @Override boolean jdkTypeDuplicatesOwnerName() { return false; } }; static final JavaVersion CURRENT; static { if (AnnotatedElement.class.isAssignableFrom(TypeVariable.class)) { if (new TypeCapture<Entry<String, int[][]>>() {}.capture() .toString() .contains("java.util.Map.java.util.Map")) { CURRENT = JAVA8; } else { CURRENT = JAVA9; } } else if (new TypeCapture<int[]>() {}.capture() instanceof Class) { CURRENT = JAVA7; } else { CURRENT = 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(); } String typeName(Type type) { return Types.toString(type); } boolean jdkTypeDuplicatesOwnerName() { return true; } } /** * Per <a href="https://code.google.com/p/guava-libraries/issues/detail?id=1635">issue 1635</a>, * In JDK 1.7.0_51-b13, {@link TypeVariableImpl#equals(Object)} is changed to no longer be equal * to custom TypeVariable implementations. As a result, we need to make sure our TypeVariable * implementation respects symmetry. Moreover, we don't want to reconstruct a native type variable * {@code <A>} using our implementation unless some of its bounds have changed in resolution. This * avoids creating unequal TypeVariable implementation unnecessarily. When the bounds do change, * however, it's fine for the synthetic TypeVariable to be unequal to any native TypeVariable * anyway. */ static final class NativeTypeVariableEquals<X> { static final boolean NATIVE_TYPE_VARIABLE_ONLY = !NativeTypeVariableEquals.class.getTypeParameters()[0].equals( newArtificialTypeVariable(NativeTypeVariableEquals.class, "X")); } private Types() {} }
google/guava
guava/src/com/google/common/reflect/Types.java
363
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.composite; import java.util.List; /** * Word. */ public class Word extends LetterComposite { /** * Constructor. */ public Word(List<Letter> letters) { letters.forEach(this::add); } /** * Constructor. * @param letters to include */ public Word(char... letters) { for (char letter : letters) { this.add(new Letter(letter)); } } @Override protected void printThisBefore() { System.out.print(" "); } }
smedals/java-design-patterns
composite/src/main/java/com/iluwatar/composite/Word.java
364
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.script; import org.elasticsearch.ElasticsearchParseException; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesArray; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.LoggingDeprecationHandler; import org.elasticsearch.common.xcontent.XContentHelper; import org.elasticsearch.xcontent.AbstractObjectParser; import org.elasticsearch.xcontent.ObjectParser; import org.elasticsearch.xcontent.ObjectParser.ValueType; import org.elasticsearch.xcontent.ParseField; import org.elasticsearch.xcontent.ToXContent; import org.elasticsearch.xcontent.ToXContentObject; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xcontent.XContentFactory; import org.elasticsearch.xcontent.XContentParser; import org.elasticsearch.xcontent.XContentParser.Token; import org.elasticsearch.xcontent.XContentType; import org.elasticsearch.xcontent.json.JsonXContent; import java.io.IOException; import java.io.InputStream; import java.io.UncheckedIOException; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.Objects; import java.util.function.BiConsumer; /** * {@link Script} represents used-defined input that can be used to * compile and execute a script from the {@link ScriptService} * based on the {@link ScriptType}. * * There are two types of scripts specified by {@link ScriptType}, * <code>INLINE</code>, and <code>STORED</code>. * * The following describes the expected parameters for each type of script: * * <ul> * <li> {@link ScriptType#INLINE} * <ul> * <li> {@link Script#lang} - specifies the language, defaults to {@link Script#DEFAULT_SCRIPT_LANG} * <li> {@link Script#idOrCode} - specifies the code to be compiled, must not be {@code null} * <li> {@link Script#options} - specifies the compiler options for this script; must not be {@code null}, * use an empty {@link Map} to specify no options * <li> {@link Script#params} - {@link Map} of user-defined parameters; must not be {@code null}, * use an empty {@link Map} to specify no params * </ul> * <li> {@link ScriptType#STORED} * <ul> * <li> {@link Script#lang} - the language will be specified when storing the script, so this should * be {@code null} * <li> {@link Script#idOrCode} - specifies the id of the stored script to be looked up, must not be {@code null} * <li> {@link Script#options} - compiler options will be specified when a stored script is stored, * so they have no meaning here and must be {@code null} * <li> {@link Script#params} - {@link Map} of user-defined parameters; must not be {@code null}, * use an empty {@link Map} to specify no params * </ul> * </ul> */ public final class Script implements ToXContentObject, Writeable { /** * The name of the of the default scripting language. */ public static final String DEFAULT_SCRIPT_LANG = "painless"; /** * The name of the default template language. */ public static final String DEFAULT_TEMPLATE_LANG = "mustache"; /** * The default {@link ScriptType}. */ public static final ScriptType DEFAULT_SCRIPT_TYPE = ScriptType.INLINE; /** * Compiler option for {@link XContentType} used for templates. */ public static final String CONTENT_TYPE_OPTION = "content_type"; /** * Standard {@link ParseField} for outer level of script queries. */ public static final ParseField SCRIPT_PARSE_FIELD = new ParseField("script"); /** * Standard {@link ParseField} for source on the inner level. */ public static final ParseField SOURCE_PARSE_FIELD = new ParseField("source"); /** * Standard {@link ParseField} for lang on the inner level. */ public static final ParseField LANG_PARSE_FIELD = new ParseField("lang"); /** * Standard {@link ParseField} for options on the inner level. */ public static final ParseField OPTIONS_PARSE_FIELD = new ParseField("options"); /** * Standard {@link ParseField} for params on the inner level. */ public static final ParseField PARAMS_PARSE_FIELD = new ParseField("params"); /** * Helper class used by {@link ObjectParser} to store mutable {@link Script} variables and then * construct an immutable {@link Script} object based on parsed XContent. */ private static final class Builder { private ScriptType type; private String lang; private String idOrCode; private Map<String, String> options; private Map<String, Object> params; private Builder() { // This cannot default to an empty map because options are potentially added at multiple points. this.options = new HashMap<>(); this.params = Collections.emptyMap(); } /** * Since inline scripts can accept code rather than just an id, they must also be able * to handle template parsing, hence the need for custom parsing code. Templates can * consist of either an {@link String} or a JSON object. If a JSON object is discovered * then the content type option must also be saved as a compiler option. */ private void setInline(XContentParser parser) { try { if (type != null) { throwOnlyOneOfType(); } type = ScriptType.INLINE; if (parser.currentToken() == Token.START_OBJECT) { // this is really for search templates, that need to be converted to json format XContentBuilder builder = XContentFactory.jsonBuilder(); idOrCode = Strings.toString(builder.copyCurrentStructure(parser)); options.put(CONTENT_TYPE_OPTION, XContentType.JSON.mediaType()); } else { idOrCode = parser.text(); } } catch (IOException exception) { throw new UncheckedIOException(exception); } } /** * Set both the id and the type of the stored script. */ private void setStored(String idOrCode) { if (type != null) { throwOnlyOneOfType(); } type = ScriptType.STORED; this.idOrCode = idOrCode; } /** * Helper method to throw an exception if more than one type of {@link Script} is specified. */ private static void throwOnlyOneOfType() { throw new IllegalArgumentException( "must only use one of [" + ScriptType.INLINE.getParseField().getPreferredName() + ", " + ScriptType.STORED.getParseField().getPreferredName() + "]" + " when specifying a script" ); } private void setLang(String lang) { this.lang = lang; } /** * Options may have already been added if an inline template was specified. * Appends the user-defined compiler options with the internal compiler options. */ private void setOptions(Map<String, String> options) { this.options.putAll(options); } private void setParams(Map<String, Object> params) { this.params = params; } /** * Validates the parameters and creates an {@link Script}. * @param defaultLang The default lang is not a compile-time constant and must be provided * at run-time this way in case a legacy default language is used from * previously stored queries. */ private Script build(String defaultLang) { if (type == null) { throw new IllegalArgumentException("must specify either [source] for an inline script or [id] for a stored script"); } if (type == ScriptType.INLINE) { if (lang == null) { lang = defaultLang; } if (idOrCode == null) { throw new IllegalArgumentException("must specify <id> for an inline script"); } if (options.size() > 1 || options.size() == 1 && options.get(CONTENT_TYPE_OPTION) == null) { options.remove(CONTENT_TYPE_OPTION); throw new IllegalArgumentException("illegal compiler options [" + options + "] specified"); } } else if (type == ScriptType.STORED) { if (lang != null) { throw new IllegalArgumentException("illegally specified <lang> for a stored script"); } if (idOrCode == null) { throw new IllegalArgumentException("must specify <code> for a stored script"); } if (options.isEmpty()) { options = null; } else { throw new IllegalArgumentException( "field [" + OPTIONS_PARSE_FIELD.getPreferredName() + "] " + "cannot be specified using a stored script" ); } } return new Script(type, lang, idOrCode, options, params); } } private static final ObjectParser<Builder, Void> PARSER = new ObjectParser<>("script", Builder::new); static { // Defines the fields necessary to parse a Script as XContent using an ObjectParser. PARSER.declareField(Builder::setInline, parser -> parser, ScriptType.INLINE.getParseField(), ValueType.OBJECT_OR_STRING); PARSER.declareString(Builder::setStored, ScriptType.STORED.getParseField()); PARSER.declareString(Builder::setLang, LANG_PARSE_FIELD); PARSER.declareField(Builder::setOptions, XContentParser::mapStrings, OPTIONS_PARSE_FIELD, ValueType.OBJECT); PARSER.declareField(Builder::setParams, XContentParser::map, PARAMS_PARSE_FIELD, ValueType.OBJECT); } /** * Declare a script field on an {@link ObjectParser} with the standard name ({@code script}). * @param <T> Whatever type the {@linkplain ObjectParser} is parsing. * @param parser the parser itself * @param consumer the consumer for the script */ public static <T> void declareScript(AbstractObjectParser<T, ?> parser, BiConsumer<T, Script> consumer) { declareScript(parser, consumer, Script.SCRIPT_PARSE_FIELD); } /** * Declare a script field on an {@link ObjectParser}. * @param <T> Whatever type the {@linkplain ObjectParser} is parsing. * @param parser the parser itself * @param consumer the consumer for the script * @param parseField the field name */ public static <T> void declareScript(AbstractObjectParser<T, ?> parser, BiConsumer<T, Script> consumer, ParseField parseField) { parser.declareField(consumer, (p, c) -> Script.parse(p), parseField, ValueType.OBJECT_OR_STRING); } /** * Convenience method to call {@link Script#parse(XContentParser, String)} * using the default scripting language. */ public static Script parse(XContentParser parser) throws IOException { return parse(parser, DEFAULT_SCRIPT_LANG); } /** * Parse the script configured in the given settings. */ public static Script parse(Settings settings) { try (XContentBuilder builder = JsonXContent.contentBuilder()) { builder.startObject(); settings.toXContent(builder, ToXContent.EMPTY_PARAMS); builder.endObject(); try ( XContentParser parser = XContentHelper.createParserNotCompressed( LoggingDeprecationHandler.XCONTENT_PARSER_CONFIG, BytesReference.bytes(builder), XContentType.JSON ) ) { return parse(parser); } } catch (IOException e) { // it should not happen since we are not actually reading from a stream but an in-memory byte[] throw new IllegalStateException(e); } } /** * This will parse XContent into a {@link Script}. The following formats can be parsed: * * The simple format defaults to an {@link ScriptType#INLINE} with no compiler options or user-defined params: * * Example: * {@code * "return Math.log(doc.popularity) * 100;" * } * * The complex format where {@link ScriptType} and idOrCode are required while lang, options and params are not required. * * {@code * { * // Exactly one of "id" or "source" must be specified * "id" : "<id>", * // OR * "source": "<source>", * "lang" : "<lang>", * "options" : { * "option0" : "<option0>", * "option1" : "<option1>", * ... * }, * "params" : { * "param0" : "<param0>", * "param1" : "<param1>", * ... * } * } * } * * Example: * {@code * { * "source" : "return Math.log(doc.popularity) * params.multiplier", * "lang" : "painless", * "params" : { * "multiplier" : 100.0 * } * } * } * * This also handles templates in a special way. If a complexly formatted query is specified as another complex * JSON object the query is assumed to be a template, and the format will be preserved. * * {@code * { * "source" : { "query" : ... }, * "lang" : "<lang>", * "options" : { * "option0" : "<option0>", * "option1" : "<option1>", * ... * }, * "params" : { * "param0" : "<param0>", * "param1" : "<param1>", * ... * } * } * } * * @param parser The {@link XContentParser} to be used. * @param defaultLang The default language to use if no language is specified. The default language isn't necessarily * the one defined by {@link Script#DEFAULT_SCRIPT_LANG} due to backwards compatibility requirements * related to stored queries using previously default languages. * * @return The parsed {@link Script}. */ public static Script parse(XContentParser parser, String defaultLang) throws IOException { Objects.requireNonNull(defaultLang); Token token = parser.currentToken(); if (token == null) { token = parser.nextToken(); } if (token == Token.VALUE_STRING) { return new Script(ScriptType.INLINE, defaultLang, parser.text(), Collections.emptyMap()); } return PARSER.apply(parser, null).build(defaultLang); } /** * Parse a {@link Script} from an {@link Object}, that can either be a {@link String} or a {@link Map}. * @see #parse(XContentParser, String) * @param config The object to parse the script from. * @return The parsed {@link Script}. */ @SuppressWarnings("unchecked") public static Script parse(Object config) { Objects.requireNonNull(config, "Script must not be null"); if (config instanceof String) { return new Script((String) config); } else if (config instanceof Map) { Map<String, Object> configMap = (Map<String, Object>) config; String script = null; ScriptType type = null; String lang = null; Map<String, Object> params = Collections.emptyMap(); Map<String, String> options = Collections.emptyMap(); for (Map.Entry<String, Object> entry : configMap.entrySet()) { String parameterName = entry.getKey(); Object parameterValue = entry.getValue(); if (Script.LANG_PARSE_FIELD.match(parameterName, LoggingDeprecationHandler.INSTANCE)) { if (parameterValue instanceof String || parameterValue == null) { lang = (String) parameterValue; } else { throw new ElasticsearchParseException("Value must be of type String: [" + parameterName + "]"); } } else if (Script.PARAMS_PARSE_FIELD.match(parameterName, LoggingDeprecationHandler.INSTANCE)) { if (parameterValue instanceof Map || parameterValue == null) { params = (Map<String, Object>) parameterValue; } else { throw new ElasticsearchParseException("Value must be of type Map: [" + parameterName + "]"); } } else if (Script.OPTIONS_PARSE_FIELD.match(parameterName, LoggingDeprecationHandler.INSTANCE)) { if (parameterValue instanceof Map || parameterValue == null) { options = (Map<String, String>) parameterValue; } else { throw new ElasticsearchParseException("Value must be of type Map: [" + parameterName + "]"); } } else if (ScriptType.INLINE.getParseField().match(parameterName, LoggingDeprecationHandler.INSTANCE)) { if (parameterValue instanceof String || parameterValue == null) { script = (String) parameterValue; type = ScriptType.INLINE; } else { throw new ElasticsearchParseException("Value must be of type String: [" + parameterName + "]"); } } else if (ScriptType.STORED.getParseField().match(parameterName, LoggingDeprecationHandler.INSTANCE)) { if (parameterValue instanceof String || parameterValue == null) { script = (String) parameterValue; type = ScriptType.STORED; } else { throw new ElasticsearchParseException("Value must be of type String: [" + parameterName + "]"); } } else { throw new ElasticsearchParseException("Unsupported field [" + parameterName + "]"); } } if (script == null) { throw new ElasticsearchParseException( "Expected one of [{}] or [{}] fields, but found none", ScriptType.INLINE.getParseField().getPreferredName(), ScriptType.STORED.getParseField().getPreferredName() ); } assert type != null : "if script is not null, type should definitely not be null"; if (type == ScriptType.STORED) { if (lang != null) { throw new IllegalArgumentException( "[" + Script.LANG_PARSE_FIELD.getPreferredName() + "] cannot be specified for stored scripts" ); } return new Script(type, null, script, null, params); } else { return new Script(type, lang == null ? DEFAULT_SCRIPT_LANG : lang, script, options, params); } } else { throw new IllegalArgumentException("Script value should be a String or a Map"); } } private final ScriptType type; private final String lang; private final String idOrCode; private final Map<String, String> options; private final Map<String, Object> params; /** * Constructor for simple script using the default language and default type. * @param idOrCode The id or code to use dependent on the default script type. */ public Script(String idOrCode) { this(DEFAULT_SCRIPT_TYPE, DEFAULT_SCRIPT_LANG, idOrCode, Collections.emptyMap(), Collections.emptyMap()); } /** * Constructor for a script that does not need to use compiler options. * @param type The {@link ScriptType}. * @param lang The language for this {@link Script} if the {@link ScriptType} is {@link ScriptType#INLINE}. * For {@link ScriptType#STORED} scripts this should be null, but can * be specified to access scripts stored as part of the stored scripts deprecated API. * @param idOrCode The id for this {@link Script} if the {@link ScriptType} is {@link ScriptType#STORED}. * The code for this {@link Script} if the {@link ScriptType} is {@link ScriptType#INLINE}. * @param params The user-defined params to be bound for script execution. */ public Script(ScriptType type, String lang, String idOrCode, Map<String, Object> params) { this(type, lang, idOrCode, type == ScriptType.INLINE ? Collections.emptyMap() : null, params); } /** * Constructor for a script that requires the use of compiler options. * @param type The {@link ScriptType}. * @param lang The language for this {@link Script} if the {@link ScriptType} is {@link ScriptType#INLINE}. * For {@link ScriptType#STORED} scripts this should be null, but can * be specified to access scripts stored as part of the stored scripts deprecated API. * @param idOrCode The id for this {@link Script} if the {@link ScriptType} is {@link ScriptType#STORED}. * The code for this {@link Script} if the {@link ScriptType} is {@link ScriptType#INLINE}. * @param options The map of compiler options for this {@link Script} if the {@link ScriptType} * is {@link ScriptType#INLINE}, {@code null} otherwise. * @param params The user-defined params to be bound for script execution. */ public Script(ScriptType type, String lang, String idOrCode, Map<String, String> options, Map<String, Object> params) { this.type = Objects.requireNonNull(type); this.idOrCode = Objects.requireNonNull(idOrCode); this.params = Collections.unmodifiableMap(Objects.requireNonNull(params)); if (type == ScriptType.INLINE) { this.lang = Objects.requireNonNull(lang); this.options = Collections.unmodifiableMap(Objects.requireNonNull(options)); } else if (type == ScriptType.STORED) { if (lang != null) { throw new IllegalArgumentException("lang cannot be specified for stored scripts"); } this.lang = null; if (options != null) { throw new IllegalStateException("options cannot be specified for stored scripts"); } this.options = null; } else { throw new IllegalStateException("unknown script type [" + type.getName() + "]"); } } /** * Creates a {@link Script} read from an input stream. */ public Script(StreamInput in) throws IOException { this.type = ScriptType.readFrom(in); this.lang = in.readOptionalString(); this.idOrCode = in.readString(); @SuppressWarnings("unchecked") Map<String, String> options = (Map<String, String>) (Map) in.readGenericMap(); this.options = options; this.params = in.readGenericMap(); } @Override public void writeTo(StreamOutput out) throws IOException { type.writeTo(out); out.writeOptionalString(lang); out.writeString(idOrCode); @SuppressWarnings("unchecked") Map<String, Object> options = (Map<String, Object>) (Map) this.options; out.writeMapWithConsistentOrder(options); out.writeMapWithConsistentOrder(params); } /** * This will build scripts into the following XContent structure: * * {@code * { * "<(id, source)>" : "<idOrCode>", * "lang" : "<lang>", * "options" : { * "option0" : "<option0>", * "option1" : "<option1>", * ... * }, * "params" : { * "param0" : "<param0>", * "param1" : "<param1>", * ... * } * } * } * * Example: * {@code * { * "source" : "return Math.log(doc.popularity) * params.multiplier;", * "lang" : "painless", * "params" : { * "multiplier" : 100.0 * } * } * } * * Note that lang, options, and params will only be included if there have been any specified. * * This also handles templates in a special way. If the {@link Script#CONTENT_TYPE_OPTION} option * is provided and the {@link ScriptType#INLINE} is specified then the template will be preserved as a raw field. * * {@code * { * "source" : { "query" : ... }, * "lang" : "<lang>", * "options" : { * "option0" : "<option0>", * "option1" : "<option1>", * ... * }, * "params" : { * "param0" : "<param0>", * "param1" : "<param1>", * ... * } * } * } */ @Override public XContentBuilder toXContent(XContentBuilder builder, Params builderParams) throws IOException { builder.startObject(); String contentType = options == null ? null : options.get(CONTENT_TYPE_OPTION); if (type == ScriptType.INLINE) { if (contentType != null && builder.contentType().mediaType().equals(contentType)) { try (InputStream stream = new BytesArray(idOrCode).streamInput()) { builder.rawField(SOURCE_PARSE_FIELD.getPreferredName(), stream); } } else { builder.field(SOURCE_PARSE_FIELD.getPreferredName(), idOrCode); } } else { builder.field("id", idOrCode); } if (lang != null) { builder.field(LANG_PARSE_FIELD.getPreferredName(), lang); } if (options != null && options.isEmpty() == false) { builder.field(OPTIONS_PARSE_FIELD.getPreferredName(), options); } if (params.isEmpty() == false) { builder.field(PARAMS_PARSE_FIELD.getPreferredName(), params); } builder.endObject(); return builder; } /** * @return The {@link ScriptType} for this {@link Script}. */ public ScriptType getType() { return type; } /** * @return The language for this {@link Script} if the {@link ScriptType} is {@link ScriptType#INLINE}. * For {@link ScriptType#STORED} scripts this should be null, but can * be specified to access scripts stored as part of the stored scripts deprecated API. */ public String getLang() { return lang; } /** * @return The id for this {@link Script} if the {@link ScriptType} is {@link ScriptType#STORED}. * The code for this {@link Script} if the {@link ScriptType} is {@link ScriptType#INLINE}. */ public String getIdOrCode() { return idOrCode; } /** * @return The map of compiler options for this {@link Script} if the {@link ScriptType} * is {@link ScriptType#INLINE}, {@code null} otherwise. */ public Map<String, String> getOptions() { return options; } /** * @return The map of user-defined params for this {@link Script}. */ public Map<String, Object> getParams() { return params; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Script script = (Script) o; return type == script.type && Objects.equals(lang, script.lang) && Objects.equals(idOrCode, script.idOrCode) && Objects.equals(options, script.options) && Objects.equals(params, script.params); } @Override public int hashCode() { int result = type.hashCode(); result = 31 * result + (lang != null ? lang.hashCode() : 0); result = 31 * result + idOrCode.hashCode(); result = 31 * result + (options != null ? options.hashCode() : 0); result = 31 * result + params.hashCode(); return result; } @Override public String toString() { return "Script{" + "type=" + type + ", lang='" + lang + '\'' + ", idOrCode='" + idOrCode + '\'' + ", options=" + options + ", params=" + params + '}'; } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/script/Script.java
365
/* * 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 static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Predicates.compose; import static com.google.common.collect.CollectPreconditions.checkEntryNotNull; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT; import static java.util.Collections.singletonMap; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Converter; import com.google.common.base.Equivalence; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Preconditions; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.MapDifference.ValueDifference; import com.google.common.primitives.Ints; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.j2objc.annotations.RetainedWith; import com.google.j2objc.annotations.Weak; import com.google.j2objc.annotations.WeakOuter; import java.io.Serializable; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumMap; import java.util.Enumeration; import java.util.HashMap; import java.util.IdentityHashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Properties; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.Spliterator; import java.util.Spliterators; import java.util.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.BinaryOperator; import java.util.function.Consumer; import java.util.stream.Collector; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods pertaining to {@link Map} instances (including instances of {@link * SortedMap}, {@link BiMap}, etc.). Also see this class's counterparts {@link Lists}, {@link Sets} * and {@link Queues}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#maps">{@code Maps}</a>. * * @author Kevin Bourrillion * @author Mike Bostock * @author Isaac Shum * @author Louis Wasserman * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Maps { private Maps() {} private enum EntryFunction implements Function<Entry<?, ?>, @Nullable Object> { KEY { @Override @CheckForNull public Object apply(Entry<?, ?> entry) { return entry.getKey(); } }, VALUE { @Override @CheckForNull public Object apply(Entry<?, ?> entry) { return entry.getValue(); } }; } @SuppressWarnings("unchecked") static <K extends @Nullable Object> Function<Entry<K, ?>, K> keyFunction() { return (Function) EntryFunction.KEY; } @SuppressWarnings("unchecked") static <V extends @Nullable Object> Function<Entry<?, V>, V> valueFunction() { return (Function) EntryFunction.VALUE; } static <K extends @Nullable Object, V extends @Nullable Object> Iterator<K> keyIterator( Iterator<Entry<K, V>> entryIterator) { return new TransformedIterator<Entry<K, V>, K>(entryIterator) { @Override @ParametricNullness K transform(Entry<K, V> entry) { return entry.getKey(); } }; } static <K extends @Nullable Object, V extends @Nullable Object> Iterator<V> valueIterator( Iterator<Entry<K, V>> entryIterator) { return new TransformedIterator<Entry<K, V>, V>(entryIterator) { @Override @ParametricNullness V transform(Entry<K, V> entry) { return entry.getValue(); } }; } /** * Returns an immutable map instance containing the given entries. Internally, the returned map * will be backed by an {@link EnumMap}. * * <p>The iteration order of the returned map follows the enum's iteration order, not the order in * which the elements appear in the given map. * * @param map the map to make an immutable copy of * @return an immutable map containing those entries * @since 14.0 */ @GwtCompatible(serializable = true) public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap( Map<K, ? extends V> map) { if (map instanceof ImmutableEnumMap) { @SuppressWarnings("unchecked") // safe covariant cast ImmutableEnumMap<K, V> result = (ImmutableEnumMap<K, V>) map; return result; } Iterator<? extends Entry<K, ? extends V>> entryItr = map.entrySet().iterator(); if (!entryItr.hasNext()) { return ImmutableMap.of(); } Entry<K, ? extends V> entry1 = entryItr.next(); K key1 = entry1.getKey(); V value1 = entry1.getValue(); checkEntryNotNull(key1, value1); // Do something that works for j2cl, where we can't call getDeclaredClass(): EnumMap<K, V> enumMap = new EnumMap<>(singletonMap(key1, value1)); while (entryItr.hasNext()) { Entry<K, ? extends V> entry = entryItr.next(); K key = entry.getKey(); V value = entry.getValue(); checkEntryNotNull(key, value); enumMap.put(key, value); } return ImmutableEnumMap.asImmutable(enumMap); } /** * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys * and values are the result of applying the provided mapping functions to the input elements. The * resulting implementation is specialized for enum key types. The returned map and its views will * iterate over keys in their enum definition order, not encounter order. * * <p>If the mapped keys contain duplicates, an {@code IllegalArgumentException} is thrown when * the collection operation is performed. (This differs from the {@code Collector} returned by * {@link java.util.stream.Collectors#toMap(java.util.function.Function, * java.util.function.Function) Collectors.toMap(Function, Function)}, which throws an {@code * IllegalStateException}.) * * @since 21.0 */ public static <T extends @Nullable Object, K extends Enum<K>, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap( java.util.function.Function<? super T, ? extends K> keyFunction, java.util.function.Function<? super T, ? extends V> valueFunction) { return CollectCollectors.toImmutableEnumMap(keyFunction, valueFunction); } /** * Returns a {@link Collector} that accumulates elements into an {@code ImmutableMap} whose keys * and values are the result of applying the provided mapping functions to the input elements. The * resulting implementation is specialized for enum key types. The returned map and its views will * iterate over keys in their enum definition order, not encounter order. * * <p>If the mapped keys contain duplicates, the values are merged using the specified merging * function. * * @since 21.0 */ public static <T extends @Nullable Object, K extends Enum<K>, V> Collector<T, ?, ImmutableMap<K, V>> toImmutableEnumMap( java.util.function.Function<? super T, ? extends K> keyFunction, java.util.function.Function<? super T, ? extends V> valueFunction, BinaryOperator<V> mergeFunction) { return CollectCollectors.toImmutableEnumMap(keyFunction, valueFunction, mergeFunction); } /** * Creates a <i>mutable</i>, empty {@code HashMap} instance. * * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead. * * <p><b>Note:</b> if {@code K} is an {@code enum} type, use {@link #newEnumMap} instead. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code HashMap} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @return a new, empty {@code HashMap} */ public static <K extends @Nullable Object, V extends @Nullable Object> HashMap<K, V> newHashMap() { return new HashMap<>(); } /** * Creates a <i>mutable</i> {@code HashMap} instance with the same mappings as the specified map. * * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#copyOf(Map)} instead. * * <p><b>Note:</b> if {@code K} is an {@link Enum} type, use {@link #newEnumMap} instead. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code HashMap} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @param map the mappings to be placed in the new map * @return a new {@code HashMap} initialized with the mappings from {@code map} */ public static <K extends @Nullable Object, V extends @Nullable Object> HashMap<K, V> newHashMap( Map<? extends K, ? extends V> map) { return new HashMap<>(map); } /** * Creates a {@code HashMap} instance, with a high enough "initial capacity" that it <i>should</i> * hold {@code expectedSize} elements without growth. This behavior cannot be broadly guaranteed, * but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed that the method * isn't inadvertently <i>oversizing</i> the returned map. * * @param expectedSize the number of entries you expect to add to the returned map * @return a new, empty {@code HashMap} with enough capacity to hold {@code expectedSize} entries * without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative */ public static <K extends @Nullable Object, V extends @Nullable Object> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) { return new HashMap<>(capacity(expectedSize)); } /** * Returns a capacity that is sufficient to keep the map from being resized as long as it grows no * larger than expectedSize and the load factor is ≥ its default (0.75). */ static int capacity(int expectedSize) { if (expectedSize < 3) { checkNonnegative(expectedSize, "expectedSize"); return expectedSize + 1; } if (expectedSize < Ints.MAX_POWER_OF_TWO) { // This seems to be consistent across JDKs. The capacity argument to HashMap and LinkedHashMap // ends up being used to compute a "threshold" size, beyond which the internal table // will be resized. That threshold is ceilingPowerOfTwo(capacity*loadFactor), where // loadFactor is 0.75 by default. So with the calculation here we ensure that the // threshold is equal to ceilingPowerOfTwo(expectedSize). There is a separate code // path when the first operation on the new map is putAll(otherMap). There, prior to // https://github.com/openjdk/jdk/commit/3e393047e12147a81e2899784b943923fc34da8e, a bug // meant that sometimes a too-large threshold is calculated. However, this new threshold is // independent of the initial capacity, except that it won't be lower than the threshold // computed from that capacity. Because the internal table is only allocated on the first // write, we won't see copying because of the new threshold. So it is always OK to use the // calculation here. return (int) Math.ceil(expectedSize / 0.75); } return Integer.MAX_VALUE; // any large value } /** * Creates a <i>mutable</i>, empty, insertion-ordered {@code LinkedHashMap} instance. * * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#of()} instead. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code LinkedHashMap} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @return a new, empty {@code LinkedHashMap} */ public static <K extends @Nullable Object, V extends @Nullable Object> LinkedHashMap<K, V> newLinkedHashMap() { return new LinkedHashMap<>(); } /** * Creates a <i>mutable</i>, insertion-ordered {@code LinkedHashMap} instance with the same * mappings as the specified map. * * <p><b>Note:</b> if mutability is not required, use {@link ImmutableMap#copyOf(Map)} instead. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code LinkedHashMap} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @param map the mappings to be placed in the new map * @return a new, {@code LinkedHashMap} initialized with the mappings from {@code map} */ public static <K extends @Nullable Object, V extends @Nullable Object> LinkedHashMap<K, V> newLinkedHashMap(Map<? extends K, ? extends V> map) { return new LinkedHashMap<>(map); } /** * Creates a {@code LinkedHashMap} instance, with a high enough "initial capacity" that it * <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be * broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed * that the method isn't inadvertently <i>oversizing</i> the returned map. * * @param expectedSize the number of entries you expect to add to the returned map * @return a new, empty {@code LinkedHashMap} with enough capacity to hold {@code expectedSize} * entries without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative * @since 19.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> LinkedHashMap<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) { return new LinkedHashMap<>(capacity(expectedSize)); } /** * Creates a new empty {@link ConcurrentHashMap} instance. * * @since 3.0 */ public static <K, V> ConcurrentMap<K, V> newConcurrentMap() { return new ConcurrentHashMap<>(); } /** * Creates a <i>mutable</i>, empty {@code TreeMap} instance using the natural ordering of its * elements. * * <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedMap#of()} instead. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code TreeMap} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @return a new, empty {@code TreeMap} */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static <K extends Comparable, V extends @Nullable Object> TreeMap<K, V> newTreeMap() { return new TreeMap<>(); } /** * Creates a <i>mutable</i> {@code TreeMap} instance with the same mappings as the specified map * and using the same ordering as the specified map. * * <p><b>Note:</b> if mutability is not required, use {@link * ImmutableSortedMap#copyOfSorted(SortedMap)} instead. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code TreeMap} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @param map the sorted map whose mappings are to be placed in the new map and whose comparator * is to be used to sort the new map * @return a new {@code TreeMap} initialized with the mappings from {@code map} and using the * comparator of {@code map} */ public static <K extends @Nullable Object, V extends @Nullable Object> TreeMap<K, V> newTreeMap( SortedMap<K, ? extends V> map) { return new TreeMap<>(map); } /** * Creates a <i>mutable</i>, empty {@code TreeMap} instance using the given comparator. * * <p><b>Note:</b> if mutability is not required, use {@code * ImmutableSortedMap.orderedBy(comparator).build()} instead. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code TreeMap} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @param comparator the comparator to sort the keys with * @return a new, empty {@code TreeMap} */ public static <C extends @Nullable Object, K extends C, V extends @Nullable Object> TreeMap<K, V> newTreeMap(@CheckForNull Comparator<C> comparator) { // Ideally, the extra type parameter "C" shouldn't be necessary. It is a // work-around of a compiler type inference quirk that prevents the // following code from being compiled: // Comparator<Class<?>> comparator = null; // Map<Class<? extends Throwable>, String> map = newTreeMap(comparator); return new TreeMap<>(comparator); } /** * Creates an {@code EnumMap} instance. * * @param type the key type for this map * @return a new, empty {@code EnumMap} */ public static <K extends Enum<K>, V extends @Nullable Object> EnumMap<K, V> newEnumMap( Class<K> type) { return new EnumMap<>(checkNotNull(type)); } /** * Creates an {@code EnumMap} with the same mappings as the specified map. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code EnumMap} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @param map the map from which to initialize this {@code EnumMap} * @return a new {@code EnumMap} initialized with the mappings from {@code map} * @throws IllegalArgumentException if {@code m} is not an {@code EnumMap} instance and contains * no mappings */ public static <K extends Enum<K>, V extends @Nullable Object> EnumMap<K, V> newEnumMap( Map<K, ? extends V> map) { return new EnumMap<>(map); } /** * Creates an {@code IdentityHashMap} instance. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code IdentityHashMap} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @return a new, empty {@code IdentityHashMap} */ public static <K extends @Nullable Object, V extends @Nullable Object> IdentityHashMap<K, V> newIdentityHashMap() { return new IdentityHashMap<>(); } /** * Computes the difference between two maps. This difference is an immutable snapshot of the state * of the maps at the time this method is called. It will never change, even if the maps change at * a later time. * * <p>Since this method uses {@code HashMap} instances internally, the keys of the supplied maps * must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}. * * <p><b>Note:</b>If you only need to know whether two maps have the same mappings, call {@code * left.equals(right)} instead of this method. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @return the difference between the two maps */ public static <K extends @Nullable Object, V extends @Nullable Object> MapDifference<K, V> difference( Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) { if (left instanceof SortedMap) { @SuppressWarnings("unchecked") SortedMap<K, ? extends V> sortedLeft = (SortedMap<K, ? extends V>) left; return difference(sortedLeft, right); } return difference(left, right, Equivalence.equals()); } /** * Computes the difference between two maps. This difference is an immutable snapshot of the state * of the maps at the time this method is called. It will never change, even if the maps change at * a later time. * * <p>Since this method uses {@code HashMap} instances internally, the keys of the supplied maps * must be well-behaved with respect to {@link Object#equals} and {@link Object#hashCode}. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @param valueEquivalence the equivalence relationship to use to compare values * @return the difference between the two maps * @since 10.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> MapDifference<K, V> difference( Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super @NonNull V> valueEquivalence) { Preconditions.checkNotNull(valueEquivalence); Map<K, V> onlyOnLeft = newLinkedHashMap(); Map<K, V> onlyOnRight = new LinkedHashMap<>(right); // will whittle it down Map<K, V> onBoth = newLinkedHashMap(); Map<K, MapDifference.ValueDifference<V>> differences = newLinkedHashMap(); doDifference(left, right, valueEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences); return new MapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences); } /** * Computes the difference between two sorted maps, using the comparator of the left map, or * {@code Ordering.natural()} if the left map uses the natural ordering of its elements. This * difference is an immutable snapshot of the state of the maps at the time this method is called. * It will never change, even if the maps change at a later time. * * <p>Since this method uses {@code TreeMap} instances internally, the keys of the right map must * all compare as distinct according to the comparator of the left map. * * <p><b>Note:</b>If you only need to know whether two sorted maps have the same mappings, call * {@code left.equals(right)} instead of this method. * * @param left the map to treat as the "left" map for purposes of comparison * @param right the map to treat as the "right" map for purposes of comparison * @return the difference between the two maps * @since 11.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> SortedMapDifference<K, V> difference( SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) { checkNotNull(left); checkNotNull(right); Comparator<? super K> comparator = orNaturalOrder(left.comparator()); SortedMap<K, V> onlyOnLeft = Maps.newTreeMap(comparator); SortedMap<K, V> onlyOnRight = Maps.newTreeMap(comparator); onlyOnRight.putAll(right); // will whittle it down SortedMap<K, V> onBoth = Maps.newTreeMap(comparator); SortedMap<K, MapDifference.ValueDifference<V>> differences = Maps.newTreeMap(comparator); doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences); return new SortedMapDifferenceImpl<>(onlyOnLeft, onlyOnRight, onBoth, differences); } private static <K extends @Nullable Object, V extends @Nullable Object> void doDifference( Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super @NonNull V> valueEquivalence, Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth, Map<K, MapDifference.ValueDifference<V>> differences) { for (Entry<? extends K, ? extends V> entry : left.entrySet()) { K leftKey = entry.getKey(); V leftValue = entry.getValue(); if (right.containsKey(leftKey)) { /* * The cast is safe because onlyOnRight contains all the keys of right. * * TODO(cpovirk): Consider checking onlyOnRight.containsKey instead of right.containsKey. * That could change behavior if the input maps use different equivalence relations (and so * a key that appears once in `right` might appear multiple times in `left`). We don't * guarantee behavior in that case, anyway, and the current behavior is likely undesirable. * So that's either a reason to feel free to change it or a reason to not bother thinking * further about this. */ V rightValue = uncheckedCastNullableTToT(onlyOnRight.remove(leftKey)); if (valueEquivalence.equivalent(leftValue, rightValue)) { onBoth.put(leftKey, leftValue); } else { differences.put(leftKey, ValueDifferenceImpl.create(leftValue, rightValue)); } } else { onlyOnLeft.put(leftKey, leftValue); } } } private static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> unmodifiableMap( Map<K, ? extends V> map) { if (map instanceof SortedMap) { return Collections.unmodifiableSortedMap((SortedMap<K, ? extends V>) map); } else { return Collections.unmodifiableMap(map); } } static class MapDifferenceImpl<K extends @Nullable Object, V extends @Nullable Object> implements MapDifference<K, V> { final Map<K, V> onlyOnLeft; final Map<K, V> onlyOnRight; final Map<K, V> onBoth; final Map<K, ValueDifference<V>> differences; MapDifferenceImpl( Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth, Map<K, ValueDifference<V>> differences) { this.onlyOnLeft = unmodifiableMap(onlyOnLeft); this.onlyOnRight = unmodifiableMap(onlyOnRight); this.onBoth = unmodifiableMap(onBoth); this.differences = unmodifiableMap(differences); } @Override public boolean areEqual() { return onlyOnLeft.isEmpty() && onlyOnRight.isEmpty() && differences.isEmpty(); } @Override public Map<K, V> entriesOnlyOnLeft() { return onlyOnLeft; } @Override public Map<K, V> entriesOnlyOnRight() { return onlyOnRight; } @Override public Map<K, V> entriesInCommon() { return onBoth; } @Override public Map<K, ValueDifference<V>> entriesDiffering() { return differences; } @Override public boolean equals(@CheckForNull Object object) { if (object == this) { return true; } if (object instanceof MapDifference) { MapDifference<?, ?> other = (MapDifference<?, ?>) object; return entriesOnlyOnLeft().equals(other.entriesOnlyOnLeft()) && entriesOnlyOnRight().equals(other.entriesOnlyOnRight()) && entriesInCommon().equals(other.entriesInCommon()) && entriesDiffering().equals(other.entriesDiffering()); } return false; } @Override public int hashCode() { return Objects.hashCode( entriesOnlyOnLeft(), entriesOnlyOnRight(), entriesInCommon(), entriesDiffering()); } @Override public String toString() { if (areEqual()) { return "equal"; } StringBuilder result = new StringBuilder("not equal"); if (!onlyOnLeft.isEmpty()) { result.append(": only on left=").append(onlyOnLeft); } if (!onlyOnRight.isEmpty()) { result.append(": only on right=").append(onlyOnRight); } if (!differences.isEmpty()) { result.append(": value differences=").append(differences); } return result.toString(); } } static class ValueDifferenceImpl<V extends @Nullable Object> implements MapDifference.ValueDifference<V> { @ParametricNullness private final V left; @ParametricNullness private final V right; static <V extends @Nullable Object> ValueDifference<V> create( @ParametricNullness V left, @ParametricNullness V right) { return new ValueDifferenceImpl<>(left, right); } private ValueDifferenceImpl(@ParametricNullness V left, @ParametricNullness V right) { this.left = left; this.right = right; } @Override @ParametricNullness public V leftValue() { return left; } @Override @ParametricNullness public V rightValue() { return right; } @Override public boolean equals(@CheckForNull Object object) { if (object instanceof MapDifference.ValueDifference) { MapDifference.ValueDifference<?> that = (MapDifference.ValueDifference<?>) object; return Objects.equal(this.left, that.leftValue()) && Objects.equal(this.right, that.rightValue()); } return false; } @Override public int hashCode() { return Objects.hashCode(left, right); } @Override public String toString() { return "(" + left + ", " + right + ")"; } } static class SortedMapDifferenceImpl<K extends @Nullable Object, V extends @Nullable Object> extends MapDifferenceImpl<K, V> implements SortedMapDifference<K, V> { SortedMapDifferenceImpl( SortedMap<K, V> onlyOnLeft, SortedMap<K, V> onlyOnRight, SortedMap<K, V> onBoth, SortedMap<K, ValueDifference<V>> differences) { super(onlyOnLeft, onlyOnRight, onBoth, differences); } @Override public SortedMap<K, ValueDifference<V>> entriesDiffering() { return (SortedMap<K, ValueDifference<V>>) super.entriesDiffering(); } @Override public SortedMap<K, V> entriesInCommon() { return (SortedMap<K, V>) super.entriesInCommon(); } @Override public SortedMap<K, V> entriesOnlyOnLeft() { return (SortedMap<K, V>) super.entriesOnlyOnLeft(); } @Override public SortedMap<K, V> entriesOnlyOnRight() { return (SortedMap<K, V>) super.entriesOnlyOnRight(); } } /** * Returns the specified comparator if not null; otherwise returns {@code Ordering.natural()}. * This method is an abomination of generics; the only purpose of this method is to contain the * ugly type-casting in one place. */ @SuppressWarnings("unchecked") static <E extends @Nullable Object> Comparator<? super E> orNaturalOrder( @CheckForNull Comparator<? super E> comparator) { if (comparator != null) { // can't use ? : because of javac bug 5080917 return comparator; } return (Comparator<E>) Ordering.natural(); } /** * Returns a live {@link Map} view whose keys are the contents of {@code set} and whose values are * computed on demand using {@code function}. To get an immutable <i>copy</i> instead, use {@link * #toMap(Iterable, Function)}. * * <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping * {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code * entrySet} views of the returned map iterate in the same order as the backing set. * * <p>Modifications to the backing set are read through to the returned map. The returned map * supports removal operations if the backing set does. Removal operations write through to the * backing set. The returned map does not support put operations. * * <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the * set does not contain {@code null}, because the view cannot stop {@code null} from being added * to the set. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K}, * {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for * which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when * calling methods on the resulting map view. * * @since 14.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> asMap( Set<K> set, Function<? super K, V> function) { return new AsMapView<>(set, function); } /** * Returns a view of the sorted set as a map, mapping keys from the set according to the specified * function. * * <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping * {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code * entrySet} views of the returned map iterate in the same order as the backing set. * * <p>Modifications to the backing set are read through to the returned map. The returned map * supports removal operations if the backing set does. Removal operations write through to the * backing set. The returned map does not support put operations. * * <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the * set does not contain {@code null}, because the view cannot stop {@code null} from being added * to the set. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K}, * {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for * which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when * calling methods on the resulting map view. * * @since 14.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> asMap( SortedSet<K> set, Function<? super K, V> function) { return new SortedAsMapView<>(set, function); } /** * Returns a view of the navigable set as a map, mapping keys from the set according to the * specified function. * * <p>Specifically, for each {@code k} in the backing set, the returned map has an entry mapping * {@code k} to {@code function.apply(k)}. The {@code keySet}, {@code values}, and {@code * entrySet} views of the returned map iterate in the same order as the backing set. * * <p>Modifications to the backing set are read through to the returned map. The returned map * supports removal operations if the backing set does. Removal operations write through to the * backing set. The returned map does not support put operations. * * <p><b>Warning:</b> If the function rejects {@code null}, caution is required to make sure the * set does not contain {@code null}, because the view cannot stop {@code null} from being added * to the set. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of key type {@code K}, * {@code k.equals(k2)} implies that {@code k2} is also of type {@code K}. Using a key type for * which this may not hold, such as {@code ArrayList}, may risk a {@code ClassCastException} when * calling methods on the resulting map view. * * @since 14.0 */ @GwtIncompatible // NavigableMap public static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> asMap( NavigableSet<K> set, Function<? super K, V> function) { return new NavigableAsMapView<>(set, function); } private static class AsMapView<K extends @Nullable Object, V extends @Nullable Object> extends ViewCachingAbstractMap<K, V> { private final Set<K> set; final Function<? super K, V> function; Set<K> backingSet() { return set; } AsMapView(Set<K> set, Function<? super K, V> function) { this.set = checkNotNull(set); this.function = checkNotNull(function); } @Override public Set<K> createKeySet() { return removeOnlySet(backingSet()); } @Override Collection<V> createValues() { return Collections2.transform(set, function); } @Override public int size() { return backingSet().size(); } @Override public boolean containsKey(@CheckForNull Object key) { return backingSet().contains(key); } @Override @CheckForNull public V get(@CheckForNull Object key) { return getOrDefault(key, null); } @Override @CheckForNull public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) { if (Collections2.safeContains(backingSet(), key)) { @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it K k = (K) key; return function.apply(k); } else { return defaultValue; } } @Override @CheckForNull public V remove(@CheckForNull Object key) { if (backingSet().remove(key)) { @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it K k = (K) key; return function.apply(k); } else { return null; } } @Override public void clear() { backingSet().clear(); } @Override protected Set<Entry<K, V>> createEntrySet() { @WeakOuter class EntrySetImpl extends EntrySet<K, V> { @Override Map<K, V> map() { return AsMapView.this; } @Override public Iterator<Entry<K, V>> iterator() { return asMapEntryIterator(backingSet(), function); } } return new EntrySetImpl(); } @Override public void forEach(BiConsumer<? super K, ? super V> action) { checkNotNull(action); // avoids allocation of entries backingSet().forEach(k -> action.accept(k, function.apply(k))); } } static <K extends @Nullable Object, V extends @Nullable Object> Iterator<Entry<K, V>> asMapEntryIterator(Set<K> set, final Function<? super K, V> function) { return new TransformedIterator<K, Entry<K, V>>(set.iterator()) { @Override Entry<K, V> transform(@ParametricNullness final K key) { return immutableEntry(key, function.apply(key)); } }; } private static class SortedAsMapView<K extends @Nullable Object, V extends @Nullable Object> extends AsMapView<K, V> implements SortedMap<K, V> { SortedAsMapView(SortedSet<K> set, Function<? super K, V> function) { super(set, function); } @Override SortedSet<K> backingSet() { return (SortedSet<K>) super.backingSet(); } @Override @CheckForNull public Comparator<? super K> comparator() { return backingSet().comparator(); } @Override public Set<K> keySet() { return removeOnlySortedSet(backingSet()); } @Override public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { return asMap(backingSet().subSet(fromKey, toKey), function); } @Override public SortedMap<K, V> headMap(@ParametricNullness K toKey) { return asMap(backingSet().headSet(toKey), function); } @Override public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) { return asMap(backingSet().tailSet(fromKey), function); } @Override @ParametricNullness public K firstKey() { return backingSet().first(); } @Override @ParametricNullness public K lastKey() { return backingSet().last(); } } @GwtIncompatible // NavigableMap private static final class NavigableAsMapView< K extends @Nullable Object, V extends @Nullable Object> extends AbstractNavigableMap<K, V> { /* * Using AbstractNavigableMap is simpler than extending SortedAsMapView and rewriting all the * NavigableMap methods. */ private final NavigableSet<K> set; private final Function<? super K, V> function; NavigableAsMapView(NavigableSet<K> ks, Function<? super K, V> vFunction) { this.set = checkNotNull(ks); this.function = checkNotNull(vFunction); } @Override public NavigableMap<K, V> subMap( @ParametricNullness K fromKey, boolean fromInclusive, @ParametricNullness K toKey, boolean toInclusive) { return asMap(set.subSet(fromKey, fromInclusive, toKey, toInclusive), function); } @Override public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) { return asMap(set.headSet(toKey, inclusive), function); } @Override public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) { return asMap(set.tailSet(fromKey, inclusive), function); } @Override @CheckForNull public Comparator<? super K> comparator() { return set.comparator(); } @Override @CheckForNull public V get(@CheckForNull Object key) { return getOrDefault(key, null); } @Override @CheckForNull public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) { if (Collections2.safeContains(set, key)) { @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it K k = (K) key; return function.apply(k); } else { return defaultValue; } } @Override public void clear() { set.clear(); } @Override Iterator<Entry<K, V>> entryIterator() { return asMapEntryIterator(set, function); } @Override Spliterator<Entry<K, V>> entrySpliterator() { return CollectSpliterators.map(set.spliterator(), e -> immutableEntry(e, function.apply(e))); } @Override public void forEach(BiConsumer<? super K, ? super V> action) { set.forEach(k -> action.accept(k, function.apply(k))); } @Override Iterator<Entry<K, V>> descendingEntryIterator() { return descendingMap().entrySet().iterator(); } @Override public NavigableSet<K> navigableKeySet() { return removeOnlyNavigableSet(set); } @Override public int size() { return set.size(); } @Override public NavigableMap<K, V> descendingMap() { return asMap(set.descendingSet(), function); } } private static <E extends @Nullable Object> Set<E> removeOnlySet(final Set<E> set) { return new ForwardingSet<E>() { @Override protected Set<E> delegate() { return set; } @Override public boolean add(@ParametricNullness E element) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends E> es) { throw new UnsupportedOperationException(); } }; } private static <E extends @Nullable Object> SortedSet<E> removeOnlySortedSet( final SortedSet<E> set) { return new ForwardingSortedSet<E>() { @Override protected SortedSet<E> delegate() { return set; } @Override public boolean add(@ParametricNullness E element) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends E> es) { throw new UnsupportedOperationException(); } @Override public SortedSet<E> headSet(@ParametricNullness E toElement) { return removeOnlySortedSet(super.headSet(toElement)); } @Override public SortedSet<E> subSet( @ParametricNullness E fromElement, @ParametricNullness E toElement) { return removeOnlySortedSet(super.subSet(fromElement, toElement)); } @Override public SortedSet<E> tailSet(@ParametricNullness E fromElement) { return removeOnlySortedSet(super.tailSet(fromElement)); } }; } @GwtIncompatible // NavigableSet private static <E extends @Nullable Object> NavigableSet<E> removeOnlyNavigableSet( final NavigableSet<E> set) { return new ForwardingNavigableSet<E>() { @Override protected NavigableSet<E> delegate() { return set; } @Override public boolean add(@ParametricNullness E element) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends E> es) { throw new UnsupportedOperationException(); } @Override public SortedSet<E> headSet(@ParametricNullness E toElement) { return removeOnlySortedSet(super.headSet(toElement)); } @Override public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) { return removeOnlyNavigableSet(super.headSet(toElement, inclusive)); } @Override public SortedSet<E> subSet( @ParametricNullness E fromElement, @ParametricNullness E toElement) { return removeOnlySortedSet(super.subSet(fromElement, toElement)); } @Override public NavigableSet<E> subSet( @ParametricNullness E fromElement, boolean fromInclusive, @ParametricNullness E toElement, boolean toInclusive) { return removeOnlyNavigableSet( super.subSet(fromElement, fromInclusive, toElement, toInclusive)); } @Override public SortedSet<E> tailSet(@ParametricNullness E fromElement) { return removeOnlySortedSet(super.tailSet(fromElement)); } @Override public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) { return removeOnlyNavigableSet(super.tailSet(fromElement, inclusive)); } @Override public NavigableSet<E> descendingSet() { return removeOnlyNavigableSet(super.descendingSet()); } }; } /** * Returns an immutable map whose keys are the distinct elements of {@code keys} and whose value * for each key was computed by {@code valueFunction}. The map's iteration order is the order of * the first appearance of each key in {@code keys}. * * <p>When there are multiple instances of a key in {@code keys}, it is unspecified whether {@code * valueFunction} will be applied to more than one instance of that key and, if it is, which * result will be mapped to that key in the returned map. * * <p>If {@code keys} is a {@link Set}, a live view can be obtained instead of a copy using {@link * Maps#asMap(Set, Function)}. * * @throws NullPointerException if any element of {@code keys} is {@code null}, or if {@code * valueFunction} produces {@code null} for any key * @since 14.0 */ public static <K, V> ImmutableMap<K, V> toMap( Iterable<K> keys, Function<? super K, V> valueFunction) { return toMap(keys.iterator(), valueFunction); } /** * Returns an immutable map whose keys are the distinct elements of {@code keys} and whose value * for each key was computed by {@code valueFunction}. The map's iteration order is the order of * the first appearance of each key in {@code keys}. * * <p>When there are multiple instances of a key in {@code keys}, it is unspecified whether {@code * valueFunction} will be applied to more than one instance of that key and, if it is, which * result will be mapped to that key in the returned map. * * @throws NullPointerException if any element of {@code keys} is {@code null}, or if {@code * valueFunction} produces {@code null} for any key * @since 14.0 */ public static <K, V> ImmutableMap<K, V> toMap( Iterator<K> keys, Function<? super K, V> valueFunction) { checkNotNull(valueFunction); ImmutableMap.Builder<K, V> builder = ImmutableMap.builder(); while (keys.hasNext()) { K key = keys.next(); builder.put(key, valueFunction.apply(key)); } // Using buildKeepingLast() so as not to fail on duplicate keys return builder.buildKeepingLast(); } /** * Returns a map with the given {@code values}, indexed by keys derived from those values. In * other words, each input value produces an entry in the map whose key is the result of applying * {@code keyFunction} to that value. These entries appear in the same order as the input values. * Example usage: * * <pre>{@code * Color red = new Color("red", 255, 0, 0); * ... * ImmutableSet<Color> allColors = ImmutableSet.of(red, green, blue); * * ImmutableMap<String, Color> colorForName = * uniqueIndex(allColors, c -> c.toString()); * assertThat(colorForName).containsEntry("red", red); * }</pre> * * <p>If your index may associate multiple values with each key, use {@link * Multimaps#index(Iterable, Function) Multimaps.index}. * * <p><b>Note:</b> on Java 8+, it is usually better to use streams. For example: * * <pre>{@code * import static com.google.common.collect.ImmutableMap.toImmutableMap; * ... * ImmutableMap<String, Color> colorForName = * allColors.stream().collect(toImmutableMap(c -> c.toString(), c -> c)); * }</pre> * * <p>Streams provide a more standard and flexible API and the lambdas make it clear what the keys * and values in the map are. * * @param values the values to use when constructing the {@code Map} * @param keyFunction the function used to produce the key for each value * @return a map mapping the result of evaluating the function {@code keyFunction} on each value * in the input collection to that value * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one * value in the input collection * @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code * keyFunction} produces {@code null} for any value */ @CanIgnoreReturnValue public static <K, V> ImmutableMap<K, V> uniqueIndex( Iterable<V> values, Function<? super V, K> keyFunction) { if (values instanceof Collection) { return uniqueIndex( values.iterator(), keyFunction, ImmutableMap.builderWithExpectedSize(((Collection<?>) values).size())); } return uniqueIndex(values.iterator(), keyFunction); } /** * Returns a map with the given {@code values}, indexed by keys derived from those values. In * other words, each input value produces an entry in the map whose key is the result of applying * {@code keyFunction} to that value. These entries appear in the same order as the input values. * Example usage: * * <pre>{@code * Color red = new Color("red", 255, 0, 0); * ... * Iterator<Color> allColors = ImmutableSet.of(red, green, blue).iterator(); * * Map<String, Color> colorForName = * uniqueIndex(allColors, toStringFunction()); * assertThat(colorForName).containsEntry("red", red); * }</pre> * * <p>If your index may associate multiple values with each key, use {@link * Multimaps#index(Iterator, Function) Multimaps.index}. * * @param values the values to use when constructing the {@code Map} * @param keyFunction the function used to produce the key for each value * @return a map mapping the result of evaluating the function {@code keyFunction} on each value * in the input collection to that value * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one * value in the input collection * @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code * keyFunction} produces {@code null} for any value * @since 10.0 */ @CanIgnoreReturnValue public static <K, V> ImmutableMap<K, V> uniqueIndex( Iterator<V> values, Function<? super V, K> keyFunction) { return uniqueIndex(values, keyFunction, ImmutableMap.builder()); } private static <K, V> ImmutableMap<K, V> uniqueIndex( Iterator<V> values, Function<? super V, K> keyFunction, ImmutableMap.Builder<K, V> builder) { checkNotNull(keyFunction); while (values.hasNext()) { V value = values.next(); builder.put(keyFunction.apply(value), value); } try { return builder.buildOrThrow(); } catch (IllegalArgumentException duplicateKeys) { throw new IllegalArgumentException( duplicateKeys.getMessage() + ". To index multiple values under a key, use Multimaps.index."); } } /** * Creates an {@code ImmutableMap<String, String>} from a {@code Properties} instance. Properties * normally derive from {@code Map<Object, Object>}, but they typically contain strings, which is * awkward. This method lets you get a plain-old-{@code Map} out of a {@code Properties}. * * @param properties a {@code Properties} object to be converted * @return an immutable map containing all the entries in {@code properties} * @throws ClassCastException if any key in {@code properties} is not a {@code String} * @throws NullPointerException if any key or value in {@code properties} is null */ @J2ktIncompatible @GwtIncompatible // java.util.Properties public static ImmutableMap<String, String> fromProperties(Properties properties) { ImmutableMap.Builder<String, String> builder = ImmutableMap.builder(); for (Enumeration<?> e = properties.propertyNames(); e.hasMoreElements(); ) { /* * requireNonNull is safe because propertyNames contains only non-null elements. * * Accordingly, we have it annotated as returning `Enumeration<? extends Object>` in our * prototype checker's JDK. However, the checker still sees the return type as plain * `Enumeration<?>`, probably because of one of the following two bugs (and maybe those two * bugs are themselves just symptoms of the same underlying problem): * * https://github.com/typetools/checker-framework/issues/3030 * * https://github.com/typetools/checker-framework/issues/3236 */ String key = (String) requireNonNull(e.nextElement()); /* * requireNonNull is safe because the key came from propertyNames... * * ...except that it's possible for users to insert a string key with a non-string value, and * in that case, getProperty *will* return null. * * TODO(b/192002623): Handle that case: Either: * * - Skip non-string keys and values entirely, as proposed in the linked bug. * * - Throw ClassCastException instead of NullPointerException, as documented in the current * Javadoc. (Note that we can't necessarily "just" change our call to `getProperty` to `get` * because `get` does not consult the default properties.) */ builder.put(key, requireNonNull(properties.getProperty(key))); } return builder.buildOrThrow(); } /** * Returns an immutable map entry with the specified key and value. The {@link Entry#setValue} * operation throws an {@link UnsupportedOperationException}. * * <p>The returned entry is serializable. * * <p><b>Java 9 users:</b> consider using {@code java.util.Map.entry(key, value)} if the key and * value are non-null and the entry does not need to be serializable. * * @param key the key to be associated with the returned entry * @param value the value to be associated with the returned entry */ @GwtCompatible(serializable = true) public static <K extends @Nullable Object, V extends @Nullable Object> Entry<K, V> immutableEntry( @ParametricNullness K key, @ParametricNullness V value) { return new ImmutableEntry<>(key, value); } /** * Returns an unmodifiable view of the specified set of entries. The {@link Entry#setValue} * operation throws an {@link UnsupportedOperationException}, as do any operations that would * modify the returned set. * * @param entrySet the entries for which to return an unmodifiable view * @return an unmodifiable view of the entries */ static <K extends @Nullable Object, V extends @Nullable Object> Set<Entry<K, V>> unmodifiableEntrySet(Set<Entry<K, V>> entrySet) { return new UnmodifiableEntrySet<>(Collections.unmodifiableSet(entrySet)); } /** * Returns an unmodifiable view of the specified map entry. The {@link Entry#setValue} operation * throws an {@link UnsupportedOperationException}. This also has the side effect of redefining * {@code equals} to comply with the Entry contract, to avoid a possible nefarious implementation * of equals. * * @param entry the entry for which to return an unmodifiable view * @return an unmodifiable view of the entry */ static <K extends @Nullable Object, V extends @Nullable Object> Entry<K, V> unmodifiableEntry( final Entry<? extends K, ? extends V> entry) { checkNotNull(entry); return new AbstractMapEntry<K, V>() { @Override @ParametricNullness public K getKey() { return entry.getKey(); } @Override @ParametricNullness public V getValue() { return entry.getValue(); } }; } static <K extends @Nullable Object, V extends @Nullable Object> UnmodifiableIterator<Entry<K, V>> unmodifiableEntryIterator( final Iterator<Entry<K, V>> entryIterator) { return new UnmodifiableIterator<Entry<K, V>>() { @Override public boolean hasNext() { return entryIterator.hasNext(); } @Override public Entry<K, V> next() { return unmodifiableEntry(entryIterator.next()); } }; } /** The implementation of {@link Multimaps#unmodifiableEntries}. */ static class UnmodifiableEntries<K extends @Nullable Object, V extends @Nullable Object> extends ForwardingCollection<Entry<K, V>> { private final Collection<Entry<K, V>> entries; UnmodifiableEntries(Collection<Entry<K, V>> entries) { this.entries = entries; } @Override protected Collection<Entry<K, V>> delegate() { return entries; } @Override public Iterator<Entry<K, V>> iterator() { return unmodifiableEntryIterator(entries.iterator()); } // See java.util.Collections.UnmodifiableEntrySet for details on attacks. @Override public @Nullable Object[] toArray() { /* * standardToArray returns `@Nullable Object[]` rather than `Object[]` but because it can * be used with collections that may contain null. This collection never contains nulls, so we * could return `Object[]`. But this class is private and J2KT cannot change return types in * overrides, so we declare `@Nullable Object[]` as the return type. */ return standardToArray(); } @Override @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations public <T extends @Nullable Object> T[] toArray(T[] array) { return standardToArray(array); } } /** The implementation of {@link Maps#unmodifiableEntrySet(Set)}. */ static class UnmodifiableEntrySet<K extends @Nullable Object, V extends @Nullable Object> extends UnmodifiableEntries<K, V> implements Set<Entry<K, V>> { UnmodifiableEntrySet(Set<Entry<K, V>> entries) { super(entries); } // See java.util.Collections.UnmodifiableEntrySet for details on attacks. @Override public boolean equals(@CheckForNull Object object) { return Sets.equalsImpl(this, object); } @Override public int hashCode() { return Sets.hashCodeImpl(this); } } /** * Returns a {@link Converter} that converts values using {@link BiMap#get bimap.get()}, and whose * inverse view converts values using {@link BiMap#inverse bimap.inverse()}{@code .get()}. * * <p>To use a plain {@link Map} as a {@link Function}, see {@link * com.google.common.base.Functions#forMap(Map)} or {@link * com.google.common.base.Functions#forMap(Map, Object)}. * * @since 16.0 */ public static <A, B> Converter<A, B> asConverter(final BiMap<A, B> bimap) { return new BiMapConverter<>(bimap); } private static final class BiMapConverter<A, B> extends Converter<A, B> implements Serializable { private final BiMap<A, B> bimap; BiMapConverter(BiMap<A, B> bimap) { this.bimap = checkNotNull(bimap); } @Override protected B doForward(A a) { return convert(bimap, a); } @Override protected A doBackward(B b) { return convert(bimap.inverse(), b); } private static <X, Y> Y convert(BiMap<X, Y> bimap, X input) { Y output = bimap.get(input); checkArgument(output != null, "No non-null mapping present for input: %s", input); return output; } @Override public boolean equals(@CheckForNull Object object) { if (object instanceof BiMapConverter) { BiMapConverter<?, ?> that = (BiMapConverter<?, ?>) object; return this.bimap.equals(that.bimap); } return false; } @Override public int hashCode() { return bimap.hashCode(); } // There's really no good way to implement toString() without printing the entire BiMap, right? @Override public String toString() { return "Maps.asConverter(" + bimap + ")"; } private static final long serialVersionUID = 0L; } /** * Returns a synchronized (thread-safe) bimap backed by the specified bimap. In order to guarantee * serial access, it is critical that <b>all</b> access to the backing bimap is accomplished * through the returned bimap. * * <p>It is imperative that the user manually synchronize on the returned map when accessing any * of its collection views: * * <pre>{@code * BiMap<Long, String> map = Maps.synchronizedBiMap( * HashBiMap.<Long, String>create()); * ... * Set<Long> set = map.keySet(); // Needn't be in synchronized block * ... * synchronized (map) { // Synchronizing on map, not set! * Iterator<Long> it = set.iterator(); // Must be in synchronized block * while (it.hasNext()) { * foo(it.next()); * } * } * }</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned bimap will be serializable if the specified bimap is serializable. * * @param bimap the bimap to be wrapped in a synchronized view * @return a synchronized view of the specified bimap */ public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) { return Synchronized.biMap(bimap, null); } /** * Returns an unmodifiable view of the specified bimap. This method allows modules to provide * users with "read-only" access to internal bimaps. Query operations on the returned bimap "read * through" to the specified bimap, and attempts to modify the returned map, whether direct or via * its collection views, result in an {@code UnsupportedOperationException}. * * <p>The returned bimap will be serializable if the specified bimap is serializable. * * @param bimap the bimap for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified bimap */ public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> unmodifiableBiMap(BiMap<? extends K, ? extends V> bimap) { return new UnmodifiableBiMap<>(bimap, null); } /** * @see Maps#unmodifiableBiMap(BiMap) */ private static class UnmodifiableBiMap<K extends @Nullable Object, V extends @Nullable Object> extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable { final Map<K, V> unmodifiableMap; final BiMap<? extends K, ? extends V> delegate; @LazyInit @RetainedWith @CheckForNull BiMap<V, K> inverse; @LazyInit @CheckForNull transient Set<V> values; UnmodifiableBiMap(BiMap<? extends K, ? extends V> delegate, @CheckForNull BiMap<V, K> inverse) { unmodifiableMap = Collections.unmodifiableMap(delegate); this.delegate = delegate; this.inverse = inverse; } @Override protected Map<K, V> delegate() { return unmodifiableMap; } @Override @CheckForNull public V forcePut(@ParametricNullness K key, @ParametricNullness V value) { throw new UnsupportedOperationException(); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { throw new UnsupportedOperationException(); } @Override @CheckForNull public V putIfAbsent(K key, V value) { throw new UnsupportedOperationException(); } @Override public boolean remove(@Nullable Object key, @Nullable Object value) { throw new UnsupportedOperationException(); } @Override public boolean replace(K key, V oldValue, V newValue) { throw new UnsupportedOperationException(); } @Override @CheckForNull public V replace(K key, V value) { throw new UnsupportedOperationException(); } @Override public V computeIfAbsent( K key, java.util.function.Function<? super K, ? extends V> mappingFunction) { throw new UnsupportedOperationException(); } @Override @CheckForNull /* * Our checker arguably should produce a nullness error here until we see @NonNull in JDK APIs. * But it doesn't, which may be a sign that we still permit parameter contravariance in some * cases? */ public V computeIfPresent( K key, BiFunction<? super K, ? super @NonNull V, ? extends @Nullable V> remappingFunction) { throw new UnsupportedOperationException(); } @Override @CheckForNull public V compute( K key, BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction) { throw new UnsupportedOperationException(); } @Override @CheckForNull @SuppressWarnings("nullness") // TODO(b/262880368): Remove once we see @NonNull in JDK APIs public V merge( K key, @NonNull V value, BiFunction<? super @NonNull V, ? super @NonNull V, ? extends @Nullable V> function) { throw new UnsupportedOperationException(); } @Override public BiMap<V, K> inverse() { BiMap<V, K> result = inverse; return (result == null) ? inverse = new UnmodifiableBiMap<>(delegate.inverse(), this) : result; } @Override public Set<V> values() { Set<V> result = values; return (result == null) ? values = Collections.unmodifiableSet(delegate.values()) : result; } private static final long serialVersionUID = 0; } /** * Returns a view of a map where each value is transformed by a function. All other properties of * the map, such as iteration order, are left intact. For example, the code: * * <pre>{@code * Map<String, Integer> map = ImmutableMap.of("a", 4, "b", 9); * Function<Integer, Double> sqrt = * new Function<Integer, Double>() { * public Double apply(Integer in) { * return Math.sqrt((int) in); * } * }; * Map<String, Double> transformed = Maps.transformValues(map, sqrt); * System.out.println(transformed); * }</pre> * * ... prints {@code {a=2.0, b=3.0}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports * removal operations, and these are reflected in the underlying map. * * <p>It's acceptable for the underlying map to contain null keys, and even null values provided * that the function is capable of accepting null input. The transformed map might contain null * values, if the function sometimes gives a null result. * * <p>The returned map is not thread-safe or serializable, even if the underlying map is. * * <p>The function is applied lazily, invoked when needed. This is necessary for the returned map * to be a view, but it means that the function will be applied many times for bulk operations * like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code * function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a * view, copy the returned map into a new map of your choosing. */ public static < K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> Map<K, V2> transformValues(Map<K, V1> fromMap, Function<? super V1, V2> function) { return transformEntries(fromMap, asEntryTransformer(function)); } /** * Returns a view of a sorted map where each value is transformed by a function. All other * properties of the map, such as iteration order, are left intact. For example, the code: * * <pre>{@code * SortedMap<String, Integer> map = ImmutableSortedMap.of("a", 4, "b", 9); * Function<Integer, Double> sqrt = * new Function<Integer, Double>() { * public Double apply(Integer in) { * return Math.sqrt((int) in); * } * }; * SortedMap<String, Double> transformed = * Maps.transformValues(map, sqrt); * System.out.println(transformed); * }</pre> * * ... prints {@code {a=2.0, b=3.0}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports * removal operations, and these are reflected in the underlying map. * * <p>It's acceptable for the underlying map to contain null keys, and even null values provided * that the function is capable of accepting null input. The transformed map might contain null * values, if the function sometimes gives a null result. * * <p>The returned map is not thread-safe or serializable, even if the underlying map is. * * <p>The function is applied lazily, invoked when needed. This is necessary for the returned map * to be a view, but it means that the function will be applied many times for bulk operations * like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code * function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a * view, copy the returned map into a new map of your choosing. * * @since 11.0 */ public static < K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> SortedMap<K, V2> transformValues( SortedMap<K, V1> fromMap, Function<? super V1, V2> function) { return transformEntries(fromMap, asEntryTransformer(function)); } /** * Returns a view of a navigable map where each value is transformed by a function. All other * properties of the map, such as iteration order, are left intact. For example, the code: * * <pre>{@code * NavigableMap<String, Integer> map = Maps.newTreeMap(); * map.put("a", 4); * map.put("b", 9); * Function<Integer, Double> sqrt = * new Function<Integer, Double>() { * public Double apply(Integer in) { * return Math.sqrt((int) in); * } * }; * NavigableMap<String, Double> transformed = * Maps.transformNavigableValues(map, sqrt); * System.out.println(transformed); * }</pre> * * ... prints {@code {a=2.0, b=3.0}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports * removal operations, and these are reflected in the underlying map. * * <p>It's acceptable for the underlying map to contain null keys, and even null values provided * that the function is capable of accepting null input. The transformed map might contain null * values, if the function sometimes gives a null result. * * <p>The returned map is not thread-safe or serializable, even if the underlying map is. * * <p>The function is applied lazily, invoked when needed. This is necessary for the returned map * to be a view, but it means that the function will be applied many times for bulk operations * like {@link Map#containsValue} and {@code Map.toString()}. For this to perform well, {@code * function} should be fast. To avoid lazy evaluation when the returned map doesn't need to be a * view, copy the returned map into a new map of your choosing. * * @since 13.0 */ @GwtIncompatible // NavigableMap public static < K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> NavigableMap<K, V2> transformValues( NavigableMap<K, V1> fromMap, Function<? super V1, V2> function) { return transformEntries(fromMap, asEntryTransformer(function)); } /** * Returns a view of a map whose values are derived from the original map's entries. In contrast * to {@link #transformValues}, this method's entry-transformation logic may depend on the key as * well as the value. * * <p>All other properties of the transformed map, such as iteration order, are left intact. For * example, the code: * * <pre>{@code * Map<String, Boolean> options = * ImmutableMap.of("verbose", true, "sort", false); * EntryTransformer<String, Boolean, String> flagPrefixer = * new EntryTransformer<String, Boolean, String>() { * public String transformEntry(String key, Boolean value) { * return value ? key : "no" + key; * } * }; * Map<String, String> transformed = * Maps.transformEntries(options, flagPrefixer); * System.out.println(transformed); * }</pre> * * ... prints {@code {verbose=verbose, sort=nosort}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports * removal operations, and these are reflected in the underlying map. * * <p>It's acceptable for the underlying map to contain null keys and null values provided that * the transformer is capable of accepting null inputs. The transformed map might contain null * values if the transformer sometimes gives a null result. * * <p>The returned map is not thread-safe or serializable, even if the underlying map is. * * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned * map to be a view, but it means that the transformer will be applied many times for bulk * operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map * doesn't need to be a view, copy the returned map into a new map of your choosing. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the * transformed map. * * @since 7.0 */ public static < K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> Map<K, V2> transformEntries( Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return new TransformedEntriesMap<>(fromMap, transformer); } /** * Returns a view of a sorted map whose values are derived from the original sorted map's entries. * In contrast to {@link #transformValues}, this method's entry-transformation logic may depend on * the key as well as the value. * * <p>All other properties of the transformed map, such as iteration order, are left intact. For * example, the code: * * <pre>{@code * Map<String, Boolean> options = * ImmutableSortedMap.of("verbose", true, "sort", false); * EntryTransformer<String, Boolean, String> flagPrefixer = * new EntryTransformer<String, Boolean, String>() { * public String transformEntry(String key, Boolean value) { * return value ? key : "yes" + key; * } * }; * SortedMap<String, String> transformed = * Maps.transformEntries(options, flagPrefixer); * System.out.println(transformed); * }</pre> * * ... prints {@code {sort=yessort, verbose=verbose}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports * removal operations, and these are reflected in the underlying map. * * <p>It's acceptable for the underlying map to contain null keys and null values provided that * the transformer is capable of accepting null inputs. The transformed map might contain null * values if the transformer sometimes gives a null result. * * <p>The returned map is not thread-safe or serializable, even if the underlying map is. * * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned * map to be a view, but it means that the transformer will be applied many times for bulk * operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map * doesn't need to be a view, copy the returned map into a new map of your choosing. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the * transformed map. * * @since 11.0 */ public static < K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> SortedMap<K, V2> transformEntries( SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return new TransformedEntriesSortedMap<>(fromMap, transformer); } /** * Returns a view of a navigable map whose values are derived from the original navigable map's * entries. In contrast to {@link #transformValues}, this method's entry-transformation logic may * depend on the key as well as the value. * * <p>All other properties of the transformed map, such as iteration order, are left intact. For * example, the code: * * <pre>{@code * NavigableMap<String, Boolean> options = Maps.newTreeMap(); * options.put("verbose", false); * options.put("sort", true); * EntryTransformer<String, Boolean, String> flagPrefixer = * new EntryTransformer<String, Boolean, String>() { * public String transformEntry(String key, Boolean value) { * return value ? key : ("yes" + key); * } * }; * NavigableMap<String, String> transformed = * LabsMaps.transformNavigableEntries(options, flagPrefixer); * System.out.println(transformed); * }</pre> * * ... prints {@code {sort=yessort, verbose=verbose}}. * * <p>Changes in the underlying map are reflected in this view. Conversely, this view supports * removal operations, and these are reflected in the underlying map. * * <p>It's acceptable for the underlying map to contain null keys and null values provided that * the transformer is capable of accepting null inputs. The transformed map might contain null * values if the transformer sometimes gives a null result. * * <p>The returned map is not thread-safe or serializable, even if the underlying map is. * * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned * map to be a view, but it means that the transformer will be applied many times for bulk * operations like {@link Map#containsValue} and {@link Object#toString}. For this to perform * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned map * doesn't need to be a view, copy the returned map into a new map of your choosing. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the * transformed map. * * @since 13.0 */ @GwtIncompatible // NavigableMap public static < K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> NavigableMap<K, V2> transformEntries( NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return new TransformedEntriesNavigableMap<>(fromMap, transformer); } /** * A transformation of the value of a key-value pair, using both key and value as inputs. To apply * the transformation to a map, use {@link Maps#transformEntries(Map, EntryTransformer)}. * * @param <K> the key type of the input and output entries * @param <V1> the value type of the input entry * @param <V2> the value type of the output entry * @since 7.0 */ @FunctionalInterface public interface EntryTransformer< K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> { /** * Determines an output value based on a key-value pair. This method is <i>generally * expected</i>, but not absolutely required, to have the following properties: * * <ul> * <li>Its execution does not cause any observable side effects. * <li>The computation is <i>consistent with equals</i>; that is, {@link Objects#equal * Objects.equal}{@code (k1, k2) &&} {@link Objects#equal}{@code (v1, v2)} implies that * {@code Objects.equal(transformer.transform(k1, v1), transformer.transform(k2, v2))}. * </ul> * * @throws NullPointerException if the key or value is null and this transformer does not accept * null arguments */ @ParametricNullness V2 transformEntry(@ParametricNullness K key, @ParametricNullness V1 value); } /** Views a function as an entry transformer that ignores the entry key. */ static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> EntryTransformer<K, V1, V2> asEntryTransformer(final Function<? super V1, V2> function) { checkNotNull(function); return new EntryTransformer<K, V1, V2>() { @Override @ParametricNullness public V2 transformEntry(@ParametricNullness K key, @ParametricNullness V1 value) { return function.apply(value); } }; } static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> Function<V1, V2> asValueToValueFunction( final EntryTransformer<? super K, V1, V2> transformer, @ParametricNullness final K key) { checkNotNull(transformer); return new Function<V1, V2>() { @Override @ParametricNullness public V2 apply(@ParametricNullness V1 v1) { return transformer.transformEntry(key, v1); } }; } /** Views an entry transformer as a function from {@code Entry} to values. */ static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> Function<Entry<K, V1>, V2> asEntryToValueFunction( final EntryTransformer<? super K, ? super V1, V2> transformer) { checkNotNull(transformer); return new Function<Entry<K, V1>, V2>() { @Override @ParametricNullness public V2 apply(Entry<K, V1> entry) { return transformer.transformEntry(entry.getKey(), entry.getValue()); } }; } /** Returns a view of an entry transformed by the specified transformer. */ static <V2 extends @Nullable Object, K extends @Nullable Object, V1 extends @Nullable Object> Entry<K, V2> transformEntry( final EntryTransformer<? super K, ? super V1, V2> transformer, final Entry<K, V1> entry) { checkNotNull(transformer); checkNotNull(entry); return new AbstractMapEntry<K, V2>() { @Override @ParametricNullness public K getKey() { return entry.getKey(); } @Override @ParametricNullness public V2 getValue() { return transformer.transformEntry(entry.getKey(), entry.getValue()); } }; } /** Views an entry transformer as a function from entries to entries. */ static <K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> Function<Entry<K, V1>, Entry<K, V2>> asEntryToEntryFunction( final EntryTransformer<? super K, ? super V1, V2> transformer) { checkNotNull(transformer); return new Function<Entry<K, V1>, Entry<K, V2>>() { @Override public Entry<K, V2> apply(final Entry<K, V1> entry) { return transformEntry(transformer, entry); } }; } static class TransformedEntriesMap< K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> extends IteratorBasedAbstractMap<K, V2> { final Map<K, V1> fromMap; final EntryTransformer<? super K, ? super V1, V2> transformer; TransformedEntriesMap( Map<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { this.fromMap = checkNotNull(fromMap); this.transformer = checkNotNull(transformer); } @Override public int size() { return fromMap.size(); } @Override public boolean containsKey(@CheckForNull Object key) { return fromMap.containsKey(key); } @Override @CheckForNull public V2 get(@CheckForNull Object key) { return getOrDefault(key, null); } // safe as long as the user followed the <b>Warning</b> in the javadoc @SuppressWarnings("unchecked") @Override @CheckForNull public V2 getOrDefault(@CheckForNull Object key, @CheckForNull V2 defaultValue) { V1 value = fromMap.get(key); if (value != null || fromMap.containsKey(key)) { // The cast is safe because of the containsKey check. return transformer.transformEntry((K) key, uncheckedCastNullableTToT(value)); } return defaultValue; } // safe as long as the user followed the <b>Warning</b> in the javadoc @SuppressWarnings("unchecked") @Override @CheckForNull public V2 remove(@CheckForNull Object key) { return fromMap.containsKey(key) // The cast is safe because of the containsKey check. ? transformer.transformEntry((K) key, uncheckedCastNullableTToT(fromMap.remove(key))) : null; } @Override public void clear() { fromMap.clear(); } @Override public Set<K> keySet() { return fromMap.keySet(); } @Override Iterator<Entry<K, V2>> entryIterator() { return Iterators.transform( fromMap.entrySet().iterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer)); } @Override Spliterator<Entry<K, V2>> entrySpliterator() { return CollectSpliterators.map( fromMap.entrySet().spliterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer)); } @Override public void forEach(BiConsumer<? super K, ? super V2> action) { checkNotNull(action); // avoids creating new Entry<K, V2> objects fromMap.forEach((k, v1) -> action.accept(k, transformer.transformEntry(k, v1))); } @Override public Collection<V2> values() { return new Values<>(this); } } static class TransformedEntriesSortedMap< K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> extends TransformedEntriesMap<K, V1, V2> implements SortedMap<K, V2> { protected SortedMap<K, V1> fromMap() { return (SortedMap<K, V1>) fromMap; } TransformedEntriesSortedMap( SortedMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { super(fromMap, transformer); } @Override @CheckForNull public Comparator<? super K> comparator() { return fromMap().comparator(); } @Override @ParametricNullness public K firstKey() { return fromMap().firstKey(); } @Override public SortedMap<K, V2> headMap(@ParametricNullness K toKey) { return transformEntries(fromMap().headMap(toKey), transformer); } @Override @ParametricNullness public K lastKey() { return fromMap().lastKey(); } @Override public SortedMap<K, V2> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { return transformEntries(fromMap().subMap(fromKey, toKey), transformer); } @Override public SortedMap<K, V2> tailMap(@ParametricNullness K fromKey) { return transformEntries(fromMap().tailMap(fromKey), transformer); } } @GwtIncompatible // NavigableMap private static class TransformedEntriesNavigableMap< K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> extends TransformedEntriesSortedMap<K, V1, V2> implements NavigableMap<K, V2> { TransformedEntriesNavigableMap( NavigableMap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { super(fromMap, transformer); } @Override @CheckForNull public Entry<K, V2> ceilingEntry(@ParametricNullness K key) { return transformEntry(fromMap().ceilingEntry(key)); } @Override @CheckForNull public K ceilingKey(@ParametricNullness K key) { return fromMap().ceilingKey(key); } @Override public NavigableSet<K> descendingKeySet() { return fromMap().descendingKeySet(); } @Override public NavigableMap<K, V2> descendingMap() { return transformEntries(fromMap().descendingMap(), transformer); } @Override @CheckForNull public Entry<K, V2> firstEntry() { return transformEntry(fromMap().firstEntry()); } @Override @CheckForNull public Entry<K, V2> floorEntry(@ParametricNullness K key) { return transformEntry(fromMap().floorEntry(key)); } @Override @CheckForNull public K floorKey(@ParametricNullness K key) { return fromMap().floorKey(key); } @Override public NavigableMap<K, V2> headMap(@ParametricNullness K toKey) { return headMap(toKey, false); } @Override public NavigableMap<K, V2> headMap(@ParametricNullness K toKey, boolean inclusive) { return transformEntries(fromMap().headMap(toKey, inclusive), transformer); } @Override @CheckForNull public Entry<K, V2> higherEntry(@ParametricNullness K key) { return transformEntry(fromMap().higherEntry(key)); } @Override @CheckForNull public K higherKey(@ParametricNullness K key) { return fromMap().higherKey(key); } @Override @CheckForNull public Entry<K, V2> lastEntry() { return transformEntry(fromMap().lastEntry()); } @Override @CheckForNull public Entry<K, V2> lowerEntry(@ParametricNullness K key) { return transformEntry(fromMap().lowerEntry(key)); } @Override @CheckForNull public K lowerKey(@ParametricNullness K key) { return fromMap().lowerKey(key); } @Override public NavigableSet<K> navigableKeySet() { return fromMap().navigableKeySet(); } @Override @CheckForNull public Entry<K, V2> pollFirstEntry() { return transformEntry(fromMap().pollFirstEntry()); } @Override @CheckForNull public Entry<K, V2> pollLastEntry() { return transformEntry(fromMap().pollLastEntry()); } @Override public NavigableMap<K, V2> subMap( @ParametricNullness K fromKey, boolean fromInclusive, @ParametricNullness K toKey, boolean toInclusive) { return transformEntries( fromMap().subMap(fromKey, fromInclusive, toKey, toInclusive), transformer); } @Override public NavigableMap<K, V2> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { return subMap(fromKey, true, toKey, false); } @Override public NavigableMap<K, V2> tailMap(@ParametricNullness K fromKey) { return tailMap(fromKey, true); } @Override public NavigableMap<K, V2> tailMap(@ParametricNullness K fromKey, boolean inclusive) { return transformEntries(fromMap().tailMap(fromKey, inclusive), transformer); } @CheckForNull private Entry<K, V2> transformEntry(@CheckForNull Entry<K, V1> entry) { return (entry == null) ? null : Maps.transformEntry(transformer, entry); } @Override protected NavigableMap<K, V1> fromMap() { return (NavigableMap<K, V1>) super.fromMap(); } } static <K extends @Nullable Object> Predicate<Entry<K, ?>> keyPredicateOnEntries( Predicate<? super K> keyPredicate) { return compose(keyPredicate, Maps.<K>keyFunction()); } static <V extends @Nullable Object> Predicate<Entry<?, V>> valuePredicateOnEntries( Predicate<? super V> valuePredicate) { return compose(valuePredicate, Maps.<V>valueFunction()); } /** * Returns a map containing the mappings in {@code unfiltered} whose keys satisfy a predicate. The * returned map is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the map * and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and * {@code putAll()} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map * or its views, only mappings whose keys satisfy the filter will be removed from the underlying * map. * * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value * mapping in the underlying map and determine which satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at * {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. */ public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterKeys( Map<K, V> unfiltered, final Predicate<? super K> keyPredicate) { checkNotNull(keyPredicate); Predicate<Entry<K, ?>> entryPredicate = keyPredicateOnEntries(keyPredicate); return (unfiltered instanceof AbstractFilteredMap) ? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate) : new FilteredKeyMap<K, V>(checkNotNull(unfiltered), keyPredicate, entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} whose keys satisfy a * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the * other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the map * and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and * {@code putAll()} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map * or its views, only mappings whose keys satisfy the filter will be removed from the underlying * map. * * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value * mapping in the underlying map and determine which satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at * {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. * * @since 11.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> filterKeys( SortedMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { // TODO(lowasser): Return a subclass of Maps.FilteredKeyMap for slightly better // performance. return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); } /** * Returns a navigable map containing the mappings in {@code unfiltered} whose keys satisfy a * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the * other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the map * and its views. When given a key that doesn't satisfy the predicate, the map's {@code put()} and * {@code putAll()} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map * or its views, only mappings whose keys satisfy the filter will be removed from the underlying * map. * * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value * mapping in the underlying map and determine which satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at * {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. * * @since 14.0 */ @GwtIncompatible // NavigableMap public static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> filterKeys( NavigableMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { // TODO(lowasser): Return a subclass of Maps.FilteredKeyMap for slightly better // performance. return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); } /** * Returns a bimap containing the mappings in {@code unfiltered} whose keys satisfy a predicate. * The returned bimap is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the bimap * and its views. When given a key that doesn't satisfy the predicate, the bimap's {@code put()}, * {@code forcePut()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * bimap or its views, only mappings that satisfy the filter will be removed from the underlying * bimap. * * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key in * the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i> * needed, it may be faster to copy the filtered bimap and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented * at {@link Predicate#apply}. * * @since 14.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterKeys( BiMap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { checkNotNull(keyPredicate); return filterEntries(unfiltered, Maps.<K>keyPredicateOnEntries(keyPredicate)); } /** * Returns a map containing the mappings in {@code unfiltered} whose values satisfy a predicate. * The returned map is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the map * and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()}, * {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map * or its views, only mappings whose values satisfy the filter will be removed from the underlying * map. * * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value * mapping in the underlying map and determine which satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented * at {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. */ public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterValues( Map<K, V> unfiltered, final Predicate<? super V> valuePredicate) { return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); } /** * Returns a sorted map containing the mappings in {@code unfiltered} whose values satisfy a * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the * other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the map * and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()}, * {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map * or its views, only mappings whose values satisfy the filter will be removed from the underlying * map. * * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value * mapping in the underlying map and determine which satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented * at {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. * * @since 11.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> filterValues( SortedMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); } /** * Returns a navigable map containing the mappings in {@code unfiltered} whose values satisfy a * predicate. The returned map is a live view of {@code unfiltered}; changes to one affect the * other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the map * and its views. When given a value that doesn't satisfy the predicate, the map's {@code put()}, * {@code putAll()}, and {@link Entry#setValue} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map * or its views, only mappings whose values satisfy the filter will be removed from the underlying * map. * * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value * mapping in the underlying map and determine which satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented * at {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. * * @since 14.0 */ @GwtIncompatible // NavigableMap public static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> filterValues( NavigableMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); } /** * Returns a bimap containing the mappings in {@code unfiltered} whose values satisfy a predicate. * The returned bimap is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the bimap * and its views. When given a value that doesn't satisfy the predicate, the bimap's {@code * put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link * IllegalArgumentException}. Similarly, the map's entries have a {@link Entry#setValue} method * that throws an {@link IllegalArgumentException} when the provided value doesn't satisfy the * predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * bimap or its views, only mappings that satisfy the filter will be removed from the underlying * bimap. * * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every value in * the underlying bimap and determine which satisfy the filter. When a live view is <i>not</i> * needed, it may be faster to copy the filtered bimap and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented * at {@link Predicate#apply}. * * @since 14.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterValues( BiMap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); } /** * Returns a map containing the mappings in {@code unfiltered} that satisfy a predicate. The * returned map is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the map * and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code * put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the * map's entries have a {@link Entry#setValue} method that throws an {@link * IllegalArgumentException} when the existing key and the provided value don't satisfy the * predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map * or its views, only mappings that satisfy the filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value * mapping in the underlying map and determine which satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented * at {@link Predicate#apply}. */ public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterEntries( Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(entryPredicate); return (unfiltered instanceof AbstractFilteredMap) ? filterFiltered((AbstractFilteredMap<K, V>) unfiltered, entryPredicate) : new FilteredEntryMap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} that satisfy a predicate. * The returned map is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the map * and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code * put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the * map's entries have a {@link Entry#setValue} method that throws an {@link * IllegalArgumentException} when the existing key and the provided value don't satisfy the * predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map * or its views, only mappings that satisfy the filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value * mapping in the underlying map and determine which satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented * at {@link Predicate#apply}. * * @since 11.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> filterEntries( SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(entryPredicate); return (unfiltered instanceof FilteredEntrySortedMap) ? filterFiltered((FilteredEntrySortedMap<K, V>) unfiltered, entryPredicate) : new FilteredEntrySortedMap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Returns a sorted map containing the mappings in {@code unfiltered} that satisfy a predicate. * The returned map is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting map's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the map * and its views. When given a key/value pair that doesn't satisfy the predicate, the map's {@code * put()} and {@code putAll()} methods throw an {@link IllegalArgumentException}. Similarly, the * map's entries have a {@link Entry#setValue} method that throws an {@link * IllegalArgumentException} when the existing key and the provided value don't satisfy the * predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered map * or its views, only mappings that satisfy the filter will be removed from the underlying map. * * <p>The returned map isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered map's methods, such as {@code size()}, iterate across every key/value * mapping in the underlying map and determine which satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy the filtered map and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented * at {@link Predicate#apply}. * * @since 14.0 */ @GwtIncompatible // NavigableMap public static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> filterEntries( NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(entryPredicate); return (unfiltered instanceof FilteredEntryNavigableMap) ? filterFiltered((FilteredEntryNavigableMap<K, V>) unfiltered, entryPredicate) : new FilteredEntryNavigableMap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Returns a bimap containing the mappings in {@code unfiltered} that satisfy a predicate. The * returned bimap is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting bimap's {@code keySet()}, {@code entrySet()}, and {@code values()} views have * iterators that don't support {@code remove()}, but all other methods are supported by the bimap * and its views. When given a key/value pair that doesn't satisfy the predicate, the bimap's * {@code put()}, {@code forcePut()} and {@code putAll()} methods throw an {@link * IllegalArgumentException}. Similarly, the map's entries have an {@link Entry#setValue} method * that throws an {@link IllegalArgumentException} when the existing key and the provided value * don't satisfy the predicate. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * bimap or its views, only mappings that satisfy the filter will be removed from the underlying * bimap. * * <p>The returned bimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered bimap's methods, such as {@code size()}, iterate across every key/value * mapping in the underlying bimap and determine which satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy the filtered bimap and use the copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals </i>, as documented * at {@link Predicate#apply}. * * @since 14.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterEntries( BiMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(unfiltered); checkNotNull(entryPredicate); return (unfiltered instanceof FilteredEntryBiMap) ? filterFiltered((FilteredEntryBiMap<K, V>) unfiltered, entryPredicate) : new FilteredEntryBiMap<K, V>(unfiltered, entryPredicate); } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered * map. */ private static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> filterFiltered( AbstractFilteredMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { return new FilteredEntryMap<>( map.unfiltered, Predicates.<Entry<K, V>>and(map.predicate, entryPredicate)); } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered * sorted map. */ private static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> filterFiltered( FilteredEntrySortedMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.predicate, entryPredicate); return new FilteredEntrySortedMap<>(map.sortedMap(), predicate); } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered * navigable map. */ @GwtIncompatible // NavigableMap private static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> filterFiltered( FilteredEntryNavigableMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.entryPredicate, entryPredicate); return new FilteredEntryNavigableMap<>(map.unfiltered, predicate); } /** * Support {@code clear()}, {@code removeAll()}, and {@code retainAll()} when filtering a filtered * map. */ private static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> filterFiltered( FilteredEntryBiMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(map.predicate, entryPredicate); return new FilteredEntryBiMap<>(map.unfiltered(), predicate); } private abstract static class AbstractFilteredMap< K extends @Nullable Object, V extends @Nullable Object> extends ViewCachingAbstractMap<K, V> { final Map<K, V> unfiltered; final Predicate<? super Entry<K, V>> predicate; AbstractFilteredMap(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) { this.unfiltered = unfiltered; this.predicate = predicate; } boolean apply(@CheckForNull Object key, @ParametricNullness V value) { // This method is called only when the key is in the map (or about to be added to the map), // implying that key is a K. @SuppressWarnings({"unchecked", "nullness"}) K k = (K) key; return predicate.apply(Maps.immutableEntry(k, value)); } @Override @CheckForNull public V put(@ParametricNullness K key, @ParametricNullness V value) { checkArgument(apply(key, value)); return unfiltered.put(key, value); } @Override public void putAll(Map<? extends K, ? extends V> map) { for (Entry<? extends K, ? extends V> entry : map.entrySet()) { checkArgument(apply(entry.getKey(), entry.getValue())); } unfiltered.putAll(map); } @Override public boolean containsKey(@CheckForNull Object key) { return unfiltered.containsKey(key) && apply(key, unfiltered.get(key)); } @Override @CheckForNull public V get(@CheckForNull Object key) { V value = unfiltered.get(key); return ((value != null) && apply(key, value)) ? value : null; } @Override public boolean isEmpty() { return entrySet().isEmpty(); } @Override @CheckForNull public V remove(@CheckForNull Object key) { return containsKey(key) ? unfiltered.remove(key) : null; } @Override Collection<V> createValues() { return new FilteredMapValues<>(this, unfiltered, predicate); } } private static final class FilteredMapValues< K extends @Nullable Object, V extends @Nullable Object> extends Maps.Values<K, V> { final Map<K, V> unfiltered; final Predicate<? super Entry<K, V>> predicate; FilteredMapValues( Map<K, V> filteredMap, Map<K, V> unfiltered, Predicate<? super Entry<K, V>> predicate) { super(filteredMap); this.unfiltered = unfiltered; this.predicate = predicate; } @Override public boolean remove(@CheckForNull Object o) { Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator(); while (entryItr.hasNext()) { Entry<K, V> entry = entryItr.next(); if (predicate.apply(entry) && Objects.equal(entry.getValue(), o)) { entryItr.remove(); return true; } } return false; } @Override public boolean removeAll(Collection<?> collection) { Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator(); boolean result = false; while (entryItr.hasNext()) { Entry<K, V> entry = entryItr.next(); if (predicate.apply(entry) && collection.contains(entry.getValue())) { entryItr.remove(); result = true; } } return result; } @Override public boolean retainAll(Collection<?> collection) { Iterator<Entry<K, V>> entryItr = unfiltered.entrySet().iterator(); boolean result = false; while (entryItr.hasNext()) { Entry<K, V> entry = entryItr.next(); if (predicate.apply(entry) && !collection.contains(entry.getValue())) { entryItr.remove(); result = true; } } return result; } @Override public @Nullable Object[] toArray() { // creating an ArrayList so filtering happens once return Lists.newArrayList(iterator()).toArray(); } @Override @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations public <T extends @Nullable Object> T[] toArray(T[] array) { return Lists.newArrayList(iterator()).toArray(array); } } private static class FilteredKeyMap<K extends @Nullable Object, V extends @Nullable Object> extends AbstractFilteredMap<K, V> { final Predicate<? super K> keyPredicate; FilteredKeyMap( Map<K, V> unfiltered, Predicate<? super K> keyPredicate, Predicate<? super Entry<K, V>> entryPredicate) { super(unfiltered, entryPredicate); this.keyPredicate = keyPredicate; } @Override protected Set<Entry<K, V>> createEntrySet() { return Sets.filter(unfiltered.entrySet(), predicate); } @Override Set<K> createKeySet() { return Sets.filter(unfiltered.keySet(), keyPredicate); } // The cast is called only when the key is in the unfiltered map, implying // that key is a K. @Override @SuppressWarnings("unchecked") public boolean containsKey(@CheckForNull Object key) { return unfiltered.containsKey(key) && keyPredicate.apply((K) key); } } static class FilteredEntryMap<K extends @Nullable Object, V extends @Nullable Object> extends AbstractFilteredMap<K, V> { /** * Entries in this set satisfy the predicate, but they don't validate the input to {@code * Entry.setValue()}. */ final Set<Entry<K, V>> filteredEntrySet; FilteredEntryMap(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { super(unfiltered, entryPredicate); filteredEntrySet = Sets.filter(unfiltered.entrySet(), predicate); } @Override protected Set<Entry<K, V>> createEntrySet() { return new EntrySet(); } @WeakOuter private class EntrySet extends ForwardingSet<Entry<K, V>> { @Override protected Set<Entry<K, V>> delegate() { return filteredEntrySet; } @Override public Iterator<Entry<K, V>> iterator() { return new TransformedIterator<Entry<K, V>, Entry<K, V>>(filteredEntrySet.iterator()) { @Override Entry<K, V> transform(final Entry<K, V> entry) { return new ForwardingMapEntry<K, V>() { @Override protected Entry<K, V> delegate() { return entry; } @Override @ParametricNullness public V setValue(@ParametricNullness V newValue) { checkArgument(apply(getKey(), newValue)); return super.setValue(newValue); } }; } }; } } @Override Set<K> createKeySet() { return new KeySet(); } static <K extends @Nullable Object, V extends @Nullable Object> boolean removeAllKeys( Map<K, V> map, Predicate<? super Entry<K, V>> entryPredicate, Collection<?> keyCollection) { Iterator<Entry<K, V>> entryItr = map.entrySet().iterator(); boolean result = false; while (entryItr.hasNext()) { Entry<K, V> entry = entryItr.next(); if (entryPredicate.apply(entry) && keyCollection.contains(entry.getKey())) { entryItr.remove(); result = true; } } return result; } static <K extends @Nullable Object, V extends @Nullable Object> boolean retainAllKeys( Map<K, V> map, Predicate<? super Entry<K, V>> entryPredicate, Collection<?> keyCollection) { Iterator<Entry<K, V>> entryItr = map.entrySet().iterator(); boolean result = false; while (entryItr.hasNext()) { Entry<K, V> entry = entryItr.next(); if (entryPredicate.apply(entry) && !keyCollection.contains(entry.getKey())) { entryItr.remove(); result = true; } } return result; } @WeakOuter class KeySet extends Maps.KeySet<K, V> { KeySet() { super(FilteredEntryMap.this); } @Override public boolean remove(@CheckForNull Object o) { if (containsKey(o)) { unfiltered.remove(o); return true; } return false; } @Override public boolean removeAll(Collection<?> collection) { return removeAllKeys(unfiltered, predicate, collection); } @Override public boolean retainAll(Collection<?> collection) { return retainAllKeys(unfiltered, predicate, collection); } @Override public @Nullable Object[] toArray() { // creating an ArrayList so filtering happens once return Lists.newArrayList(iterator()).toArray(); } @Override @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations public <T extends @Nullable Object> T[] toArray(T[] array) { return Lists.newArrayList(iterator()).toArray(array); } } } private static class FilteredEntrySortedMap< K extends @Nullable Object, V extends @Nullable Object> extends FilteredEntryMap<K, V> implements SortedMap<K, V> { FilteredEntrySortedMap( SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { super(unfiltered, entryPredicate); } SortedMap<K, V> sortedMap() { return (SortedMap<K, V>) unfiltered; } @Override public SortedSet<K> keySet() { return (SortedSet<K>) super.keySet(); } @Override SortedSet<K> createKeySet() { return new SortedKeySet(); } @WeakOuter class SortedKeySet extends KeySet implements SortedSet<K> { @Override @CheckForNull public Comparator<? super K> comparator() { return sortedMap().comparator(); } @Override public SortedSet<K> subSet( @ParametricNullness K fromElement, @ParametricNullness K toElement) { return (SortedSet<K>) subMap(fromElement, toElement).keySet(); } @Override public SortedSet<K> headSet(@ParametricNullness K toElement) { return (SortedSet<K>) headMap(toElement).keySet(); } @Override public SortedSet<K> tailSet(@ParametricNullness K fromElement) { return (SortedSet<K>) tailMap(fromElement).keySet(); } @Override @ParametricNullness public K first() { return firstKey(); } @Override @ParametricNullness public K last() { return lastKey(); } } @Override @CheckForNull public Comparator<? super K> comparator() { return sortedMap().comparator(); } @Override @ParametricNullness public K firstKey() { // correctly throws NoSuchElementException when filtered map is empty. return keySet().iterator().next(); } @Override @ParametricNullness public K lastKey() { SortedMap<K, V> headMap = sortedMap(); while (true) { // correctly throws NoSuchElementException when filtered map is empty. K key = headMap.lastKey(); // The cast is safe because the key is taken from the map. if (apply(key, uncheckedCastNullableTToT(unfiltered.get(key)))) { return key; } headMap = sortedMap().headMap(key); } } @Override public SortedMap<K, V> headMap(@ParametricNullness K toKey) { return new FilteredEntrySortedMap<>(sortedMap().headMap(toKey), predicate); } @Override public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { return new FilteredEntrySortedMap<>(sortedMap().subMap(fromKey, toKey), predicate); } @Override public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) { return new FilteredEntrySortedMap<>(sortedMap().tailMap(fromKey), predicate); } } @GwtIncompatible // NavigableMap private static class FilteredEntryNavigableMap< K extends @Nullable Object, V extends @Nullable Object> extends AbstractNavigableMap<K, V> { /* * It's less code to extend AbstractNavigableMap and forward the filtering logic to * FilteredEntryMap than to extend FilteredEntrySortedMap and reimplement all the NavigableMap * methods. */ private final NavigableMap<K, V> unfiltered; private final Predicate<? super Entry<K, V>> entryPredicate; private final Map<K, V> filteredDelegate; FilteredEntryNavigableMap( NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { this.unfiltered = checkNotNull(unfiltered); this.entryPredicate = entryPredicate; this.filteredDelegate = new FilteredEntryMap<>(unfiltered, entryPredicate); } @Override @CheckForNull public Comparator<? super K> comparator() { return unfiltered.comparator(); } @Override public NavigableSet<K> navigableKeySet() { return new Maps.NavigableKeySet<K, V>(this) { @Override public boolean removeAll(Collection<?> collection) { return FilteredEntryMap.removeAllKeys(unfiltered, entryPredicate, collection); } @Override public boolean retainAll(Collection<?> collection) { return FilteredEntryMap.retainAllKeys(unfiltered, entryPredicate, collection); } }; } @Override public Collection<V> values() { return new FilteredMapValues<>(this, unfiltered, entryPredicate); } @Override Iterator<Entry<K, V>> entryIterator() { return Iterators.filter(unfiltered.entrySet().iterator(), entryPredicate); } @Override Iterator<Entry<K, V>> descendingEntryIterator() { return Iterators.filter(unfiltered.descendingMap().entrySet().iterator(), entryPredicate); } @Override public int size() { return filteredDelegate.size(); } @Override public boolean isEmpty() { return !Iterables.any(unfiltered.entrySet(), entryPredicate); } @Override @CheckForNull public V get(@CheckForNull Object key) { return filteredDelegate.get(key); } @Override public boolean containsKey(@CheckForNull Object key) { return filteredDelegate.containsKey(key); } @Override @CheckForNull public V put(@ParametricNullness K key, @ParametricNullness V value) { return filteredDelegate.put(key, value); } @Override @CheckForNull public V remove(@CheckForNull Object key) { return filteredDelegate.remove(key); } @Override public void putAll(Map<? extends K, ? extends V> m) { filteredDelegate.putAll(m); } @Override public void clear() { filteredDelegate.clear(); } @Override public Set<Entry<K, V>> entrySet() { return filteredDelegate.entrySet(); } @Override @CheckForNull public Entry<K, V> pollFirstEntry() { return Iterables.removeFirstMatching(unfiltered.entrySet(), entryPredicate); } @Override @CheckForNull public Entry<K, V> pollLastEntry() { return Iterables.removeFirstMatching(unfiltered.descendingMap().entrySet(), entryPredicate); } @Override public NavigableMap<K, V> descendingMap() { return filterEntries(unfiltered.descendingMap(), entryPredicate); } @Override public NavigableMap<K, V> subMap( @ParametricNullness K fromKey, boolean fromInclusive, @ParametricNullness K toKey, boolean toInclusive) { return filterEntries( unfiltered.subMap(fromKey, fromInclusive, toKey, toInclusive), entryPredicate); } @Override public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) { return filterEntries(unfiltered.headMap(toKey, inclusive), entryPredicate); } @Override public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) { return filterEntries(unfiltered.tailMap(fromKey, inclusive), entryPredicate); } } static final class FilteredEntryBiMap<K extends @Nullable Object, V extends @Nullable Object> extends FilteredEntryMap<K, V> implements BiMap<K, V> { @RetainedWith private final BiMap<V, K> inverse; private static <K extends @Nullable Object, V extends @Nullable Object> Predicate<Entry<V, K>> inversePredicate( final Predicate<? super Entry<K, V>> forwardPredicate) { return new Predicate<Entry<V, K>>() { @Override public boolean apply(Entry<V, K> input) { return forwardPredicate.apply( Maps.<K, V>immutableEntry(input.getValue(), input.getKey())); } }; } FilteredEntryBiMap(BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate) { super(delegate, predicate); this.inverse = new FilteredEntryBiMap<>(delegate.inverse(), inversePredicate(predicate), this); } private FilteredEntryBiMap( BiMap<K, V> delegate, Predicate<? super Entry<K, V>> predicate, BiMap<V, K> inverse) { super(delegate, predicate); this.inverse = inverse; } BiMap<K, V> unfiltered() { return (BiMap<K, V>) unfiltered; } @Override @CheckForNull public V forcePut(@ParametricNullness K key, @ParametricNullness V value) { checkArgument(apply(key, value)); return unfiltered().forcePut(key, value); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { unfiltered() .replaceAll( (key, value) -> predicate.apply(Maps.<K, V>immutableEntry(key, value)) ? function.apply(key, value) : value); } @Override public BiMap<V, K> inverse() { return inverse; } @Override public Set<V> values() { return inverse.keySet(); } } /** * Returns an unmodifiable view of the specified navigable map. Query operations on the returned * map read through to the specified map, and attempts to modify the returned map, whether direct * or via its views, result in an {@code UnsupportedOperationException}. * * <p>The returned navigable map will be serializable if the specified navigable map is * serializable. * * <p>This method's signature will not permit you to convert a {@code NavigableMap<? extends K, * V>} to a {@code NavigableMap<K, V>}. If it permitted this, the returned map's {@code * comparator()} method might return a {@code Comparator<? extends K>}, which works only on a * particular subtype of {@code K}, but promise that it's a {@code Comparator<? super K>}, which * must work on any type of {@code K}. * * @param map the navigable map for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified navigable map * @since 12.0 */ @GwtIncompatible // NavigableMap public static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> unmodifiableNavigableMap(NavigableMap<K, ? extends V> map) { checkNotNull(map); if (map instanceof UnmodifiableNavigableMap) { @SuppressWarnings("unchecked") // covariant NavigableMap<K, V> result = (NavigableMap<K, V>) map; return result; } else { return new UnmodifiableNavigableMap<>(map); } } @CheckForNull private static <K extends @Nullable Object, V extends @Nullable Object> Entry<K, V> unmodifiableOrNull(@CheckForNull Entry<K, ? extends V> entry) { return (entry == null) ? null : Maps.unmodifiableEntry(entry); } @GwtIncompatible // NavigableMap static class UnmodifiableNavigableMap<K extends @Nullable Object, V extends @Nullable Object> extends ForwardingSortedMap<K, V> implements NavigableMap<K, V>, Serializable { private final NavigableMap<K, ? extends V> delegate; UnmodifiableNavigableMap(NavigableMap<K, ? extends V> delegate) { this.delegate = delegate; } UnmodifiableNavigableMap( NavigableMap<K, ? extends V> delegate, UnmodifiableNavigableMap<K, V> descendingMap) { this.delegate = delegate; this.descendingMap = descendingMap; } @Override protected SortedMap<K, V> delegate() { return Collections.unmodifiableSortedMap(delegate); } @Override @CheckForNull public Entry<K, V> lowerEntry(@ParametricNullness K key) { return unmodifiableOrNull(delegate.lowerEntry(key)); } @Override @CheckForNull public K lowerKey(@ParametricNullness K key) { return delegate.lowerKey(key); } @Override @CheckForNull public Entry<K, V> floorEntry(@ParametricNullness K key) { return unmodifiableOrNull(delegate.floorEntry(key)); } @Override @CheckForNull public K floorKey(@ParametricNullness K key) { return delegate.floorKey(key); } @Override @CheckForNull public Entry<K, V> ceilingEntry(@ParametricNullness K key) { return unmodifiableOrNull(delegate.ceilingEntry(key)); } @Override @CheckForNull public K ceilingKey(@ParametricNullness K key) { return delegate.ceilingKey(key); } @Override @CheckForNull public Entry<K, V> higherEntry(@ParametricNullness K key) { return unmodifiableOrNull(delegate.higherEntry(key)); } @Override @CheckForNull public K higherKey(@ParametricNullness K key) { return delegate.higherKey(key); } @Override @CheckForNull public Entry<K, V> firstEntry() { return unmodifiableOrNull(delegate.firstEntry()); } @Override @CheckForNull public Entry<K, V> lastEntry() { return unmodifiableOrNull(delegate.lastEntry()); } @Override @CheckForNull public final Entry<K, V> pollFirstEntry() { throw new UnsupportedOperationException(); } @Override @CheckForNull public final Entry<K, V> pollLastEntry() { throw new UnsupportedOperationException(); } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { throw new UnsupportedOperationException(); } @Override @CheckForNull public V putIfAbsent(K key, V value) { throw new UnsupportedOperationException(); } @Override public boolean remove(@Nullable Object key, @Nullable Object value) { throw new UnsupportedOperationException(); } @Override public boolean replace(K key, V oldValue, V newValue) { throw new UnsupportedOperationException(); } @Override @CheckForNull public V replace(K key, V value) { throw new UnsupportedOperationException(); } @Override public V computeIfAbsent( K key, java.util.function.Function<? super K, ? extends V> mappingFunction) { throw new UnsupportedOperationException(); } /* * TODO(cpovirk): Uncomment the @NonNull annotations below once our JDK stubs and J2KT * emulations include them. */ @Override @CheckForNull /* * Our checker arguably should produce a nullness error here until we see @NonNull in JDK APIs. * But it doesn't, which may be a sign that we still permit parameter contravariance in some * cases? */ public V computeIfPresent( K key, BiFunction<? super K, ? super @NonNull V, ? extends @Nullable V> remappingFunction) { throw new UnsupportedOperationException(); } @Override @CheckForNull public V compute( K key, BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction) { throw new UnsupportedOperationException(); } @Override @CheckForNull @SuppressWarnings("nullness") // TODO(b/262880368): Remove once we see @NonNull in JDK APIs public V merge( K key, @NonNull V value, BiFunction<? super @NonNull V, ? super @NonNull V, ? extends @Nullable V> function) { throw new UnsupportedOperationException(); } @LazyInit @CheckForNull private transient UnmodifiableNavigableMap<K, V> descendingMap; @Override public NavigableMap<K, V> descendingMap() { UnmodifiableNavigableMap<K, V> result = descendingMap; return (result == null) ? descendingMap = new UnmodifiableNavigableMap<>(delegate.descendingMap(), this) : result; } @Override public Set<K> keySet() { return navigableKeySet(); } @Override public NavigableSet<K> navigableKeySet() { return Sets.unmodifiableNavigableSet(delegate.navigableKeySet()); } @Override public NavigableSet<K> descendingKeySet() { return Sets.unmodifiableNavigableSet(delegate.descendingKeySet()); } @Override public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { return subMap(fromKey, true, toKey, false); } @Override public NavigableMap<K, V> subMap( @ParametricNullness K fromKey, boolean fromInclusive, @ParametricNullness K toKey, boolean toInclusive) { return Maps.unmodifiableNavigableMap( delegate.subMap(fromKey, fromInclusive, toKey, toInclusive)); } @Override public SortedMap<K, V> headMap(@ParametricNullness K toKey) { return headMap(toKey, false); } @Override public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) { return Maps.unmodifiableNavigableMap(delegate.headMap(toKey, inclusive)); } @Override public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) { return tailMap(fromKey, true); } @Override public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) { return Maps.unmodifiableNavigableMap(delegate.tailMap(fromKey, inclusive)); } } /** * Returns a synchronized (thread-safe) navigable map backed by the specified navigable map. In * order to guarantee serial access, it is critical that <b>all</b> access to the backing * navigable map is accomplished through the returned navigable map (or its views). * * <p>It is imperative that the user manually synchronize on the returned navigable map when * iterating over any of its collection views, or the collections views of any of its {@code * descendingMap}, {@code subMap}, {@code headMap} or {@code tailMap} views. * * <pre>{@code * NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>()); * * // Needn't be in synchronized block * NavigableSet<K> set = map.navigableKeySet(); * * synchronized (map) { // Synchronizing on map, not set! * Iterator<K> it = set.iterator(); // Must be in synchronized block * while (it.hasNext()) { * foo(it.next()); * } * } * }</pre> * * <p>or: * * <pre>{@code * NavigableMap<K, V> map = synchronizedNavigableMap(new TreeMap<K, V>()); * NavigableMap<K, V> map2 = map.subMap(foo, false, bar, true); * * // Needn't be in synchronized block * NavigableSet<K> set2 = map2.descendingKeySet(); * * synchronized (map) { // Synchronizing on map, not map2 or set2! * Iterator<K> it = set2.iterator(); // Must be in synchronized block * while (it.hasNext()) { * foo(it.next()); * } * } * }</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned navigable map will be serializable if the specified navigable map is * serializable. * * @param navigableMap the navigable map to be "wrapped" in a synchronized navigable map. * @return a synchronized view of the specified navigable map. * @since 13.0 */ @GwtIncompatible // NavigableMap public static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> synchronizedNavigableMap(NavigableMap<K, V> navigableMap) { return Synchronized.navigableMap(navigableMap); } /** * {@code AbstractMap} extension that makes it easy to cache customized keySet, values, and * entrySet views. */ @GwtCompatible abstract static class ViewCachingAbstractMap< K extends @Nullable Object, V extends @Nullable Object> extends AbstractMap<K, V> { /** * Creates the entry set to be returned by {@link #entrySet()}. This method is invoked at most * once on a given map, at the time when {@code entrySet} is first called. */ abstract Set<Entry<K, V>> createEntrySet(); @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet; @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } @LazyInit @CheckForNull private transient Set<K> keySet; @Override public Set<K> keySet() { Set<K> result = keySet; return (result == null) ? keySet = createKeySet() : result; } Set<K> createKeySet() { return new KeySet<>(this); } @LazyInit @CheckForNull private transient Collection<V> values; @Override public Collection<V> values() { Collection<V> result = values; return (result == null) ? values = createValues() : result; } Collection<V> createValues() { return new Values<>(this); } } abstract static class IteratorBasedAbstractMap< K extends @Nullable Object, V extends @Nullable Object> extends AbstractMap<K, V> { @Override public abstract int size(); abstract Iterator<Entry<K, V>> entryIterator(); Spliterator<Entry<K, V>> entrySpliterator() { return Spliterators.spliterator( entryIterator(), size(), Spliterator.SIZED | Spliterator.DISTINCT); } @Override public Set<Entry<K, V>> entrySet() { return new EntrySet<K, V>() { @Override Map<K, V> map() { return IteratorBasedAbstractMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return entryIterator(); } @Override public Spliterator<Entry<K, V>> spliterator() { return entrySpliterator(); } @Override public void forEach(Consumer<? super Entry<K, V>> action) { forEachEntry(action); } }; } void forEachEntry(Consumer<? super Entry<K, V>> action) { entryIterator().forEachRemaining(action); } @Override public void clear() { Iterators.clear(entryIterator()); } } /** * Delegates to {@link Map#get}. Returns {@code null} on {@code ClassCastException} and {@code * NullPointerException}. */ @CheckForNull static <V extends @Nullable Object> V safeGet(Map<?, V> map, @CheckForNull Object key) { checkNotNull(map); try { return map.get(key); } catch (ClassCastException | NullPointerException e) { return null; } } /** * Delegates to {@link Map#containsKey}. Returns {@code false} on {@code ClassCastException} and * {@code NullPointerException}. */ static boolean safeContainsKey(Map<?, ?> map, @CheckForNull Object key) { checkNotNull(map); try { return map.containsKey(key); } catch (ClassCastException | NullPointerException e) { return false; } } /** * Delegates to {@link Map#remove}. Returns {@code null} on {@code ClassCastException} and {@code * NullPointerException}. */ @CheckForNull static <V extends @Nullable Object> V safeRemove(Map<?, V> map, @CheckForNull Object key) { checkNotNull(map); try { return map.remove(key); } catch (ClassCastException | NullPointerException e) { return null; } } /** An admittedly inefficient implementation of {@link Map#containsKey}. */ static boolean containsKeyImpl(Map<?, ?> map, @CheckForNull Object key) { return Iterators.contains(keyIterator(map.entrySet().iterator()), key); } /** An implementation of {@link Map#containsValue}. */ static boolean containsValueImpl(Map<?, ?> map, @CheckForNull Object value) { return Iterators.contains(valueIterator(map.entrySet().iterator()), value); } /** * Implements {@code Collection.contains} safely for forwarding collections of map entries. If * {@code o} is an instance of {@code Entry}, it is wrapped using {@link #unmodifiableEntry} to * protect against a possible nefarious equals method. * * <p>Note that {@code c} is the backing (delegate) collection, rather than the forwarding * collection. * * @param c the delegate (unwrapped) collection of map entries * @param o the object that might be contained in {@code c} * @return {@code true} if {@code c} contains {@code o} */ static <K extends @Nullable Object, V extends @Nullable Object> boolean containsEntryImpl( Collection<Entry<K, V>> c, @CheckForNull Object o) { if (!(o instanceof Entry)) { return false; } return c.contains(unmodifiableEntry((Entry<?, ?>) o)); } /** * Implements {@code Collection.remove} safely for forwarding collections of map entries. If * {@code o} is an instance of {@code Entry}, it is wrapped using {@link #unmodifiableEntry} to * protect against a possible nefarious equals method. * * <p>Note that {@code c} is backing (delegate) collection, rather than the forwarding collection. * * @param c the delegate (unwrapped) collection of map entries * @param o the object to remove from {@code c} * @return {@code true} if {@code c} was changed */ static <K extends @Nullable Object, V extends @Nullable Object> boolean removeEntryImpl( Collection<Entry<K, V>> c, @CheckForNull Object o) { if (!(o instanceof Entry)) { return false; } return c.remove(unmodifiableEntry((Entry<?, ?>) o)); } /** An implementation of {@link Map#equals}. */ static boolean equalsImpl(Map<?, ?> map, @CheckForNull Object object) { if (map == object) { return true; } else if (object instanceof Map) { Map<?, ?> o = (Map<?, ?>) object; return map.entrySet().equals(o.entrySet()); } return false; } /** An implementation of {@link Map#toString}. */ static String toStringImpl(Map<?, ?> map) { StringBuilder sb = Collections2.newStringBuilderForCollection(map.size()).append('{'); boolean first = true; for (Entry<?, ?> entry : map.entrySet()) { if (!first) { sb.append(", "); } first = false; sb.append(entry.getKey()).append('=').append(entry.getValue()); } return sb.append('}').toString(); } /** An implementation of {@link Map#putAll}. */ static <K extends @Nullable Object, V extends @Nullable Object> void putAllImpl( Map<K, V> self, Map<? extends K, ? extends V> map) { for (Entry<? extends K, ? extends V> entry : map.entrySet()) { self.put(entry.getKey(), entry.getValue()); } } static class KeySet<K extends @Nullable Object, V extends @Nullable Object> extends Sets.ImprovedAbstractSet<K> { @Weak final Map<K, V> map; KeySet(Map<K, V> map) { this.map = checkNotNull(map); } Map<K, V> map() { return map; } @Override public Iterator<K> iterator() { return keyIterator(map().entrySet().iterator()); } @Override public void forEach(Consumer<? super K> action) { checkNotNull(action); // avoids entry allocation for those maps that allocate entries on iteration map.forEach((k, v) -> action.accept(k)); } @Override public int size() { return map().size(); } @Override public boolean isEmpty() { return map().isEmpty(); } @Override public boolean contains(@CheckForNull Object o) { return map().containsKey(o); } @Override public boolean remove(@CheckForNull Object o) { if (contains(o)) { map().remove(o); return true; } return false; } @Override public void clear() { map().clear(); } } @CheckForNull static <K extends @Nullable Object> K keyOrNull(@CheckForNull Entry<K, ?> entry) { return (entry == null) ? null : entry.getKey(); } @CheckForNull static <V extends @Nullable Object> V valueOrNull(@CheckForNull Entry<?, V> entry) { return (entry == null) ? null : entry.getValue(); } static class SortedKeySet<K extends @Nullable Object, V extends @Nullable Object> extends KeySet<K, V> implements SortedSet<K> { SortedKeySet(SortedMap<K, V> map) { super(map); } @Override SortedMap<K, V> map() { return (SortedMap<K, V>) super.map(); } @Override @CheckForNull public Comparator<? super K> comparator() { return map().comparator(); } @Override public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) { return new SortedKeySet<>(map().subMap(fromElement, toElement)); } @Override public SortedSet<K> headSet(@ParametricNullness K toElement) { return new SortedKeySet<>(map().headMap(toElement)); } @Override public SortedSet<K> tailSet(@ParametricNullness K fromElement) { return new SortedKeySet<>(map().tailMap(fromElement)); } @Override @ParametricNullness public K first() { return map().firstKey(); } @Override @ParametricNullness public K last() { return map().lastKey(); } } @GwtIncompatible // NavigableMap static class NavigableKeySet<K extends @Nullable Object, V extends @Nullable Object> extends SortedKeySet<K, V> implements NavigableSet<K> { NavigableKeySet(NavigableMap<K, V> map) { super(map); } @Override NavigableMap<K, V> map() { return (NavigableMap<K, V>) map; } @Override @CheckForNull public K lower(@ParametricNullness K e) { return map().lowerKey(e); } @Override @CheckForNull public K floor(@ParametricNullness K e) { return map().floorKey(e); } @Override @CheckForNull public K ceiling(@ParametricNullness K e) { return map().ceilingKey(e); } @Override @CheckForNull public K higher(@ParametricNullness K e) { return map().higherKey(e); } @Override @CheckForNull public K pollFirst() { return keyOrNull(map().pollFirstEntry()); } @Override @CheckForNull public K pollLast() { return keyOrNull(map().pollLastEntry()); } @Override public NavigableSet<K> descendingSet() { return map().descendingKeySet(); } @Override public Iterator<K> descendingIterator() { return descendingSet().iterator(); } @Override public NavigableSet<K> subSet( @ParametricNullness K fromElement, boolean fromInclusive, @ParametricNullness K toElement, boolean toInclusive) { return map().subMap(fromElement, fromInclusive, toElement, toInclusive).navigableKeySet(); } @Override public SortedSet<K> subSet(@ParametricNullness K fromElement, @ParametricNullness K toElement) { return subSet(fromElement, true, toElement, false); } @Override public NavigableSet<K> headSet(@ParametricNullness K toElement, boolean inclusive) { return map().headMap(toElement, inclusive).navigableKeySet(); } @Override public SortedSet<K> headSet(@ParametricNullness K toElement) { return headSet(toElement, false); } @Override public NavigableSet<K> tailSet(@ParametricNullness K fromElement, boolean inclusive) { return map().tailMap(fromElement, inclusive).navigableKeySet(); } @Override public SortedSet<K> tailSet(@ParametricNullness K fromElement) { return tailSet(fromElement, true); } } static class Values<K extends @Nullable Object, V extends @Nullable Object> extends AbstractCollection<V> { @Weak final Map<K, V> map; Values(Map<K, V> map) { this.map = checkNotNull(map); } final Map<K, V> map() { return map; } @Override public Iterator<V> iterator() { return valueIterator(map().entrySet().iterator()); } @Override public void forEach(Consumer<? super V> action) { checkNotNull(action); // avoids allocation of entries for those maps that generate fresh entries on iteration map.forEach((k, v) -> action.accept(v)); } @Override public boolean remove(@CheckForNull Object o) { try { return super.remove(o); } catch (UnsupportedOperationException e) { for (Entry<K, V> entry : map().entrySet()) { if (Objects.equal(o, entry.getValue())) { map().remove(entry.getKey()); return true; } } return false; } } @Override public boolean removeAll(Collection<?> c) { try { return super.removeAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { Set<K> toRemove = Sets.newHashSet(); for (Entry<K, V> entry : map().entrySet()) { if (c.contains(entry.getValue())) { toRemove.add(entry.getKey()); } } return map().keySet().removeAll(toRemove); } } @Override public boolean retainAll(Collection<?> c) { try { return super.retainAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { Set<K> toRetain = Sets.newHashSet(); for (Entry<K, V> entry : map().entrySet()) { if (c.contains(entry.getValue())) { toRetain.add(entry.getKey()); } } return map().keySet().retainAll(toRetain); } } @Override public int size() { return map().size(); } @Override public boolean isEmpty() { return map().isEmpty(); } @Override public boolean contains(@CheckForNull Object o) { return map().containsValue(o); } @Override public void clear() { map().clear(); } } abstract static class EntrySet<K extends @Nullable Object, V extends @Nullable Object> extends Sets.ImprovedAbstractSet<Entry<K, V>> { abstract Map<K, V> map(); @Override public int size() { return map().size(); } @Override public void clear() { map().clear(); } @Override public boolean contains(@CheckForNull Object o) { if (o instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) o; Object key = entry.getKey(); V value = Maps.safeGet(map(), key); return Objects.equal(value, entry.getValue()) && (value != null || map().containsKey(key)); } return false; } @Override public boolean isEmpty() { return map().isEmpty(); } @Override public boolean remove(@CheckForNull Object o) { /* * `o instanceof Entry` is guaranteed by `contains`, but we check it here to satisfy our * nullness checker. */ if (contains(o) && o instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) o; return map().keySet().remove(entry.getKey()); } return false; } @Override public boolean removeAll(Collection<?> c) { try { return super.removeAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { // if the iterators don't support remove return Sets.removeAllImpl(this, c.iterator()); } } @Override public boolean retainAll(Collection<?> c) { try { return super.retainAll(checkNotNull(c)); } catch (UnsupportedOperationException e) { // if the iterators don't support remove Set<@Nullable Object> keys = Sets.newHashSetWithExpectedSize(c.size()); for (Object o : c) { /* * `o instanceof Entry` is guaranteed by `contains`, but we check it here to satisfy our * nullness checker. */ if (contains(o) && o instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) o; keys.add(entry.getKey()); } } return map().keySet().retainAll(keys); } } } @GwtIncompatible // NavigableMap abstract static class DescendingMap<K extends @Nullable Object, V extends @Nullable Object> extends ForwardingMap<K, V> implements NavigableMap<K, V> { abstract NavigableMap<K, V> forward(); @Override protected final Map<K, V> delegate() { return forward(); } @LazyInit @CheckForNull private transient Comparator<? super K> comparator; @SuppressWarnings("unchecked") @Override public Comparator<? super K> comparator() { Comparator<? super K> result = comparator; if (result == null) { Comparator<? super K> forwardCmp = forward().comparator(); if (forwardCmp == null) { forwardCmp = (Comparator) Ordering.natural(); } result = comparator = reverse(forwardCmp); } return result; } // If we inline this, we get a javac error. private static <T extends @Nullable Object> Ordering<T> reverse(Comparator<T> forward) { return Ordering.from(forward).reverse(); } @Override @ParametricNullness public K firstKey() { return forward().lastKey(); } @Override @ParametricNullness public K lastKey() { return forward().firstKey(); } @Override @CheckForNull public Entry<K, V> lowerEntry(@ParametricNullness K key) { return forward().higherEntry(key); } @Override @CheckForNull public K lowerKey(@ParametricNullness K key) { return forward().higherKey(key); } @Override @CheckForNull public Entry<K, V> floorEntry(@ParametricNullness K key) { return forward().ceilingEntry(key); } @Override @CheckForNull public K floorKey(@ParametricNullness K key) { return forward().ceilingKey(key); } @Override @CheckForNull public Entry<K, V> ceilingEntry(@ParametricNullness K key) { return forward().floorEntry(key); } @Override @CheckForNull public K ceilingKey(@ParametricNullness K key) { return forward().floorKey(key); } @Override @CheckForNull public Entry<K, V> higherEntry(@ParametricNullness K key) { return forward().lowerEntry(key); } @Override @CheckForNull public K higherKey(@ParametricNullness K key) { return forward().lowerKey(key); } @Override @CheckForNull public Entry<K, V> firstEntry() { return forward().lastEntry(); } @Override @CheckForNull public Entry<K, V> lastEntry() { return forward().firstEntry(); } @Override @CheckForNull public Entry<K, V> pollFirstEntry() { return forward().pollLastEntry(); } @Override @CheckForNull public Entry<K, V> pollLastEntry() { return forward().pollFirstEntry(); } @Override public NavigableMap<K, V> descendingMap() { return forward(); } @LazyInit @CheckForNull private transient Set<Entry<K, V>> entrySet; @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = createEntrySet() : result; } abstract Iterator<Entry<K, V>> entryIterator(); Set<Entry<K, V>> createEntrySet() { @WeakOuter class EntrySetImpl extends EntrySet<K, V> { @Override Map<K, V> map() { return DescendingMap.this; } @Override public Iterator<Entry<K, V>> iterator() { return entryIterator(); } } return new EntrySetImpl(); } @Override public Set<K> keySet() { return navigableKeySet(); } @LazyInit @CheckForNull private transient NavigableSet<K> navigableKeySet; @Override public NavigableSet<K> navigableKeySet() { NavigableSet<K> result = navigableKeySet; return (result == null) ? navigableKeySet = new NavigableKeySet<>(this) : result; } @Override public NavigableSet<K> descendingKeySet() { return forward().navigableKeySet(); } @Override public NavigableMap<K, V> subMap( @ParametricNullness K fromKey, boolean fromInclusive, @ParametricNullness K toKey, boolean toInclusive) { return forward().subMap(toKey, toInclusive, fromKey, fromInclusive).descendingMap(); } @Override public SortedMap<K, V> subMap(@ParametricNullness K fromKey, @ParametricNullness K toKey) { return subMap(fromKey, true, toKey, false); } @Override public NavigableMap<K, V> headMap(@ParametricNullness K toKey, boolean inclusive) { return forward().tailMap(toKey, inclusive).descendingMap(); } @Override public SortedMap<K, V> headMap(@ParametricNullness K toKey) { return headMap(toKey, false); } @Override public NavigableMap<K, V> tailMap(@ParametricNullness K fromKey, boolean inclusive) { return forward().headMap(fromKey, inclusive).descendingMap(); } @Override public SortedMap<K, V> tailMap(@ParametricNullness K fromKey) { return tailMap(fromKey, true); } @Override public Collection<V> values() { return new Values<>(this); } @Override public String toString() { return standardToString(); } } /** Returns a map from the ith element of list to i. */ static <E> ImmutableMap<E, Integer> indexMap(Collection<E> list) { ImmutableMap.Builder<E, Integer> builder = new ImmutableMap.Builder<>(list.size()); int i = 0; for (E e : list) { builder.put(e, i++); } return builder.buildOrThrow(); } /** * Returns a view of the portion of {@code map} whose keys are contained by {@code range}. * * <p>This method delegates to the appropriate methods of {@link NavigableMap} (namely {@link * NavigableMap#subMap(Object, boolean, Object, boolean) subMap()}, {@link * NavigableMap#tailMap(Object, boolean) tailMap()}, and {@link NavigableMap#headMap(Object, * boolean) headMap()}) to actually construct the view. Consult these methods for a full * description of the returned view's behavior. * * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural * ordering. {@code NavigableMap} on the other hand can specify a custom ordering via a {@link * Comparator}, which can violate the natural ordering. Using this method (or in general using * {@code Range}) with unnaturally-ordered maps can lead to unexpected and undefined behavior. * * @since 20.0 */ @GwtIncompatible // NavigableMap public static <K extends Comparable<? super K>, V extends @Nullable Object> NavigableMap<K, V> subMap(NavigableMap<K, V> map, Range<K> range) { if (map.comparator() != null && map.comparator() != Ordering.natural() && range.hasLowerBound() && range.hasUpperBound()) { checkArgument( map.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0, "map is using a custom comparator which is inconsistent with the natural ordering."); } if (range.hasLowerBound() && range.hasUpperBound()) { return map.subMap( range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED, range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED); } else if (range.hasLowerBound()) { return map.tailMap(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED); } else if (range.hasUpperBound()) { return map.headMap(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED); } return checkNotNull(map); } }
google/guava
guava/src/com/google/common/collect/Maps.java
366
/* * 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.cache; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static com.google.common.cache.CacheBuilder.NULL_TICKER; import static com.google.common.cache.CacheBuilder.UNSET_INT; import static com.google.common.util.concurrent.Futures.transform; import static com.google.common.util.concurrent.MoreExecutors.directExecutor; import static com.google.common.util.concurrent.Uninterruptibles.getUninterruptibly; import static java.util.Collections.unmodifiableSet; import static java.util.concurrent.TimeUnit.NANOSECONDS; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Equivalence; import com.google.common.base.Stopwatch; import com.google.common.base.Ticker; import com.google.common.cache.AbstractCache.SimpleStatsCounter; import com.google.common.cache.AbstractCache.StatsCounter; import com.google.common.cache.CacheBuilder.NullListener; import com.google.common.cache.CacheBuilder.OneWeigher; import com.google.common.cache.CacheLoader.InvalidCacheLoadException; import com.google.common.cache.CacheLoader.UnsupportedLoadingOperationException; import com.google.common.collect.AbstractSequentialIterator; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Maps; import com.google.common.collect.Sets; import com.google.common.primitives.Ints; import com.google.common.util.concurrent.ExecutionError; import com.google.common.util.concurrent.Futures; import com.google.common.util.concurrent.ListenableFuture; import com.google.common.util.concurrent.SettableFuture; import com.google.common.util.concurrent.UncheckedExecutionException; import com.google.common.util.concurrent.Uninterruptibles; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.concurrent.GuardedBy; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.j2objc.annotations.RetainedWith; import com.google.j2objc.annotations.Weak; import java.io.IOException; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.Serializable; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractQueue; import java.util.AbstractSet; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Queue; import java.util.Set; import java.util.concurrent.Callable; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.ExecutionException; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicReferenceArray; import java.util.concurrent.locks.ReentrantLock; import java.util.function.BiFunction; import java.util.function.BiPredicate; import java.util.function.Function; import java.util.function.Predicate; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * The concurrent hash map implementation built by {@link CacheBuilder}. * * <p>This implementation is heavily derived from revision 1.96 of <a * href="http://tinyurl.com/ConcurrentHashMap">ConcurrentHashMap.java</a>. * * @author Charles Fry * @author Bob Lee ({@code com.google.common.collect.MapMaker}) * @author Doug Lea ({@code ConcurrentHashMap}) */ @SuppressWarnings({ "GoodTime", // lots of violations (nanosecond math) "nullness", // too much trouble for the payoff }) @GwtCompatible(emulated = true) // TODO(cpovirk): Annotate for nullness. class LocalCache<K, V> extends AbstractMap<K, V> implements ConcurrentMap<K, V> { /* * The basic strategy is to subdivide the table among Segments, each of which itself is a * concurrently readable hash table. The map supports non-blocking reads and concurrent writes * across different segments. * * If a maximum size is specified, a best-effort bounding is performed per segment, using a * page-replacement algorithm to determine which entries to evict when the capacity has been * exceeded. * * The page replacement algorithm's data structures are kept casually consistent with the map. The * ordering of writes to a segment is sequentially consistent. An update to the map and recording * of reads may not be immediately reflected on the algorithm's data structures. These structures * are guarded by a lock and operations are applied in batches to avoid lock contention. The * penalty of applying the batches is spread across threads so that the amortized cost is slightly * higher than performing just the operation without enforcing the capacity constraint. * * This implementation uses a per-segment queue to record a memento of the additions, removals, * and accesses that were performed on the map. The queue is drained on writes and when it exceeds * its capacity threshold. * * The Least Recently Used page replacement algorithm was chosen due to its simplicity, high hit * rate, and ability to be implemented with O(1) time complexity. The initial LRU implementation * operates per-segment rather than globally for increased implementation simplicity. We expect * the cache hit rate to be similar to that of a global LRU algorithm. */ // Constants /** * The maximum capacity, used if a higher value is implicitly specified by either of the * constructors with arguments. MUST be a power of two {@code <= 1<<30} to ensure that entries are * indexable using ints. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** The maximum number of segments to allow; used to bound constructor arguments. */ static final int MAX_SEGMENTS = 1 << 16; // slightly conservative /** Number of (unsynchronized) retries in the containsValue method. */ static final int CONTAINS_VALUE_RETRIES = 3; /** * Number of cache access operations that can be buffered per segment before the cache's recency * ordering information is updated. This is used to avoid lock contention by recording a memento * of reads and delaying a lock acquisition until the threshold is crossed or a mutation occurs. * * <p>This must be a (2^n)-1 as it is used as a mask. */ static final int DRAIN_THRESHOLD = 0x3F; /** * Maximum number of entries to be drained in a single cleanup run. This applies independently to * the cleanup queue and both reference queues. */ // TODO(fry): empirically optimize this static final int DRAIN_MAX = 16; // Fields static final Logger logger = Logger.getLogger(LocalCache.class.getName()); /** * Mask value for indexing into segments. The upper bits of a key's hash code are used to choose * the segment. */ final int segmentMask; /** * Shift value for indexing within segments. Helps prevent entries that end up in the same segment * from also ending up in the same bucket. */ final int segmentShift; /** The segments, each of which is a specialized hash table. */ final Segment<K, V>[] segments; /** The concurrency level. */ final int concurrencyLevel; /** Strategy for comparing keys. */ final Equivalence<Object> keyEquivalence; /** Strategy for comparing values. */ final Equivalence<Object> valueEquivalence; /** Strategy for referencing keys. */ final Strength keyStrength; /** Strategy for referencing values. */ final Strength valueStrength; /** The maximum weight of this map. UNSET_INT if there is no maximum. */ final long maxWeight; /** Weigher to weigh cache entries. */ final Weigher<K, V> weigher; /** How long after the last access to an entry the map will retain that entry. */ final long expireAfterAccessNanos; /** How long after the last write to an entry the map will retain that entry. */ final long expireAfterWriteNanos; /** How long after the last write an entry becomes a candidate for refresh. */ final long refreshNanos; /** Entries waiting to be consumed by the removal listener. */ // TODO(fry): define a new type which creates event objects and automates the clear logic final Queue<RemovalNotification<K, V>> removalNotificationQueue; /** * A listener that is invoked when an entry is removed due to expiration or garbage collection of * soft/weak entries. */ final RemovalListener<K, V> removalListener; /** Measures time in a testable way. */ final Ticker ticker; /** Factory used to create new entries. */ final EntryFactory entryFactory; /** * Accumulates global cache statistics. Note that there are also per-segments stats counters which * must be aggregated to obtain a global stats view. */ final StatsCounter globalStatsCounter; /** The default cache loader to use on loading operations. */ @CheckForNull final CacheLoader<? super K, V> defaultLoader; /** * Creates a new, empty map with the specified strategy, initial capacity and concurrency level. */ LocalCache( CacheBuilder<? super K, ? super V> builder, @CheckForNull CacheLoader<? super K, V> loader) { concurrencyLevel = Math.min(builder.getConcurrencyLevel(), MAX_SEGMENTS); keyStrength = builder.getKeyStrength(); valueStrength = builder.getValueStrength(); keyEquivalence = builder.getKeyEquivalence(); valueEquivalence = builder.getValueEquivalence(); maxWeight = builder.getMaximumWeight(); weigher = builder.getWeigher(); expireAfterAccessNanos = builder.getExpireAfterAccessNanos(); expireAfterWriteNanos = builder.getExpireAfterWriteNanos(); refreshNanos = builder.getRefreshNanos(); removalListener = builder.getRemovalListener(); removalNotificationQueue = (removalListener == NullListener.INSTANCE) ? LocalCache.discardingQueue() : new ConcurrentLinkedQueue<>(); ticker = builder.getTicker(recordsTime()); entryFactory = EntryFactory.getFactory(keyStrength, usesAccessEntries(), usesWriteEntries()); globalStatsCounter = builder.getStatsCounterSupplier().get(); defaultLoader = loader; int initialCapacity = Math.min(builder.getInitialCapacity(), MAXIMUM_CAPACITY); if (evictsBySize() && !customWeigher()) { initialCapacity = (int) Math.min(initialCapacity, maxWeight); } // Find the lowest power-of-two segmentCount that exceeds concurrencyLevel, unless // maximumSize/Weight is specified in which case ensure that each segment gets at least 10 // entries. The special casing for size-based eviction is only necessary because that eviction // happens per segment instead of globally, so too many segments compared to the maximum size // will result in random eviction behavior. int segmentShift = 0; int segmentCount = 1; while (segmentCount < concurrencyLevel && (!evictsBySize() || segmentCount * 20L <= maxWeight)) { ++segmentShift; segmentCount <<= 1; } this.segmentShift = 32 - segmentShift; segmentMask = segmentCount - 1; this.segments = newSegmentArray(segmentCount); int segmentCapacity = initialCapacity / segmentCount; if (segmentCapacity * segmentCount < initialCapacity) { ++segmentCapacity; } int segmentSize = 1; while (segmentSize < segmentCapacity) { segmentSize <<= 1; } if (evictsBySize()) { // Ensure sum of segment max weights = overall max weights long maxSegmentWeight = maxWeight / segmentCount + 1; long remainder = maxWeight % segmentCount; for (int i = 0; i < this.segments.length; ++i) { if (i == remainder) { maxSegmentWeight--; } this.segments[i] = createSegment(segmentSize, maxSegmentWeight, builder.getStatsCounterSupplier().get()); } } else { for (int i = 0; i < this.segments.length; ++i) { this.segments[i] = createSegment(segmentSize, UNSET_INT, builder.getStatsCounterSupplier().get()); } } } boolean evictsBySize() { return maxWeight >= 0; } boolean customWeigher() { return weigher != OneWeigher.INSTANCE; } boolean expires() { return expiresAfterWrite() || expiresAfterAccess(); } boolean expiresAfterWrite() { return expireAfterWriteNanos > 0; } boolean expiresAfterAccess() { return expireAfterAccessNanos > 0; } boolean refreshes() { return refreshNanos > 0; } boolean usesAccessQueue() { return expiresAfterAccess() || evictsBySize(); } boolean usesWriteQueue() { return expiresAfterWrite(); } boolean recordsWrite() { return expiresAfterWrite() || refreshes(); } boolean recordsAccess() { return expiresAfterAccess(); } boolean recordsTime() { return recordsWrite() || recordsAccess(); } boolean usesWriteEntries() { return usesWriteQueue() || recordsWrite(); } boolean usesAccessEntries() { return usesAccessQueue() || recordsAccess(); } boolean usesKeyReferences() { return keyStrength != Strength.STRONG; } boolean usesValueReferences() { return valueStrength != Strength.STRONG; } enum Strength { /* * TODO(kevinb): If we strongly reference the value and aren't loading, we needn't wrap the * value. This could save ~8 bytes per entry. */ STRONG { @Override <K, V> ValueReference<K, V> referenceValue( Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight) { return (weight == 1) ? new StrongValueReference<K, V>(value) : new WeightedStrongValueReference<K, V>(value, weight); } @Override Equivalence<Object> defaultEquivalence() { return Equivalence.equals(); } }, SOFT { @Override <K, V> ValueReference<K, V> referenceValue( Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight) { return (weight == 1) ? new SoftValueReference<K, V>(segment.valueReferenceQueue, value, entry) : new WeightedSoftValueReference<K, V>( segment.valueReferenceQueue, value, entry, weight); } @Override Equivalence<Object> defaultEquivalence() { return Equivalence.identity(); } }, WEAK { @Override <K, V> ValueReference<K, V> referenceValue( Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight) { return (weight == 1) ? new WeakValueReference<K, V>(segment.valueReferenceQueue, value, entry) : new WeightedWeakValueReference<K, V>( segment.valueReferenceQueue, value, entry, weight); } @Override Equivalence<Object> defaultEquivalence() { return Equivalence.identity(); } }; /** Creates a reference for the given value according to this value strength. */ abstract <K, V> ValueReference<K, V> referenceValue( Segment<K, V> segment, ReferenceEntry<K, V> entry, V value, int weight); /** * Returns the default equivalence strategy used to compare and hash keys or values referenced * at this strength. This strategy will be used unless the user explicitly specifies an * alternate strategy. */ abstract Equivalence<Object> defaultEquivalence(); } /** Creates new entries. */ enum EntryFactory { STRONG { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { return new StrongEntry<>(key, hash, next); } }, STRONG_ACCESS { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { return new StrongAccessEntry<>(key, hash, next); } @Override <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext, K key) { ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key); copyAccessEntry(original, newEntry); return newEntry; } }, STRONG_WRITE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { return new StrongWriteEntry<>(key, hash, next); } @Override <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext, K key) { ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key); copyWriteEntry(original, newEntry); return newEntry; } }, STRONG_ACCESS_WRITE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { return new StrongAccessWriteEntry<>(key, hash, next); } @Override <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext, K key) { ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key); copyAccessEntry(original, newEntry); copyWriteEntry(original, newEntry); return newEntry; } }, WEAK { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { return new WeakEntry<>(segment.keyReferenceQueue, key, hash, next); } }, WEAK_ACCESS { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { return new WeakAccessEntry<>(segment.keyReferenceQueue, key, hash, next); } @Override <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext, K key) { ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key); copyAccessEntry(original, newEntry); return newEntry; } }, WEAK_WRITE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { return new WeakWriteEntry<>(segment.keyReferenceQueue, key, hash, next); } @Override <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext, K key) { ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key); copyWriteEntry(original, newEntry); return newEntry; } }, WEAK_ACCESS_WRITE { @Override <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { return new WeakAccessWriteEntry<>(segment.keyReferenceQueue, key, hash, next); } @Override <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext, K key) { ReferenceEntry<K, V> newEntry = super.copyEntry(segment, original, newNext, key); copyAccessEntry(original, newEntry); copyWriteEntry(original, newEntry); return newEntry; } }; // Masks used to compute indices in the following table. static final int ACCESS_MASK = 1; static final int WRITE_MASK = 2; static final int WEAK_MASK = 4; /** Look-up table for factories. */ static final EntryFactory[] factories = { STRONG, STRONG_ACCESS, STRONG_WRITE, STRONG_ACCESS_WRITE, WEAK, WEAK_ACCESS, WEAK_WRITE, WEAK_ACCESS_WRITE, }; static EntryFactory getFactory( Strength keyStrength, boolean usesAccessQueue, boolean usesWriteQueue) { int flags = ((keyStrength == Strength.WEAK) ? WEAK_MASK : 0) | (usesAccessQueue ? ACCESS_MASK : 0) | (usesWriteQueue ? WRITE_MASK : 0); return factories[flags]; } /** * Creates a new entry. * * @param segment to create the entry for * @param key of the entry * @param hash of the key * @param next entry in the same bucket */ abstract <K, V> ReferenceEntry<K, V> newEntry( Segment<K, V> segment, K key, int hash, @CheckForNull ReferenceEntry<K, V> next); /** * Copies an entry, assigning it a new {@code next} entry. * * @param original the entry to copy. But avoid calling {@code getKey} on it: Instead, use the * {@code key} parameter. That way, we prevent the key from being garbage collected in the * case of weak keys. If we create a new entry with a key that is null at construction time, * we're not sure if entry will necessarily ever be garbage collected. * @param newNext entry in the same bucket * @param key the key to copy from the original entry to the new one. Use this in preference to * {@code original.getKey()}. */ // Guarded By Segment.this <K, V> ReferenceEntry<K, V> copyEntry( Segment<K, V> segment, ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext, K key) { return newEntry(segment, key, original.getHash(), newNext); } // Guarded By Segment.this <K, V> void copyAccessEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) { // TODO(fry): when we link values instead of entries this method can go // away, as can connectAccessOrder, nullifyAccessOrder. newEntry.setAccessTime(original.getAccessTime()); connectAccessOrder(original.getPreviousInAccessQueue(), newEntry); connectAccessOrder(newEntry, original.getNextInAccessQueue()); nullifyAccessOrder(original); } // Guarded By Segment.this <K, V> void copyWriteEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newEntry) { // TODO(fry): when we link values instead of entries this method can go // away, as can connectWriteOrder, nullifyWriteOrder. newEntry.setWriteTime(original.getWriteTime()); connectWriteOrder(original.getPreviousInWriteQueue(), newEntry); connectWriteOrder(newEntry, original.getNextInWriteQueue()); nullifyWriteOrder(original); } } /** A reference to a value. */ interface ValueReference<K, V> { /** Returns the value. Does not block or throw exceptions. */ @CheckForNull V get(); /** * Waits for a value that may still be loading. Unlike get(), this method can block (in the case * of FutureValueReference). * * @throws ExecutionException if the loading thread throws an exception * @throws ExecutionError if the loading thread throws an error */ V waitForValue() throws ExecutionException; /** Returns the weight of this entry. This is assumed to be static between calls to setValue. */ int getWeight(); /** * Returns the entry associated with this value reference, or {@code null} if this value * reference is independent of any entry. */ @CheckForNull ReferenceEntry<K, V> getEntry(); /** * Creates a copy of this reference for the given entry. * * <p>{@code value} may be null only for a loading reference. */ ValueReference<K, V> copyFor( ReferenceQueue<V> queue, @CheckForNull V value, ReferenceEntry<K, V> entry); /** * Notify pending loads that a new value was set. This is only relevant to loading value * references. */ void notifyNewValue(@CheckForNull V newValue); /** * Returns true if a new value is currently loading, regardless of whether there is an existing * value. It is assumed that the return value of this method is constant for any given * ValueReference instance. */ boolean isLoading(); /** * Returns true if this reference contains an active value, meaning one that is still considered * present in the cache. Active values consist of live values, which are returned by cache * lookups, and dead values, which have been evicted but awaiting removal. Non-active values * consist strictly of loading values, though during refresh a value may be both active and * loading. */ boolean isActive(); } /** Placeholder. Indicates that the value hasn't been set yet. */ static final ValueReference<Object, Object> UNSET = new ValueReference<Object, Object>() { @CheckForNull @Override public Object get() { return null; } @Override public int getWeight() { return 0; } @CheckForNull @Override public ReferenceEntry<Object, Object> getEntry() { return null; } @Override public ValueReference<Object, Object> copyFor( ReferenceQueue<Object> queue, @CheckForNull Object value, ReferenceEntry<Object, Object> entry) { return this; } @Override public boolean isLoading() { return false; } @Override public boolean isActive() { return false; } @CheckForNull @Override public Object waitForValue() { return null; } @Override public void notifyNewValue(Object newValue) {} }; /** Singleton placeholder that indicates a value is being loaded. */ @SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value static <K, V> ValueReference<K, V> unset() { return (ValueReference<K, V>) UNSET; } private enum NullEntry implements ReferenceEntry<Object, Object> { INSTANCE; @CheckForNull @Override public ValueReference<Object, Object> getValueReference() { return null; } @Override public void setValueReference(ValueReference<Object, Object> valueReference) {} @CheckForNull @Override public ReferenceEntry<Object, Object> getNext() { return null; } @Override public int getHash() { return 0; } @CheckForNull @Override public Object getKey() { return null; } @Override public long getAccessTime() { return 0; } @Override public void setAccessTime(long time) {} @Override public ReferenceEntry<Object, Object> getNextInAccessQueue() { return this; } @Override public void setNextInAccessQueue(ReferenceEntry<Object, Object> next) {} @Override public ReferenceEntry<Object, Object> getPreviousInAccessQueue() { return this; } @Override public void setPreviousInAccessQueue(ReferenceEntry<Object, Object> previous) {} @Override public long getWriteTime() { return 0; } @Override public void setWriteTime(long time) {} @Override public ReferenceEntry<Object, Object> getNextInWriteQueue() { return this; } @Override public void setNextInWriteQueue(ReferenceEntry<Object, Object> next) {} @Override public ReferenceEntry<Object, Object> getPreviousInWriteQueue() { return this; } @Override public void setPreviousInWriteQueue(ReferenceEntry<Object, Object> previous) {} } abstract static class AbstractReferenceEntry<K, V> implements ReferenceEntry<K, V> { @Override public ValueReference<K, V> getValueReference() { throw new UnsupportedOperationException(); } @Override public void setValueReference(ValueReference<K, V> valueReference) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getNext() { throw new UnsupportedOperationException(); } @Override public int getHash() { throw new UnsupportedOperationException(); } @Override public K getKey() { throw new UnsupportedOperationException(); } @Override public long getAccessTime() { throw new UnsupportedOperationException(); } @Override public void setAccessTime(long time) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getNextInAccessQueue() { throw new UnsupportedOperationException(); } @Override public void setNextInAccessQueue(ReferenceEntry<K, V> next) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getPreviousInAccessQueue() { throw new UnsupportedOperationException(); } @Override public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) { throw new UnsupportedOperationException(); } @Override public long getWriteTime() { throw new UnsupportedOperationException(); } @Override public void setWriteTime(long time) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getNextInWriteQueue() { throw new UnsupportedOperationException(); } @Override public void setNextInWriteQueue(ReferenceEntry<K, V> next) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getPreviousInWriteQueue() { throw new UnsupportedOperationException(); } @Override public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) { throw new UnsupportedOperationException(); } } @SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value static <K, V> ReferenceEntry<K, V> nullEntry() { return (ReferenceEntry<K, V>) NullEntry.INSTANCE; } static final Queue<?> DISCARDING_QUEUE = new AbstractQueue<Object>() { @Override public boolean offer(Object o) { return true; } @CheckForNull @Override public Object peek() { return null; } @CheckForNull @Override public Object poll() { return null; } @Override public int size() { return 0; } @Override public Iterator<Object> iterator() { return ImmutableSet.of().iterator(); } }; /** Queue that discards all elements. */ @SuppressWarnings("unchecked") // impl never uses a parameter or returns any non-null value static <E> Queue<E> discardingQueue() { return (Queue) DISCARDING_QUEUE; } /* * Note: All of this duplicate code sucks, but it saves a lot of memory. If only Java had mixins! * To maintain this code, make a change for the strong reference type. Then, cut and paste, and * replace "Strong" with "Soft" or "Weak" within the pasted text. The primary difference is that * strong entries store the key reference directly while soft and weak entries delegate to their * respective superclasses. */ /** Used for strongly-referenced keys. */ static class StrongEntry<K, V> extends AbstractReferenceEntry<K, V> { final K key; StrongEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { this.key = key; this.hash = hash; this.next = next; } @Override public K getKey() { return this.key; } // The code below is exactly the same for each entry type. final int hash; @CheckForNull final ReferenceEntry<K, V> next; volatile ValueReference<K, V> valueReference = unset(); @Override public ValueReference<K, V> getValueReference() { return valueReference; } @Override public void setValueReference(ValueReference<K, V> valueReference) { this.valueReference = valueReference; } @Override public int getHash() { return hash; } @Override public ReferenceEntry<K, V> getNext() { return next; } } static final class StrongAccessEntry<K, V> extends StrongEntry<K, V> { StrongAccessEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { super(key, hash, next); } // The code below is exactly the same for each access entry type. volatile long accessTime = Long.MAX_VALUE; @Override public long getAccessTime() { return accessTime; } @Override public void setAccessTime(long time) { this.accessTime = time; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> nextAccess = nullEntry(); @Override public ReferenceEntry<K, V> getNextInAccessQueue() { return nextAccess; } @Override public void setNextInAccessQueue(ReferenceEntry<K, V> next) { this.nextAccess = next; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> previousAccess = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousInAccessQueue() { return previousAccess; } @Override public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) { this.previousAccess = previous; } } static final class StrongWriteEntry<K, V> extends StrongEntry<K, V> { StrongWriteEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { super(key, hash, next); } // The code below is exactly the same for each write entry type. volatile long writeTime = Long.MAX_VALUE; @Override public long getWriteTime() { return writeTime; } @Override public void setWriteTime(long time) { this.writeTime = time; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> nextWrite = nullEntry(); @Override public ReferenceEntry<K, V> getNextInWriteQueue() { return nextWrite; } @Override public void setNextInWriteQueue(ReferenceEntry<K, V> next) { this.nextWrite = next; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> previousWrite = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousInWriteQueue() { return previousWrite; } @Override public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) { this.previousWrite = previous; } } static final class StrongAccessWriteEntry<K, V> extends StrongEntry<K, V> { StrongAccessWriteEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { super(key, hash, next); } // The code below is exactly the same for each access entry type. volatile long accessTime = Long.MAX_VALUE; @Override public long getAccessTime() { return accessTime; } @Override public void setAccessTime(long time) { this.accessTime = time; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> nextAccess = nullEntry(); @Override public ReferenceEntry<K, V> getNextInAccessQueue() { return nextAccess; } @Override public void setNextInAccessQueue(ReferenceEntry<K, V> next) { this.nextAccess = next; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> previousAccess = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousInAccessQueue() { return previousAccess; } @Override public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) { this.previousAccess = previous; } // The code below is exactly the same for each write entry type. volatile long writeTime = Long.MAX_VALUE; @Override public long getWriteTime() { return writeTime; } @Override public void setWriteTime(long time) { this.writeTime = time; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> nextWrite = nullEntry(); @Override public ReferenceEntry<K, V> getNextInWriteQueue() { return nextWrite; } @Override public void setNextInWriteQueue(ReferenceEntry<K, V> next) { this.nextWrite = next; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> previousWrite = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousInWriteQueue() { return previousWrite; } @Override public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) { this.previousWrite = previous; } } /** Used for weakly-referenced keys. */ static class WeakEntry<K, V> extends WeakReference<K> implements ReferenceEntry<K, V> { WeakEntry(ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { super(key, queue); this.hash = hash; this.next = next; } @Override public K getKey() { return get(); } /* * It'd be nice to get these for free from AbstractReferenceEntry, but we're already extending * WeakReference<K>. */ // null access @Override public long getAccessTime() { throw new UnsupportedOperationException(); } @Override public void setAccessTime(long time) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getNextInAccessQueue() { throw new UnsupportedOperationException(); } @Override public void setNextInAccessQueue(ReferenceEntry<K, V> next) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getPreviousInAccessQueue() { throw new UnsupportedOperationException(); } @Override public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) { throw new UnsupportedOperationException(); } // null write @Override public long getWriteTime() { throw new UnsupportedOperationException(); } @Override public void setWriteTime(long time) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getNextInWriteQueue() { throw new UnsupportedOperationException(); } @Override public void setNextInWriteQueue(ReferenceEntry<K, V> next) { throw new UnsupportedOperationException(); } @Override public ReferenceEntry<K, V> getPreviousInWriteQueue() { throw new UnsupportedOperationException(); } @Override public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) { throw new UnsupportedOperationException(); } // The code below is exactly the same for each entry type. final int hash; @CheckForNull final ReferenceEntry<K, V> next; volatile ValueReference<K, V> valueReference = unset(); @Override public ValueReference<K, V> getValueReference() { return valueReference; } @Override public void setValueReference(ValueReference<K, V> valueReference) { this.valueReference = valueReference; } @Override public int getHash() { return hash; } @Override public ReferenceEntry<K, V> getNext() { return next; } } static final class WeakAccessEntry<K, V> extends WeakEntry<K, V> { WeakAccessEntry( ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { super(queue, key, hash, next); } // The code below is exactly the same for each access entry type. volatile long accessTime = Long.MAX_VALUE; @Override public long getAccessTime() { return accessTime; } @Override public void setAccessTime(long time) { this.accessTime = time; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> nextAccess = nullEntry(); @Override public ReferenceEntry<K, V> getNextInAccessQueue() { return nextAccess; } @Override public void setNextInAccessQueue(ReferenceEntry<K, V> next) { this.nextAccess = next; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> previousAccess = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousInAccessQueue() { return previousAccess; } @Override public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) { this.previousAccess = previous; } } static final class WeakWriteEntry<K, V> extends WeakEntry<K, V> { WeakWriteEntry( ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { super(queue, key, hash, next); } // The code below is exactly the same for each write entry type. volatile long writeTime = Long.MAX_VALUE; @Override public long getWriteTime() { return writeTime; } @Override public void setWriteTime(long time) { this.writeTime = time; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> nextWrite = nullEntry(); @Override public ReferenceEntry<K, V> getNextInWriteQueue() { return nextWrite; } @Override public void setNextInWriteQueue(ReferenceEntry<K, V> next) { this.nextWrite = next; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> previousWrite = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousInWriteQueue() { return previousWrite; } @Override public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) { this.previousWrite = previous; } } static final class WeakAccessWriteEntry<K, V> extends WeakEntry<K, V> { WeakAccessWriteEntry( ReferenceQueue<K> queue, K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { super(queue, key, hash, next); } // The code below is exactly the same for each access entry type. volatile long accessTime = Long.MAX_VALUE; @Override public long getAccessTime() { return accessTime; } @Override public void setAccessTime(long time) { this.accessTime = time; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> nextAccess = nullEntry(); @Override public ReferenceEntry<K, V> getNextInAccessQueue() { return nextAccess; } @Override public void setNextInAccessQueue(ReferenceEntry<K, V> next) { this.nextAccess = next; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> previousAccess = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousInAccessQueue() { return previousAccess; } @Override public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) { this.previousAccess = previous; } // The code below is exactly the same for each write entry type. volatile long writeTime = Long.MAX_VALUE; @Override public long getWriteTime() { return writeTime; } @Override public void setWriteTime(long time) { this.writeTime = time; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> nextWrite = nullEntry(); @Override public ReferenceEntry<K, V> getNextInWriteQueue() { return nextWrite; } @Override public void setNextInWriteQueue(ReferenceEntry<K, V> next) { this.nextWrite = next; } // Guarded By Segment.this @Weak ReferenceEntry<K, V> previousWrite = nullEntry(); @Override public ReferenceEntry<K, V> getPreviousInWriteQueue() { return previousWrite; } @Override public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) { this.previousWrite = previous; } } /** References a weak value. */ static class WeakValueReference<K, V> extends WeakReference<V> implements ValueReference<K, V> { final ReferenceEntry<K, V> entry; WeakValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) { super(referent, queue); this.entry = entry; } @Override public int getWeight() { return 1; } @Override public ReferenceEntry<K, V> getEntry() { return entry; } @Override public void notifyNewValue(V newValue) {} @Override public ValueReference<K, V> copyFor( ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) { return new WeakValueReference<>(queue, value, entry); } @Override public boolean isLoading() { return false; } @Override public boolean isActive() { return true; } @Override public V waitForValue() { return get(); } } /** References a soft value. */ static class SoftValueReference<K, V> extends SoftReference<V> implements ValueReference<K, V> { final ReferenceEntry<K, V> entry; SoftValueReference(ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry) { super(referent, queue); this.entry = entry; } @Override public int getWeight() { return 1; } @Override public ReferenceEntry<K, V> getEntry() { return entry; } @Override public void notifyNewValue(V newValue) {} @Override public ValueReference<K, V> copyFor( ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) { return new SoftValueReference<>(queue, value, entry); } @Override public boolean isLoading() { return false; } @Override public boolean isActive() { return true; } @Override public V waitForValue() { return get(); } } /** References a strong value. */ static class StrongValueReference<K, V> implements ValueReference<K, V> { final V referent; StrongValueReference(V referent) { this.referent = referent; } @Override public V get() { return referent; } @Override public int getWeight() { return 1; } @Override public ReferenceEntry<K, V> getEntry() { return null; } @Override public ValueReference<K, V> copyFor( ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) { return this; } @Override public boolean isLoading() { return false; } @Override public boolean isActive() { return true; } @Override public V waitForValue() { return get(); } @Override public void notifyNewValue(V newValue) {} } /** References a weak value. */ static final class WeightedWeakValueReference<K, V> extends WeakValueReference<K, V> { final int weight; WeightedWeakValueReference( ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry, int weight) { super(queue, referent, entry); this.weight = weight; } @Override public int getWeight() { return weight; } @Override public ValueReference<K, V> copyFor( ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) { return new WeightedWeakValueReference<>(queue, value, entry, weight); } } /** References a soft value. */ static final class WeightedSoftValueReference<K, V> extends SoftValueReference<K, V> { final int weight; WeightedSoftValueReference( ReferenceQueue<V> queue, V referent, ReferenceEntry<K, V> entry, int weight) { super(queue, referent, entry); this.weight = weight; } @Override public int getWeight() { return weight; } @Override public ValueReference<K, V> copyFor( ReferenceQueue<V> queue, V value, ReferenceEntry<K, V> entry) { return new WeightedSoftValueReference<>(queue, value, entry, weight); } } /** References a strong value. */ static final class WeightedStrongValueReference<K, V> extends StrongValueReference<K, V> { final int weight; WeightedStrongValueReference(V referent, int weight) { super(referent); this.weight = weight; } @Override public int getWeight() { return weight; } } /** * Applies a supplemental hash function to a given hash code, which defends against poor quality * hash functions. This is critical when the concurrent hash map uses power-of-two length hash * tables, that otherwise encounter collisions for hash codes that do not differ in lower or upper * bits. * * @param h hash code */ static int rehash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. // TODO(kevinb): use Hashing/move this to Hashing? h += (h << 15) ^ 0xffffcd7d; h ^= (h >>> 10); h += (h << 3); h ^= (h >>> 6); h += (h << 2) + (h << 14); return h ^ (h >>> 16); } /** * This method is a convenience for testing. Code should call {@link Segment#newEntry} directly. */ @VisibleForTesting ReferenceEntry<K, V> newEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { Segment<K, V> segment = segmentFor(hash); segment.lock(); try { return segment.newEntry(key, hash, next); } finally { segment.unlock(); } } /** * This method is a convenience for testing. Code should call {@link Segment#copyEntry} directly. */ // Guarded By Segment.this @SuppressWarnings("GuardedBy") @VisibleForTesting ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) { int hash = original.getHash(); return segmentFor(hash).copyEntry(original, newNext); } /** * This method is a convenience for testing. Code should call {@link Segment#setValue} instead. */ // Guarded By Segment.this @VisibleForTesting ValueReference<K, V> newValueReference(ReferenceEntry<K, V> entry, V value, int weight) { int hash = entry.getHash(); return valueStrength.referenceValue(segmentFor(hash), entry, checkNotNull(value), weight); } int hash(@CheckForNull Object key) { int h = keyEquivalence.hash(key); return rehash(h); } void reclaimValue(ValueReference<K, V> valueReference) { ReferenceEntry<K, V> entry = valueReference.getEntry(); int hash = entry.getHash(); segmentFor(hash).reclaimValue(entry.getKey(), hash, valueReference); } void reclaimKey(ReferenceEntry<K, V> entry) { int hash = entry.getHash(); segmentFor(hash).reclaimKey(entry, hash); } /** * This method is a convenience for testing. Code should call {@link Segment#getLiveValue} * instead. */ @VisibleForTesting boolean isLive(ReferenceEntry<K, V> entry, long now) { return segmentFor(entry.getHash()).getLiveValue(entry, now) != null; } /** * Returns the segment that should be used for a key with the given hash. * * @param hash the hash code for the key * @return the segment */ Segment<K, V> segmentFor(int hash) { // TODO(fry): Lazily create segments? return segments[(hash >>> segmentShift) & segmentMask]; } Segment<K, V> createSegment( int initialCapacity, long maxSegmentWeight, StatsCounter statsCounter) { return new Segment<>(this, initialCapacity, maxSegmentWeight, statsCounter); } /** * Gets the value from an entry. Returns null if the entry is invalid, partially-collected, * loading, or expired. Unlike {@link Segment#getLiveValue} this method does not attempt to clean * up stale entries. As such it should only be called outside a segment context, such as during * iteration. */ @CheckForNull V getLiveValue(ReferenceEntry<K, V> entry, long now) { if (entry.getKey() == null) { return null; } V value = entry.getValueReference().get(); if (value == null) { return null; } if (isExpired(entry, now)) { return null; } return value; } // expiration /** Returns true if the entry has expired. */ boolean isExpired(ReferenceEntry<K, V> entry, long now) { checkNotNull(entry); if (expiresAfterAccess() && (now - entry.getAccessTime() >= expireAfterAccessNanos)) { return true; } if (expiresAfterWrite() && (now - entry.getWriteTime() >= expireAfterWriteNanos)) { return true; } return false; } // queues // Guarded By Segment.this static <K, V> void connectAccessOrder(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) { previous.setNextInAccessQueue(next); next.setPreviousInAccessQueue(previous); } // Guarded By Segment.this static <K, V> void nullifyAccessOrder(ReferenceEntry<K, V> nulled) { ReferenceEntry<K, V> nullEntry = nullEntry(); nulled.setNextInAccessQueue(nullEntry); nulled.setPreviousInAccessQueue(nullEntry); } // Guarded By Segment.this static <K, V> void connectWriteOrder(ReferenceEntry<K, V> previous, ReferenceEntry<K, V> next) { previous.setNextInWriteQueue(next); next.setPreviousInWriteQueue(previous); } // Guarded By Segment.this static <K, V> void nullifyWriteOrder(ReferenceEntry<K, V> nulled) { ReferenceEntry<K, V> nullEntry = nullEntry(); nulled.setNextInWriteQueue(nullEntry); nulled.setPreviousInWriteQueue(nullEntry); } /** * Notifies listeners that an entry has been automatically removed due to expiration, eviction, or * eligibility for garbage collection. This should be called every time expireEntries or * evictEntry is called (once the lock is released). */ void processPendingNotifications() { RemovalNotification<K, V> notification; while ((notification = removalNotificationQueue.poll()) != null) { try { removalListener.onRemoval(notification); } catch (Throwable e) { logger.log(Level.WARNING, "Exception thrown by removal listener", e); } } } @SuppressWarnings("unchecked") final Segment<K, V>[] newSegmentArray(int ssize) { return (Segment<K, V>[]) new Segment<?, ?>[ssize]; } // Inner Classes /** * Segments are specialized versions of hash tables. This subclass inherits from ReentrantLock * opportunistically, just to simplify some locking and avoid separate construction. */ @SuppressWarnings("serial") // This class is never serialized. static class Segment<K, V> extends ReentrantLock { /* * TODO(fry): Consider copying variables (like evictsBySize) from outer class into this class. * It will require more memory but will reduce indirection. */ /* * Segments maintain a table of entry lists that are ALWAYS kept in a consistent state, so can * be read without locking. Next fields of nodes are immutable (final). All list additions are * performed at the front of each bin. This makes it easy to check changes, and also fast to * traverse. When nodes would otherwise be changed, new nodes are created to replace them. This * works well for hash tables since the bin lists tend to be short. (The average length is less * than two.) * * Read operations can thus proceed without locking, but rely on selected uses of volatiles to * ensure that completed write operations performed by other threads are noticed. For most * purposes, the "count" field, tracking the number of elements, serves as that volatile * variable ensuring visibility. This is convenient because this field needs to be read in many * read operations anyway: * * - All (unsynchronized) read operations must first read the "count" field, and should not look * at table entries if it is 0. * * - All (synchronized) write operations should write to the "count" field after structurally * changing any bin. The operations must not take any action that could even momentarily cause a * concurrent read operation to see inconsistent data. This is made easier by the nature of the * read operations in Map. For example, no operation can reveal that the table has grown but the * threshold has not yet been updated, so there are no atomicity requirements for this with * respect to reads. * * As a guide, all critical volatile reads and writes to the count field are marked in code * comments. */ @Weak final LocalCache<K, V> map; /** The number of live elements in this segment's region. */ volatile int count; /** The weight of the live elements in this segment's region. */ @GuardedBy("this") long totalWeight; /** * Number of updates that alter the size of the table. This is used during bulk-read methods to * make sure they see a consistent snapshot: If modCounts change during a traversal of segments * loading size or checking containsValue, then we might have an inconsistent view of state so * (usually) must retry. */ int modCount; /** * The table is expanded when its size exceeds this threshold. (The value of this field is * always {@code (int) (capacity * 0.75)}.) */ int threshold; /** The per-segment table. */ @CheckForNull volatile AtomicReferenceArray<ReferenceEntry<K, V>> table; /** The maximum weight of this segment. UNSET_INT if there is no maximum. */ final long maxSegmentWeight; /** * The key reference queue contains entries whose keys have been garbage collected, and which * need to be cleaned up internally. */ @CheckForNull final ReferenceQueue<K> keyReferenceQueue; /** * The value reference queue contains value references whose values have been garbage collected, * and which need to be cleaned up internally. */ @CheckForNull final ReferenceQueue<V> valueReferenceQueue; /** * The recency queue is used to record which entries were accessed for updating the access * list's ordering. It is drained as a batch operation when either the DRAIN_THRESHOLD is * crossed or a write occurs on the segment. */ final Queue<ReferenceEntry<K, V>> recencyQueue; /** * A counter of the number of reads since the last write, used to drain queues on a small * fraction of read operations. */ final AtomicInteger readCount = new AtomicInteger(); /** * A queue of elements currently in the map, ordered by write time. Elements are added to the * tail of the queue on write. */ @GuardedBy("this") final Queue<ReferenceEntry<K, V>> writeQueue; /** * A queue of elements currently in the map, ordered by access time. Elements are added to the * tail of the queue on access (note that writes count as accesses). */ @GuardedBy("this") final Queue<ReferenceEntry<K, V>> accessQueue; /** Accumulates cache statistics. */ final StatsCounter statsCounter; Segment( LocalCache<K, V> map, int initialCapacity, long maxSegmentWeight, StatsCounter statsCounter) { this.map = map; this.maxSegmentWeight = maxSegmentWeight; this.statsCounter = checkNotNull(statsCounter); initTable(newEntryArray(initialCapacity)); keyReferenceQueue = map.usesKeyReferences() ? new ReferenceQueue<>() : null; valueReferenceQueue = map.usesValueReferences() ? new ReferenceQueue<>() : null; recencyQueue = map.usesAccessQueue() ? new ConcurrentLinkedQueue<>() : LocalCache.discardingQueue(); writeQueue = map.usesWriteQueue() ? new WriteQueue<>() : LocalCache.discardingQueue(); accessQueue = map.usesAccessQueue() ? new AccessQueue<>() : LocalCache.discardingQueue(); } AtomicReferenceArray<ReferenceEntry<K, V>> newEntryArray(int size) { return new AtomicReferenceArray<>(size); } void initTable(AtomicReferenceArray<ReferenceEntry<K, V>> newTable) { this.threshold = newTable.length() * 3 / 4; // 0.75 if (!map.customWeigher() && this.threshold == maxSegmentWeight) { // prevent spurious expansion before eviction this.threshold++; } this.table = newTable; } @GuardedBy("this") ReferenceEntry<K, V> newEntry(K key, int hash, @CheckForNull ReferenceEntry<K, V> next) { return map.entryFactory.newEntry(this, checkNotNull(key), hash, next); } /** * Copies {@code original} into a new entry chained to {@code newNext}. Returns the new entry, * or {@code null} if {@code original} was already garbage collected. */ @CheckForNull @GuardedBy("this") ReferenceEntry<K, V> copyEntry(ReferenceEntry<K, V> original, ReferenceEntry<K, V> newNext) { K key = original.getKey(); if (key == null) { // key collected return null; } ValueReference<K, V> valueReference = original.getValueReference(); V value = valueReference.get(); if ((value == null) && valueReference.isActive()) { // value collected return null; } ReferenceEntry<K, V> newEntry = map.entryFactory.copyEntry(this, original, newNext, key); newEntry.setValueReference(valueReference.copyFor(this.valueReferenceQueue, value, newEntry)); return newEntry; } /** Sets a new value of an entry. Adds newly created entries at the end of the access queue. */ @GuardedBy("this") void setValue(ReferenceEntry<K, V> entry, K key, V value, long now) { ValueReference<K, V> previous = entry.getValueReference(); int weight = map.weigher.weigh(key, value); checkState(weight >= 0, "Weights must be non-negative"); ValueReference<K, V> valueReference = map.valueStrength.referenceValue(this, entry, value, weight); entry.setValueReference(valueReference); recordWrite(entry, weight, now); previous.notifyNewValue(value); } // loading @CanIgnoreReturnValue V get(K key, int hash, CacheLoader<? super K, V> loader) throws ExecutionException { checkNotNull(key); checkNotNull(loader); try { if (count != 0) { // read-volatile // don't call getLiveEntry, which would ignore loading values ReferenceEntry<K, V> e = getEntry(key, hash); if (e != null) { long now = map.ticker.read(); V value = getLiveValue(e, now); if (value != null) { recordRead(e, now); statsCounter.recordHits(1); return scheduleRefresh(e, key, hash, value, now, loader); } ValueReference<K, V> valueReference = e.getValueReference(); if (valueReference.isLoading()) { return waitForLoadingValue(e, key, valueReference); } } } // at this point e is either null or expired; return lockedGetOrLoad(key, hash, loader); } catch (ExecutionException ee) { Throwable cause = ee.getCause(); if (cause instanceof Error) { throw new ExecutionError((Error) cause); } else if (cause instanceof RuntimeException) { throw new UncheckedExecutionException(cause); } throw ee; } finally { postReadCleanup(); } } @CheckForNull V get(Object key, int hash) { try { if (count != 0) { // read-volatile long now = map.ticker.read(); ReferenceEntry<K, V> e = getLiveEntry(key, hash, now); if (e == null) { return null; } V value = e.getValueReference().get(); if (value != null) { recordRead(e, now); return scheduleRefresh(e, e.getKey(), hash, value, now, map.defaultLoader); } tryDrainReferenceQueues(); } return null; } finally { postReadCleanup(); } } V lockedGetOrLoad(K key, int hash, CacheLoader<? super K, V> loader) throws ExecutionException { ReferenceEntry<K, V> e; ValueReference<K, V> valueReference = null; LoadingValueReference<K, V> loadingValueReference = null; boolean createNewEntry = true; lock(); try { // re-read ticker once inside the lock long now = map.ticker.read(); preWriteCleanup(now); int newCount = this.count - 1; AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { valueReference = e.getValueReference(); if (valueReference.isLoading()) { createNewEntry = false; } else { V value = valueReference.get(); if (value == null) { enqueueNotification( entryKey, hash, value, valueReference.getWeight(), RemovalCause.COLLECTED); } else if (map.isExpired(e, now)) { // This is a duplicate check, as preWriteCleanup already purged expired // entries, but let's accommodate an incorrect expiration queue. enqueueNotification( entryKey, hash, value, valueReference.getWeight(), RemovalCause.EXPIRED); } else { recordLockedRead(e, now); statsCounter.recordHits(1); // we were concurrent with loading; don't consider refresh return value; } // immediately reuse invalid entries writeQueue.remove(e); accessQueue.remove(e); this.count = newCount; // write-volatile } break; } } if (createNewEntry) { loadingValueReference = new LoadingValueReference<>(); if (e == null) { e = newEntry(key, hash, first); e.setValueReference(loadingValueReference); table.set(index, e); } else { e.setValueReference(loadingValueReference); } } } finally { unlock(); postWriteCleanup(); } if (createNewEntry) { try { // Synchronizes on the entry to allow failing fast when a recursive load is // detected. This may be circumvented when an entry is copied, but will fail fast most // of the time. synchronized (e) { return loadSync(key, hash, loadingValueReference, loader); } } finally { statsCounter.recordMisses(1); } } else { // The entry already exists. Wait for loading. return waitForLoadingValue(e, key, valueReference); } } V waitForLoadingValue(ReferenceEntry<K, V> e, K key, ValueReference<K, V> valueReference) throws ExecutionException { if (!valueReference.isLoading()) { throw new AssertionError(); } checkState(!Thread.holdsLock(e), "Recursive load of: %s", key); // don't consider expiration as we're concurrent with loading try { V value = valueReference.waitForValue(); if (value == null) { throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + "."); } // re-read ticker now that loading has completed long now = map.ticker.read(); recordRead(e, now); return value; } finally { statsCounter.recordMisses(1); } } @CheckForNull V compute( K key, int hash, BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> function) { ReferenceEntry<K, V> e; ValueReference<K, V> valueReference = null; ComputingValueReference<K, V> computingValueReference = null; boolean createNewEntry = true; V newValue; lock(); try { // re-read ticker once inside the lock long now = map.ticker.read(); preWriteCleanup(now); AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { valueReference = e.getValueReference(); if (map.isExpired(e, now)) { // This is a duplicate check, as preWriteCleanup already purged expired // entries, but let's accommodate an incorrect expiration queue. enqueueNotification( entryKey, hash, valueReference.get(), valueReference.getWeight(), RemovalCause.EXPIRED); } // immediately reuse invalid entries writeQueue.remove(e); accessQueue.remove(e); createNewEntry = false; break; } } // note valueReference can be an existing value or even itself another loading value if // the value for the key is already being computed. computingValueReference = new ComputingValueReference<>(valueReference); if (e == null) { createNewEntry = true; e = newEntry(key, hash, first); e.setValueReference(computingValueReference); table.set(index, e); } else { e.setValueReference(computingValueReference); } newValue = computingValueReference.compute(key, function); if (newValue != null) { if (valueReference != null && newValue == valueReference.get()) { computingValueReference.set(newValue); e.setValueReference(valueReference); recordWrite(e, 0, now); // no change in weight return newValue; } try { return getAndRecordStats( key, hash, computingValueReference, Futures.immediateFuture(newValue)); } catch (ExecutionException exception) { throw new AssertionError("impossible; Futures.immediateFuture can't throw"); } } else if (createNewEntry || valueReference.isLoading()) { removeLoadingValue(key, hash, computingValueReference); return null; } else { removeEntry(e, hash, RemovalCause.EXPLICIT); return null; } } finally { unlock(); postWriteCleanup(); } } // at most one of loadSync/loadAsync may be called for any given LoadingValueReference V loadSync( K key, int hash, LoadingValueReference<K, V> loadingValueReference, CacheLoader<? super K, V> loader) throws ExecutionException { ListenableFuture<V> loadingFuture = loadingValueReference.loadFuture(key, loader); return getAndRecordStats(key, hash, loadingValueReference, loadingFuture); } ListenableFuture<V> loadAsync( final K key, final int hash, final LoadingValueReference<K, V> loadingValueReference, CacheLoader<? super K, V> loader) { final ListenableFuture<V> loadingFuture = loadingValueReference.loadFuture(key, loader); loadingFuture.addListener( () -> { try { getAndRecordStats(key, hash, loadingValueReference, loadingFuture); } catch (Throwable t) { logger.log(Level.WARNING, "Exception thrown during refresh", t); loadingValueReference.setException(t); } }, directExecutor()); return loadingFuture; } /** Waits uninterruptibly for {@code newValue} to be loaded, and then records loading stats. */ @CanIgnoreReturnValue V getAndRecordStats( K key, int hash, LoadingValueReference<K, V> loadingValueReference, ListenableFuture<V> newValue) throws ExecutionException { V value = null; try { value = getUninterruptibly(newValue); if (value == null) { throw new InvalidCacheLoadException("CacheLoader returned null for key " + key + "."); } statsCounter.recordLoadSuccess(loadingValueReference.elapsedNanos()); storeLoadedValue(key, hash, loadingValueReference, value); return value; } finally { if (value == null) { statsCounter.recordLoadException(loadingValueReference.elapsedNanos()); removeLoadingValue(key, hash, loadingValueReference); } } } V scheduleRefresh( ReferenceEntry<K, V> entry, K key, int hash, V oldValue, long now, CacheLoader<? super K, V> loader) { if (map.refreshes() && (now - entry.getWriteTime() > map.refreshNanos) && !entry.getValueReference().isLoading()) { V newValue = refresh(key, hash, loader, true); if (newValue != null) { return newValue; } } return oldValue; } /** * Refreshes the value associated with {@code key}, unless another thread is already doing so. * Returns the newly refreshed value associated with {@code key} if it was refreshed inline, or * {@code null} if another thread is performing the refresh or if an error occurs during * refresh. */ @CanIgnoreReturnValue @CheckForNull V refresh(K key, int hash, CacheLoader<? super K, V> loader, boolean checkTime) { final LoadingValueReference<K, V> loadingValueReference = insertLoadingValueReference(key, hash, checkTime); if (loadingValueReference == null) { return null; } ListenableFuture<V> result = loadAsync(key, hash, loadingValueReference, loader); if (result.isDone()) { try { return Uninterruptibles.getUninterruptibly(result); } catch (Throwable t) { // don't let refresh exceptions propagate; error was already logged } } return null; } /** * Returns a newly inserted {@code LoadingValueReference}, or null if the live value reference * is already loading. */ @CheckForNull LoadingValueReference<K, V> insertLoadingValueReference( final K key, final int hash, boolean checkTime) { ReferenceEntry<K, V> e = null; lock(); try { long now = map.ticker.read(); preWriteCleanup(now); AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); // Look for an existing entry. for (e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { // We found an existing entry. ValueReference<K, V> valueReference = e.getValueReference(); if (valueReference.isLoading() || (checkTime && (now - e.getWriteTime() < map.refreshNanos))) { // refresh is a no-op if loading is pending // if checkTime, we want to check *after* acquiring the lock if refresh still needs // to be scheduled return null; } // continue returning old value while loading ++modCount; LoadingValueReference<K, V> loadingValueReference = new LoadingValueReference<>(valueReference); e.setValueReference(loadingValueReference); return loadingValueReference; } } ++modCount; LoadingValueReference<K, V> loadingValueReference = new LoadingValueReference<>(); e = newEntry(key, hash, first); e.setValueReference(loadingValueReference); table.set(index, e); return loadingValueReference; } finally { unlock(); postWriteCleanup(); } } // reference queues, for garbage collection cleanup /** Cleanup collected entries when the lock is available. */ void tryDrainReferenceQueues() { if (tryLock()) { try { drainReferenceQueues(); } finally { unlock(); } } } /** * Drain the key and value reference queues, cleaning up internal entries containing garbage * collected keys or values. */ @GuardedBy("this") void drainReferenceQueues() { if (map.usesKeyReferences()) { drainKeyReferenceQueue(); } if (map.usesValueReferences()) { drainValueReferenceQueue(); } } @GuardedBy("this") void drainKeyReferenceQueue() { Reference<? extends K> ref; int i = 0; while ((ref = keyReferenceQueue.poll()) != null) { @SuppressWarnings("unchecked") ReferenceEntry<K, V> entry = (ReferenceEntry<K, V>) ref; map.reclaimKey(entry); if (++i == DRAIN_MAX) { break; } } } @GuardedBy("this") void drainValueReferenceQueue() { Reference<? extends V> ref; int i = 0; while ((ref = valueReferenceQueue.poll()) != null) { @SuppressWarnings("unchecked") ValueReference<K, V> valueReference = (ValueReference<K, V>) ref; map.reclaimValue(valueReference); if (++i == DRAIN_MAX) { break; } } } /** Clears all entries from the key and value reference queues. */ void clearReferenceQueues() { if (map.usesKeyReferences()) { clearKeyReferenceQueue(); } if (map.usesValueReferences()) { clearValueReferenceQueue(); } } void clearKeyReferenceQueue() { while (keyReferenceQueue.poll() != null) {} } void clearValueReferenceQueue() { while (valueReferenceQueue.poll() != null) {} } // recency queue, shared by expiration and eviction /** * Records the relative order in which this read was performed by adding {@code entry} to the * recency queue. At write-time, or when the queue is full past the threshold, the queue will be * drained and the entries therein processed. * * <p>Note: locked reads should use {@link #recordLockedRead}. */ void recordRead(ReferenceEntry<K, V> entry, long now) { if (map.recordsAccess()) { entry.setAccessTime(now); } recencyQueue.add(entry); } /** * Updates the eviction metadata that {@code entry} was just read. This currently amounts to * adding {@code entry} to relevant eviction lists. * * <p>Note: this method should only be called under lock, as it directly manipulates the * eviction queues. Unlocked reads should use {@link #recordRead}. */ @GuardedBy("this") void recordLockedRead(ReferenceEntry<K, V> entry, long now) { if (map.recordsAccess()) { entry.setAccessTime(now); } accessQueue.add(entry); } /** * Updates eviction metadata that {@code entry} was just written. This currently amounts to * adding {@code entry} to relevant eviction lists. */ @GuardedBy("this") void recordWrite(ReferenceEntry<K, V> entry, int weight, long now) { // we are already under lock, so drain the recency queue immediately drainRecencyQueue(); totalWeight += weight; if (map.recordsAccess()) { entry.setAccessTime(now); } if (map.recordsWrite()) { entry.setWriteTime(now); } accessQueue.add(entry); writeQueue.add(entry); } /** * Drains the recency queue, updating eviction metadata that the entries therein were read in * the specified relative order. This currently amounts to adding them to relevant eviction * lists (accounting for the fact that they could have been removed from the map since being * added to the recency queue). */ @GuardedBy("this") void drainRecencyQueue() { ReferenceEntry<K, V> e; while ((e = recencyQueue.poll()) != null) { // An entry may be in the recency queue despite it being removed from // the map . This can occur when the entry was concurrently read while a // writer is removing it from the segment or after a clear has removed // all the segment's entries. if (accessQueue.contains(e)) { accessQueue.add(e); } } } // expiration /** Cleanup expired entries when the lock is available. */ void tryExpireEntries(long now) { if (tryLock()) { try { expireEntries(now); } finally { unlock(); // don't call postWriteCleanup as we're in a read } } } @GuardedBy("this") void expireEntries(long now) { drainRecencyQueue(); ReferenceEntry<K, V> e; while ((e = writeQueue.peek()) != null && map.isExpired(e, now)) { if (!removeEntry(e, e.getHash(), RemovalCause.EXPIRED)) { throw new AssertionError(); } } while ((e = accessQueue.peek()) != null && map.isExpired(e, now)) { if (!removeEntry(e, e.getHash(), RemovalCause.EXPIRED)) { throw new AssertionError(); } } } // eviction @GuardedBy("this") void enqueueNotification( @CheckForNull K key, int hash, @CheckForNull V value, int weight, RemovalCause cause) { totalWeight -= weight; if (cause.wasEvicted()) { statsCounter.recordEviction(); } if (map.removalNotificationQueue != DISCARDING_QUEUE) { RemovalNotification<K, V> notification = RemovalNotification.create(key, value, cause); map.removalNotificationQueue.offer(notification); } } /** * Performs eviction if the segment is over capacity. Avoids flushing the entire cache if the * newest entry exceeds the maximum weight all on its own. * * @param newest the most recently added entry */ @GuardedBy("this") void evictEntries(ReferenceEntry<K, V> newest) { if (!map.evictsBySize()) { return; } drainRecencyQueue(); // If the newest entry by itself is too heavy for the segment, don't bother evicting // anything else, just that if (newest.getValueReference().getWeight() > maxSegmentWeight) { if (!removeEntry(newest, newest.getHash(), RemovalCause.SIZE)) { throw new AssertionError(); } } while (totalWeight > maxSegmentWeight) { ReferenceEntry<K, V> e = getNextEvictable(); if (!removeEntry(e, e.getHash(), RemovalCause.SIZE)) { throw new AssertionError(); } } } // TODO(fry): instead implement this with an eviction head @GuardedBy("this") ReferenceEntry<K, V> getNextEvictable() { for (ReferenceEntry<K, V> e : accessQueue) { int weight = e.getValueReference().getWeight(); if (weight > 0) { return e; } } throw new AssertionError(); } /** Returns first entry of bin for given hash. */ ReferenceEntry<K, V> getFirst(int hash) { // read this volatile field only once AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; return table.get(hash & (table.length() - 1)); } // Specialized implementations of map methods @CheckForNull ReferenceEntry<K, V> getEntry(Object key, int hash) { for (ReferenceEntry<K, V> e = getFirst(hash); e != null; e = e.getNext()) { if (e.getHash() != hash) { continue; } K entryKey = e.getKey(); if (entryKey == null) { tryDrainReferenceQueues(); continue; } if (map.keyEquivalence.equivalent(key, entryKey)) { return e; } } return null; } @CheckForNull ReferenceEntry<K, V> getLiveEntry(Object key, int hash, long now) { ReferenceEntry<K, V> e = getEntry(key, hash); if (e == null) { return null; } else if (map.isExpired(e, now)) { tryExpireEntries(now); return null; } return e; } /** * Gets the value from an entry. Returns null if the entry is invalid, partially-collected, * loading, or expired. */ V getLiveValue(ReferenceEntry<K, V> entry, long now) { if (entry.getKey() == null) { tryDrainReferenceQueues(); return null; } V value = entry.getValueReference().get(); if (value == null) { tryDrainReferenceQueues(); return null; } if (map.isExpired(entry, now)) { tryExpireEntries(now); return null; } return value; } boolean containsKey(Object key, int hash) { try { if (count != 0) { // read-volatile long now = map.ticker.read(); ReferenceEntry<K, V> e = getLiveEntry(key, hash, now); if (e == null) { return false; } return e.getValueReference().get() != null; } return false; } finally { postReadCleanup(); } } /** * This method is a convenience for testing. Code should call {@link LocalCache#containsValue} * directly. */ @VisibleForTesting boolean containsValue(Object value) { try { if (count != 0) { // read-volatile long now = map.ticker.read(); AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int length = table.length(); for (int i = 0; i < length; ++i) { for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) { V entryValue = getLiveValue(e, now); if (entryValue == null) { continue; } if (map.valueEquivalence.equivalent(value, entryValue)) { return true; } } } } return false; } finally { postReadCleanup(); } } @CanIgnoreReturnValue @CheckForNull V put(K key, int hash, V value, boolean onlyIfAbsent) { lock(); try { long now = map.ticker.read(); preWriteCleanup(now); int newCount = this.count + 1; if (newCount > this.threshold) { // ensure capacity expand(); newCount = this.count + 1; } AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); // Look for an existing entry. for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { // We found an existing entry. ValueReference<K, V> valueReference = e.getValueReference(); V entryValue = valueReference.get(); if (entryValue == null) { ++modCount; if (valueReference.isActive()) { enqueueNotification( key, hash, entryValue, valueReference.getWeight(), RemovalCause.COLLECTED); setValue(e, key, value, now); newCount = this.count; // count remains unchanged } else { setValue(e, key, value, now); newCount = this.count + 1; } this.count = newCount; // write-volatile evictEntries(e); return null; } else if (onlyIfAbsent) { // Mimic // "if (!map.containsKey(key)) ... // else return map.get(key); recordLockedRead(e, now); return entryValue; } else { // clobber existing entry, count remains unchanged ++modCount; enqueueNotification( key, hash, entryValue, valueReference.getWeight(), RemovalCause.REPLACED); setValue(e, key, value, now); evictEntries(e); return entryValue; } } } // Create a new entry. ++modCount; ReferenceEntry<K, V> newEntry = newEntry(key, hash, first); setValue(newEntry, key, value, now); table.set(index, newEntry); newCount = this.count + 1; this.count = newCount; // write-volatile evictEntries(newEntry); return null; } finally { unlock(); postWriteCleanup(); } } /** Expands the table if possible. */ @GuardedBy("this") void expand() { AtomicReferenceArray<ReferenceEntry<K, V>> oldTable = table; int oldCapacity = oldTable.length(); if (oldCapacity >= MAXIMUM_CAPACITY) { return; } /* * Reclassify nodes in each list to new Map. Because we are using power-of-two expansion, the * elements from each bin must either stay at same index, or move with a power of two offset. * We eliminate unnecessary node creation by catching cases where old nodes can be reused * because their next fields won't change. Statistically, at the default threshold, only about * one-sixth of them need cloning when a table doubles. The nodes they replace will be garbage * collectable as soon as they are no longer referenced by any reader thread that may be in * the midst of traversing table right now. */ int newCount = count; AtomicReferenceArray<ReferenceEntry<K, V>> newTable = newEntryArray(oldCapacity << 1); threshold = newTable.length() * 3 / 4; int newMask = newTable.length() - 1; for (int oldIndex = 0; oldIndex < oldCapacity; ++oldIndex) { // We need to guarantee that any existing reads of old Map can // proceed. So we cannot yet null out each bin. ReferenceEntry<K, V> head = oldTable.get(oldIndex); if (head != null) { ReferenceEntry<K, V> next = head.getNext(); int headIndex = head.getHash() & newMask; // Single node on list if (next == null) { newTable.set(headIndex, head); } else { // Reuse the consecutive sequence of nodes with the same target // index from the end of the list. tail points to the first // entry in the reusable list. ReferenceEntry<K, V> tail = head; int tailIndex = headIndex; for (ReferenceEntry<K, V> e = next; e != null; e = e.getNext()) { int newIndex = e.getHash() & newMask; if (newIndex != tailIndex) { // The index changed. We'll need to copy the previous entry. tailIndex = newIndex; tail = e; } } newTable.set(tailIndex, tail); // Clone nodes leading up to the tail. for (ReferenceEntry<K, V> e = head; e != tail; e = e.getNext()) { int newIndex = e.getHash() & newMask; ReferenceEntry<K, V> newNext = newTable.get(newIndex); ReferenceEntry<K, V> newFirst = copyEntry(e, newNext); if (newFirst != null) { newTable.set(newIndex, newFirst); } else { removeCollectedEntry(e); newCount--; } } } } } table = newTable; this.count = newCount; } boolean replace(K key, int hash, V oldValue, V newValue) { lock(); try { long now = map.ticker.read(); preWriteCleanup(now); AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { ValueReference<K, V> valueReference = e.getValueReference(); V entryValue = valueReference.get(); if (entryValue == null) { if (valueReference.isActive()) { // If the value disappeared, this entry is partially collected. int newCount = this.count - 1; ++modCount; ReferenceEntry<K, V> newFirst = removeValueFromChain( first, e, entryKey, hash, entryValue, valueReference, RemovalCause.COLLECTED); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile } return false; } if (map.valueEquivalence.equivalent(oldValue, entryValue)) { ++modCount; enqueueNotification( key, hash, entryValue, valueReference.getWeight(), RemovalCause.REPLACED); setValue(e, key, newValue, now); evictEntries(e); return true; } else { // Mimic // "if (map.containsKey(key) && map.get(key).equals(oldValue))..." recordLockedRead(e, now); return false; } } } return false; } finally { unlock(); postWriteCleanup(); } } @CheckForNull V replace(K key, int hash, V newValue) { lock(); try { long now = map.ticker.read(); preWriteCleanup(now); AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { ValueReference<K, V> valueReference = e.getValueReference(); V entryValue = valueReference.get(); if (entryValue == null) { if (valueReference.isActive()) { // If the value disappeared, this entry is partially collected. int newCount = this.count - 1; ++modCount; ReferenceEntry<K, V> newFirst = removeValueFromChain( first, e, entryKey, hash, entryValue, valueReference, RemovalCause.COLLECTED); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile } return null; } ++modCount; enqueueNotification( key, hash, entryValue, valueReference.getWeight(), RemovalCause.REPLACED); setValue(e, key, newValue, now); evictEntries(e); return entryValue; } } return null; } finally { unlock(); postWriteCleanup(); } } @CheckForNull V remove(Object key, int hash) { lock(); try { long now = map.ticker.read(); preWriteCleanup(now); int newCount = this.count - 1; AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { ValueReference<K, V> valueReference = e.getValueReference(); V entryValue = valueReference.get(); RemovalCause cause; if (entryValue != null) { cause = RemovalCause.EXPLICIT; } else if (valueReference.isActive()) { cause = RemovalCause.COLLECTED; } else { // currently loading return null; } ++modCount; ReferenceEntry<K, V> newFirst = removeValueFromChain(first, e, entryKey, hash, entryValue, valueReference, cause); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile return entryValue; } } return null; } finally { unlock(); postWriteCleanup(); } } boolean remove(Object key, int hash, Object value) { lock(); try { long now = map.ticker.read(); preWriteCleanup(now); int newCount = this.count - 1; AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { ValueReference<K, V> valueReference = e.getValueReference(); V entryValue = valueReference.get(); RemovalCause cause; if (map.valueEquivalence.equivalent(value, entryValue)) { cause = RemovalCause.EXPLICIT; } else if (entryValue == null && valueReference.isActive()) { cause = RemovalCause.COLLECTED; } else { // currently loading return false; } ++modCount; ReferenceEntry<K, V> newFirst = removeValueFromChain(first, e, entryKey, hash, entryValue, valueReference, cause); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile return (cause == RemovalCause.EXPLICIT); } } return false; } finally { unlock(); postWriteCleanup(); } } @CanIgnoreReturnValue boolean storeLoadedValue( K key, int hash, LoadingValueReference<K, V> oldValueReference, V newValue) { lock(); try { long now = map.ticker.read(); preWriteCleanup(now); int newCount = this.count + 1; if (newCount > this.threshold) { // ensure capacity expand(); newCount = this.count + 1; } AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { ValueReference<K, V> valueReference = e.getValueReference(); V entryValue = valueReference.get(); // replace the old LoadingValueReference if it's live, otherwise // perform a putIfAbsent if (oldValueReference == valueReference || (entryValue == null && valueReference != UNSET)) { ++modCount; if (oldValueReference.isActive()) { RemovalCause cause = (entryValue == null) ? RemovalCause.COLLECTED : RemovalCause.REPLACED; enqueueNotification(key, hash, entryValue, oldValueReference.getWeight(), cause); newCount--; } setValue(e, key, newValue, now); this.count = newCount; // write-volatile evictEntries(e); return true; } // the loaded value was already clobbered enqueueNotification(key, hash, newValue, 0, RemovalCause.REPLACED); return false; } } ++modCount; ReferenceEntry<K, V> newEntry = newEntry(key, hash, first); setValue(newEntry, key, newValue, now); table.set(index, newEntry); this.count = newCount; // write-volatile evictEntries(newEntry); return true; } finally { unlock(); postWriteCleanup(); } } void clear() { if (count != 0) { // read-volatile lock(); try { long now = map.ticker.read(); preWriteCleanup(now); AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; for (int i = 0; i < table.length(); ++i) { for (ReferenceEntry<K, V> e = table.get(i); e != null; e = e.getNext()) { // Loading references aren't actually in the map yet. if (e.getValueReference().isActive()) { K key = e.getKey(); V value = e.getValueReference().get(); RemovalCause cause = (key == null || value == null) ? RemovalCause.COLLECTED : RemovalCause.EXPLICIT; enqueueNotification( key, e.getHash(), value, e.getValueReference().getWeight(), cause); } } } for (int i = 0; i < table.length(); ++i) { table.set(i, null); } clearReferenceQueues(); writeQueue.clear(); accessQueue.clear(); readCount.set(0); ++modCount; count = 0; // write-volatile } finally { unlock(); postWriteCleanup(); } } } @GuardedBy("this") @CheckForNull ReferenceEntry<K, V> removeValueFromChain( ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry, @CheckForNull K key, int hash, V value, ValueReference<K, V> valueReference, RemovalCause cause) { enqueueNotification(key, hash, value, valueReference.getWeight(), cause); writeQueue.remove(entry); accessQueue.remove(entry); if (valueReference.isLoading()) { valueReference.notifyNewValue(null); return first; } else { return removeEntryFromChain(first, entry); } } @GuardedBy("this") @CheckForNull ReferenceEntry<K, V> removeEntryFromChain( ReferenceEntry<K, V> first, ReferenceEntry<K, V> entry) { int newCount = count; ReferenceEntry<K, V> newFirst = entry.getNext(); for (ReferenceEntry<K, V> e = first; e != entry; e = e.getNext()) { ReferenceEntry<K, V> next = copyEntry(e, newFirst); if (next != null) { newFirst = next; } else { removeCollectedEntry(e); newCount--; } } this.count = newCount; return newFirst; } @GuardedBy("this") void removeCollectedEntry(ReferenceEntry<K, V> entry) { enqueueNotification( entry.getKey(), entry.getHash(), entry.getValueReference().get(), entry.getValueReference().getWeight(), RemovalCause.COLLECTED); writeQueue.remove(entry); accessQueue.remove(entry); } /** Removes an entry whose key has been garbage collected. */ @CanIgnoreReturnValue boolean reclaimKey(ReferenceEntry<K, V> entry, int hash) { lock(); try { int newCount = count - 1; AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { if (e == entry) { ++modCount; ReferenceEntry<K, V> newFirst = removeValueFromChain( first, e, e.getKey(), hash, e.getValueReference().get(), e.getValueReference(), RemovalCause.COLLECTED); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile return true; } } return false; } finally { unlock(); postWriteCleanup(); } } /** Removes an entry whose value has been garbage collected. */ @CanIgnoreReturnValue boolean reclaimValue(K key, int hash, ValueReference<K, V> valueReference) { lock(); try { int newCount = this.count - 1; AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { ValueReference<K, V> v = e.getValueReference(); if (v == valueReference) { ++modCount; ReferenceEntry<K, V> newFirst = removeValueFromChain( first, e, entryKey, hash, valueReference.get(), valueReference, RemovalCause.COLLECTED); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile return true; } return false; } } return false; } finally { unlock(); if (!isHeldByCurrentThread()) { // don't clean up inside of put postWriteCleanup(); } } } @CanIgnoreReturnValue boolean removeLoadingValue(K key, int hash, LoadingValueReference<K, V> valueReference) { lock(); try { AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { K entryKey = e.getKey(); if (e.getHash() == hash && entryKey != null && map.keyEquivalence.equivalent(key, entryKey)) { ValueReference<K, V> v = e.getValueReference(); if (v == valueReference) { if (valueReference.isActive()) { e.setValueReference(valueReference.getOldValue()); } else { ReferenceEntry<K, V> newFirst = removeEntryFromChain(first, e); table.set(index, newFirst); } return true; } return false; } } return false; } finally { unlock(); postWriteCleanup(); } } @VisibleForTesting @GuardedBy("this") @CanIgnoreReturnValue boolean removeEntry(ReferenceEntry<K, V> entry, int hash, RemovalCause cause) { int newCount = this.count - 1; AtomicReferenceArray<ReferenceEntry<K, V>> table = this.table; int index = hash & (table.length() - 1); ReferenceEntry<K, V> first = table.get(index); for (ReferenceEntry<K, V> e = first; e != null; e = e.getNext()) { if (e == entry) { ++modCount; ReferenceEntry<K, V> newFirst = removeValueFromChain( first, e, e.getKey(), hash, e.getValueReference().get(), e.getValueReference(), cause); newCount = this.count - 1; table.set(index, newFirst); this.count = newCount; // write-volatile return true; } } return false; } /** * Performs routine cleanup following a read. Normally cleanup happens during writes. If cleanup * is not observed after a sufficient number of reads, try cleaning up from the read thread. */ void postReadCleanup() { if ((readCount.incrementAndGet() & DRAIN_THRESHOLD) == 0) { cleanUp(); } } /** * Performs routine cleanup prior to executing a write. This should be called every time a write * thread acquires the segment lock, immediately after acquiring the lock. * * <p>Post-condition: expireEntries has been run. */ @GuardedBy("this") void preWriteCleanup(long now) { runLockedCleanup(now); } /** Performs routine cleanup following a write. */ void postWriteCleanup() { runUnlockedCleanup(); } void cleanUp() { long now = map.ticker.read(); runLockedCleanup(now); runUnlockedCleanup(); } void runLockedCleanup(long now) { if (tryLock()) { try { drainReferenceQueues(); expireEntries(now); // calls drainRecencyQueue readCount.set(0); } finally { unlock(); } } } void runUnlockedCleanup() { // locked cleanup may generate notifications we can send unlocked if (!isHeldByCurrentThread()) { map.processPendingNotifications(); } } } static class LoadingValueReference<K, V> implements ValueReference<K, V> { volatile ValueReference<K, V> oldValue; // TODO(fry): rename get, then extend AbstractFuture instead of containing SettableFuture final SettableFuture<V> futureValue = SettableFuture.create(); final Stopwatch stopwatch = Stopwatch.createUnstarted(); public LoadingValueReference() { this(null); } public LoadingValueReference(@CheckForNull ValueReference<K, V> oldValue) { this.oldValue = (oldValue == null) ? LocalCache.unset() : oldValue; } @Override public boolean isLoading() { return true; } @Override public boolean isActive() { return oldValue.isActive(); } @Override public int getWeight() { return oldValue.getWeight(); } @CanIgnoreReturnValue public boolean set(@CheckForNull V newValue) { return futureValue.set(newValue); } @CanIgnoreReturnValue public boolean setException(Throwable t) { return futureValue.setException(t); } private ListenableFuture<V> fullyFailedFuture(Throwable t) { return Futures.immediateFailedFuture(t); } @Override public void notifyNewValue(@CheckForNull V newValue) { if (newValue != null) { // The pending load was clobbered by a manual write. // Unblock all pending gets, and have them return the new value. set(newValue); } else { // The pending load was removed. Delay notifications until loading completes. oldValue = unset(); } // TODO(fry): could also cancel loading if we had a handle on its future } public ListenableFuture<V> loadFuture(K key, CacheLoader<? super K, V> loader) { try { stopwatch.start(); V previousValue = oldValue.get(); if (previousValue == null) { V newValue = loader.load(key); return set(newValue) ? futureValue : Futures.immediateFuture(newValue); } ListenableFuture<V> newValue = loader.reload(key, previousValue); if (newValue == null) { return Futures.immediateFuture(null); } // To avoid a race, make sure the refreshed value is set into loadingValueReference // *before* returning newValue from the cache query. return transform( newValue, newResult -> { LoadingValueReference.this.set(newResult); return newResult; }, directExecutor()); } catch (Throwable t) { ListenableFuture<V> result = setException(t) ? futureValue : fullyFailedFuture(t); if (t instanceof InterruptedException) { Thread.currentThread().interrupt(); } return result; } } @CheckForNull public V compute( K key, BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> function) { stopwatch.start(); V previousValue; try { previousValue = oldValue.waitForValue(); } catch (ExecutionException e) { previousValue = null; } V newValue; try { newValue = function.apply(key, previousValue); } catch (Throwable th) { this.setException(th); throw th; } this.set(newValue); return newValue; } public long elapsedNanos() { return stopwatch.elapsed(NANOSECONDS); } @Override public V waitForValue() throws ExecutionException { return getUninterruptibly(futureValue); } @Override public V get() { return oldValue.get(); } public ValueReference<K, V> getOldValue() { return oldValue; } @Override public ReferenceEntry<K, V> getEntry() { return null; } @Override public ValueReference<K, V> copyFor( ReferenceQueue<V> queue, @CheckForNull V value, ReferenceEntry<K, V> entry) { return this; } } static class ComputingValueReference<K, V> extends LoadingValueReference<K, V> { ComputingValueReference(ValueReference<K, V> oldValue) { super(oldValue); } @Override public boolean isLoading() { return false; } } // Queues /** * A custom queue for managing eviction order. Note that this is tightly integrated with {@code * ReferenceEntry}, upon which it relies to perform its linking. * * <p>Note that this entire implementation makes the assumption that all elements which are in the * map are also in this queue, and that all elements not in the queue are not in the map. * * <p>The benefits of creating our own queue are that (1) we can replace elements in the middle of * the queue as part of copyWriteEntry, and (2) the contains method is highly optimized for the * current model. */ static final class WriteQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> { final ReferenceEntry<K, V> head = new AbstractReferenceEntry<K, V>() { @Override public long getWriteTime() { return Long.MAX_VALUE; } @Override public void setWriteTime(long time) {} @Weak ReferenceEntry<K, V> nextWrite = this; @Override public ReferenceEntry<K, V> getNextInWriteQueue() { return nextWrite; } @Override public void setNextInWriteQueue(ReferenceEntry<K, V> next) { this.nextWrite = next; } @Weak ReferenceEntry<K, V> previousWrite = this; @Override public ReferenceEntry<K, V> getPreviousInWriteQueue() { return previousWrite; } @Override public void setPreviousInWriteQueue(ReferenceEntry<K, V> previous) { this.previousWrite = previous; } }; // implements Queue @Override public boolean offer(ReferenceEntry<K, V> entry) { // unlink connectWriteOrder(entry.getPreviousInWriteQueue(), entry.getNextInWriteQueue()); // add to tail connectWriteOrder(head.getPreviousInWriteQueue(), entry); connectWriteOrder(entry, head); return true; } @CheckForNull @Override public ReferenceEntry<K, V> peek() { ReferenceEntry<K, V> next = head.getNextInWriteQueue(); return (next == head) ? null : next; } @CheckForNull @Override public ReferenceEntry<K, V> poll() { ReferenceEntry<K, V> next = head.getNextInWriteQueue(); if (next == head) { return null; } remove(next); return next; } @Override @SuppressWarnings("unchecked") @CanIgnoreReturnValue public boolean remove(Object o) { ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o; ReferenceEntry<K, V> previous = e.getPreviousInWriteQueue(); ReferenceEntry<K, V> next = e.getNextInWriteQueue(); connectWriteOrder(previous, next); nullifyWriteOrder(e); return next != NullEntry.INSTANCE; } @Override @SuppressWarnings("unchecked") public boolean contains(Object o) { ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o; return e.getNextInWriteQueue() != NullEntry.INSTANCE; } @Override public boolean isEmpty() { return head.getNextInWriteQueue() == head; } @Override public int size() { int size = 0; for (ReferenceEntry<K, V> e = head.getNextInWriteQueue(); e != head; e = e.getNextInWriteQueue()) { size++; } return size; } @Override public void clear() { ReferenceEntry<K, V> e = head.getNextInWriteQueue(); while (e != head) { ReferenceEntry<K, V> next = e.getNextInWriteQueue(); nullifyWriteOrder(e); e = next; } head.setNextInWriteQueue(head); head.setPreviousInWriteQueue(head); } @Override public Iterator<ReferenceEntry<K, V>> iterator() { return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) { @CheckForNull @Override protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) { ReferenceEntry<K, V> next = previous.getNextInWriteQueue(); return (next == head) ? null : next; } }; } } /** * A custom queue for managing access order. Note that this is tightly integrated with {@code * ReferenceEntry}, upon which it relies to perform its linking. * * <p>Note that this entire implementation makes the assumption that all elements which are in the * map are also in this queue, and that all elements not in the queue are not in the map. * * <p>The benefits of creating our own queue are that (1) we can replace elements in the middle of * the queue as part of copyWriteEntry, and (2) the contains method is highly optimized for the * current model. */ static final class AccessQueue<K, V> extends AbstractQueue<ReferenceEntry<K, V>> { final ReferenceEntry<K, V> head = new AbstractReferenceEntry<K, V>() { @Override public long getAccessTime() { return Long.MAX_VALUE; } @Override public void setAccessTime(long time) {} @Weak ReferenceEntry<K, V> nextAccess = this; @Override public ReferenceEntry<K, V> getNextInAccessQueue() { return nextAccess; } @Override public void setNextInAccessQueue(ReferenceEntry<K, V> next) { this.nextAccess = next; } @Weak ReferenceEntry<K, V> previousAccess = this; @Override public ReferenceEntry<K, V> getPreviousInAccessQueue() { return previousAccess; } @Override public void setPreviousInAccessQueue(ReferenceEntry<K, V> previous) { this.previousAccess = previous; } }; // implements Queue @Override public boolean offer(ReferenceEntry<K, V> entry) { // unlink connectAccessOrder(entry.getPreviousInAccessQueue(), entry.getNextInAccessQueue()); // add to tail connectAccessOrder(head.getPreviousInAccessQueue(), entry); connectAccessOrder(entry, head); return true; } @CheckForNull @Override public ReferenceEntry<K, V> peek() { ReferenceEntry<K, V> next = head.getNextInAccessQueue(); return (next == head) ? null : next; } @CheckForNull @Override public ReferenceEntry<K, V> poll() { ReferenceEntry<K, V> next = head.getNextInAccessQueue(); if (next == head) { return null; } remove(next); return next; } @Override @SuppressWarnings("unchecked") @CanIgnoreReturnValue public boolean remove(Object o) { ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o; ReferenceEntry<K, V> previous = e.getPreviousInAccessQueue(); ReferenceEntry<K, V> next = e.getNextInAccessQueue(); connectAccessOrder(previous, next); nullifyAccessOrder(e); return next != NullEntry.INSTANCE; } @Override @SuppressWarnings("unchecked") public boolean contains(Object o) { ReferenceEntry<K, V> e = (ReferenceEntry<K, V>) o; return e.getNextInAccessQueue() != NullEntry.INSTANCE; } @Override public boolean isEmpty() { return head.getNextInAccessQueue() == head; } @Override public int size() { int size = 0; for (ReferenceEntry<K, V> e = head.getNextInAccessQueue(); e != head; e = e.getNextInAccessQueue()) { size++; } return size; } @Override public void clear() { ReferenceEntry<K, V> e = head.getNextInAccessQueue(); while (e != head) { ReferenceEntry<K, V> next = e.getNextInAccessQueue(); nullifyAccessOrder(e); e = next; } head.setNextInAccessQueue(head); head.setPreviousInAccessQueue(head); } @Override public Iterator<ReferenceEntry<K, V>> iterator() { return new AbstractSequentialIterator<ReferenceEntry<K, V>>(peek()) { @CheckForNull @Override protected ReferenceEntry<K, V> computeNext(ReferenceEntry<K, V> previous) { ReferenceEntry<K, V> next = previous.getNextInAccessQueue(); return (next == head) ? null : next; } }; } } // Cache support public void cleanUp() { for (Segment<?, ?> segment : segments) { segment.cleanUp(); } } // ConcurrentMap methods @Override public boolean isEmpty() { /* * Sum per-segment modCounts to avoid mis-reporting when elements are concurrently added and * removed in one segment while checking another, in which case the table was never actually * empty at any point. (The sum ensures accuracy up through at least 1<<31 per-segment * modifications before recheck.) Method containsValue() uses similar constructions for * stability checks. */ long sum = 0L; Segment<K, V>[] segments = this.segments; for (Segment<K, V> segment : segments) { if (segment.count != 0) { return false; } sum += segment.modCount; } if (sum != 0L) { // recheck unless no modifications for (Segment<K, V> segment : segments) { if (segment.count != 0) { return false; } sum -= segment.modCount; } return sum == 0L; } return true; } long longSize() { Segment<K, V>[] segments = this.segments; long sum = 0; for (Segment<K, V> segment : segments) { sum += segment.count; } return sum; } @Override public int size() { return Ints.saturatedCast(longSize()); } @CanIgnoreReturnValue // TODO(b/27479612): consider removing this @Override @CheckForNull public V get(@CheckForNull Object key) { if (key == null) { return null; } int hash = hash(key); return segmentFor(hash).get(key, hash); } @CanIgnoreReturnValue // TODO(b/27479612): consider removing this V get(K key, CacheLoader<? super K, V> loader) throws ExecutionException { int hash = hash(checkNotNull(key)); return segmentFor(hash).get(key, hash, loader); } @CheckForNull public V getIfPresent(Object key) { int hash = hash(checkNotNull(key)); V value = segmentFor(hash).get(key, hash); if (value == null) { globalStatsCounter.recordMisses(1); } else { globalStatsCounter.recordHits(1); } return value; } @Override @CheckForNull public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) { V result = get(key); return (result != null) ? result : defaultValue; } V getOrLoad(K key) throws ExecutionException { return get(key, defaultLoader); } ImmutableMap<K, V> getAllPresent(Iterable<?> keys) { int hits = 0; int misses = 0; ImmutableMap.Builder<K, V> result = ImmutableMap.builder(); for (Object key : keys) { V value = get(key); if (value == null) { misses++; } else { // TODO(fry): store entry key instead of query key @SuppressWarnings("unchecked") K castKey = (K) key; result.put(castKey, value); hits++; } } globalStatsCounter.recordHits(hits); globalStatsCounter.recordMisses(misses); return result.buildKeepingLast(); } ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException { int hits = 0; int misses = 0; Map<K, V> result = Maps.newLinkedHashMap(); Set<K> keysToLoad = Sets.newLinkedHashSet(); for (K key : keys) { V value = get(key); if (!result.containsKey(key)) { result.put(key, value); if (value == null) { misses++; keysToLoad.add(key); } else { hits++; } } } try { if (!keysToLoad.isEmpty()) { try { Map<K, V> newEntries = loadAll(unmodifiableSet(keysToLoad), defaultLoader); for (K key : keysToLoad) { V value = newEntries.get(key); if (value == null) { throw new InvalidCacheLoadException("loadAll failed to return a value for " + key); } result.put(key, value); } } catch (UnsupportedLoadingOperationException e) { // loadAll not implemented, fallback to load for (K key : keysToLoad) { misses--; // get will count this miss result.put(key, get(key, defaultLoader)); } } } return ImmutableMap.copyOf(result); } finally { globalStatsCounter.recordHits(hits); globalStatsCounter.recordMisses(misses); } } /** * Returns the result of calling {@link CacheLoader#loadAll}, or null if {@code loader} doesn't * implement {@code loadAll}. */ @CheckForNull Map<K, V> loadAll(Set<? extends K> keys, CacheLoader<? super K, V> loader) throws ExecutionException { checkNotNull(loader); checkNotNull(keys); Stopwatch stopwatch = Stopwatch.createStarted(); Map<K, V> result; boolean success = false; try { @SuppressWarnings("unchecked") // safe since all keys extend K Map<K, V> map = (Map<K, V>) loader.loadAll(keys); result = map; success = true; } catch (UnsupportedLoadingOperationException e) { success = true; throw e; } catch (InterruptedException e) { Thread.currentThread().interrupt(); throw new ExecutionException(e); } catch (RuntimeException e) { throw new UncheckedExecutionException(e); } catch (Exception e) { throw new ExecutionException(e); } catch (Error e) { throw new ExecutionError(e); } finally { if (!success) { globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS)); } } if (result == null) { globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS)); throw new InvalidCacheLoadException(loader + " returned null map from loadAll"); } stopwatch.stop(); // TODO(fry): batch by segment boolean nullsPresent = false; for (Entry<K, V> entry : result.entrySet()) { K key = entry.getKey(); V value = entry.getValue(); if (key == null || value == null) { // delay failure until non-null entries are stored nullsPresent = true; } else { put(key, value); } } if (nullsPresent) { globalStatsCounter.recordLoadException(stopwatch.elapsed(NANOSECONDS)); throw new InvalidCacheLoadException(loader + " returned null keys or values from loadAll"); } // TODO(fry): record count of loaded entries globalStatsCounter.recordLoadSuccess(stopwatch.elapsed(NANOSECONDS)); return result; } /** * Returns the internal entry for the specified key. The entry may be loading, expired, or * partially collected. */ @CheckForNull ReferenceEntry<K, V> getEntry(@CheckForNull Object key) { // does not impact recency ordering if (key == null) { return null; } int hash = hash(key); return segmentFor(hash).getEntry(key, hash); } void refresh(K key) { int hash = hash(checkNotNull(key)); segmentFor(hash).refresh(key, hash, defaultLoader, false); } @Override public boolean containsKey(@CheckForNull Object key) { // does not impact recency ordering if (key == null) { return false; } int hash = hash(key); return segmentFor(hash).containsKey(key, hash); } @Override public boolean containsValue(@CheckForNull Object value) { // does not impact recency ordering if (value == null) { return false; } // This implementation is patterned after ConcurrentHashMap, but without the locking. The only // way for it to return a false negative would be for the target value to jump around in the map // such that none of the subsequent iterations observed it, despite the fact that at every point // in time it was present somewhere int the map. This becomes increasingly unlikely as // CONTAINS_VALUE_RETRIES increases, though without locking it is theoretically possible. long now = ticker.read(); final Segment<K, V>[] segments = this.segments; long last = -1L; for (int i = 0; i < CONTAINS_VALUE_RETRIES; i++) { long sum = 0L; for (Segment<K, V> segment : segments) { // ensure visibility of most recent completed write int unused = segment.count; // read-volatile AtomicReferenceArray<ReferenceEntry<K, V>> table = segment.table; for (int j = 0; j < table.length(); j++) { for (ReferenceEntry<K, V> e = table.get(j); e != null; e = e.getNext()) { V v = segment.getLiveValue(e, now); if (v != null && valueEquivalence.equivalent(value, v)) { return true; } } } sum += segment.modCount; } if (sum == last) { break; } last = sum; } return false; } @CheckForNull @CanIgnoreReturnValue @Override public V put(K key, V value) { checkNotNull(key); checkNotNull(value); int hash = hash(key); return segmentFor(hash).put(key, hash, value, false); } @CheckForNull @Override public V putIfAbsent(K key, V value) { checkNotNull(key); checkNotNull(value); int hash = hash(key); return segmentFor(hash).put(key, hash, value, true); } @Override @CheckForNull public V compute( K key, BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> function) { checkNotNull(key); checkNotNull(function); int hash = hash(key); return segmentFor(hash).compute(key, hash, function); } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> function) { checkNotNull(key); checkNotNull(function); return compute(key, (k, oldValue) -> (oldValue == null) ? function.apply(key) : oldValue); } @Override @CheckForNull public V computeIfPresent( K key, BiFunction<? super K, ? super V, ? extends @Nullable V> function) { checkNotNull(key); checkNotNull(function); return compute(key, (k, oldValue) -> (oldValue == null) ? null : function.apply(k, oldValue)); } @Override @CheckForNull public V merge( K key, V newValue, BiFunction<? super V, ? super V, ? extends @Nullable V> function) { checkNotNull(key); checkNotNull(newValue); checkNotNull(function); return compute( key, (k, oldValue) -> (oldValue == null) ? newValue : function.apply(oldValue, newValue)); } @Override public void putAll(Map<? extends K, ? extends V> m) { for (Entry<? extends K, ? extends V> e : m.entrySet()) { put(e.getKey(), e.getValue()); } } @CheckForNull @CanIgnoreReturnValue @Override public V remove(@CheckForNull Object key) { if (key == null) { return null; } int hash = hash(key); return segmentFor(hash).remove(key, hash); } @CanIgnoreReturnValue @Override public boolean remove(@CheckForNull Object key, @CheckForNull Object value) { if (key == null || value == null) { return false; } int hash = hash(key); return segmentFor(hash).remove(key, hash, value); } @CanIgnoreReturnValue @Override public boolean replace(K key, @CheckForNull V oldValue, V newValue) { checkNotNull(key); checkNotNull(newValue); if (oldValue == null) { return false; } int hash = hash(key); return segmentFor(hash).replace(key, hash, oldValue, newValue); } @CheckForNull @CanIgnoreReturnValue @Override public V replace(K key, V value) { checkNotNull(key); checkNotNull(value); int hash = hash(key); return segmentFor(hash).replace(key, hash, value); } @Override public void clear() { for (Segment<K, V> segment : segments) { segment.clear(); } } void invalidateAll(Iterable<?> keys) { // TODO(fry): batch by segment for (Object key : keys) { remove(key); } } @LazyInit @RetainedWith @CheckForNull Set<K> keySet; @Override public Set<K> keySet() { // does not impact recency ordering Set<K> ks = keySet; return (ks != null) ? ks : (keySet = new KeySet()); } @LazyInit @RetainedWith @CheckForNull Collection<V> values; @Override public Collection<V> values() { // does not impact recency ordering Collection<V> vs = values; return (vs != null) ? vs : (values = new Values()); } @LazyInit @RetainedWith @CheckForNull Set<Entry<K, V>> entrySet; @Override @GwtIncompatible // Not supported. public Set<Entry<K, V>> entrySet() { // does not impact recency ordering Set<Entry<K, V>> es = entrySet; return (es != null) ? es : (entrySet = new EntrySet()); } // Iterator Support abstract class HashIterator<T> implements Iterator<T> { int nextSegmentIndex; int nextTableIndex; @CheckForNull Segment<K, V> currentSegment; @CheckForNull AtomicReferenceArray<ReferenceEntry<K, V>> currentTable; @CheckForNull ReferenceEntry<K, V> nextEntry; @CheckForNull WriteThroughEntry nextExternal; @CheckForNull WriteThroughEntry lastReturned; HashIterator() { nextSegmentIndex = segments.length - 1; nextTableIndex = -1; advance(); } @Override public abstract T next(); final void advance() { nextExternal = null; if (nextInChain()) { return; } if (nextInTable()) { return; } while (nextSegmentIndex >= 0) { currentSegment = segments[nextSegmentIndex--]; if (currentSegment.count != 0) { currentTable = currentSegment.table; nextTableIndex = currentTable.length() - 1; if (nextInTable()) { return; } } } } /** Finds the next entry in the current chain. Returns true if an entry was found. */ boolean nextInChain() { if (nextEntry != null) { for (nextEntry = nextEntry.getNext(); nextEntry != null; nextEntry = nextEntry.getNext()) { if (advanceTo(nextEntry)) { return true; } } } return false; } /** Finds the next entry in the current table. Returns true if an entry was found. */ boolean nextInTable() { while (nextTableIndex >= 0) { if ((nextEntry = currentTable.get(nextTableIndex--)) != null) { if (advanceTo(nextEntry) || nextInChain()) { return true; } } } return false; } /** * Advances to the given entry. Returns true if the entry was valid, false if it should be * skipped. */ boolean advanceTo(ReferenceEntry<K, V> entry) { try { long now = ticker.read(); K key = entry.getKey(); V value = getLiveValue(entry, now); if (value != null) { nextExternal = new WriteThroughEntry(key, value); return true; } else { // Skip stale entry. return false; } } finally { currentSegment.postReadCleanup(); } } @Override public boolean hasNext() { return nextExternal != null; } WriteThroughEntry nextEntry() { if (nextExternal == null) { throw new NoSuchElementException(); } lastReturned = nextExternal; advance(); return lastReturned; } @Override public void remove() { checkState(lastReturned != null); LocalCache.this.remove(lastReturned.getKey()); lastReturned = null; } } final class KeyIterator extends HashIterator<K> { @Override public K next() { return nextEntry().getKey(); } } final class ValueIterator extends HashIterator<V> { @Override public V next() { return nextEntry().getValue(); } } /** * Custom Entry class used by EntryIterator.next(), that relays setValue changes to the underlying * map. */ final class WriteThroughEntry implements Entry<K, V> { final K key; // non-null V value; // non-null WriteThroughEntry(K key, V value) { this.key = key; this.value = value; } @Override public K getKey() { return key; } @Override public V getValue() { return value; } @Override public boolean equals(@CheckForNull Object object) { // Cannot use key and value equivalence if (object instanceof Entry) { Entry<?, ?> that = (Entry<?, ?>) object; return key.equals(that.getKey()) && value.equals(that.getValue()); } return false; } @Override public int hashCode() { // Cannot use key and value equivalence return key.hashCode() ^ value.hashCode(); } @Override public V setValue(V newValue) { V oldValue = put(key, newValue); value = newValue; // only if put succeeds return oldValue; } @Override public String toString() { return getKey() + "=" + getValue(); } } final class EntryIterator extends HashIterator<Entry<K, V>> { @Override public Entry<K, V> next() { return nextEntry(); } } abstract class AbstractCacheSet<T> extends AbstractSet<T> { @Override public int size() { return LocalCache.this.size(); } @Override public boolean isEmpty() { return LocalCache.this.isEmpty(); } @Override public void clear() { LocalCache.this.clear(); } } boolean removeIf(BiPredicate<? super K, ? super V> filter) { checkNotNull(filter); boolean changed = false; for (K key : keySet()) { while (true) { V value = get(key); if (value == null || !filter.test(key, value)) { break; } else if (LocalCache.this.remove(key, value)) { changed = true; break; } } } return changed; } final class KeySet extends AbstractCacheSet<K> { @Override public Iterator<K> iterator() { return new KeyIterator(); } @Override public boolean contains(Object o) { return LocalCache.this.containsKey(o); } @Override public boolean remove(Object o) { return LocalCache.this.remove(o) != null; } } final class Values extends AbstractCollection<V> { @Override public int size() { return LocalCache.this.size(); } @Override public boolean isEmpty() { return LocalCache.this.isEmpty(); } @Override public void clear() { LocalCache.this.clear(); } @Override public Iterator<V> iterator() { return new ValueIterator(); } @Override public boolean removeIf(Predicate<? super V> filter) { checkNotNull(filter); return LocalCache.this.removeIf((k, v) -> filter.test(v)); } @Override public boolean contains(Object o) { return LocalCache.this.containsValue(o); } } final class EntrySet extends AbstractCacheSet<Entry<K, V>> { @Override public Iterator<Entry<K, V>> iterator() { return new EntryIterator(); } @Override public boolean removeIf(Predicate<? super Entry<K, V>> filter) { checkNotNull(filter); return LocalCache.this.removeIf((k, v) -> filter.test(Maps.immutableEntry(k, v))); } @Override public boolean contains(Object o) { if (!(o instanceof Entry)) { return false; } Entry<?, ?> e = (Entry<?, ?>) o; Object key = e.getKey(); if (key == null) { return false; } V v = LocalCache.this.get(key); return v != null && valueEquivalence.equivalent(e.getValue(), v); } @Override public boolean remove(Object o) { if (!(o instanceof Entry)) { return false; } Entry<?, ?> e = (Entry<?, ?>) o; Object key = e.getKey(); return key != null && LocalCache.this.remove(key, e.getValue()); } } // Serialization Support /** * Serializes the configuration of a LocalCache, reconstituting it as a Cache using CacheBuilder * upon deserialization. An instance of this class is fit for use by the writeReplace of * LocalManualCache. * * <p>Unfortunately, readResolve() doesn't get called when a circular dependency is present, so * the proxy must be able to behave as the cache itself. */ static class ManualSerializationProxy<K, V> extends ForwardingCache<K, V> implements Serializable { private static final long serialVersionUID = 1; final Strength keyStrength; final Strength valueStrength; final Equivalence<Object> keyEquivalence; final Equivalence<Object> valueEquivalence; final long expireAfterWriteNanos; final long expireAfterAccessNanos; final long maxWeight; final Weigher<K, V> weigher; final int concurrencyLevel; final RemovalListener<? super K, ? super V> removalListener; @CheckForNull final Ticker ticker; final CacheLoader<? super K, V> loader; @CheckForNull transient Cache<K, V> delegate; ManualSerializationProxy(LocalCache<K, V> cache) { this( cache.keyStrength, cache.valueStrength, cache.keyEquivalence, cache.valueEquivalence, cache.expireAfterWriteNanos, cache.expireAfterAccessNanos, cache.maxWeight, cache.weigher, cache.concurrencyLevel, cache.removalListener, cache.ticker, cache.defaultLoader); } private ManualSerializationProxy( Strength keyStrength, Strength valueStrength, Equivalence<Object> keyEquivalence, Equivalence<Object> valueEquivalence, long expireAfterWriteNanos, long expireAfterAccessNanos, long maxWeight, Weigher<K, V> weigher, int concurrencyLevel, RemovalListener<? super K, ? super V> removalListener, Ticker ticker, CacheLoader<? super K, V> loader) { this.keyStrength = keyStrength; this.valueStrength = valueStrength; this.keyEquivalence = keyEquivalence; this.valueEquivalence = valueEquivalence; this.expireAfterWriteNanos = expireAfterWriteNanos; this.expireAfterAccessNanos = expireAfterAccessNanos; this.maxWeight = maxWeight; this.weigher = weigher; this.concurrencyLevel = concurrencyLevel; this.removalListener = removalListener; this.ticker = (ticker == Ticker.systemTicker() || ticker == NULL_TICKER) ? null : ticker; this.loader = loader; } CacheBuilder<K, V> recreateCacheBuilder() { CacheBuilder<K, V> builder = CacheBuilder.newBuilder() .setKeyStrength(keyStrength) .setValueStrength(valueStrength) .keyEquivalence(keyEquivalence) .valueEquivalence(valueEquivalence) .concurrencyLevel(concurrencyLevel) .removalListener(removalListener); builder.strictParsing = false; if (expireAfterWriteNanos > 0) { builder.expireAfterWrite(expireAfterWriteNanos, TimeUnit.NANOSECONDS); } if (expireAfterAccessNanos > 0) { builder.expireAfterAccess(expireAfterAccessNanos, TimeUnit.NANOSECONDS); } if (weigher != OneWeigher.INSTANCE) { Object unused = builder.weigher(weigher); if (maxWeight != UNSET_INT) { builder.maximumWeight(maxWeight); } } else { if (maxWeight != UNSET_INT) { builder.maximumSize(maxWeight); } } if (ticker != null) { builder.ticker(ticker); } return builder; } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); CacheBuilder<K, V> builder = recreateCacheBuilder(); this.delegate = builder.build(); } private Object readResolve() { return delegate; } @Override protected Cache<K, V> delegate() { return delegate; } } /** * Serializes the configuration of a LocalCache, reconstituting it as an LoadingCache using * CacheBuilder upon deserialization. An instance of this class is fit for use by the writeReplace * of LocalLoadingCache. * * <p>Unfortunately, readResolve() doesn't get called when a circular dependency is present, so * the proxy must be able to behave as the cache itself. */ static final class LoadingSerializationProxy<K, V> extends ManualSerializationProxy<K, V> implements LoadingCache<K, V>, Serializable { private static final long serialVersionUID = 1; @CheckForNull transient LoadingCache<K, V> autoDelegate; LoadingSerializationProxy(LocalCache<K, V> cache) { super(cache); } private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); CacheBuilder<K, V> builder = recreateCacheBuilder(); this.autoDelegate = builder.build(loader); } @Override public V get(K key) throws ExecutionException { return autoDelegate.get(key); } @Override public V getUnchecked(K key) { return autoDelegate.getUnchecked(key); } @Override public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException { return autoDelegate.getAll(keys); } @Override public V apply(K key) { return autoDelegate.apply(key); } @Override public void refresh(K key) { autoDelegate.refresh(key); } private Object readResolve() { return autoDelegate; } } static class LocalManualCache<K, V> implements Cache<K, V>, Serializable { final LocalCache<K, V> localCache; LocalManualCache(CacheBuilder<? super K, ? super V> builder) { this(new LocalCache<>(builder, null)); } private LocalManualCache(LocalCache<K, V> localCache) { this.localCache = localCache; } // Cache methods @Override @CheckForNull public V getIfPresent(Object key) { return localCache.getIfPresent(key); } @Override public V get(K key, final Callable<? extends V> valueLoader) throws ExecutionException { checkNotNull(valueLoader); return localCache.get( key, new CacheLoader<Object, V>() { @Override public V load(Object key) throws Exception { return valueLoader.call(); } }); } @Override public ImmutableMap<K, V> getAllPresent(Iterable<?> keys) { return localCache.getAllPresent(keys); } @Override public void put(K key, V value) { localCache.put(key, value); } @Override public void putAll(Map<? extends K, ? extends V> m) { localCache.putAll(m); } @Override public void invalidate(Object key) { checkNotNull(key); localCache.remove(key); } @Override public void invalidateAll(Iterable<?> keys) { localCache.invalidateAll(keys); } @Override public void invalidateAll() { localCache.clear(); } @Override public long size() { return localCache.longSize(); } @Override public ConcurrentMap<K, V> asMap() { return localCache; } @Override public CacheStats stats() { SimpleStatsCounter aggregator = new SimpleStatsCounter(); aggregator.incrementBy(localCache.globalStatsCounter); for (Segment<K, V> segment : localCache.segments) { aggregator.incrementBy(segment.statsCounter); } return aggregator.snapshot(); } @Override public void cleanUp() { localCache.cleanUp(); } // Serialization Support private static final long serialVersionUID = 1; Object writeReplace() { return new ManualSerializationProxy<>(localCache); } private void readObject(ObjectInputStream in) throws InvalidObjectException { throw new InvalidObjectException("Use ManualSerializationProxy"); } } static class LocalLoadingCache<K, V> extends LocalManualCache<K, V> implements LoadingCache<K, V> { LocalLoadingCache( CacheBuilder<? super K, ? super V> builder, CacheLoader<? super K, V> loader) { super(new LocalCache<>(builder, checkNotNull(loader))); } // LoadingCache methods @Override public V get(K key) throws ExecutionException { return localCache.getOrLoad(key); } @CanIgnoreReturnValue // TODO(b/27479612): consider removing this @Override public V getUnchecked(K key) { try { return get(key); } catch (ExecutionException e) { throw new UncheckedExecutionException(e.getCause()); } } @Override public ImmutableMap<K, V> getAll(Iterable<? extends K> keys) throws ExecutionException { return localCache.getAll(keys); } @Override public void refresh(K key) { localCache.refresh(key); } @Override public final V apply(K key) { return getUnchecked(key); } // Serialization Support private static final long serialVersionUID = 1; @Override Object writeReplace() { return new LoadingSerializationProxy<>(localCache); } private void readObject(ObjectInputStream in) throws InvalidObjectException { throw new InvalidObjectException("Use LoadingSerializationProxy"); } } }
google/guava
guava/src/com/google/common/cache/LocalCache.java
367
/* * Copyright (C) 2015 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 static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT; import static java.lang.Math.min; import static java.util.Objects.requireNonNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.math.LongMath; import com.google.errorprone.annotations.InlineMe; import com.google.errorprone.annotations.InlineMeValidationDisabled; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.OptionalDouble; import java.util.OptionalInt; import java.util.OptionalLong; import java.util.PrimitiveIterator; import java.util.Spliterator; import java.util.Spliterators; import java.util.Spliterators.AbstractSpliterator; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.DoubleConsumer; import java.util.function.IntConsumer; import java.util.function.LongConsumer; import java.util.stream.BaseStream; import java.util.stream.DoubleStream; import java.util.stream.IntStream; import java.util.stream.LongStream; import java.util.stream.Stream; import java.util.stream.StreamSupport; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods related to {@code Stream} instances. * * @since 21.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Streams { /** * Returns a sequential {@link Stream} of the contents of {@code iterable}, delegating to {@link * Collection#stream} if possible. */ public static <T extends @Nullable Object> Stream<T> stream(Iterable<T> iterable) { return (iterable instanceof Collection) ? ((Collection<T>) iterable).stream() : StreamSupport.stream(iterable.spliterator(), false); } /** * Returns {@link Collection#stream}. * * @deprecated There is no reason to use this; just invoke {@code collection.stream()} directly. */ @Deprecated @InlineMe(replacement = "collection.stream()") public static <T extends @Nullable Object> Stream<T> stream(Collection<T> collection) { return collection.stream(); } /** * Returns a sequential {@link Stream} of the remaining contents of {@code iterator}. Do not use * {@code iterator} directly after passing it to this method. */ public static <T extends @Nullable Object> Stream<T> stream(Iterator<T> iterator) { return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false); } /** * If a value is present in {@code optional}, returns a stream containing only that element, * otherwise returns an empty stream. */ public static <T> Stream<T> stream(com.google.common.base.Optional<T> optional) { return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty(); } /** * If a value is present in {@code optional}, returns a stream containing only that element, * otherwise returns an empty stream. * * <p><b>Java 9 users:</b> use {@code optional.stream()} instead. */ @Beta @InlineMe(replacement = "optional.stream()") @InlineMeValidationDisabled("Java 9+ API only") public static <T> Stream<T> stream(java.util.Optional<T> optional) { return optional.isPresent() ? Stream.of(optional.get()) : Stream.empty(); } /** * If a value is present in {@code optional}, returns a stream containing only that element, * otherwise returns an empty stream. * * <p><b>Java 9 users:</b> use {@code optional.stream()} instead. */ @Beta @InlineMe(replacement = "optional.stream()") @InlineMeValidationDisabled("Java 9+ API only") public static IntStream stream(OptionalInt optional) { return optional.isPresent() ? IntStream.of(optional.getAsInt()) : IntStream.empty(); } /** * If a value is present in {@code optional}, returns a stream containing only that element, * otherwise returns an empty stream. * * <p><b>Java 9 users:</b> use {@code optional.stream()} instead. */ @Beta @InlineMe(replacement = "optional.stream()") @InlineMeValidationDisabled("Java 9+ API only") public static LongStream stream(OptionalLong optional) { return optional.isPresent() ? LongStream.of(optional.getAsLong()) : LongStream.empty(); } /** * If a value is present in {@code optional}, returns a stream containing only that element, * otherwise returns an empty stream. * * <p><b>Java 9 users:</b> use {@code optional.stream()} instead. */ @Beta @InlineMe(replacement = "optional.stream()") @InlineMeValidationDisabled("Java 9+ API only") public static DoubleStream stream(OptionalDouble optional) { return optional.isPresent() ? DoubleStream.of(optional.getAsDouble()) : DoubleStream.empty(); } @SuppressWarnings("CatchingUnchecked") // sneaky checked exception private static void closeAll(BaseStream<?, ?>[] toClose) { // If one of the streams throws an exception, continue closing the others, then throw the // exception later. If more than one stream throws an exception, the later ones are added to the // first as suppressed exceptions. We don't catch Error on the grounds that it should be allowed // to propagate immediately. Exception exception = null; for (BaseStream<?, ?> stream : toClose) { try { stream.close(); } catch (Exception e) { // sneaky checked exception if (exception == null) { exception = e; } else { exception.addSuppressed(e); } } } if (exception != null) { // Normally this is a RuntimeException that doesn't need sneakyThrow. // But theoretically we could see sneaky checked exception sneakyThrow(exception); } } /** Throws an undeclared checked exception. */ private static void sneakyThrow(Throwable t) { class SneakyThrower<T extends Throwable> { @SuppressWarnings("unchecked") // not really safe, but that's the point void throwIt(Throwable t) throws T { throw (T) t; } } new SneakyThrower<Error>().throwIt(t); } /** * Returns a {@link Stream} containing the elements of the first stream, followed by the elements * of the second stream, and so on. * * <p>This is equivalent to {@code Stream.of(streams).flatMap(stream -> stream)}, but the returned * stream may perform better. * * @see Stream#concat(Stream, Stream) */ @SuppressWarnings("unchecked") // could probably be avoided with a forwarding Spliterator @SafeVarargs public static <T extends @Nullable Object> Stream<T> concat(Stream<? extends T>... streams) { // TODO(lowasser): consider an implementation that can support SUBSIZED boolean isParallel = false; int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL; long estimatedSize = 0L; ImmutableList.Builder<Spliterator<? extends T>> splitrsBuilder = new ImmutableList.Builder<>(streams.length); for (Stream<? extends T> stream : streams) { isParallel |= stream.isParallel(); Spliterator<? extends T> splitr = stream.spliterator(); splitrsBuilder.add(splitr); characteristics &= splitr.characteristics(); estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize()); } return StreamSupport.stream( CollectSpliterators.flatMap( splitrsBuilder.build().spliterator(), splitr -> (Spliterator<T>) splitr, characteristics, estimatedSize), isParallel) .onClose(() -> closeAll(streams)); } /** * Returns an {@link IntStream} containing the elements of the first stream, followed by the * elements of the second stream, and so on. * * <p>This is equivalent to {@code Stream.of(streams).flatMapToInt(stream -> stream)}, but the * returned stream may perform better. * * @see IntStream#concat(IntStream, IntStream) */ public static IntStream concat(IntStream... streams) { boolean isParallel = false; int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL; long estimatedSize = 0L; ImmutableList.Builder<Spliterator.OfInt> splitrsBuilder = new ImmutableList.Builder<>(streams.length); for (IntStream stream : streams) { isParallel |= stream.isParallel(); Spliterator.OfInt splitr = stream.spliterator(); splitrsBuilder.add(splitr); characteristics &= splitr.characteristics(); estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize()); } return StreamSupport.intStream( CollectSpliterators.flatMapToInt( splitrsBuilder.build().spliterator(), splitr -> splitr, characteristics, estimatedSize), isParallel) .onClose(() -> closeAll(streams)); } /** * Returns a {@link LongStream} containing the elements of the first stream, followed by the * elements of the second stream, and so on. * * <p>This is equivalent to {@code Stream.of(streams).flatMapToLong(stream -> stream)}, but the * returned stream may perform better. * * @see LongStream#concat(LongStream, LongStream) */ public static LongStream concat(LongStream... streams) { boolean isParallel = false; int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL; long estimatedSize = 0L; ImmutableList.Builder<Spliterator.OfLong> splitrsBuilder = new ImmutableList.Builder<>(streams.length); for (LongStream stream : streams) { isParallel |= stream.isParallel(); Spliterator.OfLong splitr = stream.spliterator(); splitrsBuilder.add(splitr); characteristics &= splitr.characteristics(); estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize()); } return StreamSupport.longStream( CollectSpliterators.flatMapToLong( splitrsBuilder.build().spliterator(), splitr -> splitr, characteristics, estimatedSize), isParallel) .onClose(() -> closeAll(streams)); } /** * Returns a {@link DoubleStream} containing the elements of the first stream, followed by the * elements of the second stream, and so on. * * <p>This is equivalent to {@code Stream.of(streams).flatMapToDouble(stream -> stream)}, but the * returned stream may perform better. * * @see DoubleStream#concat(DoubleStream, DoubleStream) */ public static DoubleStream concat(DoubleStream... streams) { boolean isParallel = false; int characteristics = Spliterator.ORDERED | Spliterator.SIZED | Spliterator.NONNULL; long estimatedSize = 0L; ImmutableList.Builder<Spliterator.OfDouble> splitrsBuilder = new ImmutableList.Builder<>(streams.length); for (DoubleStream stream : streams) { isParallel |= stream.isParallel(); Spliterator.OfDouble splitr = stream.spliterator(); splitrsBuilder.add(splitr); characteristics &= splitr.characteristics(); estimatedSize = LongMath.saturatedAdd(estimatedSize, splitr.estimateSize()); } return StreamSupport.doubleStream( CollectSpliterators.flatMapToDouble( splitrsBuilder.build().spliterator(), splitr -> splitr, characteristics, estimatedSize), isParallel) .onClose(() -> closeAll(streams)); } /** * Returns a stream in which each element is the result of passing the corresponding element of * each of {@code streamA} and {@code streamB} to {@code function}. * * <p>For example: * * <pre>{@code * Streams.zip( * Stream.of("foo1", "foo2", "foo3"), * Stream.of("bar1", "bar2"), * (arg1, arg2) -> arg1 + ":" + arg2) * }</pre> * * <p>will return {@code Stream.of("foo1:bar1", "foo2:bar2")}. * * <p>The resulting stream will only be as long as the shorter of the two input streams; if one * stream is longer, its extra elements will be ignored. * * <p>Note that if you are calling {@link Stream#forEach} on the resulting stream, you might want * to consider using {@link #forEachPair} instead of this method. * * <p><b>Performance note:</b> The resulting stream is not <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a>. * This may harm parallel performance. */ @Beta public static <A extends @Nullable Object, B extends @Nullable Object, R extends @Nullable Object> Stream<R> zip( Stream<A> streamA, Stream<B> streamB, BiFunction<? super A, ? super B, R> function) { checkNotNull(streamA); checkNotNull(streamB); checkNotNull(function); boolean isParallel = streamA.isParallel() || streamB.isParallel(); // same as Stream.concat Spliterator<A> splitrA = streamA.spliterator(); Spliterator<B> splitrB = streamB.spliterator(); int characteristics = splitrA.characteristics() & splitrB.characteristics() & (Spliterator.SIZED | Spliterator.ORDERED); Iterator<A> itrA = Spliterators.iterator(splitrA); Iterator<B> itrB = Spliterators.iterator(splitrB); return StreamSupport.stream( new AbstractSpliterator<R>( min(splitrA.estimateSize(), splitrB.estimateSize()), characteristics) { @Override public boolean tryAdvance(Consumer<? super R> action) { if (itrA.hasNext() && itrB.hasNext()) { action.accept(function.apply(itrA.next(), itrB.next())); return true; } return false; } }, isParallel) .onClose(streamA::close) .onClose(streamB::close); } /** * Invokes {@code consumer} once for each pair of <i>corresponding</i> elements in {@code streamA} * and {@code streamB}. If one stream is longer than the other, the extra elements are silently * ignored. Elements passed to the consumer are guaranteed to come from the same position in their * respective source streams. For example: * * <pre>{@code * Streams.forEachPair( * Stream.of("foo1", "foo2", "foo3"), * Stream.of("bar1", "bar2"), * (arg1, arg2) -> System.out.println(arg1 + ":" + arg2) * }</pre> * * <p>will print: * * <pre>{@code * foo1:bar1 * foo2:bar2 * }</pre> * * <p><b>Warning:</b> If either supplied stream is a parallel stream, the same correspondence * between elements will be made, but the order in which those pairs of elements are passed to the * consumer is <i>not</i> defined. * * <p>Note that many usages of this method can be replaced with simpler calls to {@link #zip}. * This method behaves equivalently to {@linkplain #zip zipping} the stream elements into * temporary pair objects and then using {@link Stream#forEach} on that stream. * * @since 22.0 */ @Beta public static <A extends @Nullable Object, B extends @Nullable Object> void forEachPair( Stream<A> streamA, Stream<B> streamB, BiConsumer<? super A, ? super B> consumer) { checkNotNull(consumer); if (streamA.isParallel() || streamB.isParallel()) { zip(streamA, streamB, TemporaryPair::new).forEach(pair -> consumer.accept(pair.a, pair.b)); } else { Iterator<A> iterA = streamA.iterator(); Iterator<B> iterB = streamB.iterator(); while (iterA.hasNext() && iterB.hasNext()) { consumer.accept(iterA.next(), iterB.next()); } } } // Use this carefully - it doesn't implement value semantics private static class TemporaryPair<A extends @Nullable Object, B extends @Nullable Object> { @ParametricNullness final A a; @ParametricNullness final B b; TemporaryPair(@ParametricNullness A a, @ParametricNullness B b) { this.a = a; this.b = b; } } /** * Returns a stream consisting of the results of applying the given function to the elements of * {@code stream} and their indices in the stream. For example, * * <pre>{@code * mapWithIndex( * Stream.of("a", "b", "c"), * (e, index) -> index + ":" + e) * }</pre> * * <p>would return {@code Stream.of("0:a", "1:b", "2:c")}. * * <p>The resulting stream is <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * if and only if {@code stream} was efficiently splittable and its underlying spliterator * reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream * comes from a data structure supporting efficient indexed random access, typically an array or * list. * * <p>The order of the resulting stream is defined if and only if the order of the original stream * was defined. */ public static <T extends @Nullable Object, R extends @Nullable Object> Stream<R> mapWithIndex( Stream<T> stream, FunctionWithIndex<? super T, ? extends R> function) { checkNotNull(stream); checkNotNull(function); boolean isParallel = stream.isParallel(); Spliterator<T> fromSpliterator = stream.spliterator(); if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) { Iterator<T> fromIterator = Spliterators.iterator(fromSpliterator); return StreamSupport.stream( new AbstractSpliterator<R>( fromSpliterator.estimateSize(), fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) { long index = 0; @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromIterator.hasNext()) { action.accept(function.apply(fromIterator.next(), index++)); return true; } return false; } }, isParallel) .onClose(stream::close); } class Splitr extends MapWithIndexSpliterator<Spliterator<T>, R, Splitr> implements Consumer<T> { @CheckForNull T holder; Splitr(Spliterator<T> splitr, long index) { super(splitr, index); } @Override public void accept(@ParametricNullness T t) { this.holder = t; } @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromSpliterator.tryAdvance(this)) { try { // The cast is safe because tryAdvance puts a T into `holder`. action.accept(function.apply(uncheckedCastNullableTToT(holder), index++)); return true; } finally { holder = null; } } return false; } @Override Splitr createSplit(Spliterator<T> from, long i) { return new Splitr(from, i); } } return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close); } /** * Returns a stream consisting of the results of applying the given function to the elements of * {@code stream} and their indexes in the stream. For example, * * <pre>{@code * mapWithIndex( * IntStream.of(10, 11, 12), * (e, index) -> index + ":" + e) * }</pre> * * <p>...would return {@code Stream.of("0:10", "1:11", "2:12")}. * * <p>The resulting stream is <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * if and only if {@code stream} was efficiently splittable and its underlying spliterator * reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream * comes from a data structure supporting efficient indexed random access, typically an array or * list. * * <p>The order of the resulting stream is defined if and only if the order of the original stream * was defined. */ public static <R extends @Nullable Object> Stream<R> mapWithIndex( IntStream stream, IntFunctionWithIndex<R> function) { checkNotNull(stream); checkNotNull(function); boolean isParallel = stream.isParallel(); Spliterator.OfInt fromSpliterator = stream.spliterator(); if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) { PrimitiveIterator.OfInt fromIterator = Spliterators.iterator(fromSpliterator); return StreamSupport.stream( new AbstractSpliterator<R>( fromSpliterator.estimateSize(), fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) { long index = 0; @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromIterator.hasNext()) { action.accept(function.apply(fromIterator.nextInt(), index++)); return true; } return false; } }, isParallel) .onClose(stream::close); } class Splitr extends MapWithIndexSpliterator<Spliterator.OfInt, R, Splitr> implements IntConsumer, Spliterator<R> { int holder; Splitr(Spliterator.OfInt splitr, long index) { super(splitr, index); } @Override public void accept(int t) { this.holder = t; } @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromSpliterator.tryAdvance(this)) { action.accept(function.apply(holder, index++)); return true; } return false; } @Override Splitr createSplit(Spliterator.OfInt from, long i) { return new Splitr(from, i); } } return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close); } /** * Returns a stream consisting of the results of applying the given function to the elements of * {@code stream} and their indexes in the stream. For example, * * <pre>{@code * mapWithIndex( * LongStream.of(10, 11, 12), * (e, index) -> index + ":" + e) * }</pre> * * <p>...would return {@code Stream.of("0:10", "1:11", "2:12")}. * * <p>The resulting stream is <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * if and only if {@code stream} was efficiently splittable and its underlying spliterator * reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream * comes from a data structure supporting efficient indexed random access, typically an array or * list. * * <p>The order of the resulting stream is defined if and only if the order of the original stream * was defined. */ public static <R extends @Nullable Object> Stream<R> mapWithIndex( LongStream stream, LongFunctionWithIndex<R> function) { checkNotNull(stream); checkNotNull(function); boolean isParallel = stream.isParallel(); Spliterator.OfLong fromSpliterator = stream.spliterator(); if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) { PrimitiveIterator.OfLong fromIterator = Spliterators.iterator(fromSpliterator); return StreamSupport.stream( new AbstractSpliterator<R>( fromSpliterator.estimateSize(), fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) { long index = 0; @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromIterator.hasNext()) { action.accept(function.apply(fromIterator.nextLong(), index++)); return true; } return false; } }, isParallel) .onClose(stream::close); } class Splitr extends MapWithIndexSpliterator<Spliterator.OfLong, R, Splitr> implements LongConsumer, Spliterator<R> { long holder; Splitr(Spliterator.OfLong splitr, long index) { super(splitr, index); } @Override public void accept(long t) { this.holder = t; } @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromSpliterator.tryAdvance(this)) { action.accept(function.apply(holder, index++)); return true; } return false; } @Override Splitr createSplit(Spliterator.OfLong from, long i) { return new Splitr(from, i); } } return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close); } /** * Returns a stream consisting of the results of applying the given function to the elements of * {@code stream} and their indexes in the stream. For example, * * <pre>{@code * mapWithIndex( * DoubleStream.of(0.0, 1.0, 2.0) * (e, index) -> index + ":" + e) * }</pre> * * <p>...would return {@code Stream.of("0:0.0", "1:1.0", "2:2.0")}. * * <p>The resulting stream is <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * if and only if {@code stream} was efficiently splittable and its underlying spliterator * reported {@link Spliterator#SUBSIZED}. This is generally the case if the underlying stream * comes from a data structure supporting efficient indexed random access, typically an array or * list. * * <p>The order of the resulting stream is defined if and only if the order of the original stream * was defined. */ public static <R extends @Nullable Object> Stream<R> mapWithIndex( DoubleStream stream, DoubleFunctionWithIndex<R> function) { checkNotNull(stream); checkNotNull(function); boolean isParallel = stream.isParallel(); Spliterator.OfDouble fromSpliterator = stream.spliterator(); if (!fromSpliterator.hasCharacteristics(Spliterator.SUBSIZED)) { PrimitiveIterator.OfDouble fromIterator = Spliterators.iterator(fromSpliterator); return StreamSupport.stream( new AbstractSpliterator<R>( fromSpliterator.estimateSize(), fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED)) { long index = 0; @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromIterator.hasNext()) { action.accept(function.apply(fromIterator.nextDouble(), index++)); return true; } return false; } }, isParallel) .onClose(stream::close); } class Splitr extends MapWithIndexSpliterator<Spliterator.OfDouble, R, Splitr> implements DoubleConsumer, Spliterator<R> { double holder; Splitr(Spliterator.OfDouble splitr, long index) { super(splitr, index); } @Override public void accept(double t) { this.holder = t; } @Override public boolean tryAdvance(Consumer<? super R> action) { if (fromSpliterator.tryAdvance(this)) { action.accept(function.apply(holder, index++)); return true; } return false; } @Override Splitr createSplit(Spliterator.OfDouble from, long i) { return new Splitr(from, i); } } return StreamSupport.stream(new Splitr(fromSpliterator, 0), isParallel).onClose(stream::close); } /** * An analogue of {@link java.util.function.Function} also accepting an index. * * <p>This interface is only intended for use by callers of {@link #mapWithIndex(Stream, * FunctionWithIndex)}. * * @since 21.0 */ public interface FunctionWithIndex<T extends @Nullable Object, R extends @Nullable Object> { /** Applies this function to the given argument and its index within a stream. */ @ParametricNullness R apply(@ParametricNullness T from, long index); } private abstract static class MapWithIndexSpliterator< F extends Spliterator<?>, R extends @Nullable Object, S extends MapWithIndexSpliterator<F, R, S>> implements Spliterator<R> { final F fromSpliterator; long index; MapWithIndexSpliterator(F fromSpliterator, long index) { this.fromSpliterator = fromSpliterator; this.index = index; } abstract S createSplit(F from, long i); @Override @CheckForNull public S trySplit() { Spliterator<?> splitOrNull = fromSpliterator.trySplit(); if (splitOrNull == null) { return null; } @SuppressWarnings("unchecked") F split = (F) splitOrNull; S result = createSplit(split, index); this.index += split.getExactSizeIfKnown(); return result; } @Override public long estimateSize() { return fromSpliterator.estimateSize(); } @Override public int characteristics() { return fromSpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.SIZED | Spliterator.SUBSIZED); } } /** * An analogue of {@link java.util.function.IntFunction} also accepting an index. * * <p>This interface is only intended for use by callers of {@link #mapWithIndex(IntStream, * IntFunctionWithIndex)}. * * @since 21.0 */ public interface IntFunctionWithIndex<R extends @Nullable Object> { /** Applies this function to the given argument and its index within a stream. */ @ParametricNullness R apply(int from, long index); } /** * An analogue of {@link java.util.function.LongFunction} also accepting an index. * * <p>This interface is only intended for use by callers of {@link #mapWithIndex(LongStream, * LongFunctionWithIndex)}. * * @since 21.0 */ public interface LongFunctionWithIndex<R extends @Nullable Object> { /** Applies this function to the given argument and its index within a stream. */ @ParametricNullness R apply(long from, long index); } /** * An analogue of {@link java.util.function.DoubleFunction} also accepting an index. * * <p>This interface is only intended for use by callers of {@link #mapWithIndex(DoubleStream, * DoubleFunctionWithIndex)}. * * @since 21.0 */ public interface DoubleFunctionWithIndex<R extends @Nullable Object> { /** Applies this function to the given argument and its index within a stream. */ @ParametricNullness R apply(double from, long index); } /** * Returns the last element of the specified stream, or {@link java.util.Optional#empty} if the * stream is empty. * * <p>Equivalent to {@code stream.reduce((a, b) -> b)}, but may perform significantly better. This * method's runtime will be between O(log n) and O(n), performing better on <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * streams. * * <p>If the stream has nondeterministic order, this has equivalent semantics to {@link * Stream#findAny} (which you might as well use). * * @see Stream#findFirst() * @throws NullPointerException if the last element of the stream is null */ /* * By declaring <T> instead of <T extends @Nullable Object>, we declare this method as requiring a * stream whose elements are non-null. However, the method goes out of its way to still handle * nulls in the stream. This means that the method can safely be used with a stream that contains * nulls as long as the *last* element is *not* null. * * (To "go out of its way," the method tracks a `set` bit so that it can distinguish "the final * split has a last element of null, so throw NPE" from "the final split was empty, so look for an * element in the prior one.") */ public static <T> java.util.Optional<T> findLast(Stream<T> stream) { class OptionalState { boolean set = false; @CheckForNull T value = null; void set(T value) { this.set = true; this.value = value; } T get() { /* * requireNonNull is safe because we call get() only if we've previously called set(). * * (For further discussion of nullness, see the comment above the method.) */ return requireNonNull(value); } } OptionalState state = new OptionalState(); Deque<Spliterator<T>> splits = new ArrayDeque<>(); splits.addLast(stream.spliterator()); while (!splits.isEmpty()) { Spliterator<T> spliterator = splits.removeLast(); if (spliterator.getExactSizeIfKnown() == 0) { continue; // drop this split } // Many spliterators will have trySplits that are SUBSIZED even if they are not themselves // SUBSIZED. if (spliterator.hasCharacteristics(Spliterator.SUBSIZED)) { // we can drill down to exactly the smallest nonempty spliterator while (true) { Spliterator<T> prefix = spliterator.trySplit(); if (prefix == null || prefix.getExactSizeIfKnown() == 0) { break; } else if (spliterator.getExactSizeIfKnown() == 0) { spliterator = prefix; break; } } // spliterator is known to be nonempty now spliterator.forEachRemaining(state::set); return java.util.Optional.of(state.get()); } Spliterator<T> prefix = spliterator.trySplit(); if (prefix == null || prefix.getExactSizeIfKnown() == 0) { // we can't split this any further spliterator.forEachRemaining(state::set); if (state.set) { return java.util.Optional.of(state.get()); } // fall back to the last split continue; } splits.addLast(prefix); splits.addLast(spliterator); } return java.util.Optional.empty(); } /** * Returns the last element of the specified stream, or {@link OptionalInt#empty} if the stream is * empty. * * <p>Equivalent to {@code stream.reduce((a, b) -> b)}, but may perform significantly better. This * method's runtime will be between O(log n) and O(n), performing better on <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * streams. * * @see IntStream#findFirst() * @throws NullPointerException if the last element of the stream is null */ public static OptionalInt findLast(IntStream stream) { // findLast(Stream) does some allocation, so we might as well box some more java.util.Optional<Integer> boxedLast = findLast(stream.boxed()); return boxedLast.map(OptionalInt::of).orElse(OptionalInt.empty()); } /** * Returns the last element of the specified stream, or {@link OptionalLong#empty} if the stream * is empty. * * <p>Equivalent to {@code stream.reduce((a, b) -> b)}, but may perform significantly better. This * method's runtime will be between O(log n) and O(n), performing better on <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * streams. * * @see LongStream#findFirst() * @throws NullPointerException if the last element of the stream is null */ public static OptionalLong findLast(LongStream stream) { // findLast(Stream) does some allocation, so we might as well box some more java.util.Optional<Long> boxedLast = findLast(stream.boxed()); return boxedLast.map(OptionalLong::of).orElse(OptionalLong.empty()); } /** * Returns the last element of the specified stream, or {@link OptionalDouble#empty} if the stream * is empty. * * <p>Equivalent to {@code stream.reduce((a, b) -> b)}, but may perform significantly better. This * method's runtime will be between O(log n) and O(n), performing better on <a * href="http://gee.cs.oswego.edu/dl/html/StreamParallelGuidance.html">efficiently splittable</a> * streams. * * @see DoubleStream#findFirst() * @throws NullPointerException if the last element of the stream is null */ public static OptionalDouble findLast(DoubleStream stream) { // findLast(Stream) does some allocation, so we might as well box some more java.util.Optional<Double> boxedLast = findLast(stream.boxed()); return boxedLast.map(OptionalDouble::of).orElse(OptionalDouble.empty()); } private Streams() {} }
google/guava
guava/src/com/google/common/collect/Streams.java
368
/* * 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 static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.j2objc.annotations.RetainedWith; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Collection; import java.util.Comparator; import java.util.Deque; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import java.util.Map; import java.util.NavigableMap; import java.util.NavigableSet; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.Spliterator; import java.util.function.BiConsumer; import java.util.function.BiFunction; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Predicate; import java.util.function.UnaryOperator; import java.util.stream.Stream; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Synchronized collection views. The returned synchronized collection views are serializable if the * backing collection and the mutex are serializable. * * <p>If {@code null} is passed as the {@code mutex} parameter to any of this class's top-level * methods or inner class constructors, the created object uses itself as the synchronization mutex. * * <p>This class should be used by other collection classes only. * * @author Mike Bostock * @author Jared Levy */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault /* * I have decided not to bother adding @ParametricNullness annotations in this class. Adding them is * a lot of busy work, and the annotation matters only when the APIs to be annotated are visible to * Kotlin code. In this class, nothing is publicly visible (nor exposed indirectly through a * publicly visible subclass), and I doubt any of our current or future Kotlin extensions for the * package will refer to the class. Plus, @ParametricNullness is only a temporary workaround, * anyway, so we just need to get by without the annotations here until Kotlin better understands * our other nullness annotations. */ final class Synchronized { private Synchronized() {} static class SynchronizedObject implements Serializable { final Object delegate; final Object mutex; SynchronizedObject(Object delegate, @CheckForNull Object mutex) { this.delegate = checkNotNull(delegate); this.mutex = (mutex == null) ? this : mutex; } Object delegate() { return delegate; } // No equals and hashCode; see ForwardingObject for details. @Override public String toString() { synchronized (mutex) { return delegate.toString(); } } // Serialization invokes writeObject only when it's private. // The SynchronizedObject subclasses don't need a writeObject method since // they don't contain any non-transient member variables, while the // following writeObject() handles the SynchronizedObject members. @GwtIncompatible // java.io.ObjectOutputStream @J2ktIncompatible private void writeObject(ObjectOutputStream stream) throws IOException { synchronized (mutex) { stream.defaultWriteObject(); } } @GwtIncompatible // not needed in emulated source @J2ktIncompatible private static final long serialVersionUID = 0; } private static <E extends @Nullable Object> Collection<E> collection( Collection<E> collection, @CheckForNull Object mutex) { return new SynchronizedCollection<>(collection, mutex); } @VisibleForTesting static class SynchronizedCollection<E extends @Nullable Object> extends SynchronizedObject implements Collection<E> { private SynchronizedCollection(Collection<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Collection<E> delegate() { return (Collection<E>) super.delegate(); } @Override public boolean add(E e) { synchronized (mutex) { return delegate().add(e); } } @Override public boolean addAll(Collection<? extends E> c) { synchronized (mutex) { return delegate().addAll(c); } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public boolean contains(@CheckForNull Object o) { synchronized (mutex) { return delegate().contains(o); } } @Override public boolean containsAll(Collection<?> c) { synchronized (mutex) { return delegate().containsAll(c); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public Iterator<E> iterator() { return delegate().iterator(); // manually synchronized } @Override public Spliterator<E> spliterator() { synchronized (mutex) { return delegate().spliterator(); } } @Override public Stream<E> stream() { synchronized (mutex) { return delegate().stream(); } } @Override public Stream<E> parallelStream() { synchronized (mutex) { return delegate().parallelStream(); } } @Override public void forEach(Consumer<? super E> action) { synchronized (mutex) { delegate().forEach(action); } } @Override public boolean remove(@CheckForNull Object o) { synchronized (mutex) { return delegate().remove(o); } } @Override public boolean removeAll(Collection<?> c) { synchronized (mutex) { return delegate().removeAll(c); } } @Override public boolean retainAll(Collection<?> c) { synchronized (mutex) { return delegate().retainAll(c); } } @Override public boolean removeIf(Predicate<? super E> filter) { synchronized (mutex) { return delegate().removeIf(filter); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public @Nullable Object[] toArray() { synchronized (mutex) { return delegate().toArray(); } } @Override @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations public <T extends @Nullable Object> T[] toArray(T[] a) { synchronized (mutex) { return delegate().toArray(a); } } private static final long serialVersionUID = 0; } @VisibleForTesting static <E extends @Nullable Object> Set<E> set(Set<E> set, @CheckForNull Object mutex) { return new SynchronizedSet<>(set, mutex); } static class SynchronizedSet<E extends @Nullable Object> extends SynchronizedCollection<E> implements Set<E> { SynchronizedSet(Set<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override Set<E> delegate() { return (Set<E>) super.delegate(); } @Override public boolean equals(@CheckForNull Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } private static <E extends @Nullable Object> SortedSet<E> sortedSet( SortedSet<E> set, @CheckForNull Object mutex) { return new SynchronizedSortedSet<>(set, mutex); } static class SynchronizedSortedSet<E extends @Nullable Object> extends SynchronizedSet<E> implements SortedSet<E> { SynchronizedSortedSet(SortedSet<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override SortedSet<E> delegate() { return (SortedSet<E>) super.delegate(); } @Override @CheckForNull public Comparator<? super E> comparator() { synchronized (mutex) { return delegate().comparator(); } } @Override public SortedSet<E> subSet(E fromElement, E toElement) { synchronized (mutex) { return sortedSet(delegate().subSet(fromElement, toElement), mutex); } } @Override public SortedSet<E> headSet(E toElement) { synchronized (mutex) { return sortedSet(delegate().headSet(toElement), mutex); } } @Override public SortedSet<E> tailSet(E fromElement) { synchronized (mutex) { return sortedSet(delegate().tailSet(fromElement), mutex); } } @Override public E first() { synchronized (mutex) { return delegate().first(); } } @Override public E last() { synchronized (mutex) { return delegate().last(); } } private static final long serialVersionUID = 0; } private static <E extends @Nullable Object> List<E> list( List<E> list, @CheckForNull Object mutex) { return (list instanceof RandomAccess) ? new SynchronizedRandomAccessList<E>(list, mutex) : new SynchronizedList<E>(list, mutex); } static class SynchronizedList<E extends @Nullable Object> extends SynchronizedCollection<E> implements List<E> { SynchronizedList(List<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override List<E> delegate() { return (List<E>) super.delegate(); } @Override public void add(int index, E element) { synchronized (mutex) { delegate().add(index, element); } } @Override public boolean addAll(int index, Collection<? extends E> c) { synchronized (mutex) { return delegate().addAll(index, c); } } @Override public E get(int index) { synchronized (mutex) { return delegate().get(index); } } @Override public int indexOf(@CheckForNull Object o) { synchronized (mutex) { return delegate().indexOf(o); } } @Override public int lastIndexOf(@CheckForNull Object o) { synchronized (mutex) { return delegate().lastIndexOf(o); } } @Override public ListIterator<E> listIterator() { return delegate().listIterator(); // manually synchronized } @Override public ListIterator<E> listIterator(int index) { return delegate().listIterator(index); // manually synchronized } @Override public E remove(int index) { synchronized (mutex) { return delegate().remove(index); } } @Override public E set(int index, E element) { synchronized (mutex) { return delegate().set(index, element); } } @Override public void replaceAll(UnaryOperator<E> operator) { synchronized (mutex) { delegate().replaceAll(operator); } } @Override public void sort(@Nullable Comparator<? super E> c) { synchronized (mutex) { delegate().sort(c); } } @Override public List<E> subList(int fromIndex, int toIndex) { synchronized (mutex) { return list(delegate().subList(fromIndex, toIndex), mutex); } } @Override public boolean equals(@CheckForNull Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static final class SynchronizedRandomAccessList<E extends @Nullable Object> extends SynchronizedList<E> implements RandomAccess { SynchronizedRandomAccessList(List<E> list, @CheckForNull Object mutex) { super(list, mutex); } private static final long serialVersionUID = 0; } static <E extends @Nullable Object> Multiset<E> multiset( Multiset<E> multiset, @CheckForNull Object mutex) { if (multiset instanceof SynchronizedMultiset || multiset instanceof ImmutableMultiset) { return multiset; } return new SynchronizedMultiset<>(multiset, mutex); } static final class SynchronizedMultiset<E extends @Nullable Object> extends SynchronizedCollection<E> implements Multiset<E> { @CheckForNull transient Set<E> elementSet; @CheckForNull transient Set<Multiset.Entry<E>> entrySet; SynchronizedMultiset(Multiset<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override Multiset<E> delegate() { return (Multiset<E>) super.delegate(); } @Override public int count(@CheckForNull Object o) { synchronized (mutex) { return delegate().count(o); } } @Override public int add(@ParametricNullness E e, int n) { synchronized (mutex) { return delegate().add(e, n); } } @Override public int remove(@CheckForNull Object o, int n) { synchronized (mutex) { return delegate().remove(o, n); } } @Override public int setCount(@ParametricNullness E element, int count) { synchronized (mutex) { return delegate().setCount(element, count); } } @Override public boolean setCount(@ParametricNullness E element, int oldCount, int newCount) { synchronized (mutex) { return delegate().setCount(element, oldCount, newCount); } } @Override public Set<E> elementSet() { synchronized (mutex) { if (elementSet == null) { elementSet = typePreservingSet(delegate().elementSet(), mutex); } return elementSet; } } @Override public Set<Multiset.Entry<E>> entrySet() { synchronized (mutex) { if (entrySet == null) { entrySet = typePreservingSet(delegate().entrySet(), mutex); } return entrySet; } } @Override public boolean equals(@CheckForNull Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> multimap( Multimap<K, V> multimap, @CheckForNull Object mutex) { if (multimap instanceof SynchronizedMultimap || multimap instanceof BaseImmutableMultimap) { return multimap; } return new SynchronizedMultimap<>(multimap, mutex); } static class SynchronizedMultimap<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedObject implements Multimap<K, V> { @CheckForNull transient Set<K> keySet; @CheckForNull transient Collection<V> valuesCollection; @CheckForNull transient Collection<Map.Entry<K, V>> entries; @CheckForNull transient Map<K, Collection<V>> asMap; @CheckForNull transient Multiset<K> keys; @SuppressWarnings("unchecked") @Override Multimap<K, V> delegate() { return (Multimap<K, V>) super.delegate(); } SynchronizedMultimap(Multimap<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public boolean containsKey(@CheckForNull Object key) { synchronized (mutex) { return delegate().containsKey(key); } } @Override public boolean containsValue(@CheckForNull Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override public boolean containsEntry(@CheckForNull Object key, @CheckForNull Object value) { synchronized (mutex) { return delegate().containsEntry(key, value); } } @Override public Collection<V> get(@ParametricNullness K key) { synchronized (mutex) { return typePreservingCollection(delegate().get(key), mutex); } } @Override public boolean put(@ParametricNullness K key, @ParametricNullness V value) { synchronized (mutex) { return delegate().put(key, value); } } @Override public boolean putAll(@ParametricNullness K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().putAll(key, values); } } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { synchronized (mutex) { return delegate().putAll(multimap); } } @Override public Collection<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public boolean remove(@CheckForNull Object key, @CheckForNull Object value) { synchronized (mutex) { return delegate().remove(key, value); } } @Override public Collection<V> removeAll(@CheckForNull Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public Set<K> keySet() { synchronized (mutex) { if (keySet == null) { keySet = typePreservingSet(delegate().keySet(), mutex); } return keySet; } } @Override public Collection<V> values() { synchronized (mutex) { if (valuesCollection == null) { valuesCollection = collection(delegate().values(), mutex); } return valuesCollection; } } @Override public Collection<Map.Entry<K, V>> entries() { synchronized (mutex) { if (entries == null) { entries = typePreservingCollection(delegate().entries(), mutex); } return entries; } } @Override public void forEach(BiConsumer<? super K, ? super V> action) { synchronized (mutex) { delegate().forEach(action); } } @Override public Map<K, Collection<V>> asMap() { synchronized (mutex) { if (asMap == null) { asMap = new SynchronizedAsMap<>(delegate().asMap(), mutex); } return asMap; } } @Override public Multiset<K> keys() { synchronized (mutex) { if (keys == null) { keys = multiset(delegate().keys(), mutex); } return keys; } } @Override public boolean equals(@CheckForNull Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K extends @Nullable Object, V extends @Nullable Object> ListMultimap<K, V> listMultimap( ListMultimap<K, V> multimap, @CheckForNull Object mutex) { if (multimap instanceof SynchronizedListMultimap || multimap instanceof BaseImmutableMultimap) { return multimap; } return new SynchronizedListMultimap<>(multimap, mutex); } static final class SynchronizedListMultimap< K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedMultimap<K, V> implements ListMultimap<K, V> { SynchronizedListMultimap(ListMultimap<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override ListMultimap<K, V> delegate() { return (ListMultimap<K, V>) super.delegate(); } @Override public List<V> get(K key) { synchronized (mutex) { return list(delegate().get(key), mutex); } } @Override public List<V> removeAll(@CheckForNull Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public List<V> replaceValues(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } private static final long serialVersionUID = 0; } static <K extends @Nullable Object, V extends @Nullable Object> SetMultimap<K, V> setMultimap( SetMultimap<K, V> multimap, @CheckForNull Object mutex) { if (multimap instanceof SynchronizedSetMultimap || multimap instanceof BaseImmutableMultimap) { return multimap; } return new SynchronizedSetMultimap<>(multimap, mutex); } static class SynchronizedSetMultimap<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedMultimap<K, V> implements SetMultimap<K, V> { @CheckForNull transient Set<Map.Entry<K, V>> entrySet; SynchronizedSetMultimap(SetMultimap<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override SetMultimap<K, V> delegate() { return (SetMultimap<K, V>) super.delegate(); } @Override public Set<V> get(K key) { synchronized (mutex) { return set(delegate().get(key), mutex); } } @Override public Set<V> removeAll(@CheckForNull Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public Set<V> replaceValues(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override public Set<Map.Entry<K, V>> entries() { synchronized (mutex) { if (entrySet == null) { entrySet = set(delegate().entries(), mutex); } return entrySet; } } private static final long serialVersionUID = 0; } static <K extends @Nullable Object, V extends @Nullable Object> SortedSetMultimap<K, V> sortedSetMultimap( SortedSetMultimap<K, V> multimap, @CheckForNull Object mutex) { if (multimap instanceof SynchronizedSortedSetMultimap) { return multimap; } return new SynchronizedSortedSetMultimap<>(multimap, mutex); } static final class SynchronizedSortedSetMultimap< K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedSetMultimap<K, V> implements SortedSetMultimap<K, V> { SynchronizedSortedSetMultimap(SortedSetMultimap<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override SortedSetMultimap<K, V> delegate() { return (SortedSetMultimap<K, V>) super.delegate(); } @Override public SortedSet<V> get(K key) { synchronized (mutex) { return sortedSet(delegate().get(key), mutex); } } @Override public SortedSet<V> removeAll(@CheckForNull Object key) { synchronized (mutex) { return delegate().removeAll(key); // copy not synchronized } } @Override public SortedSet<V> replaceValues(K key, Iterable<? extends V> values) { synchronized (mutex) { return delegate().replaceValues(key, values); // copy not synchronized } } @Override @CheckForNull public Comparator<? super V> valueComparator() { synchronized (mutex) { return delegate().valueComparator(); } } private static final long serialVersionUID = 0; } private static <E extends @Nullable Object> Collection<E> typePreservingCollection( Collection<E> collection, @CheckForNull Object mutex) { if (collection instanceof SortedSet) { return sortedSet((SortedSet<E>) collection, mutex); } if (collection instanceof Set) { return set((Set<E>) collection, mutex); } if (collection instanceof List) { return list((List<E>) collection, mutex); } return collection(collection, mutex); } private static <E extends @Nullable Object> Set<E> typePreservingSet( Set<E> set, @CheckForNull Object mutex) { if (set instanceof SortedSet) { return sortedSet((SortedSet<E>) set, mutex); } else { return set(set, mutex); } } static final class SynchronizedAsMapEntries< K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedSet<Map.Entry<K, Collection<V>>> { SynchronizedAsMapEntries( Set<Map.Entry<K, Collection<V>>> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override public Iterator<Map.Entry<K, Collection<V>>> iterator() { // Must be manually synchronized. return new TransformedIterator<Map.Entry<K, Collection<V>>, Map.Entry<K, Collection<V>>>( super.iterator()) { @Override Map.Entry<K, Collection<V>> transform(final Map.Entry<K, Collection<V>> entry) { return new ForwardingMapEntry<K, Collection<V>>() { @Override protected Map.Entry<K, Collection<V>> delegate() { return entry; } @Override public Collection<V> getValue() { return typePreservingCollection(entry.getValue(), mutex); } }; } }; } // See Collections.CheckedMap.CheckedEntrySet for details on attacks. @Override public @Nullable Object[] toArray() { synchronized (mutex) { /* * toArrayImpl returns `@Nullable Object[]` rather than `Object[]` but only because it can * be used with collections that may contain null. This collection never contains nulls, so * we could return `Object[]`. But this class is private and J2KT cannot change return types * in overrides, so we declare `@Nullable Object[]` as the return type. */ return ObjectArrays.toArrayImpl(delegate()); } } @Override @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations public <T extends @Nullable Object> T[] toArray(T[] array) { synchronized (mutex) { return ObjectArrays.toArrayImpl(delegate(), array); } } @Override public boolean contains(@CheckForNull Object o) { synchronized (mutex) { return Maps.containsEntryImpl(delegate(), o); } } @Override public boolean containsAll(Collection<?> c) { synchronized (mutex) { return Collections2.containsAllImpl(delegate(), c); } } @Override public boolean equals(@CheckForNull Object o) { if (o == this) { return true; } synchronized (mutex) { return Sets.equalsImpl(delegate(), o); } } @Override public boolean remove(@CheckForNull Object o) { synchronized (mutex) { return Maps.removeEntryImpl(delegate(), o); } } @Override public boolean removeAll(Collection<?> c) { synchronized (mutex) { return Iterators.removeAll(delegate().iterator(), c); } } @Override public boolean retainAll(Collection<?> c) { synchronized (mutex) { return Iterators.retainAll(delegate().iterator(), c); } } private static final long serialVersionUID = 0; } @VisibleForTesting static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> map( Map<K, V> map, @CheckForNull Object mutex) { return new SynchronizedMap<>(map, mutex); } static class SynchronizedMap<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedObject implements Map<K, V> { @CheckForNull transient Set<K> keySet; @CheckForNull transient Collection<V> values; @CheckForNull transient Set<Map.Entry<K, V>> entrySet; SynchronizedMap(Map<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Map<K, V> delegate() { return (Map<K, V>) super.delegate(); } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override public boolean containsKey(@CheckForNull Object key) { synchronized (mutex) { return delegate().containsKey(key); } } @Override public boolean containsValue(@CheckForNull Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override public Set<Map.Entry<K, V>> entrySet() { synchronized (mutex) { if (entrySet == null) { entrySet = set(delegate().entrySet(), mutex); } return entrySet; } } @Override public void forEach(BiConsumer<? super K, ? super V> action) { synchronized (mutex) { delegate().forEach(action); } } @Override @CheckForNull public V get(@CheckForNull Object key) { synchronized (mutex) { return delegate().get(key); } } @Override @CheckForNull public V getOrDefault(@CheckForNull Object key, @CheckForNull V defaultValue) { synchronized (mutex) { return delegate().getOrDefault(key, defaultValue); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public Set<K> keySet() { synchronized (mutex) { if (keySet == null) { keySet = set(delegate().keySet(), mutex); } return keySet; } } @Override @CheckForNull public V put(K key, V value) { synchronized (mutex) { return delegate().put(key, value); } } @Override @CheckForNull public V putIfAbsent(K key, V value) { synchronized (mutex) { return delegate().putIfAbsent(key, value); } } @Override public boolean replace(K key, V oldValue, V newValue) { synchronized (mutex) { return delegate().replace(key, oldValue, newValue); } } @Override @CheckForNull public V replace(K key, V value) { synchronized (mutex) { return delegate().replace(key, value); } } @Override public V computeIfAbsent(K key, Function<? super K, ? extends V> mappingFunction) { synchronized (mutex) { return delegate().computeIfAbsent(key, mappingFunction); } } @Override @CheckForNull @SuppressWarnings("nullness") // TODO(b/262880368): Remove once we see @NonNull in JDK APIs public V computeIfPresent( K key, BiFunction<? super K, ? super @NonNull V, ? extends @Nullable V> remappingFunction) { synchronized (mutex) { return delegate().computeIfPresent(key, remappingFunction); } } @Override @CheckForNull public V compute( K key, BiFunction<? super K, ? super @Nullable V, ? extends @Nullable V> remappingFunction) { synchronized (mutex) { return delegate().compute(key, remappingFunction); } } @Override @CheckForNull @SuppressWarnings("nullness") // TODO(b/262880368): Remove once we see @NonNull in JDK APIs public V merge( K key, @NonNull V value, BiFunction<? super @NonNull V, ? super @NonNull V, ? extends @Nullable V> remappingFunction) { synchronized (mutex) { return delegate().merge(key, value, remappingFunction); } } @Override public void putAll(Map<? extends K, ? extends V> map) { synchronized (mutex) { delegate().putAll(map); } } @Override public void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) { synchronized (mutex) { delegate().replaceAll(function); } } @Override @CheckForNull public V remove(@CheckForNull Object key) { synchronized (mutex) { return delegate().remove(key); } } @Override public boolean remove(@CheckForNull Object key, @CheckForNull Object value) { synchronized (mutex) { return delegate().remove(key, value); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public Collection<V> values() { synchronized (mutex) { if (values == null) { values = collection(delegate().values(), mutex); } return values; } } @Override public boolean equals(@CheckForNull Object o) { if (o == this) { return true; } synchronized (mutex) { return delegate().equals(o); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } private static final long serialVersionUID = 0; } static <K extends @Nullable Object, V extends @Nullable Object> SortedMap<K, V> sortedMap( SortedMap<K, V> sortedMap, @CheckForNull Object mutex) { return new SynchronizedSortedMap<>(sortedMap, mutex); } static class SynchronizedSortedMap<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedMap<K, V> implements SortedMap<K, V> { SynchronizedSortedMap(SortedMap<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override SortedMap<K, V> delegate() { return (SortedMap<K, V>) super.delegate(); } @Override @CheckForNull public Comparator<? super K> comparator() { synchronized (mutex) { return delegate().comparator(); } } @Override public K firstKey() { synchronized (mutex) { return delegate().firstKey(); } } @Override public SortedMap<K, V> headMap(K toKey) { synchronized (mutex) { return sortedMap(delegate().headMap(toKey), mutex); } } @Override public K lastKey() { synchronized (mutex) { return delegate().lastKey(); } } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { synchronized (mutex) { return sortedMap(delegate().subMap(fromKey, toKey), mutex); } } @Override public SortedMap<K, V> tailMap(K fromKey) { synchronized (mutex) { return sortedMap(delegate().tailMap(fromKey), mutex); } } private static final long serialVersionUID = 0; } static <K extends @Nullable Object, V extends @Nullable Object> BiMap<K, V> biMap( BiMap<K, V> bimap, @CheckForNull Object mutex) { if (bimap instanceof SynchronizedBiMap || bimap instanceof ImmutableBiMap) { return bimap; } return new SynchronizedBiMap<>(bimap, mutex, null); } static final class SynchronizedBiMap<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedMap<K, V> implements BiMap<K, V>, Serializable { @CheckForNull private transient Set<V> valueSet; @RetainedWith @CheckForNull private transient BiMap<V, K> inverse; private SynchronizedBiMap( BiMap<K, V> delegate, @CheckForNull Object mutex, @CheckForNull BiMap<V, K> inverse) { super(delegate, mutex); this.inverse = inverse; } @Override BiMap<K, V> delegate() { return (BiMap<K, V>) super.delegate(); } @Override public Set<V> values() { synchronized (mutex) { if (valueSet == null) { valueSet = set(delegate().values(), mutex); } return valueSet; } } @Override @CheckForNull public V forcePut(@ParametricNullness K key, @ParametricNullness V value) { synchronized (mutex) { return delegate().forcePut(key, value); } } @Override public BiMap<V, K> inverse() { synchronized (mutex) { if (inverse == null) { inverse = new SynchronizedBiMap<>(delegate().inverse(), mutex, this); } return inverse; } } private static final long serialVersionUID = 0; } static final class SynchronizedAsMap<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedMap<K, Collection<V>> { @CheckForNull transient Set<Map.Entry<K, Collection<V>>> asMapEntrySet; @CheckForNull transient Collection<Collection<V>> asMapValues; SynchronizedAsMap(Map<K, Collection<V>> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override @CheckForNull public Collection<V> get(@CheckForNull Object key) { synchronized (mutex) { Collection<V> collection = super.get(key); return (collection == null) ? null : typePreservingCollection(collection, mutex); } } @Override public Set<Map.Entry<K, Collection<V>>> entrySet() { synchronized (mutex) { if (asMapEntrySet == null) { asMapEntrySet = new SynchronizedAsMapEntries<>(delegate().entrySet(), mutex); } return asMapEntrySet; } } @Override public Collection<Collection<V>> values() { synchronized (mutex) { if (asMapValues == null) { asMapValues = new SynchronizedAsMapValues<V>(delegate().values(), mutex); } return asMapValues; } } @Override public boolean containsValue(@CheckForNull Object o) { // values() and its contains() method are both synchronized. return values().contains(o); } private static final long serialVersionUID = 0; } static final class SynchronizedAsMapValues<V extends @Nullable Object> extends SynchronizedCollection<Collection<V>> { SynchronizedAsMapValues(Collection<Collection<V>> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override public Iterator<Collection<V>> iterator() { // Must be manually synchronized. return new TransformedIterator<Collection<V>, Collection<V>>(super.iterator()) { @Override Collection<V> transform(Collection<V> from) { return typePreservingCollection(from, mutex); } }; } private static final long serialVersionUID = 0; } @GwtIncompatible // NavigableSet @VisibleForTesting static final class SynchronizedNavigableSet<E extends @Nullable Object> extends SynchronizedSortedSet<E> implements NavigableSet<E> { SynchronizedNavigableSet(NavigableSet<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override NavigableSet<E> delegate() { return (NavigableSet<E>) super.delegate(); } @Override @CheckForNull public E ceiling(E e) { synchronized (mutex) { return delegate().ceiling(e); } } @Override public Iterator<E> descendingIterator() { return delegate().descendingIterator(); // manually synchronized } @CheckForNull transient NavigableSet<E> descendingSet; @Override public NavigableSet<E> descendingSet() { synchronized (mutex) { if (descendingSet == null) { NavigableSet<E> dS = Synchronized.navigableSet(delegate().descendingSet(), mutex); descendingSet = dS; return dS; } return descendingSet; } } @Override @CheckForNull public E floor(E e) { synchronized (mutex) { return delegate().floor(e); } } @Override public NavigableSet<E> headSet(E toElement, boolean inclusive) { synchronized (mutex) { return Synchronized.navigableSet(delegate().headSet(toElement, inclusive), mutex); } } @Override public SortedSet<E> headSet(E toElement) { return headSet(toElement, false); } @Override @CheckForNull public E higher(E e) { synchronized (mutex) { return delegate().higher(e); } } @Override @CheckForNull public E lower(E e) { synchronized (mutex) { return delegate().lower(e); } } @Override @CheckForNull public E pollFirst() { synchronized (mutex) { return delegate().pollFirst(); } } @Override @CheckForNull public E pollLast() { synchronized (mutex) { return delegate().pollLast(); } } @Override public NavigableSet<E> subSet( E fromElement, boolean fromInclusive, E toElement, boolean toInclusive) { synchronized (mutex) { return Synchronized.navigableSet( delegate().subSet(fromElement, fromInclusive, toElement, toInclusive), mutex); } } @Override public SortedSet<E> subSet(E fromElement, E toElement) { return subSet(fromElement, true, toElement, false); } @Override public NavigableSet<E> tailSet(E fromElement, boolean inclusive) { synchronized (mutex) { return Synchronized.navigableSet(delegate().tailSet(fromElement, inclusive), mutex); } } @Override public SortedSet<E> tailSet(E fromElement) { return tailSet(fromElement, true); } private static final long serialVersionUID = 0; } @GwtIncompatible // NavigableSet static <E extends @Nullable Object> NavigableSet<E> navigableSet( NavigableSet<E> navigableSet, @CheckForNull Object mutex) { return new SynchronizedNavigableSet<>(navigableSet, mutex); } @GwtIncompatible // NavigableSet static <E extends @Nullable Object> NavigableSet<E> navigableSet(NavigableSet<E> navigableSet) { return navigableSet(navigableSet, null); } @GwtIncompatible // NavigableMap static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> navigableMap( NavigableMap<K, V> navigableMap) { return navigableMap(navigableMap, null); } @GwtIncompatible // NavigableMap static <K extends @Nullable Object, V extends @Nullable Object> NavigableMap<K, V> navigableMap( NavigableMap<K, V> navigableMap, @CheckForNull Object mutex) { return new SynchronizedNavigableMap<>(navigableMap, mutex); } @GwtIncompatible // NavigableMap @VisibleForTesting static final class SynchronizedNavigableMap< K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedSortedMap<K, V> implements NavigableMap<K, V> { SynchronizedNavigableMap(NavigableMap<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override NavigableMap<K, V> delegate() { return (NavigableMap<K, V>) super.delegate(); } @Override @CheckForNull public Map.Entry<K, V> ceilingEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().ceilingEntry(key), mutex); } } @Override @CheckForNull public K ceilingKey(K key) { synchronized (mutex) { return delegate().ceilingKey(key); } } @CheckForNull transient NavigableSet<K> descendingKeySet; @Override public NavigableSet<K> descendingKeySet() { synchronized (mutex) { if (descendingKeySet == null) { return descendingKeySet = Synchronized.navigableSet(delegate().descendingKeySet(), mutex); } return descendingKeySet; } } @CheckForNull transient NavigableMap<K, V> descendingMap; @Override public NavigableMap<K, V> descendingMap() { synchronized (mutex) { if (descendingMap == null) { return descendingMap = navigableMap(delegate().descendingMap(), mutex); } return descendingMap; } } @Override @CheckForNull public Map.Entry<K, V> firstEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().firstEntry(), mutex); } } @Override @CheckForNull public Map.Entry<K, V> floorEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().floorEntry(key), mutex); } } @Override @CheckForNull public K floorKey(K key) { synchronized (mutex) { return delegate().floorKey(key); } } @Override public NavigableMap<K, V> headMap(K toKey, boolean inclusive) { synchronized (mutex) { return navigableMap(delegate().headMap(toKey, inclusive), mutex); } } @Override public SortedMap<K, V> headMap(K toKey) { return headMap(toKey, false); } @Override @CheckForNull public Map.Entry<K, V> higherEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().higherEntry(key), mutex); } } @Override @CheckForNull public K higherKey(K key) { synchronized (mutex) { return delegate().higherKey(key); } } @Override @CheckForNull public Map.Entry<K, V> lastEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().lastEntry(), mutex); } } @Override @CheckForNull public Map.Entry<K, V> lowerEntry(K key) { synchronized (mutex) { return nullableSynchronizedEntry(delegate().lowerEntry(key), mutex); } } @Override @CheckForNull public K lowerKey(K key) { synchronized (mutex) { return delegate().lowerKey(key); } } @Override public Set<K> keySet() { return navigableKeySet(); } @CheckForNull transient NavigableSet<K> navigableKeySet; @Override public NavigableSet<K> navigableKeySet() { synchronized (mutex) { if (navigableKeySet == null) { return navigableKeySet = Synchronized.navigableSet(delegate().navigableKeySet(), mutex); } return navigableKeySet; } } @Override @CheckForNull public Map.Entry<K, V> pollFirstEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().pollFirstEntry(), mutex); } } @Override @CheckForNull public Map.Entry<K, V> pollLastEntry() { synchronized (mutex) { return nullableSynchronizedEntry(delegate().pollLastEntry(), mutex); } } @Override public NavigableMap<K, V> subMap( K fromKey, boolean fromInclusive, K toKey, boolean toInclusive) { synchronized (mutex) { return navigableMap(delegate().subMap(fromKey, fromInclusive, toKey, toInclusive), mutex); } } @Override public SortedMap<K, V> subMap(K fromKey, K toKey) { return subMap(fromKey, true, toKey, false); } @Override public NavigableMap<K, V> tailMap(K fromKey, boolean inclusive) { synchronized (mutex) { return navigableMap(delegate().tailMap(fromKey, inclusive), mutex); } } @Override public SortedMap<K, V> tailMap(K fromKey) { return tailMap(fromKey, true); } private static final long serialVersionUID = 0; } @GwtIncompatible // works but is needed only for NavigableMap @CheckForNull private static <K extends @Nullable Object, V extends @Nullable Object> Map.Entry<K, V> nullableSynchronizedEntry( @CheckForNull Map.Entry<K, V> entry, @CheckForNull Object mutex) { if (entry == null) { return null; } return new SynchronizedEntry<>(entry, mutex); } @GwtIncompatible // works but is needed only for NavigableMap static final class SynchronizedEntry<K extends @Nullable Object, V extends @Nullable Object> extends SynchronizedObject implements Map.Entry<K, V> { SynchronizedEntry(Map.Entry<K, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") // guaranteed by the constructor @Override Map.Entry<K, V> delegate() { return (Map.Entry<K, V>) super.delegate(); } @Override public boolean equals(@CheckForNull Object obj) { synchronized (mutex) { return delegate().equals(obj); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } @Override public K getKey() { synchronized (mutex) { return delegate().getKey(); } } @Override public V getValue() { synchronized (mutex) { return delegate().getValue(); } } @Override public V setValue(V value) { synchronized (mutex) { return delegate().setValue(value); } } private static final long serialVersionUID = 0; } static <E extends @Nullable Object> Queue<E> queue(Queue<E> queue, @CheckForNull Object mutex) { return (queue instanceof SynchronizedQueue) ? queue : new SynchronizedQueue<E>(queue, mutex); } static class SynchronizedQueue<E extends @Nullable Object> extends SynchronizedCollection<E> implements Queue<E> { SynchronizedQueue(Queue<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override Queue<E> delegate() { return (Queue<E>) super.delegate(); } @Override public E element() { synchronized (mutex) { return delegate().element(); } } @Override public boolean offer(E e) { synchronized (mutex) { return delegate().offer(e); } } @Override @CheckForNull public E peek() { synchronized (mutex) { return delegate().peek(); } } @Override @CheckForNull public E poll() { synchronized (mutex) { return delegate().poll(); } } @Override public E remove() { synchronized (mutex) { return delegate().remove(); } } private static final long serialVersionUID = 0; } static <E extends @Nullable Object> Deque<E> deque(Deque<E> deque, @CheckForNull Object mutex) { return new SynchronizedDeque<>(deque, mutex); } static final class SynchronizedDeque<E extends @Nullable Object> extends SynchronizedQueue<E> implements Deque<E> { SynchronizedDeque(Deque<E> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @Override Deque<E> delegate() { return (Deque<E>) super.delegate(); } @Override public void addFirst(E e) { synchronized (mutex) { delegate().addFirst(e); } } @Override public void addLast(E e) { synchronized (mutex) { delegate().addLast(e); } } @Override public boolean offerFirst(E e) { synchronized (mutex) { return delegate().offerFirst(e); } } @Override public boolean offerLast(E e) { synchronized (mutex) { return delegate().offerLast(e); } } @Override public E removeFirst() { synchronized (mutex) { return delegate().removeFirst(); } } @Override public E removeLast() { synchronized (mutex) { return delegate().removeLast(); } } @Override @CheckForNull public E pollFirst() { synchronized (mutex) { return delegate().pollFirst(); } } @Override @CheckForNull public E pollLast() { synchronized (mutex) { return delegate().pollLast(); } } @Override public E getFirst() { synchronized (mutex) { return delegate().getFirst(); } } @Override public E getLast() { synchronized (mutex) { return delegate().getLast(); } } @Override @CheckForNull public E peekFirst() { synchronized (mutex) { return delegate().peekFirst(); } } @Override @CheckForNull public E peekLast() { synchronized (mutex) { return delegate().peekLast(); } } @Override public boolean removeFirstOccurrence(@CheckForNull Object o) { synchronized (mutex) { return delegate().removeFirstOccurrence(o); } } @Override public boolean removeLastOccurrence(@CheckForNull Object o) { synchronized (mutex) { return delegate().removeLastOccurrence(o); } } @Override public void push(E e) { synchronized (mutex) { delegate().push(e); } } @Override public E pop() { synchronized (mutex) { return delegate().pop(); } } @Override public Iterator<E> descendingIterator() { synchronized (mutex) { return delegate().descendingIterator(); } } private static final long serialVersionUID = 0; } static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Table<R, C, V> table(Table<R, C, V> table, @CheckForNull Object mutex) { return new SynchronizedTable<>(table, mutex); } static final class SynchronizedTable< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> extends SynchronizedObject implements Table<R, C, V> { SynchronizedTable(Table<R, C, V> delegate, @CheckForNull Object mutex) { super(delegate, mutex); } @SuppressWarnings("unchecked") @Override Table<R, C, V> delegate() { return (Table<R, C, V>) super.delegate(); } @Override public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { synchronized (mutex) { return delegate().contains(rowKey, columnKey); } } @Override public boolean containsRow(@CheckForNull Object rowKey) { synchronized (mutex) { return delegate().containsRow(rowKey); } } @Override public boolean containsColumn(@CheckForNull Object columnKey) { synchronized (mutex) { return delegate().containsColumn(columnKey); } } @Override public boolean containsValue(@CheckForNull Object value) { synchronized (mutex) { return delegate().containsValue(value); } } @Override @CheckForNull public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { synchronized (mutex) { return delegate().get(rowKey, columnKey); } } @Override public boolean isEmpty() { synchronized (mutex) { return delegate().isEmpty(); } } @Override public int size() { synchronized (mutex) { return delegate().size(); } } @Override public void clear() { synchronized (mutex) { delegate().clear(); } } @Override @CheckForNull public V put( @ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value) { synchronized (mutex) { return delegate().put(rowKey, columnKey, value); } } @Override public void putAll(Table<? extends R, ? extends C, ? extends V> table) { synchronized (mutex) { delegate().putAll(table); } } @Override @CheckForNull public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { synchronized (mutex) { return delegate().remove(rowKey, columnKey); } } @Override public Map<C, V> row(@ParametricNullness R rowKey) { synchronized (mutex) { return map(delegate().row(rowKey), mutex); } } @Override public Map<R, V> column(@ParametricNullness C columnKey) { synchronized (mutex) { return map(delegate().column(columnKey), mutex); } } @Override public Set<Cell<R, C, V>> cellSet() { synchronized (mutex) { return set(delegate().cellSet(), mutex); } } @Override public Set<R> rowKeySet() { synchronized (mutex) { return set(delegate().rowKeySet(), mutex); } } @Override public Set<C> columnKeySet() { synchronized (mutex) { return set(delegate().columnKeySet(), mutex); } } @Override public Collection<V> values() { synchronized (mutex) { return collection(delegate().values(), mutex); } } @Override public Map<R, Map<C, V>> rowMap() { synchronized (mutex) { return map( Maps.transformValues( delegate().rowMap(), new com.google.common.base.Function<Map<C, V>, Map<C, V>>() { @Override public Map<C, V> apply(Map<C, V> t) { return map(t, mutex); } }), mutex); } } @Override public Map<C, Map<R, V>> columnMap() { synchronized (mutex) { return map( Maps.transformValues( delegate().columnMap(), new com.google.common.base.Function<Map<R, V>, Map<R, V>>() { @Override public Map<R, V> apply(Map<R, V> t) { return map(t, mutex); } }), mutex); } } @Override public int hashCode() { synchronized (mutex) { return delegate().hashCode(); } } @Override public boolean equals(@CheckForNull Object obj) { if (this == obj) { return true; } synchronized (mutex) { return delegate().equals(obj); } } } }
google/guava
guava/src/com/google/common/collect/Synchronized.java
369
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Converter; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import java.util.Spliterator; import java.util.Spliterators; import javax.annotation.CheckForNull; /** * Static utility methods pertaining to {@code long} primitives, that are not already found in * either {@link Long} or {@link Arrays}. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Longs { private Longs() {} /** * The number of bytes required to represent a primitive {@code long} value. * * <p><b>Java 8+ users:</b> use {@link Long#BYTES} instead. */ public static final int BYTES = Long.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as a {@code long}. * * @since 10.0 */ public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Long) * value).hashCode()}. * * <p>This method always return the value specified by {@link Long#hashCode()} in java, which * might be different from {@code ((Long) value).hashCode()} in GWT because {@link * Long#hashCode()} in GWT does not obey the JRE contract. * * <p><b>Java 8+ users:</b> use {@link Long#hashCode(long)} instead. * * @param value a primitive {@code long} value * @return a hash code for the value */ public static int hashCode(long value) { return (int) (value ^ (value >>> 32)); } /** * Compares the two specified {@code long} values. The sign of the value returned is the same as * that of {@code ((Long) a).compareTo(b)}. * * <p><b>Java 7+ users:</b> this method should be treated as deprecated; use the equivalent {@link * Long#compare} method instead. * * @param a the first {@code long} to compare * @param b the second {@code long} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(long a, long b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } /** * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return {@code true} if {@code array[i] == target} for some value of {@code i} */ public static boolean contains(long[] array, long target) { for (long value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int indexOf(long[] array, long target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf(long[] array, long target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code target} within * {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, * i, i + target.length)} contains exactly the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(long[] array, long[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int lastIndexOf(long[] array, long target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf(long[] array, long target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code long} values * @return the value present in {@code array} that is less than or equal to every other value in * the array * @throws IllegalArgumentException if {@code array} is empty */ public static long min(long... array) { checkArgument(array.length > 0); long min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code long} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array * @throws IllegalArgumentException if {@code array} is empty */ public static long max(long... array) { checkArgument(array.length > 0); long max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. * * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code * value} is greater than {@code max}, {@code max} is returned. * * @param value the {@code long} value to constrain * @param min the lower bound (inclusive) of the range to constrain {@code value} to * @param max the upper bound (inclusive) of the range to constrain {@code value} to * @throws IllegalArgumentException if {@code min > max} * @since 21.0 */ public static long constrainToRange(long value, long min, long max) { checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max); return Math.min(Math.max(value, min), max); } /** * Returns the values from each provided array combined into a single array. For example, {@code * concat(new long[] {a, b}, new long[] {}, new long[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code long} arrays * @return a single array containing all the values from the source arrays, in order * @throws IllegalArgumentException if the total number of elements in {@code arrays} does not fit * in an {@code int} */ public static long[] concat(long[]... arrays) { long length = 0; for (long[] array : arrays) { length += array.length; } long[] result = new long[checkNoOverflow(length)]; int pos = 0; for (long[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } private static int checkNoOverflow(long result) { checkArgument( result == (int) result, "the total number of elements (%s) in the arrays must fit in an int", result); return (int) result; } /** * Returns a big-endian representation of {@code value} in an 8-element byte array; equivalent to * {@code ByteBuffer.allocate(8).putLong(value).array()}. For example, the input value {@code * 0x1213141516171819L} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, * 0x18, 0x19}}. * * <p>If you need to convert and concatenate several values (possibly even of different types), * use a shared {@link java.nio.ByteBuffer} instance, or use {@link * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. */ public static byte[] toByteArray(long value) { // Note that this code needs to stay compatible with GWT, which has known // bugs when narrowing byte casts of long values occur. byte[] result = new byte[8]; for (int i = 7; i >= 0; i--) { result[i] = (byte) (value & 0xffL); value >>= 8; } return result; } /** * Returns the {@code long} value whose big-endian representation is stored in the first 8 bytes * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getLong()}. For example, the * input byte array {@code {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}} would yield the * {@code long} value {@code 0x1213141516171819L}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more * flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 8 elements */ public static long fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes( bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7]); } /** * Returns the {@code long} value whose byte representation is the given 8 bytes, in big-endian * order; equivalent to {@code Longs.fromByteArray(new byte[] {b1, b2, b3, b4, b5, b6, b7, b8})}. * * @since 7.0 */ public static long fromBytes( byte b1, byte b2, byte b3, byte b4, byte b5, byte b6, byte b7, byte b8) { return (b1 & 0xFFL) << 56 | (b2 & 0xFFL) << 48 | (b3 & 0xFFL) << 40 | (b4 & 0xFFL) << 32 | (b5 & 0xFFL) << 24 | (b6 & 0xFFL) << 16 | (b7 & 0xFFL) << 8 | (b8 & 0xFFL); } /* * Moving asciiDigits into this static holder class lets ProGuard eliminate and inline the Longs * class. */ static final class AsciiDigits { private AsciiDigits() {} private static final byte[] asciiDigits; static { byte[] result = new byte[128]; Arrays.fill(result, (byte) -1); for (int i = 0; i < 10; i++) { result['0' + i] = (byte) i; } for (int i = 0; i < 26; i++) { result['A' + i] = (byte) (10 + i); result['a' + i] = (byte) (10 + i); } asciiDigits = result; } static int digit(char c) { return (c < 128) ? asciiDigits[c] : -1; } } /** * Parses the specified string as a signed decimal long value. The ASCII character {@code '-'} ( * <code>'&#92;u002D'</code>) is recognized as the minus sign. * * <p>Unlike {@link Long#parseLong(String)}, this method returns {@code null} instead of throwing * an exception if parsing fails. Additionally, this method only accepts ASCII digits, and returns * {@code null} if non-ASCII digits are present in the string. * * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite * the change to {@link Long#parseLong(String)} for that version. * * @param string the string representation of a long value * @return the long value represented by {@code string}, or {@code null} if {@code string} has a * length of zero or cannot be parsed as a long value * @throws NullPointerException if {@code string} is {@code null} * @since 14.0 */ @CheckForNull public static Long tryParse(String string) { return tryParse(string, 10); } /** * Parses the specified string as a signed long value using the specified radix. The ASCII * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign. * * <p>Unlike {@link Long#parseLong(String, int)}, this method returns {@code null} instead of * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, * and returns {@code null} if non-ASCII digits are present in the string. * * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite * the change to {@link Long#parseLong(String, int)} for that version. * * @param string the string representation of a long value * @param radix the radix to use when parsing * @return the long value represented by {@code string} using {@code radix}, or {@code null} if * {@code string} has a length of zero or cannot be parsed as a long value * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix > * Character.MAX_RADIX} * @throws NullPointerException if {@code string} is {@code null} * @since 19.0 */ @CheckForNull public static Long tryParse(String string, int radix) { if (checkNotNull(string).isEmpty()) { return null; } if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new IllegalArgumentException( "radix must be between MIN_RADIX and MAX_RADIX but was " + radix); } boolean negative = string.charAt(0) == '-'; int index = negative ? 1 : 0; if (index == string.length()) { return null; } int digit = AsciiDigits.digit(string.charAt(index++)); if (digit < 0 || digit >= radix) { return null; } long accum = -digit; long cap = Long.MIN_VALUE / radix; while (index < string.length()) { digit = AsciiDigits.digit(string.charAt(index++)); if (digit < 0 || digit >= radix || accum < cap) { return null; } accum *= radix; if (accum < Long.MIN_VALUE + digit) { return null; } accum -= digit; } if (negative) { return accum; } else if (accum == Long.MIN_VALUE) { return null; } else { return -accum; } } private static final class LongConverter extends Converter<String, Long> implements Serializable { static final Converter<String, Long> INSTANCE = new LongConverter(); @Override protected Long doForward(String value) { return Long.decode(value); } @Override protected String doBackward(Long value) { return value.toString(); } @Override public String toString() { return "Longs.stringConverter()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } /** * Returns a serializable converter object that converts between strings and longs using {@link * Long#decode} and {@link Long#toString()}. The returned converter throws {@link * NumberFormatException} if the input string is invalid. * * <p><b>Warning:</b> please see {@link Long#decode} to understand exactly how strings are parsed. * For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the value * {@code 83L}. * * @since 16.0 */ public static Converter<String, Long> stringConverter() { return LongConverter.INSTANCE; } /** * Returns an array containing the same values as {@code array}, but guaranteed to be of a * specified minimum length. If {@code array} already has a length of at least {@code minLength}, * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is * returned, containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative * @return an array containing the values of {@code array}, with guaranteed minimum length {@code * minLength} */ public static long[] ensureCapacity(long[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; } /** * Returns a string containing the supplied {@code long} values separated by {@code separator}. * For example, {@code join("-", 1L, 2L, 3L)} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting string * (but not at the start or end) * @param array an array of {@code long} values, possibly empty */ public static String join(String separator, long... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 10); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code long} arrays <a * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it * compares, using {@link #compare(long, long)}), the first pair of values that follow any common * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For * example, {@code [] < [1L] < [1L, 2L] < [2L]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with {@link Arrays#equals(long[], * long[])}. * * @since 2.0 */ public static Comparator<long[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<long[]> { INSTANCE; @Override public int compare(long[] left, long[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Longs.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } @Override public String toString() { return "Longs.lexicographicalComparator()"; } } /** * Sorts the elements of {@code array} in descending order. * * @since 23.1 */ public static void sortDescending(long[] array) { checkNotNull(array); sortDescending(array, 0, array.length); } /** * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} * exclusive in descending order. * * @since 23.1 */ public static void sortDescending(long[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); Arrays.sort(array, fromIndex, toIndex); reverse(array, fromIndex, toIndex); } /** * Reverses the elements of {@code array}. This is equivalent to {@code * Collections.reverse(Longs.asList(array))}, but is likely to be more efficient. * * @since 23.1 */ public static void reverse(long[] array) { checkNotNull(array); reverse(array, 0, array.length); } /** * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} * exclusive. This is equivalent to {@code * Collections.reverse(Longs.asList(array).subList(fromIndex, toIndex))}, but is likely to be more * efficient. * * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or * {@code toIndex > fromIndex} * @since 23.1 */ public static void reverse(long[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { long tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } /** * Performs a right rotation of {@code array} of "distance" places, so that the first element is * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Longs.asList(array), * distance)}, but is considerably faster and avoids allocation and garbage collection. * * <p>The provided "distance" may be negative, which will rotate left. * * @since 32.0.0 */ public static void rotate(long[] array, int distance) { rotate(array, distance, 0, array.length); } /** * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code * toIndex} exclusive. This is equivalent to {@code * Collections.rotate(Longs.asList(array).subList(fromIndex, toIndex), distance)}, but is * considerably faster and avoids allocations and garbage collection. * * <p>The provided "distance" may be negative, which will rotate left. * * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or * {@code toIndex > fromIndex} * @since 32.0.0 */ public static void rotate(long[] array, int distance, int fromIndex, int toIndex) { // See Ints.rotate for more details about possible algorithms here. checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); if (array.length <= 1) { return; } int length = toIndex - fromIndex; // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many // places left to rotate. int m = -distance % length; m = (m < 0) ? m + length : m; // The current index of what will become the first element of the rotated section. int newFirstIndex = m + fromIndex; if (newFirstIndex == fromIndex) { return; } reverse(array, fromIndex, newFirstIndex); reverse(array, newFirstIndex, toIndex); reverse(array, fromIndex, toIndex); } /** * Returns an array containing each value of {@code collection}, converted to a {@code long} value * in the manner of {@link Number#longValue}. * * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. * Calling this method is as thread-safe as calling that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the same order, converted * to primitives * @throws NullPointerException if {@code collection} or any of its elements is null * @since 1.0 (parameter was {@code Collection<Long>} before 12.0) */ public static long[] toArray(Collection<? extends Number> collection) { if (collection instanceof LongArrayAsList) { return ((LongArrayAsList) collection).toLongArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; long[] array = new long[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).longValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to * set a value to {@code null} will result in a {@link NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of {@code Long} objects * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for * the returned list is unspecified. * * <p>The returned list is serializable. * * <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableLongArray} * instead, which has an {@link ImmutableLongArray#asList asList} view. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Long> asList(long... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new LongArrayAsList(backingArray); } @GwtCompatible private static class LongArrayAsList extends AbstractList<Long> implements RandomAccess, Serializable { final long[] array; final int start; final int end; LongArrayAsList(long[] array) { this(array, 0, array.length); } LongArrayAsList(long[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Long get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public Spliterator.OfLong spliterator() { return Spliterators.spliterator(array, start, end, 0); } @Override public boolean contains(@CheckForNull Object target) { // Overridden to prevent a ton of boxing return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1; } @Override public int indexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Long) { int i = Longs.indexOf(array, (Long) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Long) { int i = Longs.lastIndexOf(array, (Long) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Long set(int index, Long element) { checkElementIndex(index, size()); long oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Long> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new LongArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(@CheckForNull Object object) { if (object == this) { return true; } if (object instanceof LongArrayAsList) { LongArrayAsList that = (LongArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Longs.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 10); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } long[] toLongArray() { return Arrays.copyOfRange(array, start, end); } private static final long serialVersionUID = 0; } }
google/guava
guava/src/com/google/common/primitives/Longs.java
370
/* * 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.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Preconditions; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.PriorityQueue; import java.util.Queue; import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentLinkedQueue; import java.util.concurrent.LinkedBlockingDeque; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.PriorityBlockingQueue; import java.util.concurrent.SynchronousQueue; import java.util.concurrent.TimeUnit; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods pertaining to {@link Queue} and {@link Deque} instances. Also see this * class's counterparts {@link Lists}, {@link Sets}, and {@link Maps}. * * @author Kurt Alfred Kluever * @since 11.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Queues { private Queues() {} // ArrayBlockingQueue /** * Creates an empty {@code ArrayBlockingQueue} with the given (fixed) capacity and nonfair access * policy. */ @J2ktIncompatible @GwtIncompatible // ArrayBlockingQueue public static <E> ArrayBlockingQueue<E> newArrayBlockingQueue(int capacity) { return new ArrayBlockingQueue<>(capacity); } // ArrayDeque /** * Creates an empty {@code ArrayDeque}. * * @since 12.0 */ public static <E> ArrayDeque<E> newArrayDeque() { return new ArrayDeque<>(); } /** * Creates an {@code ArrayDeque} containing the elements of the specified iterable, in the order * they are returned by the iterable's iterator. * * @since 12.0 */ public static <E> ArrayDeque<E> newArrayDeque(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new ArrayDeque<>((Collection<? extends E>) elements); } ArrayDeque<E> deque = new ArrayDeque<>(); Iterables.addAll(deque, elements); return deque; } // ConcurrentLinkedQueue /** Creates an empty {@code ConcurrentLinkedQueue}. */ @J2ktIncompatible @GwtIncompatible // ConcurrentLinkedQueue public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue() { return new ConcurrentLinkedQueue<>(); } /** * Creates a {@code ConcurrentLinkedQueue} containing the elements of the specified iterable, in * the order they are returned by the iterable's iterator. */ @J2ktIncompatible @GwtIncompatible // ConcurrentLinkedQueue public static <E> ConcurrentLinkedQueue<E> newConcurrentLinkedQueue( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new ConcurrentLinkedQueue<>((Collection<? extends E>) elements); } ConcurrentLinkedQueue<E> queue = new ConcurrentLinkedQueue<>(); Iterables.addAll(queue, elements); return queue; } // LinkedBlockingDeque /** * Creates an empty {@code LinkedBlockingDeque} with a capacity of {@link Integer#MAX_VALUE}. * * @since 12.0 */ @J2ktIncompatible @GwtIncompatible // LinkedBlockingDeque public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque() { return new LinkedBlockingDeque<>(); } /** * Creates an empty {@code LinkedBlockingDeque} with the given (fixed) capacity. * * @throws IllegalArgumentException if {@code capacity} is less than 1 * @since 12.0 */ @J2ktIncompatible @GwtIncompatible // LinkedBlockingDeque public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(int capacity) { return new LinkedBlockingDeque<>(capacity); } /** * Creates a {@code LinkedBlockingDeque} with a capacity of {@link Integer#MAX_VALUE}, containing * the elements of the specified iterable, in the order they are returned by the iterable's * iterator. * * @since 12.0 */ @J2ktIncompatible @GwtIncompatible // LinkedBlockingDeque public static <E> LinkedBlockingDeque<E> newLinkedBlockingDeque(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new LinkedBlockingDeque<>((Collection<? extends E>) elements); } LinkedBlockingDeque<E> deque = new LinkedBlockingDeque<>(); Iterables.addAll(deque, elements); return deque; } // LinkedBlockingQueue /** Creates an empty {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}. */ @J2ktIncompatible @GwtIncompatible // LinkedBlockingQueue public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue() { return new LinkedBlockingQueue<>(); } /** * Creates an empty {@code LinkedBlockingQueue} with the given (fixed) capacity. * * @throws IllegalArgumentException if {@code capacity} is less than 1 */ @J2ktIncompatible @GwtIncompatible // LinkedBlockingQueue public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(int capacity) { return new LinkedBlockingQueue<>(capacity); } /** * Creates a {@code LinkedBlockingQueue} with a capacity of {@link Integer#MAX_VALUE}, containing * the elements of the specified iterable, in the order they are returned by the iterable's * iterator. * * @param elements the elements that the queue should contain, in order * @return a new {@code LinkedBlockingQueue} containing those elements */ @J2ktIncompatible @GwtIncompatible // LinkedBlockingQueue public static <E> LinkedBlockingQueue<E> newLinkedBlockingQueue(Iterable<? extends E> elements) { if (elements instanceof Collection) { return new LinkedBlockingQueue<>((Collection<? extends E>) elements); } LinkedBlockingQueue<E> queue = new LinkedBlockingQueue<>(); Iterables.addAll(queue, elements); return queue; } // LinkedList: see {@link com.google.common.collect.Lists} // PriorityBlockingQueue /** * Creates an empty {@code PriorityBlockingQueue} with the ordering given by its elements' natural * ordering. * * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable} * in 15.0) */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 @J2ktIncompatible @GwtIncompatible // PriorityBlockingQueue public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue() { return new PriorityBlockingQueue<>(); } /** * Creates a {@code PriorityBlockingQueue} containing the given elements. * * <p><b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue}, * this priority queue will be ordered according to the same ordering. * * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable} * in 15.0) */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 @J2ktIncompatible @GwtIncompatible // PriorityBlockingQueue public static <E extends Comparable> PriorityBlockingQueue<E> newPriorityBlockingQueue( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new PriorityBlockingQueue<>((Collection<? extends E>) elements); } PriorityBlockingQueue<E> queue = new PriorityBlockingQueue<>(); Iterables.addAll(queue, elements); return queue; } // PriorityQueue /** * Creates an empty {@code PriorityQueue} with the ordering given by its elements' natural * ordering. * * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable} * in 15.0) */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static <E extends Comparable> PriorityQueue<E> newPriorityQueue() { return new PriorityQueue<>(); } /** * Creates a {@code PriorityQueue} containing the given elements. * * <p><b>Note:</b> If the specified iterable is a {@code SortedSet} or a {@code PriorityQueue}, * this priority queue will be ordered according to the same ordering. * * @since 11.0 (but the bound of {@code E} was changed from {@code Object} to {@code Comparable} * in 15.0) */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static <E extends Comparable> PriorityQueue<E> newPriorityQueue( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new PriorityQueue<>((Collection<? extends E>) elements); } PriorityQueue<E> queue = new PriorityQueue<>(); Iterables.addAll(queue, elements); return queue; } // SynchronousQueue /** Creates an empty {@code SynchronousQueue} with nonfair access policy. */ @J2ktIncompatible @GwtIncompatible // SynchronousQueue public static <E> SynchronousQueue<E> newSynchronousQueue() { return new SynchronousQueue<>(); } /** * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested {@code * numElements} elements are not available, it will wait for them up to the specified timeout. * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up * @return the number of elements transferred * @throws InterruptedException if interrupted while waiting * @since 28.0 */ @CanIgnoreReturnValue @J2ktIncompatible @GwtIncompatible // BlockingQueue public static <E> int drain( BlockingQueue<E> q, Collection<? super E> buffer, int numElements, java.time.Duration timeout) throws InterruptedException { // TODO(b/126049426): Consider using saturateToNanos(timeout) instead. return drain(q, buffer, numElements, timeout.toNanos(), TimeUnit.NANOSECONDS); } /** * Drains the queue as {@link BlockingQueue#drainTo(Collection, int)}, but if the requested {@code * numElements} elements are not available, it will wait for them up to the specified timeout. * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up, in units of {@code unit} * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter * @return the number of elements transferred * @throws InterruptedException if interrupted while waiting */ @CanIgnoreReturnValue @J2ktIncompatible @GwtIncompatible // BlockingQueue @SuppressWarnings("GoodTime") // should accept a java.time.Duration public static <E> int drain( BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout, TimeUnit unit) throws InterruptedException { Preconditions.checkNotNull(buffer); /* * This code performs one System.nanoTime() more than necessary, and in return, the time to * execute Queue#drainTo is not added *on top* of waiting for the timeout (which could make * the timeout arbitrarily inaccurate, given a queue that is slow to drain). */ long deadline = System.nanoTime() + unit.toNanos(timeout); int added = 0; while (added < numElements) { // we could rely solely on #poll, but #drainTo might be more efficient when there are multiple // elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) added += q.drainTo(buffer, numElements - added); if (added < numElements) { // not enough elements immediately available; will have to poll E e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); if (e == null) { break; // we already waited enough, and there are no more elements in sight } buffer.add(e); added++; } } return added; } /** * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, Duration)}, but with a * different behavior in case it is interrupted while waiting. In that case, the operation will * continue as usual, and in the end the thread's interruption status will be set (no {@code * InterruptedException} is thrown). * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up * @return the number of elements transferred * @since 28.0 */ @CanIgnoreReturnValue @J2ktIncompatible @GwtIncompatible // BlockingQueue public static <E> int drainUninterruptibly( BlockingQueue<E> q, Collection<? super E> buffer, int numElements, java.time.Duration timeout) { // TODO(b/126049426): Consider using saturateToNanos(timeout) instead. return drainUninterruptibly(q, buffer, numElements, timeout.toNanos(), TimeUnit.NANOSECONDS); } /** * Drains the queue as {@linkplain #drain(BlockingQueue, Collection, int, long, TimeUnit)}, but * with a different behavior in case it is interrupted while waiting. In that case, the operation * will continue as usual, and in the end the thread's interruption status will be set (no {@code * InterruptedException} is thrown). * * @param q the blocking queue to be drained * @param buffer where to add the transferred elements * @param numElements the number of elements to be waited for * @param timeout how long to wait before giving up, in units of {@code unit} * @param unit a {@code TimeUnit} determining how to interpret the timeout parameter * @return the number of elements transferred */ @CanIgnoreReturnValue @J2ktIncompatible @GwtIncompatible // BlockingQueue @SuppressWarnings("GoodTime") // should accept a java.time.Duration public static <E> int drainUninterruptibly( BlockingQueue<E> q, Collection<? super E> buffer, int numElements, long timeout, TimeUnit unit) { Preconditions.checkNotNull(buffer); long deadline = System.nanoTime() + unit.toNanos(timeout); int added = 0; boolean interrupted = false; try { while (added < numElements) { // we could rely solely on #poll, but #drainTo might be more efficient when there are // multiple elements already available (e.g. LinkedBlockingQueue#drainTo locks only once) added += q.drainTo(buffer, numElements - added); if (added < numElements) { // not enough elements immediately available; will have to poll E e; // written exactly once, by a successful (uninterrupted) invocation of #poll while (true) { try { e = q.poll(deadline - System.nanoTime(), TimeUnit.NANOSECONDS); break; } catch (InterruptedException ex) { interrupted = true; // note interruption and retry } } if (e == null) { break; // we already waited enough, and there are no more elements in sight } buffer.add(e); added++; } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } return added; } /** * Returns a synchronized (thread-safe) queue backed by the specified queue. In order to guarantee * serial access, it is critical that <b>all</b> access to the backing queue is accomplished * through the returned queue. * * <p>It is imperative that the user manually synchronize on the returned queue when accessing the * queue's iterator: * * <pre>{@code * Queue<E> queue = Queues.synchronizedQueue(MinMaxPriorityQueue.<E>create()); * ... * queue.add(element); // Needn't be in synchronized block * ... * synchronized (queue) { // Must synchronize on queue! * Iterator<E> i = queue.iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * } * }</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned queue will be serializable if the specified queue is serializable. * * @param queue the queue to be wrapped in a synchronized view * @return a synchronized view of the specified queue * @since 14.0 */ public static <E extends @Nullable Object> Queue<E> synchronizedQueue(Queue<E> queue) { return Synchronized.queue(queue, null); } /** * Returns a synchronized (thread-safe) deque backed by the specified deque. In order to guarantee * serial access, it is critical that <b>all</b> access to the backing deque is accomplished * through the returned deque. * * <p>It is imperative that the user manually synchronize on the returned deque when accessing any * of the deque's iterators: * * <pre>{@code * Deque<E> deque = Queues.synchronizedDeque(Queues.<E>newArrayDeque()); * ... * deque.add(element); // Needn't be in synchronized block * ... * synchronized (deque) { // Must synchronize on deque! * Iterator<E> i = deque.iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * } * }</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned deque will be serializable if the specified deque is serializable. * * @param deque the deque to be wrapped in a synchronized view * @return a synchronized view of the specified deque * @since 15.0 */ public static <E extends @Nullable Object> Deque<E> synchronizedDeque(Deque<E> deque) { return Synchronized.deque(deque, null); } }
google/guava
guava/src/com/google/common/collect/Queues.java
371
/* * Copyright (C) 2014 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.graph; import com.google.common.annotations.Beta; import com.google.errorprone.annotations.DoNotMock; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; /** * An interface for <a * href="https://en.wikipedia.org/wiki/Graph_(discrete_mathematics)">graph</a>-structured data, * whose edges are unique objects. * * <p>A graph is composed of a set of nodes and a set of edges connecting pairs of nodes. * * <p>There are three primary interfaces provided to represent graphs. In order of increasing * complexity they are: {@link Graph}, {@link ValueGraph}, and {@link Network}. You should generally * prefer the simplest interface that satisfies your use case. See the <a * href="https://github.com/google/guava/wiki/GraphsExplained#choosing-the-right-graph-type"> * "Choosing the right graph type"</a> section of the Guava User Guide for more details. * * <h3>Capabilities</h3> * * <p>{@code Network} supports the following use cases (<a * href="https://github.com/google/guava/wiki/GraphsExplained#definitions">definitions of * terms</a>): * * <ul> * <li>directed graphs * <li>undirected graphs * <li>graphs that do/don't allow parallel edges * <li>graphs that do/don't allow self-loops * <li>graphs whose nodes/edges are insertion-ordered, sorted, or unordered * <li>graphs whose edges are unique objects * </ul> * * <h3>Building a {@code Network}</h3> * * <p>The implementation classes that {@code common.graph} provides are not public, by design. To * create an instance of one of the built-in implementations of {@code Network}, use the {@link * NetworkBuilder} class: * * <pre>{@code * MutableNetwork<Integer, MyEdge> network = NetworkBuilder.directed().build(); * }</pre> * * <p>{@link NetworkBuilder#build()} returns an instance of {@link MutableNetwork}, which is a * subtype of {@code Network} that provides methods for adding and removing nodes and edges. If you * do not need to mutate a network (e.g. if you write a method than runs a read-only algorithm on * the network), you should use the non-mutating {@link Network} interface, or an {@link * ImmutableNetwork}. * * <p>You can create an immutable copy of an existing {@code Network} using {@link * ImmutableNetwork#copyOf(Network)}: * * <pre>{@code * ImmutableNetwork<Integer, MyEdge> immutableGraph = ImmutableNetwork.copyOf(network); * }</pre> * * <p>Instances of {@link ImmutableNetwork} do not implement {@link MutableNetwork} (obviously!) and * are contractually guaranteed to be unmodifiable and thread-safe. * * <p>The Guava User Guide has <a * href="https://github.com/google/guava/wiki/GraphsExplained#building-graph-instances">more * information on (and examples of) building graphs</a>. * * <h3>Additional documentation</h3> * * <p>See the Guava User Guide for the {@code common.graph} package (<a * href="https://github.com/google/guava/wiki/GraphsExplained">"Graphs Explained"</a>) for * additional documentation, including: * * <ul> * <li><a * href="https://github.com/google/guava/wiki/GraphsExplained#equals-hashcode-and-graph-equivalence"> * {@code equals()}, {@code hashCode()}, and graph equivalence</a> * <li><a href="https://github.com/google/guava/wiki/GraphsExplained#synchronization"> * Synchronization policy</a> * <li><a href="https://github.com/google/guava/wiki/GraphsExplained#notes-for-implementors">Notes * for implementors</a> * </ul> * * @author James Sexton * @author Joshua O'Madadhain * @param <N> Node parameter type * @param <E> Edge parameter type * @since 20.0 */ @Beta @DoNotMock("Use NetworkBuilder to create a real instance") @ElementTypesAreNonnullByDefault public interface Network<N, E> extends SuccessorsFunction<N>, PredecessorsFunction<N> { // // Network-level accessors // /** Returns all nodes in this network, in the order specified by {@link #nodeOrder()}. */ Set<N> nodes(); /** Returns all edges in this network, in the order specified by {@link #edgeOrder()}. */ Set<E> edges(); /** * Returns a live view of this network as a {@link Graph}. The resulting {@link Graph} will have * an edge connecting node A to node B if this {@link Network} has an edge connecting A to B. * * <p>If this network {@link #allowsParallelEdges() allows parallel edges}, parallel edges will be * treated as if collapsed into a single edge. For example, the {@link #degree(Object)} of a node * in the {@link Graph} view may be less than the degree of the same node in this {@link Network}. */ Graph<N> asGraph(); // // Network properties // /** * Returns true if the edges in this network are directed. Directed edges connect a {@link * EndpointPair#source() source node} to a {@link EndpointPair#target() target node}, while * undirected edges connect a pair of nodes to each other. */ boolean isDirected(); /** * Returns true if this network allows parallel edges. Attempting to add a parallel edge to a * network that does not allow them will throw an {@link IllegalArgumentException}. */ boolean allowsParallelEdges(); /** * Returns true if this network allows self-loops (edges that connect a node to itself). * Attempting to add a self-loop to a network that does not allow them will throw an {@link * IllegalArgumentException}. */ boolean allowsSelfLoops(); /** Returns the order of iteration for the elements of {@link #nodes()}. */ ElementOrder<N> nodeOrder(); /** Returns the order of iteration for the elements of {@link #edges()}. */ ElementOrder<E> edgeOrder(); // // Element-level accessors // /** * Returns a live view of the nodes which have an incident edge in common with {@code node} in * this graph. * * <p>This is equal to the union of {@link #predecessors(Object)} and {@link #successors(Object)}. * * <p>If {@code node} is removed from the network after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the network after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this network */ Set<N> adjacentNodes(N node); /** * Returns a live view of all nodes in this network adjacent to {@code node} which can be reached * by traversing {@code node}'s incoming edges <i>against</i> the direction (if any) of the edge. * * <p>In an undirected network, this is equivalent to {@link #adjacentNodes(Object)}. * * <p>If {@code node} is removed from the network after this method is called, the `Set` returned * by this method will be invalidated, and will throw `IllegalStateException` if it is accessed in * any way. * * @throws IllegalArgumentException if {@code node} is not an element of this network */ @Override Set<N> predecessors(N node); /** * Returns a live view of all nodes in this network adjacent to {@code node} which can be reached * by traversing {@code node}'s outgoing edges in the direction (if any) of the edge. * * <p>In an undirected network, this is equivalent to {@link #adjacentNodes(Object)}. * * <p>This is <i>not</i> the same as "all nodes reachable from {@code node} by following outgoing * edges". For that functionality, see {@link Graphs#reachableNodes(Graph, Object)}. * * <p>If {@code node} is removed from the network after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the network after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this network */ @Override Set<N> successors(N node); /** * Returns a live view of the edges whose {@link #incidentNodes(Object) incident nodes} in this * network include {@code node}. * * <p>This is equal to the union of {@link #inEdges(Object)} and {@link #outEdges(Object)}. * * <p>If {@code node} is removed from the network after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the network after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this network * @since 24.0 */ Set<E> incidentEdges(N node); /** * Returns a live view of all edges in this network which can be traversed in the direction (if * any) of the edge to end at {@code node}. * * <p>In a directed network, an incoming edge's {@link EndpointPair#target()} equals {@code node}. * * <p>In an undirected network, this is equivalent to {@link #incidentEdges(Object)}. * * <p>If {@code node} is removed from the network after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the network after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this network */ Set<E> inEdges(N node); /** * Returns a live view of all edges in this network which can be traversed in the direction (if * any) of the edge starting from {@code node}. * * <p>In a directed network, an outgoing edge's {@link EndpointPair#source()} equals {@code node}. * * <p>In an undirected network, this is equivalent to {@link #incidentEdges(Object)}. * * <p>If {@code node} is removed from the network after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code node} is re-added to the network after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code node} is not an element of this network */ Set<E> outEdges(N node); /** * Returns the count of {@code node}'s {@link #incidentEdges(Object) incident edges}, counting * self-loops twice (equivalently, the number of times an edge touches {@code node}). * * <p>For directed networks, this is equal to {@code inDegree(node) + outDegree(node)}. * * <p>For undirected networks, this is equal to {@code incidentEdges(node).size()} + (number of * self-loops incident to {@code node}). * * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}. * * @throws IllegalArgumentException if {@code node} is not an element of this network */ int degree(N node); /** * Returns the count of {@code node}'s {@link #inEdges(Object) incoming edges} in a directed * network. In an undirected network, returns the {@link #degree(Object)}. * * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}. * * @throws IllegalArgumentException if {@code node} is not an element of this network */ int inDegree(N node); /** * Returns the count of {@code node}'s {@link #outEdges(Object) outgoing edges} in a directed * network. In an undirected network, returns the {@link #degree(Object)}. * * <p>If the count is greater than {@code Integer.MAX_VALUE}, returns {@code Integer.MAX_VALUE}. * * @throws IllegalArgumentException if {@code node} is not an element of this network */ int outDegree(N node); /** * Returns the nodes which are the endpoints of {@code edge} in this network. * * @throws IllegalArgumentException if {@code edge} is not an element of this network */ EndpointPair<N> incidentNodes(E edge); /** * Returns a live view of the edges which have an {@link #incidentNodes(Object) incident node} in * common with {@code edge}. An edge is not considered adjacent to itself. * * <p>If {@code edge} is removed from the network after this method is called, the {@code Set} * {@code view} returned by this method will be invalidated, and will throw {@code * IllegalStateException} if it is accessed in any way, with the following exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code edge} is re-added to the network after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code edge} is not an element of this network */ Set<E> adjacentEdges(E edge); /** * Returns a live view of the set of edges that each directly connect {@code nodeU} to {@code * nodeV}. * * <p>In an undirected network, this is equal to {@code edgesConnecting(nodeV, nodeU)}. * * <p>The resulting set of edges will be parallel (i.e. have equal {@link * #incidentNodes(Object)}). If this network does not {@link #allowsParallelEdges() allow parallel * edges}, the resulting set will contain at most one edge (equivalent to {@code * edgeConnecting(nodeU, nodeV).asSet()}). * * <p>If either {@code nodeU} or {@code nodeV} are removed from the network after this method is * called, the {@code Set} {@code view} returned by this method will be invalidated, and will * throw {@code IllegalStateException} if it is accessed in any way, with the following * exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if {@code nodeU} or {@code nodeV} are re-added to the network after having been removed, * {@code view}'s behavior is undefined * </ul> * * @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this * network */ Set<E> edgesConnecting(N nodeU, N nodeV); /** * Returns a live view of the set of edges that each directly connect {@code endpoints} (in the * order, if any, specified by {@code endpoints}). * * <p>The resulting set of edges will be parallel (i.e. have equal {@link * #incidentNodes(Object)}). If this network does not {@link #allowsParallelEdges() allow parallel * edges}, the resulting set will contain at most one edge (equivalent to {@code * edgeConnecting(endpoints).asSet()}). * * <p>If this network is directed, {@code endpoints} must be ordered. * * <p>If either element of {@code endpoints} is removed from the network after this method is * called, the {@code Set} {@code view} returned by this method will be invalidated, and will * throw {@code IllegalStateException} if it is accessed in any way, with the following * exceptions: * * <ul> * <li>{@code view.equals(view)} evaluates to {@code true} (but any other `equals()` expression * involving {@code view} will throw) * <li>{@code hashCode()} does not throw * <li>if either endpoint is re-added to the network after having been removed, {@code view}'s * behavior is undefined * </ul> * * @throws IllegalArgumentException if either endpoint is not an element of this network * @throws IllegalArgumentException if the endpoints are unordered and the network is directed * @since 27.1 */ Set<E> edgesConnecting(EndpointPair<N> endpoints); /** * Returns the single edge that directly connects {@code nodeU} to {@code nodeV}, if one is * present, or {@code Optional.empty()} if no such edge exists. * * <p>In an undirected network, this is equal to {@code edgeConnecting(nodeV, nodeU)}. * * @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU} * to {@code nodeV} * @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this * network * @since 23.0 */ Optional<E> edgeConnecting(N nodeU, N nodeV); /** * Returns the single edge that directly connects {@code endpoints} (in the order, if any, * specified by {@code endpoints}), if one is present, or {@code Optional.empty()} if no such edge * exists. * * <p>If this network is directed, the endpoints must be ordered. * * @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU} * to {@code nodeV} * @throws IllegalArgumentException if either endpoint is not an element of this network * @throws IllegalArgumentException if the endpoints are unordered and the network is directed * @since 27.1 */ Optional<E> edgeConnecting(EndpointPair<N> endpoints); /** * Returns the single edge that directly connects {@code nodeU} to {@code nodeV}, if one is * present, or {@code null} if no such edge exists. * * <p>In an undirected network, this is equal to {@code edgeConnectingOrNull(nodeV, nodeU)}. * * @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU} * to {@code nodeV} * @throws IllegalArgumentException if {@code nodeU} or {@code nodeV} is not an element of this * network * @since 23.0 */ @CheckForNull E edgeConnectingOrNull(N nodeU, N nodeV); /** * Returns the single edge that directly connects {@code endpoints} (in the order, if any, * specified by {@code endpoints}), if one is present, or {@code null} if no such edge exists. * * <p>If this network is directed, the endpoints must be ordered. * * @throws IllegalArgumentException if there are multiple parallel edges connecting {@code nodeU} * to {@code nodeV} * @throws IllegalArgumentException if either endpoint is not an element of this network * @throws IllegalArgumentException if the endpoints are unordered and the network is directed * @since 27.1 */ @CheckForNull E edgeConnectingOrNull(EndpointPair<N> endpoints); /** * Returns true if there is an edge that directly connects {@code nodeU} to {@code nodeV}. This is * equivalent to {@code nodes().contains(nodeU) && successors(nodeU).contains(nodeV)}, and to * {@code edgeConnectingOrNull(nodeU, nodeV) != null}. * * <p>In an undirected network, this is equal to {@code hasEdgeConnecting(nodeV, nodeU)}. * * @since 23.0 */ boolean hasEdgeConnecting(N nodeU, N nodeV); /** * Returns true if there is an edge that directly connects {@code endpoints} (in the order, if * any, specified by {@code endpoints}). * * <p>Unlike the other {@code EndpointPair}-accepting methods, this method does not throw if the * endpoints are unordered and the network is directed; it simply returns {@code false}. This is * for consistency with {@link Graph#hasEdgeConnecting(EndpointPair)} and {@link * ValueGraph#hasEdgeConnecting(EndpointPair)}. * * @since 27.1 */ boolean hasEdgeConnecting(EndpointPair<N> endpoints); // // Network identity // /** * Returns {@code true} iff {@code object} is a {@link Network} that has the same elements and the * same structural relationships as those in this network. * * <p>Thus, two networks A and B are equal if <b>all</b> of the following are true: * * <ul> * <li>A and B have equal {@link #isDirected() directedness}. * <li>A and B have equal {@link #nodes() node sets}. * <li>A and B have equal {@link #edges() edge sets}. * <li>Every edge in A and B connects the same nodes in the same direction (if any). * </ul> * * <p>Network properties besides {@link #isDirected() directedness} do <b>not</b> affect equality. * For example, two networks may be considered equal even if one allows parallel edges and the * other doesn't. Additionally, the order in which nodes or edges are added to the network, and * the order in which they are iterated over, are irrelevant. * * <p>A reference implementation of this is provided by {@link AbstractNetwork#equals(Object)}. */ @Override boolean equals(@CheckForNull Object object); /** * Returns the hash code for this network. The hash code of a network is defined as the hash code * of a map from each of its {@link #edges() edges} to their {@link #incidentNodes(Object) * incident nodes}. * * <p>A reference implementation of this is provided by {@link AbstractNetwork#hashCode()}. */ @Override int hashCode(); }
google/guava
guava/src/com/google/common/graph/Network.java
372
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.bridge; /** * Weapon. */ public interface Weapon { void wield(); void swing(); void unwield(); Enchantment getEnchantment(); }
smedals/java-design-patterns
bridge/src/main/java/com/iluwatar/bridge/Weapon.java
373
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.observer; import java.util.ArrayList; import java.util.List; import lombok.extern.slf4j.Slf4j; /** * Weather can be observed by implementing {@link WeatherObserver} interface and registering as * listener. */ @Slf4j public class Weather { private WeatherType currentWeather; private final List<WeatherObserver> observers; public Weather() { observers = new ArrayList<>(); currentWeather = WeatherType.SUNNY; } public void addObserver(WeatherObserver obs) { observers.add(obs); } public void removeObserver(WeatherObserver obs) { observers.remove(obs); } /** * Makes time pass for weather. */ public void timePasses() { var enumValues = WeatherType.values(); currentWeather = enumValues[(currentWeather.ordinal() + 1) % enumValues.length]; LOGGER.info("The weather changed to {}.", currentWeather); notifyObservers(); } private void notifyObservers() { for (var obs : observers) { obs.update(currentWeather); } } }
smedals/java-design-patterns
observer/src/main/java/com/iluwatar/observer/Weather.java
374
/* * 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.collect; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.J2ktIncompatible; import java.util.Arrays; import java.util.Map; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import org.checkerframework.checker.nullness.qual.Nullable; /** * Methods factored out so that they can be emulated differently in GWT. * * @author Hayward Chan */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault final class Platform { /** Returns the platform preferred implementation of a map based on a hash table. */ static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> newHashMapWithExpectedSize(int expectedSize) { return Maps.newHashMapWithExpectedSize(expectedSize); } /** * Returns the platform preferred implementation of an insertion ordered map based on a hash * table. */ static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> newLinkedHashMapWithExpectedSize(int expectedSize) { return Maps.newLinkedHashMapWithExpectedSize(expectedSize); } /** Returns the platform preferred implementation of a set based on a hash table. */ static <E extends @Nullable Object> Set<E> newHashSetWithExpectedSize(int expectedSize) { return Sets.newHashSetWithExpectedSize(expectedSize); } /** Returns the platform preferred implementation of a thread-safe hash set. */ static <E> Set<E> newConcurrentHashSet() { return ConcurrentHashMap.newKeySet(); } /** * Returns the platform preferred implementation of an insertion ordered set based on a hash * table. */ static <E extends @Nullable Object> Set<E> newLinkedHashSetWithExpectedSize(int expectedSize) { return Sets.newLinkedHashSetWithExpectedSize(expectedSize); } /** * Returns the platform preferred map implementation that preserves insertion order when used only * for insertions. */ static <K extends @Nullable Object, V extends @Nullable Object> Map<K, V> preservesInsertionOrderOnPutsMap() { return Maps.newLinkedHashMap(); } /** * Returns the platform preferred set implementation that preserves insertion order when used only * for insertions. */ static <E extends @Nullable Object> Set<E> preservesInsertionOrderOnAddsSet() { return CompactHashSet.create(); } /** * Returns a new array of the given length with the same type as a reference array. * * @param reference any array of the desired type * @param length the length of the new array */ /* * The new array contains nulls, even if the old array did not. If we wanted to be accurate, we * would declare a return type of `@Nullable T[]`. However, we've decided not to think too hard * about arrays for now, as they're a mess. (We previously discussed this in the review of * ObjectArrays, which is the main caller of this method.) */ static <T extends @Nullable Object> T[] newArray(T[] reference, int length) { T[] empty = reference.length == 0 ? reference : Arrays.copyOf(reference, 0); return Arrays.copyOf(empty, length); } /** Equivalent to Arrays.copyOfRange(source, from, to, arrayOfType.getClass()). */ /* * Arrays are a mess from a nullness perspective, and Class instances for object-array types are * even worse. For now, we just suppress and move on with our lives. * * - https://github.com/jspecify/jspecify/issues/65 * * - https://github.com/jspecify/jdk/commit/71d826792b8c7ef95d492c50a274deab938f2552 */ /* * TODO(cpovirk): Is the unchecked cast avoidable? Would System.arraycopy be similarly fast (if * likewise not type-checked)? Could our single caller do something different? */ @SuppressWarnings({"nullness", "unchecked"}) static <T extends @Nullable Object> T[] copy(Object[] source, int from, int to, T[] arrayOfType) { return Arrays.copyOfRange(source, from, to, (Class<? extends T[]>) arrayOfType.getClass()); } /** * Configures the given map maker to use weak keys, if possible; does nothing otherwise (i.e., in * GWT). This is sometimes acceptable, when only server-side code could generate enough volume * that reclamation becomes important. */ @J2ktIncompatible static MapMaker tryWeakKeys(MapMaker mapMaker) { return mapMaker.weakKeys(); } static <E extends Enum<E>> Class<E> getDeclaringClassOrObjectForJ2cl(E e) { return e.getDeclaringClass(); } static int reduceIterationsIfGwt(int iterations) { return iterations; } static int reduceExponentIfGwt(int exponent) { return exponent; } private Platform() {} }
google/guava
guava/src/com/google/common/collect/Platform.java
375
/* * @notice * Copyright 2012 Jeff Hain * * 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. * * ============================================================================= * Notice of fdlibm package this program is partially derived from: * * Copyright (C) 1993 by Sun Microsystems, Inc. All rights reserved. * * Developed at SunSoft, a Sun Microsystems, Inc. business. * Permission to use, copy, modify, and distribute this * software is freely granted, provided that this notice * is preserved. * ============================================================================= * * This code sourced from: * https://github.com/jeffhain/jafama/blob/d7d2a7659e96e148d827acc24cf385b872cda365/src/main/java/net/jafama/FastMath.java */ package org.elasticsearch.h3; /** * This file is forked from https://github.com/jeffhain/jafama. In particular, it forks the following file: * https://github.com/jeffhain/jafama/blob/master/src/main/java/net/jafama/FastMath.java * * It modifies the original implementation by removing not needed methods leaving the following trigonometric function: * <ul> * <li>{@link #cos(double)}</li> * <li>{@link #sin(double)}</li> * <li>{@link #tan(double)}</li> * <li>{@link #acos(double)}</li> * <li>{@link #asin(double)}</li> * <li>{@link #atan(double)}</li> * <li>{@link #atan2(double, double)}</li> * </ul> */ final class FastMath { /* * For trigonometric functions, use of look-up tables and Taylor-Lagrange formula * with 4 derivatives (more take longer to compute and don't add much accuracy, * less require larger tables (which use more memory, take more time to initialize, * and are slower to access (at least on the machine they were developed on))). * * For angles reduction of cos/sin/tan functions: * - for small values, instead of reducing angles, and then computing the best index * for look-up tables, we compute this index right away, and use it for reduction, * - for large values, treatments derived from fdlibm package are used, as done in * java.lang.Math. They are faster but still "slow", so if you work with * large numbers and need speed over accuracy for them, you might want to use * normalizeXXXFast treatments before your function, or modify cos/sin/tan * so that they call the fast normalization treatments instead of the accurate ones. * NB: If an angle is huge (like PI*1e20), in double precision format its last digits * are zeros, which most likely is not the case for the intended value, and doing * an accurate reduction on a very inaccurate value is most likely pointless. * But it gives some sort of coherence that could be needed in some cases. * * Multiplication on double appears to be about as fast (or not much slower) than call * to <double_array>[<index>], and regrouping some doubles in a private class, to use * index only once, does not seem to speed things up, so: * - for uniformly tabulated values, to retrieve the parameter corresponding to * an index, we recompute it rather than using an array to store it, * - for cos/sin, we recompute derivatives divided by (multiplied by inverse of) * factorial each time, rather than storing them in arrays. * * Lengths of look-up tables are usually of the form 2^n+1, for their values to be * of the form (<a_constant> * k/2^n, k in 0 .. 2^n), so that particular values * (PI/2, etc.) are "exactly" computed, as well as for other reasons. * * Most math treatments I could find on the web, including "fast" ones, * usually take care of special cases (NaN, etc.) at the beginning, and * then deal with the general case, which adds a useless overhead for the * general (and common) case. In this class, special cases are only dealt * with when needed, and if the general case does not already handle them. */ // -------------------------------------------------------------------------- // GENERAL CONSTANTS // -------------------------------------------------------------------------- private static final double ONE_DIV_F2 = 1 / 2.0; private static final double ONE_DIV_F3 = 1 / 6.0; private static final double ONE_DIV_F4 = 1 / 24.0; private static final double TWO_POW_24 = Double.longBitsToDouble(0x4170000000000000L); private static final double TWO_POW_N24 = Double.longBitsToDouble(0x3E70000000000000L); private static final double TWO_POW_66 = Double.longBitsToDouble(0x4410000000000000L); private static final int MIN_DOUBLE_EXPONENT = -1074; private static final int MAX_DOUBLE_EXPONENT = 1023; // -------------------------------------------------------------------------- // CONSTANTS FOR NORMALIZATIONS // -------------------------------------------------------------------------- /* * Table of constants for 1/(2*PI), 282 Hex digits (enough for normalizing doubles). * 1/(2*PI) approximation = sum of ONE_OVER_TWOPI_TAB[i]*2^(-24*(i+1)). */ private static final double[] ONE_OVER_TWOPI_TAB = { 0x28BE60, 0xDB9391, 0x054A7F, 0x09D5F4, 0x7D4D37, 0x7036D8, 0xA5664F, 0x10E410, 0x7F9458, 0xEAF7AE, 0xF1586D, 0xC91B8E, 0x909374, 0xB80192, 0x4BBA82, 0x746487, 0x3F877A, 0xC72C4A, 0x69CFBA, 0x208D7D, 0x4BAED1, 0x213A67, 0x1C09AD, 0x17DF90, 0x4E6475, 0x8E60D4, 0xCE7D27, 0x2117E2, 0xEF7E4A, 0x0EC7FE, 0x25FFF7, 0x816603, 0xFBCBC4, 0x62D682, 0x9B47DB, 0x4D9FB3, 0xC9F2C2, 0x6DD3D1, 0x8FD9A7, 0x97FA8B, 0x5D49EE, 0xB1FAF9, 0x7C5ECF, 0x41CE7D, 0xE294A4, 0xBA9AFE, 0xD7EC47 }; /* * Constants for 2*PI. Only the 23 most significant bits of each mantissa are used. * 2*PI approximation = sum of TWOPI_TAB<i>. */ private static final double TWOPI_TAB0 = Double.longBitsToDouble(0x401921FB40000000L); private static final double TWOPI_TAB1 = Double.longBitsToDouble(0x3E94442D00000000L); private static final double TWOPI_TAB2 = Double.longBitsToDouble(0x3D18469880000000L); private static final double TWOPI_TAB3 = Double.longBitsToDouble(0x3B98CC5160000000L); private static final double TWOPI_TAB4 = Double.longBitsToDouble(0x3A101B8380000000L); private static final double INVPIO2 = Double.longBitsToDouble(0x3FE45F306DC9C883L); // 6.36619772367581382433e-01 53 bits of 2/pi private static final double PIO2_HI = Double.longBitsToDouble(0x3FF921FB54400000L); // 1.57079632673412561417e+00 first 33 bits of pi/2 private static final double PIO2_LO = Double.longBitsToDouble(0x3DD0B4611A626331L); // 6.07710050650619224932e-11 pi/2 - PIO2_HI private static final double INVTWOPI = INVPIO2 / 4; private static final double TWOPI_HI = 4 * PIO2_HI; private static final double TWOPI_LO = 4 * PIO2_LO; // fdlibm uses 2^19*PI/2 here, but we normalize with % 2*PI instead of % PI/2, // and we can bear some more error. private static final double NORMALIZE_ANGLE_MAX_MEDIUM_DOUBLE = StrictMath.pow(2, 20) * (2 * Math.PI); // -------------------------------------------------------------------------- // CONSTANTS AND TABLES FOR COS, SIN // -------------------------------------------------------------------------- private static final int SIN_COS_TABS_SIZE = (1 << getTabSizePower(11)) + 1; private static final double SIN_COS_DELTA_HI = TWOPI_HI / (SIN_COS_TABS_SIZE - 1); private static final double SIN_COS_DELTA_LO = TWOPI_LO / (SIN_COS_TABS_SIZE - 1); private static final double SIN_COS_INDEXER = 1 / (SIN_COS_DELTA_HI + SIN_COS_DELTA_LO); private static final double[] sinTab = new double[SIN_COS_TABS_SIZE]; private static final double[] cosTab = new double[SIN_COS_TABS_SIZE]; // Max abs value for fast modulo, above which we use regular angle normalization. // This value must be < (Integer.MAX_VALUE / SIN_COS_INDEXER), to stay in range of int type. // The higher it is, the higher the error, but also the faster it is for lower values. // If you set it to ((Integer.MAX_VALUE / SIN_COS_INDEXER) * 0.99), worse accuracy on double range is about 1e-10. private static final double SIN_COS_MAX_VALUE_FOR_INT_MODULO = ((Integer.MAX_VALUE >> 9) / SIN_COS_INDEXER) * 0.99; // -------------------------------------------------------------------------- // CONSTANTS AND TABLES FOR TAN // -------------------------------------------------------------------------- // We use the following formula: // 1) tan(-x) = -tan(x) // 2) tan(x) = 1/tan(PI/2-x) // ---> we only have to compute tan(x) on [0,A] with PI/4<=A<PI/2. // We use indexing past look-up tables, so that indexing information // allows for fast recomputation of angle in [0,PI/2] range. private static final int TAN_VIRTUAL_TABS_SIZE = (1 << getTabSizePower(12)) + 1; // Must be >= 45deg, and supposed to be >= 51.4deg, as fdlibm code is not // supposed to work with values inferior to that (51.4deg is about // (PI/2-Double.longBitsToDouble(0x3FE5942800000000L))). private static final double TAN_MAX_VALUE_FOR_TABS = Math.toRadians(77.0); private static final int TAN_TABS_SIZE = (int) ((TAN_MAX_VALUE_FOR_TABS / (Math.PI / 2)) * (TAN_VIRTUAL_TABS_SIZE - 1)) + 1; private static final double TAN_DELTA_HI = PIO2_HI / (TAN_VIRTUAL_TABS_SIZE - 1); private static final double TAN_DELTA_LO = PIO2_LO / (TAN_VIRTUAL_TABS_SIZE - 1); private static final double TAN_INDEXER = 1 / (TAN_DELTA_HI + TAN_DELTA_LO); private static final double[] tanTab = new double[TAN_TABS_SIZE]; private static final double[] tanDer1DivF1Tab = new double[TAN_TABS_SIZE]; private static final double[] tanDer2DivF2Tab = new double[TAN_TABS_SIZE]; private static final double[] tanDer3DivF3Tab = new double[TAN_TABS_SIZE]; private static final double[] tanDer4DivF4Tab = new double[TAN_TABS_SIZE]; // Max abs value for fast modulo, above which we use regular angle normalization. // This value must be < (Integer.MAX_VALUE / TAN_INDEXER), to stay in range of int type. // The higher it is, the higher the error, but also the faster it is for lower values. private static final double TAN_MAX_VALUE_FOR_INT_MODULO = (((Integer.MAX_VALUE >> 9) / TAN_INDEXER) * 0.99); // -------------------------------------------------------------------------- // CONSTANTS AND TABLES FOR ACOS, ASIN // -------------------------------------------------------------------------- // We use the following formula: // 1) acos(x) = PI/2 - asin(x) // 2) asin(-x) = -asin(x) // ---> we only have to compute asin(x) on [0,1]. // For values not close to +-1, we use look-up tables; // for values near +-1, we use code derived from fdlibm. // Supposed to be >= sin(77.2deg), as fdlibm code is supposed to work with values > 0.975, // but seems to work well enough as long as value >= sin(25deg). private static final double ASIN_MAX_VALUE_FOR_TABS = StrictMath.sin(Math.toRadians(73.0)); private static final int ASIN_TABS_SIZE = (1 << getTabSizePower(13)) + 1; private static final double ASIN_DELTA = ASIN_MAX_VALUE_FOR_TABS / (ASIN_TABS_SIZE - 1); private static final double ASIN_INDEXER = 1 / ASIN_DELTA; private static final double[] asinTab = new double[ASIN_TABS_SIZE]; private static final double[] asinDer1DivF1Tab = new double[ASIN_TABS_SIZE]; private static final double[] asinDer2DivF2Tab = new double[ASIN_TABS_SIZE]; private static final double[] asinDer3DivF3Tab = new double[ASIN_TABS_SIZE]; private static final double[] asinDer4DivF4Tab = new double[ASIN_TABS_SIZE]; private static final double ASIN_MAX_VALUE_FOR_POWTABS = StrictMath.sin(Math.toRadians(88.6)); private static final int ASIN_POWTABS_POWER = 84; private static final double ASIN_POWTABS_ONE_DIV_MAX_VALUE = 1 / ASIN_MAX_VALUE_FOR_POWTABS; private static final int ASIN_POWTABS_SIZE = (1 << getTabSizePower(12)) + 1; private static final int ASIN_POWTABS_SIZE_MINUS_ONE = ASIN_POWTABS_SIZE - 1; private static final double[] asinParamPowTab = new double[ASIN_POWTABS_SIZE]; private static final double[] asinPowTab = new double[ASIN_POWTABS_SIZE]; private static final double[] asinDer1DivF1PowTab = new double[ASIN_POWTABS_SIZE]; private static final double[] asinDer2DivF2PowTab = new double[ASIN_POWTABS_SIZE]; private static final double[] asinDer3DivF3PowTab = new double[ASIN_POWTABS_SIZE]; private static final double[] asinDer4DivF4PowTab = new double[ASIN_POWTABS_SIZE]; private static final double ASIN_PIO2_HI = Double.longBitsToDouble(0x3FF921FB54442D18L); // 1.57079632679489655800e+00 private static final double ASIN_PIO2_LO = Double.longBitsToDouble(0x3C91A62633145C07L); // 6.12323399573676603587e-17 private static final double ASIN_PS0 = Double.longBitsToDouble(0x3fc5555555555555L); // 1.66666666666666657415e-01 private static final double ASIN_PS1 = Double.longBitsToDouble(0xbfd4d61203eb6f7dL); // -3.25565818622400915405e-01 private static final double ASIN_PS2 = Double.longBitsToDouble(0x3fc9c1550e884455L); // 2.01212532134862925881e-01 private static final double ASIN_PS3 = Double.longBitsToDouble(0xbfa48228b5688f3bL); // -4.00555345006794114027e-02 private static final double ASIN_PS4 = Double.longBitsToDouble(0x3f49efe07501b288L); // 7.91534994289814532176e-04 private static final double ASIN_PS5 = Double.longBitsToDouble(0x3f023de10dfdf709L); // 3.47933107596021167570e-05 private static final double ASIN_QS1 = Double.longBitsToDouble(0xc0033a271c8a2d4bL); // -2.40339491173441421878e+00 private static final double ASIN_QS2 = Double.longBitsToDouble(0x40002ae59c598ac8L); // 2.02094576023350569471e+00 private static final double ASIN_QS3 = Double.longBitsToDouble(0xbfe6066c1b8d0159L); // -6.88283971605453293030e-01 private static final double ASIN_QS4 = Double.longBitsToDouble(0x3fb3b8c5b12e9282L); // 7.70381505559019352791e-02 // -------------------------------------------------------------------------- // CONSTANTS AND TABLES FOR ATAN // -------------------------------------------------------------------------- // We use the formula atan(-x) = -atan(x) // ---> we only have to compute atan(x) on [0,+infinity[. // For values corresponding to angles not close to +-PI/2, we use look-up tables; // for values corresponding to angles near +-PI/2, we use code derived from fdlibm. // Supposed to be >= tan(67.7deg), as fdlibm code is supposed to work with values > 2.4375. private static final double ATAN_MAX_VALUE_FOR_TABS = StrictMath.tan(Math.toRadians(74.0)); private static final int ATAN_TABS_SIZE = (1 << getTabSizePower(12)) + 1; private static final double ATAN_DELTA = ATAN_MAX_VALUE_FOR_TABS / (ATAN_TABS_SIZE - 1); private static final double ATAN_INDEXER = 1 / ATAN_DELTA; private static final double[] atanTab = new double[ATAN_TABS_SIZE]; private static final double[] atanDer1DivF1Tab = new double[ATAN_TABS_SIZE]; private static final double[] atanDer2DivF2Tab = new double[ATAN_TABS_SIZE]; private static final double[] atanDer3DivF3Tab = new double[ATAN_TABS_SIZE]; private static final double[] atanDer4DivF4Tab = new double[ATAN_TABS_SIZE]; private static final double ATAN_HI3 = Double.longBitsToDouble(0x3ff921fb54442d18L); // 1.57079632679489655800e+00 atan(inf)hi private static final double ATAN_LO3 = Double.longBitsToDouble(0x3c91a62633145c07L); // 6.12323399573676603587e-17 atan(inf)lo private static final double ATAN_AT0 = Double.longBitsToDouble(0x3fd555555555550dL); // 3.33333333333329318027e-01 private static final double ATAN_AT1 = Double.longBitsToDouble(0xbfc999999998ebc4L); // -1.99999999998764832476e-01 private static final double ATAN_AT2 = Double.longBitsToDouble(0x3fc24924920083ffL); // 1.42857142725034663711e-01 private static final double ATAN_AT3 = Double.longBitsToDouble(0xbfbc71c6fe231671L); // -1.11111104054623557880e-01 private static final double ATAN_AT4 = Double.longBitsToDouble(0x3fb745cdc54c206eL); // 9.09088713343650656196e-02 private static final double ATAN_AT5 = Double.longBitsToDouble(0xbfb3b0f2af749a6dL); // -7.69187620504482999495e-02 private static final double ATAN_AT6 = Double.longBitsToDouble(0x3fb10d66a0d03d51L); // 6.66107313738753120669e-02 private static final double ATAN_AT7 = Double.longBitsToDouble(0xbfadde2d52defd9aL); // -5.83357013379057348645e-02 private static final double ATAN_AT8 = Double.longBitsToDouble(0x3fa97b4b24760debL); // 4.97687799461593236017e-02 private static final double ATAN_AT9 = Double.longBitsToDouble(0xbfa2b4442c6a6c2fL); // -3.65315727442169155270e-02 private static final double ATAN_AT10 = Double.longBitsToDouble(0x3f90ad3ae322da11L); // 1.62858201153657823623e-02 // -------------------------------------------------------------------------- // TABLE FOR POWERS OF TWO // -------------------------------------------------------------------------- private static final double[] twoPowTab = new double[(MAX_DOUBLE_EXPONENT - MIN_DOUBLE_EXPONENT) + 1]; // -------------------------------------------------------------------------- // PUBLIC TREATMENTS // -------------------------------------------------------------------------- /** * @param angle Angle in radians. * @return Angle cosine. */ public static double cos(double angle) { angle = Math.abs(angle); if (angle > SIN_COS_MAX_VALUE_FOR_INT_MODULO) { // Faster than using normalizeZeroTwoPi. angle = remainderTwoPi(angle); if (angle < 0.0) { angle += 2 * Math.PI; } } // index: possibly outside tables range. int index = (int) (angle * SIN_COS_INDEXER + 0.5); double delta = (angle - index * SIN_COS_DELTA_HI) - index * SIN_COS_DELTA_LO; // Making sure index is within tables range. // Last value of each table is the same than first, so we ignore it (tabs size minus one) for modulo. index &= (SIN_COS_TABS_SIZE - 2); // index % (SIN_COS_TABS_SIZE-1) double indexCos = cosTab[index]; double indexSin = sinTab[index]; return indexCos + delta * (-indexSin + delta * (-indexCos * ONE_DIV_F2 + delta * (indexSin * ONE_DIV_F3 + delta * indexCos * ONE_DIV_F4))); } /** * @param angle Angle in radians. * @return Angle sine. */ public static double sin(double angle) { boolean negateResult; if (angle < 0.0) { angle = -angle; negateResult = true; } else { negateResult = false; } if (angle > SIN_COS_MAX_VALUE_FOR_INT_MODULO) { // Faster than using normalizeZeroTwoPi. angle = remainderTwoPi(angle); if (angle < 0.0) { angle += 2 * Math.PI; } } int index = (int) (angle * SIN_COS_INDEXER + 0.5); double delta = (angle - index * SIN_COS_DELTA_HI) - index * SIN_COS_DELTA_LO; index &= (SIN_COS_TABS_SIZE - 2); // index % (SIN_COS_TABS_SIZE-1) double indexSin = sinTab[index]; double indexCos = cosTab[index]; double result = indexSin + delta * (indexCos + delta * (-indexSin * ONE_DIV_F2 + delta * (-indexCos * ONE_DIV_F3 + delta * indexSin * ONE_DIV_F4))); return negateResult ? -result : result; } /** * @param angle Angle in radians. * @return Angle tangent. */ public static double tan(double angle) { if (Math.abs(angle) > TAN_MAX_VALUE_FOR_INT_MODULO) { // Faster than using normalizeMinusHalfPiHalfPi. angle = remainderTwoPi(angle); if (angle < -Math.PI / 2) { angle += Math.PI; } else if (angle > Math.PI / 2) { angle -= Math.PI; } } boolean negateResult; if (angle < 0.0) { angle = -angle; negateResult = true; } else { negateResult = false; } int index = (int) (angle * TAN_INDEXER + 0.5); double delta = (angle - index * TAN_DELTA_HI) - index * TAN_DELTA_LO; // index modulo PI, i.e. 2*(virtual tab size minus one). index &= (2 * (TAN_VIRTUAL_TABS_SIZE - 1) - 1); // index % (2*(TAN_VIRTUAL_TABS_SIZE-1)) // Here, index is in [0,2*(TAN_VIRTUAL_TABS_SIZE-1)-1], i.e. indicates an angle in [0,PI[. if (index > (TAN_VIRTUAL_TABS_SIZE - 1)) { index = (2 * (TAN_VIRTUAL_TABS_SIZE - 1)) - index; delta = -delta; negateResult = negateResult == false; } double result; if (index < TAN_TABS_SIZE) { result = tanTab[index] + delta * (tanDer1DivF1Tab[index] + delta * (tanDer2DivF2Tab[index] + delta * (tanDer3DivF3Tab[index] + delta * tanDer4DivF4Tab[index]))); } else { // angle in ]TAN_MAX_VALUE_FOR_TABS,TAN_MAX_VALUE_FOR_INT_MODULO], or angle is NaN // Using tan(angle) == 1/tan(PI/2-angle) formula: changing angle (index and delta), and inverting. index = (TAN_VIRTUAL_TABS_SIZE - 1) - index; result = 1 / (tanTab[index] - delta * (tanDer1DivF1Tab[index] - delta * (tanDer2DivF2Tab[index] - delta * (tanDer3DivF3Tab[index] - delta * tanDer4DivF4Tab[index])))); } return negateResult ? -result : result; } /** * @param value Value in [-1,1]. * @return Value arccosine, in radians, in [0,PI]. */ public static double acos(double value) { return Math.PI / 2 - FastMath.asin(value); } /** * @param value Value in [-1,1]. * @return Value arcsine, in radians, in [-PI/2,PI/2]. */ public static double asin(double value) { boolean negateResult; if (value < 0.0) { value = -value; negateResult = true; } else { negateResult = false; } if (value <= ASIN_MAX_VALUE_FOR_TABS) { int index = (int) (value * ASIN_INDEXER + 0.5); double delta = value - index * ASIN_DELTA; double result = asinTab[index] + delta * (asinDer1DivF1Tab[index] + delta * (asinDer2DivF2Tab[index] + delta * (asinDer3DivF3Tab[index] + delta * asinDer4DivF4Tab[index]))); return negateResult ? -result : result; } else if (value <= ASIN_MAX_VALUE_FOR_POWTABS) { int index = (int) (FastMath.powFast(value * ASIN_POWTABS_ONE_DIV_MAX_VALUE, ASIN_POWTABS_POWER) * ASIN_POWTABS_SIZE_MINUS_ONE + 0.5); double delta = value - asinParamPowTab[index]; double result = asinPowTab[index] + delta * (asinDer1DivF1PowTab[index] + delta * (asinDer2DivF2PowTab[index] + delta * (asinDer3DivF3PowTab[index] + delta * asinDer4DivF4PowTab[index]))); return negateResult ? -result : result; } else { // value > ASIN_MAX_VALUE_FOR_TABS, or value is NaN // This part is derived from fdlibm. if (value < 1.0) { double t = (1.0 - value) * 0.5; double p = t * (ASIN_PS0 + t * (ASIN_PS1 + t * (ASIN_PS2 + t * (ASIN_PS3 + t * (ASIN_PS4 + t * ASIN_PS5))))); double q = 1.0 + t * (ASIN_QS1 + t * (ASIN_QS2 + t * (ASIN_QS3 + t * ASIN_QS4))); double s = Math.sqrt(t); double z = s + s * (p / q); double result = ASIN_PIO2_HI - ((z + z) - ASIN_PIO2_LO); return negateResult ? -result : result; } else { // value >= 1.0, or value is NaN if (value == 1.0) { return negateResult ? -Math.PI / 2 : Math.PI / 2; } else { return Double.NaN; } } } } /** * @param value A double value. * @return Value arctangent, in radians, in [-PI/2,PI/2]. */ public static double atan(double value) { boolean negateResult; if (value < 0.0) { value = -value; negateResult = true; } else { negateResult = false; } if (value == 1.0) { // We want "exact" result for 1.0. return negateResult ? -Math.PI / 4 : Math.PI / 4; } else if (value <= ATAN_MAX_VALUE_FOR_TABS) { int index = (int) (value * ATAN_INDEXER + 0.5); double delta = value - index * ATAN_DELTA; double result = atanTab[index] + delta * (atanDer1DivF1Tab[index] + delta * (atanDer2DivF2Tab[index] + delta * (atanDer3DivF3Tab[index] + delta * atanDer4DivF4Tab[index]))); return negateResult ? -result : result; } else { // value > ATAN_MAX_VALUE_FOR_TABS, or value is NaN // This part is derived from fdlibm. if (value < TWO_POW_66) { double x = -1 / value; double x2 = x * x; double x4 = x2 * x2; double s1 = x2 * (ATAN_AT0 + x4 * (ATAN_AT2 + x4 * (ATAN_AT4 + x4 * (ATAN_AT6 + x4 * (ATAN_AT8 + x4 * ATAN_AT10))))); double s2 = x4 * (ATAN_AT1 + x4 * (ATAN_AT3 + x4 * (ATAN_AT5 + x4 * (ATAN_AT7 + x4 * ATAN_AT9)))); double result = ATAN_HI3 - ((x * (s1 + s2) - ATAN_LO3) - x); return negateResult ? -result : result; } else { // value >= 2^66, or value is NaN if (Double.isNaN(value)) { return Double.NaN; } else { return negateResult ? -Math.PI / 2 : Math.PI / 2; } } } } /** * For special values for which multiple conventions could be adopted, behaves like Math.atan2(double,double). * * @param y Coordinate on y axis. * @param x Coordinate on x axis. * @return Angle from x axis positive side to (x,y) position, in radians, in [-PI,PI]. * Angle measure is positive when going from x axis to y axis (positive sides). */ public static double atan2(double y, double x) { if (x > 0.0) { if (y == 0.0) { return (1 / y == Double.NEGATIVE_INFINITY) ? -0.0 : 0.0; } if (x == Double.POSITIVE_INFINITY) { if (y == Double.POSITIVE_INFINITY) { return Math.PI / 4; } else if (y == Double.NEGATIVE_INFINITY) { return -Math.PI / 4; } else if (y > 0.0) { return 0.0; } else if (y < 0.0) { return -0.0; } else { return Double.NaN; } } else { return FastMath.atan(y / x); } } else if (x < 0.0) { if (y == 0.0) { return (1 / y == Double.NEGATIVE_INFINITY) ? -Math.PI : Math.PI; } if (x == Double.NEGATIVE_INFINITY) { if (y == Double.POSITIVE_INFINITY) { return 3 * Math.PI / 4; } else if (y == Double.NEGATIVE_INFINITY) { return -3 * Math.PI / 4; } else if (y > 0.0) { return Math.PI; } else if (y < 0.0) { return -Math.PI; } else { return Double.NaN; } } else if (y > 0.0) { return Math.PI / 2 + FastMath.atan(-x / y); } else if (y < 0.0) { return -Math.PI / 2 - FastMath.atan(x / y); } else { return Double.NaN; } } else if (x == 0.0) { if (y == 0.0) { if (1 / x == Double.NEGATIVE_INFINITY) { return (1 / y == Double.NEGATIVE_INFINITY) ? -Math.PI : Math.PI; } else { return (1 / y == Double.NEGATIVE_INFINITY) ? -0.0 : 0.0; } } if (y > 0.0) { return Math.PI / 2; } else if (y < 0.0) { return -Math.PI / 2; } else { return Double.NaN; } } else { return Double.NaN; } } /** * This treatment is somehow accurate for low values of |power|, * and for |power*getExponent(value)| &lt; 1023 or so (to stay away * from double extreme magnitudes (large and small)). * * @param value A double value. * @param power A power. * @return value^power. */ private static double powFast(double value, int power) { if (power > 5) { // Most common case first. double oddRemains = 1.0; do { // Test if power is odd. if ((power & 1) != 0) { oddRemains *= value; } value *= value; power >>= 1; // power = power / 2 } while (power > 5); // Here, power is in [3,5]: faster to finish outside the loop. if (power == 3) { return oddRemains * value * value * value; } else { double v2 = value * value; if (power == 4) { return oddRemains * v2 * v2; } else { // power == 5 return oddRemains * v2 * v2 * value; } } } else if (power >= 0) { // power in [0,5] if (power < 3) { // power in [0,2] if (power == 2) { // Most common case first. return value * value; } else if (power != 0) { // faster than == 1 return value; } else { // power == 0 return 1.0; } } else { // power in [3,5] if (power == 3) { return value * value * value; } else { // power in [4,5] double v2 = value * value; if (power == 4) { return v2 * v2; } else { // power == 5 return v2 * v2 * value; } } } } else { // power < 0 // Opposite of Integer.MIN_VALUE does not exist as int. if (power == Integer.MIN_VALUE) { // Integer.MAX_VALUE = -(power+1) return 1.0 / (FastMath.powFast(value, Integer.MAX_VALUE) * value); } else { return 1.0 / FastMath.powFast(value, -power); } } } // -------------------------------------------------------------------------- // PRIVATE TREATMENTS // -------------------------------------------------------------------------- /** * FastMath is non-instantiable. */ private FastMath() {} /** * Use look-up tables size power through this method, * to make sure is it small in case java.lang.Math * is directly used. */ private static int getTabSizePower(int tabSizePower) { return tabSizePower; } /** * Remainder using an accurate definition of PI. * Derived from a fdlibm treatment called __ieee754_rem_pio2. * * This method can return values slightly (like one ULP or so) outside [-Math.PI,Math.PI] range. * * @param angle Angle in radians. * @return Remainder of (angle % (2*PI)), which is in [-PI,PI] range. */ private static double remainderTwoPi(double angle) { boolean negateResult; if (angle < 0.0) { negateResult = true; angle = -angle; } else { negateResult = false; } if (angle <= NORMALIZE_ANGLE_MAX_MEDIUM_DOUBLE) { double fn = (double) (int) (angle * INVTWOPI + 0.5); double result = (angle - fn * TWOPI_HI) - fn * TWOPI_LO; return negateResult ? -result : result; } else if (angle < Double.POSITIVE_INFINITY) { // Reworking exponent to have a value < 2^24. long lx = Double.doubleToRawLongBits(angle); long exp = ((lx >> 52) & 0x7FF) - 1046; double z = Double.longBitsToDouble(lx - (exp << 52)); double x0 = (double) ((int) z); z = (z - x0) * TWO_POW_24; double x1 = (double) ((int) z); double x2 = (z - x1) * TWO_POW_24; double result = subRemainderTwoPi(x0, x1, x2, (int) exp, (x2 == 0) ? 2 : 3); return negateResult ? -result : result; } else { // angle is +infinity or NaN return Double.NaN; } } /** * Remainder using an accurate definition of PI. * Derived from a fdlibm treatment called __kernel_rem_pio2. * * @param x0 Most significant part of the value, as an integer &lt; 2^24, in double precision format. Must be >= 0. * @param x1 Following significant part of the value, as an integer &lt; 2^24, in double precision format. * @param x2 Least significant part of the value, as an integer &lt; 2^24, in double precision format. * @param e0 Exponent of x0 (value is (2^e0)*(x0+(2^-24)*(x1+(2^-24)*x2))). Must be &ge; -20. * @param nx Number of significant parts to take into account. Must be 2 or 3. * @return Remainder of (value % (2*PI)), which is in [-PI,PI] range. */ private static double subRemainderTwoPi(double x0, double x1, double x2, int e0, int nx) { int ih; double z, fw; double f0, f1, f2, f3, f4, f5, f6 = 0.0, f7; double q0, q1, q2, q3, q4, q5; int iq0, iq1, iq2, iq3, iq4; final int jx = nx - 1; // jx in [1,2] (nx in [2,3]) // Could use a table to avoid division, but the gain isn't worth it most likely... final int jv = (e0 - 3) / 24; // We do not handle the case (e0-3 < -23). int q = e0 - ((jv << 4) + (jv << 3)) - 24; // e0-24*(jv+1) final int j = jv + 4; if (jx == 1) { f5 = (j >= 0) ? ONE_OVER_TWOPI_TAB[j] : 0.0; f4 = (j >= 1) ? ONE_OVER_TWOPI_TAB[j - 1] : 0.0; f3 = (j >= 2) ? ONE_OVER_TWOPI_TAB[j - 2] : 0.0; f2 = (j >= 3) ? ONE_OVER_TWOPI_TAB[j - 3] : 0.0; f1 = (j >= 4) ? ONE_OVER_TWOPI_TAB[j - 4] : 0.0; f0 = (j >= 5) ? ONE_OVER_TWOPI_TAB[j - 5] : 0.0; q0 = x0 * f1 + x1 * f0; q1 = x0 * f2 + x1 * f1; q2 = x0 * f3 + x1 * f2; q3 = x0 * f4 + x1 * f3; q4 = x0 * f5 + x1 * f4; } else { // jx == 2 f6 = (j >= 0) ? ONE_OVER_TWOPI_TAB[j] : 0.0; f5 = (j >= 1) ? ONE_OVER_TWOPI_TAB[j - 1] : 0.0; f4 = (j >= 2) ? ONE_OVER_TWOPI_TAB[j - 2] : 0.0; f3 = (j >= 3) ? ONE_OVER_TWOPI_TAB[j - 3] : 0.0; f2 = (j >= 4) ? ONE_OVER_TWOPI_TAB[j - 4] : 0.0; f1 = (j >= 5) ? ONE_OVER_TWOPI_TAB[j - 5] : 0.0; f0 = (j >= 6) ? ONE_OVER_TWOPI_TAB[j - 6] : 0.0; q0 = x0 * f2 + x1 * f1 + x2 * f0; q1 = x0 * f3 + x1 * f2 + x2 * f1; q2 = x0 * f4 + x1 * f3 + x2 * f2; q3 = x0 * f5 + x1 * f4 + x2 * f3; q4 = x0 * f6 + x1 * f5 + x2 * f4; } z = q4; fw = (double) ((int) (TWO_POW_N24 * z)); iq0 = (int) (z - TWO_POW_24 * fw); z = q3 + fw; fw = (double) ((int) (TWO_POW_N24 * z)); iq1 = (int) (z - TWO_POW_24 * fw); z = q2 + fw; fw = (double) ((int) (TWO_POW_N24 * z)); iq2 = (int) (z - TWO_POW_24 * fw); z = q1 + fw; fw = (double) ((int) (TWO_POW_N24 * z)); iq3 = (int) (z - TWO_POW_24 * fw); z = q0 + fw; // Here, q is in [-25,2] range or so, so we can use the table right away. double twoPowQ = twoPowTab[q - MIN_DOUBLE_EXPONENT]; z = (z * twoPowQ) % 8.0; z -= (double) ((int) z); if (q > 0) { iq3 &= 0xFFFFFF >> q; ih = iq3 >> (23 - q); } else if (q == 0) { ih = iq3 >> 23; } else if (z >= 0.5) { ih = 2; } else { ih = 0; } if (ih > 0) { int carry; if (iq0 != 0) { carry = 1; iq0 = 0x1000000 - iq0; iq1 = 0x0FFFFFF - iq1; iq2 = 0x0FFFFFF - iq2; iq3 = 0x0FFFFFF - iq3; } else { if (iq1 != 0) { carry = 1; iq1 = 0x1000000 - iq1; iq2 = 0x0FFFFFF - iq2; iq3 = 0x0FFFFFF - iq3; } else { if (iq2 != 0) { carry = 1; iq2 = 0x1000000 - iq2; iq3 = 0x0FFFFFF - iq3; } else { if (iq3 != 0) { carry = 1; iq3 = 0x1000000 - iq3; } else { carry = 0; } } } } if (q > 0) { switch (q) { case 1 -> iq3 &= 0x7FFFFF; case 2 -> iq3 &= 0x3FFFFF; } } if (ih == 2) { z = 1.0 - z; if (carry != 0) { z -= twoPowQ; } } } if (z == 0.0) { if (jx == 1) { f6 = ONE_OVER_TWOPI_TAB[jv + 5]; q5 = x0 * f6 + x1 * f5; } else { // jx == 2 f7 = ONE_OVER_TWOPI_TAB[jv + 5]; q5 = x0 * f7 + x1 * f6 + x2 * f5; } z = q5; fw = (double) ((int) (TWO_POW_N24 * z)); iq0 = (int) (z - TWO_POW_24 * fw); z = q4 + fw; fw = (double) ((int) (TWO_POW_N24 * z)); iq1 = (int) (z - TWO_POW_24 * fw); z = q3 + fw; fw = (double) ((int) (TWO_POW_N24 * z)); iq2 = (int) (z - TWO_POW_24 * fw); z = q2 + fw; fw = (double) ((int) (TWO_POW_N24 * z)); iq3 = (int) (z - TWO_POW_24 * fw); z = q1 + fw; fw = (double) ((int) (TWO_POW_N24 * z)); iq4 = (int) (z - TWO_POW_24 * fw); z = q0 + fw; z = (z * twoPowQ) % 8.0; z -= (double) ((int) z); if (q > 0) { // some parentheses for Eclipse formatter's weaknesses with bits shifts iq4 &= (0xFFFFFF >> q); ih = (iq4 >> (23 - q)); } else if (q == 0) { ih = iq4 >> 23; } else if (z >= 0.5) { ih = 2; } else { ih = 0; } if (ih > 0) { if (iq0 != 0) { iq0 = 0x1000000 - iq0; iq1 = 0x0FFFFFF - iq1; iq2 = 0x0FFFFFF - iq2; iq3 = 0x0FFFFFF - iq3; iq4 = 0x0FFFFFF - iq4; } else { if (iq1 != 0) { iq1 = 0x1000000 - iq1; iq2 = 0x0FFFFFF - iq2; iq3 = 0x0FFFFFF - iq3; iq4 = 0x0FFFFFF - iq4; } else { if (iq2 != 0) { iq2 = 0x1000000 - iq2; iq3 = 0x0FFFFFF - iq3; iq4 = 0x0FFFFFF - iq4; } else { if (iq3 != 0) { iq3 = 0x1000000 - iq3; iq4 = 0x0FFFFFF - iq4; } else { if (iq4 != 0) { iq4 = 0x1000000 - iq4; } } } } } if (q > 0) { switch (q) { case 1 -> iq4 &= 0x7FFFFF; case 2 -> iq4 &= 0x3FFFFF; } } } fw = twoPowQ * TWO_POW_N24; // q -= 24, so initializing fw with ((2^q)*(2^-24)=2^(q-24)) } else { // Here, q is in [-25,-2] range or so, so we could use twoPow's table right away with // iq4 = (int)(z*twoPowTab[-q-TWO_POW_TAB_MIN_POW]); // but tests show using division is faster... iq4 = (int) (z / twoPowQ); fw = twoPowQ; } q4 = fw * (double) iq4; fw *= TWO_POW_N24; q3 = fw * (double) iq3; fw *= TWO_POW_N24; q2 = fw * (double) iq2; fw *= TWO_POW_N24; q1 = fw * (double) iq1; fw *= TWO_POW_N24; q0 = fw * (double) iq0; fw *= TWO_POW_N24; fw = TWOPI_TAB0 * q4; fw += TWOPI_TAB0 * q3 + TWOPI_TAB1 * q4; fw += TWOPI_TAB0 * q2 + TWOPI_TAB1 * q3 + TWOPI_TAB2 * q4; fw += TWOPI_TAB0 * q1 + TWOPI_TAB1 * q2 + TWOPI_TAB2 * q3 + TWOPI_TAB3 * q4; fw += TWOPI_TAB0 * q0 + TWOPI_TAB1 * q1 + TWOPI_TAB2 * q2 + TWOPI_TAB3 * q3 + TWOPI_TAB4 * q4; return (ih == 0) ? fw : -fw; } // -------------------------------------------------------------------------- // STATIC INITIALIZATIONS // -------------------------------------------------------------------------- /** * Initializes look-up tables. * * Might use some FastMath methods in there, not to spend * an hour in it, but must take care not to use methods * which look-up tables have not yet been initialized, * or that are not accurate enough. */ static { // sin and cos final int SIN_COS_PI_INDEX = (SIN_COS_TABS_SIZE - 1) / 2; final int SIN_COS_PI_MUL_2_INDEX = 2 * SIN_COS_PI_INDEX; final int SIN_COS_PI_MUL_0_5_INDEX = SIN_COS_PI_INDEX / 2; final int SIN_COS_PI_MUL_1_5_INDEX = 3 * SIN_COS_PI_INDEX / 2; for (int i = 0; i < SIN_COS_TABS_SIZE; i++) { // angle: in [0,2*PI]. double angle = i * SIN_COS_DELTA_HI + i * SIN_COS_DELTA_LO; double sinAngle = StrictMath.sin(angle); double cosAngle = StrictMath.cos(angle); // For indexes corresponding to null cosine or sine, we make sure the value is zero // and not an epsilon. This allows for a much better accuracy for results close to zero. if (i == SIN_COS_PI_INDEX) { sinAngle = 0.0; } else if (i == SIN_COS_PI_MUL_2_INDEX) { sinAngle = 0.0; } else if (i == SIN_COS_PI_MUL_0_5_INDEX) { cosAngle = 0.0; } else if (i == SIN_COS_PI_MUL_1_5_INDEX) { cosAngle = 0.0; } sinTab[i] = sinAngle; cosTab[i] = cosAngle; } // tan for (int i = 0; i < TAN_TABS_SIZE; i++) { // angle: in [0,TAN_MAX_VALUE_FOR_TABS]. double angle = i * TAN_DELTA_HI + i * TAN_DELTA_LO; tanTab[i] = StrictMath.tan(angle); double cosAngle = StrictMath.cos(angle); double sinAngle = StrictMath.sin(angle); double cosAngleInv = 1 / cosAngle; double cosAngleInv2 = cosAngleInv * cosAngleInv; double cosAngleInv3 = cosAngleInv2 * cosAngleInv; double cosAngleInv4 = cosAngleInv2 * cosAngleInv2; double cosAngleInv5 = cosAngleInv3 * cosAngleInv2; tanDer1DivF1Tab[i] = cosAngleInv2; tanDer2DivF2Tab[i] = ((2 * sinAngle) * cosAngleInv3) * ONE_DIV_F2; tanDer3DivF3Tab[i] = ((2 * (1 + 2 * sinAngle * sinAngle)) * cosAngleInv4) * ONE_DIV_F3; tanDer4DivF4Tab[i] = ((8 * sinAngle * (2 + sinAngle * sinAngle)) * cosAngleInv5) * ONE_DIV_F4; } // asin for (int i = 0; i < ASIN_TABS_SIZE; i++) { // x: in [0,ASIN_MAX_VALUE_FOR_TABS]. double x = i * ASIN_DELTA; asinTab[i] = StrictMath.asin(x); double oneMinusXSqInv = 1.0 / (1 - x * x); double oneMinusXSqInv0_5 = StrictMath.sqrt(oneMinusXSqInv); double oneMinusXSqInv1_5 = oneMinusXSqInv0_5 * oneMinusXSqInv; double oneMinusXSqInv2_5 = oneMinusXSqInv1_5 * oneMinusXSqInv; double oneMinusXSqInv3_5 = oneMinusXSqInv2_5 * oneMinusXSqInv; asinDer1DivF1Tab[i] = oneMinusXSqInv0_5; asinDer2DivF2Tab[i] = (x * oneMinusXSqInv1_5) * ONE_DIV_F2; asinDer3DivF3Tab[i] = ((1 + 2 * x * x) * oneMinusXSqInv2_5) * ONE_DIV_F3; asinDer4DivF4Tab[i] = ((5 + 2 * x * (2 + x * (5 - 2 * x))) * oneMinusXSqInv3_5) * ONE_DIV_F4; } for (int i = 0; i < ASIN_POWTABS_SIZE; i++) { // x: in [0,ASIN_MAX_VALUE_FOR_POWTABS]. double x = StrictMath.pow(i * (1.0 / ASIN_POWTABS_SIZE_MINUS_ONE), 1.0 / ASIN_POWTABS_POWER) * ASIN_MAX_VALUE_FOR_POWTABS; asinParamPowTab[i] = x; asinPowTab[i] = StrictMath.asin(x); double oneMinusXSqInv = 1.0 / (1 - x * x); double oneMinusXSqInv0_5 = StrictMath.sqrt(oneMinusXSqInv); double oneMinusXSqInv1_5 = oneMinusXSqInv0_5 * oneMinusXSqInv; double oneMinusXSqInv2_5 = oneMinusXSqInv1_5 * oneMinusXSqInv; double oneMinusXSqInv3_5 = oneMinusXSqInv2_5 * oneMinusXSqInv; asinDer1DivF1PowTab[i] = oneMinusXSqInv0_5; asinDer2DivF2PowTab[i] = (x * oneMinusXSqInv1_5) * ONE_DIV_F2; asinDer3DivF3PowTab[i] = ((1 + 2 * x * x) * oneMinusXSqInv2_5) * ONE_DIV_F3; asinDer4DivF4PowTab[i] = ((5 + 2 * x * (2 + x * (5 - 2 * x))) * oneMinusXSqInv3_5) * ONE_DIV_F4; } // atan for (int i = 0; i < ATAN_TABS_SIZE; i++) { // x: in [0,ATAN_MAX_VALUE_FOR_TABS]. double x = i * ATAN_DELTA; double onePlusXSqInv = 1.0 / (1 + x * x); double onePlusXSqInv2 = onePlusXSqInv * onePlusXSqInv; double onePlusXSqInv3 = onePlusXSqInv2 * onePlusXSqInv; double onePlusXSqInv4 = onePlusXSqInv2 * onePlusXSqInv2; atanTab[i] = StrictMath.atan(x); atanDer1DivF1Tab[i] = onePlusXSqInv; atanDer2DivF2Tab[i] = (-2 * x * onePlusXSqInv2) * ONE_DIV_F2; atanDer3DivF3Tab[i] = ((-2 + 6 * x * x) * onePlusXSqInv3) * ONE_DIV_F3; atanDer4DivF4Tab[i] = ((24 * x * (1 - x * x)) * onePlusXSqInv4) * ONE_DIV_F4; } // twoPow for (int i = MIN_DOUBLE_EXPONENT; i <= MAX_DOUBLE_EXPONENT; i++) { twoPowTab[i - MIN_DOUBLE_EXPONENT] = StrictMath.pow(2.0, i); } } }
elastic/elasticsearch
libs/h3/src/main/java/org/elasticsearch/h3/FastMath.java
376
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.tasks; import org.elasticsearch.TransportVersions; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.common.xcontent.ObjectParserHelper; import org.elasticsearch.core.TimeValue; import org.elasticsearch.xcontent.ConstructingObjectParser; import org.elasticsearch.xcontent.ParseField; import org.elasticsearch.xcontent.ToXContentFragment; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xcontent.XContentParser; import java.io.IOException; import java.util.Collections; import java.util.Map; import java.util.concurrent.TimeUnit; import static org.elasticsearch.xcontent.ConstructingObjectParser.constructorArg; import static org.elasticsearch.xcontent.ConstructingObjectParser.optionalConstructorArg; /** * Information about a currently running task. * <p> * Tasks are used for communication with transport actions. As a result, they can contain callback * references as well as mutable state. That makes it impractical to send tasks over transport channels * and use in APIs. Instead, immutable and writeable TaskInfo objects are used to represent * snapshot information about currently running tasks. */ public record TaskInfo( TaskId taskId, String type, String node, String action, String description, Task.Status status, long startTime, long runningTimeNanos, boolean cancellable, boolean cancelled, TaskId parentTaskId, Map<String, String> headers ) implements Writeable, ToXContentFragment { static final String INCLUDE_CANCELLED_PARAM = "include_cancelled"; public TaskInfo { assert cancellable || cancelled == false : "uncancellable task cannot be cancelled"; } /** * Read from a stream. */ public static TaskInfo from(StreamInput in) throws IOException { TaskId taskId = TaskId.readFromStream(in); return new TaskInfo( taskId, in.readString(), in.getTransportVersion().onOrAfter(TransportVersions.V_8_10_X) ? in.readString() : taskId.getNodeId(), in.readString(), in.readOptionalString(), in.readOptionalNamedWriteable(Task.Status.class), in.readLong(), in.readLong(), in.readBoolean(), in.readBoolean(), TaskId.readFromStream(in), in.readMap(StreamInput::readString) ); } @Override public void writeTo(StreamOutput out) throws IOException { taskId.writeTo(out); out.writeString(type); if (out.getTransportVersion().onOrAfter(TransportVersions.V_8_10_X)) { out.writeString(node); } out.writeString(action); out.writeOptionalString(description); out.writeOptionalNamedWriteable(status); out.writeLong(startTime); out.writeLong(runningTimeNanos); out.writeBoolean(cancellable); out.writeBoolean(cancelled); parentTaskId.writeTo(out); out.writeMap(headers, StreamOutput::writeString); } public long id() { return taskId.getId(); } @Override public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException { builder.field("node", node); builder.field("id", taskId.getId()); builder.field("type", type); builder.field("action", action); if (status != null) { builder.field("status", status, params); } if (description != null) { builder.field("description", description); } builder.timeField("start_time_in_millis", "start_time", startTime); if (builder.humanReadable()) { builder.field("running_time", new TimeValue(runningTimeNanos, TimeUnit.NANOSECONDS).toString()); } builder.field("running_time_in_nanos", runningTimeNanos); builder.field("cancellable", cancellable); if (params.paramAsBoolean(INCLUDE_CANCELLED_PARAM, true) && cancellable) { // don't record this on entries in the tasks index, since we can't add this field to the mapping dynamically and it's not // important for completed tasks anyway builder.field("cancelled", cancelled); } if (parentTaskId.isSet()) { builder.field("parent_task_id", parentTaskId.toString()); } builder.startObject("headers"); for (Map.Entry<String, String> attribute : headers.entrySet()) { builder.field(attribute.getKey(), attribute.getValue()); } builder.endObject(); return builder; } public static TaskInfo fromXContent(XContentParser parser) { return PARSER.apply(parser, null); } public static final ConstructingObjectParser<TaskInfo, Void> PARSER = new ConstructingObjectParser<>("task_info", true, a -> { int i = 0; String node = (String) a[i++]; TaskId id = new TaskId(node, (Long) a[i++]); String type = (String) a[i++]; String action = (String) a[i++]; String description = (String) a[i++]; BytesReference statusBytes = (BytesReference) a[i++]; long startTime = (Long) a[i++]; long runningTimeNanos = (Long) a[i++]; boolean cancellable = (Boolean) a[i++]; boolean cancelled = a[i++] == Boolean.TRUE; String parentTaskIdString = (String) a[i++]; @SuppressWarnings("unchecked") Map<String, String> headers = (Map<String, String>) a[i++]; if (headers == null) { // This might happen if we are reading an old version of task info headers = Collections.emptyMap(); } RawTaskStatus status = statusBytes == null ? null : new RawTaskStatus(statusBytes); TaskId parentTaskId = parentTaskIdString == null ? TaskId.EMPTY_TASK_ID : new TaskId(parentTaskIdString); return new TaskInfo( id, type, node, action, description, status, startTime, runningTimeNanos, cancellable, cancelled, parentTaskId, headers ); }); static { // Note for the future: this has to be backwards and forwards compatible with all changes to the task storage format PARSER.declareString(constructorArg(), new ParseField("node")); PARSER.declareLong(constructorArg(), new ParseField("id")); PARSER.declareString(constructorArg(), new ParseField("type")); PARSER.declareString(constructorArg(), new ParseField("action")); PARSER.declareString(optionalConstructorArg(), new ParseField("description")); ObjectParserHelper.declareRawObject(PARSER, optionalConstructorArg(), new ParseField("status")); PARSER.declareLong(constructorArg(), new ParseField("start_time_in_millis")); PARSER.declareLong(constructorArg(), new ParseField("running_time_in_nanos")); PARSER.declareBoolean(constructorArg(), new ParseField("cancellable")); PARSER.declareBoolean(optionalConstructorArg(), new ParseField("cancelled")); PARSER.declareString(optionalConstructorArg(), new ParseField("parent_task_id")); PARSER.declareObject(optionalConstructorArg(), (p, c) -> p.mapStrings(), new ParseField("headers")); } @Override public String toString() { return Strings.toString(this, true, true); } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/tasks/TaskInfo.java
377
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.transport; import org.elasticsearch.TransportVersion; import org.elasticsearch.TransportVersions; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.util.concurrent.ThreadContext; import org.elasticsearch.core.Tuple; import java.io.IOException; import java.util.Map; import java.util.Set; public class Header { private static final String RESPONSE_NAME = "NO_ACTION_NAME_FOR_RESPONSES"; private final int networkMessageSize; private final TransportVersion version; private final long requestId; private final byte status; // These are directly set by tests String actionName; Tuple<Map<String, String>, Map<String, Set<String>>> headers; private Compression.Scheme compressionScheme = null; Header(int networkMessageSize, long requestId, byte status, TransportVersion version) { this.networkMessageSize = networkMessageSize; this.version = version; this.requestId = requestId; this.status = status; } public int getNetworkMessageSize() { return networkMessageSize; } TransportVersion getVersion() { return version; } long getRequestId() { return requestId; } public boolean isRequest() { return TransportStatus.isRequest(status); } boolean isResponse() { return TransportStatus.isRequest(status) == false; } boolean isError() { return TransportStatus.isError(status); } public boolean isHandshake() { return TransportStatus.isHandshake(status); } boolean isCompressed() { return TransportStatus.isCompress(status); } public String getActionName() { return actionName; } public Compression.Scheme getCompressionScheme() { return compressionScheme; } public Map<String, String> getRequestHeaders() { var allHeaders = getHeaders(); return allHeaders == null ? null : allHeaders.v1(); } boolean needsToReadVariableHeader() { return headers == null; } Tuple<Map<String, String>, Map<String, Set<String>>> getHeaders() { return headers; } void finishParsingHeader(StreamInput input) throws IOException { this.headers = ThreadContext.readHeadersFromStream(input); if (isRequest()) { if (version.before(TransportVersions.V_8_0_0)) { // discard features input.readStringArray(); } this.actionName = input.readString(); } else { this.actionName = RESPONSE_NAME; } } void setCompressionScheme(Compression.Scheme compressionScheme) { assert isCompressed(); this.compressionScheme = compressionScheme; } @Override public String toString() { return "Header{" + networkMessageSize + "}{" + version + "}{" + requestId + "}{" + isRequest() + "}{" + isError() + "}{" + isHandshake() + "}{" + isCompressed() + "}{" + actionName + "}"; } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/transport/Header.java
378
/* * 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 static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Collections2.FilteredCollection; import com.google.common.math.IntMath; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.DoNotCall; import com.google.errorprone.annotations.concurrent.LazyInit; import java.io.Serializable; import java.util.AbstractSet; import java.util.Arrays; import java.util.BitSet; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.EnumSet; import java.util.HashSet; import java.util.Iterator; import java.util.LinkedHashSet; import java.util.List; import java.util.Map; import java.util.NavigableSet; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.CopyOnWriteArraySet; import java.util.function.Consumer; import java.util.stream.Collector; import java.util.stream.Stream; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods pertaining to {@link Set} instances. Also see this class's counterparts * {@link Lists}, {@link Maps} and {@link Queues}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#sets">{@code Sets}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @author Chris Povirk * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Sets { private Sets() {} /** * {@link AbstractSet} substitute without the potentially-quadratic {@code removeAll} * implementation. */ abstract static class ImprovedAbstractSet<E extends @Nullable Object> extends AbstractSet<E> { @Override public boolean removeAll(Collection<?> c) { return removeAllImpl(this, c); } @Override public boolean retainAll(Collection<?> c) { return super.retainAll(checkNotNull(c)); // GWT compatibility } } /** * Returns an immutable set instance containing the given enum elements. Internally, the returned * set will be backed by an {@link EnumSet}. * * <p>The iteration order of the returned set follows the enum's iteration order, not the order in * which the elements are provided to the method. * * @param anElement one of the elements the set should contain * @param otherElements the rest of the elements the set should contain * @return an immutable set containing those elements, minus duplicates */ // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 @GwtCompatible(serializable = true) public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet( E anElement, E... otherElements) { return ImmutableEnumSet.asImmutable(EnumSet.of(anElement, otherElements)); } /** * Returns an immutable set instance containing the given enum elements. Internally, the returned * set will be backed by an {@link EnumSet}. * * <p>The iteration order of the returned set follows the enum's iteration order, not the order in * which the elements appear in the given collection. * * @param elements the elements, all of the same {@code enum} type, that the set should contain * @return an immutable set containing those elements, minus duplicates */ // http://code.google.com/p/google-web-toolkit/issues/detail?id=3028 @GwtCompatible(serializable = true) public static <E extends Enum<E>> ImmutableSet<E> immutableEnumSet(Iterable<E> elements) { if (elements instanceof ImmutableEnumSet) { return (ImmutableEnumSet<E>) elements; } else if (elements instanceof Collection) { Collection<E> collection = (Collection<E>) elements; if (collection.isEmpty()) { return ImmutableSet.of(); } else { return ImmutableEnumSet.asImmutable(EnumSet.copyOf(collection)); } } else { Iterator<E> itr = elements.iterator(); if (itr.hasNext()) { EnumSet<E> enumSet = EnumSet.of(itr.next()); Iterators.addAll(enumSet, itr); return ImmutableEnumSet.asImmutable(enumSet); } else { return ImmutableSet.of(); } } } /** * Returns a {@code Collector} that accumulates the input elements into a new {@code ImmutableSet} * with an implementation specialized for enums. Unlike {@link ImmutableSet#toImmutableSet}, the * resulting set will iterate over elements in their enum definition order, not encounter order. * * @since 21.0 */ public static <E extends Enum<E>> Collector<E, ?, ImmutableSet<E>> toImmutableEnumSet() { return CollectCollectors.toImmutableEnumSet(); } /** * Returns a new, <i>mutable</i> {@code EnumSet} instance containing the given elements in their * natural order. This method behaves identically to {@link EnumSet#copyOf(Collection)}, but also * accepts non-{@code Collection} iterables and empty iterables. */ public static <E extends Enum<E>> EnumSet<E> newEnumSet( Iterable<E> iterable, Class<E> elementType) { EnumSet<E> set = EnumSet.noneOf(elementType); Iterables.addAll(set, iterable); return set; } // HashSet /** * Creates a <i>mutable</i>, initially empty {@code HashSet} instance. * * <p><b>Note:</b> if mutability is not required, use {@link ImmutableSet#of()} instead. If {@code * E} is an {@link Enum} type, use {@link EnumSet#noneOf} instead. Otherwise, strongly consider * using a {@code LinkedHashSet} instead, at the cost of increased memory footprint, to get * deterministic iteration behavior. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code HashSet} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. */ public static <E extends @Nullable Object> HashSet<E> newHashSet() { return new HashSet<>(); } /** * Creates a <i>mutable</i> {@code HashSet} instance initially containing the given elements. * * <p><b>Note:</b> if elements are non-null and won't be added or removed after this point, use * {@link ImmutableSet#of()} or {@link ImmutableSet#copyOf(Object[])} instead. If {@code E} is an * {@link Enum} type, use {@link EnumSet#of(Enum, Enum[])} instead. Otherwise, strongly consider * using a {@code LinkedHashSet} instead, at the cost of increased memory footprint, to get * deterministic iteration behavior. * * <p>This method is just a small convenience, either for {@code newHashSet(}{@link Arrays#asList * asList}{@code (...))}, or for creating an empty set then calling {@link Collections#addAll}. * This method is not actually very useful and will likely be deprecated in the future. */ @SuppressWarnings("nullness") // TODO: b/316358623 - Remove after checker fix. public static <E extends @Nullable Object> HashSet<E> newHashSet(E... elements) { HashSet<E> set = newHashSetWithExpectedSize(elements.length); Collections.addAll(set, elements); return set; } /** * Creates a <i>mutable</i> {@code HashSet} instance containing the given elements. A very thin * convenience for creating an empty set then calling {@link Collection#addAll} or {@link * Iterables#addAll}. * * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link * ImmutableSet#copyOf(Iterable)} instead. (Or, change {@code elements} to be a {@link * FluentIterable} and call {@code elements.toSet()}.) * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, use {@link #newEnumSet(Iterable, Class)} * instead. * * <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method. * Instead, use the {@code HashSet} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * <p>Overall, this method is not very useful and will likely be deprecated in the future. */ public static <E extends @Nullable Object> HashSet<E> newHashSet(Iterable<? extends E> elements) { return (elements instanceof Collection) ? new HashSet<E>((Collection<? extends E>) elements) : newHashSet(elements.iterator()); } /** * Creates a <i>mutable</i> {@code HashSet} instance containing the given elements. A very thin * convenience for creating an empty set and then calling {@link Iterators#addAll}. * * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link * ImmutableSet#copyOf(Iterator)} instead. * * <p><b>Note:</b> if {@code E} is an {@link Enum} type, you should create an {@link EnumSet} * instead. * * <p>Overall, this method is not very useful and will likely be deprecated in the future. */ public static <E extends @Nullable Object> HashSet<E> newHashSet(Iterator<? extends E> elements) { HashSet<E> set = newHashSet(); Iterators.addAll(set, elements); return set; } /** * Returns a new hash set using the smallest initial table size that can hold {@code expectedSize} * elements without resizing. Note that this is not what {@link HashSet#HashSet(int)} does, but it * is what most users want and expect it to do. * * <p>This behavior can't be broadly guaranteed, but has been tested with OpenJDK 1.7 and 1.8. * * @param expectedSize the number of elements you expect to add to the returned set * @return a new, empty hash set with enough capacity to hold {@code expectedSize} elements * without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative */ public static <E extends @Nullable Object> HashSet<E> newHashSetWithExpectedSize( int expectedSize) { return new HashSet<>(Maps.capacity(expectedSize)); } /** * Creates a thread-safe set backed by a hash map. The set is backed by a {@link * ConcurrentHashMap} instance, and thus carries the same concurrency guarantees. * * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be used as an element. The * set is serializable. * * @return a new, empty thread-safe {@code Set} * @since 15.0 */ public static <E> Set<E> newConcurrentHashSet() { return Platform.newConcurrentHashSet(); } /** * Creates a thread-safe set backed by a hash map and containing the given elements. The set is * backed by a {@link ConcurrentHashMap} instance, and thus carries the same concurrency * guarantees. * * <p>Unlike {@code HashSet}, this class does NOT allow {@code null} to be used as an element. The * set is serializable. * * @param elements the elements that the set should contain * @return a new thread-safe set containing those elements (minus duplicates) * @throws NullPointerException if {@code elements} or any of its contents is null * @since 15.0 */ public static <E> Set<E> newConcurrentHashSet(Iterable<? extends E> elements) { Set<E> set = newConcurrentHashSet(); Iterables.addAll(set, elements); return set; } // LinkedHashSet /** * Creates a <i>mutable</i>, empty {@code LinkedHashSet} instance. * * <p><b>Note:</b> if mutability is not required, use {@link ImmutableSet#of()} instead. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code LinkedHashSet} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @return a new, empty {@code LinkedHashSet} */ public static <E extends @Nullable Object> LinkedHashSet<E> newLinkedHashSet() { return new LinkedHashSet<>(); } /** * Creates a <i>mutable</i> {@code LinkedHashSet} instance containing the given elements in order. * * <p><b>Note:</b> if mutability is not required and the elements are non-null, use {@link * ImmutableSet#copyOf(Iterable)} instead. * * <p><b>Note:</b> if {@code elements} is a {@link Collection}, you don't need this method. * Instead, use the {@code LinkedHashSet} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * <p>Overall, this method is not very useful and will likely be deprecated in the future. * * @param elements the elements that the set should contain, in order * @return a new {@code LinkedHashSet} containing those elements (minus duplicates) */ public static <E extends @Nullable Object> LinkedHashSet<E> newLinkedHashSet( Iterable<? extends E> elements) { if (elements instanceof Collection) { return new LinkedHashSet<>((Collection<? extends E>) elements); } LinkedHashSet<E> set = newLinkedHashSet(); Iterables.addAll(set, elements); return set; } /** * Creates a {@code LinkedHashSet} instance, with a high enough "initial capacity" that it * <i>should</i> hold {@code expectedSize} elements without growth. This behavior cannot be * broadly guaranteed, but it is observed to be true for OpenJDK 1.7. It also can't be guaranteed * that the method isn't inadvertently <i>oversizing</i> the returned set. * * @param expectedSize the number of elements you expect to add to the returned set * @return a new, empty {@code LinkedHashSet} with enough capacity to hold {@code expectedSize} * elements without resizing * @throws IllegalArgumentException if {@code expectedSize} is negative * @since 11.0 */ public static <E extends @Nullable Object> LinkedHashSet<E> newLinkedHashSetWithExpectedSize( int expectedSize) { return new LinkedHashSet<>(Maps.capacity(expectedSize)); } // TreeSet /** * Creates a <i>mutable</i>, empty {@code TreeSet} instance sorted by the natural sort ordering of * its elements. * * <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedSet#of()} instead. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code TreeSet} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * @return a new, empty {@code TreeSet} */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static <E extends Comparable> TreeSet<E> newTreeSet() { return new TreeSet<>(); } /** * Creates a <i>mutable</i> {@code TreeSet} instance containing the given elements sorted by their * natural ordering. * * <p><b>Note:</b> if mutability is not required, use {@link ImmutableSortedSet#copyOf(Iterable)} * instead. * * <p><b>Note:</b> If {@code elements} is a {@code SortedSet} with an explicit comparator, this * method has different behavior than {@link TreeSet#TreeSet(SortedSet)}, which returns a {@code * TreeSet} with that comparator. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code TreeSet} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. * * <p>This method is just a small convenience for creating an empty set and then calling {@link * Iterables#addAll}. This method is not very useful and will likely be deprecated in the future. * * @param elements the elements that the set should contain * @return a new {@code TreeSet} containing those elements (minus duplicates) */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static <E extends Comparable> TreeSet<E> newTreeSet(Iterable<? extends E> elements) { TreeSet<E> set = newTreeSet(); Iterables.addAll(set, elements); return set; } /** * Creates a <i>mutable</i>, empty {@code TreeSet} instance with the given comparator. * * <p><b>Note:</b> if mutability is not required, use {@code * ImmutableSortedSet.orderedBy(comparator).build()} instead. * * <p><b>Note:</b> this method is now unnecessary and should be treated as deprecated. Instead, * use the {@code TreeSet} constructor directly, taking advantage of <a * href="http://goo.gl/iz2Wi">"diamond" syntax</a>. One caveat to this is that the {@code TreeSet} * constructor uses a null {@code Comparator} to mean "natural ordering," whereas this factory * rejects null. Clean your code accordingly. * * @param comparator the comparator to use to sort the set * @return a new, empty {@code TreeSet} * @throws NullPointerException if {@code comparator} is null */ public static <E extends @Nullable Object> TreeSet<E> newTreeSet( Comparator<? super E> comparator) { return new TreeSet<>(checkNotNull(comparator)); } /** * Creates an empty {@code Set} that uses identity to determine equality. It compares object * references, instead of calling {@code equals}, to determine whether a provided object matches * an element in the set. For example, {@code contains} returns {@code false} when passed an * object that equals a set member, but isn't the same instance. This behavior is similar to the * way {@code IdentityHashMap} handles key lookups. * * @since 8.0 */ public static <E extends @Nullable Object> Set<E> newIdentityHashSet() { return Collections.newSetFromMap(Maps.<E, Boolean>newIdentityHashMap()); } /** * Creates an empty {@code CopyOnWriteArraySet} instance. * * <p><b>Note:</b> if you need an immutable empty {@link Set}, use {@link Collections#emptySet} * instead. * * @return a new, empty {@code CopyOnWriteArraySet} * @since 12.0 */ @J2ktIncompatible @GwtIncompatible // CopyOnWriteArraySet public static <E extends @Nullable Object> CopyOnWriteArraySet<E> newCopyOnWriteArraySet() { return new CopyOnWriteArraySet<>(); } /** * Creates a {@code CopyOnWriteArraySet} instance containing the given elements. * * @param elements the elements that the set should contain, in order * @return a new {@code CopyOnWriteArraySet} containing those elements * @since 12.0 */ @J2ktIncompatible @GwtIncompatible // CopyOnWriteArraySet public static <E extends @Nullable Object> CopyOnWriteArraySet<E> newCopyOnWriteArraySet( Iterable<? extends E> elements) { // We copy elements to an ArrayList first, rather than incurring the // quadratic cost of adding them to the COWAS directly. Collection<? extends E> elementsCollection = (elements instanceof Collection) ? (Collection<? extends E>) elements : Lists.newArrayList(elements); return new CopyOnWriteArraySet<>(elementsCollection); } /** * Creates an {@code EnumSet} consisting of all enum values that are not in the specified * collection. If the collection is an {@link EnumSet}, this method has the same behavior as * {@link EnumSet#complementOf}. Otherwise, the specified collection must contain at least one * element, in order to determine the element type. If the collection could be empty, use {@link * #complementOf(Collection, Class)} instead of this method. * * @param collection the collection whose complement should be stored in the enum set * @return a new, modifiable {@code EnumSet} containing all values of the enum that aren't present * in the given collection * @throws IllegalArgumentException if {@code collection} is not an {@code EnumSet} instance and * contains no elements */ @J2ktIncompatible @GwtIncompatible // EnumSet.complementOf public static <E extends Enum<E>> EnumSet<E> complementOf(Collection<E> collection) { if (collection instanceof EnumSet) { return EnumSet.complementOf((EnumSet<E>) collection); } checkArgument( !collection.isEmpty(), "collection is empty; use the other version of this method"); Class<E> type = collection.iterator().next().getDeclaringClass(); return makeComplementByHand(collection, type); } /** * Creates an {@code EnumSet} consisting of all enum values that are not in the specified * collection. This is equivalent to {@link EnumSet#complementOf}, but can act on any input * collection, as long as the elements are of enum type. * * @param collection the collection whose complement should be stored in the {@code EnumSet} * @param type the type of the elements in the set * @return a new, modifiable {@code EnumSet} initially containing all the values of the enum not * present in the given collection */ @J2ktIncompatible @GwtIncompatible // EnumSet.complementOf public static <E extends Enum<E>> EnumSet<E> complementOf( Collection<E> collection, Class<E> type) { checkNotNull(collection); return (collection instanceof EnumSet) ? EnumSet.complementOf((EnumSet<E>) collection) : makeComplementByHand(collection, type); } @J2ktIncompatible @GwtIncompatible private static <E extends Enum<E>> EnumSet<E> makeComplementByHand( Collection<E> collection, Class<E> type) { EnumSet<E> result = EnumSet.allOf(type); result.removeAll(collection); return result; } /** * Returns a set backed by the specified map. The resulting set displays the same ordering, * concurrency, and performance characteristics as the backing map. In essence, this factory * method provides a {@link Set} implementation corresponding to any {@link Map} implementation. * There is no need to use this method on a {@link Map} implementation that already has a * corresponding {@link Set} implementation (such as {@link java.util.HashMap} or {@link * java.util.TreeMap}). * * <p>Each method invocation on the set returned by this method results in exactly one method * invocation on the backing map or its {@code keySet} view, with one exception. The {@code * addAll} method is implemented as a sequence of {@code put} invocations on the backing map. * * <p>The specified map must be empty at the time this method is invoked, and should not be * accessed directly after this method returns. These conditions are ensured if the map is created * empty, passed directly to this method, and no reference to the map is retained, as illustrated * in the following code fragment: * * <pre>{@code * Set<Object> identityHashSet = Sets.newSetFromMap( * new IdentityHashMap<Object, Boolean>()); * }</pre> * * <p>The returned set is serializable if the backing map is. * * @param map the backing map * @return the set backed by the map * @throws IllegalArgumentException if {@code map} is not empty * @deprecated Use {@link Collections#newSetFromMap} instead. */ @Deprecated public static <E extends @Nullable Object> Set<E> newSetFromMap( Map<E, Boolean> map) { return Collections.newSetFromMap(map); } /** * An unmodifiable view of a set which may be backed by other sets; this view will change as the * backing sets do. Contains methods to copy the data into a new set which will then remain * stable. There is usually no reason to retain a reference of type {@code SetView}; typically, * you either use it as a plain {@link Set}, or immediately invoke {@link #immutableCopy} or * {@link #copyInto} and forget the {@code SetView} itself. * * @since 2.0 */ public abstract static class SetView<E extends @Nullable Object> extends AbstractSet<E> { private SetView() {} // no subclasses but our own /** * Returns an immutable copy of the current contents of this set view. Does not support null * elements. * * <p><b>Warning:</b> this may have unexpected results if a backing set of this view uses a * nonstandard notion of equivalence, for example if it is a {@link TreeSet} using a comparator * that is inconsistent with {@link Object#equals(Object)}. */ @SuppressWarnings("nullness") // Unsafe, but we can't fix it now. public ImmutableSet<@NonNull E> immutableCopy() { return ImmutableSet.copyOf((SetView<@NonNull E>) this); } /** * Copies the current contents of this set view into an existing set. This method has equivalent * behavior to {@code set.addAll(this)}, assuming that all the sets involved are based on the * same notion of equivalence. * * @return a reference to {@code set}, for convenience */ // Note: S should logically extend Set<? super E> but can't due to either // some javac bug or some weirdness in the spec, not sure which. @CanIgnoreReturnValue public <S extends Set<E>> S copyInto(S set) { set.addAll(this); return set; } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @CanIgnoreReturnValue @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final boolean add(@ParametricNullness E e) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @CanIgnoreReturnValue @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final boolean remove(@CheckForNull Object object) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @CanIgnoreReturnValue @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final boolean addAll(Collection<? extends E> newElements) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @CanIgnoreReturnValue @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final boolean removeAll(Collection<?> oldElements) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @CanIgnoreReturnValue @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final boolean removeIf(java.util.function.Predicate<? super E> filter) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @CanIgnoreReturnValue @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final boolean retainAll(Collection<?> elementsToKeep) { throw new UnsupportedOperationException(); } /** * Guaranteed to throw an exception and leave the collection unmodified. * * @throws UnsupportedOperationException always * @deprecated Unsupported operation. */ @Deprecated @Override @DoNotCall("Always throws UnsupportedOperationException") public final void clear() { throw new UnsupportedOperationException(); } /** * Scope the return type to {@link UnmodifiableIterator} to ensure this is an unmodifiable view. * * @since 20.0 (present with return type {@link Iterator} since 2.0) */ @Override public abstract UnmodifiableIterator<E> iterator(); } /** * Returns an unmodifiable <b>view</b> of the union of two sets. The returned set contains all * elements that are contained in either backing set. Iterating over the returned set iterates * first over all the elements of {@code set1}, then over each element of {@code set2}, in order, * that is not contained in {@code set1}. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based on different * equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a * {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}. */ public static <E extends @Nullable Object> SetView<E> union( final Set<? extends E> set1, final Set<? extends E> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); return new SetView<E>() { @Override public int size() { int size = set1.size(); for (E e : set2) { if (!set1.contains(e)) { size++; } } return size; } @Override public boolean isEmpty() { return set1.isEmpty() && set2.isEmpty(); } @Override public UnmodifiableIterator<E> iterator() { return new AbstractIterator<E>() { final Iterator<? extends E> itr1 = set1.iterator(); final Iterator<? extends E> itr2 = set2.iterator(); @Override @CheckForNull protected E computeNext() { if (itr1.hasNext()) { return itr1.next(); } while (itr2.hasNext()) { E e = itr2.next(); if (!set1.contains(e)) { return e; } } return endOfData(); } }; } @Override public Stream<E> stream() { return Stream.concat(set1.stream(), set2.stream().filter((E e) -> !set1.contains(e))); } @Override public Stream<E> parallelStream() { return stream().parallel(); } @Override public boolean contains(@CheckForNull Object object) { return set1.contains(object) || set2.contains(object); } @Override public <S extends Set<E>> S copyInto(S set) { set.addAll(set1); set.addAll(set2); return set; } @Override @SuppressWarnings({"nullness", "unchecked"}) // see supertype public ImmutableSet<@NonNull E> immutableCopy() { ImmutableSet.Builder<@NonNull E> builder = new ImmutableSet.Builder<@NonNull E>() .addAll((Iterable<@NonNull E>) set1) .addAll((Iterable<@NonNull E>) set2); return (ImmutableSet<@NonNull E>) builder.build(); } }; } /** * Returns an unmodifiable <b>view</b> of the intersection of two sets. The returned set contains * all elements that are contained by both backing sets. The iteration order of the returned set * matches that of {@code set1}. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based on different * equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a * {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}. * * <p><b>Note:</b> The returned view performs slightly better when {@code set1} is the smaller of * the two sets. If you have reason to believe one of your sets will generally be smaller than the * other, pass it first. Unfortunately, since this method sets the generic type of the returned * set based on the type of the first set passed, this could in rare cases force you to make a * cast, for example: * * <pre>{@code * Set<Object> aFewBadObjects = ... * Set<String> manyBadStrings = ... * * // impossible for a non-String to be in the intersection * SuppressWarnings("unchecked") * Set<String> badStrings = (Set) Sets.intersection( * aFewBadObjects, manyBadStrings); * }</pre> * * <p>This is unfortunate, but should come up only very rarely. */ public static <E extends @Nullable Object> SetView<E> intersection( final Set<E> set1, final Set<?> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); return new SetView<E>() { @Override public UnmodifiableIterator<E> iterator() { return new AbstractIterator<E>() { final Iterator<E> itr = set1.iterator(); @Override @CheckForNull protected E computeNext() { while (itr.hasNext()) { E e = itr.next(); if (set2.contains(e)) { return e; } } return endOfData(); } }; } @Override public Stream<E> stream() { return set1.stream().filter(set2::contains); } @Override public Stream<E> parallelStream() { return set1.parallelStream().filter(set2::contains); } @Override public int size() { int size = 0; for (E e : set1) { if (set2.contains(e)) { size++; } } return size; } @Override public boolean isEmpty() { return Collections.disjoint(set2, set1); } @Override public boolean contains(@CheckForNull Object object) { return set1.contains(object) && set2.contains(object); } @Override public boolean containsAll(Collection<?> collection) { return set1.containsAll(collection) && set2.containsAll(collection); } }; } /** * Returns an unmodifiable <b>view</b> of the difference of two sets. The returned set contains * all elements that are contained by {@code set1} and not contained by {@code set2}. {@code set2} * may also contain elements not present in {@code set1}; these are simply ignored. The iteration * order of the returned set matches that of {@code set1}. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based on different * equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a * {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}. */ public static <E extends @Nullable Object> SetView<E> difference( final Set<E> set1, final Set<?> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); return new SetView<E>() { @Override public UnmodifiableIterator<E> iterator() { return new AbstractIterator<E>() { final Iterator<E> itr = set1.iterator(); @Override @CheckForNull protected E computeNext() { while (itr.hasNext()) { E e = itr.next(); if (!set2.contains(e)) { return e; } } return endOfData(); } }; } @Override public Stream<E> stream() { return set1.stream().filter(e -> !set2.contains(e)); } @Override public Stream<E> parallelStream() { return set1.parallelStream().filter(e -> !set2.contains(e)); } @Override public int size() { int size = 0; for (E e : set1) { if (!set2.contains(e)) { size++; } } return size; } @Override public boolean isEmpty() { return set2.containsAll(set1); } @Override public boolean contains(@CheckForNull Object element) { return set1.contains(element) && !set2.contains(element); } }; } /** * Returns an unmodifiable <b>view</b> of the symmetric difference of two sets. The returned set * contains all elements that are contained in either {@code set1} or {@code set2} but not in * both. The iteration order of the returned set is undefined. * * <p>Results are undefined if {@code set1} and {@code set2} are sets based on different * equivalence relations, for example if {@code set1} is a {@link HashSet} and {@code set2} is a * {@link TreeSet} or the {@link Map#keySet} of an {@code IdentityHashMap}. * * @since 3.0 */ public static <E extends @Nullable Object> SetView<E> symmetricDifference( final Set<? extends E> set1, final Set<? extends E> set2) { checkNotNull(set1, "set1"); checkNotNull(set2, "set2"); return new SetView<E>() { @Override public UnmodifiableIterator<E> iterator() { final Iterator<? extends E> itr1 = set1.iterator(); final Iterator<? extends E> itr2 = set2.iterator(); return new AbstractIterator<E>() { @Override @CheckForNull public E computeNext() { while (itr1.hasNext()) { E elem1 = itr1.next(); if (!set2.contains(elem1)) { return elem1; } } while (itr2.hasNext()) { E elem2 = itr2.next(); if (!set1.contains(elem2)) { return elem2; } } return endOfData(); } }; } @Override public int size() { int size = 0; for (E e : set1) { if (!set2.contains(e)) { size++; } } for (E e : set2) { if (!set1.contains(e)) { size++; } } return size; } @Override public boolean isEmpty() { return set1.equals(set2); } @Override public boolean contains(@CheckForNull Object element) { return set1.contains(element) ^ set2.contains(element); } }; } /** * Returns the elements of {@code unfiltered} that satisfy a predicate. The returned set is a live * view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting set's iterator does not support {@code remove()}, but all other set methods * are supported. When given an element that doesn't satisfy the predicate, the set's {@code * add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods * such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements * that satisfy the filter will be removed from the underlying set. * * <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in * the underlying set and determine which elements satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and * use the copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at * {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link * Iterables#filter(Iterable, Class)} for related functionality.) * * <p><b>Java 8+ users:</b> many use cases for this method are better addressed by {@link * java.util.stream.Stream#filter}. This method is not being deprecated, but we gently encourage * you to migrate to streams. */ // TODO(kevinb): how to omit that last sentence when building GWT javadoc? public static <E extends @Nullable Object> Set<E> filter( Set<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof SortedSet) { return filter((SortedSet<E>) unfiltered, predicate); } if (unfiltered instanceof FilteredSet) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate); return new FilteredSet<>((Set<E>) filtered.unfiltered, combinedPredicate); } return new FilteredSet<>(checkNotNull(unfiltered), checkNotNull(predicate)); } /** * Returns the elements of a {@code SortedSet}, {@code unfiltered}, that satisfy a predicate. The * returned set is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting set's iterator does not support {@code remove()}, but all other set methods * are supported. When given an element that doesn't satisfy the predicate, the set's {@code * add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods * such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements * that satisfy the filter will be removed from the underlying set. * * <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in * the underlying set and determine which elements satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and * use the copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at * {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link * Iterables#filter(Iterable, Class)} for related functionality.) * * @since 11.0 */ public static <E extends @Nullable Object> SortedSet<E> filter( SortedSet<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof FilteredSet) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate); return new FilteredSortedSet<>((SortedSet<E>) filtered.unfiltered, combinedPredicate); } return new FilteredSortedSet<>(checkNotNull(unfiltered), checkNotNull(predicate)); } /** * Returns the elements of a {@code NavigableSet}, {@code unfiltered}, that satisfy a predicate. * The returned set is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting set's iterator does not support {@code remove()}, but all other set methods * are supported. When given an element that doesn't satisfy the predicate, the set's {@code * add()} and {@code addAll()} methods throw an {@link IllegalArgumentException}. When methods * such as {@code removeAll()} and {@code clear()} are called on the filtered set, only elements * that satisfy the filter will be removed from the underlying set. * * <p>The returned set isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered set's methods, such as {@code size()}, iterate across every element in * the underlying set and determine which elements satisfy the filter. When a live view is * <i>not</i> needed, it may be faster to copy {@code Iterables.filter(unfiltered, predicate)} and * use the copy. * * <p><b>Warning:</b> {@code predicate} must be <i>consistent with equals</i>, as documented at * {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. (See {@link * Iterables#filter(Iterable, Class)} for related functionality.) * * @since 14.0 */ @GwtIncompatible // NavigableSet public static <E extends @Nullable Object> NavigableSet<E> filter( NavigableSet<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof FilteredSet) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredSet<E> filtered = (FilteredSet<E>) unfiltered; Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate); return new FilteredNavigableSet<>((NavigableSet<E>) filtered.unfiltered, combinedPredicate); } return new FilteredNavigableSet<>(checkNotNull(unfiltered), checkNotNull(predicate)); } private static class FilteredSet<E extends @Nullable Object> extends FilteredCollection<E> implements Set<E> { FilteredSet(Set<E> unfiltered, Predicate<? super E> predicate) { super(unfiltered, predicate); } @Override public boolean equals(@CheckForNull Object object) { return equalsImpl(this, object); } @Override public int hashCode() { return hashCodeImpl(this); } } private static class FilteredSortedSet<E extends @Nullable Object> extends FilteredSet<E> implements SortedSet<E> { FilteredSortedSet(SortedSet<E> unfiltered, Predicate<? super E> predicate) { super(unfiltered, predicate); } @Override @CheckForNull public Comparator<? super E> comparator() { return ((SortedSet<E>) unfiltered).comparator(); } @Override public SortedSet<E> subSet(@ParametricNullness E fromElement, @ParametricNullness E toElement) { return new FilteredSortedSet<>( ((SortedSet<E>) unfiltered).subSet(fromElement, toElement), predicate); } @Override public SortedSet<E> headSet(@ParametricNullness E toElement) { return new FilteredSortedSet<>(((SortedSet<E>) unfiltered).headSet(toElement), predicate); } @Override public SortedSet<E> tailSet(@ParametricNullness E fromElement) { return new FilteredSortedSet<>(((SortedSet<E>) unfiltered).tailSet(fromElement), predicate); } @Override @ParametricNullness public E first() { return Iterators.find(unfiltered.iterator(), predicate); } @Override @ParametricNullness public E last() { SortedSet<E> sortedUnfiltered = (SortedSet<E>) unfiltered; while (true) { E element = sortedUnfiltered.last(); if (predicate.apply(element)) { return element; } sortedUnfiltered = sortedUnfiltered.headSet(element); } } } @GwtIncompatible // NavigableSet private static class FilteredNavigableSet<E extends @Nullable Object> extends FilteredSortedSet<E> implements NavigableSet<E> { FilteredNavigableSet(NavigableSet<E> unfiltered, Predicate<? super E> predicate) { super(unfiltered, predicate); } NavigableSet<E> unfiltered() { return (NavigableSet<E>) unfiltered; } @Override @CheckForNull public E lower(@ParametricNullness E e) { return Iterators.find(unfiltered().headSet(e, false).descendingIterator(), predicate, null); } @Override @CheckForNull public E floor(@ParametricNullness E e) { return Iterators.find(unfiltered().headSet(e, true).descendingIterator(), predicate, null); } @Override @CheckForNull public E ceiling(@ParametricNullness E e) { return Iterables.find(unfiltered().tailSet(e, true), predicate, null); } @Override @CheckForNull public E higher(@ParametricNullness E e) { return Iterables.find(unfiltered().tailSet(e, false), predicate, null); } @Override @CheckForNull public E pollFirst() { return Iterables.removeFirstMatching(unfiltered(), predicate); } @Override @CheckForNull public E pollLast() { return Iterables.removeFirstMatching(unfiltered().descendingSet(), predicate); } @Override public NavigableSet<E> descendingSet() { return Sets.filter(unfiltered().descendingSet(), predicate); } @Override public Iterator<E> descendingIterator() { return Iterators.filter(unfiltered().descendingIterator(), predicate); } @Override @ParametricNullness public E last() { return Iterators.find(unfiltered().descendingIterator(), predicate); } @Override public NavigableSet<E> subSet( @ParametricNullness E fromElement, boolean fromInclusive, @ParametricNullness E toElement, boolean toInclusive) { return filter( unfiltered().subSet(fromElement, fromInclusive, toElement, toInclusive), predicate); } @Override public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) { return filter(unfiltered().headSet(toElement, inclusive), predicate); } @Override public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) { return filter(unfiltered().tailSet(fromElement, inclusive), predicate); } } /** * Returns every possible list that can be formed by choosing one element from each of the given * sets in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian * product</a>" of the sets. For example: * * <pre>{@code * Sets.cartesianProduct(ImmutableList.of( * ImmutableSet.of(1, 2), * ImmutableSet.of("A", "B", "C"))) * }</pre> * * <p>returns a set containing six lists: * * <ul> * <li>{@code ImmutableList.of(1, "A")} * <li>{@code ImmutableList.of(1, "B")} * <li>{@code ImmutableList.of(1, "C")} * <li>{@code ImmutableList.of(2, "A")} * <li>{@code ImmutableList.of(2, "B")} * <li>{@code ImmutableList.of(2, "C")} * </ul> * * <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian * products that you would get from nesting for loops: * * <pre>{@code * for (B b0 : sets.get(0)) { * for (B b1 : sets.get(1)) { * ... * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); * // operate on tuple * } * } * }</pre> * * <p>Note that if any input set is empty, the Cartesian product will also be empty. If no sets at * all are provided (an empty list), the resulting Cartesian product has one element, an empty * list (counter-intuitive, but mathematically consistent). * * <p><i>Performance notes:</i> while the cartesian product of sets of size {@code m, n, p} is a * set of size {@code m x n x p}, its actual memory consumption is much smaller. When the * cartesian set is constructed, the input sets are merely copied. Only as the resulting set is * iterated are the individual lists created, and these are not retained after iteration. * * @param sets the sets to choose elements from, in the order that the elements chosen from those * sets should appear in the resulting lists * @param <B> any common base class shared by all axes (often just {@link Object}) * @return the Cartesian product, as an immutable set containing immutable lists * @throws NullPointerException if {@code sets}, any one of the {@code sets}, or any element of a * provided set is null * @throws IllegalArgumentException if the cartesian product size exceeds the {@code int} range * @since 2.0 */ public static <B> Set<List<B>> cartesianProduct(List<? extends Set<? extends B>> sets) { return CartesianSet.create(sets); } /** * Returns every possible list that can be formed by choosing one element from each of the given * sets in order; the "n-ary <a href="http://en.wikipedia.org/wiki/Cartesian_product">Cartesian * product</a>" of the sets. For example: * * <pre>{@code * Sets.cartesianProduct( * ImmutableSet.of(1, 2), * ImmutableSet.of("A", "B", "C")) * }</pre> * * <p>returns a set containing six lists: * * <ul> * <li>{@code ImmutableList.of(1, "A")} * <li>{@code ImmutableList.of(1, "B")} * <li>{@code ImmutableList.of(1, "C")} * <li>{@code ImmutableList.of(2, "A")} * <li>{@code ImmutableList.of(2, "B")} * <li>{@code ImmutableList.of(2, "C")} * </ul> * * <p>The result is guaranteed to be in the "traditional", lexicographical order for Cartesian * products that you would get from nesting for loops: * * <pre>{@code * for (B b0 : sets.get(0)) { * for (B b1 : sets.get(1)) { * ... * ImmutableList<B> tuple = ImmutableList.of(b0, b1, ...); * // operate on tuple * } * } * }</pre> * * <p>Note that if any input set is empty, the Cartesian product will also be empty. If no sets at * all are provided (an empty list), the resulting Cartesian product has one element, an empty * list (counter-intuitive, but mathematically consistent). * * <p><i>Performance notes:</i> while the cartesian product of sets of size {@code m, n, p} is a * set of size {@code m x n x p}, its actual memory consumption is much smaller. When the * cartesian set is constructed, the input sets are merely copied. Only as the resulting set is * iterated are the individual lists created, and these are not retained after iteration. * * @param sets the sets to choose elements from, in the order that the elements chosen from those * sets should appear in the resulting lists * @param <B> any common base class shared by all axes (often just {@link Object}) * @return the Cartesian product, as an immutable set containing immutable lists * @throws NullPointerException if {@code sets}, any one of the {@code sets}, or any element of a * provided set is null * @throws IllegalArgumentException if the cartesian product size exceeds the {@code int} range * @since 2.0 */ @SafeVarargs public static <B> Set<List<B>> cartesianProduct(Set<? extends B>... sets) { return cartesianProduct(Arrays.asList(sets)); } private static final class CartesianSet<E> extends ForwardingCollection<List<E>> implements Set<List<E>> { private final transient ImmutableList<ImmutableSet<E>> axes; private final transient CartesianList<E> delegate; static <E> Set<List<E>> create(List<? extends Set<? extends E>> sets) { ImmutableList.Builder<ImmutableSet<E>> axesBuilder = new ImmutableList.Builder<>(sets.size()); for (Set<? extends E> set : sets) { ImmutableSet<E> copy = ImmutableSet.copyOf(set); if (copy.isEmpty()) { return ImmutableSet.of(); } axesBuilder.add(copy); } final ImmutableList<ImmutableSet<E>> axes = axesBuilder.build(); ImmutableList<List<E>> listAxes = new ImmutableList<List<E>>() { @Override public int size() { return axes.size(); } @Override public List<E> get(int index) { return axes.get(index).asList(); } @Override boolean isPartialView() { return true; } // redeclare to help optimizers with b/310253115 @SuppressWarnings("RedundantOverride") @Override @J2ktIncompatible // serialization @GwtIncompatible // serialization Object writeReplace() { return super.writeReplace(); } }; return new CartesianSet<E>(axes, new CartesianList<E>(listAxes)); } private CartesianSet(ImmutableList<ImmutableSet<E>> axes, CartesianList<E> delegate) { this.axes = axes; this.delegate = delegate; } @Override protected Collection<List<E>> delegate() { return delegate; } @Override public boolean contains(@CheckForNull Object object) { if (!(object instanceof List)) { return false; } List<?> list = (List<?>) object; if (list.size() != axes.size()) { return false; } int i = 0; for (Object o : list) { if (!axes.get(i).contains(o)) { return false; } i++; } return true; } @Override public boolean equals(@CheckForNull Object object) { // Warning: this is broken if size() == 0, so it is critical that we // substitute an empty ImmutableSet to the user in place of this if (object instanceof CartesianSet) { CartesianSet<?> that = (CartesianSet<?>) object; return this.axes.equals(that.axes); } if (object instanceof Set) { Set<?> that = (Set<?>) object; return this.size() == that.size() && this.containsAll(that); } return false; } @Override public int hashCode() { // Warning: this is broken if size() == 0, so it is critical that we // substitute an empty ImmutableSet to the user in place of this // It's a weird formula, but tests prove it works. int adjust = size() - 1; for (int i = 0; i < axes.size(); i++) { adjust *= 31; adjust = ~~adjust; // in GWT, we have to deal with integer overflow carefully } int hash = 1; for (Set<E> axis : axes) { hash = 31 * hash + (size() / axis.size() * axis.hashCode()); hash = ~~hash; } hash += adjust; return ~~hash; } } /** * Returns the set of all possible subsets of {@code set}. For example, {@code * powerSet(ImmutableSet.of(1, 2))} returns the set {@code {{}, {1}, {2}, {1, 2}}}. * * <p>Elements appear in these subsets in the same iteration order as they appeared in the input * set. The order in which these subsets appear in the outer set is undefined. Note that the power * set of the empty set is not the empty set, but a one-element set containing the empty set. * * <p>The returned set and its constituent sets use {@code equals} to decide whether two elements * are identical, even if the input set uses a different concept of equivalence. * * <p><i>Performance notes:</i> while the power set of a set with size {@code n} is of size {@code * 2^n}, its memory usage is only {@code O(n)}. When the power set is constructed, the input set * is merely copied. Only as the power set is iterated are the individual subsets created, and * these subsets themselves occupy only a small constant amount of memory. * * @param set the set of elements to construct a power set from * @return the power set, as an immutable set of immutable sets * @throws IllegalArgumentException if {@code set} has more than 30 unique elements (causing the * power set size to exceed the {@code int} range) * @throws NullPointerException if {@code set} is or contains {@code null} * @see <a href="http://en.wikipedia.org/wiki/Power_set">Power set article at Wikipedia</a> * @since 4.0 */ @GwtCompatible(serializable = false) public static <E> Set<Set<E>> powerSet(Set<E> set) { return new PowerSet<E>(set); } private static final class SubSet<E> extends AbstractSet<E> { private final ImmutableMap<E, Integer> inputSet; private final int mask; SubSet(ImmutableMap<E, Integer> inputSet, int mask) { this.inputSet = inputSet; this.mask = mask; } @Override public Iterator<E> iterator() { return new UnmodifiableIterator<E>() { final ImmutableList<E> elements = inputSet.keySet().asList(); int remainingSetBits = mask; @Override public boolean hasNext() { return remainingSetBits != 0; } @Override public E next() { int index = Integer.numberOfTrailingZeros(remainingSetBits); if (index == 32) { throw new NoSuchElementException(); } remainingSetBits &= ~(1 << index); return elements.get(index); } }; } @Override public int size() { return Integer.bitCount(mask); } @Override public boolean contains(@CheckForNull Object o) { Integer index = inputSet.get(o); return index != null && (mask & (1 << index)) != 0; } } private static final class PowerSet<E> extends AbstractSet<Set<E>> { final ImmutableMap<E, Integer> inputSet; PowerSet(Set<E> input) { checkArgument( input.size() <= 30, "Too many elements to create power set: %s > 30", input.size()); this.inputSet = Maps.indexMap(input); } @Override public int size() { return 1 << inputSet.size(); } @Override public boolean isEmpty() { return false; } @Override public Iterator<Set<E>> iterator() { return new AbstractIndexedListIterator<Set<E>>(size()) { @Override protected Set<E> get(final int setBits) { return new SubSet<>(inputSet, setBits); } }; } @Override public boolean contains(@CheckForNull Object obj) { if (obj instanceof Set) { Set<?> set = (Set<?>) obj; return inputSet.keySet().containsAll(set); } return false; } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof PowerSet) { PowerSet<?> that = (PowerSet<?>) obj; return inputSet.keySet().equals(that.inputSet.keySet()); } return super.equals(obj); } @Override public int hashCode() { /* * The sum of the sums of the hash codes in each subset is just the sum of * each input element's hash code times the number of sets that element * appears in. Each element appears in exactly half of the 2^n sets, so: */ return inputSet.keySet().hashCode() << (inputSet.size() - 1); } @Override public String toString() { return "powerSet(" + inputSet + ")"; } } /** * Returns the set of all subsets of {@code set} of size {@code size}. For example, {@code * combinations(ImmutableSet.of(1, 2, 3), 2)} returns the set {@code {{1, 2}, {1, 3}, {2, 3}}}. * * <p>Elements appear in these subsets in the same iteration order as they appeared in the input * set. The order in which these subsets appear in the outer set is undefined. * * <p>The returned set and its constituent sets use {@code equals} to decide whether two elements * are identical, even if the input set uses a different concept of equivalence. * * <p><i>Performance notes:</i> the memory usage of the returned set is only {@code O(n)}. When * the result set is constructed, the input set is merely copied. Only as the result set is * iterated are the individual subsets created. Each of these subsets occupies an additional O(n) * memory but only for as long as the user retains a reference to it. That is, the set returned by * {@code combinations} does not retain the individual subsets. * * @param set the set of elements to take combinations of * @param size the number of elements per combination * @return the set of all combinations of {@code size} elements from {@code set} * @throws IllegalArgumentException if {@code size} is not between 0 and {@code set.size()} * inclusive * @throws NullPointerException if {@code set} is or contains {@code null} * @since 23.0 */ public static <E> Set<Set<E>> combinations(Set<E> set, final int size) { final ImmutableMap<E, Integer> index = Maps.indexMap(set); checkNonnegative(size, "size"); checkArgument(size <= index.size(), "size (%s) must be <= set.size() (%s)", size, index.size()); if (size == 0) { return ImmutableSet.<Set<E>>of(ImmutableSet.<E>of()); } else if (size == index.size()) { return ImmutableSet.<Set<E>>of(index.keySet()); } return new AbstractSet<Set<E>>() { @Override public boolean contains(@CheckForNull Object o) { if (o instanceof Set) { Set<?> s = (Set<?>) o; return s.size() == size && index.keySet().containsAll(s); } return false; } @Override public Iterator<Set<E>> iterator() { return new AbstractIterator<Set<E>>() { final BitSet bits = new BitSet(index.size()); @Override @CheckForNull protected Set<E> computeNext() { if (bits.isEmpty()) { bits.set(0, size); } else { int firstSetBit = bits.nextSetBit(0); int bitToFlip = bits.nextClearBit(firstSetBit); if (bitToFlip == index.size()) { return endOfData(); } /* * The current set in sorted order looks like * {firstSetBit, firstSetBit + 1, ..., bitToFlip - 1, ...} * where it does *not* contain bitToFlip. * * The next combination is * * {0, 1, ..., bitToFlip - firstSetBit - 2, bitToFlip, ...} * * This is lexicographically next if you look at the combinations in descending order * e.g. {2, 1, 0}, {3, 1, 0}, {3, 2, 0}, {3, 2, 1}, {4, 1, 0}... */ bits.set(0, bitToFlip - firstSetBit - 1); bits.clear(bitToFlip - firstSetBit - 1, bitToFlip); bits.set(bitToFlip); } final BitSet copy = (BitSet) bits.clone(); return new AbstractSet<E>() { @Override public boolean contains(@CheckForNull Object o) { Integer i = index.get(o); return i != null && copy.get(i); } @Override public Iterator<E> iterator() { return new AbstractIterator<E>() { int i = -1; @Override @CheckForNull protected E computeNext() { i = copy.nextSetBit(i + 1); if (i == -1) { return endOfData(); } return index.keySet().asList().get(i); } }; } @Override public int size() { return size; } }; } }; } @Override public int size() { return IntMath.binomial(index.size(), size); } @Override public String toString() { return "Sets.combinations(" + index.keySet() + ", " + size + ")"; } }; } /** An implementation for {@link Set#hashCode()}. */ static int hashCodeImpl(Set<?> s) { int hashCode = 0; for (Object o : s) { hashCode += o != null ? o.hashCode() : 0; hashCode = ~~hashCode; // Needed to deal with unusual integer overflow in GWT. } return hashCode; } /** An implementation for {@link Set#equals(Object)}. */ static boolean equalsImpl(Set<?> s, @CheckForNull Object object) { if (s == object) { return true; } if (object instanceof Set) { Set<?> o = (Set<?>) object; try { return s.size() == o.size() && s.containsAll(o); } catch (NullPointerException | ClassCastException ignored) { return false; } } return false; } /** * Returns an unmodifiable view of the specified navigable set. This method allows modules to * provide users with "read-only" access to internal navigable sets. Query operations on the * returned set "read through" to the specified set, and attempts to modify the returned set, * whether direct or via its collection views, result in an {@code UnsupportedOperationException}. * * <p>The returned navigable set will be serializable if the specified navigable set is * serializable. * * <p><b>Java 8+ users and later:</b> Prefer {@link Collections#unmodifiableNavigableSet}. * * @param set the navigable set for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified navigable set * @since 12.0 */ public static <E extends @Nullable Object> NavigableSet<E> unmodifiableNavigableSet( NavigableSet<E> set) { if (set instanceof ImmutableCollection || set instanceof UnmodifiableNavigableSet) { return set; } return new UnmodifiableNavigableSet<>(set); } static final class UnmodifiableNavigableSet<E extends @Nullable Object> extends ForwardingSortedSet<E> implements NavigableSet<E>, Serializable { private final NavigableSet<E> delegate; private final SortedSet<E> unmodifiableDelegate; UnmodifiableNavigableSet(NavigableSet<E> delegate) { this.delegate = checkNotNull(delegate); this.unmodifiableDelegate = Collections.unmodifiableSortedSet(delegate); } @Override protected SortedSet<E> delegate() { return unmodifiableDelegate; } // default methods not forwarded by ForwardingSortedSet @Override public boolean removeIf(java.util.function.Predicate<? super E> filter) { throw new UnsupportedOperationException(); } @Override public Stream<E> stream() { return delegate.stream(); } @Override public Stream<E> parallelStream() { return delegate.parallelStream(); } @Override public void forEach(Consumer<? super E> action) { delegate.forEach(action); } @Override @CheckForNull public E lower(@ParametricNullness E e) { return delegate.lower(e); } @Override @CheckForNull public E floor(@ParametricNullness E e) { return delegate.floor(e); } @Override @CheckForNull public E ceiling(@ParametricNullness E e) { return delegate.ceiling(e); } @Override @CheckForNull public E higher(@ParametricNullness E e) { return delegate.higher(e); } @Override @CheckForNull public E pollFirst() { throw new UnsupportedOperationException(); } @Override @CheckForNull public E pollLast() { throw new UnsupportedOperationException(); } @LazyInit @CheckForNull private transient UnmodifiableNavigableSet<E> descendingSet; @Override public NavigableSet<E> descendingSet() { UnmodifiableNavigableSet<E> result = descendingSet; if (result == null) { result = descendingSet = new UnmodifiableNavigableSet<>(delegate.descendingSet()); result.descendingSet = this; } return result; } @Override public Iterator<E> descendingIterator() { return Iterators.unmodifiableIterator(delegate.descendingIterator()); } @Override public NavigableSet<E> subSet( @ParametricNullness E fromElement, boolean fromInclusive, @ParametricNullness E toElement, boolean toInclusive) { return unmodifiableNavigableSet( delegate.subSet(fromElement, fromInclusive, toElement, toInclusive)); } @Override public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) { return unmodifiableNavigableSet(delegate.headSet(toElement, inclusive)); } @Override public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) { return unmodifiableNavigableSet(delegate.tailSet(fromElement, inclusive)); } private static final long serialVersionUID = 0; } /** * Returns a synchronized (thread-safe) navigable set backed by the specified navigable set. In * order to guarantee serial access, it is critical that <b>all</b> access to the backing * navigable set is accomplished through the returned navigable set (or its views). * * <p>It is imperative that the user manually synchronize on the returned sorted set when * iterating over it or any of its {@code descendingSet}, {@code subSet}, {@code headSet}, or * {@code tailSet} views. * * <pre>{@code * NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>()); * ... * synchronized (set) { * // Must be in the synchronized block * Iterator<E> it = set.iterator(); * while (it.hasNext()) { * foo(it.next()); * } * } * }</pre> * * <p>or: * * <pre>{@code * NavigableSet<E> set = synchronizedNavigableSet(new TreeSet<E>()); * NavigableSet<E> set2 = set.descendingSet().headSet(foo); * ... * synchronized (set) { // Note: set, not set2!!! * // Must be in the synchronized block * Iterator<E> it = set2.descendingIterator(); * while (it.hasNext()) * foo(it.next()); * } * } * }</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned navigable set will be serializable if the specified navigable set is * serializable. * * <p><b>Java 8+ users and later:</b> Prefer {@link Collections#synchronizedNavigableSet}. * * @param navigableSet the navigable set to be "wrapped" in a synchronized navigable set. * @return a synchronized view of the specified navigable set. * @since 13.0 */ @GwtIncompatible // NavigableSet public static <E extends @Nullable Object> NavigableSet<E> synchronizedNavigableSet( NavigableSet<E> navigableSet) { return Synchronized.navigableSet(navigableSet); } /** Remove each element in an iterable from a set. */ static boolean removeAllImpl(Set<?> set, Iterator<?> iterator) { boolean changed = false; while (iterator.hasNext()) { changed |= set.remove(iterator.next()); } return changed; } static boolean removeAllImpl(Set<?> set, Collection<?> collection) { checkNotNull(collection); // for GWT if (collection instanceof Multiset) { collection = ((Multiset<?>) collection).elementSet(); } /* * AbstractSet.removeAll(List) has quadratic behavior if the list size * is just more than the set's size. We augment the test by * assuming that sets have fast contains() performance, and other * collections don't. See * http://code.google.com/p/guava-libraries/issues/detail?id=1013 */ if (collection instanceof Set && collection.size() > set.size()) { return Iterators.removeAll(set.iterator(), collection); } else { return removeAllImpl(set, collection.iterator()); } } @GwtIncompatible // NavigableSet static class DescendingSet<E extends @Nullable Object> extends ForwardingNavigableSet<E> { private final NavigableSet<E> forward; DescendingSet(NavigableSet<E> forward) { this.forward = forward; } @Override protected NavigableSet<E> delegate() { return forward; } @Override @CheckForNull public E lower(@ParametricNullness E e) { return forward.higher(e); } @Override @CheckForNull public E floor(@ParametricNullness E e) { return forward.ceiling(e); } @Override @CheckForNull public E ceiling(@ParametricNullness E e) { return forward.floor(e); } @Override @CheckForNull public E higher(@ParametricNullness E e) { return forward.lower(e); } @Override @CheckForNull public E pollFirst() { return forward.pollLast(); } @Override @CheckForNull public E pollLast() { return forward.pollFirst(); } @Override public NavigableSet<E> descendingSet() { return forward; } @Override public Iterator<E> descendingIterator() { return forward.iterator(); } @Override public NavigableSet<E> subSet( @ParametricNullness E fromElement, boolean fromInclusive, @ParametricNullness E toElement, boolean toInclusive) { return forward.subSet(toElement, toInclusive, fromElement, fromInclusive).descendingSet(); } @Override public SortedSet<E> subSet(@ParametricNullness E fromElement, @ParametricNullness E toElement) { return standardSubSet(fromElement, toElement); } @Override public NavigableSet<E> headSet(@ParametricNullness E toElement, boolean inclusive) { return forward.tailSet(toElement, inclusive).descendingSet(); } @Override public SortedSet<E> headSet(@ParametricNullness E toElement) { return standardHeadSet(toElement); } @Override public NavigableSet<E> tailSet(@ParametricNullness E fromElement, boolean inclusive) { return forward.headSet(fromElement, inclusive).descendingSet(); } @Override public SortedSet<E> tailSet(@ParametricNullness E fromElement) { return standardTailSet(fromElement); } @SuppressWarnings("unchecked") @Override public Comparator<? super E> comparator() { Comparator<? super E> forwardComparator = forward.comparator(); if (forwardComparator == null) { return (Comparator) Ordering.natural().reverse(); } else { return reverse(forwardComparator); } } // If we inline this, we get a javac error. private static <T extends @Nullable Object> Ordering<T> reverse(Comparator<T> forward) { return Ordering.from(forward).reverse(); } @Override @ParametricNullness public E first() { return forward.last(); } @Override @ParametricNullness public E last() { return forward.first(); } @Override public Iterator<E> iterator() { return forward.descendingIterator(); } @Override public @Nullable Object[] toArray() { return standardToArray(); } @Override @SuppressWarnings("nullness") // b/192354773 in our checker affects toArray declarations public <T extends @Nullable Object> T[] toArray(T[] array) { return standardToArray(array); } @Override public String toString() { return standardToString(); } } /** * Returns a view of the portion of {@code set} whose elements are contained by {@code range}. * * <p>This method delegates to the appropriate methods of {@link NavigableSet} (namely {@link * NavigableSet#subSet(Object, boolean, Object, boolean) subSet()}, {@link * NavigableSet#tailSet(Object, boolean) tailSet()}, and {@link NavigableSet#headSet(Object, * boolean) headSet()}) to actually construct the view. Consult these methods for a full * description of the returned view's behavior. * * <p><b>Warning:</b> {@code Range}s always represent a range of values using the values' natural * ordering. {@code NavigableSet} on the other hand can specify a custom ordering via a {@link * Comparator}, which can violate the natural ordering. Using this method (or in general using * {@code Range}) with unnaturally-ordered sets can lead to unexpected and undefined behavior. * * @since 20.0 */ @GwtIncompatible // NavigableSet public static <K extends Comparable<? super K>> NavigableSet<K> subSet( NavigableSet<K> set, Range<K> range) { if (set.comparator() != null && set.comparator() != Ordering.natural() && range.hasLowerBound() && range.hasUpperBound()) { checkArgument( set.comparator().compare(range.lowerEndpoint(), range.upperEndpoint()) <= 0, "set is using a custom comparator which is inconsistent with the natural ordering."); } if (range.hasLowerBound() && range.hasUpperBound()) { return set.subSet( range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED, range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED); } else if (range.hasLowerBound()) { return set.tailSet(range.lowerEndpoint(), range.lowerBoundType() == BoundType.CLOSED); } else if (range.hasUpperBound()) { return set.headSet(range.upperEndpoint(), range.upperBoundType() == BoundType.CLOSED); } return checkNotNull(set); } }
google/guava
guava/src/com/google/common/collect/Sets.java
379
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package view; /** * View interface. */ public interface View { void render(); }
rajprins/java-design-patterns
layers/src/main/java/view/View.java
380
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.updatemethod; import java.security.SecureRandom; import java.util.ArrayList; import java.util.List; import java.util.Random; import lombok.extern.slf4j.Slf4j; /** * The game world class. Maintain all the objects existed in the game frames. */ @Slf4j public class World { protected List<Entity> entities; protected volatile boolean isRunning; public World() { entities = new ArrayList<>(); isRunning = false; } /** * Main game loop. This loop will always run until the game is over. For * each loop it will process user input, update internal status, and render * the next frames. For more detail please refer to the game-loop pattern. */ private void gameLoop() { while (isRunning) { processInput(); update(); render(); } } /** * Handle any user input that has happened since the last call. In order to * simulate the situation in real-life game, here we add a random time lag. * The time lag ranges from 50 ms to 250 ms. */ private void processInput() { try { int lag = new SecureRandom().nextInt(200) + 50; Thread.sleep(lag); } catch (InterruptedException e) { LOGGER.error(e.getMessage()); Thread.currentThread().interrupt(); } } /** * Update internal status. The update method pattern invoke update method for * each entity in the game. */ private void update() { for (var entity : entities) { entity.update(); } } /** * Render the next frame. Here we do nothing since it is not related to the * pattern. */ private void render() { // Does Nothing } /** * Run game loop. */ public void run() { LOGGER.info("Start game."); isRunning = true; var thread = new Thread(this::gameLoop); thread.start(); } /** * Stop game loop. */ public void stop() { LOGGER.info("Stop game."); isRunning = false; } public void addEntity(Entity entity) { entities.add(entity); } }
rajprins/java-design-patterns
update-method/src/main/java/com/iluwatar/updatemethod/World.java
381
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Internal.toNanosSaturated; import static com.google.common.base.NullnessCasts.uncheckedCastNullableTToT; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import java.io.Serializable; import java.time.Duration; import java.util.concurrent.TimeUnit; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Useful suppliers. * * <p>All methods return serializable suppliers as long as they're given serializable parameters. * * @author Laurence Gonsalves * @author Harry Heymann * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Suppliers { private Suppliers() {} /** * Returns a new supplier which is the composition of the provided function and supplier. In other * words, the new supplier's value will be computed by retrieving the value from {@code supplier}, * and then applying {@code function} to that value. Note that the resulting supplier will not * call {@code supplier} or invoke {@code function} until it is called. */ public static <F extends @Nullable Object, T extends @Nullable Object> Supplier<T> compose( Function<? super F, T> function, Supplier<F> supplier) { return new SupplierComposition<>(function, supplier); } private static class SupplierComposition<F extends @Nullable Object, T extends @Nullable Object> implements Supplier<T>, Serializable { final Function<? super F, T> function; final Supplier<F> supplier; SupplierComposition(Function<? super F, T> function, Supplier<F> supplier) { this.function = checkNotNull(function); this.supplier = checkNotNull(supplier); } @Override @ParametricNullness public T get() { return function.apply(supplier.get()); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof SupplierComposition) { SupplierComposition<?, ?> that = (SupplierComposition<?, ?>) obj; return function.equals(that.function) && supplier.equals(that.supplier); } return false; } @Override public int hashCode() { return Objects.hashCode(function, supplier); } @Override public String toString() { return "Suppliers.compose(" + function + ", " + supplier + ")"; } private static final long serialVersionUID = 0; } /** * Returns a supplier which caches the instance retrieved during the first call to {@code get()} * and returns that value on subsequent calls to {@code get()}. See: <a * href="http://en.wikipedia.org/wiki/Memoization">memoization</a> * * <p>The returned supplier is thread-safe. The delegate's {@code get()} method will be invoked at * most once unless the underlying {@code get()} throws an exception. The supplier's serialized * form does not contain the cached value, which will be recalculated when {@code get()} is called * on the deserialized instance. * * <p>When the underlying delegate throws an exception then this memoizing supplier will keep * delegating calls until it returns valid data. * * <p>If {@code delegate} is an instance created by an earlier call to {@code memoize}, it is * returned directly. */ public static <T extends @Nullable Object> Supplier<T> memoize(Supplier<T> delegate) { if (delegate instanceof NonSerializableMemoizingSupplier || delegate instanceof MemoizingSupplier) { return delegate; } return delegate instanceof Serializable ? new MemoizingSupplier<T>(delegate) : new NonSerializableMemoizingSupplier<T>(delegate); } @VisibleForTesting static class MemoizingSupplier<T extends @Nullable Object> implements Supplier<T>, Serializable { final Supplier<T> delegate; transient volatile boolean initialized; // "value" does not need to be volatile; visibility piggy-backs // on volatile read of "initialized". @CheckForNull transient T value; MemoizingSupplier(Supplier<T> delegate) { this.delegate = checkNotNull(delegate); } @Override @ParametricNullness public T get() { // A 2-field variant of Double Checked Locking. if (!initialized) { synchronized (this) { if (!initialized) { T t = delegate.get(); value = t; initialized = true; return t; } } } // This is safe because we checked `initialized`. return uncheckedCastNullableTToT(value); } @Override public String toString() { return "Suppliers.memoize(" + (initialized ? "<supplier that returned " + value + ">" : delegate) + ")"; } private static final long serialVersionUID = 0; } @VisibleForTesting static class NonSerializableMemoizingSupplier<T extends @Nullable Object> implements Supplier<T> { @SuppressWarnings("UnnecessaryLambda") // Must be a fixed singleton object private static final Supplier<Void> SUCCESSFULLY_COMPUTED = () -> { throw new IllegalStateException(); // Should never get called. }; private volatile Supplier<T> delegate; // "value" does not need to be volatile; visibility piggy-backs on volatile read of "delegate". @CheckForNull private T value; NonSerializableMemoizingSupplier(Supplier<T> delegate) { this.delegate = checkNotNull(delegate); } @Override @ParametricNullness @SuppressWarnings("unchecked") // Cast from Supplier<Void> to Supplier<T> is always valid public T get() { // Because Supplier is read-heavy, we use the "double-checked locking" pattern. if (delegate != SUCCESSFULLY_COMPUTED) { synchronized (this) { if (delegate != SUCCESSFULLY_COMPUTED) { T t = delegate.get(); value = t; delegate = (Supplier<T>) SUCCESSFULLY_COMPUTED; return t; } } } // This is safe because we checked `delegate`. return uncheckedCastNullableTToT(value); } @Override public String toString() { Supplier<T> delegate = this.delegate; return "Suppliers.memoize(" + (delegate == SUCCESSFULLY_COMPUTED ? "<supplier that returned " + value + ">" : delegate) + ")"; } } /** * Returns a supplier that caches the instance supplied by the delegate and removes the cached * value after the specified time has passed. Subsequent calls to {@code get()} return the cached * value if the expiration time has not passed. After the expiration time, a new value is * retrieved, cached, and returned. See: <a * href="http://en.wikipedia.org/wiki/Memoization">memoization</a> * * <p>The returned supplier is thread-safe. The supplier's serialized form does not contain the * cached value, which will be recalculated when {@code get()} is called on the reserialized * instance. The actual memoization does not happen when the underlying delegate throws an * exception. * * <p>When the underlying delegate throws an exception then this memoizing supplier will keep * delegating calls until it returns valid data. * * @param duration the length of time after a value is created that it should stop being returned * by subsequent {@code get()} calls * @param unit the unit that {@code duration} is expressed in * @throws IllegalArgumentException if {@code duration} is not positive * @since 2.0 */ @SuppressWarnings("GoodTime") // Prefer the Duration overload public static <T extends @Nullable Object> Supplier<T> memoizeWithExpiration( Supplier<T> delegate, long duration, TimeUnit unit) { checkNotNull(delegate); checkArgument(duration > 0, "duration (%s %s) must be > 0", duration, unit); return new ExpiringMemoizingSupplier<>(delegate, unit.toNanos(duration)); } /** * Returns a supplier that caches the instance supplied by the delegate and removes the cached * value after the specified time has passed. Subsequent calls to {@code get()} return the cached * value if the expiration time has not passed. After the expiration time, a new value is * retrieved, cached, and returned. See: <a * href="http://en.wikipedia.org/wiki/Memoization">memoization</a> * * <p>The returned supplier is thread-safe. The supplier's serialized form does not contain the * cached value, which will be recalculated when {@code get()} is called on the reserialized * instance. The actual memoization does not happen when the underlying delegate throws an * exception. * * <p>When the underlying delegate throws an exception then this memoizing supplier will keep * delegating calls until it returns valid data. * * @param duration the length of time after a value is created that it should stop being returned * by subsequent {@code get()} calls * @throws IllegalArgumentException if {@code duration} is not positive * @since 33.1.0 */ @Beta // only until we're confident that Java 8+ APIs are safe for our Android users @J2ktIncompatible @GwtIncompatible // java.time.Duration @SuppressWarnings("Java7ApiChecker") // no more dangerous that wherever the user got the Duration @IgnoreJRERequirement public static <T extends @Nullable Object> Supplier<T> memoizeWithExpiration( Supplier<T> delegate, Duration duration) { checkNotNull(delegate); // The alternative of `duration.compareTo(Duration.ZERO) > 0` causes J2ObjC trouble. checkArgument( !duration.isNegative() && !duration.isZero(), "duration (%s) must be > 0", duration); return new ExpiringMemoizingSupplier<>(delegate, toNanosSaturated(duration)); } @VisibleForTesting @SuppressWarnings("GoodTime") // lots of violations static class ExpiringMemoizingSupplier<T extends @Nullable Object> implements Supplier<T>, Serializable { final Supplier<T> delegate; final long durationNanos; @CheckForNull transient volatile T value; // The special value 0 means "not yet initialized". transient volatile long expirationNanos; ExpiringMemoizingSupplier(Supplier<T> delegate, long durationNanos) { this.delegate = delegate; this.durationNanos = durationNanos; } @Override @ParametricNullness public T get() { // Another variant of Double Checked Locking. // // We use two volatile reads. We could reduce this to one by // putting our fields into a holder class, but (at least on x86) // the extra memory consumption and indirection are more // expensive than the extra volatile reads. long nanos = expirationNanos; long now = System.nanoTime(); if (nanos == 0 || now - nanos >= 0) { synchronized (this) { if (nanos == expirationNanos) { // recheck for lost race T t = delegate.get(); value = t; nanos = now + durationNanos; // In the very unlikely event that nanos is 0, set it to 1; // no one will notice 1 ns of tardiness. expirationNanos = (nanos == 0) ? 1 : nanos; return t; } } } // This is safe because we checked `expirationNanos`. return uncheckedCastNullableTToT(value); } @Override public String toString() { // This is a little strange if the unit the user provided was not NANOS, // but we don't want to store the unit just for toString return "Suppliers.memoizeWithExpiration(" + delegate + ", " + durationNanos + ", NANOS)"; } private static final long serialVersionUID = 0; } /** Returns a supplier that always supplies {@code instance}. */ public static <T extends @Nullable Object> Supplier<T> ofInstance( @ParametricNullness T instance) { return new SupplierOfInstance<>(instance); } private static class SupplierOfInstance<T extends @Nullable Object> implements Supplier<T>, Serializable { @ParametricNullness final T instance; SupplierOfInstance(@ParametricNullness T instance) { this.instance = instance; } @Override @ParametricNullness public T get() { return instance; } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof SupplierOfInstance) { SupplierOfInstance<?> that = (SupplierOfInstance<?>) obj; return Objects.equal(instance, that.instance); } return false; } @Override public int hashCode() { return Objects.hashCode(instance); } @Override public String toString() { return "Suppliers.ofInstance(" + instance + ")"; } private static final long serialVersionUID = 0; } /** * Returns a supplier whose {@code get()} method synchronizes on {@code delegate} before calling * it, making it thread-safe. */ public static <T extends @Nullable Object> Supplier<T> synchronizedSupplier( Supplier<T> delegate) { return new ThreadSafeSupplier<>(delegate); } private static class ThreadSafeSupplier<T extends @Nullable Object> implements Supplier<T>, Serializable { final Supplier<T> delegate; ThreadSafeSupplier(Supplier<T> delegate) { this.delegate = checkNotNull(delegate); } @Override @ParametricNullness public T get() { synchronized (delegate) { return delegate.get(); } } @Override public String toString() { return "Suppliers.synchronizedSupplier(" + delegate + ")"; } private static final long serialVersionUID = 0; } /** * Returns a function that accepts a supplier and returns the result of invoking {@link * Supplier#get} on that supplier. * * <p><b>Java 8+ users:</b> use the method reference {@code Supplier::get} instead. * * @since 8.0 */ public static <T extends @Nullable Object> Function<Supplier<T>, T> supplierFunction() { @SuppressWarnings("unchecked") // implementation is "fully variant" SupplierFunction<T> sf = (SupplierFunction<T>) SupplierFunctionImpl.INSTANCE; return sf; } private interface SupplierFunction<T extends @Nullable Object> extends Function<Supplier<T>, T> {} private enum SupplierFunctionImpl implements SupplierFunction<@Nullable Object> { INSTANCE; // Note: This makes T a "pass-through type" @Override @CheckForNull public Object apply(Supplier<@Nullable Object> input) { return input.get(); } @Override public String toString() { return "Suppliers.supplierFunction()"; } } }
google/guava
android/guava/src/com/google/common/base/Suppliers.java
382
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.NullnessCasts.uncheckedCastNullableTToT; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Map; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static utility methods pertaining to {@code com.google.common.base.Function} instances; see that * class for information about migrating to {@code java.util.function}. * * <p>All methods return serializable functions as long as they're given serializable parameters. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/FunctionalExplained">the use of {@code Function}</a>. * * @author Mike Bostock * @author Jared Levy * @since 2.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Functions { private Functions() {} /** * A function equivalent to the method reference {@code Object::toString}, for users not yet using * Java 8. The function simply invokes {@code toString} on its argument and returns the result. It * throws a {@link NullPointerException} on null input. * * <p><b>Warning:</b> The returned function may not be <i>consistent with equals</i> (as * documented at {@link Function#apply}). For example, this function yields different results for * the two equal instances {@code ImmutableSet.of(1, 2)} and {@code ImmutableSet.of(2, 1)}. * * <p><b>Warning:</b> as with all function types in this package, avoid depending on the specific * {@code equals}, {@code hashCode} or {@code toString} behavior of the returned function. A * future migration to {@code java.util.function} will not preserve this behavior. * * <p><b>Java 8+ users:</b> use the method reference {@code Object::toString} instead. In the * future, when this class requires Java 8, this method will be deprecated. See {@link Function} * for more important information about the Java 8+ transition. */ public static Function<Object, String> toStringFunction() { return ToStringFunction.INSTANCE; } // enum singleton pattern private enum ToStringFunction implements Function<Object, String> { INSTANCE; @Override public String apply(Object o) { checkNotNull(o); // eager for GWT. return o.toString(); } @Override public String toString() { return "Functions.toStringFunction()"; } } /** * Returns the identity function. * * <p><b>Discouraged:</b> Prefer using a lambda like {@code v -> v}, which is shorter and often * more readable. */ // implementation is "fully variant"; E has become a "pass-through" type @SuppressWarnings("unchecked") public static <E extends @Nullable Object> Function<E, E> identity() { return (Function<E, E>) IdentityFunction.INSTANCE; } // enum singleton pattern private enum IdentityFunction implements Function<@Nullable Object, @Nullable Object> { INSTANCE; @Override @CheckForNull public Object apply(@CheckForNull Object o) { return o; } @Override public String toString() { return "Functions.identity()"; } } /** * Returns a function which performs a map lookup. The returned function throws an {@link * IllegalArgumentException} if given a key that does not exist in the map. See also {@link * #forMap(Map, Object)}, which returns a default value in this case. * * <p>Note: if {@code map} is a {@link com.google.common.collect.BiMap BiMap} (or can be one), you * can use {@link com.google.common.collect.Maps#asConverter Maps.asConverter} instead to get a * function that also supports reverse conversion. * * <p><b>Java 8+ users:</b> if you are okay with {@code null} being returned for an unrecognized * key (instead of an exception being thrown), you can use the method reference {@code map::get} * instead. */ public static <K extends @Nullable Object, V extends @Nullable Object> Function<K, V> forMap( Map<K, V> map) { return new FunctionForMapNoDefault<>(map); } /** * Returns a function which performs a map lookup with a default value. The function created by * this method returns {@code defaultValue} for all inputs that do not belong to the map's key * set. See also {@link #forMap(Map)}, which throws an exception in this case. * * <p><b>Java 8+ users:</b> you can just write the lambda expression {@code k -> * map.getOrDefault(k, defaultValue)} instead. * * @param map source map that determines the function behavior * @param defaultValue the value to return for inputs that aren't map keys * @return function that returns {@code map.get(a)} when {@code a} is a key, or {@code * defaultValue} otherwise */ public static <K extends @Nullable Object, V extends @Nullable Object> Function<K, V> forMap( Map<K, ? extends V> map, @ParametricNullness V defaultValue) { return new ForMapWithDefault<>(map, defaultValue); } private static class FunctionForMapNoDefault< K extends @Nullable Object, V extends @Nullable Object> implements Function<K, V>, Serializable { final Map<K, V> map; FunctionForMapNoDefault(Map<K, V> map) { this.map = checkNotNull(map); } @Override @ParametricNullness public V apply(@ParametricNullness K key) { V result = map.get(key); checkArgument(result != null || map.containsKey(key), "Key '%s' not present in map", key); // The unchecked cast is safe because of the containsKey check. return uncheckedCastNullableTToT(result); } @Override public boolean equals(@CheckForNull Object o) { if (o instanceof FunctionForMapNoDefault) { FunctionForMapNoDefault<?, ?> that = (FunctionForMapNoDefault<?, ?>) o; return map.equals(that.map); } return false; } @Override public int hashCode() { return map.hashCode(); } @Override public String toString() { return "Functions.forMap(" + map + ")"; } private static final long serialVersionUID = 0; } private static class ForMapWithDefault<K extends @Nullable Object, V extends @Nullable Object> implements Function<K, V>, Serializable { final Map<K, ? extends V> map; @ParametricNullness final V defaultValue; ForMapWithDefault(Map<K, ? extends V> map, @ParametricNullness V defaultValue) { this.map = checkNotNull(map); this.defaultValue = defaultValue; } @Override @ParametricNullness public V apply(@ParametricNullness K key) { V result = map.get(key); // The unchecked cast is safe because of the containsKey check. return (result != null || map.containsKey(key)) ? uncheckedCastNullableTToT(result) : defaultValue; } @Override public boolean equals(@CheckForNull Object o) { if (o instanceof ForMapWithDefault) { ForMapWithDefault<?, ?> that = (ForMapWithDefault<?, ?>) o; return map.equals(that.map) && Objects.equal(defaultValue, that.defaultValue); } return false; } @Override public int hashCode() { return Objects.hashCode(map, defaultValue); } @Override public String toString() { // TODO(cpovirk): maybe remove "defaultValue=" to make this look like the method call does return "Functions.forMap(" + map + ", defaultValue=" + defaultValue + ")"; } private static final long serialVersionUID = 0; } /** * Returns the composition of two functions. For {@code f: A->B} and {@code g: B->C}, composition * is defined as the function h such that {@code h(a) == g(f(a))} for each {@code a}. * * <p><b>Java 8+ users:</b> use {@code g.compose(f)} or (probably clearer) {@code f.andThen(g)} * instead. * * @param g the second function to apply * @param f the first function to apply * @return the composition of {@code f} and {@code g} * @see <a href="//en.wikipedia.org/wiki/Function_composition">function composition</a> */ public static <A extends @Nullable Object, B extends @Nullable Object, C extends @Nullable Object> Function<A, C> compose(Function<B, C> g, Function<A, ? extends B> f) { return new FunctionComposition<>(g, f); } private static class FunctionComposition< A extends @Nullable Object, B extends @Nullable Object, C extends @Nullable Object> implements Function<A, C>, Serializable { private final Function<B, C> g; private final Function<A, ? extends B> f; public FunctionComposition(Function<B, C> g, Function<A, ? extends B> f) { this.g = checkNotNull(g); this.f = checkNotNull(f); } @Override @ParametricNullness public C apply(@ParametricNullness A a) { return g.apply(f.apply(a)); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof FunctionComposition) { FunctionComposition<?, ?, ?> that = (FunctionComposition<?, ?, ?>) obj; return f.equals(that.f) && g.equals(that.g); } return false; } @Override public int hashCode() { return f.hashCode() ^ g.hashCode(); } @Override public String toString() { // TODO(cpovirk): maybe make this look like the method call does ("Functions.compose(...)") return g + "(" + f + ")"; } private static final long serialVersionUID = 0; } /** * Creates a function that returns the same boolean output as the given predicate for all inputs. * * <p>The returned function is <i>consistent with equals</i> (as documented at {@link * Function#apply}) if and only if {@code predicate} is itself consistent with equals. * * <p><b>Java 8+ users:</b> use the method reference {@code predicate::test} instead. */ public static <T extends @Nullable Object> Function<T, Boolean> forPredicate( Predicate<T> predicate) { return new PredicateFunction<>(predicate); } /** @see Functions#forPredicate */ private static class PredicateFunction<T extends @Nullable Object> implements Function<T, Boolean>, Serializable { private final Predicate<T> predicate; private PredicateFunction(Predicate<T> predicate) { this.predicate = checkNotNull(predicate); } @Override public Boolean apply(@ParametricNullness T t) { return predicate.apply(t); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof PredicateFunction) { PredicateFunction<?> that = (PredicateFunction<?>) obj; return predicate.equals(that.predicate); } return false; } @Override public int hashCode() { return predicate.hashCode(); } @Override public String toString() { return "Functions.forPredicate(" + predicate + ")"; } private static final long serialVersionUID = 0; } /** * Returns a function that ignores its input and always returns {@code value}. * * <p><b>Java 8+ users:</b> use the lambda expression {@code o -> value} instead. * * @param value the constant value for the function to return * @return a function that always returns {@code value} */ public static <E extends @Nullable Object> Function<@Nullable Object, E> constant( @ParametricNullness E value) { return new ConstantFunction<>(value); } private static class ConstantFunction<E extends @Nullable Object> implements Function<@Nullable Object, E>, Serializable { @ParametricNullness private final E value; public ConstantFunction(@ParametricNullness E value) { this.value = value; } @Override @ParametricNullness public E apply(@CheckForNull Object from) { return value; } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof ConstantFunction) { ConstantFunction<?> that = (ConstantFunction<?>) obj; return Objects.equal(value, that.value); } return false; } @Override public int hashCode() { return (value == null) ? 0 : value.hashCode(); } @Override public String toString() { return "Functions.constant(" + value + ")"; } private static final long serialVersionUID = 0; } /** * Returns a function that ignores its input and returns the result of {@code supplier.get()}. * * <p><b>Java 8+ users:</b> use the lambda expression {@code o -> supplier.get()} instead. * * @since 10.0 */ public static <F extends @Nullable Object, T extends @Nullable Object> Function<F, T> forSupplier( Supplier<T> supplier) { return new SupplierFunction<>(supplier); } /** @see Functions#forSupplier */ private static class SupplierFunction<F extends @Nullable Object, T extends @Nullable Object> implements Function<F, T>, Serializable { private final Supplier<T> supplier; private SupplierFunction(Supplier<T> supplier) { this.supplier = checkNotNull(supplier); } @Override @ParametricNullness public T apply(@ParametricNullness F input) { return supplier.get(); } @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof SupplierFunction) { SupplierFunction<?, ?> that = (SupplierFunction<?, ?>) obj; return this.supplier.equals(that.supplier); } return false; } @Override public int hashCode() { return supplier.hashCode(); } @Override public String toString() { return "Functions.forSupplier(" + supplier + ")"; } private static final long serialVersionUID = 0; } }
google/guava
android/guava/src/com/google/common/base/Functions.java
383
/* * Copyright (C) 2017 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.graph; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Objects.requireNonNull; import com.google.common.annotations.Beta; import com.google.common.collect.AbstractIterator; import com.google.common.collect.ImmutableSet; import com.google.errorprone.annotations.DoNotMock; import java.util.ArrayDeque; import java.util.Deque; import java.util.HashSet; import java.util.Iterator; import java.util.Set; import javax.annotation.CheckForNull; /** * An object that can traverse the nodes that are reachable from a specified (set of) start node(s) * using a specified {@link SuccessorsFunction}. * * <p>There are two entry points for creating a {@code Traverser}: {@link * #forTree(SuccessorsFunction)} and {@link #forGraph(SuccessorsFunction)}. You should choose one * based on your answers to the following questions: * * <ol> * <li>Is there only one path to any node that's reachable from any start node? (If so, the graph * to be traversed is a tree or forest even if it is a subgraph of a graph which is neither.) * <li>Are the node objects' implementations of {@code equals()}/{@code hashCode()} <a * href="https://github.com/google/guava/wiki/GraphsExplained#non-recursiveness">recursive</a>? * </ol> * * <p>If your answers are: * * <ul> * <li>(1) "no" and (2) "no", use {@link #forGraph(SuccessorsFunction)}. * <li>(1) "yes" and (2) "yes", use {@link #forTree(SuccessorsFunction)}. * <li>(1) "yes" and (2) "no", you can use either, but {@code forTree()} will be more efficient. * <li>(1) "no" and (2) "yes", <b><i>neither will work</i></b>, but if you transform your node * objects into a non-recursive form, you can use {@code forGraph()}. * </ul> * * @author Jens Nyman * @param <N> Node parameter type * @since 23.1 */ @Beta @DoNotMock( "Call forGraph or forTree, passing a lambda or a Graph with the desired edges (built with" + " GraphBuilder)") @ElementTypesAreNonnullByDefault public abstract class Traverser<N> { private final SuccessorsFunction<N> successorFunction; private Traverser(SuccessorsFunction<N> successorFunction) { this.successorFunction = checkNotNull(successorFunction); } /** * Creates a new traverser for the given general {@code graph}. * * <p>Traversers created using this method are guaranteed to visit each node reachable from the * start node(s) at most once. * * <p>If you know that no node in {@code graph} is reachable by more than one path from the start * node(s), consider using {@link #forTree(SuccessorsFunction)} instead. * * <p><b>Performance notes</b> * * <ul> * <li>Traversals require <i>O(n)</i> time (where <i>n</i> is the number of nodes reachable from * the start node), assuming that the node objects have <i>O(1)</i> {@code equals()} and * {@code hashCode()} implementations. (See the <a * href="https://github.com/google/guava/wiki/GraphsExplained#elements-must-be-useable-as-map-keys"> * notes on element objects</a> for more information.) * <li>While traversing, the traverser will use <i>O(n)</i> space (where <i>n</i> is the number * of nodes that have thus far been visited), plus <i>O(H)</i> space (where <i>H</i> is the * number of nodes that have been seen but not yet visited, that is, the "horizon"). * </ul> * * @param graph {@link SuccessorsFunction} representing a general graph that may have cycles. */ public static <N> Traverser<N> forGraph(SuccessorsFunction<N> graph) { return new Traverser<N>(graph) { @Override Traversal<N> newTraversal() { return Traversal.inGraph(graph); } }; } /** * Creates a new traverser for a directed acyclic graph that has at most one path from the start * node(s) to any node reachable from the start node(s), and has no paths from any start node to * any other start node, such as a tree or forest. * * <p>{@code forTree()} is especially useful (versus {@code forGraph()}) in cases where the data * structure being traversed is, in addition to being a tree/forest, also defined <a * href="https://github.com/google/guava/wiki/GraphsExplained#non-recursiveness">recursively</a>. * This is because the {@code forTree()}-based implementations don't keep track of visited nodes, * and therefore don't need to call `equals()` or `hashCode()` on the node objects; this saves * both time and space versus traversing the same graph using {@code forGraph()}. * * <p>Providing a graph to be traversed for which there is more than one path from the start * node(s) to any node may lead to: * * <ul> * <li>Traversal not terminating (if the graph has cycles) * <li>Nodes being visited multiple times (if multiple paths exist from any start node to any * node reachable from any start node) * </ul> * * <p><b>Performance notes</b> * * <ul> * <li>Traversals require <i>O(n)</i> time (where <i>n</i> is the number of nodes reachable from * the start node). * <li>While traversing, the traverser will use <i>O(H)</i> space (where <i>H</i> is the number * of nodes that have been seen but not yet visited, that is, the "horizon"). * </ul> * * <p><b>Examples</b> (all edges are directed facing downwards) * * <p>The graph below would be valid input with start nodes of {@code a, f, c}. However, if {@code * b} were <i>also</i> a start node, then there would be multiple paths to reach {@code e} and * {@code h}. * * <pre>{@code * a b c * / \ / \ | * / \ / \ | * d e f g * | * | * h * }</pre> * * <p>. * * <p>The graph below would be a valid input with start nodes of {@code a, f}. However, if {@code * b} were a start node, there would be multiple paths to {@code f}. * * <pre>{@code * a b * / \ / \ * / \ / \ * c d e * \ / * \ / * f * }</pre> * * <p><b>Note on binary trees</b> * * <p>This method can be used to traverse over a binary tree. Given methods {@code * leftChild(node)} and {@code rightChild(node)}, this method can be called as * * <pre>{@code * Traverser.forTree(node -> ImmutableList.of(leftChild(node), rightChild(node))); * }</pre> * * @param tree {@link SuccessorsFunction} representing a directed acyclic graph that has at most * one path between any two nodes */ public static <N> Traverser<N> forTree(SuccessorsFunction<N> tree) { if (tree instanceof BaseGraph) { checkArgument(((BaseGraph<?>) tree).isDirected(), "Undirected graphs can never be trees."); } if (tree instanceof Network) { checkArgument(((Network<?, ?>) tree).isDirected(), "Undirected networks can never be trees."); } return new Traverser<N>(tree) { @Override Traversal<N> newTraversal() { return Traversal.inTree(tree); } }; } /** * Returns an unmodifiable {@code Iterable} over the nodes reachable from {@code startNode}, in * the order of a breadth-first traversal. That is, all the nodes of depth 0 are returned, then * depth 1, then 2, and so on. * * <p><b>Example:</b> The following graph with {@code startNode} {@code a} would return nodes in * the order {@code abcdef} (assuming successors are returned in alphabetical order). * * <pre>{@code * b ---- a ---- d * | | * | | * e ---- c ---- f * }</pre> * * <p>The behavior of this method is undefined if the nodes, or the topology of the graph, change * while iteration is in progress. * * <p>The returned {@code Iterable} can be iterated over multiple times. Every iterator will * compute its next element on the fly. It is thus possible to limit the traversal to a certain * number of nodes as follows: * * <pre>{@code * Iterables.limit(Traverser.forGraph(graph).breadthFirst(node), maxNumberOfNodes); * }</pre> * * <p>See <a href="https://en.wikipedia.org/wiki/Breadth-first_search">Wikipedia</a> for more * info. * * @throws IllegalArgumentException if {@code startNode} is not an element of the graph */ public final Iterable<N> breadthFirst(N startNode) { return breadthFirst(ImmutableSet.of(startNode)); } /** * Returns an unmodifiable {@code Iterable} over the nodes reachable from any of the {@code * startNodes}, in the order of a breadth-first traversal. This is equivalent to a breadth-first * traversal of a graph with an additional root node whose successors are the listed {@code * startNodes}. * * @throws IllegalArgumentException if any of {@code startNodes} is not an element of the graph * @see #breadthFirst(Object) * @since 24.1 */ public final Iterable<N> breadthFirst(Iterable<? extends N> startNodes) { ImmutableSet<N> validated = validate(startNodes); return new Iterable<N>() { @Override public Iterator<N> iterator() { return newTraversal().breadthFirst(validated.iterator()); } }; } /** * Returns an unmodifiable {@code Iterable} over the nodes reachable from {@code startNode}, in * the order of a depth-first pre-order traversal. "Pre-order" implies that nodes appear in the * {@code Iterable} in the order in which they are first visited. * * <p><b>Example:</b> The following graph with {@code startNode} {@code a} would return nodes in * the order {@code abecfd} (assuming successors are returned in alphabetical order). * * <pre>{@code * b ---- a ---- d * | | * | | * e ---- c ---- f * }</pre> * * <p>The behavior of this method is undefined if the nodes, or the topology of the graph, change * while iteration is in progress. * * <p>The returned {@code Iterable} can be iterated over multiple times. Every iterator will * compute its next element on the fly. It is thus possible to limit the traversal to a certain * number of nodes as follows: * * <pre>{@code * Iterables.limit( * Traverser.forGraph(graph).depthFirstPreOrder(node), maxNumberOfNodes); * }</pre> * * <p>See <a href="https://en.wikipedia.org/wiki/Depth-first_search">Wikipedia</a> for more info. * * @throws IllegalArgumentException if {@code startNode} is not an element of the graph */ public final Iterable<N> depthFirstPreOrder(N startNode) { return depthFirstPreOrder(ImmutableSet.of(startNode)); } /** * Returns an unmodifiable {@code Iterable} over the nodes reachable from any of the {@code * startNodes}, in the order of a depth-first pre-order traversal. This is equivalent to a * depth-first pre-order traversal of a graph with an additional root node whose successors are * the listed {@code startNodes}. * * @throws IllegalArgumentException if any of {@code startNodes} is not an element of the graph * @see #depthFirstPreOrder(Object) * @since 24.1 */ public final Iterable<N> depthFirstPreOrder(Iterable<? extends N> startNodes) { ImmutableSet<N> validated = validate(startNodes); return new Iterable<N>() { @Override public Iterator<N> iterator() { return newTraversal().preOrder(validated.iterator()); } }; } /** * Returns an unmodifiable {@code Iterable} over the nodes reachable from {@code startNode}, in * the order of a depth-first post-order traversal. "Post-order" implies that nodes appear in the * {@code Iterable} in the order in which they are visited for the last time. * * <p><b>Example:</b> The following graph with {@code startNode} {@code a} would return nodes in * the order {@code fcebda} (assuming successors are returned in alphabetical order). * * <pre>{@code * b ---- a ---- d * | | * | | * e ---- c ---- f * }</pre> * * <p>The behavior of this method is undefined if the nodes, or the topology of the graph, change * while iteration is in progress. * * <p>The returned {@code Iterable} can be iterated over multiple times. Every iterator will * compute its next element on the fly. It is thus possible to limit the traversal to a certain * number of nodes as follows: * * <pre>{@code * Iterables.limit( * Traverser.forGraph(graph).depthFirstPostOrder(node), maxNumberOfNodes); * }</pre> * * <p>See <a href="https://en.wikipedia.org/wiki/Depth-first_search">Wikipedia</a> for more info. * * @throws IllegalArgumentException if {@code startNode} is not an element of the graph */ public final Iterable<N> depthFirstPostOrder(N startNode) { return depthFirstPostOrder(ImmutableSet.of(startNode)); } /** * Returns an unmodifiable {@code Iterable} over the nodes reachable from any of the {@code * startNodes}, in the order of a depth-first post-order traversal. This is equivalent to a * depth-first post-order traversal of a graph with an additional root node whose successors are * the listed {@code startNodes}. * * @throws IllegalArgumentException if any of {@code startNodes} is not an element of the graph * @see #depthFirstPostOrder(Object) * @since 24.1 */ public final Iterable<N> depthFirstPostOrder(Iterable<? extends N> startNodes) { ImmutableSet<N> validated = validate(startNodes); return new Iterable<N>() { @Override public Iterator<N> iterator() { return newTraversal().postOrder(validated.iterator()); } }; } abstract Traversal<N> newTraversal(); @SuppressWarnings("CheckReturnValue") private ImmutableSet<N> validate(Iterable<? extends N> startNodes) { ImmutableSet<N> copy = ImmutableSet.copyOf(startNodes); for (N node : copy) { successorFunction.successors(node); // Will throw if node doesn't exist } return copy; } /** * Abstracts away the difference between traversing a graph vs. a tree. For a tree, we just take * the next element from the next non-empty iterator; for graph, we need to loop through the next * non-empty iterator to find first unvisited node. */ private abstract static class Traversal<N> { final SuccessorsFunction<N> successorFunction; Traversal(SuccessorsFunction<N> successorFunction) { this.successorFunction = successorFunction; } static <N> Traversal<N> inGraph(SuccessorsFunction<N> graph) { Set<N> visited = new HashSet<>(); return new Traversal<N>(graph) { @Override @CheckForNull N visitNext(Deque<Iterator<? extends N>> horizon) { Iterator<? extends N> top = horizon.getFirst(); while (top.hasNext()) { N element = top.next(); // requireNonNull is safe because horizon contains only graph nodes. /* * TODO(cpovirk): Replace these two statements with one (`N element = * requireNonNull(top.next())`) once our checker supports it. * * (The problem is likely * https://github.com/jspecify/jspecify-reference-checker/blob/61aafa4ae52594830cfc2d61c8b113009dbdb045/src/main/java/com/google/jspecify/nullness/NullSpecAnnotatedTypeFactory.java#L896) */ requireNonNull(element); if (visited.add(element)) { return element; } } horizon.removeFirst(); return null; } }; } static <N> Traversal<N> inTree(SuccessorsFunction<N> tree) { return new Traversal<N>(tree) { @CheckForNull @Override N visitNext(Deque<Iterator<? extends N>> horizon) { Iterator<? extends N> top = horizon.getFirst(); if (top.hasNext()) { return checkNotNull(top.next()); } horizon.removeFirst(); return null; } }; } final Iterator<N> breadthFirst(Iterator<? extends N> startNodes) { return topDown(startNodes, InsertionOrder.BACK); } final Iterator<N> preOrder(Iterator<? extends N> startNodes) { return topDown(startNodes, InsertionOrder.FRONT); } /** * In top-down traversal, an ancestor node is always traversed before any of its descendant * nodes. The traversal order among descendant nodes (particularly aunts and nieces) are * determined by the {@code InsertionOrder} parameter: nieces are placed at the FRONT before * aunts for pre-order; while in BFS they are placed at the BACK after aunts. */ private Iterator<N> topDown(Iterator<? extends N> startNodes, InsertionOrder order) { Deque<Iterator<? extends N>> horizon = new ArrayDeque<>(); horizon.add(startNodes); return new AbstractIterator<N>() { @Override @CheckForNull protected N computeNext() { do { N next = visitNext(horizon); if (next != null) { Iterator<? extends N> successors = successorFunction.successors(next).iterator(); if (successors.hasNext()) { // BFS: horizon.addLast(successors) // Pre-order: horizon.addFirst(successors) order.insertInto(horizon, successors); } return next; } } while (!horizon.isEmpty()); return endOfData(); } }; } final Iterator<N> postOrder(Iterator<? extends N> startNodes) { Deque<N> ancestorStack = new ArrayDeque<>(); Deque<Iterator<? extends N>> horizon = new ArrayDeque<>(); horizon.add(startNodes); return new AbstractIterator<N>() { @Override @CheckForNull protected N computeNext() { for (N next = visitNext(horizon); next != null; next = visitNext(horizon)) { Iterator<? extends N> successors = successorFunction.successors(next).iterator(); if (!successors.hasNext()) { return next; } horizon.addFirst(successors); ancestorStack.push(next); } // TODO(b/192579700): Use a ternary once it no longer confuses our nullness checker. if (!ancestorStack.isEmpty()) { return ancestorStack.pop(); } return endOfData(); } }; } /** * Visits the next node from the top iterator of {@code horizon} and returns the visited node. * Null is returned to indicate reaching the end of the top iterator. * * <p>For example, if horizon is {@code [[a, b], [c, d], [e]]}, {@code visitNext()} will return * {@code [a, b, null, c, d, null, e, null]} sequentially, encoding the topological structure. * (Note, however, that the callers of {@code visitNext()} often insert additional iterators * into {@code horizon} between calls to {@code visitNext()}. This causes them to receive * additional values interleaved with those shown above.) */ @CheckForNull abstract N visitNext(Deque<Iterator<? extends N>> horizon); } /** Poor man's method reference for {@code Deque::addFirst} and {@code Deque::addLast}. */ private enum InsertionOrder { FRONT { @Override <T> void insertInto(Deque<T> deque, T value) { deque.addFirst(value); } }, BACK { @Override <T> void insertInto(Deque<T> deque, T value) { deque.addLast(value); } }; abstract <T> void insertInto(Deque<T> deque, T value); } }
google/guava
android/guava/src/com/google/common/graph/Traverser.java
384
/* * 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.GwtCompatible; import com.google.common.base.CharMatcher; import com.google.common.base.Objects; import com.google.common.base.Strings; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.Immutable; import java.io.Serializable; import javax.annotation.CheckForNull; /** * An immutable representation of a host and port. * * <p>Example usage: * * <pre> * HostAndPort hp = HostAndPort.fromString("[2001:db8::1]") * .withDefaultPort(80) * .requireBracketsForIPv6(); * hp.getHost(); // 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 #getHost()} omits brackets * <li>[2001:db8::1]:80 - {@link #getHost()} 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 */ @Immutable @GwtCompatible @ElementTypesAreNonnullByDefault 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. * * <p>A successful parse does not imply any degree of sanity in this field. For additional * validation, see the {@link HostSpecifier} class. * * @since 20.0 (since 10.0 as {@code getHostText}) */ public String getHost() { 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), "Port out of range: %s", port); HostAndPort parsedHost = fromString(host); checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); return new HostAndPort(parsedHost.host, port, parsedHost.hasBracketlessColons); } /** * Build a HostAndPort instance from a host only. * * <p>Note: Non-bracketed IPv6 literals are allowed. Use {@link #requireBracketsForIPv6()} to * prohibit these. * * @param host the host-only string to parse. Must not contain a port number. * @return if parsing was successful, a populated HostAndPort object. * @throws IllegalArgumentException if {@code host} contains a port number. * @since 17.0 */ public static HostAndPort fromHost(String host) { HostAndPort parsedHost = fromString(host); checkArgument(!parsedHost.hasPort(), "Host has a port: %s", host); return parsedHost; } /** * Split a freeform string into a host and port, without strict validation. * * <p>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. */ @CanIgnoreReturnValue // TODO(b/219820829): consider removing public static HostAndPort fromString(String hostPortString) { checkNotNull(hostPortString); String host; String portString = null; boolean hasBracketlessColons = false; if (hostPortString.startsWith("[")) { String[] hostAndPort = getHostAndPortFromBracketedHost(hostPortString); host = hostAndPort[0]; portString = hostAndPort[1]; } 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 (!Strings.isNullOrEmpty(portString)) { // Try to parse the whole port string as a number. // JDK7 accepts leading plus signs. We don't want to. checkArgument( !portString.startsWith("+") && CharMatcher.ascii().matchesAllOf(portString), "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); } /** * Parses a bracketed host-port string, throwing IllegalArgumentException if parsing fails. * * @param hostPortString the full bracketed host-port specification. Port might not be specified. * @return an array with 2 strings: host and port, in that order. * @throws IllegalArgumentException if parsing the bracketed host-port string fails. */ private static String[] getHostAndPortFromBracketedHost(String hostPortString) { checkArgument( hostPortString.charAt(0) == '[', "Bracketed host-port string must start with a bracket: %s", hostPortString); int colonIndex = hostPortString.indexOf(':'); int closeBracketIndex = hostPortString.lastIndexOf(']'); checkArgument( colonIndex > -1 && closeBracketIndex > colonIndex, "Invalid bracketed host/port: %s", hostPortString); String host = hostPortString.substring(1, closeBracketIndex); if (closeBracketIndex + 1 == hostPortString.length()) { return new String[] {host, ""}; } else { checkArgument( hostPortString.charAt(closeBracketIndex + 1) == ':', "Only a colon may follow a close bracket: %s", hostPortString); for (int i = closeBracketIndex + 2; i < hostPortString.length(); ++i) { checkArgument( Character.isDigit(hostPortString.charAt(i)), "Port must be numeric: %s", hostPortString); } return new String[] {host, hostPortString.substring(closeBracketIndex + 2)}; } } /** * Provide a default port if the parsed string contained only a host. * * <p>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()) { 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. */ @CanIgnoreReturnValue public HostAndPort requireBracketsForIPv6() { checkArgument(!hasBracketlessColons, "Possible bracketless IPv6 literal: %s", host); return this; } @Override public boolean equals(@CheckForNull 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; } return false; } @Override public int hashCode() { return Objects.hashCode(host, port); } /** Rebuild the host:port string, including brackets if necessary. */ @Override public String toString() { // "[]:12345" requires 8 extra bytes. StringBuilder builder = new StringBuilder(host.length() + 8); 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; }
google/guava
android/guava/src/com/google/common/net/HostAndPort.java
385
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import static java.util.Arrays.asList; import static java.util.Collections.unmodifiableList; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.util.AbstractList; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.annotation.CheckForNull; /** * Static utility methods pertaining to instances of {@link Throwable}. * * <p>See the Guava User Guide entry on <a * href="https://github.com/google/guava/wiki/ThrowablesExplained">Throwables</a>. * * @author Kevin Bourrillion * @author Ben Yu * @since 1.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Throwables { private Throwables() {} /** * Throws {@code throwable} if it is an instance of {@code declaredType}. Example usage: * * <pre> * for (Foo foo : foos) { * try { * foo.bar(); * } catch (BarException | RuntimeException | Error t) { * failure = t; * } * } * if (failure != null) { * throwIfInstanceOf(failure, BarException.class); * throwIfUnchecked(failure); * throw new AssertionError(failure); * } * </pre> * * @since 20.0 */ @GwtIncompatible // Class.cast, Class.isInstance public static <X extends Throwable> void throwIfInstanceOf( Throwable throwable, Class<X> declaredType) throws X { checkNotNull(throwable); if (declaredType.isInstance(throwable)) { throw declaredType.cast(throwable); } } /** * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@code * declaredType}. Example usage: * * <pre> * try { * someMethodThatCouldThrowAnything(); * } catch (IKnowWhatToDoWithThisException e) { * handle(e); * } catch (Throwable t) { * Throwables.propagateIfInstanceOf(t, IOException.class); * Throwables.propagateIfInstanceOf(t, SQLException.class); * throw Throwables.propagate(t); * } * </pre> * * @deprecated Use {@link #throwIfInstanceOf}, which has the same behavior but rejects {@code * null}. */ @Deprecated @J2ktIncompatible @GwtIncompatible // throwIfInstanceOf public static <X extends Throwable> void propagateIfInstanceOf( @CheckForNull Throwable throwable, Class<X> declaredType) throws X { if (throwable != null) { throwIfInstanceOf(throwable, declaredType); } } /** * Throws {@code throwable} if it is a {@link RuntimeException} or {@link Error}. Example usage: * * <pre> * for (Foo foo : foos) { * try { * foo.bar(); * } catch (RuntimeException | Error t) { * failure = t; * } * } * if (failure != null) { * throwIfUnchecked(failure); * throw new AssertionError(failure); * } * </pre> * * @since 20.0 */ public static void throwIfUnchecked(Throwable throwable) { checkNotNull(throwable); if (throwable instanceof RuntimeException) { throw (RuntimeException) throwable; } if (throwable instanceof Error) { throw (Error) throwable; } } /** * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link * RuntimeException} or {@link Error}. * * @deprecated Use {@link #throwIfUnchecked}, which has the same behavior but rejects {@code * null}. */ @Deprecated @J2ktIncompatible @GwtIncompatible public static void propagateIfPossible(@CheckForNull Throwable throwable) { if (throwable != null) { throwIfUnchecked(throwable); } } /** * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link * RuntimeException}, {@link Error}, or {@code declaredType}. * * <p><b>Discouraged</b> in favor of calling {@link #throwIfInstanceOf} and {@link * #throwIfUnchecked}. * * @param throwable the Throwable to possibly propagate * @param declaredType the single checked exception type declared by the calling method * @deprecated Use a combination of {@link #throwIfInstanceOf} and {@link #throwIfUnchecked}, * which togther provide the same behavior except that they reject {@code null}. */ @Deprecated @J2ktIncompatible @GwtIncompatible // propagateIfInstanceOf public static <X extends Throwable> void propagateIfPossible( @CheckForNull Throwable throwable, Class<X> declaredType) throws X { propagateIfInstanceOf(throwable, declaredType); propagateIfPossible(throwable); } /** * Propagates {@code throwable} exactly as-is, if and only if it is an instance of {@link * RuntimeException}, {@link Error}, {@code declaredType1}, or {@code declaredType2}. * * @param throwable the Throwable to possibly propagate * @param declaredType1 any checked exception type declared by the calling method * @param declaredType2 any other checked exception type declared by the calling method * @deprecated Use a combination of two calls to {@link #throwIfInstanceOf} and one call to {@link * #throwIfUnchecked}, which togther provide the same behavior except that they reject {@code * null}. */ @Deprecated @J2ktIncompatible @GwtIncompatible // propagateIfInstanceOf public static <X1 extends Throwable, X2 extends Throwable> void propagateIfPossible( @CheckForNull Throwable throwable, Class<X1> declaredType1, Class<X2> declaredType2) throws X1, X2 { checkNotNull(declaredType2); propagateIfInstanceOf(throwable, declaredType1); propagateIfPossible(throwable, declaredType2); } /** * Propagates {@code throwable} as-is if it is an instance of {@link RuntimeException} or {@link * Error}, or else as a last resort, wraps it in a {@code RuntimeException} and then propagates. * * <p>This method always throws an exception. The {@code RuntimeException} return type allows * client code to signal to the compiler that statements after the call are unreachable. Example * usage: * * <pre> * T doSomething() { * try { * return someMethodThatCouldThrowAnything(); * } catch (IKnowWhatToDoWithThisException e) { * return handle(e); * } catch (Throwable t) { * throw Throwables.propagate(t); * } * } * </pre> * * @param throwable the Throwable to propagate * @return nothing will ever be returned; this return type is only for your convenience, as * illustrated in the example above * @deprecated To preserve behavior, use {@code throw e} or {@code throw new RuntimeException(e)} * directly, or use a combination of {@link #throwIfUnchecked} and {@code throw new * RuntimeException(e)}. But consider whether users would be better off if your API threw a * different type of exception. For background on the deprecation, read <a * href="https://goo.gl/Ivn2kc">Why we deprecated {@code Throwables.propagate}</a>. */ @CanIgnoreReturnValue @J2ktIncompatible @GwtIncompatible @Deprecated public static RuntimeException propagate(Throwable throwable) { throwIfUnchecked(throwable); throw new RuntimeException(throwable); } /** * Returns the innermost cause of {@code throwable}. The first throwable in a chain provides * context from when the error or exception was initially detected. Example usage: * * <pre> * assertEquals("Unable to assign a customer id", Throwables.getRootCause(e).getMessage()); * </pre> * * @throws IllegalArgumentException if there is a loop in the causal chain */ public static Throwable getRootCause(Throwable throwable) { // Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches // the slower pointer, then there's a loop. Throwable slowPointer = throwable; boolean advanceSlowPointer = false; Throwable cause; while ((cause = throwable.getCause()) != null) { throwable = cause; if (throwable == slowPointer) { throw new IllegalArgumentException("Loop in causal chain detected.", throwable); } if (advanceSlowPointer) { slowPointer = slowPointer.getCause(); } advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration } return throwable; } /** * Gets a {@code Throwable} cause chain as a list. The first entry in the list will be {@code * throwable} followed by its cause hierarchy. Note that this is a snapshot of the cause chain and * will not reflect any subsequent changes to the cause chain. * * <p>Here's an example of how it can be used to find specific types of exceptions in the cause * chain: * * <pre> * Iterables.filter(Throwables.getCausalChain(e), IOException.class)); * </pre> * * @param throwable the non-null {@code Throwable} to extract causes from * @return an unmodifiable list containing the cause chain starting with {@code throwable} * @throws IllegalArgumentException if there is a loop in the causal chain */ public static List<Throwable> getCausalChain(Throwable throwable) { checkNotNull(throwable); List<Throwable> causes = new ArrayList<>(4); causes.add(throwable); // Keep a second pointer that slowly walks the causal chain. If the fast pointer ever catches // the slower pointer, then there's a loop. Throwable slowPointer = throwable; boolean advanceSlowPointer = false; Throwable cause; while ((cause = throwable.getCause()) != null) { throwable = cause; causes.add(throwable); if (throwable == slowPointer) { throw new IllegalArgumentException("Loop in causal chain detected.", throwable); } if (advanceSlowPointer) { slowPointer = slowPointer.getCause(); } advanceSlowPointer = !advanceSlowPointer; // only advance every other iteration } return Collections.unmodifiableList(causes); } /** * Returns {@code throwable}'s cause, cast to {@code expectedCauseType}. * * <p>Prefer this method instead of manually casting an exception's cause. For example, {@code * (IOException) e.getCause()} throws a {@link ClassCastException} that discards the original * exception {@code e} if the cause is not an {@link IOException}, but {@code * Throwables.getCauseAs(e, IOException.class)} keeps {@code e} as the {@link * ClassCastException}'s cause. * * @throws ClassCastException if the cause cannot be cast to the expected type. The {@code * ClassCastException}'s cause is {@code throwable}. * @since 22.0 */ @GwtIncompatible // Class.cast(Object) @CheckForNull public static <X extends Throwable> X getCauseAs( Throwable throwable, Class<X> expectedCauseType) { try { return expectedCauseType.cast(throwable.getCause()); } catch (ClassCastException e) { e.initCause(throwable); throw e; } } /** * Returns a string containing the result of {@link Throwable#toString() toString()}, followed by * the full, recursive stack trace of {@code throwable}. Note that you probably should not be * parsing the resulting string; if you need programmatic access to the stack frames, you can call * {@link Throwable#getStackTrace()}. */ @GwtIncompatible // java.io.PrintWriter, java.io.StringWriter public static String getStackTraceAsString(Throwable throwable) { StringWriter stringWriter = new StringWriter(); throwable.printStackTrace(new PrintWriter(stringWriter)); return stringWriter.toString(); } /** * Returns the stack trace of {@code throwable}, possibly providing slower iteration over the full * trace but faster iteration over parts of the trace. Here, "slower" and "faster" are defined in * comparison to the normal way to access the stack trace, {@link Throwable#getStackTrace() * throwable.getStackTrace()}. Note, however, that this method's special implementation is not * available for all platforms and configurations. If that implementation is unavailable, this * method falls back to {@code getStackTrace}. Callers that require the special implementation can * check its availability with {@link #lazyStackTraceIsLazy()}. * * <p>The expected (but not guaranteed) performance of the special implementation differs from * {@code getStackTrace} in one main way: The {@code lazyStackTrace} call itself returns quickly * by delaying the per-stack-frame work until each element is accessed. Roughly speaking: * * <ul> * <li>{@code getStackTrace} takes {@code stackSize} time to return but then negligible time to * retrieve each element of the returned list. * <li>{@code lazyStackTrace} takes negligible time to return but then {@code 1/stackSize} time * to retrieve each element of the returned list (probably slightly more than {@code * 1/stackSize}). * </ul> * * <p>Note: The special implementation does not respect calls to {@link Throwable#setStackTrace * throwable.setStackTrace}. Instead, it always reflects the original stack trace from the * exception's creation. * * @since 19.0 * @deprecated This method is equivalent to {@link Throwable#getStackTrace()} on JDK versions past * JDK 8 and on all Android versions. Use {@link Throwable#getStackTrace()} directly, or where * possible use the {@code java.lang.StackWalker.walk} method introduced in JDK 9. */ @Deprecated @J2ktIncompatible @GwtIncompatible // lazyStackTraceIsLazy, jlaStackTrace public static List<StackTraceElement> lazyStackTrace(Throwable throwable) { return lazyStackTraceIsLazy() ? jlaStackTrace(throwable) : unmodifiableList(asList(throwable.getStackTrace())); } /** * Returns whether {@link #lazyStackTrace} will use the special implementation described in its * documentation. * * @since 19.0 * @deprecated This method always returns false on JDK versions past JDK 8 and on all Android * versions. */ @Deprecated @J2ktIncompatible @GwtIncompatible // getStackTraceElementMethod public static boolean lazyStackTraceIsLazy() { return getStackTraceElementMethod != null && getStackTraceDepthMethod != null; } @J2ktIncompatible @GwtIncompatible // invokeAccessibleNonThrowingMethod private static List<StackTraceElement> jlaStackTrace(Throwable t) { checkNotNull(t); /* * TODO(cpovirk): Consider optimizing iterator() to catch IOOBE instead of doing bounds checks. * * TODO(cpovirk): Consider the UnsignedBytes pattern if it performs faster and doesn't cause * AOSP grief. */ return new AbstractList<StackTraceElement>() { /* * The following requireNonNull calls are safe because we use jlaStackTrace() only if * lazyStackTraceIsLazy() returns true. */ @Override public StackTraceElement get(int n) { return (StackTraceElement) invokeAccessibleNonThrowingMethod( requireNonNull(getStackTraceElementMethod), requireNonNull(jla), t, n); } @Override public int size() { return (Integer) invokeAccessibleNonThrowingMethod( requireNonNull(getStackTraceDepthMethod), requireNonNull(jla), t); } }; } @J2ktIncompatible @GwtIncompatible // java.lang.reflect private static Object invokeAccessibleNonThrowingMethod( Method method, Object receiver, Object... params) { try { return method.invoke(receiver, params); } catch (IllegalAccessException e) { throw new RuntimeException(e); } catch (InvocationTargetException e) { throw propagate(e.getCause()); } } /** JavaLangAccess class name to load using reflection */ @J2ktIncompatible @GwtIncompatible // not used by GWT emulation private static final String JAVA_LANG_ACCESS_CLASSNAME = "sun.misc.JavaLangAccess"; /** SharedSecrets class name to load using reflection */ @J2ktIncompatible @GwtIncompatible // not used by GWT emulation @VisibleForTesting static final String SHARED_SECRETS_CLASSNAME = "sun.misc.SharedSecrets"; /** Access to some fancy internal JVM internals. */ @J2ktIncompatible @GwtIncompatible // java.lang.reflect @CheckForNull private static final Object jla = getJLA(); /** * The "getStackTraceElementMethod" method, only available on some JDKs so we use reflection to * find it when available. When this is null, use the slow way. */ @J2ktIncompatible @GwtIncompatible // java.lang.reflect @CheckForNull private static final Method getStackTraceElementMethod = (jla == null) ? null : getGetMethod(); /** * The "getStackTraceDepth" method, only available on some JDKs so we use reflection to find it * when available. When this is null, use the slow way. */ @J2ktIncompatible @GwtIncompatible // java.lang.reflect @CheckForNull private static final Method getStackTraceDepthMethod = (jla == null) ? null : getSizeMethod(jla); /** * Returns the JavaLangAccess class that is present in all Sun JDKs. It is not allowed in * AppEngine, and not present in non-Sun JDKs. */ @SuppressWarnings("removal") // b/318391980 @J2ktIncompatible @GwtIncompatible // java.lang.reflect @CheckForNull private static Object getJLA() { try { /* * We load sun.misc.* classes using reflection since Android doesn't support these classes and * would result in compilation failure if we directly refer to these classes. */ Class<?> sharedSecrets = Class.forName(SHARED_SECRETS_CLASSNAME, false, null); Method langAccess = sharedSecrets.getMethod("getJavaLangAccess"); return langAccess.invoke(null); } catch (ThreadDeath death) { throw death; } catch (Throwable t) { /* * This is not one of AppEngine's allowed classes, so even in Sun JDKs, this can fail with * a NoClassDefFoundError. Other apps might deny access to sun.misc packages. */ return null; } } /** * Returns the Method that can be used to resolve an individual StackTraceElement, or null if that * method cannot be found (it is only to be found in fairly recent JDKs). */ @J2ktIncompatible @GwtIncompatible // java.lang.reflect @CheckForNull private static Method getGetMethod() { return getJlaMethod("getStackTraceElement", Throwable.class, int.class); } /** * Returns the Method that can be used to return the size of a stack, or null if that method * cannot be found (it is only to be found in fairly recent JDKs). Tries to test method {@link * sun.misc.JavaLangAccess#getStackTraceDepth(Throwable) getStackTraceDepth} prior to return it * (might fail some JDKs). * * <p>See <a href="https://github.com/google/guava/issues/2887">Throwables#lazyStackTrace throws * UnsupportedOperationException</a>. */ @J2ktIncompatible @GwtIncompatible // java.lang.reflect @CheckForNull private static Method getSizeMethod(Object jla) { try { Method getStackTraceDepth = getJlaMethod("getStackTraceDepth", Throwable.class); if (getStackTraceDepth == null) { return null; } getStackTraceDepth.invoke(jla, new Throwable()); return getStackTraceDepth; } catch (UnsupportedOperationException | IllegalAccessException | InvocationTargetException e) { return null; } } @SuppressWarnings("removal") // b/318391980 @J2ktIncompatible @GwtIncompatible // java.lang.reflect @CheckForNull private static Method getJlaMethod(String name, Class<?>... parameterTypes) throws ThreadDeath { try { return Class.forName(JAVA_LANG_ACCESS_CLASSNAME, false, null).getMethod(name, parameterTypes); } catch (ThreadDeath death) { throw death; } catch (Throwable t) { /* * Either the JavaLangAccess class itself is not found, or the method is not supported on the * JVM. */ return null; } } }
google/guava
guava/src/com/google/common/base/Throwables.java
386
/* * Licensed to Elasticsearch B.V. under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch B.V. licenses this file to you 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 project is based on a modification of https://github.com/uber/h3 which is licensed under the Apache 2.0 License. * * Copyright 2016-2021 Uber Technologies, Inc. */ package org.elasticsearch.h3; /** * Computes the neighbour H3 index from a given index. */ final class HexRing { private static final int INVALID_BASE_CELL = 127; /** Neighboring base cell ID in each IJK direction. * * For each base cell, for each direction, the neighboring base * cell ID is given. 127 indicates there is no neighbor in that direction. */ private static final int[][] baseCellNeighbors = new int[][] { { 0, 1, 5, 2, 4, 3, 8 }, // base cell 0 { 1, 7, 6, 9, 0, 3, 2 }, // base cell 1 { 2, 6, 10, 11, 0, 1, 5 }, // base cell 2 { 3, 13, 1, 7, 4, 12, 0 }, // base cell 3 { 4, INVALID_BASE_CELL, 15, 8, 3, 0, 12 }, // base cell 4 (pentagon) { 5, 2, 18, 10, 8, 0, 16 }, // base cell 5 { 6, 14, 11, 17, 1, 9, 2 }, // base cell 6 { 7, 21, 9, 19, 3, 13, 1 }, // base cell 7 { 8, 5, 22, 16, 4, 0, 15 }, // base cell 8 { 9, 19, 14, 20, 1, 7, 6 }, // base cell 9 { 10, 11, 24, 23, 5, 2, 18 }, // base cell 10 { 11, 17, 23, 25, 2, 6, 10 }, // base cell 11 { 12, 28, 13, 26, 4, 15, 3 }, // base cell 12 { 13, 26, 21, 29, 3, 12, 7 }, // base cell 13 { 14, INVALID_BASE_CELL, 17, 27, 9, 20, 6 }, // base cell 14 (pentagon) { 15, 22, 28, 31, 4, 8, 12 }, // base cell 15 { 16, 18, 33, 30, 8, 5, 22 }, // base cell 16 { 17, 11, 14, 6, 35, 25, 27 }, // base cell 17 { 18, 24, 30, 32, 5, 10, 16 }, // base cell 18 { 19, 34, 20, 36, 7, 21, 9 }, // base cell 19 { 20, 14, 19, 9, 40, 27, 36 }, // base cell 20 { 21, 38, 19, 34, 13, 29, 7 }, // base cell 21 { 22, 16, 41, 33, 15, 8, 31 }, // base cell 22 { 23, 24, 11, 10, 39, 37, 25 }, // base cell 23 { 24, INVALID_BASE_CELL, 32, 37, 10, 23, 18 }, // base cell 24 (pentagon) { 25, 23, 17, 11, 45, 39, 35 }, // base cell 25 { 26, 42, 29, 43, 12, 28, 13 }, // base cell 26 { 27, 40, 35, 46, 14, 20, 17 }, // base cell 27 { 28, 31, 42, 44, 12, 15, 26 }, // base cell 28 { 29, 43, 38, 47, 13, 26, 21 }, // base cell 29 { 30, 32, 48, 50, 16, 18, 33 }, // base cell 30 { 31, 41, 44, 53, 15, 22, 28 }, // base cell 31 { 32, 30, 24, 18, 52, 50, 37 }, // base cell 32 { 33, 30, 49, 48, 22, 16, 41 }, // base cell 33 { 34, 19, 38, 21, 54, 36, 51 }, // base cell 34 { 35, 46, 45, 56, 17, 27, 25 }, // base cell 35 { 36, 20, 34, 19, 55, 40, 54 }, // base cell 36 { 37, 39, 52, 57, 24, 23, 32 }, // base cell 37 { 38, INVALID_BASE_CELL, 34, 51, 29, 47, 21 }, // base cell 38 (pentagon) { 39, 37, 25, 23, 59, 57, 45 }, // base cell 39 { 40, 27, 36, 20, 60, 46, 55 }, // base cell 40 { 41, 49, 53, 61, 22, 33, 31 }, // base cell 41 { 42, 58, 43, 62, 28, 44, 26 }, // base cell 42 { 43, 62, 47, 64, 26, 42, 29 }, // base cell 43 { 44, 53, 58, 65, 28, 31, 42 }, // base cell 44 { 45, 39, 35, 25, 63, 59, 56 }, // base cell 45 { 46, 60, 56, 68, 27, 40, 35 }, // base cell 46 { 47, 38, 43, 29, 69, 51, 64 }, // base cell 47 { 48, 49, 30, 33, 67, 66, 50 }, // base cell 48 { 49, INVALID_BASE_CELL, 61, 66, 33, 48, 41 }, // base cell 49 (pentagon) { 50, 48, 32, 30, 70, 67, 52 }, // base cell 50 { 51, 69, 54, 71, 38, 47, 34 }, // base cell 51 { 52, 57, 70, 74, 32, 37, 50 }, // base cell 52 { 53, 61, 65, 75, 31, 41, 44 }, // base cell 53 { 54, 71, 55, 73, 34, 51, 36 }, // base cell 54 { 55, 40, 54, 36, 72, 60, 73 }, // base cell 55 { 56, 68, 63, 77, 35, 46, 45 }, // base cell 56 { 57, 59, 74, 78, 37, 39, 52 }, // base cell 57 { 58, INVALID_BASE_CELL, 62, 76, 44, 65, 42 }, // base cell 58 (pentagon) { 59, 63, 78, 79, 39, 45, 57 }, // base cell 59 { 60, 72, 68, 80, 40, 55, 46 }, // base cell 60 { 61, 53, 49, 41, 81, 75, 66 }, // base cell 61 { 62, 43, 58, 42, 82, 64, 76 }, // base cell 62 { 63, INVALID_BASE_CELL, 56, 45, 79, 59, 77 }, // base cell 63 (pentagon) { 64, 47, 62, 43, 84, 69, 82 }, // base cell 64 { 65, 58, 53, 44, 86, 76, 75 }, // base cell 65 { 66, 67, 81, 85, 49, 48, 61 }, // base cell 66 { 67, 66, 50, 48, 87, 85, 70 }, // base cell 67 { 68, 56, 60, 46, 90, 77, 80 }, // base cell 68 { 69, 51, 64, 47, 89, 71, 84 }, // base cell 69 { 70, 67, 52, 50, 83, 87, 74 }, // base cell 70 { 71, 89, 73, 91, 51, 69, 54 }, // base cell 71 { 72, INVALID_BASE_CELL, 73, 55, 80, 60, 88 }, // base cell 72 (pentagon) { 73, 91, 72, 88, 54, 71, 55 }, // base cell 73 { 74, 78, 83, 92, 52, 57, 70 }, // base cell 74 { 75, 65, 61, 53, 94, 86, 81 }, // base cell 75 { 76, 86, 82, 96, 58, 65, 62 }, // base cell 76 { 77, 63, 68, 56, 93, 79, 90 }, // base cell 77 { 78, 74, 59, 57, 95, 92, 79 }, // base cell 78 { 79, 78, 63, 59, 93, 95, 77 }, // base cell 79 { 80, 68, 72, 60, 99, 90, 88 }, // base cell 80 { 81, 85, 94, 101, 61, 66, 75 }, // base cell 81 { 82, 96, 84, 98, 62, 76, 64 }, // base cell 82 { 83, INVALID_BASE_CELL, 74, 70, 100, 87, 92 }, // base cell 83 (pentagon) { 84, 69, 82, 64, 97, 89, 98 }, // base cell 84 { 85, 87, 101, 102, 66, 67, 81 }, // base cell 85 { 86, 76, 75, 65, 104, 96, 94 }, // base cell 86 { 87, 83, 102, 100, 67, 70, 85 }, // base cell 87 { 88, 72, 91, 73, 99, 80, 105 }, // base cell 88 { 89, 97, 91, 103, 69, 84, 71 }, // base cell 89 { 90, 77, 80, 68, 106, 93, 99 }, // base cell 90 { 91, 73, 89, 71, 105, 88, 103 }, // base cell 91 { 92, 83, 78, 74, 108, 100, 95 }, // base cell 92 { 93, 79, 90, 77, 109, 95, 106 }, // base cell 93 { 94, 86, 81, 75, 107, 104, 101 }, // base cell 94 { 95, 92, 79, 78, 109, 108, 93 }, // base cell 95 { 96, 104, 98, 110, 76, 86, 82 }, // base cell 96 { 97, INVALID_BASE_CELL, 98, 84, 103, 89, 111 }, // base cell 97 (pentagon) { 98, 110, 97, 111, 82, 96, 84 }, // base cell 98 { 99, 80, 105, 88, 106, 90, 113 }, // base cell 99 { 100, 102, 83, 87, 108, 114, 92 }, // base cell 100 { 101, 102, 107, 112, 81, 85, 94 }, // base cell 101 { 102, 101, 87, 85, 114, 112, 100 }, // base cell 102 { 103, 91, 97, 89, 116, 105, 111 }, // base cell 103 { 104, 107, 110, 115, 86, 94, 96 }, // base cell 104 { 105, 88, 103, 91, 113, 99, 116 }, // base cell 105 { 106, 93, 99, 90, 117, 109, 113 }, // base cell 106 { 107, INVALID_BASE_CELL, 101, 94, 115, 104, 112 }, // base cell 107 (pentagon) { 108, 100, 95, 92, 118, 114, 109 }, // base cell 108 { 109, 108, 93, 95, 117, 118, 106 }, // base cell 109 { 110, 98, 104, 96, 119, 111, 115 }, // base cell 110 { 111, 97, 110, 98, 116, 103, 119 }, // base cell 111 { 112, 107, 102, 101, 120, 115, 114 }, // base cell 112 { 113, 99, 116, 105, 117, 106, 121 }, // base cell 113 { 114, 112, 100, 102, 118, 120, 108 }, // base cell 114 { 115, 110, 107, 104, 120, 119, 112 }, // base cell 115 { 116, 103, 119, 111, 113, 105, 121 }, // base cell 116 { 117, INVALID_BASE_CELL, 109, 118, 113, 121, 106 }, // base cell 117 (pentagon) { 118, 120, 108, 114, 117, 121, 109 }, // base cell 118 { 119, 111, 115, 110, 121, 116, 120 }, // base cell 119 { 120, 115, 114, 112, 121, 119, 118 }, // base cell 120 { 121, 116, 120, 119, 117, 113, 118 }, // base cell 121 }; /** @brief Neighboring base cell rotations in each IJK direction. * * For each base cell, for each direction, the number of 60 degree * CCW rotations to the coordinate system of the neighbor is given. * -1 indicates there is no neighbor in that direction. */ private static final int[][] baseCellNeighbor60CCWRots = new int[][] { { 0, 5, 0, 0, 1, 5, 1 }, // base cell 0 { 0, 0, 1, 0, 1, 0, 1 }, // base cell 1 { 0, 0, 0, 0, 0, 5, 0 }, // base cell 2 { 0, 5, 0, 0, 2, 5, 1 }, // base cell 3 { 0, -1, 1, 0, 3, 4, 2 }, // base cell 4 (pentagon) { 0, 0, 1, 0, 1, 0, 1 }, // base cell 5 { 0, 0, 0, 3, 5, 5, 0 }, // base cell 6 { 0, 0, 0, 0, 0, 5, 0 }, // base cell 7 { 0, 5, 0, 0, 0, 5, 1 }, // base cell 8 { 0, 0, 1, 3, 0, 0, 1 }, // base cell 9 { 0, 0, 1, 3, 0, 0, 1 }, // base cell 10 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 11 { 0, 5, 0, 0, 3, 5, 1 }, // base cell 12 { 0, 0, 1, 0, 1, 0, 1 }, // base cell 13 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 14 (pentagon) { 0, 5, 0, 0, 4, 5, 1 }, // base cell 15 { 0, 0, 0, 0, 0, 5, 0 }, // base cell 16 { 0, 3, 3, 3, 3, 0, 3 }, // base cell 17 { 0, 0, 0, 3, 5, 5, 0 }, // base cell 18 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 19 { 0, 3, 3, 3, 0, 3, 0 }, // base cell 20 { 0, 0, 0, 3, 5, 5, 0 }, // base cell 21 { 0, 0, 1, 0, 1, 0, 1 }, // base cell 22 { 0, 3, 3, 3, 0, 3, 0 }, // base cell 23 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 24 (pentagon) { 0, 0, 0, 3, 0, 0, 3 }, // base cell 25 { 0, 0, 0, 0, 0, 5, 0 }, // base cell 26 { 0, 3, 0, 0, 0, 3, 3 }, // base cell 27 { 0, 0, 1, 0, 1, 0, 1 }, // base cell 28 { 0, 0, 1, 3, 0, 0, 1 }, // base cell 29 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 30 { 0, 0, 0, 0, 0, 5, 0 }, // base cell 31 { 0, 3, 3, 3, 3, 0, 3 }, // base cell 32 { 0, 0, 1, 3, 0, 0, 1 }, // base cell 33 { 0, 3, 3, 3, 3, 0, 3 }, // base cell 34 { 0, 0, 3, 0, 3, 0, 3 }, // base cell 35 { 0, 0, 0, 3, 0, 0, 3 }, // base cell 36 { 0, 3, 0, 0, 0, 3, 3 }, // base cell 37 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 38 (pentagon) { 0, 3, 0, 0, 3, 3, 0 }, // base cell 39 { 0, 3, 0, 0, 3, 3, 0 }, // base cell 40 { 0, 0, 0, 3, 5, 5, 0 }, // base cell 41 { 0, 0, 0, 3, 5, 5, 0 }, // base cell 42 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 43 { 0, 0, 1, 3, 0, 0, 1 }, // base cell 44 { 0, 0, 3, 0, 0, 3, 3 }, // base cell 45 { 0, 0, 0, 3, 0, 3, 0 }, // base cell 46 { 0, 3, 3, 3, 0, 3, 0 }, // base cell 47 { 0, 3, 3, 3, 0, 3, 0 }, // base cell 48 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 49 (pentagon) { 0, 0, 0, 3, 0, 0, 3 }, // base cell 50 { 0, 3, 0, 0, 0, 3, 3 }, // base cell 51 { 0, 0, 3, 0, 3, 0, 3 }, // base cell 52 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 53 { 0, 0, 3, 0, 3, 0, 3 }, // base cell 54 { 0, 0, 3, 0, 0, 3, 3 }, // base cell 55 { 0, 3, 3, 3, 0, 0, 3 }, // base cell 56 { 0, 0, 0, 3, 0, 3, 0 }, // base cell 57 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 58 (pentagon) { 0, 3, 3, 3, 3, 3, 0 }, // base cell 59 { 0, 3, 3, 3, 3, 3, 0 }, // base cell 60 { 0, 3, 3, 3, 3, 0, 3 }, // base cell 61 { 0, 3, 3, 3, 3, 0, 3 }, // base cell 62 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 63 (pentagon) { 0, 0, 0, 3, 0, 0, 3 }, // base cell 64 { 0, 3, 3, 3, 0, 3, 0 }, // base cell 65 { 0, 3, 0, 0, 0, 3, 3 }, // base cell 66 { 0, 3, 0, 0, 3, 3, 0 }, // base cell 67 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 68 { 0, 3, 0, 0, 3, 3, 0 }, // base cell 69 { 0, 0, 3, 0, 0, 3, 3 }, // base cell 70 { 0, 0, 0, 3, 0, 3, 0 }, // base cell 71 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 72 (pentagon) { 0, 3, 3, 3, 0, 0, 3 }, // base cell 73 { 0, 3, 3, 3, 0, 0, 3 }, // base cell 74 { 0, 0, 0, 3, 0, 0, 3 }, // base cell 75 { 0, 3, 0, 0, 0, 3, 3 }, // base cell 76 { 0, 0, 0, 3, 0, 5, 0 }, // base cell 77 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 78 { 0, 0, 1, 3, 1, 0, 1 }, // base cell 79 { 0, 0, 1, 3, 1, 0, 1 }, // base cell 80 { 0, 0, 3, 0, 3, 0, 3 }, // base cell 81 { 0, 0, 3, 0, 3, 0, 3 }, // base cell 82 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 83 (pentagon) { 0, 0, 3, 0, 0, 3, 3 }, // base cell 84 { 0, 0, 0, 3, 0, 3, 0 }, // base cell 85 { 0, 3, 0, 0, 3, 3, 0 }, // base cell 86 { 0, 3, 3, 3, 3, 3, 0 }, // base cell 87 { 0, 0, 0, 3, 0, 5, 0 }, // base cell 88 { 0, 3, 3, 3, 3, 3, 0 }, // base cell 89 { 0, 0, 0, 0, 0, 0, 1 }, // base cell 90 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 91 { 0, 0, 0, 3, 0, 5, 0 }, // base cell 92 { 0, 5, 0, 0, 5, 5, 0 }, // base cell 93 { 0, 0, 3, 0, 0, 3, 3 }, // base cell 94 { 0, 0, 0, 0, 0, 0, 1 }, // base cell 95 { 0, 0, 0, 3, 0, 3, 0 }, // base cell 96 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 97 (pentagon) { 0, 3, 3, 3, 0, 0, 3 }, // base cell 98 { 0, 5, 0, 0, 5, 5, 0 }, // base cell 99 { 0, 0, 1, 3, 1, 0, 1 }, // base cell 100 { 0, 3, 3, 3, 0, 0, 3 }, // base cell 101 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 102 { 0, 0, 1, 3, 1, 0, 1 }, // base cell 103 { 0, 3, 3, 3, 3, 3, 0 }, // base cell 104 { 0, 0, 0, 0, 0, 0, 1 }, // base cell 105 { 0, 0, 1, 0, 3, 5, 1 }, // base cell 106 { 0, -1, 3, 0, 5, 2, 0 }, // base cell 107 (pentagon) { 0, 5, 0, 0, 5, 5, 0 }, // base cell 108 { 0, 0, 1, 0, 4, 5, 1 }, // base cell 109 { 0, 3, 3, 3, 0, 0, 0 }, // base cell 110 { 0, 0, 0, 3, 0, 5, 0 }, // base cell 111 { 0, 0, 0, 3, 0, 5, 0 }, // base cell 112 { 0, 0, 1, 0, 2, 5, 1 }, // base cell 113 { 0, 0, 0, 0, 0, 0, 1 }, // base cell 114 { 0, 0, 1, 3, 1, 0, 1 }, // base cell 115 { 0, 5, 0, 0, 5, 5, 0 }, // base cell 116 { 0, -1, 1, 0, 3, 4, 2 }, // base cell 117 (pentagon) { 0, 0, 1, 0, 0, 5, 1 }, // base cell 118 { 0, 0, 0, 0, 0, 0, 1 }, // base cell 119 { 0, 5, 0, 0, 5, 5, 0 }, // base cell 120 { 0, 0, 1, 0, 1, 5, 1 }, // base cell 121 }; private static final int E_SUCCESS = 0; // Success (no error) private static final int E_PENTAGON = 9; // Pentagon distortion was encountered which the algorithm private static final int E_CELL_INVALID = 5; // `H3Index` cell argument was not valid private static final int E_FAILED = 1; // The operation failed but a more specific error is not available /** * Directions used for traversing a hexagonal ring counterclockwise around * {1, 0, 0} * * <pre> * _ * _/ \\_ * / \\5/ \\ * \\0/ \\4/ * / \\_/ \\ * \\1/ \\3/ * \\2/ * </pre> */ static final CoordIJK.Direction[] DIRECTIONS = new CoordIJK.Direction[] { CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT }; /** * New digit when traversing along class II grids. * * Current digit -> direction -> new digit. */ private static final CoordIJK.Direction[][] NEW_DIGIT_II = new CoordIJK.Direction[][] { { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT }, { CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT }, { CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT }, { CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.K_AXES_DIGIT }, { CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT }, { CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT } }; /** * New traversal direction when traversing along class II grids. * * Current digit -> direction -> new ap7 move (at coarser level). */ private static final CoordIJK.Direction[][] NEW_ADJUSTMENT_II = new CoordIJK.Direction[][] { { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.J_AXES_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT } }; /** * New traversal direction when traversing along class III grids. * * Current digit -> direction -> new ap7 move (at coarser level). */ private static final CoordIJK.Direction[][] NEW_DIGIT_III = new CoordIJK.Direction[][] { { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT }, { CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT }, { CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT }, { CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT }, { CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT }, { CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT } }; /** * New traversal direction when traversing along class III grids. * * Current digit -> direction -> new ap7 move (at coarser level). */ private static final CoordIJK.Direction[][] NEW_ADJUSTMENT_III = new CoordIJK.Direction[][] { { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT }, { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT } }; private static final CoordIJK.Direction[] NEIGHBORSETCLOCKWISE = new CoordIJK.Direction[] { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT }; private static final CoordIJK.Direction[] NEIGHBORSETCOUNTERCLOCKWISE = new CoordIJK.Direction[] { CoordIJK.Direction.CENTER_DIGIT, CoordIJK.Direction.IK_AXES_DIGIT, CoordIJK.Direction.JK_AXES_DIGIT, CoordIJK.Direction.K_AXES_DIGIT, CoordIJK.Direction.IJ_AXES_DIGIT, CoordIJK.Direction.I_AXES_DIGIT, CoordIJK.Direction.J_AXES_DIGIT }; /** * Returns whether or not the provided H3Indexes are neighbors. * @param origin The origin H3 index. * @param destination The destination H3 index. * @return true if the indexes are neighbors, false otherwise */ public static boolean areNeighbours(long origin, long destination) { // Make sure they're hexagon indexes if (H3Index.H3_get_mode(origin) != Constants.H3_CELL_MODE) { throw new IllegalArgumentException("Invalid cell: " + origin); } if (H3Index.H3_get_mode(destination) != Constants.H3_CELL_MODE) { throw new IllegalArgumentException("Invalid cell: " + destination); } // Hexagons cannot be neighbors with themselves if (origin == destination) { return false; } final int resolution = H3Index.H3_get_resolution(origin); // Only hexagons in the same resolution can be neighbors if (resolution != H3Index.H3_get_resolution(destination)) { return false; } // H3 Indexes that share the same parent are very likely to be neighbors // Child 0 is neighbor with all of its parent's 'offspring', the other // children are neighbors with 3 of the 7 children. So a simple comparison // of origin and destination parents and then a lookup table of the children // is a super-cheap way to possibly determine they are neighbors. if (resolution > 1) { long originParent = H3.h3ToParent(origin); long destinationParent = H3.h3ToParent(destination); if (originParent == destinationParent) { int originResDigit = H3Index.H3_get_index_digit(origin, resolution); int destinationResDigit = H3Index.H3_get_index_digit(destination, resolution); if (originResDigit == CoordIJK.Direction.CENTER_DIGIT.digit() || destinationResDigit == CoordIJK.Direction.CENTER_DIGIT.digit()) { return true; } if (originResDigit >= CoordIJK.Direction.INVALID_DIGIT.digit()) { // Prevent indexing off the end of the array below throw new IllegalArgumentException(""); } if ((originResDigit == CoordIJK.Direction.K_AXES_DIGIT.digit() || destinationResDigit == CoordIJK.Direction.K_AXES_DIGIT.digit()) && H3.isPentagon(originParent)) { // If these are invalid cells, fail rather than incorrectly // reporting neighbors. For pentagon cells that are actually // neighbors across the deleted subsequence, they will fail the // optimized check below, but they will be accepted by the // gridDisk check below that. throw new IllegalArgumentException("Undefined error checking for neighbors"); } // These sets are the relevant neighbors in the clockwise // and counter-clockwise if (NEIGHBORSETCLOCKWISE[originResDigit].digit() == destinationResDigit || NEIGHBORSETCOUNTERCLOCKWISE[originResDigit].digit() == destinationResDigit) { return true; } } } // Otherwise, we have to determine the neighbor relationship the "hard" way. for (int i = 0; i < 6; i++) { long neighbor = h3NeighborInDirection(origin, DIRECTIONS[i].digit()); if (neighbor != -1) { // -1 is an expected case when trying to traverse off of // pentagons. if (destination == neighbor) { return true; } } } return false; } /** * Returns the hexagon index neighboring the origin, in the direction dir. * * Implementation note: The only reachable case where this returns -1 is if the * origin is a pentagon and the translation is in the k direction. Thus, * -1 can only be returned if origin is a pentagon. * * @param origin Origin index * @param dir Direction to move in * @return H3Index of the specified neighbor or -1 if there is no more neighbor */ static long h3NeighborInDirection(long origin, int dir) { long current = origin; int newRotations = 0; int oldBaseCell = H3Index.H3_get_base_cell(current); if (oldBaseCell < 0 || oldBaseCell >= Constants.NUM_BASE_CELLS) { // LCOV_EXCL_BR_LINE // Base cells less than zero can not be represented in an index throw new IllegalArgumentException("Invalid base cell looking for neighbor"); } int oldLeadingDigit = H3Index.h3LeadingNonZeroDigit(current); // Adjust the indexing digits and, if needed, the base cell. int r = H3Index.H3_get_resolution(current) - 1; while (true) { if (r == -1) { current = H3Index.H3_set_base_cell(current, baseCellNeighbors[oldBaseCell][dir]); newRotations = baseCellNeighbor60CCWRots[oldBaseCell][dir]; if (H3Index.H3_get_base_cell(current) == INVALID_BASE_CELL) { // Adjust for the deleted k vertex at the base cell level. // This edge actually borders a different neighbor. current = H3Index.H3_set_base_cell(current, baseCellNeighbors[oldBaseCell][CoordIJK.Direction.IK_AXES_DIGIT.digit()]); newRotations = baseCellNeighbor60CCWRots[oldBaseCell][CoordIJK.Direction.IK_AXES_DIGIT.digit()]; // perform the adjustment for the k-subsequence we're skipping // over. current = H3Index.h3Rotate60ccw(current); } break; } else { int oldDigit = H3Index.H3_get_index_digit(current, r + 1); int nextDir; if (oldDigit == CoordIJK.Direction.INVALID_DIGIT.digit()) { // Only possible on invalid input throw new IllegalArgumentException(); } else if (H3Index.isResolutionClassIII(r + 1)) { current = H3Index.H3_set_index_digit(current, r + 1, NEW_DIGIT_II[oldDigit][dir].digit()); nextDir = NEW_ADJUSTMENT_II[oldDigit][dir].digit(); } else { current = H3Index.H3_set_index_digit(current, r + 1, NEW_DIGIT_III[oldDigit][dir].digit()); nextDir = NEW_ADJUSTMENT_III[oldDigit][dir].digit(); } if (nextDir != CoordIJK.Direction.CENTER_DIGIT.digit()) { dir = nextDir; r--; } else { // No more adjustment to perform break; } } } int newBaseCell = H3Index.H3_get_base_cell(current); if (BaseCells.isBaseCellPentagon(newBaseCell)) { // force rotation out of missing k-axes sub-sequence if (H3Index.h3LeadingNonZeroDigit(current) == CoordIJK.Direction.K_AXES_DIGIT.digit()) { if (oldBaseCell != newBaseCell) { // in this case, we traversed into the deleted // k subsequence of a pentagon base cell. // We need to rotate out of that case depending // on how we got here. // check for a cw/ccw offset face; default is ccw if (BaseCells.baseCellIsCwOffset(newBaseCell, BaseCells.getBaseFaceIJK(oldBaseCell).face)) { current = H3Index.h3Rotate60cw(current); } else { // See cwOffsetPent in testGridDisk.c for why this is // unreachable. current = H3Index.h3Rotate60ccw(current); // LCOV_EXCL_LINE } } else { // In this case, we traversed into the deleted // k subsequence from within the same pentagon // base cell. if (oldLeadingDigit == CoordIJK.Direction.CENTER_DIGIT.digit()) { // Undefined: the k direction is deleted from here return -1L; } else if (oldLeadingDigit == CoordIJK.Direction.JK_AXES_DIGIT.digit()) { // Rotate out of the deleted k subsequence // We also need an additional change to the direction we're // moving in current = H3Index.h3Rotate60ccw(current); } else if (oldLeadingDigit == CoordIJK.Direction.IK_AXES_DIGIT.digit()) { // Rotate out of the deleted k subsequence // We also need an additional change to the direction we're // moving in current = H3Index.h3Rotate60cw(current); } else { // Should never occur throw new IllegalArgumentException("Undefined error looking for neighbor"); // LCOV_EXCL_LINE } } } for (int i = 0; i < newRotations; i++) { current = H3Index.h3RotatePent60ccw(current); } } else { for (int i = 0; i < newRotations; i++) { current = H3Index.h3Rotate60ccw(current); } } return current; } }
elastic/elasticsearch
libs/h3/src/main/java/org/elasticsearch/h3/HexRing.java
388
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.flux.view; import com.iluwatar.flux.store.Store; /** * Views define the representation of data. */ public interface View { void storeChanged(Store store); void render(); }
smedals/java-design-patterns
flux/src/main/java/com/iluwatar/flux/view/View.java
389
/* * 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.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Objects; import com.google.common.base.Supplier; import com.google.common.collect.Table.Cell; import java.io.Serializable; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.Map; import java.util.Set; import java.util.SortedMap; import java.util.SortedSet; import java.util.function.BinaryOperator; import java.util.stream.Collector; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Provides static methods that involve a {@code Table}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#tables">{@code Tables}</a>. * * @author Jared Levy * @author Louis Wasserman * @since 7.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Tables { private Tables() {} /** * Returns a {@link Collector} that accumulates elements into a {@code Table} created using the * specified supplier, whose cells are generated by applying the provided mapping functions to the * input elements. Cells are inserted into the generated {@code Table} in encounter order. * * <p>If multiple input elements map to the same row and column, an {@code IllegalStateException} * is thrown when the collection operation is performed. * * <p>To collect to an {@link ImmutableTable}, use {@link ImmutableTable#toImmutableTable}. * * @since 33.2.0 (available since 21.0 in guava-jre) */ @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"}) @IgnoreJRERequirement // Users will use this only if they're already using streams. @Beta // TODO: b/288085449 - Remove. public static < T extends @Nullable Object, R extends @Nullable Object, C extends @Nullable Object, V, I extends Table<R, C, V>> Collector<T, ?, I> toTable( java.util.function.Function<? super T, ? extends R> rowFunction, java.util.function.Function<? super T, ? extends C> columnFunction, java.util.function.Function<? super T, ? extends V> valueFunction, java.util.function.Supplier<I> tableSupplier) { return TableCollectors.<T, R, C, V, I>toTable( rowFunction, columnFunction, valueFunction, tableSupplier); } /** * Returns a {@link Collector} that accumulates elements into a {@code Table} created using the * specified supplier, whose cells are generated by applying the provided mapping functions to the * input elements. Cells are inserted into the generated {@code Table} in encounter order. * * <p>If multiple input elements map to the same row and column, the specified merging function is * used to combine the values. Like {@link * java.util.stream.Collectors#toMap(java.util.function.Function, java.util.function.Function, * BinaryOperator, java.util.function.Supplier)}, this Collector throws a {@code * NullPointerException} on null values returned from {@code valueFunction}, and treats nulls * returned from {@code mergeFunction} as removals of that row/column pair. * * @since 33.2.0 (available since 21.0 in guava-jre) */ @SuppressWarnings({"AndroidJdkLibsChecker", "Java7ApiChecker"}) @IgnoreJRERequirement // Users will use this only if they're already using streams. @Beta // TODO: b/288085449 - Remove. public static < T extends @Nullable Object, R extends @Nullable Object, C extends @Nullable Object, V, I extends Table<R, C, V>> Collector<T, ?, I> toTable( java.util.function.Function<? super T, ? extends R> rowFunction, java.util.function.Function<? super T, ? extends C> columnFunction, java.util.function.Function<? super T, ? extends V> valueFunction, BinaryOperator<V> mergeFunction, java.util.function.Supplier<I> tableSupplier) { return TableCollectors.<T, R, C, V, I>toTable( rowFunction, columnFunction, valueFunction, mergeFunction, tableSupplier); } /** * Returns an immutable cell with the specified row key, column key, and value. * * <p>The returned cell is serializable. * * @param rowKey the row key to be associated with the returned cell * @param columnKey the column key to be associated with the returned cell * @param value the value to be associated with the returned cell */ public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Cell<R, C, V> immutableCell( @ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value) { return new ImmutableCell<>(rowKey, columnKey, value); } static final class ImmutableCell< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> extends AbstractCell<R, C, V> implements Serializable { @ParametricNullness private final R rowKey; @ParametricNullness private final C columnKey; @ParametricNullness private final V value; ImmutableCell( @ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value) { this.rowKey = rowKey; this.columnKey = columnKey; this.value = value; } @Override @ParametricNullness public R getRowKey() { return rowKey; } @Override @ParametricNullness public C getColumnKey() { return columnKey; } @Override @ParametricNullness public V getValue() { return value; } private static final long serialVersionUID = 0; } abstract static class AbstractCell< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> implements Cell<R, C, V> { // needed for serialization AbstractCell() {} @Override public boolean equals(@CheckForNull Object obj) { if (obj == this) { return true; } if (obj instanceof Cell) { Cell<?, ?, ?> other = (Cell<?, ?, ?>) obj; return Objects.equal(getRowKey(), other.getRowKey()) && Objects.equal(getColumnKey(), other.getColumnKey()) && Objects.equal(getValue(), other.getValue()); } return false; } @Override public int hashCode() { return Objects.hashCode(getRowKey(), getColumnKey(), getValue()); } @Override public String toString() { return "(" + getRowKey() + "," + getColumnKey() + ")=" + getValue(); } } /** * Creates a transposed view of a given table that flips its row and column keys. In other words, * calling {@code get(columnKey, rowKey)} on the generated table always returns the same value as * calling {@code get(rowKey, columnKey)} on the original table. Updating the original table * changes the contents of the transposed table and vice versa. * * <p>The returned table supports update operations as long as the input table supports the * analogous operation with swapped rows and columns. For example, in a {@link HashBasedTable} * instance, {@code rowKeySet().iterator()} supports {@code remove()} but {@code * columnKeySet().iterator()} doesn't. With a transposed {@link HashBasedTable}, it's the other * way around. */ public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Table<C, R, V> transpose(Table<R, C, V> table) { return (table instanceof TransposeTable) ? ((TransposeTable<R, C, V>) table).original : new TransposeTable<C, R, V>(table); } private static class TransposeTable< C extends @Nullable Object, R extends @Nullable Object, V extends @Nullable Object> extends AbstractTable<C, R, V> { final Table<R, C, V> original; TransposeTable(Table<R, C, V> original) { this.original = checkNotNull(original); } @Override public void clear() { original.clear(); } @Override public Map<C, V> column(@ParametricNullness R columnKey) { return original.row(columnKey); } @Override public Set<R> columnKeySet() { return original.rowKeySet(); } @Override public Map<R, Map<C, V>> columnMap() { return original.rowMap(); } @Override public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return original.contains(columnKey, rowKey); } @Override public boolean containsColumn(@CheckForNull Object columnKey) { return original.containsRow(columnKey); } @Override public boolean containsRow(@CheckForNull Object rowKey) { return original.containsColumn(rowKey); } @Override public boolean containsValue(@CheckForNull Object value) { return original.containsValue(value); } @Override @CheckForNull public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return original.get(columnKey, rowKey); } @Override @CheckForNull public V put( @ParametricNullness C rowKey, @ParametricNullness R columnKey, @ParametricNullness V value) { return original.put(columnKey, rowKey, value); } @Override public void putAll(Table<? extends C, ? extends R, ? extends V> table) { original.putAll(transpose(table)); } @Override @CheckForNull public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return original.remove(columnKey, rowKey); } @Override public Map<R, V> row(@ParametricNullness C rowKey) { return original.column(rowKey); } @Override public Set<C> rowKeySet() { return original.columnKeySet(); } @Override public Map<C, Map<R, V>> rowMap() { return original.columnMap(); } @Override public int size() { return original.size(); } @Override public Collection<V> values() { return original.values(); } @Override Iterator<Cell<C, R, V>> cellIterator() { return Iterators.transform(original.cellSet().iterator(), Tables::transposeCell); } } private static < R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Cell<C, R, V> transposeCell(Cell<R, C, V> cell) { return immutableCell(cell.getColumnKey(), cell.getRowKey(), cell.getValue()); } /** * Creates a table that uses the specified backing map and factory. It can generate a table based * on arbitrary {@link Map} classes. * * <p>The {@code factory}-generated and {@code backingMap} classes determine the table iteration * order. However, the table's {@code row()} method returns instances of a different class than * {@code factory.get()} does. * * <p>Call this method only when the simpler factory methods in classes like {@link * HashBasedTable} and {@link TreeBasedTable} won't suffice. * * <p>The views returned by the {@code Table} methods {@link Table#column}, {@link * Table#columnKeySet}, and {@link Table#columnMap} have iterators that don't support {@code * remove()}. Otherwise, all optional operations are supported. Null row keys, columns keys, and * values are not supported. * * <p>Lookups by row key are often faster than lookups by column key, because the data is stored * in a {@code Map<R, Map<C, V>>}. A method call like {@code column(columnKey).get(rowKey)} still * runs quickly, since the row key is provided. However, {@code column(columnKey).size()} takes * longer, since an iteration across all row keys occurs. * * <p>Note that this implementation is not synchronized. If multiple threads access this table * concurrently and one of the threads modifies the table, it must be synchronized externally. * * <p>The table is serializable if {@code backingMap}, {@code factory}, the maps generated by * {@code factory}, and the table contents are all serializable. * * <p>Note: the table assumes complete ownership over of {@code backingMap} and the maps returned * by {@code factory}. Those objects should not be manually updated and they should not use soft, * weak, or phantom references. * * @param backingMap place to store the mapping from each row key to its corresponding column key * / value map * @param factory supplier of new, empty maps that will each hold all column key / value mappings * for a given row key * @throws IllegalArgumentException if {@code backingMap} is not empty * @since 10.0 */ public static <R, C, V> Table<R, C, V> newCustomTable( Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) { checkArgument(backingMap.isEmpty()); checkNotNull(factory); // TODO(jlevy): Wrap factory to validate that the supplied maps are empty? return new StandardTable<>(backingMap, factory); } /** * Returns a view of a table where each value is transformed by a function. All other properties * of the table, such as iteration order, are left intact. * * <p>Changes in the underlying table are reflected in this view. Conversely, this view supports * removal operations, and these are reflected in the underlying table. * * <p>It's acceptable for the underlying table to contain null keys, and even null values provided * that the function is capable of accepting null input. The transformed table might contain null * values, if the function sometimes gives a null result. * * <p>The returned table is not thread-safe or serializable, even if the underlying table is. * * <p>The function is applied lazily, invoked when needed. This is necessary for the returned * table to be a view, but it means that the function will be applied many times for bulk * operations like {@link Table#containsValue} and {@code Table.toString()}. For this to perform * well, {@code function} should be fast. To avoid lazy evaluation when the returned table doesn't * need to be a view, copy the returned table into a new table of your choosing. * * @since 10.0 */ public static < R extends @Nullable Object, C extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> Table<R, C, V2> transformValues( Table<R, C, V1> fromTable, Function<? super V1, V2> function) { return new TransformedTable<>(fromTable, function); } private static class TransformedTable< R extends @Nullable Object, C extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> extends AbstractTable<R, C, V2> { final Table<R, C, V1> fromTable; final Function<? super V1, V2> function; TransformedTable(Table<R, C, V1> fromTable, Function<? super V1, V2> function) { this.fromTable = checkNotNull(fromTable); this.function = checkNotNull(function); } @Override public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return fromTable.contains(rowKey, columnKey); } @Override @CheckForNull public V2 get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { // The function is passed a null input only when the table contains a null // value. // The cast is safe because of the contains() check. return contains(rowKey, columnKey) ? function.apply(uncheckedCastNullableTToT(fromTable.get(rowKey, columnKey))) : null; } @Override public int size() { return fromTable.size(); } @Override public void clear() { fromTable.clear(); } @Override @CheckForNull public V2 put( @ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V2 value) { throw new UnsupportedOperationException(); } @Override public void putAll(Table<? extends R, ? extends C, ? extends V2> table) { throw new UnsupportedOperationException(); } @Override @CheckForNull public V2 remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return contains(rowKey, columnKey) // The cast is safe because of the contains() check. ? function.apply(uncheckedCastNullableTToT(fromTable.remove(rowKey, columnKey))) : null; } @Override public Map<C, V2> row(@ParametricNullness R rowKey) { return Maps.transformValues(fromTable.row(rowKey), function); } @Override public Map<R, V2> column(@ParametricNullness C columnKey) { return Maps.transformValues(fromTable.column(columnKey), function); } Function<Cell<R, C, V1>, Cell<R, C, V2>> cellFunction() { return new Function<Cell<R, C, V1>, Cell<R, C, V2>>() { @Override public Cell<R, C, V2> apply(Cell<R, C, V1> cell) { return immutableCell( cell.getRowKey(), cell.getColumnKey(), function.apply(cell.getValue())); } }; } @Override Iterator<Cell<R, C, V2>> cellIterator() { return Iterators.transform(fromTable.cellSet().iterator(), cellFunction()); } @Override public Set<R> rowKeySet() { return fromTable.rowKeySet(); } @Override public Set<C> columnKeySet() { return fromTable.columnKeySet(); } @Override Collection<V2> createValues() { return Collections2.transform(fromTable.values(), function); } @Override public Map<R, Map<C, V2>> rowMap() { Function<Map<C, V1>, Map<C, V2>> rowFunction = new Function<Map<C, V1>, Map<C, V2>>() { @Override public Map<C, V2> apply(Map<C, V1> row) { return Maps.transformValues(row, function); } }; return Maps.transformValues(fromTable.rowMap(), rowFunction); } @Override public Map<C, Map<R, V2>> columnMap() { Function<Map<R, V1>, Map<R, V2>> columnFunction = new Function<Map<R, V1>, Map<R, V2>>() { @Override public Map<R, V2> apply(Map<R, V1> column) { return Maps.transformValues(column, function); } }; return Maps.transformValues(fromTable.columnMap(), columnFunction); } } /** * Returns an unmodifiable view of the specified table. This method allows modules to provide * users with "read-only" access to internal tables. Query operations on the returned table "read * through" to the specified table, and attempts to modify the returned table, whether direct or * via its collection views, result in an {@code UnsupportedOperationException}. * * <p>The returned table will be serializable if the specified table is serializable. * * <p>Consider using an {@link ImmutableTable}, which is guaranteed never to change. * * @since 11.0 */ public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Table<R, C, V> unmodifiableTable(Table<? extends R, ? extends C, ? extends V> table) { return new UnmodifiableTable<>(table); } private static class UnmodifiableTable< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> extends ForwardingTable<R, C, V> implements Serializable { final Table<? extends R, ? extends C, ? extends V> delegate; UnmodifiableTable(Table<? extends R, ? extends C, ? extends V> delegate) { this.delegate = checkNotNull(delegate); } @SuppressWarnings("unchecked") // safe, covariant cast @Override protected Table<R, C, V> delegate() { return (Table<R, C, V>) delegate; } @Override public Set<Cell<R, C, V>> cellSet() { return Collections.unmodifiableSet(super.cellSet()); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Map<R, V> column(@ParametricNullness C columnKey) { return Collections.unmodifiableMap(super.column(columnKey)); } @Override public Set<C> columnKeySet() { return Collections.unmodifiableSet(super.columnKeySet()); } @Override public Map<C, Map<R, V>> columnMap() { Function<Map<R, V>, Map<R, V>> wrapper = unmodifiableWrapper(); return Collections.unmodifiableMap(Maps.transformValues(super.columnMap(), wrapper)); } @Override @CheckForNull public V put( @ParametricNullness R rowKey, @ParametricNullness C columnKey, @ParametricNullness V value) { throw new UnsupportedOperationException(); } @Override public void putAll(Table<? extends R, ? extends C, ? extends V> table) { throw new UnsupportedOperationException(); } @Override @CheckForNull public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { throw new UnsupportedOperationException(); } @Override public Map<C, V> row(@ParametricNullness R rowKey) { return Collections.unmodifiableMap(super.row(rowKey)); } @Override public Set<R> rowKeySet() { return Collections.unmodifiableSet(super.rowKeySet()); } @Override public Map<R, Map<C, V>> rowMap() { Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper(); return Collections.unmodifiableMap(Maps.transformValues(super.rowMap(), wrapper)); } @Override public Collection<V> values() { return Collections.unmodifiableCollection(super.values()); } private static final long serialVersionUID = 0; } /** * Returns an unmodifiable view of the specified row-sorted table. This method allows modules to * provide users with "read-only" access to internal tables. Query operations on the returned * table "read through" to the specified table, and attempts to modify the returned table, whether * direct or via its collection views, result in an {@code UnsupportedOperationException}. * * <p>The returned table will be serializable if the specified table is serializable. * * @param table the row-sorted table for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified table * @since 11.0 */ public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> RowSortedTable<R, C, V> unmodifiableRowSortedTable( RowSortedTable<R, ? extends C, ? extends V> table) { /* * It's not ? extends R, because it's technically not covariant in R. Specifically, * table.rowMap().comparator() could return a comparator that only works for the ? extends R. * Collections.unmodifiableSortedMap makes the same distinction. */ return new UnmodifiableRowSortedMap<>(table); } private static final class UnmodifiableRowSortedMap< R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> extends UnmodifiableTable<R, C, V> implements RowSortedTable<R, C, V> { public UnmodifiableRowSortedMap(RowSortedTable<R, ? extends C, ? extends V> delegate) { super(delegate); } @Override protected RowSortedTable<R, C, V> delegate() { return (RowSortedTable<R, C, V>) super.delegate(); } @Override public SortedMap<R, Map<C, V>> rowMap() { Function<Map<C, V>, Map<C, V>> wrapper = unmodifiableWrapper(); return Collections.unmodifiableSortedMap(Maps.transformValues(delegate().rowMap(), wrapper)); } @Override public SortedSet<R> rowKeySet() { return Collections.unmodifiableSortedSet(delegate().rowKeySet()); } private static final long serialVersionUID = 0; } @SuppressWarnings("unchecked") private static <K extends @Nullable Object, V extends @Nullable Object> Function<Map<K, V>, Map<K, V>> unmodifiableWrapper() { return (Function) UNMODIFIABLE_WRAPPER; } private static final Function<? extends Map<?, ?>, ? extends Map<?, ?>> UNMODIFIABLE_WRAPPER = new Function<Map<Object, Object>, Map<Object, Object>>() { @Override public Map<Object, Object> apply(Map<Object, Object> input) { return Collections.unmodifiableMap(input); } }; /** * Returns a synchronized (thread-safe) table backed by the specified table. In order to guarantee * serial access, it is critical that <b>all</b> access to the backing table is accomplished * through the returned table. * * <p>It is imperative that the user manually synchronize on the returned table when accessing any * of its collection views: * * <pre>{@code * Table<R, C, V> table = Tables.synchronizedTable(HashBasedTable.<R, C, V>create()); * ... * Map<C, V> row = table.row(rowKey); // Needn't be in synchronized block * ... * synchronized (table) { // Synchronizing on table, not row! * Iterator<Entry<C, V>> i = row.entrySet().iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * } * }</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>The returned table will be serializable if the specified table is serializable. * * @param table the table to be wrapped in a synchronized view * @return a synchronized view of the specified table * @since 22.0 */ public static <R extends @Nullable Object, C extends @Nullable Object, V extends @Nullable Object> Table<R, C, V> synchronizedTable(Table<R, C, V> table) { return Synchronized.table(table, null); } static boolean equalsImpl(Table<?, ?, ?> table, @CheckForNull Object obj) { if (obj == table) { return true; } else if (obj instanceof Table) { Table<?, ?, ?> that = (Table<?, ?, ?>) obj; return table.cellSet().equals(that.cellSet()); } else { return false; } } }
google/guava
android/guava/src/com/google/common/collect/Tables.java
390
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import java.io.Serializable; import java.lang.ref.WeakReference; import java.lang.reflect.Field; import java.util.EnumSet; import java.util.HashMap; import java.util.Map; import java.util.WeakHashMap; import javax.annotation.CheckForNull; /** * Utility methods for working with {@link Enum} instances. * * @author Steve McKay * @since 9.0 */ @GwtIncompatible @J2ktIncompatible @ElementTypesAreNonnullByDefault public final class Enums { private Enums() {} /** * Returns the {@link Field} in which {@code enumValue} is defined. For example, to get the {@code * Description} annotation on the {@code GOLF} constant of enum {@code Sport}, use {@code * Enums.getField(Sport.GOLF).getAnnotation(Description.class)}. * * @since 12.0 */ @GwtIncompatible // reflection public static Field getField(Enum<?> enumValue) { Class<?> clazz = enumValue.getDeclaringClass(); try { return clazz.getDeclaredField(enumValue.name()); } catch (NoSuchFieldException impossible) { throw new AssertionError(impossible); } } /** * Returns an optional enum constant for the given type, using {@link Enum#valueOf}. If the * constant does not exist, {@link Optional#absent} is returned. A common use case is for parsing * user input or falling back to a default enum constant. For example, {@code * Enums.getIfPresent(Country.class, countryInput).or(Country.DEFAULT);} * * @since 12.0 */ public static <T extends Enum<T>> Optional<T> getIfPresent(Class<T> enumClass, String value) { checkNotNull(enumClass); checkNotNull(value); return Platform.getEnumIfPresent(enumClass, value); } @GwtIncompatible // java.lang.ref.WeakReference private static final Map<Class<? extends Enum<?>>, Map<String, WeakReference<? extends Enum<?>>>> enumConstantCache = new WeakHashMap<>(); @GwtIncompatible // java.lang.ref.WeakReference private static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> populateCache( Class<T> enumClass) { Map<String, WeakReference<? extends Enum<?>>> result = new HashMap<>(); for (T enumInstance : EnumSet.allOf(enumClass)) { result.put(enumInstance.name(), new WeakReference<Enum<?>>(enumInstance)); } enumConstantCache.put(enumClass, result); return result; } @GwtIncompatible // java.lang.ref.WeakReference static <T extends Enum<T>> Map<String, WeakReference<? extends Enum<?>>> getEnumConstants( Class<T> enumClass) { synchronized (enumConstantCache) { Map<String, WeakReference<? extends Enum<?>>> constants = enumConstantCache.get(enumClass); if (constants == null) { constants = populateCache(enumClass); } return constants; } } /** * Returns a serializable converter that converts between strings and {@code enum} values of type * {@code enumClass} using {@link Enum#valueOf(Class, String)} and {@link Enum#name()}. The * converter will throw an {@code IllegalArgumentException} if the argument is not the name of any * enum constant in the specified enum. * * @since 16.0 */ @GwtIncompatible public static <T extends Enum<T>> Converter<String, T> stringConverter(Class<T> enumClass) { return new StringConverter<>(enumClass); } @GwtIncompatible private static final class StringConverter<T extends Enum<T>> extends Converter<String, T> implements Serializable { private final Class<T> enumClass; StringConverter(Class<T> enumClass) { this.enumClass = checkNotNull(enumClass); } @Override protected T doForward(String value) { return Enum.valueOf(enumClass, value); } @Override protected String doBackward(T enumValue) { return enumValue.name(); } @Override public boolean equals(@CheckForNull Object object) { if (object instanceof StringConverter) { StringConverter<?> that = (StringConverter<?>) object; return this.enumClass.equals(that.enumClass); } return false; } @Override public int hashCode() { return enumClass.hashCode(); } @Override public String toString() { return "Enums.stringConverter(" + enumClass.getName() + ".class)"; } private static final long serialVersionUID = 0L; } }
google/guava
android/guava/src/com/google/common/base/Enums.java
391
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.prototype; import lombok.EqualsAndHashCode; import lombok.NoArgsConstructor; /** * Warlord. */ @EqualsAndHashCode(callSuper = false) @NoArgsConstructor public abstract class Warlord extends Prototype<Warlord> { public Warlord(Warlord source) { } }
smedals/java-design-patterns
prototype/src/main/java/com/iluwatar/prototype/Warlord.java
392
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.command; import java.util.Deque; import java.util.LinkedList; import lombok.extern.slf4j.Slf4j; /** * Wizard is the invoker of the commands. */ @Slf4j public class Wizard { private final Deque<Runnable> undoStack = new LinkedList<>(); private final Deque<Runnable> redoStack = new LinkedList<>(); /** * Cast spell. */ public void castSpell(Runnable runnable) { runnable.run(); undoStack.offerLast(runnable); } /** * Undo last spell. */ public void undoLastSpell() { if (!undoStack.isEmpty()) { var previousSpell = undoStack.pollLast(); redoStack.offerLast(previousSpell); previousSpell.run(); } } /** * Redo last spell. */ public void redoLastSpell() { if (!redoStack.isEmpty()) { var previousSpell = redoStack.pollLast(); undoStack.offerLast(previousSpell); previousSpell.run(); } } @Override public String toString() { return "Wizard"; } }
smedals/java-design-patterns
command/src/main/java/com/iluwatar/command/Wizard.java
393
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.errorprone.annotations.ForOverride; import java.io.Serializable; import java.util.function.BiPredicate; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A strategy for determining whether two instances are considered equivalent, and for computing * hash codes in a manner consistent with that equivalence. Two examples of equivalences are the * {@linkplain #identity() identity equivalence} and the {@linkplain #equals "equals" equivalence}. * * @author Bob Lee * @author Ben Yu * @author Gregory Kick * @since 10.0 (<a href="https://github.com/google/guava/wiki/Compatibility">mostly * source-compatible</a> since 4.0) */ @GwtCompatible @ElementTypesAreNonnullByDefault /* * The type parameter is <T> rather than <T extends @Nullable> so that we can use T in the * doEquivalent and doHash methods to indicate that the parameter cannot be null. */ public abstract class Equivalence<T> implements BiPredicate<@Nullable T, @Nullable T> { /** Constructor for use by subclasses. */ protected Equivalence() {} /** * Returns {@code true} if the given objects are considered equivalent. * * <p>This method describes an <i>equivalence relation</i> on object references, meaning that for * all references {@code x}, {@code y}, and {@code z} (any of which may be null): * * <ul> * <li>{@code equivalent(x, x)} is true (<i>reflexive</i> property) * <li>{@code equivalent(x, y)} and {@code equivalent(y, x)} each return the same result * (<i>symmetric</i> property) * <li>If {@code equivalent(x, y)} and {@code equivalent(y, z)} are both true, then {@code * equivalent(x, z)} is also true (<i>transitive</i> property) * </ul> * * <p>Note that all calls to {@code equivalent(x, y)} are expected to return the same result as * long as neither {@code x} nor {@code y} is modified. */ public final boolean equivalent(@CheckForNull T a, @CheckForNull T b) { if (a == b) { return true; } if (a == null || b == null) { return false; } return doEquivalent(a, b); } /** * @deprecated Provided only to satisfy the {@link BiPredicate} interface; use {@link #equivalent} * instead. * @since 21.0 */ @Deprecated @Override public final boolean test(@CheckForNull T t, @CheckForNull T u) { return equivalent(t, u); } /** * Implemented by the user to determine whether {@code a} and {@code b} are considered equivalent, * subject to the requirements specified in {@link #equivalent}. * * <p>This method should not be called except by {@link #equivalent}. When {@link #equivalent} * calls this method, {@code a} and {@code b} are guaranteed to be distinct, non-null instances. * * @since 10.0 (previously, subclasses would override equivalent()) */ @ForOverride protected abstract boolean doEquivalent(T a, T b); /** * Returns a hash code for {@code t}. * * <p>The {@code hash} has the following properties: * * <ul> * <li>It is <i>consistent</i>: for any reference {@code x}, multiple invocations of {@code * hash(x}} consistently return the same value provided {@code x} remains unchanged * according to the definition of the equivalence. The hash need not remain consistent from * one execution of an application to another execution of the same application. * <li>It is <i>distributable across equivalence</i>: for any references {@code x} and {@code * y}, if {@code equivalent(x, y)}, then {@code hash(x) == hash(y)}. It is <i>not</i> * necessary that the hash be distributable across <i>inequivalence</i>. If {@code * equivalence(x, y)} is false, {@code hash(x) == hash(y)} may still be true. * <li>{@code hash(null)} is {@code 0}. * </ul> */ public final int hash(@CheckForNull T t) { if (t == null) { return 0; } return doHash(t); } /** * Implemented by the user to return a hash code for {@code t}, subject to the requirements * specified in {@link #hash}. * * <p>This method should not be called except by {@link #hash}. When {@link #hash} calls this * method, {@code t} is guaranteed to be non-null. * * @since 10.0 (previously, subclasses would override hash()) */ @ForOverride protected abstract int doHash(T t); /** * Returns a new equivalence relation for {@code F} which evaluates equivalence by first applying * {@code function} to the argument, then evaluating using {@code this}. That is, for any pair of * non-null objects {@code x} and {@code y}, {@code equivalence.onResultOf(function).equivalent(a, * b)} is true if and only if {@code equivalence.equivalent(function.apply(a), function.apply(b))} * is true. * * <p>For example: * * <pre>{@code * Equivalence<Person> SAME_AGE = Equivalence.equals().onResultOf(GET_PERSON_AGE); * }</pre> * * <p>{@code function} will never be invoked with a null value. * * <p>Note that {@code function} must be consistent according to {@code this} equivalence * relation. That is, invoking {@link Function#apply} multiple times for a given value must return * equivalent results. For example, {@code * Equivalence.identity().onResultOf(Functions.toStringFunction())} is broken because it's not * guaranteed that {@link Object#toString}) always returns the same string instance. * * @since 10.0 */ public final <F> Equivalence<F> onResultOf(Function<? super F, ? extends @Nullable T> function) { return new FunctionalEquivalence<>(function, this); } /** * Returns a wrapper of {@code reference} that implements {@link Wrapper#equals(Object) * Object.equals()} such that {@code wrap(a).equals(wrap(b))} if and only if {@code equivalent(a, * b)}. * * <p>The returned object is serializable if both this {@code Equivalence} and {@code reference} * are serializable (including when {@code reference} is null). * * @since 10.0 */ public final <S extends @Nullable T> Wrapper<S> wrap(@ParametricNullness S reference) { return new Wrapper<>(this, reference); } /** * Wraps an object so that {@link #equals(Object)} and {@link #hashCode()} delegate to an {@link * Equivalence}. * * <p>For example, given an {@link Equivalence} for {@link String strings} named {@code equiv} * that tests equivalence using their lengths: * * <pre>{@code * equiv.wrap("a").equals(equiv.wrap("b")) // true * equiv.wrap("a").equals(equiv.wrap("hello")) // false * }</pre> * * <p>Note in particular that an equivalence wrapper is never equal to the object it wraps. * * <pre>{@code * equiv.wrap(obj).equals(obj) // always false * }</pre> * * @since 10.0 */ public static final class Wrapper<T extends @Nullable Object> implements Serializable { /* * Equivalence's type argument is always non-nullable: Equivalence<Number>, never * Equivalence<@Nullable Number>. That can still produce wrappers of various types -- * Wrapper<Number>, Wrapper<Integer>, Wrapper<@Nullable Integer>, etc. If we used just * Equivalence<? super T> below, no type could satisfy both that bound and T's own * bound. With this type, they have some overlap: in our example, Equivalence<Number> * and Equivalence<Object>. */ private final Equivalence<? super @NonNull T> equivalence; @ParametricNullness private final T reference; private Wrapper(Equivalence<? super @NonNull T> equivalence, @ParametricNullness T reference) { this.equivalence = checkNotNull(equivalence); this.reference = reference; } /** Returns the (possibly null) reference wrapped by this instance. */ @ParametricNullness public T get() { return reference; } /** * Returns {@code true} if {@link Equivalence#equivalent(Object, Object)} applied to the wrapped * references is {@code true} and both wrappers use the {@link Object#equals(Object) same} * equivalence. */ @Override public boolean equals(@CheckForNull Object obj) { if (obj == this) { return true; } if (obj instanceof Wrapper) { Wrapper<?> that = (Wrapper<?>) obj; // note: not necessarily a Wrapper<T> if (this.equivalence.equals(that.equivalence)) { /* * We'll accept that as sufficient "proof" that either equivalence should be able to * handle either reference, so it's safe to circumvent compile-time type checking. */ @SuppressWarnings("unchecked") Equivalence<Object> equivalence = (Equivalence<Object>) this.equivalence; return equivalence.equivalent(this.reference, that.reference); } } return false; } /** Returns the result of {@link Equivalence#hash(Object)} applied to the wrapped reference. */ @Override public int hashCode() { return equivalence.hash(reference); } /** * Returns a string representation for this equivalence wrapper. The form of this string * representation is not specified. */ @Override public String toString() { return equivalence + ".wrap(" + reference + ")"; } private static final long serialVersionUID = 0; } /** * Returns an equivalence over iterables based on the equivalence of their elements. More * specifically, two iterables are considered equivalent if they both contain the same number of * elements, and each pair of corresponding elements is equivalent according to {@code this}. Null * iterables are equivalent to one another. * * <p>Note that this method performs a similar function for equivalences as {@link * com.google.common.collect.Ordering#lexicographical} does for orderings. * * <p>The returned object is serializable if this object is serializable. * * @since 10.0 */ @GwtCompatible(serializable = true) public final <S extends @Nullable T> Equivalence<Iterable<S>> pairwise() { // Ideally, the returned equivalence would support Iterable<? extends T>. However, // the need for this is so rare that it's not worth making callers deal with the ugly wildcard. return new PairwiseEquivalence<>(this); } /** * Returns a predicate that evaluates to true if and only if the input is equivalent to {@code * target} according to this equivalence relation. * * @since 10.0 */ public final Predicate<@Nullable T> equivalentTo(@CheckForNull T target) { return new EquivalentToPredicate<>(this, target); } private static final class EquivalentToPredicate<T> implements Predicate<@Nullable T>, Serializable { private final Equivalence<T> equivalence; @CheckForNull private final T target; EquivalentToPredicate(Equivalence<T> equivalence, @CheckForNull T target) { this.equivalence = checkNotNull(equivalence); this.target = target; } @Override public boolean apply(@CheckForNull T input) { return equivalence.equivalent(input, target); } @Override public boolean equals(@CheckForNull Object obj) { if (this == obj) { return true; } if (obj instanceof EquivalentToPredicate) { EquivalentToPredicate<?> that = (EquivalentToPredicate<?>) obj; return equivalence.equals(that.equivalence) && Objects.equal(target, that.target); } return false; } @Override public int hashCode() { return Objects.hashCode(equivalence, target); } @Override public String toString() { return equivalence + ".equivalentTo(" + target + ")"; } private static final long serialVersionUID = 0; } /** * Returns an equivalence that delegates to {@link Object#equals} and {@link Object#hashCode}. * {@link Equivalence#equivalent} returns {@code true} if both values are null, or if neither * value is null and {@link Object#equals} returns {@code true}. {@link Equivalence#hash} returns * {@code 0} if passed a null value. * * @since 13.0 * @since 8.0 (in Equivalences with null-friendly behavior) * @since 4.0 (in Equivalences) */ public static Equivalence<Object> equals() { return Equals.INSTANCE; } /** * Returns an equivalence that uses {@code ==} to compare values and {@link * System#identityHashCode(Object)} to compute the hash code. {@link Equivalence#equivalent} * returns {@code true} if {@code a == b}, including in the case that a and b are both null. * * @since 13.0 * @since 4.0 (in Equivalences) */ public static Equivalence<Object> identity() { return Identity.INSTANCE; } static final class Equals extends Equivalence<Object> implements Serializable { static final Equals INSTANCE = new Equals(); @Override protected boolean doEquivalent(Object a, Object b) { return a.equals(b); } @Override protected int doHash(Object o) { return o.hashCode(); } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } static final class Identity extends Equivalence<Object> implements Serializable { static final Identity INSTANCE = new Identity(); @Override protected boolean doEquivalent(Object a, Object b) { return false; } @Override protected int doHash(Object o) { return System.identityHashCode(o); } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } }
google/guava
guava/src/com/google/common/base/Equivalence.java
394
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import static com.google.common.base.Strings.lenientFormat; import static java.lang.Double.NEGATIVE_INFINITY; import static java.lang.Double.POSITIVE_INFINITY; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Converter; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import java.util.Spliterator; import java.util.Spliterators; import javax.annotation.CheckForNull; /** * Static utility methods pertaining to {@code double} primitives, that are not already found in * either {@link Double} or {@link Arrays}. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Doubles extends DoublesMethodsForWeb { private Doubles() {} /** * The number of bytes required to represent a primitive {@code double} value. * * <p><b>Java 8+ users:</b> use {@link Double#BYTES} instead. * * @since 10.0 */ public static final int BYTES = Double.SIZE / Byte.SIZE; /** * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Double) * value).hashCode()}. * * <p><b>Java 8+ users:</b> use {@link Double#hashCode(double)} instead. * * @param value a primitive {@code double} value * @return a hash code for the value */ public static int hashCode(double value) { return ((Double) value).hashCode(); // TODO(kevinb): do it this way when we can (GWT problem): // long bits = Double.doubleToLongBits(value); // return (int) (bits ^ (bits >>> 32)); } /** * Compares the two specified {@code double} values. The sign of the value returned is the same as * that of <code>((Double) a).{@linkplain Double#compareTo compareTo}(b)</code>. As with that * method, {@code NaN} is treated as greater than all other values, and {@code 0.0 > -0.0}. * * <p><b>Note:</b> this method simply delegates to the JDK method {@link Double#compare}. It is * provided for consistency with the other primitive types, whose compare methods were not added * to the JDK until JDK 7. * * @param a the first {@code double} to compare * @param b the second {@code double} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(double a, double b) { return Double.compare(a, b); } /** * Returns {@code true} if {@code value} represents a real number. This is equivalent to, but not * necessarily implemented as, {@code !(Double.isInfinite(value) || Double.isNaN(value))}. * * <p><b>Java 8+ users:</b> use {@link Double#isFinite(double)} instead. * * @since 10.0 */ public static boolean isFinite(double value) { return NEGATIVE_INFINITY < value && value < POSITIVE_INFINITY; } /** * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. Note * that this always returns {@code false} when {@code target} is {@code NaN}. * * @param array an array of {@code double} values, possibly empty * @param target a primitive {@code double} value * @return {@code true} if {@code array[i] == target} for some value of {@code i} */ public static boolean contains(double[] array, double target) { for (double value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in {@code array}. Note * that this always returns {@code -1} when {@code target} is {@code NaN}. * * @param array an array of {@code double} values, possibly empty * @param target a primitive {@code double} value * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int indexOf(double[] array, double target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf(double[] array, double target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code target} within * {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, * i, i + target.length)} contains exactly the same elements as {@code target}. * * <p>Note that this always returns {@code -1} when {@code target} contains {@code NaN}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(double[] array, double[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in {@code array}. Note * that this always returns {@code -1} when {@code target} is {@code NaN}. * * @param array an array of {@code double} values, possibly empty * @param target a primitive {@code double} value * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int lastIndexOf(double[] array, double target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf(double[] array, double target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}, using the same rules of comparison as {@link * Math#min(double, double)}. * * @param array a <i>nonempty</i> array of {@code double} values * @return the value present in {@code array} that is less than or equal to every other value in * the array * @throws IllegalArgumentException if {@code array} is empty */ @GwtIncompatible( "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static double min(double... array) { checkArgument(array.length > 0); double min = array[0]; for (int i = 1; i < array.length; i++) { min = Math.min(min, array[i]); } return min; } /** * Returns the greatest value present in {@code array}, using the same rules of comparison as * {@link Math#max(double, double)}. * * @param array a <i>nonempty</i> array of {@code double} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array * @throws IllegalArgumentException if {@code array} is empty */ @GwtIncompatible( "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static double max(double... array) { checkArgument(array.length > 0); double max = array[0]; for (int i = 1; i < array.length; i++) { max = Math.max(max, array[i]); } return max; } /** * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. * * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code * value} is greater than {@code max}, {@code max} is returned. * * @param value the {@code double} value to constrain * @param min the lower bound (inclusive) of the range to constrain {@code value} to * @param max the upper bound (inclusive) of the range to constrain {@code value} to * @throws IllegalArgumentException if {@code min > max} * @since 21.0 */ public static double constrainToRange(double value, double min, double max) { // avoid auto-boxing by not using Preconditions.checkArgument(); see Guava issue 3984 // Reject NaN by testing for the good case (min <= max) instead of the bad (min > max). if (min <= max) { return Math.min(Math.max(value, min), max); } throw new IllegalArgumentException( lenientFormat("min (%s) must be less than or equal to max (%s)", min, max)); } /** * Returns the values from each provided array combined into a single array. For example, {@code * concat(new double[] {a, b}, new double[] {}, new double[] {c}} returns the array {@code {a, b, * c}}. * * @param arrays zero or more {@code double} arrays * @return a single array containing all the values from the source arrays, in order */ public static double[] concat(double[]... arrays) { int length = 0; for (double[] array : arrays) { length += array.length; } double[] result = new double[length]; int pos = 0; for (double[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } private static final class DoubleConverter extends Converter<String, Double> implements Serializable { static final Converter<String, Double> INSTANCE = new DoubleConverter(); @Override protected Double doForward(String value) { return Double.valueOf(value); } @Override protected String doBackward(Double value) { return value.toString(); } @Override public String toString() { return "Doubles.stringConverter()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } /** * Returns a serializable converter object that converts between strings and doubles using {@link * Double#valueOf} and {@link Double#toString()}. * * @since 16.0 */ public static Converter<String, Double> stringConverter() { return DoubleConverter.INSTANCE; } /** * Returns an array containing the same values as {@code array}, but guaranteed to be of a * specified minimum length. If {@code array} already has a length of at least {@code minLength}, * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is * returned, containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative * @return an array containing the values of {@code array}, with guaranteed minimum length {@code * minLength} */ public static double[] ensureCapacity(double[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; } /** * Returns a string containing the supplied {@code double} values, converted to strings as * specified by {@link Double#toString(double)}, and separated by {@code separator}. For example, * {@code join("-", 1.0, 2.0, 3.0)} returns the string {@code "1.0-2.0-3.0"}. * * <p>Note that {@link Double#toString(double)} formats {@code double} differently in GWT * sometimes. In the previous example, it returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting string * (but not at the start or end) * @param array an array of {@code double} values, possibly empty */ public static String join(String separator, double... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 12); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code double} arrays <a * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it * compares, using {@link #compare(double, double)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the shorter array as the * lesser. For example, {@code [] < [1.0] < [1.0, 2.0] < [2.0]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with {@link Arrays#equals(double[], * double[])}. * * @since 2.0 */ public static Comparator<double[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<double[]> { INSTANCE; @Override public int compare(double[] left, double[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Double.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } @Override public String toString() { return "Doubles.lexicographicalComparator()"; } } /** * Sorts the elements of {@code array} in descending order. * * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats * all NaN values as equal and 0.0 as greater than -0.0. * * @since 23.1 */ public static void sortDescending(double[] array) { checkNotNull(array); sortDescending(array, 0, array.length); } /** * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} * exclusive in descending order. * * <p>Note that this method uses the total order imposed by {@link Double#compare}, which treats * all NaN values as equal and 0.0 as greater than -0.0. * * @since 23.1 */ public static void sortDescending(double[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); Arrays.sort(array, fromIndex, toIndex); reverse(array, fromIndex, toIndex); } /** * Reverses the elements of {@code array}. This is equivalent to {@code * Collections.reverse(Doubles.asList(array))}, but is likely to be more efficient. * * @since 23.1 */ public static void reverse(double[] array) { checkNotNull(array); reverse(array, 0, array.length); } /** * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} * exclusive. This is equivalent to {@code * Collections.reverse(Doubles.asList(array).subList(fromIndex, toIndex))}, but is likely to be * more efficient. * * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or * {@code toIndex > fromIndex} * @since 23.1 */ public static void reverse(double[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { double tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } /** * Performs a right rotation of {@code array} of "distance" places, so that the first element is * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Bytes.asList(array), * distance)}, but is considerably faster and avoids allocation and garbage collection. * * <p>The provided "distance" may be negative, which will rotate left. * * @since 32.0.0 */ public static void rotate(double[] array, int distance) { rotate(array, distance, 0, array.length); } /** * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code * toIndex} exclusive. This is equivalent to {@code * Collections.rotate(Bytes.asList(array).subList(fromIndex, toIndex), distance)}, but is * considerably faster and avoids allocations and garbage collection. * * <p>The provided "distance" may be negative, which will rotate left. * * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or * {@code toIndex > fromIndex} * @since 32.0.0 */ public static void rotate(double[] array, int distance, int fromIndex, int toIndex) { // See Ints.rotate for more details about possible algorithms here. checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); if (array.length <= 1) { return; } int length = toIndex - fromIndex; // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many // places left to rotate. int m = -distance % length; m = (m < 0) ? m + length : m; // The current index of what will become the first element of the rotated section. int newFirstIndex = m + fromIndex; if (newFirstIndex == fromIndex) { return; } reverse(array, fromIndex, newFirstIndex); reverse(array, newFirstIndex, toIndex); reverse(array, fromIndex, toIndex); } /** * Returns an array containing each value of {@code collection}, converted to a {@code double} * value in the manner of {@link Number#doubleValue}. * * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. * Calling this method is as thread-safe as calling that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the same order, converted * to primitives * @throws NullPointerException if {@code collection} or any of its elements is null * @since 1.0 (parameter was {@code Collection<Double>} before 12.0) */ public static double[] toArray(Collection<? extends Number> collection) { if (collection instanceof DoubleArrayAsList) { return ((DoubleArrayAsList) collection).toDoubleArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; double[] array = new double[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).doubleValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to * set a value to {@code null} will result in a {@link NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of {@code Double} objects * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for * the returned list is unspecified. * * <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN} * is used as a parameter to any of its methods. * * <p>The returned list is serializable. * * <p><b>Note:</b> when possible, you should represent your data as an {@link * ImmutableDoubleArray} instead, which has an {@link ImmutableDoubleArray#asList asList} view. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Double> asList(double... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new DoubleArrayAsList(backingArray); } @GwtCompatible private static class DoubleArrayAsList extends AbstractList<Double> implements RandomAccess, Serializable { final double[] array; final int start; final int end; DoubleArrayAsList(double[] array) { this(array, 0, array.length); } DoubleArrayAsList(double[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Double get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public Spliterator.OfDouble spliterator() { return Spliterators.spliterator(array, start, end, 0); } @Override public boolean contains(@CheckForNull Object target) { // Overridden to prevent a ton of boxing return (target instanceof Double) && Doubles.indexOf(array, (Double) target, start, end) != -1; } @Override public int indexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Double) { int i = Doubles.indexOf(array, (Double) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Double) { int i = Doubles.lastIndexOf(array, (Double) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Double set(int index, Double element) { checkElementIndex(index, size()); double oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Double> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new DoubleArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(@CheckForNull Object object) { if (object == this) { return true; } if (object instanceof DoubleArrayAsList) { DoubleArrayAsList that = (DoubleArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Doubles.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 12); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } double[] toDoubleArray() { return Arrays.copyOfRange(array, start, end); } private static final long serialVersionUID = 0; } /** * This is adapted from the regex suggested by {@link Double#valueOf(String)} for prevalidating * inputs. All valid inputs must pass this regex, but it's semantically fine if not all inputs * that pass this regex are valid -- only a performance hit is incurred, not a semantics bug. */ @GwtIncompatible // regular expressions static final java.util.regex.Pattern FLOATING_POINT_PATTERN = fpPattern(); @GwtIncompatible // regular expressions private static java.util.regex.Pattern fpPattern() { /* * We use # instead of * for possessive quantifiers. This lets us strip them out when building * the regex for RE2 (which doesn't support them) but leave them in when building it for * java.util.regex (where we want them in order to avoid catastrophic backtracking). */ String decimal = "(?:\\d+#(?:\\.\\d*#)?|\\.\\d+#)"; String completeDec = decimal + "(?:[eE][+-]?\\d+#)?[fFdD]?"; String hex = "(?:[0-9a-fA-F]+#(?:\\.[0-9a-fA-F]*#)?|\\.[0-9a-fA-F]+#)"; String completeHex = "0[xX]" + hex + "[pP][+-]?\\d+#[fFdD]?"; String fpPattern = "[+-]?(?:NaN|Infinity|" + completeDec + "|" + completeHex + ")"; fpPattern = fpPattern.replace( "#", "+" ); return java.util.regex.Pattern .compile(fpPattern); } /** * Parses the specified string as a double-precision floating point value. The ASCII character * {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign. * * <p>Unlike {@link Double#parseDouble(String)}, this method returns {@code null} instead of * throwing an exception if parsing fails. Valid inputs are exactly those accepted by {@link * Double#valueOf(String)}, except that leading and trailing whitespace is not permitted. * * <p>This implementation is likely to be faster than {@code Double.parseDouble} if many failures * are expected. * * @param string the string representation of a {@code double} value * @return the floating point value represented by {@code string}, or {@code null} if {@code * string} has a length of zero or cannot be parsed as a {@code double} value * @throws NullPointerException if {@code string} is {@code null} * @since 14.0 */ @GwtIncompatible // regular expressions @CheckForNull public static Double tryParse(String string) { if (FLOATING_POINT_PATTERN.matcher(string).matches()) { // TODO(lowasser): could be potentially optimized, but only with // extensive testing try { return Double.parseDouble(string); } catch (NumberFormatException e) { // Double.parseDouble has changed specs several times, so fall through // gracefully } } return null; } }
google/guava
guava/src/com/google/common/primitives/Doubles.java
395
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Converter; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import java.util.Spliterator; import java.util.Spliterators; import javax.annotation.CheckForNull; /** * Static utility methods pertaining to {@code int} primitives, that are not already found in either * {@link Integer} or {@link Arrays}. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Ints extends IntsMethodsForWeb { private Ints() {} /** * The number of bytes required to represent a primitive {@code int} value. * * <p><b>Java 8+ users:</b> use {@link Integer#BYTES} instead. */ public static final int BYTES = Integer.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as an {@code int}. * * @since 10.0 */ public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Integer) * value).hashCode()}. * * <p><b>Java 8+ users:</b> use {@link Integer#hashCode(int)} instead. * * @param value a primitive {@code int} value * @return a hash code for the value */ public static int hashCode(int value) { return value; } /** * Returns the {@code int} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code int} type * @return the {@code int} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link Integer#MAX_VALUE} or * less than {@link Integer#MIN_VALUE} */ public static int checkedCast(long value) { int result = (int) value; checkArgument(result == value, "Out of range: %s", value); return result; } /** * Returns the {@code int} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code int} if it is in the range of the {@code int} type, * {@link Integer#MAX_VALUE} if it is too large, or {@link Integer#MIN_VALUE} if it is too * small */ public static int saturatedCast(long value) { if (value > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } if (value < Integer.MIN_VALUE) { return Integer.MIN_VALUE; } return (int) value; } /** * Compares the two specified {@code int} values. The sign of the value returned is the same as * that of {@code ((Integer) a).compareTo(b)}. * * <p><b>Java 7+ users:</b> this method should be treated as deprecated; use the equivalent {@link * Integer#compare} method instead. * * @param a the first {@code int} to compare * @param b the second {@code int} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(int a, int b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } /** * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return {@code true} if {@code array[i] == target} for some value of {@code i} */ public static boolean contains(int[] array, int target) { for (int value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int indexOf(int[] array, int target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf(int[] array, int target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code target} within * {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, * i, i + target.length)} contains exactly the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(int[] array, int[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int lastIndexOf(int[] array, int target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf(int[] array, int target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code int} values * @return the value present in {@code array} that is less than or equal to every other value in * the array * @throws IllegalArgumentException if {@code array} is empty */ @GwtIncompatible( "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static int min(int... array) { checkArgument(array.length > 0); int min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code int} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array * @throws IllegalArgumentException if {@code array} is empty */ @GwtIncompatible( "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static int max(int... array) { checkArgument(array.length > 0); int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the value nearest to {@code value} which is within the closed range {@code [min..max]}. * * <p>If {@code value} is within the range {@code [min..max]}, {@code value} is returned * unchanged. If {@code value} is less than {@code min}, {@code min} is returned, and if {@code * value} is greater than {@code max}, {@code max} is returned. * * @param value the {@code int} value to constrain * @param min the lower bound (inclusive) of the range to constrain {@code value} to * @param max the upper bound (inclusive) of the range to constrain {@code value} to * @throws IllegalArgumentException if {@code min > max} * @since 21.0 */ public static int constrainToRange(int value, int min, int max) { checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max); return Math.min(Math.max(value, min), max); } /** * Returns the values from each provided array combined into a single array. For example, {@code * concat(new int[] {a, b}, new int[] {}, new int[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code int} arrays * @return a single array containing all the values from the source arrays, in order */ public static int[] concat(int[]... arrays) { int length = 0; for (int[] array : arrays) { length += array.length; } int[] result = new int[length]; int pos = 0; for (int[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in a 4-element byte array; equivalent to * {@code ByteBuffer.allocate(4).putInt(value).array()}. For example, the input value {@code * 0x12131415} would yield the byte array {@code {0x12, 0x13, 0x14, 0x15}}. * * <p>If you need to convert and concatenate several values (possibly even of different types), * use a shared {@link java.nio.ByteBuffer} instance, or use {@link * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. */ public static byte[] toByteArray(int value) { return new byte[] { (byte) (value >> 24), (byte) (value >> 16), (byte) (value >> 8), (byte) value }; } /** * Returns the {@code int} value whose big-endian representation is stored in the first 4 bytes of * {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getInt()}. For example, the input * byte array {@code {0x12, 0x13, 0x14, 0x15, 0x33}} would yield the {@code int} value {@code * 0x12131415}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more * flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 4 elements */ public static int fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1], bytes[2], bytes[3]); } /** * Returns the {@code int} value whose byte representation is the given 4 bytes, in big-endian * order; equivalent to {@code Ints.fromByteArray(new byte[] {b1, b2, b3, b4})}. * * @since 7.0 */ public static int fromBytes(byte b1, byte b2, byte b3, byte b4) { return b1 << 24 | (b2 & 0xFF) << 16 | (b3 & 0xFF) << 8 | (b4 & 0xFF); } private static final class IntConverter extends Converter<String, Integer> implements Serializable { static final Converter<String, Integer> INSTANCE = new IntConverter(); @Override protected Integer doForward(String value) { return Integer.decode(value); } @Override protected String doBackward(Integer value) { return value.toString(); } @Override public String toString() { return "Ints.stringConverter()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } /** * Returns a serializable converter object that converts between strings and integers using {@link * Integer#decode} and {@link Integer#toString()}. The returned converter throws {@link * NumberFormatException} if the input string is invalid. * * <p><b>Warning:</b> please see {@link Integer#decode} to understand exactly how strings are * parsed. For example, the string {@code "0123"} is treated as <i>octal</i> and converted to the * value {@code 83}. * * @since 16.0 */ public static Converter<String, Integer> stringConverter() { return IntConverter.INSTANCE; } /** * Returns an array containing the same values as {@code array}, but guaranteed to be of a * specified minimum length. If {@code array} already has a length of at least {@code minLength}, * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is * returned, containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative * @return an array containing the values of {@code array}, with guaranteed minimum length {@code * minLength} */ public static int[] ensureCapacity(int[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; } /** * Returns a string containing the supplied {@code int} values separated by {@code separator}. For * example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting string * (but not at the start or end) * @param array an array of {@code int} values, possibly empty */ public static String join(String separator, int... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code int} arrays <a * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it * compares, using {@link #compare(int, int)}), the first pair of values that follow any common * prefix, or when one array is a prefix of the other, treats the shorter array as the lesser. For * example, {@code [] < [1] < [1, 2] < [2]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with {@link Arrays#equals(int[], int[])}. * * @since 2.0 */ public static Comparator<int[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<int[]> { INSTANCE; @Override public int compare(int[] left, int[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Ints.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } @Override public String toString() { return "Ints.lexicographicalComparator()"; } } /** * Sorts the elements of {@code array} in descending order. * * @since 23.1 */ public static void sortDescending(int[] array) { checkNotNull(array); sortDescending(array, 0, array.length); } /** * Sorts the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} * exclusive in descending order. * * @since 23.1 */ public static void sortDescending(int[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); Arrays.sort(array, fromIndex, toIndex); reverse(array, fromIndex, toIndex); } /** * Reverses the elements of {@code array}. This is equivalent to {@code * Collections.reverse(Ints.asList(array))}, but is likely to be more efficient. * * @since 23.1 */ public static void reverse(int[] array) { checkNotNull(array); reverse(array, 0, array.length); } /** * Reverses the elements of {@code array} between {@code fromIndex} inclusive and {@code toIndex} * exclusive. This is equivalent to {@code * Collections.reverse(Ints.asList(array).subList(fromIndex, toIndex))}, but is likely to be more * efficient. * * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or * {@code toIndex > fromIndex} * @since 23.1 */ public static void reverse(int[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { int tmp = array[i]; array[i] = array[j]; array[j] = tmp; } } /** * Performs a right rotation of {@code array} of "distance" places, so that the first element is * moved to index "distance", and the element at index {@code i} ends up at index {@code (distance * + i) mod array.length}. This is equivalent to {@code Collections.rotate(Ints.asList(array), * distance)}, but is considerably faster and avoids allocation and garbage collection. * * <p>The provided "distance" may be negative, which will rotate left. * * @since 32.0.0 */ public static void rotate(int[] array, int distance) { rotate(array, distance, 0, array.length); } /** * Performs a right rotation of {@code array} between {@code fromIndex} inclusive and {@code * toIndex} exclusive. This is equivalent to {@code * Collections.rotate(Ints.asList(array).subList(fromIndex, toIndex), distance)}, but is * considerably faster and avoids allocations and garbage collection. * * <p>The provided "distance" may be negative, which will rotate left. * * @throws IndexOutOfBoundsException if {@code fromIndex < 0}, {@code toIndex > array.length}, or * {@code toIndex > fromIndex} * @since 32.0.0 */ public static void rotate(int[] array, int distance, int fromIndex, int toIndex) { // There are several well-known algorithms for rotating part of an array (or, equivalently, // exchanging two blocks of memory). This classic text by Gries and Mills mentions several: // https://ecommons.cornell.edu/bitstream/handle/1813/6292/81-452.pdf. // (1) "Reversal", the one we have here. // (2) "Dolphin". If we're rotating an array a of size n by a distance of d, then element a[0] // ends up at a[d], which in turn ends up at a[2d], and so on until we get back to a[0]. // (All indices taken mod n.) If d and n are mutually prime, all elements will have been // moved at that point. Otherwise, we can rotate the cycle a[1], a[1 + d], a[1 + 2d], etc, // then a[2] etc, and so on until we have rotated all elements. There are gcd(d, n) cycles // in all. // (3) "Successive". We can consider that we are exchanging a block of size d (a[0..d-1]) with a // block of size n-d (a[d..n-1]), where in general these blocks have different sizes. If we // imagine a line separating the first block from the second, we can proceed by exchanging // the smaller of these blocks with the far end of the other one. That leaves us with a // smaller version of the same problem. // Say we are rotating abcdefgh by 5. We start with abcde|fgh. The smaller block is [fgh]: // [abc]de|[fgh] -> [fgh]de|[abc]. Now [fgh] is in the right place, but we need to swap [de] // with [abc]: fgh[de]|a[bc] -> fgh[bc]|a[de]. Now we need to swap [a] with [bc]: // fgh[b]c|[a]de -> fgh[a]c|[b]de. Finally we need to swap [c] with [b]: // fgha[c]|[b]de -> fgha[b]|[c]de. Because these two blocks are the same size, we are done. // The Dolphin algorithm is attractive because it does the fewest array reads and writes: each // array slot is read and written exactly once. However, it can have very poor memory locality: // benchmarking shows it can take 7 times longer than the other two in some cases. The other two // do n swaps, minus a delta (0 or 2 for Reversal, gcd(d, n) for Successive), so that's about // twice as many reads and writes. But benchmarking shows that they usually perform better than // Dolphin. Reversal is about as good as Successive on average, and it is much simpler, // especially since we already have a `reverse` method. checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); if (array.length <= 1) { return; } int length = toIndex - fromIndex; // Obtain m = (-distance mod length), a non-negative value less than "length". This is how many // places left to rotate. int m = -distance % length; m = (m < 0) ? m + length : m; // The current index of what will become the first element of the rotated section. int newFirstIndex = m + fromIndex; if (newFirstIndex == fromIndex) { return; } reverse(array, fromIndex, newFirstIndex); reverse(array, newFirstIndex, toIndex); reverse(array, fromIndex, toIndex); } /** * Returns an array containing each value of {@code collection}, converted to a {@code int} value * in the manner of {@link Number#intValue}. * * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. * Calling this method is as thread-safe as calling that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the same order, converted * to primitives * @throws NullPointerException if {@code collection} or any of its elements is null * @since 1.0 (parameter was {@code Collection<Integer>} before 12.0) */ public static int[] toArray(Collection<? extends Number> collection) { if (collection instanceof IntArrayAsList) { return ((IntArrayAsList) collection).toIntArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; int[] array = new int[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).intValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to * set a value to {@code null} will result in a {@link NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of {@code Integer} objects * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for * the returned list is unspecified. * * <p>The returned list is serializable. * * <p><b>Note:</b> when possible, you should represent your data as an {@link ImmutableIntArray} * instead, which has an {@link ImmutableIntArray#asList asList} view. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Integer> asList(int... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new IntArrayAsList(backingArray); } @GwtCompatible private static class IntArrayAsList extends AbstractList<Integer> implements RandomAccess, Serializable { final int[] array; final int start; final int end; IntArrayAsList(int[] array) { this(array, 0, array.length); } IntArrayAsList(int[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Integer get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public Spliterator.OfInt spliterator() { return Spliterators.spliterator(array, start, end, 0); } @Override public boolean contains(@CheckForNull Object target) { // Overridden to prevent a ton of boxing return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1; } @Override public int indexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Integer) { int i = Ints.indexOf(array, (Integer) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Integer) { int i = Ints.lastIndexOf(array, (Integer) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Integer set(int index, Integer element) { checkElementIndex(index, size()); int oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Integer> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new IntArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(@CheckForNull Object object) { if (object == this) { return true; } if (object instanceof IntArrayAsList) { IntArrayAsList that = (IntArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Ints.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 5); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } int[] toIntArray() { return Arrays.copyOfRange(array, start, end); } private static final long serialVersionUID = 0; } /** * Parses the specified string as a signed decimal integer value. The ASCII character {@code '-'} * (<code>'&#92;u002D'</code>) is recognized as the minus sign. * * <p>Unlike {@link Integer#parseInt(String)}, this method returns {@code null} instead of * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, * and returns {@code null} if non-ASCII digits are present in the string. * * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite * the change to {@link Integer#parseInt(String)} for that version. * * @param string the string representation of an integer value * @return the integer value represented by {@code string}, or {@code null} if {@code string} has * a length of zero or cannot be parsed as an integer value * @throws NullPointerException if {@code string} is {@code null} * @since 11.0 */ @CheckForNull public static Integer tryParse(String string) { return tryParse(string, 10); } /** * Parses the specified string as a signed integer value using the specified radix. The ASCII * character {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign. * * <p>Unlike {@link Integer#parseInt(String, int)}, this method returns {@code null} instead of * throwing an exception if parsing fails. Additionally, this method only accepts ASCII digits, * and returns {@code null} if non-ASCII digits are present in the string. * * <p>Note that strings prefixed with ASCII {@code '+'} are rejected, even under JDK 7, despite * the change to {@link Integer#parseInt(String, int)} for that version. * * @param string the string representation of an integer value * @param radix the radix to use when parsing * @return the integer value represented by {@code string} using {@code radix}, or {@code null} if * {@code string} has a length of zero or cannot be parsed as an integer value * @throws IllegalArgumentException if {@code radix < Character.MIN_RADIX} or {@code radix > * Character.MAX_RADIX} * @throws NullPointerException if {@code string} is {@code null} * @since 19.0 */ @CheckForNull public static Integer tryParse(String string, int radix) { Long result = Longs.tryParse(string, radix); if (result == null || result.longValue() != result.intValue()) { return null; } else { return result.intValue(); } } }
google/guava
guava/src/com/google/common/primitives/Ints.java
396
/* * 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 static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.primitives.Booleans; import java.io.Serializable; import java.util.NoSuchElementException; import javax.annotation.CheckForNull; /** * Implementation detail for the internal structure of {@link Range} instances. Represents a unique * way of "cutting" a "number line" (actually of instances of type {@code C}, not necessarily * "numbers") into two sections; this can be done below a certain value, above a certain value, * below all values or above all values. With this object defined in this way, an interval can * always be represented by a pair of {@code Cut} instances. * * @author Kevin Bourrillion */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 @GwtCompatible @ElementTypesAreNonnullByDefault abstract class Cut<C extends Comparable> implements Comparable<Cut<C>>, Serializable { final C endpoint; Cut(C endpoint) { this.endpoint = endpoint; } abstract boolean isLessThan(C value); abstract BoundType typeAsLowerBound(); abstract BoundType typeAsUpperBound(); abstract Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain); abstract Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain); abstract void describeAsLowerBound(StringBuilder sb); abstract void describeAsUpperBound(StringBuilder sb); @CheckForNull abstract C leastValueAbove(DiscreteDomain<C> domain); @CheckForNull abstract C greatestValueBelow(DiscreteDomain<C> domain); /* * The canonical form is a BelowValue cut whenever possible, otherwise ABOVE_ALL, or * (only in the case of types that are unbounded below) BELOW_ALL. */ Cut<C> canonical(DiscreteDomain<C> domain) { return this; } // note: overridden by {BELOW,ABOVE}_ALL @Override public int compareTo(Cut<C> that) { if (that == belowAll()) { return 1; } if (that == aboveAll()) { return -1; } int result = Range.compareOrThrow(endpoint, that.endpoint); if (result != 0) { return result; } // same value. below comes before above return Booleans.compare(this instanceof AboveValue, that instanceof AboveValue); } C endpoint() { return endpoint; } @SuppressWarnings("unchecked") // catching CCE @Override public boolean equals(@CheckForNull Object obj) { if (obj instanceof Cut) { // It might not really be a Cut<C>, but we'll catch a CCE if it's not Cut<C> that = (Cut<C>) obj; try { int compareResult = compareTo(that); return compareResult == 0; } catch (ClassCastException wastNotComparableToOurType) { return false; } } return false; } // Prevent "missing hashCode" warning by explicitly forcing subclasses implement it @Override public abstract int hashCode(); /* * The implementation neither produces nor consumes any non-null instance of type C, so * casting the type parameter is safe. */ @SuppressWarnings("unchecked") static <C extends Comparable> Cut<C> belowAll() { return (Cut<C>) BelowAll.INSTANCE; } private static final long serialVersionUID = 0; private static final class BelowAll extends Cut<Comparable<?>> { private static final BelowAll INSTANCE = new BelowAll(); private BelowAll() { /* * No code ever sees this bogus value for `endpoint`: This class overrides both methods that * use the `endpoint` field, compareTo() and endpoint(). Additionally, the main implementation * of Cut.compareTo checks for belowAll before reading accessing `endpoint` on another Cut * instance. */ super(""); } @Override Comparable<?> endpoint() { throw new IllegalStateException("range unbounded on this side"); } @Override boolean isLessThan(Comparable<?> value) { return true; } @Override BoundType typeAsLowerBound() { throw new IllegalStateException(); } @Override BoundType typeAsUpperBound() { throw new AssertionError("this statement should be unreachable"); } @Override Cut<Comparable<?>> withLowerBoundType( BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new IllegalStateException(); } @Override Cut<Comparable<?>> withUpperBoundType( BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new AssertionError("this statement should be unreachable"); } @Override void describeAsLowerBound(StringBuilder sb) { sb.append("(-\u221e"); } @Override void describeAsUpperBound(StringBuilder sb) { throw new AssertionError(); } @Override Comparable<?> leastValueAbove(DiscreteDomain<Comparable<?>> domain) { return domain.minValue(); } @Override Comparable<?> greatestValueBelow(DiscreteDomain<Comparable<?>> domain) { throw new AssertionError(); } @Override Cut<Comparable<?>> canonical(DiscreteDomain<Comparable<?>> domain) { try { return Cut.<Comparable<?>>belowValue(domain.minValue()); } catch (NoSuchElementException e) { return this; } } @Override public int compareTo(Cut<Comparable<?>> o) { return (o == this) ? 0 : -1; } @Override public int hashCode() { return System.identityHashCode(this); } @Override public String toString() { return "-\u221e"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 0; } /* * The implementation neither produces nor consumes any non-null instance of * type C, so casting the type parameter is safe. */ @SuppressWarnings("unchecked") static <C extends Comparable> Cut<C> aboveAll() { return (Cut<C>) AboveAll.INSTANCE; } private static final class AboveAll extends Cut<Comparable<?>> { private static final AboveAll INSTANCE = new AboveAll(); private AboveAll() { // For discussion of "", see BelowAll. super(""); } @Override Comparable<?> endpoint() { throw new IllegalStateException("range unbounded on this side"); } @Override boolean isLessThan(Comparable<?> value) { return false; } @Override BoundType typeAsLowerBound() { throw new AssertionError("this statement should be unreachable"); } @Override BoundType typeAsUpperBound() { throw new IllegalStateException(); } @Override Cut<Comparable<?>> withLowerBoundType( BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new AssertionError("this statement should be unreachable"); } @Override Cut<Comparable<?>> withUpperBoundType( BoundType boundType, DiscreteDomain<Comparable<?>> domain) { throw new IllegalStateException(); } @Override void describeAsLowerBound(StringBuilder sb) { throw new AssertionError(); } @Override void describeAsUpperBound(StringBuilder sb) { sb.append("+\u221e)"); } @Override Comparable<?> leastValueAbove(DiscreteDomain<Comparable<?>> domain) { throw new AssertionError(); } @Override Comparable<?> greatestValueBelow(DiscreteDomain<Comparable<?>> domain) { return domain.maxValue(); } @Override public int compareTo(Cut<Comparable<?>> o) { return (o == this) ? 0 : 1; } @Override public int hashCode() { return System.identityHashCode(this); } @Override public String toString() { return "+\u221e"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 0; } static <C extends Comparable> Cut<C> belowValue(C endpoint) { return new BelowValue<>(endpoint); } private static final class BelowValue<C extends Comparable> extends Cut<C> { BelowValue(C endpoint) { super(checkNotNull(endpoint)); } @Override boolean isLessThan(C value) { return Range.compareOrThrow(endpoint, value) <= 0; } @Override BoundType typeAsLowerBound() { return BoundType.CLOSED; } @Override BoundType typeAsUpperBound() { return BoundType.OPEN; } @Override Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain) { switch (boundType) { case CLOSED: return this; case OPEN: C previous = domain.previous(endpoint); return (previous == null) ? Cut.<C>belowAll() : new AboveValue<C>(previous); default: throw new AssertionError(); } } @Override Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain) { switch (boundType) { case CLOSED: C previous = domain.previous(endpoint); return (previous == null) ? Cut.<C>aboveAll() : new AboveValue<C>(previous); case OPEN: return this; default: throw new AssertionError(); } } @Override void describeAsLowerBound(StringBuilder sb) { sb.append('[').append(endpoint); } @Override void describeAsUpperBound(StringBuilder sb) { sb.append(endpoint).append(')'); } @Override C leastValueAbove(DiscreteDomain<C> domain) { return endpoint; } @Override @CheckForNull C greatestValueBelow(DiscreteDomain<C> domain) { return domain.previous(endpoint); } @Override public int hashCode() { return endpoint.hashCode(); } @Override public String toString() { return "\\" + endpoint + "/"; } private static final long serialVersionUID = 0; } static <C extends Comparable> Cut<C> aboveValue(C endpoint) { return new AboveValue<>(endpoint); } private static final class AboveValue<C extends Comparable> extends Cut<C> { AboveValue(C endpoint) { super(checkNotNull(endpoint)); } @Override boolean isLessThan(C value) { return Range.compareOrThrow(endpoint, value) < 0; } @Override BoundType typeAsLowerBound() { return BoundType.OPEN; } @Override BoundType typeAsUpperBound() { return BoundType.CLOSED; } @Override Cut<C> withLowerBoundType(BoundType boundType, DiscreteDomain<C> domain) { switch (boundType) { case OPEN: return this; case CLOSED: C next = domain.next(endpoint); return (next == null) ? Cut.<C>belowAll() : belowValue(next); default: throw new AssertionError(); } } @Override Cut<C> withUpperBoundType(BoundType boundType, DiscreteDomain<C> domain) { switch (boundType) { case OPEN: C next = domain.next(endpoint); return (next == null) ? Cut.<C>aboveAll() : belowValue(next); case CLOSED: return this; default: throw new AssertionError(); } } @Override void describeAsLowerBound(StringBuilder sb) { sb.append('(').append(endpoint); } @Override void describeAsUpperBound(StringBuilder sb) { sb.append(endpoint).append(']'); } @Override @CheckForNull C leastValueAbove(DiscreteDomain<C> domain) { return domain.next(endpoint); } @Override C greatestValueBelow(DiscreteDomain<C> domain) { return endpoint; } @Override Cut<C> canonical(DiscreteDomain<C> domain) { C next = leastValueAbove(domain); return (next != null) ? belowValue(next) : Cut.<C>aboveAll(); } @Override public int hashCode() { return ~endpoint.hashCode(); } @Override public String toString() { return "/" + endpoint + "\\"; } private static final long serialVersionUID = 0; } }
google/guava
guava/src/com/google/common/collect/Cut.java
397
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.mediator; /** * Wizard party member. */ public class Wizard extends PartyMemberBase { @Override public String toString() { return "Wizard"; } }
smedals/java-design-patterns
mediator/src/main/java/com/iluwatar/mediator/Wizard.java
398
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factorykit; /** * Class representing Bows. */ public class Bow implements Weapon { @Override public String toString() { return "Bow"; } }
smedals/java-design-patterns
factory-kit/src/main/java/com/iluwatar/factorykit/Bow.java
399
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.factorykit; /** * Interface representing weapon. */ public interface Weapon { }
smedals/java-design-patterns
factory-kit/src/main/java/com/iluwatar/factorykit/Weapon.java
400
/* * 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 static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import static com.google.common.collect.CollectPreconditions.checkRemove; import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.base.Supplier; import com.google.common.collect.Maps.EntryTransformer; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.j2objc.annotations.Weak; import com.google.j2objc.annotations.WeakOuter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.AbstractCollection; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.NavigableSet; import java.util.NoSuchElementException; import java.util.Set; import java.util.SortedSet; import java.util.Spliterator; import java.util.function.BiConsumer; import java.util.function.Consumer; import java.util.stream.Collector; import java.util.stream.Stream; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Provides static methods acting on or generating a {@code Multimap}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#multimaps">{@code * Multimaps}</a>. * * @author Jared Levy * @author Robert Konigsberg * @author Mike Bostock * @author Louis Wasserman * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Multimaps { private Multimaps() {} /** * Returns a {@code Collector} accumulating entries into a {@code Multimap} generated from the * specified supplier. The keys and values of the entries are the result of applying the provided * mapping functions to the input elements, accumulated in the encounter order of the stream. * * <p>Example: * * <pre>{@code * static final ListMultimap<Character, String> FIRST_LETTER_MULTIMAP = * Stream.of("banana", "apple", "carrot", "asparagus", "cherry") * .collect( * toMultimap( * str -> str.charAt(0), * str -> str.substring(1), * MultimapBuilder.treeKeys().arrayListValues()::build)); * * // is equivalent to * * static final ListMultimap<Character, String> FIRST_LETTER_MULTIMAP; * * static { * FIRST_LETTER_MULTIMAP = MultimapBuilder.treeKeys().arrayListValues().build(); * FIRST_LETTER_MULTIMAP.put('b', "anana"); * FIRST_LETTER_MULTIMAP.put('a', "pple"); * FIRST_LETTER_MULTIMAP.put('a', "sparagus"); * FIRST_LETTER_MULTIMAP.put('c', "arrot"); * FIRST_LETTER_MULTIMAP.put('c', "herry"); * } * }</pre> * * <p>To collect to an {@link ImmutableMultimap}, use either {@link * ImmutableSetMultimap#toImmutableSetMultimap} or {@link * ImmutableListMultimap#toImmutableListMultimap}. * * @since 21.0 */ public static < T extends @Nullable Object, K extends @Nullable Object, V extends @Nullable Object, M extends Multimap<K, V>> Collector<T, ?, M> toMultimap( java.util.function.Function<? super T, ? extends K> keyFunction, java.util.function.Function<? super T, ? extends V> valueFunction, java.util.function.Supplier<M> multimapSupplier) { return CollectCollectors.<T, K, V, M>toMultimap(keyFunction, valueFunction, multimapSupplier); } /** * Returns a {@code Collector} accumulating entries into a {@code Multimap} generated from the * specified supplier. Each input element is mapped to a key and a stream of values, each of which * are put into the resulting {@code Multimap}, in the encounter order of the stream and the * encounter order of the streams of values. * * <p>Example: * * <pre>{@code * static final ListMultimap<Character, Character> FIRST_LETTER_MULTIMAP = * Stream.of("banana", "apple", "carrot", "asparagus", "cherry") * .collect( * flatteningToMultimap( * str -> str.charAt(0), * str -> str.substring(1).chars().mapToObj(c -> (char) c), * MultimapBuilder.linkedHashKeys().arrayListValues()::build)); * * // is equivalent to * * static final ListMultimap<Character, Character> FIRST_LETTER_MULTIMAP; * * static { * FIRST_LETTER_MULTIMAP = MultimapBuilder.linkedHashKeys().arrayListValues().build(); * FIRST_LETTER_MULTIMAP.putAll('b', Arrays.asList('a', 'n', 'a', 'n', 'a')); * FIRST_LETTER_MULTIMAP.putAll('a', Arrays.asList('p', 'p', 'l', 'e')); * FIRST_LETTER_MULTIMAP.putAll('c', Arrays.asList('a', 'r', 'r', 'o', 't')); * FIRST_LETTER_MULTIMAP.putAll('a', Arrays.asList('s', 'p', 'a', 'r', 'a', 'g', 'u', 's')); * FIRST_LETTER_MULTIMAP.putAll('c', Arrays.asList('h', 'e', 'r', 'r', 'y')); * } * }</pre> * * @since 21.0 */ public static < T extends @Nullable Object, K extends @Nullable Object, V extends @Nullable Object, M extends Multimap<K, V>> Collector<T, ?, M> flatteningToMultimap( java.util.function.Function<? super T, ? extends K> keyFunction, java.util.function.Function<? super T, ? extends Stream<? extends V>> valueFunction, java.util.function.Supplier<M> multimapSupplier) { return CollectCollectors.<T, K, V, M>flatteningToMultimap( keyFunction, valueFunction, multimapSupplier); } /** * Creates a new {@code Multimap} backed by {@code map}, whose internal value collections are * generated by {@code factory}. * * <p><b>Warning: do not use</b> this method when the collections returned by {@code factory} * implement either {@link List} or {@code Set}! Use the more specific method {@link * #newListMultimap}, {@link #newSetMultimap} or {@link #newSortedSetMultimap} instead, to avoid * very surprising behavior from {@link Multimap#equals}. * * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code * toString} methods for the multimap and its returned views. However, the multimap's {@code get} * method returns instances of a different class than {@code factory.get()} does. * * <p>The multimap is serializable if {@code map}, {@code factory}, the collections generated by * {@code factory}, and the multimap contents are all serializable. * * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link * #synchronizedMultimap}. * * <p>Call this method only when the simpler methods {@link ArrayListMultimap#create()}, {@link * HashMultimap#create()}, {@link LinkedHashMultimap#create()}, {@link * LinkedListMultimap#create()}, {@link TreeMultimap#create()}, and {@link * TreeMultimap#create(Comparator, Comparator)} won't suffice. * * <p>Note: the multimap assumes complete ownership over of {@code map} and the collections * returned by {@code factory}. Those objects should not be manually updated and they should not * use soft, weak, or phantom references. * * @param map place to store the mapping from each key to its corresponding values * @param factory supplier of new, empty collections that will each hold all values for a given * key * @throws IllegalArgumentException if {@code map} is not empty */ public static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> newMultimap( Map<K, Collection<V>> map, final Supplier<? extends Collection<V>> factory) { return new CustomMultimap<>(map, factory); } private static class CustomMultimap<K extends @Nullable Object, V extends @Nullable Object> extends AbstractMapBasedMultimap<K, V> { transient Supplier<? extends Collection<V>> factory; CustomMultimap(Map<K, Collection<V>> map, Supplier<? extends Collection<V>> factory) { super(map); this.factory = checkNotNull(factory); } @Override Set<K> createKeySet() { return createMaybeNavigableKeySet(); } @Override Map<K, Collection<V>> createAsMap() { return createMaybeNavigableAsMap(); } @Override protected Collection<V> createCollection() { return factory.get(); } @Override <E extends @Nullable Object> Collection<E> unmodifiableCollectionSubclass( Collection<E> collection) { if (collection instanceof NavigableSet) { return Sets.unmodifiableNavigableSet((NavigableSet<E>) collection); } else if (collection instanceof SortedSet) { return Collections.unmodifiableSortedSet((SortedSet<E>) collection); } else if (collection instanceof Set) { return Collections.unmodifiableSet((Set<E>) collection); } else if (collection instanceof List) { return Collections.unmodifiableList((List<E>) collection); } else { return Collections.unmodifiableCollection(collection); } } @Override Collection<V> wrapCollection(@ParametricNullness K key, Collection<V> collection) { if (collection instanceof List) { return wrapList(key, (List<V>) collection, null); } else if (collection instanceof NavigableSet) { return new WrappedNavigableSet(key, (NavigableSet<V>) collection, null); } else if (collection instanceof SortedSet) { return new WrappedSortedSet(key, (SortedSet<V>) collection, null); } else if (collection instanceof Set) { return new WrappedSet(key, (Set<V>) collection); } else { return new WrappedCollection(key, collection, null); } } // can't use Serialization writeMultimap and populateMultimap methods since // there's no way to generate the empty backing map. /** * @serialData the factory and the backing map */ @GwtIncompatible // java.io.ObjectOutputStream @J2ktIncompatible private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(factory); stream.writeObject(backingMap()); } @GwtIncompatible // java.io.ObjectInputStream @J2ktIncompatible @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); factory = (Supplier<? extends Collection<V>>) requireNonNull(stream.readObject()); Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject()); setMap(map); } @GwtIncompatible // java serialization not supported @J2ktIncompatible private static final long serialVersionUID = 0; } /** * Creates a new {@code ListMultimap} that uses the provided map and factory. It can generate a * multimap based on arbitrary {@link Map} and {@link List} classes. * * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code * toString} methods for the multimap and its returned views. The multimap's {@code get}, {@code * removeAll}, and {@code replaceValues} methods return {@code RandomAccess} lists if the factory * does. However, the multimap's {@code get} method returns instances of a different class than * does {@code factory.get()}. * * <p>The multimap is serializable if {@code map}, {@code factory}, the lists generated by {@code * factory}, and the multimap contents are all serializable. * * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link * #synchronizedListMultimap}. * * <p>Call this method only when the simpler methods {@link ArrayListMultimap#create()} and {@link * LinkedListMultimap#create()} won't suffice. * * <p>Note: the multimap assumes complete ownership over of {@code map} and the lists returned by * {@code factory}. Those objects should not be manually updated, they should be empty when * provided, and they should not use soft, weak, or phantom references. * * @param map place to store the mapping from each key to its corresponding values * @param factory supplier of new, empty lists that will each hold all values for a given key * @throws IllegalArgumentException if {@code map} is not empty */ public static <K extends @Nullable Object, V extends @Nullable Object> ListMultimap<K, V> newListMultimap( Map<K, Collection<V>> map, final Supplier<? extends List<V>> factory) { return new CustomListMultimap<>(map, factory); } private static class CustomListMultimap<K extends @Nullable Object, V extends @Nullable Object> extends AbstractListMultimap<K, V> { transient Supplier<? extends List<V>> factory; CustomListMultimap(Map<K, Collection<V>> map, Supplier<? extends List<V>> factory) { super(map); this.factory = checkNotNull(factory); } @Override Set<K> createKeySet() { return createMaybeNavigableKeySet(); } @Override Map<K, Collection<V>> createAsMap() { return createMaybeNavigableAsMap(); } @Override protected List<V> createCollection() { return factory.get(); } /** * @serialData the factory and the backing map */ @GwtIncompatible // java.io.ObjectOutputStream @J2ktIncompatible private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(factory); stream.writeObject(backingMap()); } @GwtIncompatible // java.io.ObjectInputStream @J2ktIncompatible @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); factory = (Supplier<? extends List<V>>) requireNonNull(stream.readObject()); Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject()); setMap(map); } @GwtIncompatible // java serialization not supported @J2ktIncompatible private static final long serialVersionUID = 0; } /** * Creates a new {@code SetMultimap} that uses the provided map and factory. It can generate a * multimap based on arbitrary {@link Map} and {@link Set} classes. * * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code * toString} methods for the multimap and its returned views. However, the multimap's {@code get} * method returns instances of a different class than {@code factory.get()} does. * * <p>The multimap is serializable if {@code map}, {@code factory}, the sets generated by {@code * factory}, and the multimap contents are all serializable. * * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link * #synchronizedSetMultimap}. * * <p>Call this method only when the simpler methods {@link HashMultimap#create()}, {@link * LinkedHashMultimap#create()}, {@link TreeMultimap#create()}, and {@link * TreeMultimap#create(Comparator, Comparator)} won't suffice. * * <p>Note: the multimap assumes complete ownership over of {@code map} and the sets returned by * {@code factory}. Those objects should not be manually updated and they should not use soft, * weak, or phantom references. * * @param map place to store the mapping from each key to its corresponding values * @param factory supplier of new, empty sets that will each hold all values for a given key * @throws IllegalArgumentException if {@code map} is not empty */ public static <K extends @Nullable Object, V extends @Nullable Object> SetMultimap<K, V> newSetMultimap( Map<K, Collection<V>> map, final Supplier<? extends Set<V>> factory) { return new CustomSetMultimap<>(map, factory); } private static class CustomSetMultimap<K extends @Nullable Object, V extends @Nullable Object> extends AbstractSetMultimap<K, V> { transient Supplier<? extends Set<V>> factory; CustomSetMultimap(Map<K, Collection<V>> map, Supplier<? extends Set<V>> factory) { super(map); this.factory = checkNotNull(factory); } @Override Set<K> createKeySet() { return createMaybeNavigableKeySet(); } @Override Map<K, Collection<V>> createAsMap() { return createMaybeNavigableAsMap(); } @Override protected Set<V> createCollection() { return factory.get(); } @Override <E extends @Nullable Object> Collection<E> unmodifiableCollectionSubclass( Collection<E> collection) { if (collection instanceof NavigableSet) { return Sets.unmodifiableNavigableSet((NavigableSet<E>) collection); } else if (collection instanceof SortedSet) { return Collections.unmodifiableSortedSet((SortedSet<E>) collection); } else { return Collections.unmodifiableSet((Set<E>) collection); } } @Override Collection<V> wrapCollection(@ParametricNullness K key, Collection<V> collection) { if (collection instanceof NavigableSet) { return new WrappedNavigableSet(key, (NavigableSet<V>) collection, null); } else if (collection instanceof SortedSet) { return new WrappedSortedSet(key, (SortedSet<V>) collection, null); } else { return new WrappedSet(key, (Set<V>) collection); } } /** * @serialData the factory and the backing map */ @GwtIncompatible // java.io.ObjectOutputStream @J2ktIncompatible private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(factory); stream.writeObject(backingMap()); } @GwtIncompatible // java.io.ObjectInputStream @J2ktIncompatible @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); factory = (Supplier<? extends Set<V>>) requireNonNull(stream.readObject()); Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject()); setMap(map); } @GwtIncompatible // not needed in emulated source @J2ktIncompatible private static final long serialVersionUID = 0; } /** * Creates a new {@code SortedSetMultimap} that uses the provided map and factory. It can generate * a multimap based on arbitrary {@link Map} and {@link SortedSet} classes. * * <p>The {@code factory}-generated and {@code map} classes determine the multimap iteration * order. They also specify the behavior of the {@code equals}, {@code hashCode}, and {@code * toString} methods for the multimap and its returned views. However, the multimap's {@code get} * method returns instances of a different class than {@code factory.get()} does. * * <p>The multimap is serializable if {@code map}, {@code factory}, the sets generated by {@code * factory}, and the multimap contents are all serializable. * * <p>The multimap is not threadsafe when any concurrent operations update the multimap, even if * {@code map} and the instances generated by {@code factory} are. Concurrent read operations will * work correctly. To allow concurrent update operations, wrap the multimap with a call to {@link * #synchronizedSortedSetMultimap}. * * <p>Call this method only when the simpler methods {@link TreeMultimap#create()} and {@link * TreeMultimap#create(Comparator, Comparator)} won't suffice. * * <p>Note: the multimap assumes complete ownership over of {@code map} and the sets returned by * {@code factory}. Those objects should not be manually updated and they should not use soft, * weak, or phantom references. * * @param map place to store the mapping from each key to its corresponding values * @param factory supplier of new, empty sorted sets that will each hold all values for a given * key * @throws IllegalArgumentException if {@code map} is not empty */ public static <K extends @Nullable Object, V extends @Nullable Object> SortedSetMultimap<K, V> newSortedSetMultimap( Map<K, Collection<V>> map, final Supplier<? extends SortedSet<V>> factory) { return new CustomSortedSetMultimap<>(map, factory); } private static class CustomSortedSetMultimap< K extends @Nullable Object, V extends @Nullable Object> extends AbstractSortedSetMultimap<K, V> { transient Supplier<? extends SortedSet<V>> factory; @CheckForNull transient Comparator<? super V> valueComparator; CustomSortedSetMultimap(Map<K, Collection<V>> map, Supplier<? extends SortedSet<V>> factory) { super(map); this.factory = checkNotNull(factory); valueComparator = factory.get().comparator(); } @Override Set<K> createKeySet() { return createMaybeNavigableKeySet(); } @Override Map<K, Collection<V>> createAsMap() { return createMaybeNavigableAsMap(); } @Override protected SortedSet<V> createCollection() { return factory.get(); } @Override @CheckForNull public Comparator<? super V> valueComparator() { return valueComparator; } /** * @serialData the factory and the backing map */ @GwtIncompatible // java.io.ObjectOutputStream @J2ktIncompatible private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(factory); stream.writeObject(backingMap()); } @GwtIncompatible // java.io.ObjectInputStream @J2ktIncompatible @SuppressWarnings("unchecked") // reading data stored by writeObject private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); factory = (Supplier<? extends SortedSet<V>>) requireNonNull(stream.readObject()); valueComparator = factory.get().comparator(); Map<K, Collection<V>> map = (Map<K, Collection<V>>) requireNonNull(stream.readObject()); setMap(map); } @GwtIncompatible // not needed in emulated source @J2ktIncompatible private static final long serialVersionUID = 0; } /** * Copies each key-value mapping in {@code source} into {@code dest}, with its key and value * reversed. * * <p>If {@code source} is an {@link ImmutableMultimap}, consider using {@link * ImmutableMultimap#inverse} instead. * * @param source any multimap * @param dest the multimap to copy into; usually empty * @return {@code dest} */ @CanIgnoreReturnValue public static <K extends @Nullable Object, V extends @Nullable Object, M extends Multimap<K, V>> M invertFrom(Multimap<? extends V, ? extends K> source, M dest) { checkNotNull(dest); for (Map.Entry<? extends V, ? extends K> entry : source.entries()) { dest.put(entry.getValue(), entry.getKey()); } return dest; } /** * Returns a synchronized (thread-safe) multimap backed by the specified multimap. In order to * guarantee serial access, it is critical that <b>all</b> access to the backing multimap is * accomplished through the returned multimap. * * <p>It is imperative that the user manually synchronize on the returned multimap when accessing * any of its collection views: * * <pre>{@code * Multimap<K, V> multimap = Multimaps.synchronizedMultimap( * HashMultimap.<K, V>create()); * ... * Collection<V> values = multimap.get(key); // Needn't be in synchronized block * ... * synchronized (multimap) { // Synchronizing on multimap, not values! * Iterator<V> i = values.iterator(); // Must be in synchronized block * while (i.hasNext()) { * foo(i.next()); * } * } * }</pre> * * <p>Failure to follow this advice may result in non-deterministic behavior. * * <p>Note that the generated multimap's {@link Multimap#removeAll} and {@link * Multimap#replaceValues} methods return collections that aren't synchronized. * * <p>The returned multimap will be serializable if the specified multimap is serializable. * * @param multimap the multimap to be wrapped in a synchronized view * @return a synchronized view of the specified multimap */ public static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> synchronizedMultimap(Multimap<K, V> multimap) { return Synchronized.multimap(multimap, null); } /** * Returns an unmodifiable view of the specified multimap. Query operations on the returned * multimap "read through" to the specified multimap, and attempts to modify the returned * multimap, either directly or through the multimap's views, result in an {@code * UnsupportedOperationException}. * * <p>The returned multimap will be serializable if the specified multimap is serializable. * * @param delegate the multimap for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified multimap */ public static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> unmodifiableMultimap(Multimap<K, V> delegate) { if (delegate instanceof UnmodifiableMultimap || delegate instanceof ImmutableMultimap) { return delegate; } return new UnmodifiableMultimap<>(delegate); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <K, V> Multimap<K, V> unmodifiableMultimap(ImmutableMultimap<K, V> delegate) { return checkNotNull(delegate); } private static class UnmodifiableMultimap<K extends @Nullable Object, V extends @Nullable Object> extends ForwardingMultimap<K, V> implements Serializable { final Multimap<K, V> delegate; @LazyInit @CheckForNull transient Collection<Entry<K, V>> entries; @LazyInit @CheckForNull transient Multiset<K> keys; @LazyInit @CheckForNull transient Set<K> keySet; @LazyInit @CheckForNull transient Collection<V> values; @LazyInit @CheckForNull transient Map<K, Collection<V>> map; UnmodifiableMultimap(final Multimap<K, V> delegate) { this.delegate = checkNotNull(delegate); } @Override protected Multimap<K, V> delegate() { return delegate; } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public Map<K, Collection<V>> asMap() { Map<K, Collection<V>> result = map; if (result == null) { result = map = Collections.unmodifiableMap( Maps.transformValues( delegate.asMap(), collection -> unmodifiableValueCollection(collection))); } return result; } @Override public Collection<Entry<K, V>> entries() { Collection<Entry<K, V>> result = entries; if (result == null) { entries = result = unmodifiableEntries(delegate.entries()); } return result; } @Override public void forEach(BiConsumer<? super K, ? super V> consumer) { delegate.forEach(checkNotNull(consumer)); } @Override public Collection<V> get(@ParametricNullness K key) { return unmodifiableValueCollection(delegate.get(key)); } @Override public Multiset<K> keys() { Multiset<K> result = keys; if (result == null) { keys = result = Multisets.unmodifiableMultiset(delegate.keys()); } return result; } @Override public Set<K> keySet() { Set<K> result = keySet; if (result == null) { keySet = result = Collections.unmodifiableSet(delegate.keySet()); } return result; } @Override public boolean put(@ParametricNullness K key, @ParametricNullness V value) { throw new UnsupportedOperationException(); } @Override public boolean putAll(@ParametricNullness K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { throw new UnsupportedOperationException(); } @Override public boolean remove(@CheckForNull Object key, @CheckForNull Object value) { throw new UnsupportedOperationException(); } @Override public Collection<V> removeAll(@CheckForNull Object key) { throw new UnsupportedOperationException(); } @Override public Collection<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public Collection<V> values() { Collection<V> result = values; if (result == null) { values = result = Collections.unmodifiableCollection(delegate.values()); } return result; } private static final long serialVersionUID = 0; } private static class UnmodifiableListMultimap< K extends @Nullable Object, V extends @Nullable Object> extends UnmodifiableMultimap<K, V> implements ListMultimap<K, V> { UnmodifiableListMultimap(ListMultimap<K, V> delegate) { super(delegate); } @Override public ListMultimap<K, V> delegate() { return (ListMultimap<K, V>) super.delegate(); } @Override public List<V> get(@ParametricNullness K key) { return Collections.unmodifiableList(delegate().get(key)); } @Override public List<V> removeAll(@CheckForNull Object key) { throw new UnsupportedOperationException(); } @Override public List<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } private static final long serialVersionUID = 0; } private static class UnmodifiableSetMultimap< K extends @Nullable Object, V extends @Nullable Object> extends UnmodifiableMultimap<K, V> implements SetMultimap<K, V> { UnmodifiableSetMultimap(SetMultimap<K, V> delegate) { super(delegate); } @Override public SetMultimap<K, V> delegate() { return (SetMultimap<K, V>) super.delegate(); } @Override public Set<V> get(@ParametricNullness K key) { /* * Note that this doesn't return a SortedSet when delegate is a * SortedSetMultiset, unlike (SortedSet<V>) super.get(). */ return Collections.unmodifiableSet(delegate().get(key)); } @Override public Set<Map.Entry<K, V>> entries() { return Maps.unmodifiableEntrySet(delegate().entries()); } @Override public Set<V> removeAll(@CheckForNull Object key) { throw new UnsupportedOperationException(); } @Override public Set<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } private static final long serialVersionUID = 0; } private static class UnmodifiableSortedSetMultimap< K extends @Nullable Object, V extends @Nullable Object> extends UnmodifiableSetMultimap<K, V> implements SortedSetMultimap<K, V> { UnmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) { super(delegate); } @Override public SortedSetMultimap<K, V> delegate() { return (SortedSetMultimap<K, V>) super.delegate(); } @Override public SortedSet<V> get(@ParametricNullness K key) { return Collections.unmodifiableSortedSet(delegate().get(key)); } @Override public SortedSet<V> removeAll(@CheckForNull Object key) { throw new UnsupportedOperationException(); } @Override public SortedSet<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override @CheckForNull public Comparator<? super V> valueComparator() { return delegate().valueComparator(); } private static final long serialVersionUID = 0; } /** * Returns a synchronized (thread-safe) {@code SetMultimap} backed by the specified multimap. * * <p>You must follow the warnings described in {@link #synchronizedMultimap}. * * <p>The returned multimap will be serializable if the specified multimap is serializable. * * @param multimap the multimap to be wrapped * @return a synchronized view of the specified multimap */ public static <K extends @Nullable Object, V extends @Nullable Object> SetMultimap<K, V> synchronizedSetMultimap(SetMultimap<K, V> multimap) { return Synchronized.setMultimap(multimap, null); } /** * Returns an unmodifiable view of the specified {@code SetMultimap}. Query operations on the * returned multimap "read through" to the specified multimap, and attempts to modify the returned * multimap, either directly or through the multimap's views, result in an {@code * UnsupportedOperationException}. * * <p>The returned multimap will be serializable if the specified multimap is serializable. * * @param delegate the multimap for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified multimap */ public static <K extends @Nullable Object, V extends @Nullable Object> SetMultimap<K, V> unmodifiableSetMultimap(SetMultimap<K, V> delegate) { if (delegate instanceof UnmodifiableSetMultimap || delegate instanceof ImmutableSetMultimap) { return delegate; } return new UnmodifiableSetMultimap<>(delegate); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <K, V> SetMultimap<K, V> unmodifiableSetMultimap( ImmutableSetMultimap<K, V> delegate) { return checkNotNull(delegate); } /** * Returns a synchronized (thread-safe) {@code SortedSetMultimap} backed by the specified * multimap. * * <p>You must follow the warnings described in {@link #synchronizedMultimap}. * * <p>The returned multimap will be serializable if the specified multimap is serializable. * * @param multimap the multimap to be wrapped * @return a synchronized view of the specified multimap */ public static <K extends @Nullable Object, V extends @Nullable Object> SortedSetMultimap<K, V> synchronizedSortedSetMultimap(SortedSetMultimap<K, V> multimap) { return Synchronized.sortedSetMultimap(multimap, null); } /** * Returns an unmodifiable view of the specified {@code SortedSetMultimap}. Query operations on * the returned multimap "read through" to the specified multimap, and attempts to modify the * returned multimap, either directly or through the multimap's views, result in an {@code * UnsupportedOperationException}. * * <p>The returned multimap will be serializable if the specified multimap is serializable. * * @param delegate the multimap for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified multimap */ public static <K extends @Nullable Object, V extends @Nullable Object> SortedSetMultimap<K, V> unmodifiableSortedSetMultimap(SortedSetMultimap<K, V> delegate) { if (delegate instanceof UnmodifiableSortedSetMultimap) { return delegate; } return new UnmodifiableSortedSetMultimap<>(delegate); } /** * Returns a synchronized (thread-safe) {@code ListMultimap} backed by the specified multimap. * * <p>You must follow the warnings described in {@link #synchronizedMultimap}. * * @param multimap the multimap to be wrapped * @return a synchronized view of the specified multimap */ public static <K extends @Nullable Object, V extends @Nullable Object> ListMultimap<K, V> synchronizedListMultimap(ListMultimap<K, V> multimap) { return Synchronized.listMultimap(multimap, null); } /** * Returns an unmodifiable view of the specified {@code ListMultimap}. Query operations on the * returned multimap "read through" to the specified multimap, and attempts to modify the returned * multimap, either directly or through the multimap's views, result in an {@code * UnsupportedOperationException}. * * <p>The returned multimap will be serializable if the specified multimap is serializable. * * @param delegate the multimap for which an unmodifiable view is to be returned * @return an unmodifiable view of the specified multimap */ public static <K extends @Nullable Object, V extends @Nullable Object> ListMultimap<K, V> unmodifiableListMultimap(ListMultimap<K, V> delegate) { if (delegate instanceof UnmodifiableListMultimap || delegate instanceof ImmutableListMultimap) { return delegate; } return new UnmodifiableListMultimap<>(delegate); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <K, V> ListMultimap<K, V> unmodifiableListMultimap( ImmutableListMultimap<K, V> delegate) { return checkNotNull(delegate); } /** * Returns an unmodifiable view of the specified collection, preserving the interface for * instances of {@code SortedSet}, {@code Set}, {@code List} and {@code Collection}, in that order * of preference. * * @param collection the collection for which to return an unmodifiable view * @return an unmodifiable view of the collection */ private static <V extends @Nullable Object> Collection<V> unmodifiableValueCollection( Collection<V> collection) { if (collection instanceof SortedSet) { return Collections.unmodifiableSortedSet((SortedSet<V>) collection); } else if (collection instanceof Set) { return Collections.unmodifiableSet((Set<V>) collection); } else if (collection instanceof List) { return Collections.unmodifiableList((List<V>) collection); } return Collections.unmodifiableCollection(collection); } /** * Returns an unmodifiable view of the specified collection of entries. The {@link Entry#setValue} * operation throws an {@link UnsupportedOperationException}. If the specified collection is a * {@code Set}, the returned collection is also a {@code Set}. * * @param entries the entries for which to return an unmodifiable view * @return an unmodifiable view of the entries */ private static <K extends @Nullable Object, V extends @Nullable Object> Collection<Entry<K, V>> unmodifiableEntries(Collection<Entry<K, V>> entries) { if (entries instanceof Set) { return Maps.unmodifiableEntrySet((Set<Entry<K, V>>) entries); } return new Maps.UnmodifiableEntries<>(Collections.unmodifiableCollection(entries)); } /** * Returns {@link ListMultimap#asMap multimap.asMap()}, with its type corrected from {@code Map<K, * Collection<V>>} to {@code Map<K, List<V>>}. * * @since 15.0 */ @SuppressWarnings("unchecked") // safe by specification of ListMultimap.asMap() public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, List<V>> asMap( ListMultimap<K, V> multimap) { return (Map<K, List<V>>) (Map<K, ?>) multimap.asMap(); } /** * Returns {@link SetMultimap#asMap multimap.asMap()}, with its type corrected from {@code Map<K, * Collection<V>>} to {@code Map<K, Set<V>>}. * * @since 15.0 */ @SuppressWarnings("unchecked") // safe by specification of SetMultimap.asMap() public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, Set<V>> asMap( SetMultimap<K, V> multimap) { return (Map<K, Set<V>>) (Map<K, ?>) multimap.asMap(); } /** * Returns {@link SortedSetMultimap#asMap multimap.asMap()}, with its type corrected from {@code * Map<K, Collection<V>>} to {@code Map<K, SortedSet<V>>}. * * @since 15.0 */ @SuppressWarnings("unchecked") // safe by specification of SortedSetMultimap.asMap() public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, SortedSet<V>> asMap( SortedSetMultimap<K, V> multimap) { return (Map<K, SortedSet<V>>) (Map<K, ?>) multimap.asMap(); } /** * Returns {@link Multimap#asMap multimap.asMap()}. This is provided for parity with the other * more strongly-typed {@code asMap()} implementations. * * @since 15.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> Map<K, Collection<V>> asMap(Multimap<K, V> multimap) { return multimap.asMap(); } /** * Returns a multimap view of the specified map. The multimap is backed by the map, so changes to * the map are reflected in the multimap, and vice versa. If the map is modified while an * iteration over one of the multimap's collection views is in progress (except through the * iterator's own {@code remove} operation, or through the {@code setValue} operation on a map * entry returned by the iterator), the results of the iteration are undefined. * * <p>The multimap supports mapping removal, which removes the corresponding mapping from the map. * It does not support any operations which might add mappings, such as {@code put}, {@code * putAll} or {@code replaceValues}. * * <p>The returned multimap will be serializable if the specified map is serializable. * * @param map the backing map for the returned multimap view */ public static <K extends @Nullable Object, V extends @Nullable Object> SetMultimap<K, V> forMap( Map<K, V> map) { return new MapMultimap<>(map); } /** @see Multimaps#forMap */ private static class MapMultimap<K extends @Nullable Object, V extends @Nullable Object> extends AbstractMultimap<K, V> implements SetMultimap<K, V>, Serializable { final Map<K, V> map; MapMultimap(Map<K, V> map) { this.map = checkNotNull(map); } @Override public int size() { return map.size(); } @Override public boolean containsKey(@CheckForNull Object key) { return map.containsKey(key); } @Override public boolean containsValue(@CheckForNull Object value) { return map.containsValue(value); } @Override public boolean containsEntry(@CheckForNull Object key, @CheckForNull Object value) { return map.entrySet().contains(Maps.immutableEntry(key, value)); } @Override public Set<V> get(@ParametricNullness final K key) { return new Sets.ImprovedAbstractSet<V>() { @Override public Iterator<V> iterator() { return new Iterator<V>() { int i; @Override public boolean hasNext() { return (i == 0) && map.containsKey(key); } @Override @ParametricNullness public V next() { if (!hasNext()) { throw new NoSuchElementException(); } i++; /* * The cast is safe because of the containsKey check in hasNext(). (That means it's * unsafe under concurrent modification, but all bets are off then, anyway.) */ return uncheckedCastNullableTToT(map.get(key)); } @Override public void remove() { checkRemove(i == 1); i = -1; map.remove(key); } }; } @Override public int size() { return map.containsKey(key) ? 1 : 0; } }; } @Override public boolean put(@ParametricNullness K key, @ParametricNullness V value) { throw new UnsupportedOperationException(); } @Override public boolean putAll(@ParametricNullness K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public boolean putAll(Multimap<? extends K, ? extends V> multimap) { throw new UnsupportedOperationException(); } @Override public Set<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) { throw new UnsupportedOperationException(); } @Override public boolean remove(@CheckForNull Object key, @CheckForNull Object value) { return map.entrySet().remove(Maps.immutableEntry(key, value)); } @Override public Set<V> removeAll(@CheckForNull Object key) { Set<V> values = new HashSet<>(2); if (!map.containsKey(key)) { return values; } values.add(map.remove(key)); return values; } @Override public void clear() { map.clear(); } @Override Set<K> createKeySet() { return map.keySet(); } @Override Collection<V> createValues() { return map.values(); } @Override public Set<Entry<K, V>> entries() { return map.entrySet(); } @Override Collection<Entry<K, V>> createEntries() { throw new AssertionError("unreachable"); } @Override Multiset<K> createKeys() { return new Multimaps.Keys<K, V>(this); } @Override Iterator<Entry<K, V>> entryIterator() { return map.entrySet().iterator(); } @Override Map<K, Collection<V>> createAsMap() { return new AsMap<>(this); } @Override public int hashCode() { return map.hashCode(); } private static final long serialVersionUID = 7845222491160860175L; } /** * Returns a view of a multimap where each value is transformed by a function. All other * properties of the multimap, such as iteration order, are left intact. For example, the code: * * <pre>{@code * Multimap<String, Integer> multimap = * ImmutableSetMultimap.of("a", 2, "b", -3, "b", -3, "a", 4, "c", 6); * Function<Integer, String> square = new Function<Integer, String>() { * public String apply(Integer in) { * return Integer.toString(in * in); * } * }; * Multimap<String, String> transformed = * Multimaps.transformValues(multimap, square); * System.out.println(transformed); * }</pre> * * ... prints {@code {a=[4, 16], b=[9, 9], c=[36]}}. * * <p>Changes in the underlying multimap are reflected in this view. Conversely, this view * supports removal operations, and these are reflected in the underlying multimap. * * <p>It's acceptable for the underlying multimap to contain null keys, and even null values * provided that the function is capable of accepting null input. The transformed multimap might * contain null values, if the function sometimes gives a null result. * * <p>The returned multimap is not thread-safe or serializable, even if the underlying multimap * is. The {@code equals} and {@code hashCode} methods of the returned multimap are meaningless, * since there is not a definition of {@code equals} or {@code hashCode} for general collections, * and {@code get()} will return a general {@code Collection} as opposed to a {@code List} or a * {@code Set}. * * <p>The function is applied lazily, invoked when needed. This is necessary for the returned * multimap to be a view, but it means that the function will be applied many times for bulk * operations like {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to * perform well, {@code function} should be fast. To avoid lazy evaluation when the returned * multimap doesn't need to be a view, copy the returned multimap into a new multimap of your * choosing. * * @since 7.0 */ public static < K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> Multimap<K, V2> transformValues( Multimap<K, V1> fromMultimap, final Function<? super V1, V2> function) { checkNotNull(function); EntryTransformer<K, V1, V2> transformer = Maps.asEntryTransformer(function); return transformEntries(fromMultimap, transformer); } /** * Returns a view of a {@code ListMultimap} where each value is transformed by a function. All * other properties of the multimap, such as iteration order, are left intact. For example, the * code: * * <pre>{@code * ListMultimap<String, Integer> multimap * = ImmutableListMultimap.of("a", 4, "a", 16, "b", 9); * Function<Integer, Double> sqrt = * new Function<Integer, Double>() { * public Double apply(Integer in) { * return Math.sqrt((int) in); * } * }; * ListMultimap<String, Double> transformed = Multimaps.transformValues(map, * sqrt); * System.out.println(transformed); * }</pre> * * ... prints {@code {a=[2.0, 4.0], b=[3.0]}}. * * <p>Changes in the underlying multimap are reflected in this view. Conversely, this view * supports removal operations, and these are reflected in the underlying multimap. * * <p>It's acceptable for the underlying multimap to contain null keys, and even null values * provided that the function is capable of accepting null input. The transformed multimap might * contain null values, if the function sometimes gives a null result. * * <p>The returned multimap is not thread-safe or serializable, even if the underlying multimap * is. * * <p>The function is applied lazily, invoked when needed. This is necessary for the returned * multimap to be a view, but it means that the function will be applied many times for bulk * operations like {@link Multimap#containsValue} and {@code Multimap.toString()}. For this to * perform well, {@code function} should be fast. To avoid lazy evaluation when the returned * multimap doesn't need to be a view, copy the returned multimap into a new multimap of your * choosing. * * @since 7.0 */ public static < K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> ListMultimap<K, V2> transformValues( ListMultimap<K, V1> fromMultimap, final Function<? super V1, V2> function) { checkNotNull(function); EntryTransformer<K, V1, V2> transformer = Maps.asEntryTransformer(function); return transformEntries(fromMultimap, transformer); } /** * Returns a view of a multimap whose values are derived from the original multimap's entries. In * contrast to {@link #transformValues}, this method's entry-transformation logic may depend on * the key as well as the value. * * <p>All other properties of the transformed multimap, such as iteration order, are left intact. * For example, the code: * * <pre>{@code * SetMultimap<String, Integer> multimap = * ImmutableSetMultimap.of("a", 1, "a", 4, "b", -6); * EntryTransformer<String, Integer, String> transformer = * new EntryTransformer<String, Integer, String>() { * public String transformEntry(String key, Integer value) { * return (value >= 0) ? key : "no" + key; * } * }; * Multimap<String, String> transformed = * Multimaps.transformEntries(multimap, transformer); * System.out.println(transformed); * }</pre> * * ... prints {@code {a=[a, a], b=[nob]}}. * * <p>Changes in the underlying multimap are reflected in this view. Conversely, this view * supports removal operations, and these are reflected in the underlying multimap. * * <p>It's acceptable for the underlying multimap to contain null keys and null values provided * that the transformer is capable of accepting null inputs. The transformed multimap might * contain null values if the transformer sometimes gives a null result. * * <p>The returned multimap is not thread-safe or serializable, even if the underlying multimap * is. The {@code equals} and {@code hashCode} methods of the returned multimap are meaningless, * since there is not a definition of {@code equals} or {@code hashCode} for general collections, * and {@code get()} will return a general {@code Collection} as opposed to a {@code List} or a * {@code Set}. * * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned * multimap to be a view, but it means that the transformer will be applied many times for bulk * operations like {@link Multimap#containsValue} and {@link Object#toString}. For this to perform * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned multimap * doesn't need to be a view, copy the returned multimap into a new multimap of your choosing. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the * transformed multimap. * * @since 7.0 */ public static < K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> Multimap<K, V2> transformEntries( Multimap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return new TransformedEntriesMultimap<>(fromMap, transformer); } /** * Returns a view of a {@code ListMultimap} whose values are derived from the original multimap's * entries. In contrast to {@link #transformValues(ListMultimap, Function)}, this method's * entry-transformation logic may depend on the key as well as the value. * * <p>All other properties of the transformed multimap, such as iteration order, are left intact. * For example, the code: * * <pre>{@code * Multimap<String, Integer> multimap = * ImmutableMultimap.of("a", 1, "a", 4, "b", 6); * EntryTransformer<String, Integer, String> transformer = * new EntryTransformer<String, Integer, String>() { * public String transformEntry(String key, Integer value) { * return key + value; * } * }; * Multimap<String, String> transformed = * Multimaps.transformEntries(multimap, transformer); * System.out.println(transformed); * }</pre> * * ... prints {@code {"a"=["a1", "a4"], "b"=["b6"]}}. * * <p>Changes in the underlying multimap are reflected in this view. Conversely, this view * supports removal operations, and these are reflected in the underlying multimap. * * <p>It's acceptable for the underlying multimap to contain null keys and null values provided * that the transformer is capable of accepting null inputs. The transformed multimap might * contain null values if the transformer sometimes gives a null result. * * <p>The returned multimap is not thread-safe or serializable, even if the underlying multimap * is. * * <p>The transformer is applied lazily, invoked when needed. This is necessary for the returned * multimap to be a view, but it means that the transformer will be applied many times for bulk * operations like {@link Multimap#containsValue} and {@link Object#toString}. For this to perform * well, {@code transformer} should be fast. To avoid lazy evaluation when the returned multimap * doesn't need to be a view, copy the returned multimap into a new multimap of your choosing. * * <p><b>Warning:</b> This method assumes that for any instance {@code k} of {@code * EntryTransformer} key type {@code K}, {@code k.equals(k2)} implies that {@code k2} is also of * type {@code K}. Using an {@code EntryTransformer} key type for which this may not hold, such as * {@code ArrayList}, may risk a {@code ClassCastException} when calling methods on the * transformed multimap. * * @since 7.0 */ public static < K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> ListMultimap<K, V2> transformEntries( ListMultimap<K, V1> fromMap, EntryTransformer<? super K, ? super V1, V2> transformer) { return new TransformedEntriesListMultimap<>(fromMap, transformer); } private static class TransformedEntriesMultimap< K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> extends AbstractMultimap<K, V2> { final Multimap<K, V1> fromMultimap; final EntryTransformer<? super K, ? super V1, V2> transformer; TransformedEntriesMultimap( Multimap<K, V1> fromMultimap, final EntryTransformer<? super K, ? super V1, V2> transformer) { this.fromMultimap = checkNotNull(fromMultimap); this.transformer = checkNotNull(transformer); } Collection<V2> transform(@ParametricNullness K key, Collection<V1> values) { Function<? super V1, V2> function = Maps.asValueToValueFunction(transformer, key); if (values instanceof List) { return Lists.transform((List<V1>) values, function); } else { return Collections2.transform(values, function); } } @Override Map<K, Collection<V2>> createAsMap() { return Maps.transformEntries(fromMultimap.asMap(), (key, value) -> transform(key, value)); } @Override public void clear() { fromMultimap.clear(); } @Override public boolean containsKey(@CheckForNull Object key) { return fromMultimap.containsKey(key); } @Override Collection<Entry<K, V2>> createEntries() { return new Entries(); } @Override Iterator<Entry<K, V2>> entryIterator() { return Iterators.transform( fromMultimap.entries().iterator(), Maps.<K, V1, V2>asEntryToEntryFunction(transformer)); } @Override public Collection<V2> get(@ParametricNullness final K key) { return transform(key, fromMultimap.get(key)); } @Override public boolean isEmpty() { return fromMultimap.isEmpty(); } @Override Set<K> createKeySet() { return fromMultimap.keySet(); } @Override Multiset<K> createKeys() { return fromMultimap.keys(); } @Override public boolean put(@ParametricNullness K key, @ParametricNullness V2 value) { throw new UnsupportedOperationException(); } @Override public boolean putAll(@ParametricNullness K key, Iterable<? extends V2> values) { throw new UnsupportedOperationException(); } @Override public boolean putAll(Multimap<? extends K, ? extends V2> multimap) { throw new UnsupportedOperationException(); } @SuppressWarnings("unchecked") @Override public boolean remove(@CheckForNull Object key, @CheckForNull Object value) { return get((K) key).remove(value); } @SuppressWarnings("unchecked") @Override public Collection<V2> removeAll(@CheckForNull Object key) { return transform((K) key, fromMultimap.removeAll(key)); } @Override public Collection<V2> replaceValues(@ParametricNullness K key, Iterable<? extends V2> values) { throw new UnsupportedOperationException(); } @Override public int size() { return fromMultimap.size(); } @Override Collection<V2> createValues() { return Collections2.transform( fromMultimap.entries(), Maps.<K, V1, V2>asEntryToValueFunction(transformer)); } } private static final class TransformedEntriesListMultimap< K extends @Nullable Object, V1 extends @Nullable Object, V2 extends @Nullable Object> extends TransformedEntriesMultimap<K, V1, V2> implements ListMultimap<K, V2> { TransformedEntriesListMultimap( ListMultimap<K, V1> fromMultimap, EntryTransformer<? super K, ? super V1, V2> transformer) { super(fromMultimap, transformer); } @Override List<V2> transform(@ParametricNullness K key, Collection<V1> values) { return Lists.transform((List<V1>) values, Maps.asValueToValueFunction(transformer, key)); } @Override public List<V2> get(@ParametricNullness K key) { return transform(key, fromMultimap.get(key)); } @SuppressWarnings("unchecked") @Override public List<V2> removeAll(@CheckForNull Object key) { return transform((K) key, fromMultimap.removeAll(key)); } @Override public List<V2> replaceValues(@ParametricNullness K key, Iterable<? extends V2> values) { throw new UnsupportedOperationException(); } } /** * Creates an index {@code ImmutableListMultimap} that contains the results of applying a * specified function to each item in an {@code Iterable} of values. Each value will be stored as * a value in the resulting multimap, yielding a multimap with the same size as the input * iterable. The key used to store that value in the multimap will be the result of calling the * function on that value. The resulting multimap is created as an immutable snapshot. In the * returned multimap, keys appear in the order they are first encountered, and the values * corresponding to each key appear in the same order as they are encountered. * * <p>For example, * * <pre>{@code * List<String> badGuys = * Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde"); * Function<String, Integer> stringLengthFunction = ...; * Multimap<Integer, String> index = * Multimaps.index(badGuys, stringLengthFunction); * System.out.println(index); * }</pre> * * <p>prints * * <pre>{@code * {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]} * }</pre> * * <p>The returned multimap is serializable if its keys and values are all serializable. * * @param values the values to use when constructing the {@code ImmutableListMultimap} * @param keyFunction the function used to produce the key for each value * @return {@code ImmutableListMultimap} mapping the result of evaluating the function {@code * keyFunction} on each value in the input collection to that value * @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code * keyFunction} produces {@code null} for any key */ public static <K, V> ImmutableListMultimap<K, V> index( Iterable<V> values, Function<? super V, K> keyFunction) { return index(values.iterator(), keyFunction); } /** * Creates an index {@code ImmutableListMultimap} that contains the results of applying a * specified function to each item in an {@code Iterator} of values. Each value will be stored as * a value in the resulting multimap, yielding a multimap with the same size as the input * iterator. The key used to store that value in the multimap will be the result of calling the * function on that value. The resulting multimap is created as an immutable snapshot. In the * returned multimap, keys appear in the order they are first encountered, and the values * corresponding to each key appear in the same order as they are encountered. * * <p>For example, * * <pre>{@code * List<String> badGuys = * Arrays.asList("Inky", "Blinky", "Pinky", "Pinky", "Clyde"); * Function<String, Integer> stringLengthFunction = ...; * Multimap<Integer, String> index = * Multimaps.index(badGuys.iterator(), stringLengthFunction); * System.out.println(index); * }</pre> * * <p>prints * * <pre>{@code * {4=[Inky], 6=[Blinky], 5=[Pinky, Pinky, Clyde]} * }</pre> * * <p>The returned multimap is serializable if its keys and values are all serializable. * * @param values the values to use when constructing the {@code ImmutableListMultimap} * @param keyFunction the function used to produce the key for each value * @return {@code ImmutableListMultimap} mapping the result of evaluating the function {@code * keyFunction} on each value in the input collection to that value * @throws NullPointerException if any element of {@code values} is {@code null}, or if {@code * keyFunction} produces {@code null} for any key * @since 10.0 */ public static <K, V> ImmutableListMultimap<K, V> index( Iterator<V> values, Function<? super V, K> keyFunction) { checkNotNull(keyFunction); ImmutableListMultimap.Builder<K, V> builder = ImmutableListMultimap.builder(); while (values.hasNext()) { V value = values.next(); checkNotNull(value, values); builder.put(keyFunction.apply(value), value); } return builder.build(); } static class Keys<K extends @Nullable Object, V extends @Nullable Object> extends AbstractMultiset<K> { @Weak final Multimap<K, V> multimap; Keys(Multimap<K, V> multimap) { this.multimap = multimap; } @Override Iterator<Multiset.Entry<K>> entryIterator() { return new TransformedIterator<Map.Entry<K, Collection<V>>, Multiset.Entry<K>>( multimap.asMap().entrySet().iterator()) { @Override Multiset.Entry<K> transform(final Map.Entry<K, Collection<V>> backingEntry) { return new Multisets.AbstractEntry<K>() { @Override @ParametricNullness public K getElement() { return backingEntry.getKey(); } @Override public int getCount() { return backingEntry.getValue().size(); } }; } }; } @Override public Spliterator<K> spliterator() { return CollectSpliterators.map(multimap.entries().spliterator(), Map.Entry::getKey); } @Override public void forEach(Consumer<? super K> consumer) { checkNotNull(consumer); multimap.entries().forEach(entry -> consumer.accept(entry.getKey())); } @Override int distinctElements() { return multimap.asMap().size(); } @Override public int size() { return multimap.size(); } @Override public boolean contains(@CheckForNull Object element) { return multimap.containsKey(element); } @Override public Iterator<K> iterator() { return Maps.keyIterator(multimap.entries().iterator()); } @Override public int count(@CheckForNull Object element) { Collection<V> values = Maps.safeGet(multimap.asMap(), element); return (values == null) ? 0 : values.size(); } @Override public int remove(@CheckForNull Object element, int occurrences) { checkNonnegative(occurrences, "occurrences"); if (occurrences == 0) { return count(element); } Collection<V> values = Maps.safeGet(multimap.asMap(), element); if (values == null) { return 0; } int oldCount = values.size(); if (occurrences >= oldCount) { values.clear(); } else { Iterator<V> iterator = values.iterator(); for (int i = 0; i < occurrences; i++) { iterator.next(); iterator.remove(); } } return oldCount; } @Override public void clear() { multimap.clear(); } @Override public Set<K> elementSet() { return multimap.keySet(); } @Override Iterator<K> elementIterator() { throw new AssertionError("should never be called"); } } /** A skeleton implementation of {@link Multimap#entries()}. */ abstract static class Entries<K extends @Nullable Object, V extends @Nullable Object> extends AbstractCollection<Map.Entry<K, V>> { abstract Multimap<K, V> multimap(); @Override public int size() { return multimap().size(); } @Override public boolean contains(@CheckForNull Object o) { if (o instanceof Map.Entry) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; return multimap().containsEntry(entry.getKey(), entry.getValue()); } return false; } @Override public boolean remove(@CheckForNull Object o) { if (o instanceof Map.Entry) { Map.Entry<?, ?> entry = (Map.Entry<?, ?>) o; return multimap().remove(entry.getKey(), entry.getValue()); } return false; } @Override public void clear() { multimap().clear(); } } /** A skeleton implementation of {@link Multimap#asMap()}. */ static final class AsMap<K extends @Nullable Object, V extends @Nullable Object> extends Maps.ViewCachingAbstractMap<K, Collection<V>> { @Weak private final Multimap<K, V> multimap; AsMap(Multimap<K, V> multimap) { this.multimap = checkNotNull(multimap); } @Override public int size() { return multimap.keySet().size(); } @Override protected Set<Entry<K, Collection<V>>> createEntrySet() { return new EntrySet(); } void removeValuesForKey(@CheckForNull Object key) { multimap.keySet().remove(key); } @WeakOuter class EntrySet extends Maps.EntrySet<K, Collection<V>> { @Override Map<K, Collection<V>> map() { return AsMap.this; } @Override public Iterator<Entry<K, Collection<V>>> iterator() { return Maps.asMapEntryIterator(multimap.keySet(), key -> multimap.get(key)); } @Override public boolean remove(@CheckForNull Object o) { if (!contains(o)) { return false; } // requireNonNull is safe because of the contains check. Map.Entry<?, ?> entry = requireNonNull((Map.Entry<?, ?>) o); removeValuesForKey(entry.getKey()); return true; } } @SuppressWarnings("unchecked") @Override @CheckForNull public Collection<V> get(@CheckForNull Object key) { return containsKey(key) ? multimap.get((K) key) : null; } @Override @CheckForNull public Collection<V> remove(@CheckForNull Object key) { return containsKey(key) ? multimap.removeAll(key) : null; } @Override public Set<K> keySet() { return multimap.keySet(); } @Override public boolean isEmpty() { return multimap.isEmpty(); } @Override public boolean containsKey(@CheckForNull Object key) { return multimap.containsKey(key); } @Override public void clear() { multimap.clear(); } } /** * Returns a multimap containing the mappings in {@code unfiltered} whose keys satisfy a * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect * the other. * * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all * other methods are supported by the multimap and its views. When adding a key that doesn't * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code * replaceValues()} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * multimap or its views, only mappings whose keys satisfy the filter will be removed from the * underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every * key/value mapping in the underlying multimap and determine which satisfy the filter. When a * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the * copy. * * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at * {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. * * @since 11.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> filterKeys( Multimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { if (unfiltered instanceof SetMultimap) { return filterKeys((SetMultimap<K, V>) unfiltered, keyPredicate); } else if (unfiltered instanceof ListMultimap) { return filterKeys((ListMultimap<K, V>) unfiltered, keyPredicate); } else if (unfiltered instanceof FilteredKeyMultimap) { FilteredKeyMultimap<K, V> prev = (FilteredKeyMultimap<K, V>) unfiltered; return new FilteredKeyMultimap<>( prev.unfiltered, Predicates.<K>and(prev.keyPredicate, keyPredicate)); } else if (unfiltered instanceof FilteredMultimap) { FilteredMultimap<K, V> prev = (FilteredMultimap<K, V>) unfiltered; return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate)); } else { return new FilteredKeyMultimap<>(unfiltered, keyPredicate); } } /** * Returns a multimap containing the mappings in {@code unfiltered} whose keys satisfy a * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect * the other. * * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all * other methods are supported by the multimap and its views. When adding a key that doesn't * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code * replaceValues()} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * multimap or its views, only mappings whose keys satisfy the filter will be removed from the * underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every * key/value mapping in the underlying multimap and determine which satisfy the filter. When a * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the * copy. * * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at * {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. * * @since 14.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> SetMultimap<K, V> filterKeys( SetMultimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { if (unfiltered instanceof FilteredKeySetMultimap) { FilteredKeySetMultimap<K, V> prev = (FilteredKeySetMultimap<K, V>) unfiltered; return new FilteredKeySetMultimap<>( prev.unfiltered(), Predicates.<K>and(prev.keyPredicate, keyPredicate)); } else if (unfiltered instanceof FilteredSetMultimap) { FilteredSetMultimap<K, V> prev = (FilteredSetMultimap<K, V>) unfiltered; return filterFiltered(prev, Maps.<K>keyPredicateOnEntries(keyPredicate)); } else { return new FilteredKeySetMultimap<>(unfiltered, keyPredicate); } } /** * Returns a multimap containing the mappings in {@code unfiltered} whose keys satisfy a * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect * the other. * * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all * other methods are supported by the multimap and its views. When adding a key that doesn't * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code * replaceValues()} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * multimap or its views, only mappings whose keys satisfy the filter will be removed from the * underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every * key/value mapping in the underlying multimap and determine which satisfy the filter. When a * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the * copy. * * <p><b>Warning:</b> {@code keyPredicate} must be <i>consistent with equals</i>, as documented at * {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. * * @since 14.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> ListMultimap<K, V> filterKeys( ListMultimap<K, V> unfiltered, final Predicate<? super K> keyPredicate) { if (unfiltered instanceof FilteredKeyListMultimap) { FilteredKeyListMultimap<K, V> prev = (FilteredKeyListMultimap<K, V>) unfiltered; return new FilteredKeyListMultimap<>( prev.unfiltered(), Predicates.<K>and(prev.keyPredicate, keyPredicate)); } else { return new FilteredKeyListMultimap<>(unfiltered, keyPredicate); } } /** * Returns a multimap containing the mappings in {@code unfiltered} whose values satisfy a * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect * the other. * * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all * other methods are supported by the multimap and its views. When adding a value that doesn't * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code * replaceValues()} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * multimap or its views, only mappings whose value satisfy the filter will be removed from the * underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every * key/value mapping in the underlying multimap and determine which satisfy the filter. When a * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the * copy. * * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented * at {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. * * @since 11.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> filterValues( Multimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); } /** * Returns a multimap containing the mappings in {@code unfiltered} whose values satisfy a * predicate. The returned multimap is a live view of {@code unfiltered}; changes to one affect * the other. * * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all * other methods are supported by the multimap and its views. When adding a value that doesn't * satisfy the predicate, the multimap's {@code put()}, {@code putAll()}, and {@code * replaceValues()} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * multimap or its views, only mappings whose value satisfy the filter will be removed from the * underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every * key/value mapping in the underlying multimap and determine which satisfy the filter. When a * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the * copy. * * <p><b>Warning:</b> {@code valuePredicate} must be <i>consistent with equals</i>, as documented * at {@link Predicate#apply}. Do not provide a predicate such as {@code * Predicates.instanceOf(ArrayList.class)}, which is inconsistent with equals. * * @since 14.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> SetMultimap<K, V> filterValues( SetMultimap<K, V> unfiltered, final Predicate<? super V> valuePredicate) { return filterEntries(unfiltered, Maps.<V>valuePredicateOnEntries(valuePredicate)); } /** * Returns a multimap containing the mappings in {@code unfiltered} that satisfy a predicate. The * returned multimap is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all * other methods are supported by the multimap and its views. When adding a key/value pair that * doesn't satisfy the predicate, multimap's {@code put()}, {@code putAll()}, and {@code * replaceValues()} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * multimap or its views, only mappings whose keys satisfy the filter will be removed from the * underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every * key/value mapping in the underlying multimap and determine which satisfy the filter. When a * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the * copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented * at {@link Predicate#apply}. * * @since 11.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> filterEntries( Multimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(entryPredicate); if (unfiltered instanceof SetMultimap) { return filterEntries((SetMultimap<K, V>) unfiltered, entryPredicate); } return (unfiltered instanceof FilteredMultimap) ? filterFiltered((FilteredMultimap<K, V>) unfiltered, entryPredicate) : new FilteredEntryMultimap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Returns a multimap containing the mappings in {@code unfiltered} that satisfy a predicate. The * returned multimap is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting multimap's views have iterators that don't support {@code remove()}, but all * other methods are supported by the multimap and its views. When adding a key/value pair that * doesn't satisfy the predicate, multimap's {@code put()}, {@code putAll()}, and {@code * replaceValues()} methods throw an {@link IllegalArgumentException}. * * <p>When methods such as {@code removeAll()} and {@code clear()} are called on the filtered * multimap or its views, only mappings whose keys satisfy the filter will be removed from the * underlying multimap. * * <p>The returned multimap isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered multimap's methods, such as {@code size()}, iterate across every * key/value mapping in the underlying multimap and determine which satisfy the filter. When a * live view is <i>not</i> needed, it may be faster to copy the filtered multimap and use the * copy. * * <p><b>Warning:</b> {@code entryPredicate} must be <i>consistent with equals</i>, as documented * at {@link Predicate#apply}. * * @since 14.0 */ public static <K extends @Nullable Object, V extends @Nullable Object> SetMultimap<K, V> filterEntries( SetMultimap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate) { checkNotNull(entryPredicate); return (unfiltered instanceof FilteredSetMultimap) ? filterFiltered((FilteredSetMultimap<K, V>) unfiltered, entryPredicate) : new FilteredEntrySetMultimap<K, V>(checkNotNull(unfiltered), entryPredicate); } /** * Support removal operations when filtering a filtered multimap. Since a filtered multimap has * iterators that don't support remove, passing one to the FilteredEntryMultimap constructor would * lead to a multimap whose removal operations would fail. This method combines the predicates to * avoid that problem. */ private static <K extends @Nullable Object, V extends @Nullable Object> Multimap<K, V> filterFiltered( FilteredMultimap<K, V> multimap, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(multimap.entryPredicate(), entryPredicate); return new FilteredEntryMultimap<>(multimap.unfiltered(), predicate); } /** * Support removal operations when filtering a filtered multimap. Since a filtered multimap has * iterators that don't support remove, passing one to the FilteredEntryMultimap constructor would * lead to a multimap whose removal operations would fail. This method combines the predicates to * avoid that problem. */ private static <K extends @Nullable Object, V extends @Nullable Object> SetMultimap<K, V> filterFiltered( FilteredSetMultimap<K, V> multimap, Predicate<? super Entry<K, V>> entryPredicate) { Predicate<Entry<K, V>> predicate = Predicates.<Entry<K, V>>and(multimap.entryPredicate(), entryPredicate); return new FilteredEntrySetMultimap<>(multimap.unfiltered(), predicate); } static boolean equalsImpl(Multimap<?, ?> multimap, @CheckForNull Object object) { if (object == multimap) { return true; } if (object instanceof Multimap) { Multimap<?, ?> that = (Multimap<?, ?>) object; return multimap.asMap().equals(that.asMap()); } return false; } // TODO(jlevy): Create methods that filter a SortedSetMultimap. }
google/guava
guava/src/com/google/common/collect/Multimaps.java
401
/* Copyright 2017 The TensorFlow Authors. All Rights Reserved. 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 org.tensorflow; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.util.Properties; /** * Helper class for loading the TensorFlow Java native library. * * <p>The Java TensorFlow bindings require a native (JNI) library. This library * (libtensorflow_jni.so on Linux, libtensorflow_jni.dylib on OS X, tensorflow_jni.dll on Windows) * can be made available to the JVM using the java.library.path System property (e.g., using * -Djava.library.path command-line argument). However, doing so requires an additional step of * configuration. * * <p>Alternatively, the native libraries can be packaed in a .jar, making them easily usable from * build systems like Maven. However, in such cases, the native library has to be extracted from the * .jar archive. * * <p>NativeLibrary.load() takes care of this. First looking for the library in java.library.path * and failing that, it tries to find the OS and architecture specific version of the library in the * set of ClassLoader resources (under org/tensorflow/native/OS-ARCH). The resources paths used for * lookup must be consistent with any packaging (such as on Maven Central) of the TensorFlow Java * native libraries. */ final class NativeLibrary { private static final boolean DEBUG = System.getProperty("org.tensorflow.NativeLibrary.DEBUG") != null; private static final String JNI_LIBNAME = "tensorflow_jni"; public static void load() { if (isLoaded() || tryLoadLibrary()) { // Either: // (1) The native library has already been statically loaded, OR // (2) The required native code has been statically linked (through a custom launcher), OR // (3) The native code is part of another library (such as an application-level library) // that has already been loaded. For example, tensorflow/tools/android/test and // tensorflow/tools/android/inference_interface include the required native code in // differently named libraries. // // Doesn't matter how, but it seems the native code is loaded, so nothing else to do. return; } // Native code is not present, perhaps it has been packaged into the .jar file containing this. // Extract the JNI library itself final String jniLibName = System.mapLibraryName(JNI_LIBNAME); final String jniResourceName = makeResourceName(jniLibName); log("jniResourceName: " + jniResourceName); final InputStream jniResource = NativeLibrary.class.getClassLoader().getResourceAsStream(jniResourceName); // Extract the JNI's dependency final String frameworkLibName = getVersionedLibraryName(System.mapLibraryName("tensorflow_framework")); final String frameworkResourceName = makeResourceName(frameworkLibName); log("frameworkResourceName: " + frameworkResourceName); final InputStream frameworkResource = NativeLibrary.class.getClassLoader().getResourceAsStream(frameworkResourceName); // Do not complain if the framework resource wasn't found. This may just mean that we're // building with --config=monolithic (in which case it's not needed and not included). if (jniResource == null) { throw new UnsatisfiedLinkError( String.format( "Cannot find TensorFlow native library for OS: %s, architecture: %s. See " + "https://github.com/tensorflow/tensorflow/tree/master/tensorflow/java/README.md" + " for possible solutions (such as building the library from source). Additional" + " information on attempts to find the native library can be obtained by adding" + " org.tensorflow.NativeLibrary.DEBUG=1 to the system properties of the JVM.", os(), architecture())); } try { // Create a temporary directory for the extracted resource and its dependencies. final File tempPath = createTemporaryDirectory(); // Deletions are in the reverse order of requests, so we need to request that the directory be // deleted first, so that it is empty when the request is fulfilled. tempPath.deleteOnExit(); final String tempDirectory = tempPath.getCanonicalPath(); if (frameworkResource != null) { extractResource(frameworkResource, frameworkLibName, tempDirectory); } else { log( frameworkResourceName + " not found. This is fine assuming " + jniResourceName + " is not built to depend on it."); } System.load(extractResource(jniResource, jniLibName, tempDirectory)); } catch (IOException e) { throw new UnsatisfiedLinkError( String.format( "Unable to extract native library into a temporary file (%s)", e.toString())); } } private static boolean tryLoadLibrary() { try { System.loadLibrary(JNI_LIBNAME); return true; } catch (UnsatisfiedLinkError e) { log("tryLoadLibraryFailed: " + e.getMessage()); return false; } } private static boolean isLoaded() { try { TensorFlow.version(); log("isLoaded: true"); return true; } catch (UnsatisfiedLinkError e) { return false; } } private static boolean resourceExists(String baseName) { return NativeLibrary.class.getClassLoader().getResource(makeResourceName(baseName)) != null; } private static String getVersionedLibraryName(String libFilename) { final String versionName = getMajorVersionNumber(); // If we're on darwin, the versioned libraries look like blah.1.dylib. final String darwinSuffix = ".dylib"; if (libFilename.endsWith(darwinSuffix)) { final String prefix = libFilename.substring(0, libFilename.length() - darwinSuffix.length()); if (versionName != null) { final String darwinVersionedLibrary = prefix + "." + versionName + darwinSuffix; if (resourceExists(darwinVersionedLibrary)) { return darwinVersionedLibrary; } } else { // If we're here, we're on darwin, but we couldn't figure out the major version number. We // already tried the library name without any changes, but let's do one final try for the // library with a .so suffix. final String darwinSoName = prefix + ".so"; if (resourceExists(darwinSoName)) { return darwinSoName; } } } else if (libFilename.endsWith(".so")) { // Libraries ending in ".so" are versioned like "libfoo.so.1", so try that. final String versionedSoName = libFilename + "." + versionName; if (versionName != null && resourceExists(versionedSoName)) { return versionedSoName; } } // Otherwise, we've got no idea. return libFilename; } /** * Returns the major version number of this TensorFlow Java API, or {@code null} if it cannot be * determined. */ private static String getMajorVersionNumber() { InputStream resourceStream = NativeLibrary.class.getClassLoader().getResourceAsStream("tensorflow-version-info"); if (resourceStream == null) { return null; } try { Properties props = new Properties(); props.load(resourceStream); String version = props.getProperty("version"); // expecting a string like 1.14.0, we want to get the first '1'. int dotIndex; if (version == null || (dotIndex = version.indexOf('.')) == -1) { return null; } String majorVersion = version.substring(0, dotIndex); try { Integer.parseInt(majorVersion); return majorVersion; } catch (NumberFormatException unused) { return null; } } catch (IOException e) { log("failed to load tensorflow version info."); return null; } } private static String extractResource( InputStream resource, String resourceName, String extractToDirectory) throws IOException { final File dst = new File(extractToDirectory, resourceName); dst.deleteOnExit(); final String dstPath = dst.toString(); log("extracting native library to: " + dstPath); final long nbytes = copy(resource, dst); log(String.format("copied %d bytes to %s", nbytes, dstPath)); return dstPath; } private static String os() { final String p = System.getProperty("os.name").toLowerCase(); if (p.contains("linux")) { return "linux"; } else if (p.contains("os x") || p.contains("darwin")) { return "darwin"; } else if (p.contains("windows")) { return "windows"; } else { return p.replaceAll("\\s", ""); } } private static String architecture() { final String arch = System.getProperty("os.arch").toLowerCase(); return (arch.equals("amd64")) ? "x86_64" : arch; } private static void log(String msg) { if (DEBUG) { System.err.println("org.tensorflow.NativeLibrary: " + msg); } } private static String makeResourceName(String baseName) { return "org/tensorflow/native/" + String.format("%s-%s/", os(), architecture()) + baseName; } private static long copy(InputStream src, File dstFile) throws IOException { FileOutputStream dst = new FileOutputStream(dstFile); try { byte[] buffer = new byte[1 << 20]; // 1MB long ret = 0; int n = 0; while ((n = src.read(buffer)) >= 0) { dst.write(buffer, 0, n); ret += n; } return ret; } finally { dst.close(); src.close(); } } // Shamelessly adapted from Guava to avoid using java.nio, for Android API // compatibility. private static File createTemporaryDirectory() { File baseDirectory = new File(System.getProperty("java.io.tmpdir")); String directoryName = "tensorflow_native_libraries-" + System.currentTimeMillis() + "-"; for (int attempt = 0; attempt < 1000; attempt++) { File temporaryDirectory = new File(baseDirectory, directoryName + attempt); if (temporaryDirectory.mkdir()) { return temporaryDirectory; } } throw new IllegalStateException( "Could not create a temporary directory (tried to make " + directoryName + "*) to extract TensorFlow native libraries."); } private NativeLibrary() {} }
tensorflow/tensorflow
tensorflow/java/src/main/java/org/tensorflow/NativeLibrary.java
402
/* * This project is licensed under the MIT license. Module model-view-viewmodel is using ZK framework licensed under LGPL (see lgpl-3.0.txt). * * The MIT License * Copyright © 2014-2022 Ilkka Seppälä * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.iluwatar.multiton; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import lombok.Getter; /** * Nazgul is a Multiton class. Nazgul instances can be queried using {@link #getInstance} method. */ public final class Nazgul { private static final Map<NazgulName, Nazgul> nazguls; @Getter private final NazgulName name; static { nazguls = new ConcurrentHashMap<>(); nazguls.put(NazgulName.KHAMUL, new Nazgul(NazgulName.KHAMUL)); nazguls.put(NazgulName.MURAZOR, new Nazgul(NazgulName.MURAZOR)); nazguls.put(NazgulName.DWAR, new Nazgul(NazgulName.DWAR)); nazguls.put(NazgulName.JI_INDUR, new Nazgul(NazgulName.JI_INDUR)); nazguls.put(NazgulName.AKHORAHIL, new Nazgul(NazgulName.AKHORAHIL)); nazguls.put(NazgulName.HOARMURATH, new Nazgul(NazgulName.HOARMURATH)); nazguls.put(NazgulName.ADUNAPHEL, new Nazgul(NazgulName.ADUNAPHEL)); nazguls.put(NazgulName.REN, new Nazgul(NazgulName.REN)); nazguls.put(NazgulName.UVATHA, new Nazgul(NazgulName.UVATHA)); } private Nazgul(NazgulName name) { this.name = name; } public static Nazgul getInstance(NazgulName name) { return nazguls.get(name); } }
iluwatar/java-design-patterns
multiton/src/main/java/com/iluwatar/multiton/Nazgul.java
403
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.bootstrap; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; import org.elasticsearch.common.ReferenceDocs; import java.lang.invoke.MethodHandles; import java.nio.file.Path; import java.util.Locale; /** * The Natives class is a wrapper class that checks if the classes necessary for calling native methods are available on * startup. If they are not available, this class will avoid calling code that loads these classes. */ final class Natives { /** no instantiation */ private Natives() {} private static final Logger logger = LogManager.getLogger(Natives.class); // marker to determine if the JNA class files are available to the JVM static final boolean JNA_AVAILABLE; static { boolean v = false; try { // load one of the main JNA classes to see if the classes are available. this does not ensure that all native // libraries are available, only the ones necessary by JNA to function MethodHandles.publicLookup().ensureInitialized(com.sun.jna.Native.class); v = true; } catch (IllegalAccessException e) { throw new AssertionError(e); } catch (UnsatisfiedLinkError e) { logger.warn( String.format( Locale.ROOT, "unable to load JNA native support library, native methods will be disabled. See %s", ReferenceDocs.EXECUTABLE_JNA_TMPDIR ), e ); } JNA_AVAILABLE = v; } static void tryMlockall() { if (JNA_AVAILABLE == false) { logger.warn("cannot mlockall because JNA is not available"); return; } JNANatives.tryMlockall(); } static void tryVirtualLock() { if (JNA_AVAILABLE == false) { logger.warn("cannot virtual lock because JNA is not available"); return; } JNANatives.tryVirtualLock(); } /** * Retrieves the short path form of the specified path. * * @param path the path * @return the short path name (or the original path if getting the short path name fails for any reason) */ static String getShortPathName(final String path) { if (JNA_AVAILABLE == false) { logger.warn("cannot obtain short path for [{}] because JNA is not available", path); return path; } return JNANatives.getShortPathName(path); } static void addConsoleCtrlHandler(ConsoleCtrlHandler handler) { if (JNA_AVAILABLE == false) { logger.warn("cannot register console handler because JNA is not available"); return; } JNANatives.addConsoleCtrlHandler(handler); } static boolean isMemoryLocked() { if (JNA_AVAILABLE == false) { return false; } return JNANatives.LOCAL_MLOCKALL; } static void tryInstallSystemCallFilter(Path tmpFile) { if (JNA_AVAILABLE == false) { logger.warn("cannot install system call filter because JNA is not available"); return; } JNANatives.tryInstallSystemCallFilter(tmpFile); } static void trySetMaxNumberOfThreads() { if (JNA_AVAILABLE == false) { logger.warn("cannot getrlimit RLIMIT_NPROC because JNA is not available"); return; } JNANatives.trySetMaxNumberOfThreads(); } static void trySetMaxSizeVirtualMemory() { if (JNA_AVAILABLE == false) { logger.warn("cannot getrlimit RLIMIT_AS because JNA is not available"); return; } JNANatives.trySetMaxSizeVirtualMemory(); } static void trySetMaxFileSize() { if (JNA_AVAILABLE == false) { logger.warn("cannot getrlimit RLIMIT_FSIZE because JNA is not available"); return; } JNANatives.trySetMaxFileSize(); } static boolean isSystemCallFilterInstalled() { if (JNA_AVAILABLE == false) { return false; } return JNANatives.LOCAL_SYSTEM_CALL_FILTER; } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/bootstrap/Natives.java
405
import java.io.*; import java.lang.Integer.*; import java.util.*; import java.util.stream.*; import java.lang.StringBuilder; import java.util.concurrent.CountDownLatch; //////////////////////////////// Solve Sudoku Puzzles //////////////////////////////// //////////////////////////////// @author Peter Norvig //////////////////////////////// /** There are two representations of puzzles that we will use: ** 1. A gridstring is 81 chars, with characters '0' or '.' for blank and '1' to '9' for digits. ** 2. A puzzle grid is an int[81] with a digit d (1-9) represented by the integer (1 << (d - 1)); ** that is, a bit pattern that has a single 1 bit representing the digit. ** A blank is represented by the OR of all the digits 1-9, meaning that any digit is possible. ** While solving the puzzle, some of these digits are eliminated, leaving fewer possibilities. ** The puzzle is solved when every square has only a single possibility. ** ** Search for a solution with `search`: ** - Fill an empty square with a guessed digit and do constraint propagation. ** - If the guess is consistent, search deeper; if not, try a different guess for the square. ** - If all guesses fail, back up to the previous level. ** - In selecting an empty square, we pick one that has the minimum number of possible digits. ** - To be able to back up, we need to keep the grid from the previous recursive level. ** But we only need to keep one grid for each level, so to save garbage collection, ** we pre-allocate one grid per level (there are 81 levels) in a `gridpool`. ** Do constraint propagation with `arcConsistent`, `dualConsistent`, and `nakedPairs`. **/ public class Sudoku { //////////////////////////////// main; command line options ////////////////////////////// static final String usage = String.join("\n", "usage: java Sudoku -(no)[fghnprstuv] | -[RT]<number> | <filename> ...", "E.g., -v turns verify flag on, -nov turns it off. -R and -T require a number. The options:\n", " -f(ile) Print summary stats for each file (default on)", " -g(rid) Print each puzzle grid and solution grid (default off)", " -h(elp) Print this usage message", " -n(aked) Run naked pairs (default on)", " -p(uzzle) Print summary stats for each puzzle (default off)", " -r(everse) Solve the reverse of each puzzle as well as each puzzle itself (default off)", " -s(earch) Run search (default on, but some puzzles can be solved with CSP methods alone)", " -t(hread) Print summary stats for each thread (default off)", " -u(nitTest)Run a suite of unit tests (default off)", " -v(erify) Verify each solution is valid (default on)", " -T<number> Concurrently run <number> threads (default 26)", " -R<number> Repeat each puzzle <number> times (default 1)", " <filename> Solve all puzzles in filename, which has one puzzle per line"); boolean printFileStats = true; // -f boolean printGrid = false; // -g boolean runNakedPairs = true; // -n boolean printPuzzleStats = false; // -p boolean reversePuzzle = false; // -r boolean runSearch = true; // -s boolean printThreadStats = false; // -t boolean verifySolution = true; // -v int nThreads = 26; // -T int repeat = 1; // -R int backtracks = 0; // count total backtracks /** Parse command line args and solve puzzles in files. **/ public static void main(String[] args) throws IOException { Sudoku s = new Sudoku(); for (String arg: args) { if (!arg.startsWith("-")) { s.solveFile(arg); } else { boolean value = !arg.startsWith("-no"); switch(arg.charAt(value ? 1 : 3)) { case 'f': s.printFileStats = value; break; case 'g': s.printGrid = value; break; case 'h': System.out.println(usage); break; case 'n': s.runNakedPairs = value; break; case 'p': s.printPuzzleStats = value; break; case 'r': s.reversePuzzle = value; break; case 's': s.runSearch = value; break; case 't': s.printThreadStats = value; break; case 'u': s.runUnitTests(); break; case 'v': s.verifySolution = value; break; case 'T': s.nThreads = Integer.parseInt(arg.substring(2)); break; case 'R': s.repeat = Integer.parseInt(arg.substring(2)); break; default: System.out.println("Unrecognized option: " + arg + "\n" + usage); } } } } //////////////////////////////// Handling Lists of Puzzles //////////////////////////////// /** Solve all the puzzles in a file. Report timing statistics. **/ void solveFile(String filename) throws IOException { List<int[]> grids = readFile(filename); long startFileTime = System.nanoTime(); switch(nThreads) { case 1: solveList(grids); break; default: solveListThreaded(grids, nThreads); break; } if (printFileStats) printStats(grids.size() * repeat, startFileTime, filename); } /** Solve a list of puzzles in a single thread. ** repeat -R<number> times; print each puzzle's stats if -p; print grid if -g; verify if -v. **/ void solveList(List<int[]> grids) { int[] puzzle = new int[N * N]; // Used to save a copy of the original grid int[][] gridpool = new int[N * N][N * N]; // Reuse grids during the search for (int g=0; g<grids.size(); ++g) { int grid[] = grids.get(g); System.arraycopy(grid, 0, puzzle, 0, grid.length); for (int i = 0; i < repeat; ++i) { long startTime = printPuzzleStats ? System.nanoTime() : 0; int[] solution = initialize(grid); // All the real work is if (runSearch) solution = search(solution, gridpool, 0); // on these 2 lines. if (printPuzzleStats) { printStats(1, startTime, "Puzzle " + (g + 1)); } if (i == 0 && (printGrid || (verifySolution && !verify(solution, puzzle)))) { printGrids("Puzzle " + (g + 1), grid, solution); } } } } /** Break a list of puzzles into nThreads sublists and solve each sublist in a separate thread. **/ void solveListThreaded(List<int[]> grids, int nThreads) { try { final long startTime = System.nanoTime(); int nGrids = grids.size(); final CountDownLatch latch = new CountDownLatch(nThreads); int size = nGrids / nThreads; for (int c = 0; c < nThreads; ++c) { int end = c == nThreads - 1 ? nGrids : (c + 1) * size; final List<int[]> sublist = grids.subList(c * size, end); new Thread() { public void run() { solveList(sublist); latch.countDown(); if (printThreadStats) { printStats(repeat * sublist.size(), startTime, "Thread"); } } }.start(); } latch.await(); // Wait for all threads to finish } catch (InterruptedException e) { System.err.println("And you may ask yourself, 'Well, how did I get here?'"); } } //////////////////////////////// Utility functions //////////////////////////////// /** Return an array of all squares in the intersection of these rows and cols **/ int[] cross(int[] rows, int[] cols) { int[] result = new int[rows.length * cols.length]; int i = 0; for (int r: rows) { for (int c: cols) { result[i++] = N * r + c; } } return result; } /** Return true iff item is an element of array, or of array[0:end]. **/ boolean member(int item, int[] array) { return member(item, array, array.length); } boolean member(int item, int[] array, int end) { for (int i = 0; i<end; ++i) { if (array[i] == item) { return true; } } return false; } //////////////////////////////// Constants //////////////////////////////// final int N = 9; // Number of cells on a side of grid. final int[] DIGITS = {1<<0, 1<<1, 1<<2, 1<<3, 1<<4, 1<<5, 1<<6, 1<<7, 1<<8}; final int ALL_DIGITS = Integer.parseInt("111111111", 2); final int[] ROWS = IntStream.range(0, N).toArray(); final int[] COLS = ROWS; final int[] SQUARES = IntStream.range(0, N * N).toArray(); final int[][] BLOCKS = {{0, 1, 2}, {3, 4, 5}, {6, 7, 8}}; final int[][] ALL_UNITS = new int[3 * N][]; final int[][][] UNITS = new int[N * N][3][N]; final int[][] PEERS = new int[N * N][20]; final int[] NUM_DIGITS = new int[ALL_DIGITS + 1]; final int[] HIGHEST_DIGIT = new int[ALL_DIGITS + 1]; { // Initialize ALL_UNITS to be an array of the 27 units: rows, columns, and blocks int i = 0; for (int r: ROWS) {ALL_UNITS[i++] = cross(new int[] {r}, COLS); } for (int c: COLS) {ALL_UNITS[i++] = cross(ROWS, new int[] {c}); } for (int[] rb: BLOCKS) {for (int[] cb: BLOCKS) {ALL_UNITS[i++] = cross(rb, cb); } } // Initialize each UNITS[s] to be an array of the 3 units for square s. for (int s: SQUARES) { i = 0; for (int[] u: ALL_UNITS) { if (member(s, u)) UNITS[s][i++] = u; } } // Initialize each PEERS[s] to be an array of the 20 squares that are peers of square s. for (int s: SQUARES) { i = 0; for (int[] u: UNITS[s]) { for (int s2: u) { if (s2 != s && !member(s2, PEERS[s], i)) { PEERS[s][i++] = s2; } } } } // Initialize NUM_DIGITS[val] to be the number of 1 bits in the bitset val // and HIGHEST_DIGIT[val] to the highest bit set in the bitset val for (int val = 0; val <= ALL_DIGITS; val++) { NUM_DIGITS[val] = Integer.bitCount(val); HIGHEST_DIGIT[val] = Integer.highestOneBit(val); } } //////////////////////////////// Search algorithm //////////////////////////////// /** Search for a solution to grid. If there is an unfilled square, select one ** and try--that is, search recursively--every possible digit for the square. **/ int[] search(int[] grid, int[][] gridpool, int level) { if (grid == null) { return null; } int s = select_square(grid); if (s == -1) { return grid; // No squares to select means we are done! } for (int d: DIGITS) { // For each possible digit d that could fill square s, try it if ((d & grid[s]) > 0) { // Copy grid's contents into gridpool[level], and use that at the next level System.arraycopy(grid, 0, gridpool[level], 0, grid.length); int[] result = search(fill(gridpool[level], s, d), gridpool, level + 1); if (result != null) { return result; } backtracks += 1; } } return null; } /** Verify that grid is a solution to the puzzle. **/ boolean verify(int[] grid, int[] puzzle) { if (grid == null) { return false; } // Check that all squares have a single digit, and // no filled square in the puzzle was changed in the solution. for (int s: SQUARES) { if ((NUM_DIGITS[grid[s]] != 1) || (NUM_DIGITS[puzzle[s]] == 1 && grid[s] != puzzle[s])) { return false; } } // Check that each unit is a permutation of digits for (int[] u: ALL_UNITS) { int unit_digits = 0; // All the digits in a unit. for (int s : u) {unit_digits |= grid[s]; } if (unit_digits != ALL_DIGITS) { return false; } } return true; } /** Choose an unfilled square with the minimum number of possible values. ** If all squares are filled, return -1 (which means the puzzle is complete). **/ int select_square(int[] grid) { int square = -1; int min = N + 1; for (int s: SQUARES) { int c = NUM_DIGITS[grid[s]]; if (c == 2) { return s; // Can't get fewer than 2 possible digits } else if (c > 1 && c < min) { square = s; min = c; } } return square; } /** fill grid[s] = d. If this leads to contradiction, return null. **/ int[] fill(int[] grid, int s, int d) { if ((grid == null) || ((grid[s] & d) == 0)) { return null; } // d not possible for grid[s] grid[s] = d; for (int p: PEERS[s]) { if (!eliminate(grid, p, d)) { // If we can't eliminate d from all peers of s, then fail return null; } } return grid; } /** Eliminate digit d as a possibility for grid[s]. ** Run the 3 constraint propagation routines. ** If constraint propagation detects a contradiction, return false. **/ boolean eliminate(int[] grid, int s, int d) { if ((grid[s] & d) == 0) { return true; } // d already eliminated from grid[s] grid[s] -= d; return arc_consistent(grid, s) && dual_consistent(grid, s, d) && naked_pairs(grid, s); } //////////////////////////////// Constraint Propagation //////////////////////////////// /** Check if square s is consistent: that is, it has multiple possible values, or it has ** one possible value which we can consistently fill. **/ boolean arc_consistent(int[] grid, int s) { int count = NUM_DIGITS[grid[s]]; return count >= 2 || (count == 1 && (fill(grid, s, grid[s]) != null)); } /** After we eliminate d from possibilities for grid[s], check each unit of s ** and make sure there is some position in the unit where d can go. ** If there is only one possible place for d, fill it with d. **/ boolean dual_consistent(int[] grid, int s, int d) { for (int[] u: UNITS[s]) { int dPlaces = 0; // The number of possible places for d within unit u int dplace = -1; // Try to find a place in the unit where d can go for (int s2: u) { if ((grid[s2] & d) > 0) { // s2 is a possible place for d dPlaces++; if (dPlaces > 1) break; dplace = s2; } } if (dPlaces == 0 || (dPlaces == 1 && (fill(grid, dplace, d) == null))) { return false; } } return true; } /** Look for two squares in a unit with the same two possible values, and no other values. ** For example, if s and s2 both have the possible values 8|9, then we know that 8 and 9 ** must go in those two squares. We don't know which is which, but we can eliminate ** 8 and 9 from any other square s3 that is in the unit. **/ boolean naked_pairs(int[] grid, int s) { if (!runNakedPairs) { return true; } int val = grid[s]; if (NUM_DIGITS[val] != 2) { return true; } // Doesn't apply for (int s2: PEERS[s]) { if (grid[s2] == val) { // s and s2 are a naked pair; find what unit(s) they share for (int[] u: UNITS[s]) { if (member(s2, u)) { for (int s3: u) { // s3 can't have either of the values in val (e.g. 8|9) if (s3 != s && s3 != s2) { int d = HIGHEST_DIGIT[val]; int d2 = val - d; if (!eliminate(grid, s3, d) || !eliminate(grid, s3, d2)) { return false; } } } } } } } return true; } //////////////////////////////// Input //////////////////////////////// /** The method `readFile` reads one puzzle per file line and returns a List of puzzle grids. **/ List<int[]> readFile(String filename) throws IOException { BufferedReader in = new BufferedReader(new FileReader(filename)); List<int[]> grids = new ArrayList<int[]>(1000); String gridstring; while ((gridstring = in.readLine()) != null) { grids.add(parseGrid(gridstring)); if (reversePuzzle) { grids.add(parseGrid(new StringBuilder(gridstring).reverse().toString())); } } return grids; } /** Parse a gridstring into a puzzle grid: an int[] with values DIGITS[0-9] or ALL_DIGITS. **/ int[] parseGrid(String gridstring) { int[] grid = new int[N * N]; int s = 0; for (int i = 0; i<gridstring.length(); ++i) { char c = gridstring.charAt(i); if ('1' <= c && c <= '9') { grid[s++] = DIGITS[c - '1']; // A single-bit set to represent a digit } else if (c == '0' || c == '.') { grid[s++] = ALL_DIGITS; // Any digit is possible } } assert s == N * N; return grid; } /** Initialize a grid from a puzzle. ** First initialize every square in the new grid to ALL_DIGITS, meaning any value is possible. ** Then, call `fill` on the puzzle's filled squares to initiate constraint propagation. **/ int[] initialize(int[] puzzle) { int[] grid = new int[N * N]; Arrays.fill(grid, ALL_DIGITS); for (int s: SQUARES) { if (puzzle[s] != ALL_DIGITS) { fill(grid, s, puzzle[s]); } } return grid; } //////////////////////////////// Output and Tests //////////////////////////////// boolean headerPrinted = false; /** Print stats on puzzles solved, average time, frequency, threads used, and name. **/ void printStats(int nGrids, long startTime, String name) { double usecs = (System.nanoTime() - startTime) / 1000.; String line = String.format("%7d %6.1f %7.3f %7d %10.1f %s", nGrids, usecs / nGrids, 1000 * nGrids / usecs, nThreads, backtracks * 1. / nGrids, name); synchronized (this) { // So that printing from different threads doesn't get garbled if (!headerPrinted) { System.out.println("Puzzles μsec KHz Threads Backtracks Name\n" + "======= ====== ======= ======= ========== ===="); headerPrinted = true; } System.out.println(line); backtracks = 0; } } /** Print the original puzzle grid and the solution grid. **/ void printGrids(String name, int[] puzzle, int[] solution) { String bar = "------+-------+------"; String gap = " "; // Space between the puzzle grid and solution grid if (solution == null) solution = new int[N * N]; synchronized (this) { // So that printing from different threads doesn't get garbled System.out.format("\n%-22s%s%s\n", name + ":", gap, (verify(solution, puzzle) ? "Solution:" : "FAILED:")); for (int r = 0; r < N; ++r) { System.out.println(rowString(puzzle, r) + gap + rowString(solution, r)); if (r == 2 || r == 5) System.out.println(bar + gap + " " + bar); } } } /** Return a String representing a row of this puzzle. **/ String rowString(int[] grid, int r) { String row = ""; for (int s = r * 9; s < (r + 1) * 9; ++s) { row += (char) ((NUM_DIGITS[grid[s]] == 9) ? '.' : (NUM_DIGITS[grid[s]] != 1) ? '?' : ('1' + Integer.numberOfTrailingZeros(grid[s]))); row += (s % 9 == 2 || s % 9 == 5 ? " | " : " "); } return row; } /** Unit Tests. Just getting started with these. **/ void runUnitTests() { assert N == 9; assert SQUARES.length == 81; for (int s: SQUARES) { assert UNITS[s].length == 3; assert PEERS[s].length == 20; } assert Arrays.equals(PEERS[19], new int[] {18, 20, 21, 22, 23, 24, 25, 26, 1, 10, 28, 37, 46, 55, 64, 73, 0, 2, 9, 11}); assert Arrays.deepToString(UNITS[19]).equals( "[[18, 19, 20, 21, 22, 23, 24, 25, 26], [1, 10, 19, 28, 37, 46, 55, 64, 73], [0, 1, 2, 9, 10, 11, 18, 19, 20]]"); System.out.println("Unit tests pass."); } }
norvig/pytudes
ipynb/Sudoku.java
406
/* * 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 static com.google.common.base.StandardSystemProperty.JAVA_IO_TMPDIR; import static com.google.common.base.StandardSystemProperty.USER_NAME; import static com.google.common.base.Throwables.throwIfUnchecked; import static java.nio.file.attribute.AclEntryFlag.DIRECTORY_INHERIT; import static java.nio.file.attribute.AclEntryFlag.FILE_INHERIT; import static java.nio.file.attribute.AclEntryType.ALLOW; import static java.nio.file.attribute.PosixFilePermissions.asFileAttribute; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtIncompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.collect.ImmutableList; import com.google.j2objc.annotations.J2ObjCIncompatible; import java.io.File; import java.io.IOException; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.nio.file.FileSystems; import java.nio.file.Paths; import java.nio.file.attribute.AclEntry; import java.nio.file.attribute.AclEntryPermission; import java.nio.file.attribute.FileAttribute; import java.nio.file.attribute.PosixFilePermissions; import java.nio.file.attribute.UserPrincipal; import java.util.EnumSet; import java.util.Set; /** * Creates temporary files and directories whose permissions are restricted to the current user or, * in the case of Android, the current app. If that is not possible (as is the case under the very * old Android Ice Cream Sandwich release), then this class throws an exception instead of creating * a file or directory that would be more accessible. */ @J2ktIncompatible @GwtIncompatible @J2ObjCIncompatible @ElementTypesAreNonnullByDefault abstract class TempFileCreator { static final TempFileCreator INSTANCE = pickSecureCreator(); /** * @throws IllegalStateException if the directory could not be created (to implement the contract * of {@link Files#createTempDir()}, such as if the system does not support creating temporary * directories securely */ abstract File createTempDir(); abstract File createTempFile(String prefix) throws IOException; private static TempFileCreator pickSecureCreator() { try { Class.forName("java.nio.file.Path"); return new JavaNioCreator(); } catch (ClassNotFoundException runningUnderAndroid) { // Try another way. } try { int version = (int) Class.forName("android.os.Build$VERSION").getField("SDK_INT").get(null); int jellyBean = (int) Class.forName("android.os.Build$VERSION_CODES").getField("JELLY_BEAN").get(null); /* * I assume that this check can't fail because JELLY_BEAN will be present only if we're * running under Jelly Bean or higher. But it seems safest to check. */ if (version < jellyBean) { return new ThrowingCreator(); } // Don't merge these catch() blocks, let alone use ReflectiveOperationException directly: // b/65343391 } catch (NoSuchFieldException e) { // The JELLY_BEAN field doesn't exist because we're running on a version before Jelly Bean :) return new ThrowingCreator(); } catch (ClassNotFoundException e) { // Should be impossible, but we want to return *something* so that class init succeeds. return new ThrowingCreator(); } catch (IllegalAccessException e) { // ditto return new ThrowingCreator(); } // Android isolates apps' temporary directories since Jelly Bean: // https://github.com/google/guava/issues/4011#issuecomment-770020802 // So we can create files there with any permissions and still get security from the isolation. return new JavaIoCreator(); } /** * Creates the permissions normally used for Windows filesystems, looking up the user afresh, even * if previous calls have initialized the {@code PermissionSupplier} fields. * * <p>This lets us test the effects of different values of the {@code user.name} system property * without needing a separate VM or classloader. */ @IgnoreJRERequirement // used only when Path is available (and only from tests) @VisibleForTesting static void testMakingUserPermissionsFromScratch() throws IOException { // All we're testing is whether it throws. FileAttribute<?> unused = JavaNioCreator.userPermissions().get(); } @IgnoreJRERequirement // used only when Path is available private static final class JavaNioCreator extends TempFileCreator { @Override File createTempDir() { try { return java.nio.file.Files.createTempDirectory( Paths.get(JAVA_IO_TMPDIR.value()), /* prefix= */ null, directoryPermissions.get()) .toFile(); } catch (IOException e) { throw new IllegalStateException("Failed to create directory", e); } } @Override File createTempFile(String prefix) throws IOException { return java.nio.file.Files.createTempFile( Paths.get(JAVA_IO_TMPDIR.value()), /* prefix= */ prefix, /* suffix= */ null, filePermissions.get()) .toFile(); } @IgnoreJRERequirement // see enclosing class (whose annotation Animal Sniffer ignores here...) private interface PermissionSupplier { FileAttribute<?> get() throws IOException; } private static final PermissionSupplier filePermissions; private static final PermissionSupplier directoryPermissions; static { Set<String> views = FileSystems.getDefault().supportedFileAttributeViews(); if (views.contains("posix")) { filePermissions = () -> asFileAttribute(PosixFilePermissions.fromString("rw-------")); directoryPermissions = () -> asFileAttribute(PosixFilePermissions.fromString("rwx------")); } else if (views.contains("acl")) { filePermissions = directoryPermissions = userPermissions(); } else { filePermissions = directoryPermissions = () -> { throw new IOException("unrecognized FileSystem type " + FileSystems.getDefault()); }; } } private static PermissionSupplier userPermissions() { try { UserPrincipal user = FileSystems.getDefault() .getUserPrincipalLookupService() .lookupPrincipalByName(getUsername()); ImmutableList<AclEntry> acl = ImmutableList.of( AclEntry.newBuilder() .setType(ALLOW) .setPrincipal(user) .setPermissions(EnumSet.allOf(AclEntryPermission.class)) .setFlags(DIRECTORY_INHERIT, FILE_INHERIT) .build()); FileAttribute<ImmutableList<AclEntry>> attribute = new FileAttribute<ImmutableList<AclEntry>>() { @Override public String name() { return "acl:acl"; } @Override public ImmutableList<AclEntry> value() { return acl; } }; return () -> attribute; } catch (IOException e) { // We throw a new exception each time so that the stack trace is right. return () -> { throw new IOException("Could not find user", e); }; } } private static String getUsername() { /* * https://github.com/google/guava/issues/6634: ProcessHandle has more accurate information, * but that class isn't available under all environments that we support. We use it if * available and fall back if not. */ String fromSystemProperty = requireNonNull(USER_NAME.value()); try { Class<?> processHandleClass = Class.forName("java.lang.ProcessHandle"); Class<?> processHandleInfoClass = Class.forName("java.lang.ProcessHandle$Info"); Class<?> optionalClass = Class.forName("java.util.Optional"); /* * We don't *need* to use reflection to access Optional: It's available on all JDKs we * support, and Android code won't get this far, anyway, because ProcessHandle is * unavailable. But given how much other reflection we're using, we might as well use it * here, too, so that we don't need to also suppress an AndroidApiChecker error. */ Method currentMethod = processHandleClass.getMethod("current"); Method infoMethod = processHandleClass.getMethod("info"); Method userMethod = processHandleInfoClass.getMethod("user"); Method orElseMethod = optionalClass.getMethod("orElse", Object.class); Object current = currentMethod.invoke(null); Object info = infoMethod.invoke(current); Object user = userMethod.invoke(info); return (String) requireNonNull(orElseMethod.invoke(user, fromSystemProperty)); } catch (ClassNotFoundException runningUnderAndroidOrJava8) { /* * I'm not sure that we could actually get here for *Android*: I would expect us to enter * the POSIX code path instead. And if we tried this code path, we'd have trouble unless we * were running under a new enough version of Android to support NIO. * * So this is probably just the "Windows Java 8" case. In that case, if we wanted *another* * layer of fallback before consulting the system property, we could try * com.sun.security.auth.module.NTSystem. * * But for now, we use the value from the system property as our best guess. */ return fromSystemProperty; } catch (InvocationTargetException e) { throwIfUnchecked(e.getCause()); // in case it's an Error or something return fromSystemProperty; // should be impossible } catch (NoSuchMethodException shouldBeImpossible) { return fromSystemProperty; } catch (IllegalAccessException shouldBeImpossible) { /* * We don't merge these into `catch (ReflectiveOperationException ...)` or an equivalent * multicatch because ReflectiveOperationException isn't available under Android: * b/124188803 */ return fromSystemProperty; } } } private static final class JavaIoCreator extends TempFileCreator { @Override File createTempDir() { File baseDir = new File(JAVA_IO_TMPDIR.value()); @SuppressWarnings("GoodTime") // reading system time without TimeSource String baseName = System.currentTimeMillis() + "-"; for (int counter = 0; counter < TEMP_DIR_ATTEMPTS; counter++) { File tempDir = new File(baseDir, baseName + counter); if (tempDir.mkdir()) { return tempDir; } } throw new IllegalStateException( "Failed to create directory within " + TEMP_DIR_ATTEMPTS + " attempts (tried " + baseName + "0 to " + baseName + (TEMP_DIR_ATTEMPTS - 1) + ')'); } @Override File createTempFile(String prefix) throws IOException { return File.createTempFile( /* prefix= */ prefix, /* suffix= */ null, /* directory= */ null /* defaults to java.io.tmpdir */); } /** Maximum loop count when creating temp directories. */ private static final int TEMP_DIR_ATTEMPTS = 10000; } private static final class ThrowingCreator extends TempFileCreator { private static final String MESSAGE = "Guava cannot securely create temporary files or directories under SDK versions before" + " Jelly Bean. You can create one yourself, either in the insecure default directory" + " or in a more secure directory, such as context.getCacheDir(). For more information," + " see the Javadoc for Files.createTempDir()."; @Override File createTempDir() { throw new IllegalStateException(MESSAGE); } @Override File createTempFile(String prefix) throws IOException { throw new IOException(MESSAGE); } } private TempFileCreator() {} }
google/guava
guava/src/com/google/common/io/TempFileCreator.java
408
import java.io.*; import java.util.*; public class Dataset implements Debuggable { public static String KEY_SEPARATION_TYPES[] = {"@TABULATION", "@COMMA"}; public static String KEY_SEPARATION_STRING[] = {"\t", ","}; public static int SEPARATION_INDEX = 1; public static String DEFAULT_DIR = "Datasets", SEP = "/", KEY_COMMENT = "//"; public static String KEY_DIRECTORY = "@DIRECTORY"; public static String KEY_PREFIX = "@PREFIX"; public static String KEY_ALGORITHM = "@ALGORITHM"; public static String KEY_NCT = "@NCT"; public static String KEY_NOISE = "@ETA_NOISE"; public static String KEY_CHECK_STRATIFIED_LABELS = "@CHECK_STRATIFIED_LABELS"; public static String START_KEYWORD = "@"; public static String FIT_CLASS = "@FIT_CLASS"; public static String[] FIT_CLASS_MODALITIES = {"NONE", "MEAN", "MEDIAN", "MINMAX", "BINARY"}; // NONE means the problem has two class modalities -> {-1, 1}, default value // Otherwise, classes are fit in {-1,1} the keyword gives the meaning of the 0 value for the class // : // * MEAN -> classes are translated so that mean = 0 and then shrunk to fit in [-1,1] // * MEDIAN -> classes are translated so that median = 0 and then shrunk to fit in [-1,1] // * MINMAX -> classes are translated so that (min+max)/2 = 0 and then shrunk to fit in [-1,1] // * BINARY -> classes are translated so that mean = 0 and then BINARIZED in {-1, +1} with signs public static int DEFAULT_INDEX_FIT_CLASS = 0; public static int INDEX_FIT_CLASS(String s) { int i; for (i = 0; i < FIT_CLASS_MODALITIES.length; i++) if (s.equals(FIT_CLASS_MODALITIES[i])) return i; Dataset.perror("Value " + s + " for keyword " + FIT_CLASS + " not recognized"); return -1; } public static double TRANSLATE_SHRINK( double v, double translate_v, double min_v, double max_v, double max_m) { if ((v < min_v) || (v > max_v)) Dataset.perror("Value " + v + " is not in the interval [" + min_v + ", " + max_v + "]"); if (max_v < min_v) Dataset.perror("Max " + max_v + " < Min " + min_v); if (max_v == min_v) return v; double delta = (v - translate_v); double mm; if (Math.abs(max_v) > Math.abs(min_v)) mm = Math.abs(max_v - translate_v); else mm = Math.abs(min_v - translate_v); return ((delta / mm) * max_m); } public static double CENTER(double v, double avg, double stddev) { if (stddev == 0.0) { Dataset.warning("Standard deviation is zero"); return 0.0; } return ((v - avg) / stddev); } public static String SUFFIX_FEATURES = "features"; public static String SUFFIX_EXAMPLES = "data"; int index_class, number_initial_features, number_real_features, number_examples_total; double eta_noise; // training noise in the LS model String nameFeatures, nameExamples, pathSave, domainName; Vector features, examples; // WARNING : features also includes class int[] index_observation_features_to_index_features; Vector stratified_sample, training_sample, test_sample; Domain myDS; public static void perror(String error_text) { System.out.println("\n" + error_text); System.out.println("\nExiting to system\n"); System.exit(1); } public static void warning(String warning_text) { System.out.println(" * WARNING * " + warning_text); } Dataset(String dir, String pref, Domain d, double eta) { myDS = d; eta_noise = eta; domainName = pref; nameFeatures = dir + SEP + pref + SEP + pref + "." + SUFFIX_FEATURES; nameExamples = dir + SEP + pref + SEP + pref + "." + SUFFIX_EXAMPLES; pathSave = dir + SEP + pref + SEP; } public void printFeatures() { int i; System.out.println(features.size() + " features : "); for (i = 0; i < features.size(); i++) System.out.println((Feature) features.elementAt(i)); System.out.println("Class index : " + index_class); } public void load_features() { FileReader e; BufferedReader br; StringTokenizer t; String dum, n, ty; Vector v = null; Vector dumv = new Vector(); int i, index = 0; features = new Vector(); index_class = -1; try { e = new FileReader(nameFeatures); br = new BufferedReader(e); while ((dum = br.readLine()) != null) { if ((dum.length() == 1) || ((dum.length() > 1) && (!dum.substring(0, KEY_COMMENT.length()).equals(KEY_COMMENT)))) { if (dum.substring(0, 1).equals(Dataset.START_KEYWORD)) { t = new StringTokenizer(dum, KEY_SEPARATION_STRING[SEPARATION_INDEX]); if (t.countTokens() < 2) Dataset.perror("No value for keyword " + t.nextToken()); n = t.nextToken(); if (n.equals(Dataset.FIT_CLASS)) Dataset.DEFAULT_INDEX_FIT_CLASS = Dataset.INDEX_FIT_CLASS(t.nextToken()); } else { t = new StringTokenizer(dum, KEY_SEPARATION_STRING[SEPARATION_INDEX]); if (t.countTokens() > 0) { n = t.nextToken(); ty = t.nextToken(); if (Feature.INDEX(ty) == Feature.CLASS_INDEX) { if (index_class != -1) Dataset.perror("At least two classes named such in feature file"); else index_class = index; } else { dumv.addElement(new Integer(index)); } if (Feature.HAS_MODALITIES(ty)) { v = new Vector(); while (t.hasMoreTokens()) v.addElement(t.nextToken()); } features.addElement(new Feature(n, ty, v)); index++; } } } } e.close(); } catch (IOException eee) { System.out.println( "Problem loading ." + SUFFIX_FEATURES + " file --- Check the access to file " + nameFeatures + "..."); System.exit(0); } index_observation_features_to_index_features = new int[dumv.size()]; for (i = 0; i < dumv.size(); i++) index_observation_features_to_index_features[i] = ((Integer) dumv.elementAt(i)).intValue(); Dataset.warning( "Class renormalization using method : " + Dataset.FIT_CLASS_MODALITIES[DEFAULT_INDEX_FIT_CLASS]); number_initial_features = features.size() - 1; if (Debug) System.out.println("Found " + features.size() + " features, including class"); } public void load_examples() { FileReader e; BufferedReader br; StringTokenizer t; String dum; Vector v = null; Double dd; examples = new Vector(); Example ee = null; int i, j, idd = 0, nex = 0; Vector<Vector<Double>> continuous_features_values = new Vector<>(); for (i = 0; i < features.size(); i++) if ((i != index_class) && (Feature.IS_CONTINUOUS(((Feature) features.elementAt(i)).type))) continuous_features_values.addElement(new Vector<Double>()); else continuous_features_values.addElement(null); // Computing the whole number of examples try { e = new FileReader(nameExamples); br = new BufferedReader(e); while ((dum = br.readLine()) != null) { if ((dum.length() == 1) || ((dum.length() > 1) && (!dum.substring(0, KEY_COMMENT.length()).equals(KEY_COMMENT)))) { t = new StringTokenizer(dum, KEY_SEPARATION_STRING[SEPARATION_INDEX]); if (t.countTokens() > 0) { nex++; } } } e.close(); } catch (IOException eee) { System.out.println( "Problem loading ." + SUFFIX_FEATURES + " file --- Check the access to file " + nameFeatures + "..."); System.exit(0); } if (SAVE_MEMORY) System.out.print(nex + " examples to load... "); number_examples_total = 0; try { e = new FileReader(nameExamples); br = new BufferedReader(e); while ((dum = br.readLine()) != null) { if ((dum.length() == 1) || ((dum.length() > 1) && (!dum.substring(0, KEY_COMMENT.length()).equals(KEY_COMMENT)))) { t = new StringTokenizer(dum, KEY_SEPARATION_STRING[SEPARATION_INDEX]); if (t.countTokens() > 0) { v = new Vector(); while (t.hasMoreTokens()) v.addElement(t.nextToken()); // v contains the class information ee = new Example(idd, v, index_class, features); number_examples_total++; examples.addElement(ee); number_real_features = ee.typed_features.size(); idd++; for (i = 0; i < features.size(); i++) if ((i != index_class) && (Feature.IS_CONTINUOUS(((Feature) features.elementAt(i)).type))) { dd = new Double(((Double) ee.typed_features.elementAt(i)).doubleValue()); if (!continuous_features_values.elementAt(i).contains(dd)) continuous_features_values.elementAt(i).addElement(dd); } if (SAVE_MEMORY) if (idd % (nex / 20) == 0) System.out.print(((idd / (nex / 20)) * 5) + "% " + myDS.memString() + " "); } } } e.close(); } catch (IOException eee) { System.out.println( "Problem loading ." + SUFFIX_EXAMPLES + " file --- Check the access to file " + nameExamples + "..."); System.exit(0); } if (number_examples_total != nex) Dataset.perror("Dataset.class :: mismatch in the number of examples"); if (SAVE_MEMORY) System.out.print("ok. \n"); double[] all_vals; for (i = 0; i < features.size(); i++) if ((i != index_class) && (Feature.IS_CONTINUOUS(((Feature) features.elementAt(i)).type))) { all_vals = new double[continuous_features_values.elementAt(i).size()]; for (j = 0; j < continuous_features_values.elementAt(i).size(); j++) all_vals[j] = continuous_features_values.elementAt(i).elementAt(j).doubleValue(); QuickSort.quicksort(all_vals); ((Feature) features.elementAt(i)).update_tests(all_vals); } // normalizing classes double[] all_classes = new double[number_examples_total]; for (i = 0; i < number_examples_total; i++) all_classes[i] = ((Example) examples.elementAt(i)).unnormalized_class; double min_c, max_c, tv; max_c = min_c = tv = 0.0; for (i = 0; i < number_examples_total; i++) { if ((i == 0) || (max_c < all_classes[i])) max_c = all_classes[i]; if ((i == 0) || (min_c > all_classes[i])) min_c = all_classes[i]; } if (DEFAULT_INDEX_FIT_CLASS == 0) { // checks that there is only two modalities for (i = 0; i < number_examples_total; i++) if ((all_classes[i] != min_c) && (all_classes[i] != max_c)) Dataset.perror( "class value " + all_classes[i] + " should be either " + min_c + " or " + max_c); tv = (min_c + max_c) / 2.0; } else if ((DEFAULT_INDEX_FIT_CLASS == 1) || (DEFAULT_INDEX_FIT_CLASS == 4)) { tv = 0.0; for (i = 0; i < number_examples_total; i++) tv += all_classes[i]; tv /= (double) number_examples_total; } else if (DEFAULT_INDEX_FIT_CLASS == 2) { tv = 0.0; QuickSort.quicksort(all_classes); tv = all_classes[number_examples_total / 2]; } else if (DEFAULT_INDEX_FIT_CLASS == 3) { tv = (min_c + max_c) / 2.0; } // end int errfound = 0; for (i = 0; i < number_examples_total; i++) { ee = (Example) examples.elementAt(i); ee.complete_normalized_class(tv, min_c, max_c, eta_noise); errfound += ee.checkFeatures(features, index_class); } if (errfound > 0) Dataset.perror( "Dataset.class :: found " + errfound + " errs for feature domains in examples. Please correct domains in .features file." + " "); if (Debug) System.out.println("Found " + examples.size() + " examples"); } public double getProportionExamplesSign(boolean positive) { int i; double cc, tot = 0.0; for (i = 0; i < number_examples_total; i++) { cc = ((Example) examples.elementAt(i)).normalized_class; if ((positive) && (cc >= 0.0)) tot++; else if ((!positive) && (cc < 0.0)) tot++; } tot /= (double) number_examples_total; return tot; } public double getProportionExamplesSign(Vector v, boolean positive) { int i; double cc, tot = 0.0; for (i = 0; i < v.size(); i++) { cc = ((Example) examples.elementAt(((Integer) v.elementAt(i)).intValue())).normalized_class; if ((positive) && (cc >= 0.0)) tot++; else if ((!positive) && (cc < 0.0)) tot++; } tot /= (double) number_examples_total; return tot; } public void generate_stratified_sample_with_check(boolean check_labels) { // stratifies sample and checks that each training sample has at least one example of each class // sign & samples are non trivial boolean check_ok = true; int i; Vector cts; double v; System.out.print( "Generating " + Dataset.NUMBER_STRATIFIED_CV + "-folds stratified sample ... "); if (!check_labels) generate_stratified_sample(); else { do { if (Debug) System.out.print( "Checking that each fold has at least one example of each class & is non trivial (no" + " variable with edges of the same sign) "); check_ok = true; generate_stratified_sample(); i = 0; do { cts = (Vector) training_sample.elementAt(i); v = getProportionExamplesSign(cts, true); if ((v == 0.0) || (v == 1.0)) check_ok = false; i++; if (Debug) System.out.print("."); } while ((i < training_sample.size()) && (check_ok)); if (Debug && check_ok) System.out.println("ok."); if (Debug && !check_ok) System.out.println("\nBad fold# " + (i - 1) + " Retrying"); } while (!check_ok); } System.out.print(" ok.\n"); } public void generate_stratified_sample() { Vector all = new Vector(); Vector all2 = new Vector(); Vector dumv, dumvtr, dumvte, refv; Random r = new Random(); int indexex = 0, indexse = 0; stratified_sample = new Vector(); int i, ir, j, k; for (i = 0; i < number_examples_total; i++) all.addElement(new Integer(i)); do { if (all.size() > 1) ir = r.nextInt(all.size()); else ir = 0; all2.addElement((Integer) all.elementAt(ir)); all.removeElementAt(ir); } while (all.size() > 0); for (i = 0; i < Dataset.NUMBER_STRATIFIED_CV; i++) stratified_sample.addElement(new Vector()); do { dumv = (Vector) stratified_sample.elementAt(indexse); dumv.addElement((Integer) all2.elementAt(indexex)); indexex++; indexse++; if (indexse >= Dataset.NUMBER_STRATIFIED_CV) indexse = 0; } while (indexex < number_examples_total); training_sample = new Vector(); test_sample = new Vector(); for (i = 0; i < Dataset.NUMBER_STRATIFIED_CV; i++) { dumvtr = new Vector(); dumvte = new Vector(); for (j = 0; j < Dataset.NUMBER_STRATIFIED_CV; j++) { dumv = (Vector) stratified_sample.elementAt(j); if (j == i) refv = dumvte; else refv = dumvtr; for (k = 0; k < dumv.size(); k++) refv.addElement((Integer) dumv.elementAt(k)); } training_sample.addElement(dumvtr); test_sample.addElement(dumvte); } } public int train_size(int fold) { return ((Vector) training_sample.elementAt(fold)).size(); } public int test_size(int fold) { return ((Vector) test_sample.elementAt(fold)).size(); } public Example train_example(int fold, int nex) { return (Example) examples.elementAt( ((Integer) ((Vector) training_sample.elementAt(fold)).elementAt(nex)).intValue()); } public Example test_example(int fold, int nex) { return (Example) examples.elementAt( ((Integer) ((Vector) test_sample.elementAt(fold)).elementAt(nex)).intValue()); } public void init_weights(String loss_name, int fold, double tt) { Example ee; int i; for (i = 0; i < train_size(fold); i++) { ee = train_example(fold, i); if (loss_name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) ee.current_boosting_weight = 1.0 / Math.pow((double) train_size(fold), 1.0 / (2.0 - tt)); // TEMPERED ADABOOST else if (loss_name.equals(Boost.KEY_NAME_LOG_LOSS)) ee.current_boosting_weight = 0.5; // LOGISTIC / LOG LOSS } } public double averageTrain_size() { int i; double val = 0.0; for (i = 0; i < NUMBER_STRATIFIED_CV; i++) val += (double) train_size(i); val /= (double) NUMBER_STRATIFIED_CV; return val; } }
google-research/google-research
tempered_boosting/Dataset.java
409
// ASM: a very small and fast Java bytecode manipulation framework // Copyright (c) 2000-2011 INRIA, France Telecom // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // 1. Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // 2. Redistributions in binary form must reproduce the above copyright // notice, this list of conditions and the following disclaimer in the // documentation and/or other materials provided with the distribution. // 3. Neither the name of the copyright holders nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. package org.springframework.asm; /** * An entry of the constant pool, of the BootstrapMethods attribute, or of the (ASM specific) type * table of a class. * * @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.4">JVMS * 4.4</a> * @see <a href="https://docs.oracle.com/javase/specs/jvms/se9/html/jvms-4.html#jvms-4.7.23">JVMS * 4.7.23</a> * @author Eric Bruneton */ abstract class Symbol { // Tag values for the constant pool entries (using the same order as in the JVMS). /** The tag value of CONSTANT_Class_info JVMS structures. */ static final int CONSTANT_CLASS_TAG = 7; /** The tag value of CONSTANT_Fieldref_info JVMS structures. */ static final int CONSTANT_FIELDREF_TAG = 9; /** The tag value of CONSTANT_Methodref_info JVMS structures. */ static final int CONSTANT_METHODREF_TAG = 10; /** The tag value of CONSTANT_InterfaceMethodref_info JVMS structures. */ static final int CONSTANT_INTERFACE_METHODREF_TAG = 11; /** The tag value of CONSTANT_String_info JVMS structures. */ static final int CONSTANT_STRING_TAG = 8; /** The tag value of CONSTANT_Integer_info JVMS structures. */ static final int CONSTANT_INTEGER_TAG = 3; /** The tag value of CONSTANT_Float_info JVMS structures. */ static final int CONSTANT_FLOAT_TAG = 4; /** The tag value of CONSTANT_Long_info JVMS structures. */ static final int CONSTANT_LONG_TAG = 5; /** The tag value of CONSTANT_Double_info JVMS structures. */ static final int CONSTANT_DOUBLE_TAG = 6; /** The tag value of CONSTANT_NameAndType_info JVMS structures. */ static final int CONSTANT_NAME_AND_TYPE_TAG = 12; /** The tag value of CONSTANT_Utf8_info JVMS structures. */ static final int CONSTANT_UTF8_TAG = 1; /** The tag value of CONSTANT_MethodHandle_info JVMS structures. */ static final int CONSTANT_METHOD_HANDLE_TAG = 15; /** The tag value of CONSTANT_MethodType_info JVMS structures. */ static final int CONSTANT_METHOD_TYPE_TAG = 16; /** The tag value of CONSTANT_Dynamic_info JVMS structures. */ static final int CONSTANT_DYNAMIC_TAG = 17; /** The tag value of CONSTANT_InvokeDynamic_info JVMS structures. */ static final int CONSTANT_INVOKE_DYNAMIC_TAG = 18; /** The tag value of CONSTANT_Module_info JVMS structures. */ static final int CONSTANT_MODULE_TAG = 19; /** The tag value of CONSTANT_Package_info JVMS structures. */ static final int CONSTANT_PACKAGE_TAG = 20; // Tag values for the BootstrapMethods attribute entries (ASM specific tag). /** The tag value of the BootstrapMethods attribute entries. */ static final int BOOTSTRAP_METHOD_TAG = 64; // Tag values for the type table entries (ASM specific tags). /** The tag value of a normal type entry in the (ASM specific) type table of a class. */ static final int TYPE_TAG = 128; /** * The tag value of an uninitialized type entry in the type table of a class. This type is used * for the normal case where the NEW instruction is before the &lt;init&gt; constructor call (in * bytecode offset order), i.e. when the label of the NEW instruction is resolved when the * constructor call is visited. If the NEW instruction is after the constructor call, use the * {@link #FORWARD_UNINITIALIZED_TYPE_TAG} tag value instead. */ static final int UNINITIALIZED_TYPE_TAG = 129; /** * The tag value of an uninitialized type entry in the type table of a class. This type is used * for the unusual case where the NEW instruction is after the &lt;init&gt; constructor call (in * bytecode offset order), i.e. when the label of the NEW instruction is not resolved when the * constructor call is visited. If the NEW instruction is before the constructor call, use the * {@link #UNINITIALIZED_TYPE_TAG} tag value instead. */ static final int FORWARD_UNINITIALIZED_TYPE_TAG = 130; /** The tag value of a merged type entry in the (ASM specific) type table of a class. */ static final int MERGED_TYPE_TAG = 131; // Instance fields. /** * The index of this symbol in the constant pool, in the BootstrapMethods attribute, or in the * (ASM specific) type table of a class (depending on the {@link #tag} value). */ final int index; /** * A tag indicating the type of this symbol. Must be one of the static tag values defined in this * class. */ final int tag; /** * The internal name of the owner class of this symbol. Only used for {@link * #CONSTANT_FIELDREF_TAG}, {@link #CONSTANT_METHODREF_TAG}, {@link * #CONSTANT_INTERFACE_METHODREF_TAG}, and {@link #CONSTANT_METHOD_HANDLE_TAG} symbols. */ final String owner; /** * The name of the class field or method corresponding to this symbol. Only used for {@link * #CONSTANT_FIELDREF_TAG}, {@link #CONSTANT_METHODREF_TAG}, {@link * #CONSTANT_INTERFACE_METHODREF_TAG}, {@link #CONSTANT_NAME_AND_TYPE_TAG}, {@link * #CONSTANT_METHOD_HANDLE_TAG}, {@link #CONSTANT_DYNAMIC_TAG} and {@link * #CONSTANT_INVOKE_DYNAMIC_TAG} symbols. */ final String name; /** * The string value of this symbol. This is: * * <ul> * <li>a field or method descriptor for {@link #CONSTANT_FIELDREF_TAG}, {@link * #CONSTANT_METHODREF_TAG}, {@link #CONSTANT_INTERFACE_METHODREF_TAG}, {@link * #CONSTANT_NAME_AND_TYPE_TAG}, {@link #CONSTANT_METHOD_HANDLE_TAG}, {@link * #CONSTANT_METHOD_TYPE_TAG}, {@link #CONSTANT_DYNAMIC_TAG} and {@link * #CONSTANT_INVOKE_DYNAMIC_TAG} symbols, * <li>an arbitrary string for {@link #CONSTANT_UTF8_TAG} and {@link #CONSTANT_STRING_TAG} * symbols, * <li>an internal class name for {@link #CONSTANT_CLASS_TAG}, {@link #TYPE_TAG}, {@link * #UNINITIALIZED_TYPE_TAG} and {@link #FORWARD_UNINITIALIZED_TYPE_TAG} symbols, * <li>{@literal null} for the other types of symbol. * </ul> */ final String value; /** * The numeric value of this symbol. This is: * * <ul> * <li>the symbol's value for {@link #CONSTANT_INTEGER_TAG},{@link #CONSTANT_FLOAT_TAG}, {@link * #CONSTANT_LONG_TAG}, {@link #CONSTANT_DOUBLE_TAG}, * <li>the CONSTANT_MethodHandle_info reference_kind field value for {@link * #CONSTANT_METHOD_HANDLE_TAG} symbols, * <li>the CONSTANT_InvokeDynamic_info bootstrap_method_attr_index field value for {@link * #CONSTANT_INVOKE_DYNAMIC_TAG} symbols, * <li>the offset of a bootstrap method in the BootstrapMethods boostrap_methods array, for * {@link #CONSTANT_DYNAMIC_TAG} or {@link #BOOTSTRAP_METHOD_TAG} symbols, * <li>the bytecode offset of the NEW instruction that created an {@link * Frame#ITEM_UNINITIALIZED} type for {@link #UNINITIALIZED_TYPE_TAG} symbols, * <li>the index of the {@link Label} (in the {@link SymbolTable#labelTable} table) of the NEW * instruction that created an {@link Frame#ITEM_UNINITIALIZED} type for {@link * #FORWARD_UNINITIALIZED_TYPE_TAG} symbols, * <li>the indices (in the class' type table) of two {@link #TYPE_TAG} source types for {@link * #MERGED_TYPE_TAG} symbols, * <li>0 for the other types of symbol. * </ul> */ final long data; /** * Additional information about this symbol, generally computed lazily. <i>Warning: the value of * this field is ignored when comparing Symbol instances</i> (to avoid duplicate entries in a * SymbolTable). Therefore, this field should only contain data that can be computed from the * other fields of this class. It contains: * * <ul> * <li>the {@link Type#getArgumentsAndReturnSizes} of the symbol's method descriptor for {@link * #CONSTANT_METHODREF_TAG}, {@link #CONSTANT_INTERFACE_METHODREF_TAG} and {@link * #CONSTANT_INVOKE_DYNAMIC_TAG} symbols, * <li>the index in the InnerClasses_attribute 'classes' array (plus one) corresponding to this * class, for {@link #CONSTANT_CLASS_TAG} symbols, * <li>the index (in the class' type table) of the merged type of the two source types for * {@link #MERGED_TYPE_TAG} symbols, * <li>0 for the other types of symbol, or if this field has not been computed yet. * </ul> */ int info; /** * Constructs a new Symbol. This constructor can't be used directly because the Symbol class is * abstract. Instead, use the factory methods of the {@link SymbolTable} class. * * @param index the symbol index in the constant pool, in the BootstrapMethods attribute, or in * the (ASM specific) type table of a class (depending on 'tag'). * @param tag the symbol type. Must be one of the static tag values defined in this class. * @param owner The internal name of the symbol's owner class. Maybe {@literal null}. * @param name The name of the symbol's corresponding class field or method. Maybe {@literal * null}. * @param value The string value of this symbol. Maybe {@literal null}. * @param data The numeric value of this symbol. */ Symbol( final int index, final int tag, final String owner, final String name, final String value, final long data) { this.index = index; this.tag = tag; this.owner = owner; this.name = name; this.value = value; this.data = data; } /** * Returns the result {@link Type#getArgumentsAndReturnSizes} on {@link #value}. * * @return the result {@link Type#getArgumentsAndReturnSizes} on {@link #value} (memoized in * {@link #info} for efficiency). This should only be used for {@link * #CONSTANT_METHODREF_TAG}, {@link #CONSTANT_INTERFACE_METHODREF_TAG} and {@link * #CONSTANT_INVOKE_DYNAMIC_TAG} symbols. */ int getArgumentsAndReturnSizes() { if (info == 0) { info = Type.getArgumentsAndReturnSizes(value); } return info; } }
spring-projects/spring-framework
spring-core/src/main/java/org/springframework/asm/Symbol.java
413
/* Copyright 2021 The TensorFlow Authors. All Rights Reserved. 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 org.tensorflow.lite; /** * An internal wrapper that wraps native SignatureRunner. * * <p>Note: This class is not thread safe. */ final class NativeSignatureRunnerWrapper { NativeSignatureRunnerWrapper(long interpreterHandle, long errorHandle, String signatureKey) { this.errorHandle = errorHandle; signatureRunnerHandle = nativeGetSignatureRunner(interpreterHandle, signatureKey); if (signatureRunnerHandle == -1) { throw new IllegalArgumentException("Input error: Signature " + signatureKey + " not found."); } } /** * Attempts to get the subgraph index associated with this Signature. Returns the subgraph index, * or -1 on error. */ public int getSubgraphIndex() { return nativeGetSubgraphIndex(signatureRunnerHandle); } /** Gets the inputs of this Signature. */ public String[] inputNames() { return nativeInputNames(signatureRunnerHandle); } /** Gets the outputs of this Signature. */ public String[] outputNames() { return nativeOutputNames(signatureRunnerHandle); } /** Gets the input tensor specified by {@code inputName}. */ public TensorImpl getInputTensor(String inputName) { return TensorImpl.fromSignatureInput(signatureRunnerHandle, inputName); } /** Gets the output tensor specified by {@code outputName}. */ public TensorImpl getOutputTensor(String outputName) { return TensorImpl.fromSignatureOutput(signatureRunnerHandle, outputName); } /** Gets the index of the input specified by {@code inputName}. */ public int getInputIndex(String inputName) { int inputIndex = nativeGetInputIndex(signatureRunnerHandle, inputName); if (inputIndex == -1) { throw new IllegalArgumentException("Input error: input " + inputName + " not found."); } return inputIndex; } /** Gets the index of the output specified by {@code outputName}. */ public int getOutputIndex(String outputName) { int outputIndex = nativeGetOutputIndex(signatureRunnerHandle, outputName); if (outputIndex == -1) { throw new IllegalArgumentException("Input error: output " + outputName + " not found."); } return outputIndex; } /** Resizes dimensions of a specific input. */ public boolean resizeInput(String inputName, int[] dims) { isMemoryAllocated = false; return nativeResizeInput(signatureRunnerHandle, errorHandle, inputName, dims); } /** Allocates tensor memory space. */ public void allocateTensorsIfNeeded() { if (isMemoryAllocated) { return; } nativeAllocateTensors(signatureRunnerHandle, errorHandle); isMemoryAllocated = true; } /** Runs inference for this Signature. */ public void invoke() { nativeInvoke(signatureRunnerHandle, errorHandle); } private final long signatureRunnerHandle; private final long errorHandle; private boolean isMemoryAllocated = false; private static native long nativeGetSignatureRunner(long interpreterHandle, String signatureKey); private static native int nativeGetSubgraphIndex(long signatureRunnerHandle); private static native String[] nativeInputNames(long signatureRunnerHandle); private static native String[] nativeOutputNames(long signatureRunnerHandle); private static native int nativeGetInputIndex(long signatureRunnerHandle, String inputName); private static native int nativeGetOutputIndex(long signatureRunnerHandle, String outputName); private static native boolean nativeResizeInput( long signatureRunnerHandle, long errorHandle, String inputName, int[] dims); private static native void nativeAllocateTensors(long signatureRunnerHandle, long errorHandle); private static native void nativeInvoke(long signatureRunnerHandle, long errorHandle); }
tensorflow/tensorflow
tensorflow/lite/java/src/main/java/org/tensorflow/lite/NativeSignatureRunnerWrapper.java
414
/* * Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one * or more contributor license agreements. Licensed under the Elastic License * 2.0 and the Server Side Public License, v 1; you may not use this file except * in compliance with, at your election, the Elastic License 2.0 or the Server * Side Public License, v 1. */ package org.elasticsearch.index; import org.elasticsearch.cluster.ClusterState; import org.elasticsearch.common.io.stream.StreamInput; import org.elasticsearch.common.io.stream.StreamOutput; import org.elasticsearch.common.io.stream.Writeable; import org.elasticsearch.xcontent.ObjectParser; import org.elasticsearch.xcontent.ParseField; import org.elasticsearch.xcontent.ToXContentObject; import org.elasticsearch.xcontent.XContentBuilder; import org.elasticsearch.xcontent.XContentParser; import java.io.IOException; import java.util.Comparator; import java.util.Objects; /** * A value class representing the basic required properties of an Elasticsearch index. */ public class Index implements Writeable, ToXContentObject { public static final Index[] EMPTY_ARRAY = new Index[0]; public static Comparator<Index> COMPARE_BY_NAME = Comparator.comparing(Index::getName); private static final String INDEX_UUID_KEY = "index_uuid"; private static final String INDEX_NAME_KEY = "index_name"; private static final ObjectParser<Builder, Void> INDEX_PARSER = new ObjectParser<>("index", Builder::new); static { INDEX_PARSER.declareString(Builder::name, new ParseField(INDEX_NAME_KEY)); INDEX_PARSER.declareString(Builder::uuid, new ParseField(INDEX_UUID_KEY)); } private final String name; private final String uuid; public Index(String name, String uuid) { this.name = Objects.requireNonNull(name); this.uuid = Objects.requireNonNull(uuid); } /** * Read from a stream. */ public Index(StreamInput in) throws IOException { this.name = in.readString(); this.uuid = in.readString(); } public String getName() { return this.name; } public String getUUID() { return uuid; } @Override public String toString() { /* * If we have a uuid we put it in the toString so it'll show up in logs which is useful as more and more things use the uuid rather * than the name as the lookup key for the index. */ if (ClusterState.UNKNOWN_UUID.equals(uuid)) { return "[" + name + "]"; } return "[" + name + "/" + uuid + "]"; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Index index1 = (Index) o; return uuid.equals(index1.uuid) && name.equals(index1.name); // allow for _na_ uuid } @Override public int hashCode() { int result = name.hashCode(); result = 31 * result + uuid.hashCode(); return result; } @Override public void writeTo(final StreamOutput out) throws IOException { out.writeString(name); out.writeString(uuid); } @Override public XContentBuilder toXContent(final XContentBuilder builder, final Params params) throws IOException { builder.startObject(); toXContentFragment(builder); return builder.endObject(); } public XContentBuilder toXContentFragment(final XContentBuilder builder) throws IOException { builder.field(INDEX_NAME_KEY, name); builder.field(INDEX_UUID_KEY, uuid); return builder; } public static Index fromXContent(final XContentParser parser) throws IOException { return INDEX_PARSER.parse(parser, null).build(); } /** * Builder for Index objects. Used by ObjectParser instances only. */ private static final class Builder { private String name; private String uuid; public void name(final String name) { this.name = name; } public void uuid(final String uuid) { this.uuid = uuid; } public Index build() { return new Index(name, uuid); } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/index/Index.java
419
/* * Copyright (C) 2013 Square, Inc. * * 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 retrofit2; import static android.os.Build.VERSION.SDK_INT; import java.util.concurrent.Executor; import javax.annotation.Nullable; final class Platform { static final @Nullable Executor callbackExecutor; static final Reflection reflection; static final BuiltInFactories builtInFactories; static { switch (System.getProperty("java.vm.name")) { case "Dalvik": callbackExecutor = new AndroidMainExecutor(); if (SDK_INT >= 24) { reflection = new Reflection.Android24(); builtInFactories = new BuiltInFactories.Java8(); } else { reflection = new Reflection(); builtInFactories = new BuiltInFactories(); } break; case "RoboVM": callbackExecutor = null; reflection = new Reflection(); builtInFactories = new BuiltInFactories(); break; default: callbackExecutor = null; reflection = new Reflection.Java8(); builtInFactories = new BuiltInFactories.Java8(); break; } } private Platform() {} }
square/retrofit
retrofit/src/main/java/retrofit2/Platform.java
422
/* * 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.GwtCompatible; import com.google.common.base.Ascii; import com.google.common.base.CharMatcher; import com.google.common.base.Joiner; import com.google.common.base.Optional; import com.google.common.base.Splitter; import com.google.common.collect.ImmutableList; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.Immutable; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.thirdparty.publicsuffix.PublicSuffixPatterns; import com.google.thirdparty.publicsuffix.PublicSuffixType; import java.util.List; import javax.annotation.CheckForNull; /** * 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. * Using the subset of public suffixes that are {@linkplain #isRegistrySuffix() registry suffixes}, * one can get a better result, as only a few registry suffixes are addressable. However, the most * 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. Of course, to actually * determine addressability of any host, clients of this class will need to perform their own DNS * lookups. * * <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> * * <p>The normalized values will be returned from {@link #toString()} 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 Catherine Berry * @since 5.0 */ @GwtCompatible(emulated = true) @Immutable @ElementTypesAreNonnullByDefault 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()} or {@link #registrySuffixIndex()} which indicates that no * relevant suffix was found. */ private static final int NO_SUFFIX_FOUND = -1; /** * Value of {@link #publicSuffixIndexCache} or {@link #registrySuffixIndexCache} which indicates * that they were not initialized yet. */ private static final int SUFFIX_NOT_INITIALIZED = -2; /** * 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; /** * Cached value of #publicSuffixIndex(). Do not use directly. * * <p>Since this field isn't {@code volatile}, if an instance of this class is shared across * threads before it is initialized, then each thread is likely to compute their own copy of the * value. */ @SuppressWarnings("Immutable") @LazyInit private int publicSuffixIndexCache = SUFFIX_NOT_INITIALIZED; /** * Cached value of #registrySuffixIndex(). Do not use directly. * * <p>Since this field isn't {@code volatile}, if an instance of this class is shared across * threads before it is initialized, then each thread is likely to compute their own copy of the * value. */ @SuppressWarnings("Immutable") @LazyInit private int registrySuffixIndexCache = SUFFIX_NOT_INITIALIZED; /** 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); } /** * Internal constructor that skips validations when creating an instance from parts of an * already-validated InternetDomainName, as in {@link ancestor}. */ private InternetDomainName(String name, ImmutableList<String> parts) { checkArgument(!parts.isEmpty(), "Cannot create an InternetDomainName with zero parts."); this.name = name; this.parts = parts; } /** * The index in the {@link #parts()} list at which the public suffix begins. For example, for the * domain name {@code myblog.blogspot.co.uk}, the value would be 1 (the index of the {@code * blogspot} part). The value is negative (specifically, {@link #NO_SUFFIX_FOUND}) if no public * suffix was found. */ private int publicSuffixIndex() { int publicSuffixIndexLocal = publicSuffixIndexCache; if (publicSuffixIndexLocal == SUFFIX_NOT_INITIALIZED) { publicSuffixIndexCache = publicSuffixIndexLocal = findSuffixOfType(Optional.<PublicSuffixType>absent()); } return publicSuffixIndexLocal; } /** * The index in the {@link #parts()} list at which the registry suffix begins. For example, for * the domain name {@code myblog.blogspot.co.uk}, the value would be 2 (the index of the {@code * co} part). The value is negative (specifically, {@link #NO_SUFFIX_FOUND}) if no registry suffix * was found. */ private int registrySuffixIndex() { int registrySuffixIndexLocal = registrySuffixIndexCache; if (registrySuffixIndexLocal == SUFFIX_NOT_INITIALIZED) { registrySuffixIndexCache = registrySuffixIndexLocal = findSuffixOfType(Optional.of(PublicSuffixType.REGISTRY)); } return registrySuffixIndexLocal; } /** * Returns the index of the leftmost part of the suffix, or -1 if not found. Note that the value * defined as a suffix may not produce {@code true} results from {@link #isPublicSuffix()} or * {@link #isRegistrySuffix()} if the domain ends with an excluded domain pattern such as {@code * "nhs.uk"}. * * <p>If a {@code desiredType} is specified, this method only finds suffixes of the given type. * Otherwise, it finds the first suffix of any type. */ private int findSuffixOfType(Optional<PublicSuffixType> desiredType) { int partsSize = parts.size(); for (int i = 0; i < partsSize; i++) { String ancestorName = DOT_JOINER.join(parts.subList(i, partsSize)); if (i > 0 && matchesType( desiredType, Optional.fromNullable(PublicSuffixPatterns.UNDER.get(ancestorName)))) { return i - 1; } if (matchesType( desiredType, Optional.fromNullable(PublicSuffixPatterns.EXACT.get(ancestorName)))) { return i; } // Excluded domains (e.g. !nhs.uk) use the next highest // domain as the effective public suffix (e.g. uk). if (PublicSuffixPatterns.EXCLUDED.containsKey(ancestorName)) { return i + 1; } } return NO_SUFFIX_FOUND; } /** * 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, as mandated by <a * href="https://tools.ietf.org/html/rfc1123#section-2">RFC 1123</a>. * </ul> * * @param domain A domain name (not IP address) * @throws IllegalArgumentException if {@code domain} is not syntactically valid according to * {@link #isValid} * @since 10.0 (previously named {@code fromLenient}) */ @CanIgnoreReturnValue // TODO(b/219820829): consider removing public static InternetDomainName from(String domain) { return new InternetDomainName(checkNotNull(domain)); } /** * Validation method used by {@code 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) { 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 DIGIT_MATCHER = CharMatcher.inRange('0', '9'); private static final CharMatcher LETTER_MATCHER = CharMatcher.inRange('a', 'z').or(CharMatcher.inRange('A', 'Z')); private static final CharMatcher PART_CHAR_MATCHER = DIGIT_MATCHER.or(LETTER_MATCHER).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: * https://groups.google.com/d/topic/google-web-toolkit-contributors/1UEzsryq1XI * * <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 && DIGIT_MATCHER.matches(part.charAt(0))) { return false; } return true; } /** * 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.com}, {@code foo.co.uk}, and {@code myblog.blogspot.com}. * * <p>Public suffixes are a proper superset of {@linkplain #isRegistrySuffix() registry suffixes}. * The list of public suffixes additionally contains privately owned domain names under which * Internet users can register subdomains. An example of a public suffix that is not a registry * suffix is {@code blogspot.com}. Note that it is true that all public suffixes <i>have</i> * registry suffixes, since domain name registries collectively control all internet domain names. * * <p>For considerations on whether the public suffix or registry suffix designation is more * suitable for your application, see <a * href="https://github.com/google/guava/wiki/InternetDomainNameExplained">this article</a>. * * @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 invalid} or {@code * google.invalid}. This is the recommended method for determining whether a domain is potentially * an addressable host. * * <p>Note that this method is equivalent to {@link #hasRegistrySuffix()} because all registry * suffixes are public suffixes <i>and</i> all public suffixes have registry suffixes. * * @since 6.0 */ public boolean hasPublicSuffix() { return publicSuffixIndex() != NO_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 */ @CheckForNull 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 myblog.blogspot.com}, but not for {@code com}, * {@code co.uk}, {@code google.invalid}, or {@code blogspot.com}. * * <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} {@code foo.co.uk}, and {@code myblog.blogspot.com}, but not for {@code * www.google.com}, {@code co.uk}, or {@code blogspot.com}. * * <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 {@linkplain * #isPublicSuffix() 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. Similarly, for {@code * myblog.blogspot.com} it returns the same domain, {@code myblog.blogspot.com}, since {@code * blogspot.com} is a public suffix. * * <p>If {@link #isTopPrivateDomain()} is true, the current domain name instance is returned. * * <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 name represents a <i>registry suffix</i>, as defined by a subset * of the Mozilla Foundation's <a href="http://publicsuffix.org/">Public Suffix List</a> (PSL). A * registry suffix is one under which Internet users can directly register names via a domain name * registrar, and have such registrations lawfully protected by internet-governing bodies such as * ICANN. Examples of registry suffixes include {@code com}, {@code co.uk}, and {@code * pvt.k12.wy.us}. Examples of domain names that are <i>not</i> registry suffixes include {@code * google.com} and {@code foo.co.uk}. * * <p>Registry suffixes are a proper subset of {@linkplain #isPublicSuffix() public suffixes}. The * list of public suffixes additionally contains privately owned domain names under which Internet * users can register subdomains. An example of a public suffix that is not a registry suffix is * {@code blogspot.com}. Note that it is true that all public suffixes <i>have</i> registry * suffixes, since domain name registries collectively control all internet domain names. * * <p>For considerations on whether the public suffix or registry suffix designation is more * suitable for your application, see <a * href="https://github.com/google/guava/wiki/InternetDomainNameExplained">this article</a>. * * @return {@code true} if this domain name appears exactly on the public suffix list as part of * the registry suffix section (labelled "ICANN"). * @since 23.3 */ public boolean isRegistrySuffix() { return registrySuffixIndex() == 0; } /** * Indicates whether this domain name ends in a {@linkplain #isRegistrySuffix() registry suffix}, * including if it is a registry suffix itself. For example, returns {@code true} for {@code * www.google.com}, {@code foo.co.uk} and {@code com}, but not for {@code invalid} or {@code * google.invalid}. * * <p>Note that this method is equivalent to {@link #hasPublicSuffix()} because all registry * suffixes are public suffixes <i>and</i> all public suffixes have registry suffixes. * * @since 23.3 */ public boolean hasRegistrySuffix() { return registrySuffixIndex() != NO_SUFFIX_FOUND; } /** * Returns the {@linkplain #isRegistrySuffix() registry suffix} portion of the domain name, or * {@code null} if no registry suffix is present. * * @since 23.3 */ @CheckForNull public InternetDomainName registrySuffix() { return hasRegistrySuffix() ? ancestor(registrySuffixIndex()) : null; } /** * Indicates whether this domain name ends in a {@linkplain #isRegistrySuffix() registry suffix}, * while not being a registry suffix itself. For example, returns {@code true} for {@code * www.google.com}, {@code foo.co.uk} and {@code blogspot.com}, but not for {@code com}, {@code * co.uk}, or {@code google.invalid}. * * @since 23.3 */ public boolean isUnderRegistrySuffix() { return registrySuffixIndex() > 0; } /** * Indicates whether this domain name is composed of exactly one subdomain component followed by a * {@linkplain #isRegistrySuffix() registry suffix}. For example, returns {@code true} for {@code * google.com}, {@code foo.co.uk}, and {@code blogspot.com}, but not for {@code www.google.com}, * {@code co.uk}, or {@code myblog.blogspot.com}. * * <p><b>Warning:</b> This method should not be used to determine the probable highest level * parent domain for which cookies may be set. Use {@link #topPrivateDomain()} for that purpose. * * @since 23.3 */ public boolean isTopDomainUnderRegistrySuffix() { return registrySuffixIndex() == 1; } /** * Returns the portion of this domain name that is one level beneath the {@linkplain * #isRegistrySuffix() registry suffix}. For example, for {@code x.adwords.google.co.uk} it * returns {@code google.co.uk}, since {@code co.uk} is a registry suffix. Similarly, for {@code * myblog.blogspot.com} it returns {@code blogspot.com}, since {@code com} is a registry suffix. * * <p>If {@link #isTopDomainUnderRegistrySuffix()} is true, the current domain name instance is * returned. * * <p><b>Warning:</b> This method should not be used to determine whether a domain is probably the * highest level for which cookies may be set. Use {@link #isTopPrivateDomain()} for that purpose. * * @throws IllegalStateException if this domain does not end with a registry suffix * @since 23.3 */ public InternetDomainName topDomainUnderRegistrySuffix() { if (isTopDomainUnderRegistrySuffix()) { return this; } checkState(isUnderRegistrySuffix(), "Not under a registry suffix: %s", name); return ancestor(registrySuffixIndex() - 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) { ImmutableList<String> ancestorParts = parts.subList(levels, parts.size()); // levels equals the number of dots that are getting clipped away, then add the length of each // clipped part to get the length of the leading substring that is being removed. int substringFrom = levels; for (int i = 0; i < levels; i++) { substringFrom += parts.get(i).length(); } String ancestorName = name.substring(substringFrom); return new InternetDomainName(ancestorName, ancestorParts); } /** * 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); } /** * 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 { InternetDomainName unused = from(name); return true; } catch (IllegalArgumentException e) { return false; } } /** * If a {@code desiredType} is specified, returns true only if the {@code actualType} is * identical. Otherwise, returns true as long as {@code actualType} is present. */ private static boolean matchesType( Optional<PublicSuffixType> desiredType, Optional<PublicSuffixType> actualType) { return desiredType.isPresent() ? desiredType.equals(actualType) : actualType.isPresent(); } /** Returns the domain name, normalized to all lower case. */ @Override public String toString() { return name; } /** * 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(@CheckForNull 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(); } }
google/guava
guava/src/com/google/common/net/InternetDomainName.java
424
import java.io.*; import java.util.*; public class Boost implements Debuggable { public static int ITER_STOP; public static String KEY_NAME_TEMPERED_LOSS = "@TemperedLoss", KEY_NAME_LOG_LOSS = "@LogLoss"; public static String[] KEY_NAME = {KEY_NAME_TEMPERED_LOSS, KEY_NAME_LOG_LOSS}; public static String[] KEY_NAME_DISPLAY = {"TemperedLoss", "LogLoss"}; public static double MAX_PRED_VALUE = 100.0; public static int MAX_SPLIT_TEST = 2000; public static double COEFF_GRAD = 0.001; public static double START_T = 0.9; public static String METHOD_NAME(String s) { int i = 0; do { if (KEY_NAME[i].equals(s)) return KEY_NAME_DISPLAY[i]; i++; } while (i < KEY_NAME.length); Dataset.perror("Boost.class :: no keyword " + s); return ""; } public static void CHECK_NAME(String s) { int i = 0; do { if (KEY_NAME[i].equals(s)) return; i++; } while (i < KEY_NAME.length); Dataset.perror("Boost.class :: no keyword " + s); } Domain myDomain; int max_number_tree, max_size_tree; double average_number_leaves, average_depth, tempered_t, next_t, grad_Z; boolean adaptive_t = false; String name, clamping; DecisionTree[] allTrees; DecisionTree[][] recordAllTrees; double[] allLeveragingCoefficients; MonotonicTreeGraph[][] recordAllMonotonicTreeGraphs_boosting_weights; MonotonicTreeGraph[][] recordAllMonotonicTreeGraphs_cardinals; double[] z_tilde; Boost(Domain d, String nn, int maxnt, int maxst, double tt, String clamped) { myDomain = d; name = nn; clamping = clamped; Boost.CHECK_NAME(name); max_number_tree = maxnt; max_size_tree = maxst; if (tt == -1.0) { adaptive_t = true; tempered_t = START_T; } else tempered_t = tt; if (!name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) tempered_t = 1.0; // not the tempered loss allTrees = null; recordAllMonotonicTreeGraphs_boosting_weights = recordAllMonotonicTreeGraphs_cardinals = null; allLeveragingCoefficients = z_tilde = null; average_number_leaves = average_depth = 0.0; recordAllTrees = new DecisionTree[NUMBER_STRATIFIED_CV][]; recordAllMonotonicTreeGraphs_boosting_weights = new MonotonicTreeGraph[NUMBER_STRATIFIED_CV][]; recordAllMonotonicTreeGraphs_cardinals = new MonotonicTreeGraph[NUMBER_STRATIFIED_CV][]; grad_Z = -1.0; } public String fullName() { String ret = Boost.METHOD_NAME(name); ret += "[" + max_number_tree + "(" + max_size_tree + "):" + ((clamping.equals(Algorithm.CLAMPED)) ? "1" : "0") + "]"; if (!adaptive_t) ret += "{" + tempered_t + "}"; else ret += "{" + -1.0 + "}"; return ret; } public Vector boost(int index_algo) { Vector v = new Vector(), v_cur = null; Vector<DecisionTree> all_trees; Vector<Double> all_leveraging_coefficients; Vector<Double> all_zs; Vector<Double> sequence_empirical_risks = new Vector<>(); Vector<Double> sequence_true_risks = new Vector<>(); Vector<Double> sequence_empirical_risks_MonotonicTreeGraph = new Vector<>(); Vector<Double> sequence_true_risks_MonotonicTreeGraph = new Vector<>(); Vector<Double> sequence_min_codensity = new Vector<>(); Vector<Double> sequence_max_codensity = new Vector<>(); // contain the errors on the tree set BUILT UP TO THE INDEX Vector<Integer> sequence_cardinal_nodes = new Vector<>(); Vector<Vector<Double>> sequence_sequence_empirical_risks = new Vector<>(); Vector<Vector<Double>> sequence_sequence_true_risks = new Vector<>(); Vector<Vector<Double>> sequence_sequence_empirical_risks_MonotonicTreeGraph = new Vector<>(); Vector<Vector<Double>> sequence_sequence_true_risks_MonotonicTreeGraph = new Vector<>(); Vector<Vector<Double>> sequence_sequence_min_codensity = new Vector<>(); Vector<Vector<Double>> sequence_sequence_max_codensity = new Vector<>(); DecisionTree dt; int i, j, curcard = 0; double leveraging_mu, leveraging_alpha, expected_edge, curerr, opterr, ser_mtg, str_mtg; double err_fin, err_fin_MonotonicTreeGraph, err_best, perr_fin, perr_fin_MonotonicTreeGraph, perr_best; int card_nodes_fin, card_nodes_best, trees_fin, trees_best; double[] min_codensity = new double[max_number_tree]; double[] max_codensity = new double[max_number_tree]; System.out.println(fullName() + " (eta = " + myDomain.myDS.eta_noise + ")"); for (i = 0; i < NUMBER_STRATIFIED_CV; i++) { all_trees = new Vector<>(); all_leveraging_coefficients = new Vector<>(); all_zs = new Vector<>(); recordAllTrees[i] = new DecisionTree[max_number_tree]; if (adaptive_t) tempered_t = Boost.START_T; TemperedBoostException.RESET_COUNTS(); allTrees = null; allLeveragingCoefficients = null; System.out.print("> Fold " + (i + 1) + "/" + NUMBER_STRATIFIED_CV + " -- "); myDomain.myDS.init_weights(name, i, tempered_t); v_cur = new Vector(); // saves in this order: // // COMPLETE SUBSET OF TREES: err = empirical risk on fold // COMPLETE SUBSET OF TREES: perr = estimated true risk on fold // COMPLETE SUBSET OF TREES: tree number // COMPLETE SUBSET OF TREES: tree size (total card of all nodes) sequence_empirical_risks = new Vector(); sequence_true_risks = new Vector(); sequence_empirical_risks_MonotonicTreeGraph = new Vector(); sequence_true_risks_MonotonicTreeGraph = new Vector(); sequence_min_codensity = new Vector(); sequence_max_codensity = new Vector(); sequence_cardinal_nodes = new Vector(); min_codensity = new double[max_number_tree]; for (j = 0; j < max_number_tree; j++) { System.out.print("."); v_cur = new Vector(); dt = oneTree(j, i); leveraging_mu = dt.leveraging_mu(); // leveraging coefficient curcard += dt.number_nodes; average_number_leaves += (double) dt.leaves.size(); average_depth += (double) dt.depth; all_trees.addElement(dt); leveraging_alpha = dt.leveraging_alpha(leveraging_mu, all_zs); all_leveraging_coefficients.addElement(new Double(leveraging_alpha)); if ((SAVE_PARAMETERS_DURING_TRAINING) || (j == max_number_tree - 1)) { sequence_empirical_risks.addElement( new Double( ensemble_error_noise_free( all_trees, all_leveraging_coefficients, true, i, false))); sequence_true_risks.addElement( new Double( ensemble_error_noise_free( all_trees, all_leveraging_coefficients, false, i, false))); ser_mtg = ensemble_error_noise_free(all_trees, all_leveraging_coefficients, true, i, true); sequence_empirical_risks_MonotonicTreeGraph.addElement(new Double(ser_mtg)); str_mtg = ensemble_error_noise_free(all_trees, all_leveraging_coefficients, false, i, true); sequence_true_risks_MonotonicTreeGraph.addElement(new Double(str_mtg)); sequence_cardinal_nodes.addElement(new Integer(curcard)); } if ((adaptive_t) && (j > 0)) tempered_t = next_t; // change here otherwise inconsistencies in computations if (name.equals(Boost.KEY_NAME_TEMPERED_LOSS)) { try { reweight_examples_tempered_loss( dt, leveraging_mu, i, all_zs, j, min_codensity, max_codensity); } catch (TemperedBoostException eee) { min_codensity[j] = -1.0; max_codensity[j] = -1.0; reweight_examples_infinite_weight(dt, leveraging_mu, i, all_zs); } } else if (name.equals(Boost.KEY_NAME_LOG_LOSS)) { reweight_examples_log_loss(dt, leveraging_mu, i); } else Dataset.perror("Boost.class :: no such loss as " + name); if ((SAVE_PARAMETERS_DURING_TRAINING) || (j == max_number_tree - 1)) { sequence_min_codensity.addElement(new Double(min_codensity[j])); sequence_max_codensity.addElement(new Double(max_codensity[j])); } if (j % 10 == 0) System.out.print(myDomain.memString()); } if (SAVE_PARAMETERS_DURING_TRAINING) { sequence_sequence_empirical_risks.addElement(sequence_empirical_risks); sequence_sequence_true_risks.addElement(sequence_true_risks); sequence_sequence_empirical_risks_MonotonicTreeGraph.addElement( sequence_empirical_risks_MonotonicTreeGraph); sequence_sequence_true_risks_MonotonicTreeGraph.addElement( sequence_true_risks_MonotonicTreeGraph); sequence_sequence_min_codensity.addElement(sequence_min_codensity); sequence_sequence_max_codensity.addElement(sequence_max_codensity); } allTrees = new DecisionTree[max_number_tree]; allLeveragingCoefficients = new double[max_number_tree]; for (j = 0; j < max_number_tree; j++) { allTrees[j] = (DecisionTree) all_trees.elementAt(j); recordAllTrees[i][j] = allTrees[j]; allLeveragingCoefficients[j] = ((Double) all_leveraging_coefficients.elementAt(j)).doubleValue(); } if (SAVE_CLASSIFIERS) save(i); err_fin = (Double) sequence_empirical_risks.elementAt(sequence_empirical_risks.size() - 1); perr_fin = (Double) sequence_true_risks.elementAt(sequence_true_risks.size() - 1); card_nodes_fin = (Integer) sequence_cardinal_nodes.elementAt(sequence_cardinal_nodes.size() - 1); trees_fin = max_number_tree; err_fin_MonotonicTreeGraph = (Double) sequence_empirical_risks_MonotonicTreeGraph.elementAt( sequence_empirical_risks_MonotonicTreeGraph.size() - 1); perr_fin_MonotonicTreeGraph = (Double) sequence_true_risks_MonotonicTreeGraph.elementAt( sequence_true_risks_MonotonicTreeGraph.size() - 1); v_cur.addElement(new Double(err_fin)); v_cur.addElement(new Double(perr_fin)); v_cur.addElement(new Double((double) trees_fin)); v_cur.addElement(new Double((double) card_nodes_fin)); v_cur.addElement(new Double(err_fin_MonotonicTreeGraph)); v_cur.addElement(new Double(perr_fin_MonotonicTreeGraph)); v.addElement(v_cur); System.out.print( "ok. \t(e-err t-err #nodes) = (" + DF.format(err_fin) + " " + DF.format(perr_fin) + " " + ((int) card_nodes_fin) + " -- " + DF.format(err_fin_MonotonicTreeGraph) + " " + DF.format(perr_fin_MonotonicTreeGraph) + ")"); System.out.println(" (" + TemperedBoostException.STATUS() + ")"); } if (SAVE_PARAMETERS_DURING_TRAINING) { double[] avg_sequence_empirical_risks = new double[max_number_tree]; double[] stddev_sequence_empirical_risks = new double[max_number_tree]; double[] avg_sequence_true_risks = new double[max_number_tree]; double[] stddev_sequence_true_risks = new double[max_number_tree]; double[] avg_sequence_empirical_risks_MonotonicTreeGraph = new double[max_number_tree]; double[] stddev_sequence_empirical_risks_MonotonicTreeGraph = new double[max_number_tree]; double[] avg_sequence_true_risks_MonotonicTreeGraph = new double[max_number_tree]; double[] stddev_sequence_true_risks_MonotonicTreeGraph = new double[max_number_tree]; double[] avg_sequence_min_codensity = new double[max_number_tree]; double[] stddev_sequence_min_codensity = new double[max_number_tree]; double[] avg_sequence_max_codensity = new double[max_number_tree]; double[] stddev_sequence_max_codensity = new double[max_number_tree]; double[] dumseq; double[] avestd = new double[2]; for (j = 0; j < max_number_tree; j++) { dumseq = new double[NUMBER_STRATIFIED_CV]; for (i = 0; i < NUMBER_STRATIFIED_CV; i++) dumseq[i] = sequence_sequence_empirical_risks.elementAt(i).elementAt(j).doubleValue(); Statistics.avestd(dumseq, avestd); avg_sequence_empirical_risks[j] = avestd[0]; stddev_sequence_empirical_risks[j] = avestd[1]; dumseq = new double[NUMBER_STRATIFIED_CV]; for (i = 0; i < NUMBER_STRATIFIED_CV; i++) dumseq[i] = sequence_sequence_true_risks.elementAt(i).elementAt(j).doubleValue(); Statistics.avestd(dumseq, avestd); avg_sequence_true_risks[j] = avestd[0]; stddev_sequence_true_risks[j] = avestd[1]; dumseq = new double[NUMBER_STRATIFIED_CV]; for (i = 0; i < NUMBER_STRATIFIED_CV; i++) dumseq[i] = sequence_sequence_empirical_risks_MonotonicTreeGraph .elementAt(i) .elementAt(j) .doubleValue(); Statistics.avestd(dumseq, avestd); avg_sequence_empirical_risks_MonotonicTreeGraph[j] = avestd[0]; stddev_sequence_empirical_risks_MonotonicTreeGraph[j] = avestd[1]; dumseq = new double[NUMBER_STRATIFIED_CV]; for (i = 0; i < NUMBER_STRATIFIED_CV; i++) dumseq[i] = sequence_sequence_true_risks_MonotonicTreeGraph .elementAt(i) .elementAt(j) .doubleValue(); Statistics.avestd(dumseq, avestd); avg_sequence_true_risks_MonotonicTreeGraph[j] = avestd[0]; stddev_sequence_true_risks_MonotonicTreeGraph[j] = avestd[1]; dumseq = new double[NUMBER_STRATIFIED_CV]; for (i = 0; i < NUMBER_STRATIFIED_CV; i++) dumseq[i] = sequence_sequence_min_codensity.elementAt(i).elementAt(j).doubleValue(); Statistics.avestd(dumseq, avestd); avg_sequence_min_codensity[j] = avestd[0]; stddev_sequence_min_codensity[j] = avestd[1]; dumseq = new double[NUMBER_STRATIFIED_CV]; for (i = 0; i < NUMBER_STRATIFIED_CV; i++) dumseq[i] = sequence_sequence_max_codensity.elementAt(i).elementAt(j).doubleValue(); Statistics.avestd(dumseq, avestd); avg_sequence_max_codensity[j] = avestd[0]; stddev_sequence_max_codensity[j] = avestd[1]; } save( avg_sequence_empirical_risks, stddev_sequence_empirical_risks, avg_sequence_true_risks, stddev_sequence_true_risks, avg_sequence_empirical_risks_MonotonicTreeGraph, stddev_sequence_empirical_risks_MonotonicTreeGraph, avg_sequence_true_risks_MonotonicTreeGraph, stddev_sequence_true_risks_MonotonicTreeGraph, avg_sequence_min_codensity, stddev_sequence_min_codensity, avg_sequence_max_codensity, stddev_sequence_max_codensity, index_algo - 1); } System.out.println(""); return v; } public void save( double[] ae, double[] se, double[] at, double[] st, double[] ae_MonotonicTreeGraph, double[] se_MonotonicTreeGraph, double[] at_MonotonicTreeGraph, double[] st_MonotonicTreeGraph, double[] amincod, double[] smincod, double[] amaxcod, double[] smaxcod, int index_algo) { String nameSave = myDomain.myDS.pathSave + "results_" + Utils.NOW + "_Algo" + index_algo + ".txt"; int i; FileWriter f; try { f = new FileWriter(nameSave); f.write( "#Iter\tE_em_a\tE_em_s\tE_te_a\tE_te_s\tMDT_e_a\tMDT_e_s\tMDT_t_a\tMDT_t_s\tMinc_a" + "\tMinc_s\tMaxc_a\tMaxc_s\n"); for (i = 0; i < ae.length; i++) f.write( i + "\t" + DF.format(ae[i]) + "\t" + DF.format(se[i]) + "\t" + DF.format(at[i]) + "\t" + DF.format(st[i]) + "\t" + DF.format(ae_MonotonicTreeGraph[i]) + "\t" + DF.format(se_MonotonicTreeGraph[i]) + "\t" + DF.format(at_MonotonicTreeGraph[i]) + "\t" + DF.format(st_MonotonicTreeGraph[i]) + "\t" + DF8.format(amincod[i]) + "\t" + DF8.format(smincod[i]) + "\t" + DF8.format(amaxcod[i]) + "\t" + DF8.format(smaxcod[i]) + "\n"); f.close(); } catch (IOException e) { Dataset.perror("Boost.class :: Saving results error in file " + nameSave); } } public void save(int split_CV) { System.out.print(" {Saving classifier... "); String nameSave = myDomain.myDS.pathSave + "classifiers_" + Utils.NOW + ".txt"; FileWriter f = null; try { f = new FileWriter(nameSave, true); f.write( "=====> " + fullName() + " -- Fold " + (split_CV + 1) + " / " + NUMBER_STRATIFIED_CV + ": " + classifierToString()); f.close(); } catch (IOException e) { Dataset.perror("LinearBoost.class :: Saving results error in file " + nameSave); } System.out.print("ok.} "); } public String classifierToString() { String v = "H = "; int i; for (i = 0; i < max_number_tree; i++) { v += "(" + DF.format(allLeveragingCoefficients[i]) + " * T#" + i + ")"; if (i < max_number_tree - 1) v += " + "; } v += " (" + clamping + "), where\n\n"; for (i = 0; i < max_number_tree; i++) { v += "T#" + i + " = " + allTrees[i].toString(); v += "\n"; } v += "\n"; return v; } public DecisionTree oneTree(int iter, int split_CV) { DecisionTree dumTree; dumTree = new DecisionTree(iter, this, max_size_tree, split_CV); dumTree.init(tempered_t); dumTree.grow_heavy_first(); return dumTree; } // TEMPERED VERSION for reweighting public void reweight_examples_infinite_weight( DecisionTree dt, double mu, int split_CV, Vector<Double> all_zs) { // triggered if infinite weights => restricts support to infinite weights int i, ne = myDomain.myDS.train_size(split_CV), nzw = 0; double zz, ww, dumw, totsize = 0.0, newweight; Example ee; Vector<Integer> indexes_infinite = new Vector<>(); double[] last_weights = new double[ne]; double gz = 0.0; for (i = 0; i < ne; i++) { ee = myDomain.myDS.train_example(split_CV, i); ww = ee.current_boosting_weight; // tempered weight last_weights[i] = ww; try { dumw = Statistics.TEMPERED_PRODUCT( ww, Statistics.TEMPERED_EXP( -mu * dt.output_boosting(ee) * ee.noisy_normalized_class, tempered_t), tempered_t); // Use the noisy class, for training (if no noise, just the regular class) } catch (TemperedBoostException eee) { indexes_infinite.addElement(new Integer(i)); totsize += 1.0; TemperedBoostException.ADD(TemperedBoostException.INFINITE_WEIGHTS); } } newweight = 1.0 / Math.pow(totsize, Statistics.STAR(tempered_t)); for (i = 0; i < ne; i++) { ee = myDomain.myDS.train_example(split_CV, i); if (indexes_infinite.contains(new Integer(i))) ee.current_boosting_weight = newweight; else ee.current_boosting_weight = 0.0; gz += ee.current_boosting_weight * ((2.0 - tempered_t) * Statistics.H_T(last_weights[i], tempered_t) - Statistics.H_T(ee.current_boosting_weight, tempered_t)); } gz /= ((1.0 - tempered_t) * (1.0 - tempered_t)); grad_Z = gz; if (adaptive_t) next_t = Math.max(0.0, Math.min(1.0, tempered_t - (grad_Z * Boost.COEFF_GRAD))); all_zs.addElement(new Double(1.0)); } public void reweight_examples_log_loss(DecisionTree dt, double mu, int split_CV) { int i, ne = myDomain.myDS.train_size(split_CV); double ww, den; Example ee; for (i = 0; i < ne; i++) { ee = myDomain.myDS.train_example(split_CV, i); ww = ee.current_boosting_weight; den = ww + ((1.0 - ww) * Math.exp(mu * dt.unweighted_edge_training(ee))); ee.current_boosting_weight = ww / den; if ((ee.current_boosting_weight <= 0.0) || (ee.current_boosting_weight >= 1.0)) Dataset.perror( "Boost.class :: example " + ee + "has weight = " + ee.current_boosting_weight); } } public void reweight_examples_tempered_loss( DecisionTree dt, double mu, int split_CV, Vector<Double> all_zs, int j, double[] min_codensity, double[] max_codensity) throws TemperedBoostException { int i, ne = myDomain.myDS.train_size(split_CV), nzw = 0; double zz, ww, dumw, z_j = 0.0, factor, minw = -1.0, expt, mindens = -1.0, maxdens = -1.0, dens; Example ee; boolean found = false; double[] last_weights = new double[ne]; for (i = 0; i < ne; i++) { ee = myDomain.myDS.train_example(split_CV, i); ww = ee.current_boosting_weight; // tempered weight last_weights[i] = ww; expt = Statistics.TEMPERED_EXP(-mu * dt.unweighted_edge_training(ee), tempered_t); dumw = Statistics.TEMPERED_PRODUCT(ww, expt, tempered_t); // Use the noisy class, for training (if no noise, just the regular class) if (tempered_t == 1.0) z_j += dumw; else z_j += Math.pow(dumw, 2.0 - tempered_t); ee.current_boosting_weight = dumw; if (dumw == 0) { nzw++; TemperedBoostException.ADD(TemperedBoostException.ZERO_WEIGHTS); } if ((ee.current_boosting_weight != 0.0) && ((!found) || (ee.current_boosting_weight < minw))) { minw = ee.current_boosting_weight; found = true; } } if ((tempered_t == 1.0) && (nzw == 0)) { // some zero weights for AdaBoost, replace them with minimal !=0 weight z_j = 0.0; for (i = 0; i < ne; i++) { ee = myDomain.myDS.train_example(split_CV, i); if (ee.current_boosting_weight == 0.0) { ee.current_boosting_weight = minw; TemperedBoostException.ADD(TemperedBoostException.ZERO_WEIGHTS); } z_j += ee.current_boosting_weight; } } if (z_j == 0.0) Dataset.perror("Boost.class :: no >0 tempered weight"); if (tempered_t != 1.0) z_j = Math.pow(z_j, Statistics.STAR(tempered_t)); all_zs.addElement(new Double(z_j)); double gz = 0.0; double pnext2, pprev2, pprev1; for (i = 0; i < ne; i++) { ee = myDomain.myDS.train_example(split_CV, i); ee.current_boosting_weight /= z_j; pprev1 = Math.pow(last_weights[i], 1.0 - tempered_t); pprev2 = Math.pow(last_weights[i], 2.0 - tempered_t); pnext2 = Math.pow(ee.current_boosting_weight, 2.0 - tempered_t); gz += (pnext2 * Math.log(pnext2)) / (2.0 - tempered_t); gz -= ee.current_boosting_weight * pprev1 * Math.log(pprev2); if ((TemperedBoostException.MIN_WEIGHT == -1.0) || (ee.current_boosting_weight < TemperedBoostException.MIN_WEIGHT)) TemperedBoostException.MIN_WEIGHT = ee.current_boosting_weight; dens = Math.pow(ee.current_boosting_weight, 2.0 - tempered_t); if ((i == 0) || (dens < mindens)) mindens = dens; if ((i == 0) || (dens > maxdens)) maxdens = dens; if (Double.isNaN(ee.current_boosting_weight)) Dataset.perror("Example " + i + " has NaN weight"); } gz /= Math.abs(1.0 - tempered_t); grad_Z = gz; if (adaptive_t) { next_t = Math.max(0.0, Math.min(1.0, tempered_t - (grad_Z * Boost.COEFF_GRAD))); System.out.print("[" + DF.format(tempered_t) + "]"); } min_codensity[j] = mindens; max_codensity[j] = maxdens; } public double ensemble_error_noise_free( Vector all_trees, Vector all_leveraging_coefficients, boolean onTraining, int split_CV, boolean use_MonotonicTreeGraph) { // uses the true label for all computations if ((all_trees == null) || (all_trees.size() == 0)) Dataset.perror("Boost.class :: no trees to compute the error"); Example ee; DecisionTree tt; double sumerr = 0.0, output, coeff, sum, sumtree = 0.0, totedge, sum_weights = 0.0; int i, j, ne; if (onTraining) ne = myDomain.myDS.train_size(split_CV); else ne = myDomain.myDS.test_size(split_CV); if (ne == 0) Dataset.perror("DecisionTree.class :: zero sample size to compute the error"); for (i = 0; i < ne; i++) { sumtree = 0.0; if (onTraining) ee = myDomain.myDS.train_example(split_CV, i); else ee = myDomain.myDS.test_example(split_CV, i); if (onTraining) sum_weights += ee.current_boosting_weight; for (j = 0; j < all_trees.size(); j++) { tt = (DecisionTree) all_trees.elementAt(j); if (use_MonotonicTreeGraph) output = tt.output_boosting_MonotonicTreeGraph(ee); else output = tt.output_boosting(ee); coeff = ((Double) all_leveraging_coefficients.elementAt(j)).doubleValue(); sumtree += (coeff * output); if (clamping.equals(Algorithm.CLAMPED)) sumtree = Statistics.CLAMP_CLASSIFIER(sumtree, tempered_t); } if (sumtree == 0.0) { // random guess if (Utils.RANDOM_P_NOT_HALF() < 0.5) sumtree = -1.0; else sumtree = 1.0; } if (ee.normalized_class == 0.0) Dataset.perror("Boost.class :: Example " + ee + " has zero class"); totedge = sumtree * ee.normalized_class; if (totedge < 0.0) sumerr += 1.0; } sumerr /= (double) ne; return sumerr; } }
google-research/google-research
tempered_boosting/Boost.java
427
/* * 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 static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.CollectPreconditions.checkNonnegative; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.J2ktIncompatible; import com.google.common.annotations.VisibleForTesting; import com.google.common.base.Function; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.HashSet; import java.util.Iterator; import java.util.List; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.SortedMap; import java.util.SortedSet; import java.util.TreeSet; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A comparator, with additional methods to support common operations. This is an "enriched" version * of {@code Comparator} for pre-Java-8 users, in the same sense that {@link FluentIterable} is an * enriched {@link Iterable} for pre-Java-8 users. * * <h3>Three types of methods</h3> * * Like other fluent types, there are three types of methods present: methods for <i>acquiring</i>, * <i>chaining</i>, and <i>using</i>. * * <h4>Acquiring</h4> * * <p>The common ways to get an instance of {@code Ordering} are: * * <ul> * <li>Subclass it and implement {@link #compare} instead of implementing {@link Comparator} * directly * <li>Pass a <i>pre-existing</i> {@link Comparator} instance to {@link #from(Comparator)} * <li>Use the natural ordering, {@link Ordering#natural} * </ul> * * <h4>Chaining</h4> * * <p>Then you can use the <i>chaining</i> methods to get an altered version of that {@code * Ordering}, including: * * <ul> * <li>{@link #reverse} * <li>{@link #compound(Comparator)} * <li>{@link #onResultOf(Function)} * <li>{@link #nullsFirst} / {@link #nullsLast} * </ul> * * <h4>Using</h4> * * <p>Finally, use the resulting {@code Ordering} anywhere a {@link Comparator} is required, or use * any of its special operations, such as: * * <ul> * <li>{@link #immutableSortedCopy} * <li>{@link #isOrdered} / {@link #isStrictlyOrdered} * <li>{@link #min} / {@link #max} * </ul> * * <h3>Understanding complex orderings</h3> * * <p>Complex chained orderings like the following example can be challenging to understand. * * <pre>{@code * Ordering<Foo> ordering = * Ordering.natural() * .nullsFirst() * .onResultOf(getBarFunction) * .nullsLast(); * }</pre> * * Note that each chaining method returns a new ordering instance which is backed by the previous * instance, but has the chance to act on values <i>before</i> handing off to that backing instance. * As a result, it usually helps to read chained ordering expressions <i>backwards</i>. For example, * when {@code compare} is called on the above ordering: * * <ol> * <li>First, if only one {@code Foo} is null, that null value is treated as <i>greater</i> * <li>Next, non-null {@code Foo} values are passed to {@code getBarFunction} (we will be * comparing {@code Bar} values from now on) * <li>Next, if only one {@code Bar} is null, that null value is treated as <i>lesser</i> * <li>Finally, natural ordering is used (i.e. the result of {@code Bar.compareTo(Bar)} is * returned) * </ol> * * <p>Alas, {@link #reverse} is a little different. As you read backwards through a chain and * encounter a call to {@code reverse}, continue working backwards until a result is determined, and * then reverse that result. * * <h3>Additional notes</h3> * * <p>Except as noted, the orderings returned by the factory methods of this class are serializable * if and only if the provided instances that back them are. For example, if {@code ordering} and * {@code function} can themselves be serialized, then {@code ordering.onResultOf(function)} can as * well. * * <h3>Java 8+ users</h3> * * <p>If you are using Java 8+, this class is now obsolete. Most of its functionality is now * provided by {@link java.util.stream.Stream Stream} and by {@link Comparator} itself, and the rest * can now be found as static methods in our new {@link Comparators} class. See each method below * for further instructions. Whenever possible, you should change any references of type {@code * Ordering} to be of type {@code Comparator} instead. However, at this time we have no plan to * <i>deprecate</i> this class. * * <p>Many replacements involve adopting {@code Stream}, and these changes can sometimes make your * code verbose. Whenever following this advice, you should check whether {@code Stream} could be * adopted more comprehensively in your code; the end result may be quite a bit simpler. * * <h3>See also</h3> * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/OrderingExplained">{@code Ordering}</a>. * * @author Jesse Wilson * @author Kevin Bourrillion * @since 2.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public abstract class Ordering<T extends @Nullable Object> implements Comparator<T> { // Natural order /** * Returns a serializable ordering that uses the natural order of the values. The ordering throws * a {@link NullPointerException} when passed a null parameter. * * <p>The type specification is {@code <C extends Comparable>}, instead of the technically correct * {@code <C extends Comparable<? super C>>}, to support legacy types from before Java 5. * * <p><b>Java 8+ users:</b> use {@link Comparator#naturalOrder} instead. */ @GwtCompatible(serializable = true) @SuppressWarnings({"unchecked", "rawtypes"}) // TODO(kevinb): right way to explain this?? // plus https://github.com/google/guava/issues/989 public static <C extends Comparable> Ordering<C> natural() { return (Ordering<C>) NaturalOrdering.INSTANCE; } // Static factories /** * Returns an ordering based on an <i>existing</i> comparator instance. Note that it is * unnecessary to create a <i>new</i> anonymous inner class implementing {@code Comparator} just * to pass it in here. Instead, simply subclass {@code Ordering} and implement its {@code compare} * method directly. * * <p>The returned object is serializable if {@code comparator} is serializable. * * <p><b>Java 8+ users:</b> this class is now obsolete as explained in the class documentation, so * there is no need to use this method. * * @param comparator the comparator that defines the order * @return comparator itself if it is already an {@code Ordering}; otherwise an ordering that * wraps that comparator */ @GwtCompatible(serializable = true) public static <T extends @Nullable Object> Ordering<T> from(Comparator<T> comparator) { return (comparator instanceof Ordering) ? (Ordering<T>) comparator : new ComparatorOrdering<T>(comparator); } /** * Simply returns its argument. * * @deprecated no need to use this */ @GwtCompatible(serializable = true) @Deprecated public static <T extends @Nullable Object> Ordering<T> from(Ordering<T> ordering) { return checkNotNull(ordering); } /** * Returns an ordering that compares objects according to the order in which they appear in the * given list. Only objects present in the list (according to {@link Object#equals}) may be * compared. This comparator imposes a "partial ordering" over the type {@code T}. Subsequent * changes to the {@code valuesInOrder} list will have no effect on the returned comparator. Null * values in the list are not supported. * * <p>The returned comparator throws a {@link ClassCastException} when it receives an input * parameter that isn't among the provided values. * * <p>The generated comparator is serializable if all the provided values are serializable. * * @param valuesInOrder the values that the returned comparator will be able to compare, in the * order the comparator should induce * @return the comparator described above * @throws NullPointerException if any of the provided values is null * @throws IllegalArgumentException if {@code valuesInOrder} contains any duplicate values * (according to {@link Object#equals}) */ // TODO(kevinb): provide replacement @GwtCompatible(serializable = true) public static <T> Ordering<T> explicit(List<T> valuesInOrder) { return new ExplicitOrdering<>(valuesInOrder); } /** * Returns an ordering that compares objects according to the order in which they are given to * this method. Only objects present in the argument list (according to {@link Object#equals}) may * be compared. This comparator imposes a "partial ordering" over the type {@code T}. Null values * in the argument list are not supported. * * <p>The returned comparator throws a {@link ClassCastException} when it receives an input * parameter that isn't among the provided values. * * <p>The generated comparator is serializable if all the provided values are serializable. * * @param leastValue the value which the returned comparator should consider the "least" of all * values * @param remainingValuesInOrder the rest of the values that the returned comparator will be able * to compare, in the order the comparator should follow * @return the comparator described above * @throws NullPointerException if any of the provided values is null * @throws IllegalArgumentException if any duplicate values (according to {@link * Object#equals(Object)}) are present among the method arguments */ // TODO(kevinb): provide replacement @GwtCompatible(serializable = true) public static <T> Ordering<T> explicit(T leastValue, T... remainingValuesInOrder) { return explicit(Lists.asList(leastValue, remainingValuesInOrder)); } // Ordering<Object> singletons /** * Returns an ordering which treats all values as equal, indicating "no ordering." Passing this * ordering to any <i>stable</i> sort algorithm results in no change to the order of elements. * Note especially that {@link #sortedCopy} and {@link #immutableSortedCopy} are stable, and in * the returned instance these are implemented by simply copying the source list. * * <p>Example: * * <pre>{@code * Ordering.allEqual().nullsLast().sortedCopy( * asList(t, null, e, s, null, t, null)) * }</pre> * * <p>Assuming {@code t}, {@code e} and {@code s} are non-null, this returns {@code [t, e, s, t, * null, null, null]} regardless of the true comparison order of those three values (which might * not even implement {@link Comparable} at all). * * <p><b>Warning:</b> by definition, this comparator is not <i>consistent with equals</i> (as * defined {@linkplain Comparator here}). Avoid its use in APIs, such as {@link * TreeSet#TreeSet(Comparator)}, where such consistency is expected. * * <p>The returned comparator is serializable. * * <p><b>Java 8+ users:</b> Use the lambda expression {@code (a, b) -> 0} instead (in certain * cases you may need to cast that to {@code Comparator<YourType>}). * * @since 13.0 */ @GwtCompatible(serializable = true) public static Ordering<@Nullable Object> allEqual() { return AllEqualOrdering.INSTANCE; } /** * Returns an ordering that compares objects by the natural ordering of their string * representations as returned by {@code toString()}. It does not support null values. * * <p>The comparator is serializable. * * <p><b>Java 8+ users:</b> Use {@code Comparator.comparing(Object::toString)} instead. */ @GwtCompatible(serializable = true) public static Ordering<Object> usingToString() { return UsingToStringOrdering.INSTANCE; } /** * Returns an arbitrary ordering over all objects, for which {@code compare(a, b) == 0} implies * {@code a == b} (identity equality). There is no meaning whatsoever to the order imposed, but it * is constant for the life of the VM. * * <p>Because the ordering is identity-based, it is not "consistent with {@link * Object#equals(Object)}" as defined by {@link Comparator}. Use caution when building a {@link * SortedSet} or {@link SortedMap} from it, as the resulting collection will not behave exactly * according to spec. * * <p>This ordering is not serializable, as its implementation relies on {@link * System#identityHashCode(Object)}, so its behavior cannot be preserved across serialization. * * @since 2.0 */ // TODO(kevinb): copy to Comparators, etc. @J2ktIncompatible // MapMaker public static Ordering<@Nullable Object> arbitrary() { return ArbitraryOrderingHolder.ARBITRARY_ORDERING; } @J2ktIncompatible // MapMaker private static class ArbitraryOrderingHolder { static final Ordering<@Nullable Object> ARBITRARY_ORDERING = new ArbitraryOrdering(); } @J2ktIncompatible // MapMaker @VisibleForTesting static class ArbitraryOrdering extends Ordering<@Nullable Object> { private final AtomicInteger counter = new AtomicInteger(0); private final ConcurrentMap<Object, Integer> uids = Platform.tryWeakKeys(new MapMaker()).makeMap(); private Integer getUid(Object obj) { Integer uid = uids.get(obj); if (uid == null) { // One or more integer values could be skipped in the event of a race // to generate a UID for the same object from multiple threads, but // that shouldn't be a problem. uid = counter.getAndIncrement(); Integer alreadySet = uids.putIfAbsent(obj, uid); if (alreadySet != null) { uid = alreadySet; } } return uid; } @Override public int compare(@CheckForNull Object left, @CheckForNull Object right) { if (left == right) { return 0; } else if (left == null) { return -1; } else if (right == null) { return 1; } int leftCode = identityHashCode(left); int rightCode = identityHashCode(right); if (leftCode != rightCode) { return leftCode < rightCode ? -1 : 1; } // identityHashCode collision (rare, but not as rare as you'd think) int result = getUid(left).compareTo(getUid(right)); if (result == 0) { throw new AssertionError(); // extremely, extremely unlikely. } return result; } @Override public String toString() { return "Ordering.arbitrary()"; } /* * We need to be able to mock identityHashCode() calls for tests, because it * can take 1-10 seconds to find colliding objects. Mocking frameworks that * can do magic to mock static method calls still can't do so for a system * class, so we need the indirection. In production, Hotspot should still * recognize that the call is 1-morphic and should still be willing to * inline it if necessary. */ int identityHashCode(Object object) { return System.identityHashCode(object); } } // Constructor /** * Constructs a new instance of this class (only invokable by the subclass constructor, typically * implicit). */ protected Ordering() {} // Instance-based factories (and any static equivalents) /** * Returns the reverse of this ordering; the {@code Ordering} equivalent to {@link * Collections#reverseOrder(Comparator)}. * * <p><b>Java 8+ users:</b> Use {@code thisComparator.reversed()} instead. */ // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<String> o = Ordering.<String>natural().reverse(); @GwtCompatible(serializable = true) public <S extends T> Ordering<S> reverse() { return new ReverseOrdering<>(this); } /** * Returns an ordering that treats {@code null} as less than all other values and uses {@code * this} to compare non-null values. * * <p>The returned object is serializable if this object is serializable. * * <p><b>Java 8+ users:</b> Use {@code Comparator.nullsFirst(thisComparator)} instead. */ // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<String> o = Ordering.<String>natural().nullsFirst(); @GwtCompatible(serializable = true) public <S extends T> Ordering<@Nullable S> nullsFirst() { return new NullsFirstOrdering<S>(this); } /** * Returns an ordering that treats {@code null} as greater than all other values and uses this * ordering to compare non-null values. * * <p>The returned object is serializable if this object is serializable. * * <p><b>Java 8+ users:</b> Use {@code Comparator.nullsLast(thisComparator)} instead. */ // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<String> o = Ordering.<String>natural().nullsLast(); @GwtCompatible(serializable = true) public <S extends T> Ordering<@Nullable S> nullsLast() { return new NullsLastOrdering<S>(this); } /** * Returns a new ordering on {@code F} which orders elements by first applying a function to them, * then comparing those results using {@code this}. For example, to compare objects by their * string forms, in a case-insensitive manner, use: * * <pre>{@code * Ordering.from(String.CASE_INSENSITIVE_ORDER) * .onResultOf(Functions.toStringFunction()) * }</pre> * * <p><b>Java 8+ users:</b> Use {@code Comparator.comparing(function, thisComparator)} instead * (you can omit the comparator if it is the natural order). */ @GwtCompatible(serializable = true) public <F extends @Nullable Object> Ordering<F> onResultOf(Function<F, ? extends T> function) { return new ByFunctionOrdering<>(function, this); } <T2 extends T> Ordering<Entry<T2, ?>> onKeys() { return onResultOf(Maps.<T2>keyFunction()); } /** * Returns an ordering which first uses the ordering {@code this}, but which in the event of a * "tie", then delegates to {@code secondaryComparator}. For example, to sort a bug list first by * status and second by priority, you might use {@code byStatus.compound(byPriority)}. For a * compound ordering with three or more components, simply chain multiple calls to this method. * * <p>An ordering produced by this method, or a chain of calls to this method, is equivalent to * one created using {@link Ordering#compound(Iterable)} on the same component comparators. * * <p>The returned object is serializable if this object and {@code secondaryComparator} are both * serializable. * * <p><b>Java 8+ users:</b> Use {@code thisComparator.thenComparing(secondaryComparator)} instead. * Depending on what {@code secondaryComparator} is, one of the other overloads of {@code * thenComparing} may be even more useful. */ @GwtCompatible(serializable = true) public <U extends T> Ordering<U> compound(Comparator<? super U> secondaryComparator) { return new CompoundOrdering<>(this, checkNotNull(secondaryComparator)); } /** * Returns an ordering which tries each given comparator in order until a non-zero result is * found, returning that result, and returning zero only if all comparators return zero. The * returned ordering is based on the state of the {@code comparators} iterable at the time it was * provided to this method. * * <p>The returned ordering is equivalent to that produced using {@code * Ordering.from(comp1).compound(comp2).compound(comp3) . . .}. * * <p>The returned object is serializable if each of the {@code comparators} is serializable. * * <p><b>Warning:</b> Supplying an argument with undefined iteration order, such as a {@link * HashSet}, will produce non-deterministic results. * * <p><b>Java 8+ users:</b> Use a chain of calls to {@link Comparator#thenComparing(Comparator)}, * or {@code comparatorCollection.stream().reduce(Comparator::thenComparing).get()} (if the * collection might be empty, also provide a default comparator as the {@code identity} parameter * to {@code reduce}). * * @param comparators the comparators to try in order */ @GwtCompatible(serializable = true) public static <T extends @Nullable Object> Ordering<T> compound( Iterable<? extends Comparator<? super T>> comparators) { return new CompoundOrdering<>(comparators); } /** * Returns a new ordering which sorts iterables by comparing corresponding elements pairwise until * a nonzero result is found; imposes "dictionary order". If the end of one iterable is reached, * but not the other, the shorter iterable is considered to be less than the longer one. For * example, a lexicographical natural ordering over integers considers {@code [] < [1] < [1, 1] < * [1, 2] < [2]}. * * <p>Note that {@code ordering.lexicographical().reverse()} is not equivalent to {@code * ordering.reverse().lexicographical()} (consider how each would order {@code [1]} and {@code [1, * 1]}). * * <p><b>Java 8+ users:</b> Use {@link Comparators#lexicographical(Comparator)} instead. * * @since 2.0 */ @GwtCompatible(serializable = true) // type parameter <S> lets us avoid the extra <String> in statements like: // Ordering<Iterable<String>> o = // Ordering.<String>natural().lexicographical(); public <S extends T> Ordering<Iterable<S>> lexicographical() { /* * Note that technically the returned ordering should be capable of * handling not just {@code Iterable<S>} instances, but also any {@code * Iterable<? extends S>}. However, the need for this comes up so rarely * that it doesn't justify making everyone else deal with the very ugly * wildcard. */ return new LexicographicalOrdering<S>(this); } // Regular instance methods @Override public abstract int compare(@ParametricNullness T left, @ParametricNullness T right); /** * Returns the least of the specified values according to this ordering. If there are multiple * least values, the first of those is returned. The iterator will be left exhausted: its {@code * hasNext()} method will return {@code false}. * * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterator).min(thisComparator).get()} instead * (but note that it does not guarantee which tied minimum element is returned). * * @param iterator the iterator whose minimum element is to be determined * @throws NoSuchElementException if {@code iterator} is empty * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this * ordering. * @since 11.0 */ @ParametricNullness public <E extends T> E min(Iterator<E> iterator) { // let this throw NoSuchElementException as necessary E minSoFar = iterator.next(); while (iterator.hasNext()) { minSoFar = this.<E>min(minSoFar, iterator.next()); } return minSoFar; } /** * Returns the least of the specified values according to this ordering. If there are multiple * least values, the first of those is returned. * * <p><b>Java 8+ users:</b> If {@code iterable} is a {@link Collection}, use {@code * Collections.min(collection, thisComparator)} instead. Otherwise, use {@code * Streams.stream(iterable).min(thisComparator).get()} instead. Note that these alternatives do * not guarantee which tied minimum element is returned. * * @param iterable the iterable whose minimum element is to be determined * @throws NoSuchElementException if {@code iterable} is empty * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this * ordering. */ @ParametricNullness public <E extends T> E min(Iterable<E> iterable) { return min(iterable.iterator()); } /** * Returns the lesser of the two values according to this ordering. If the values compare as 0, * the first is returned. * * <p><b>Implementation note:</b> this method is invoked by the default implementations of the * other {@code min} overloads, so overriding it will affect their behavior. * * <p><b>Note:</b> Consider using {@code Comparators.min(a, b, thisComparator)} instead. If {@code * thisComparator} is {@link Ordering#natural}, then use {@code Comparators.min(a, b)}. * * @param a value to compare, returned if less than or equal to b. * @param b value to compare. * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this * ordering. */ @ParametricNullness public <E extends T> E min(@ParametricNullness E a, @ParametricNullness E b) { return (compare(a, b) <= 0) ? a : b; } /** * Returns the least of the specified values according to this ordering. If there are multiple * least values, the first of those is returned. * * <p><b>Java 8+ users:</b> Use {@code Collections.min(Arrays.asList(a, b, c...), thisComparator)} * instead (but note that it does not guarantee which tied minimum element is returned). * * @param a value to compare, returned if less than or equal to the rest. * @param b value to compare * @param c value to compare * @param rest values to compare * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this * ordering. */ @ParametricNullness public <E extends T> E min( @ParametricNullness E a, @ParametricNullness E b, @ParametricNullness E c, E... rest) { E minSoFar = min(min(a, b), c); for (E r : rest) { minSoFar = min(minSoFar, r); } return minSoFar; } /** * Returns the greatest of the specified values according to this ordering. If there are multiple * greatest values, the first of those is returned. The iterator will be left exhausted: its * {@code hasNext()} method will return {@code false}. * * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterator).max(thisComparator).get()} instead * (but note that it does not guarantee which tied maximum element is returned). * * @param iterator the iterator whose maximum element is to be determined * @throws NoSuchElementException if {@code iterator} is empty * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this * ordering. * @since 11.0 */ @ParametricNullness public <E extends T> E max(Iterator<E> iterator) { // let this throw NoSuchElementException as necessary E maxSoFar = iterator.next(); while (iterator.hasNext()) { maxSoFar = this.<E>max(maxSoFar, iterator.next()); } return maxSoFar; } /** * Returns the greatest of the specified values according to this ordering. If there are multiple * greatest values, the first of those is returned. * * <p><b>Java 8+ users:</b> If {@code iterable} is a {@link Collection}, use {@code * Collections.max(collection, thisComparator)} instead. Otherwise, use {@code * Streams.stream(iterable).max(thisComparator).get()} instead. Note that these alternatives do * not guarantee which tied maximum element is returned. * * @param iterable the iterable whose maximum element is to be determined * @throws NoSuchElementException if {@code iterable} is empty * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this * ordering. */ @ParametricNullness public <E extends T> E max(Iterable<E> iterable) { return max(iterable.iterator()); } /** * Returns the greater of the two values according to this ordering. If the values compare as 0, * the first is returned. * * <p><b>Implementation note:</b> this method is invoked by the default implementations of the * other {@code max} overloads, so overriding it will affect their behavior. * * <p><b>Note:</b> Consider using {@code Comparators.max(a, b, thisComparator)} instead. If {@code * thisComparator} is {@link Ordering#natural}, then use {@code Comparators.max(a, b)}. * * @param a value to compare, returned if greater than or equal to b. * @param b value to compare. * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this * ordering. */ @ParametricNullness public <E extends T> E max(@ParametricNullness E a, @ParametricNullness E b) { return (compare(a, b) >= 0) ? a : b; } /** * Returns the greatest of the specified values according to this ordering. If there are multiple * greatest values, the first of those is returned. * * <p><b>Java 8+ users:</b> Use {@code Collections.max(Arrays.asList(a, b, c...), thisComparator)} * instead (but note that it does not guarantee which tied maximum element is returned). * * @param a value to compare, returned if greater than or equal to the rest. * @param b value to compare * @param c value to compare * @param rest values to compare * @throws ClassCastException if the parameters are not <i>mutually comparable</i> under this * ordering. */ @ParametricNullness public <E extends T> E max( @ParametricNullness E a, @ParametricNullness E b, @ParametricNullness E c, E... rest) { E maxSoFar = max(max(a, b), c); for (E r : rest) { maxSoFar = max(maxSoFar, r); } return maxSoFar; } /** * Returns the {@code k} least elements of the given iterable according to this ordering, in order * from least to greatest. If there are fewer than {@code k} elements present, all will be * included. * * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple * elements are equivalent, it is undefined which will come first. * * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterable).collect(Comparators.least(k, * thisComparator))} instead. * * @return an immutable {@code RandomAccess} list of the {@code k} least elements in ascending * order * @throws IllegalArgumentException if {@code k} is negative * @since 8.0 */ @SuppressWarnings("nullness") // TODO: b/316358623 - Remove after checker fix. public <E extends T> List<E> leastOf(Iterable<E> iterable, int k) { if (iterable instanceof Collection) { Collection<E> collection = (Collection<E>) iterable; if (collection.size() <= 2L * k) { // In this case, just dumping the collection to an array and sorting is // faster than using the implementation for Iterator, which is // specialized for k much smaller than n. @SuppressWarnings("unchecked") // c only contains E's and doesn't escape E[] array = (E[]) collection.toArray(); Arrays.sort(array, this); if (array.length > k) { array = Arrays.copyOf(array, k); } return Collections.unmodifiableList(Arrays.asList(array)); } } return leastOf(iterable.iterator(), k); } /** * Returns the {@code k} least elements from the given iterator according to this ordering, in * order from least to greatest. If there are fewer than {@code k} elements present, all will be * included. * * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple * elements are equivalent, it is undefined which will come first. * * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterator).collect(Comparators.least(k, * thisComparator))} instead. * * @return an immutable {@code RandomAccess} list of the {@code k} least elements in ascending * order * @throws IllegalArgumentException if {@code k} is negative * @since 14.0 */ public <E extends T> List<E> leastOf(Iterator<E> iterator, int k) { checkNotNull(iterator); checkNonnegative(k, "k"); if (k == 0 || !iterator.hasNext()) { return Collections.emptyList(); } else if (k >= Integer.MAX_VALUE / 2) { // k is really large; just do a straightforward sorted-copy-and-sublist ArrayList<E> list = Lists.newArrayList(iterator); Collections.sort(list, this); if (list.size() > k) { list.subList(k, list.size()).clear(); } list.trimToSize(); return Collections.unmodifiableList(list); } else { TopKSelector<E> selector = TopKSelector.least(k, this); selector.offerAll(iterator); return selector.topK(); } } /** * Returns the {@code k} greatest elements of the given iterable according to this ordering, in * order from greatest to least. If there are fewer than {@code k} elements present, all will be * included. * * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple * elements are equivalent, it is undefined which will come first. * * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterable).collect(Comparators.greatest(k, * thisComparator))} instead. * * @return an immutable {@code RandomAccess} list of the {@code k} greatest elements in * <i>descending order</i> * @throws IllegalArgumentException if {@code k} is negative * @since 8.0 */ public <E extends T> List<E> greatestOf(Iterable<E> iterable, int k) { // TODO(kevinb): see if delegation is hurting performance noticeably // TODO(kevinb): if we change this implementation, add full unit tests. return this.<E>reverse().leastOf(iterable, k); } /** * Returns the {@code k} greatest elements from the given iterator according to this ordering, in * order from greatest to least. If there are fewer than {@code k} elements present, all will be * included. * * <p>The implementation does not necessarily use a <i>stable</i> sorting algorithm; when multiple * elements are equivalent, it is undefined which will come first. * * <p><b>Java 8+ users:</b> Use {@code Streams.stream(iterator).collect(Comparators.greatest(k, * thisComparator))} instead. * * @return an immutable {@code RandomAccess} list of the {@code k} greatest elements in * <i>descending order</i> * @throws IllegalArgumentException if {@code k} is negative * @since 14.0 */ public <E extends T> List<E> greatestOf(Iterator<E> iterator, int k) { return this.<E>reverse().leastOf(iterator, k); } /** * Returns a <b>mutable</b> list containing {@code elements} sorted by this ordering; use this * only when the resulting list may need further modification, or may contain {@code null}. The * input is not modified. The returned list is serializable and has random access. * * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard elements that are * duplicates according to the comparator. The sort performed is <i>stable</i>, meaning that such * elements will appear in the returned list in the same order they appeared in {@code elements}. * * <p><b>Performance note:</b> According to our * benchmarking * on Open JDK 7, {@link #immutableSortedCopy} generally performs better (in both time and space) * than this method, and this method in turn generally performs better than copying the list and * calling {@link Collections#sort(List)}. */ // TODO(kevinb): rerun benchmarks including new options @SuppressWarnings("nullness") // TODO: b/316358623 - Remove after checker fix. public <E extends T> List<E> sortedCopy(Iterable<E> elements) { @SuppressWarnings("unchecked") // does not escape, and contains only E's E[] array = (E[]) Iterables.toArray(elements); Arrays.sort(array, this); return Lists.newArrayList(Arrays.asList(array)); } /** * Returns an <b>immutable</b> list containing {@code elements} sorted by this ordering. The input * is not modified. * * <p>Unlike {@link Sets#newTreeSet(Iterable)}, this method does not discard elements that are * duplicates according to the comparator. The sort performed is <i>stable</i>, meaning that such * elements will appear in the returned list in the same order they appeared in {@code elements}. * * <p><b>Performance note:</b> According to our * benchmarking * on Open JDK 7, this method is the most efficient way to make a sorted copy of a collection. * * @throws NullPointerException if any element of {@code elements} is {@code null} * @since 3.0 */ // TODO(kevinb): rerun benchmarks including new options public <E extends @NonNull T> ImmutableList<E> immutableSortedCopy(Iterable<E> elements) { return ImmutableList.sortedCopyOf(this, elements); } /** * Returns {@code true} if each element in {@code iterable} after the first is greater than or * equal to the element that preceded it, according to this ordering. Note that this is always * true when the iterable has fewer than two elements. * * <p><b>Java 8+ users:</b> Use the equivalent {@link Comparators#isInOrder(Iterable, Comparator)} * instead, since the rest of {@code Ordering} is mostly obsolete (as explained in the class * documentation). */ public boolean isOrdered(Iterable<? extends T> iterable) { Iterator<? extends T> it = iterable.iterator(); if (it.hasNext()) { T prev = it.next(); while (it.hasNext()) { T next = it.next(); if (compare(prev, next) > 0) { return false; } prev = next; } } return true; } /** * Returns {@code true} if each element in {@code iterable} after the first is <i>strictly</i> * greater than the element that preceded it, according to this ordering. Note that this is always * true when the iterable has fewer than two elements. * * <p><b>Java 8+ users:</b> Use the equivalent {@link Comparators#isInStrictOrder(Iterable, * Comparator)} instead, since the rest of {@code Ordering} is mostly obsolete (as explained in * the class documentation). */ public boolean isStrictlyOrdered(Iterable<? extends T> iterable) { Iterator<? extends T> it = iterable.iterator(); if (it.hasNext()) { T prev = it.next(); while (it.hasNext()) { T next = it.next(); if (compare(prev, next) >= 0) { return false; } prev = next; } } return true; } /** * {@link Collections#binarySearch(List, Object, Comparator) Searches} {@code sortedList} for * {@code key} using the binary search algorithm. The list must be sorted using this ordering. * * @param sortedList the list to be searched * @param key the key to be searched for * @deprecated Use {@link Collections#binarySearch(List, Object, Comparator)} directly. */ @Deprecated public int binarySearch( List<? extends T> sortedList, @ParametricNullness T key) { return Collections.binarySearch(sortedList, key, this); } /** * Exception thrown by a {@link Ordering#explicit(List)} or {@link Ordering#explicit(Object, * Object[])} comparator when comparing a value outside the set of values it can compare. * Extending {@link ClassCastException} may seem odd, but it is required. */ @VisibleForTesting static class IncomparableValueException extends ClassCastException { final Object value; IncomparableValueException(Object value) { super("Cannot compare value: " + value); this.value = value; } private static final long serialVersionUID = 0; } // Never make these public static final int LEFT_IS_GREATER = 1; static final int RIGHT_IS_GREATER = -1; }
google/guava
guava/src/com/google/common/collect/Ordering.java
428
package br.uff.spark.vfs; import ru.serce.jnrfuse.struct.FileStat; /** * Based from: https://github.com/SerCeMan/jnr-fuse/blob/master/src/main/java/ru/serce/jnrfuse/examples/MemoryFS.java */ public abstract class MemoryPath { protected MemoryFS memoryFS; protected String name; protected MemoryDirectory parent; protected MemoryPath(MemoryFS memoryFS, String name) { this(memoryFS, name, null); } protected MemoryPath(MemoryFS memoryFS, String name, MemoryDirectory parent) { this.memoryFS = memoryFS; this.name = name; this.parent = parent; } protected synchronized void delete() { if (parent != null) { parent.deleteChild(this); parent = null; } } protected MemoryPath find(String path) { while (path.startsWith("/")) { path = path.substring(1); } if (path.equals(name) || path.isEmpty()) { return this; } return null; } protected abstract void getattr(FileStat stat); protected void rename(String newName) { while (newName.startsWith("/")) { newName = newName.substring(1); } name = newName; } }
UFFeScience/SAMbA
core/src/main/java/br/uff/spark/vfs/MemoryPath.java