file_id
int64
1
215k
content
stringlengths
7
454k
repo
stringlengths
6
113
path
stringlengths
6
251
206
/** * File: Vertex.java * Created Time: 2023-02-15 * Author: krahets ([email protected]) */ package utils; import java.util.*; /* 顶点类 */ public class Vertex { public int val; public Vertex(int val) { this.val = val; } /* 输入值列表 vals ,返回顶点列表 vets */ public static Vertex[] valsToVets(int[] vals) { Vertex[] vets = new Vertex[vals.length]; for (int i = 0; i < vals.length; i++) { vets[i] = new Vertex(vals[i]); } return vets; } /* 输入顶点列表 vets ,返回值列表 vals */ public static List<Integer> vetsToVals(List<Vertex> vets) { List<Integer> vals = new ArrayList<>(); for (Vertex vet : vets) { vals.add(vet.val); } return vals; } }
krahets/hello-algo
codes/java/utils/Vertex.java
207
package com.thealgorithms.sorts; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; final class SortUtils { private SortUtils() { } /** * Swaps two elements at the given positions in an array. * * @param array the array in which to swap elements * @param i the index of the first element to swap * @param j the index of the second element to swap * @param <T> the type of elements in the array */ public static <T> void swap(T[] array, int i, int j) { T temp = array[i]; array[i] = array[j]; array[j] = temp; } /** * Compares two elements to see if the first is less than the second. * * @param firstElement the first element to compare * @param secondElement the second element to compare * @return true if the first element is less than the second, false otherwise */ public static <T extends Comparable<T>> boolean less(T firstElement, T secondElement) { return firstElement.compareTo(secondElement) < 0; } /** * Compares two elements to see if the first is greater than the second. * * @param firstElement the first element to compare * @param secondElement the second element to compare * @return true if the first element is greater than the second, false otherwise */ public static <T extends Comparable<T>> boolean greater(T firstElement, T secondElement) { return firstElement.compareTo(secondElement) > 0; } /** * Compares two elements to see if the first is greater than or equal to the second. * * @param firstElement the first element to compare * @param secondElement the second element to compare * @return true if the first element is greater than or equal to the second, false otherwise */ static <T extends Comparable<T>> boolean greaterOrEqual(T firstElement, T secondElement) { return firstElement.compareTo(secondElement) >= 0; } /** * Prints the elements of a list to standard output. * * @param listToPrint the list to print */ static void print(List<?> listToPrint) { String result = listToPrint.stream().map(Object::toString).collect(Collectors.joining(" ")); System.out.println(result); } /** * Prints the elements of an array to standard output. * * @param array the array to print */ static <T> void print(T[] array) { System.out.println(Arrays.toString(array)); } /** * Flips the order of elements in the specified range of an array. * * @param array the array whose elements are to be flipped * @param left the left boundary of the range to be flipped (inclusive) * @param right the right boundary of the range to be flipped (inclusive) */ public static <T extends Comparable<T>> void flip(T[] array, int left, int right) { while (left <= right) { swap(array, left++, right--); } } /** * Checks whether the array is sorted in ascending order. * * @param array the array to check * @return true if the array is sorted in ascending order, false otherwise */ public static <T extends Comparable<T>> boolean isSorted(T[] array) { for (int i = 1; i < array.length; i++) { if (less(array[i], array[i - 1])) { return false; } } return true; } /** * Checks whether the list is sorted in ascending order. * * @param list the list to check * @return true if the list is sorted in ascending order, false otherwise */ public static <T extends Comparable<T>> boolean isSorted(List<T> list) { for (int i = 1; i < list.size(); i++) { if (less(list.get(i), list.get(i - 1))) { return false; } } return true; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/sorts/SortUtils.java
208
/* * Copyright 2002-2023 the original author or 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 * * https://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.springframework.aop; import org.aopalliance.aop.Advice; /** * Base interface holding AOP <b>advice</b> (action to take at a joinpoint) * and a filter determining the applicability of the advice (such as * a pointcut). <i>This interface is not for use by Spring users, but to * allow for commonality in support for different types of advice.</i> * * <p>Spring AOP is based around <b>around advice</b> delivered via method * <b>interception</b>, compliant with the AOP Alliance interception API. * The Advisor interface allows support for different types of advice, * such as <b>before</b> and <b>after</b> advice, which need not be * implemented using interception. * * @author Rod Johnson * @author Juergen Hoeller */ public interface Advisor { /** * Common placeholder for an empty {@code Advice} to be returned from * {@link #getAdvice()} if no proper advice has been configured (yet). * @since 5.0 */ Advice EMPTY_ADVICE = new Advice() {}; /** * Return the advice part of this aspect. An advice may be an * interceptor, a before advice, a throws advice, etc. * @return the advice that should apply if the pointcut matches * @see org.aopalliance.intercept.MethodInterceptor * @see BeforeAdvice * @see ThrowsAdvice * @see AfterReturningAdvice */ Advice getAdvice(); /** * Return whether this advice is associated with a particular instance * (for example, creating a mixin) or shared with all instances of * the advised class obtained from the same Spring bean factory. * <p><b>Note that this method is not currently used by the framework.</b> * Typical Advisor implementations always return {@code true}. * Use singleton/prototype bean definitions or appropriate programmatic * proxy creation to ensure that Advisors have the correct lifecycle model. * <p>As of 6.0.10, the default implementation returns {@code true}. * @return whether this advice is associated with a particular target instance */ default boolean isPerInstance() { return true; } }
spring-projects/spring-framework
spring-aop/src/main/java/org/springframework/aop/Advisor.java
209
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. package org.openqa.selenium; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Indicates that a feature or API is in active development, and so should not be relied upon. The * update policy for anything marked beta is that it may be deleted in the next Selenium release * without warning. * * <p>In the ideal world, this would cause the method to <span class="blink">blink gently</span> in * the user's IDE. We don't live in the ideal world. We'll find out the hard way whether reading * docs is the same thing. */ @Retention(RetentionPolicy.RUNTIME) @Target({ ElementType.ANNOTATION_TYPE, ElementType.CONSTRUCTOR, ElementType.FIELD, ElementType.METHOD, ElementType.TYPE }) @Documented public @interface Beta {}
SeleniumHQ/selenium
java/src/org/openqa/selenium/Beta.java
211
/* * 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.http; import static java.lang.annotation.ElementType.PARAMETER; import static java.lang.annotation.RetentionPolicy.RUNTIME; import java.lang.annotation.Documented; import java.lang.annotation.Retention; import java.lang.annotation.Target; /** * Replaces the header with the value of its target. * * <pre><code> * &#64;GET("/") * Call&lt;ResponseBody&gt; foo(@Header("Accept-Language") String lang); * </code></pre> * * Header parameters may be {@code null} which will omit them from the request. Passing a {@link * java.util.List List} or array will result in a header for each non-{@code null} item. * * <p>Parameter keys and values only allows ascii values by default. Specify {@link * #allowUnsafeNonAsciiValues() allowUnsafeNonAsciiValues=true} to change this behavior. * * <pre><code> * &#64;GET("/") * Call&lt;ResponseBody&gt; foo(@Header("Accept-Language", allowUnsafeNonAsciiValues=true) String lang); * </code></pre> * * <p><strong>Note:</strong> Headers do not overwrite each other. All headers with the same name * will be included in the request. * * @see Headers * @see HeaderMap */ @Documented @Retention(RUNTIME) @Target(PARAMETER) public @interface Header { /** The query parameter name. */ String value(); /** * Specifies whether the parameter {@linkplain #value() name} and value are already URL encoded. */ boolean allowUnsafeNonAsciiValues() default false; }
square/retrofit
retrofit/src/main/java/retrofit2/http/Header.java
212
// Companion Code to the paper "Generative Trees: Adversarial and Copycat" by R. Nock and M. // Guillame-Bert, in ICML'22 import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class Unknown_Feature_Value: just to force errors if features not dealt properly during program *****/ class Unknown_Feature_Value { public static String S_UNKNOWN = "-1"; public static boolean IS_UNKNOWN(double d) { String s = "" + d; return s.equals(S_UNKNOWN); } public static boolean IS_UNKNOWN(int i) { String s = "" + i; return s.equals(S_UNKNOWN); } public static boolean IS_UNKNOWN(String s) { return s.equals(S_UNKNOWN); } public static boolean IS_UNKNOWN(Object o) { if (o.getClass().getSimpleName().equals("Unknown_Feature_Value")) return true; return false; } public String toString() { return "Unknown Feature Value"; } } /************************************************************************************************************************************** * Class Histogram: stores histograms for features *****/ class Histogram implements Debuggable { static int NUMBER_CONTINUOUS_FEATURE_BINS = 19; // make this an option -- choose a number that has little chance to produce observed values at the // boundary (e.g. large prime) static int MAX_NUMBER_INTEGER_FEATURE_BINS = 19; // make this an option // IF f.imax - f.imin + 1 > NUMBER_INTEGER_FEATURE_BINS, bins the histogram with bins of same size // up to 1 String type, name; int feature_index; // reference index as in the dataset.features Vector<Feature> histogram_features; // feature vector for the histogram // IF NOMINAL: each feature has ONE modality for the bin // IF INTEGER: each feature has imin = imax = ONE modality // IF CONTINUOUS: each feature covers an interval [dmin, dmax] : NOTE closedness of intervals, not // an issue from measure standpoint Vector<Double> histogram_proportions; // in 1:1 wrt histogram_features Vector<Integer> histogram_counts; // in 1:1 wrt histogram_features Histogram() { type = name = ""; feature_index = -1; histogram_features = null; histogram_proportions = null; histogram_counts = null; } Histogram(int find, Feature f) { // creates an empty histogram: initialise the histogram_proportions to 0.0 feature_index = find; int i, index, ibinsize, ibinmin, ibinmax; double delta, be, en, local_eps; Vector<String> dumm; int[] binsize; histogram_features = new Vector<>(); histogram_proportions = new Vector<>(); histogram_counts = new Vector<>(); type = f.type; name = f.name; if (Feature.IS_NOMINAL(f.type)) { if ((f.modalities == null) || (f.modalities.size() == 0)) Dataset.perror("Histogram.class :: cannot create histogram for feature " + f); for (i = 0; i < f.modalities.size(); i++) { dumm = new Vector<>(); dumm.addElement(f.modalities.elementAt(i)); histogram_features.addElement( new Feature(f.name + "_" + i, f.type, dumm, f.dmin, f.dmax, false)); } } else if (Feature.IS_CONTINUOUS(f.type)) { if (f.dmax == f.dmin) Dataset.perror("Histogram.class :: cannot create histogram for feature " + f); delta = (f.dmax - f.dmin) / (double) NUMBER_CONTINUOUS_FEATURE_BINS; be = f.dmin; for (i = 0; i < NUMBER_CONTINUOUS_FEATURE_BINS; i++) { en = be + delta; if (i == NUMBER_CONTINUOUS_FEATURE_BINS - 1) en = f.dmax; histogram_features.addElement( new Feature(f.name + "_" + i, f.type, f.modalities, be, en, false)); be = en; } } else if (Feature.IS_INTEGER(f.type)) { if (f.imax - f.imin + 1 > MAX_NUMBER_INTEGER_FEATURE_BINS) ibinsize = MAX_NUMBER_INTEGER_FEATURE_BINS; else ibinsize = f.imax - f.imin + 1; binsize = new int[ibinsize]; index = 0; for (i = 0; i < f.imax - f.imin + 1; i++) { binsize[index]++; index += 1; if (index > ibinsize - 1) index = 0; } ibinmin = f.imin; for (i = 0; i < ibinsize; i++) { ibinmax = ibinmin + binsize[i] - 1; histogram_features.addElement( new Feature( f.name + "_" + i, f.type, f.modalities, (double) ibinmin, (double) ibinmax, false)); ibinmin = ibinmax + 1; } } for (i = 0; i < histogram_features.size(); i++) { histogram_proportions.addElement(new Double(0.0)); histogram_counts.addElement(new Integer(0)); } } public static Histogram copyOf(Histogram href) { Histogram ret = new Histogram(); ret.feature_index = href.feature_index; ret.type = href.type; ret.name = href.name; ret.histogram_features = new Vector<>(); ret.histogram_proportions = new Vector<>(); ret.histogram_counts = new Vector<>(); int i; for (i = 0; i < href.histogram_features.size(); i++) { ret.histogram_features.addElement( Feature.copyOf(href.histogram_features.elementAt(i), false)); ret.histogram_proportions.addElement( new Double(href.histogram_proportions.elementAt(i).doubleValue())); ret.histogram_counts.addElement(new Integer(href.histogram_counts.elementAt(i).intValue())); } return ret; } public int index_bin(Example e) { // returns the index of the bin the example fills in (DOES NOT USE UNKNOWN FEATURES IF ANY) int i; int index = -1; // -1 = EXAMPLES HAS UNKNOWN FEATURE VALUE int number_satisfied = 0; if (!Example.FEATURE_IS_UNKNOWN(e, feature_index)) { // written for checks, can be sped up for (i = 0; i < histogram_proportions.size(); i++) { if (Feature.EXAMPLE_MATCHES_FEATURE( e, histogram_features.elementAt(i), feature_index, histogram_features.elementAt(i).type)) { if ((index == -1) || (Algorithm.R.nextDouble() < 0.5)) { index = i; number_satisfied++; } } } if (index == -1) { System.out.println(e + " :: "); for (i = 0; i < histogram_proportions.size(); i++) System.out.println(histogram_features.elementAt(i)); Dataset.perror("Histogram.class :: example " + e + " has no bin in histogram "); } } return index; } public double percentage_intersection(int bin_index, Feature f) { if (!name.equals(f.name)) Dataset.perror( "Feature.class :: name mismatch to compute probability_vector (" + name + " != " + f.name + ")"); if (!type.equals(f.type)) Dataset.perror( "Feature.class :: type mismatch to compute probability_vector (" + type + " != " + f.type + ")"); double p = -1.0, i, r, l; if (Feature.IS_NOMINAL(f.type)) { if (f.modalities.contains( (String) histogram_features.elementAt(bin_index).modalities.elementAt(0))) p = 1.0 / ((double) f.modalities.size()); else p = 0.0; } else if (Feature.IS_INTEGER(f.type)) { int tmin, tmax, fmin, fmax; tmin = histogram_features.elementAt(bin_index).imin; tmax = histogram_features.elementAt(bin_index).imax; fmin = f.imin; fmax = f.imax; if ((tmax < fmin) || (fmax < tmin)) return 0.0; if (fmax > tmax) r = (double) tmax; else r = (double) fmax; if (fmin < tmin) l = (double) tmin; else l = (double) fmin; p = (r - l + 1.0) / ((double) fmax - fmin + 1); } else if (Feature.IS_CONTINUOUS(f.type)) { double tmin, tmax, fmin, fmax; tmin = histogram_features.elementAt(bin_index).dmin; tmax = histogram_features.elementAt(bin_index).dmax; fmin = f.dmin; fmax = f.dmax; if ((tmax <= fmin) || (fmax <= tmin)) return 0.0; if (fmax > tmax) r = tmax; else r = fmax; if (fmin < tmin) l = tmin; else l = fmin; p = (r - l) / (fmax - fmin); } return p; } public double[] normalized_domain_intersection_with(Feature f) { // returns a vector WHOSE composants sum to 1.0, // counting the per-bin % intersection with 'f.domain' int i; double[] ret = new double[histogram_features.size()]; double tot = 0.0; for (i = 0; i < histogram_features.size(); i++) { ret[i] = percentage_intersection(i, f); tot += ret[i]; } if ((tot != 1.0) && (!(Statistics.APPROXIMATELY_EQUAL(tot, 1.0, EPS2)))) Dataset.perror( "Histogram.class :: domain intersection not unit but = " + tot + " for feature " + f + " vs histogram " + this.toStringSave()); return ret; } public boolean fill_histogram(Vector<Example> v, boolean use_weights) { // fills histogram // returns true IFF found at least one example with non-UNKNOWN value for feature int i, index, count; double tot_weight = 0.0, eweight, oldw; Example e; boolean ok = false; for (i = 0; i < v.size(); i++) { e = v.elementAt(i); index = index_bin(e); if (index != -1) { if (use_weights) eweight = e.unnormalized_weight; else eweight = 1.0; oldw = histogram_proportions.elementAt(index).doubleValue(); count = histogram_counts.elementAt(index).intValue(); oldw += eweight; count++; histogram_proportions.setElementAt(new Double(oldw), index); histogram_counts.setElementAt(new Integer(count), index); tot_weight += eweight; ok = true; } } if (tot_weight == 0.0) Dataset.perror("Histogram.class :: no weight counted in filling histogram "); for (i = 0; i < histogram_proportions.size(); i++) { oldw = histogram_proportions.elementAt(i).doubleValue(); histogram_proportions.setElementAt(new Double(oldw / tot_weight), i); } return ok; } public void checkNormalized() { // check the histogram is normalized double tot = 0.0; int i; for (i = 0; i < histogram_proportions.size(); i++) tot += histogram_proportions.elementAt(i).doubleValue(); if (!Statistics.APPROXIMATELY_EQUAL(tot, 1.0, EPS)) Dataset.perror("Histogram.class :: not normalized "); } public String bucket_labels() { String v = ""; int i; if (Feature.IS_NOMINAL(type)) { for (i = 0; i < histogram_features.size(); i++) { v += (histogram_features.elementAt(i)).modalities.elementAt(0); v += "\t(std_dev)"; if (i < histogram_features.size() - 1) v += "\t"; } } else if (Feature.IS_CONTINUOUS(type)) { for (i = 0; i < histogram_features.size(); i++) { v += "[" + DF6.format((histogram_features.elementAt(i)).dmin) + "," + DF6.format((histogram_features.elementAt(i)).dmax) + "]"; v += "\t(std_dev)"; if (i < histogram_features.size() - 1) v += "\t"; } } else if (Feature.IS_INTEGER(type)) { for (i = 0; i < histogram_features.size(); i++) { v += "{" + (histogram_features.elementAt(i)).imin; if ((histogram_features.elementAt(i)).imax == (histogram_features.elementAt(i)).imin + 1) v += ", " + (histogram_features.elementAt(i)).imax; else if ((histogram_features.elementAt(i)).imax > (histogram_features.elementAt(i)).imin + 1) v += ",... " + (histogram_features.elementAt(i)).imax; v += "}"; v += "\t(std_dev)"; if (i < histogram_features.size() - 1) v += "\t"; } } return v; } public String bucket_proportions() { String v = ""; int i; for (i = 0; i < histogram_proportions.size(); i++) { v += "" + DF6.format(histogram_proportions.elementAt(i).doubleValue()); v += "\t0.0"; if (i < histogram_proportions.size() - 1) v += "\t"; } return v; } public String binsToString() { String v = ""; int i; v += Dataset.KEY_COMMENT + name + " (" + type + ") "; if (Feature.IS_CONTINUOUS(type)) v += "[#bins:" + NUMBER_CONTINUOUS_FEATURE_BINS + "]"; else if (Feature.IS_INTEGER(type)) v += "{max #bins:" + MAX_NUMBER_INTEGER_FEATURE_BINS + "}"; v += ":\n"; v += Dataset.KEY_COMMENT; v += bucket_labels(); v += "\n"; return v; } public String toStringSave() { String v = ""; int i; checkNormalized(); v += Dataset.KEY_COMMENT + name + " (" + type + ") "; if (Feature.IS_CONTINUOUS(type)) v += "[#bins:" + NUMBER_CONTINUOUS_FEATURE_BINS + "]"; else if (Feature.IS_INTEGER(type)) v += "{max #bins:" + MAX_NUMBER_INTEGER_FEATURE_BINS + "}"; v += ":\n"; v += Dataset.KEY_COMMENT; v += bucket_proportions(); v += "\n"; v += Dataset.KEY_COMMENT; v += bucket_labels(); v += "\n"; return v; } } /************************************************************************************************************************************** * Class Feature *****/ class Feature implements Debuggable { // All purpose variables (Discriminator and Generator) public static String NOMINAL = "NOMINAL", CONTINUOUS = "CONTINUOUS", INTEGER = "INTEGER"; public static String TYPE[] = {Feature.NOMINAL, Feature.CONTINUOUS, Feature.INTEGER}; public static int TYPE_INDEX(String s) { int i = 0; while (i < TYPE.length) { if (TYPE[i].equals(s)) return i; i++; } return -1; } public static String DISPERSION_NAME[] = {"Entropy", "Variance", "Variance"}; // Discriminator relevant variables public static int NUMBER_CONTINUOUS_TIES = 100; // splits the interval in this number of internal splits (results in N+1 subintervals) FOR // CONTINUOUS VARIABLES public static int FORBIDDEN_VALUE = -100000; // value to initialise doubles and int. Must not be in dataset public static boolean DISPLAY_TESTS = false; // All purpose variables String name; String type; // Feature specific domain stuff -- redesign w/ a specific class for Generics Vector<String> modalities; // applies only to Feature.NOMINAL features double dmin, dmax; // applies only to Feature.CONTINUOUS features int imin, imax; // applies only to Feature.INTEGER features double dispertion_statistic_value; // Entropy for nominal, variance for ordered boolean formatted_for_a_dt; double[] dsplits_from_training; // COMPUTED int dmin_index_in_dsplits_from_training; // index of smallest split >= dmin int dmax_index_in_dsplits_from_training; // index of largest split <= dmax int[] isplits_from_training; int imin_index_in_dsplits_from_training; // index of smallest split >= imin int imax_index_in_dsplits_from_training; // index of largest split <= imax double dmin_from_data, dmax_from_data; // applies only to Feature.CONTINUOUS features int imin_from_data, imax_from_data; // applies only to Feature.INTEGER features // Generator relevant variables boolean empty_domain; // for Generator: true iff the feature can be used for generation at a given node // Discriminator relevant variables Vector tests; // set of test values as returned by TEST_LIST public static String SAVE_FEATURE(Feature f) { String ret = ""; ret += f.name + "\t" + f.type + "\t"; int i; if (Feature.IS_NOMINAL(f.type)) { if (f.modalities == null) ret += "null"; else if (f.modalities.size() == 0) ret += "{}"; else for (i = 0; i < f.modalities.size(); i++) { ret += (String) f.modalities.elementAt(i); if (i < f.modalities.size() - 1) ret += "\t"; } } else if (Feature.IS_CONTINUOUS(f.type)) { ret += f.dmin + "\t" + f.dmax; if (f.dmin_from_data != f.dmax_from_data) ret += "\t" + f.dmin_from_data + "\t" + f.dmax_from_data; } else if (Feature.IS_INTEGER(f.type)) { ret += f.imin + "\t" + f.imax; if (f.imin_from_data != f.imax_from_data) ret += "\t" + f.imin_from_data + "\t" + f.imax_from_data; } return ret; } public double length() { double l = -1.0; if (Feature.IS_CONTINUOUS(type)) l = dmax - dmin; else if (Feature.IS_INTEGER(type)) l = (double) imax - (double) imin + 1.0; else if (Feature.IS_NOMINAL(type)) l = (double) modalities.size(); if (l < 0.0) Dataset.perror("Feature.class :: feature " + this + " has <0 length"); return l; } public boolean equals(Object o) { // makes sure the tests are ALSO in the SAME ORDER in both Features int i, j; if (o == this) return true; if (!(o instanceof Feature)) return false; Feature f = (Feature) o; if (!((((Feature.IS_NOMINAL(f.type)) && (Feature.IS_NOMINAL(type))) || ((Feature.IS_INTEGER(f.type)) && (Feature.IS_INTEGER(type))) || ((Feature.IS_CONTINUOUS(f.type)) && (Feature.IS_CONTINUOUS(type)))))) return false; if ((f.dmin_from_data != dmin_from_data) || (f.dmax_from_data != dmax_from_data) || (f.dmin != dmin) || (f.dmax != dmax) || (f.imin_from_data != imin_from_data) || (f.imax_from_data != imax_from_data) || (f.imin != imin) || (f.imax != imax)) return false; if (Feature.IS_NOMINAL(f.type)) { Vector<String> vf_test, v_test; if (f.modalities.size() != modalities.size()) return false; for (i = 0; i < f.modalities.size(); i++) if (!((String) f.modalities.elementAt(i)).equals(modalities.elementAt(i))) return false; if (f.tests.size() != tests.size()) return false; for (i = 0; i < f.tests.size(); i++) { vf_test = (Vector<String>) f.tests.elementAt(i); v_test = (Vector<String>) tests.elementAt(i); if (vf_test.size() != v_test.size()) return false; for (j = 0; j < vf_test.size(); j++) if (!((String) vf_test.elementAt(j)).equals(v_test.elementAt(j))) return false; } } else if (Feature.IS_INTEGER(f.type)) { if (f.tests.size() != tests.size()) return false; for (i = 0; i < f.tests.size(); i++) if (((Integer) f.tests.elementAt(i)).intValue() != ((Integer) tests.elementAt(i)).intValue()) return false; } else if (Feature.IS_CONTINUOUS(f.type)) { if (f.tests.size() != tests.size()) return false; for (i = 0; i < f.tests.size(); i++) if (((Double) f.tests.elementAt(i)).doubleValue() != ((Double) tests.elementAt(i)).doubleValue()) return false; } return true; } public static Feature copyOf(Feature f, boolean compute_tests) { // compute_tests = save memory for nominal features if tests not necessary Vector<String> v = null; double miv = (double) Feature.FORBIDDEN_VALUE, mav = (double) Feature.FORBIDDEN_VALUE; if (Feature.IS_NOMINAL(f.type)) v = new Vector<String>(f.modalities); else if (Feature.IS_CONTINUOUS(f.type)) { miv = f.dmin; mav = f.dmax; } else if (Feature.IS_INTEGER(f.type)) { miv = f.imin; mav = f.imax; } Feature fn = new Feature(f.name, f.type, v, miv, mav, compute_tests); if (Feature.IS_CONTINUOUS(f.type)) { fn.dmin_from_data = f.dmin_from_data; fn.dmax_from_data = f.dmax_from_data; fn.imin = fn.imax = fn.imin_from_data = fn.imax_from_data = Feature.FORBIDDEN_VALUE; } else if (Feature.IS_INTEGER(f.type)) { fn.imin_from_data = f.imin_from_data; fn.imax_from_data = f.imax_from_data; fn.dmin = fn.dmax = fn.dmin_from_data = fn.dmax_from_data = Feature.FORBIDDEN_VALUE; } return fn; } public static Feature copyOf( Feature f, boolean compute_tests, boolean use_double_splits_from_training, Dataset ds, int f_index) { // make use this is not used for non CONTINUOUS VARIABLES or not for DT induction if (!use_double_splits_from_training) return copyOf(f, compute_tests); else { if (!Feature.IS_CONTINUOUS(f.type)) Dataset.perror("Feature.class :: copyOf has to be sent for continuous variables"); Feature fn = copyOf(f, compute_tests); // updates of tests related variables int i; if (f.tests == null) fn.tests = null; else { if (f.tests.size() == 0) Dataset.perror( "Feature.class :: zero test in a non-null test vector -- this is an error"); fn.tests = new Vector<Double>(); fn.dmin_index_in_dsplits_from_training = f.dmin_index_in_dsplits_from_training; fn.dmax_index_in_dsplits_from_training = f.dmax_index_in_dsplits_from_training; for (i = 0; i < f.tests.size(); i++) fn.tests.addElement(new Double(((Double) f.tests.elementAt(i)).doubleValue())); } return fn; } } public static boolean EXAMPLE_MATCHES_FEATURE(Example e, Feature f, int f_index, String f_type) { // checks whether e.typed_features.elementAt(f_index) is in domain of f if (e.typed_features .elementAt(f_index) .getClass() .getSimpleName() .equals("Unknown_Feature_Value")) return true; double ed; int ei; String es; if (f_type.equals(Feature.CONTINUOUS)) { if (!Feature.IS_CONTINUOUS(f.type)) Dataset.perror("Feature.class :: feature type mismatch -- CONTINUOUS"); ed = ((Double) e.typed_features.elementAt(f_index)).doubleValue(); if ((ed >= f.dmin) && (ed <= f.dmax)) return true; else return false; } else if (f_type.equals(Feature.INTEGER)) { if (!Feature.IS_INTEGER(f.type)) Dataset.perror("Feature.class :: feature type mismatch -- INTEGER"); ei = ((Integer) e.typed_features.elementAt(f_index)).intValue(); if ((ei >= f.imin) && (ei <= f.imax)) return true; else return false; } else if (f_type.equals(Feature.NOMINAL)) { if (!Feature.IS_NOMINAL(f.type)) Dataset.perror("Feature.class :: feature type mismatch -- NOMINAL"); es = (String) e.typed_features.elementAt(f_index); if (f.modalities.contains(es)) return true; else return false; } else Dataset.perror("Feature.class :: feature type unknown"); return true; } public static double RELATIVE_PERCENTAGE_SUPPORT(Feature a, Feature b) { // returns size_domain(a \cap b) / size_domain(b) double num = 0.0, den = 0.0, dinf, dsup, rat = -1.0; int i; if (!a.type.equals(b.type)) Dataset.perror("Feature.class :: not the same class for features"); if (Feature.IS_CONTINUOUS(a.type)) { if ((b.dmax == b.dmin) || (a.dmax <= b.dmin) || (a.dmin >= b.dmax)) return 0.0; if (a.dmin < b.dmin) dinf = b.dmin; else dinf = a.dmin; if (a.dmax > b.dmax) dsup = b.dmax; else dsup = a.dmax; num = dsup - dinf; den = b.dmax - b.dmin; } else if (Feature.IS_INTEGER(a.type)) { if ((a.imax < b.imin) || (a.imin > b.imax)) return 0.0; if (a.imin <= b.imin) dinf = (double) b.imin; else dinf = (double) a.imin; if (a.imax >= b.imax) dsup = (double) b.imax; else dsup = (double) a.imax; num = dsup - dinf + 1.0; den = ((double) (b.imax - b.imin)) + 1.0; } else if (Feature.IS_NOMINAL(a.type)) { if (b.modalities.size() == 0) return 0.0; else den = (double) b.modalities.size(); num = 0.0; for (i = 0; i < a.modalities.size(); i++) if (b.modalities.contains((String) a.modalities.elementAt(i))) num += 1.0; } else Dataset.perror("Feature.class :: feature type unknown"); rat = num / den; if ((rat < 0.0) || (rat > 1.0)) Dataset.perror("Feature.class :: ratio " + rat + " not a probability"); return rat; } public static double RELATIVE_PERCENTAGE_SUPPORT( Discriminator_Node dn_leaf, Generator_Tree gt, Generator_Node gn_leaf) { // Pr[dn_leaf | ~gn_leaf] // returns the relative percentage (wrt gn_leaf) of the support intersection with dn_leaf // do not forget to *= gn_leaf.local_p = Pr[~gn_leaf] for n_lambda if (!dn_leaf.is_leaf) { if ((!dn_leaf.left_child.is_pure()) && (!dn_leaf.right_child.is_pure())) Dataset.perror( "Feature.class :: Discriminator_Node #" + dn_leaf.name + " not a discriminator leaf BUT both children nodes not pure"); } if (!gn_leaf.is_leaf) Dataset.perror("Feature.class :: not a generator leaf"); Vector<Feature> vf_dn = dn_leaf.support_at_classification_node; Vector<Feature> vf_gn = Generator_Node.ALL_FEATURES_DOMAINS_AT_SAMPLING_NODE(gt, gn_leaf); int i; double v = 1.0; if (vf_dn.size() != vf_gn.size()) Dataset.perror("Feature.class :: Feature vectors not of the same size"); double[] all_rat = new double[vf_gn.size()]; for (i = 0; i < vf_gn.size(); i++) { all_rat[i] = Feature.RELATIVE_PERCENTAGE_SUPPORT(vf_dn.elementAt(i), vf_gn.elementAt(i)); v *= all_rat[i]; } return v; } public static double RELATIVE_PERCENTAGE_SUPPORT( Discriminator_Node dn_leaf, Generator_Tree gt, Generator_Node gn_leaf, Feature sub_feature, int sub_feature_index) { // Pr[dn_leaf | ~gn_leaf \wedge X_[l|r]] // returns the relative percentage (wrt gn_leaf) of the support intersection with dn_leaf // do not forget to *= gn_leaf.local_p for n_lambda if (!dn_leaf.is_leaf) { if ((!dn_leaf.left_child.is_pure()) && (!dn_leaf.right_child.is_pure())) Dataset.perror( "Feature.class :: Discriminator_Node #" + dn_leaf.name + " not a discriminator leaf BUT both children nodes not pure"); } if (!gn_leaf.is_leaf) Dataset.perror("Feature.class :: not a generator leaf"); Vector<Feature> vf_dn = dn_leaf.support_at_classification_node; Vector<Feature> vf_gn = Generator_Node.ALL_FEATURES_DOMAINS_AT_SAMPLING_NODE(gt, gn_leaf); if (!IS_SUBFEATURE(sub_feature, vf_gn.elementAt(sub_feature_index))) Dataset.perror( "Feature.class :: " + sub_feature + " not a subfeature of " + vf_gn.elementAt(sub_feature_index)); vf_gn.setElementAt(sub_feature, sub_feature_index); int i; double v = 1.0; if (vf_dn.size() != vf_gn.size()) Dataset.perror("Feature.class :: Feature vectors not of the same size"); double[] all_rat = new double[vf_gn.size()]; for (i = 0; i < vf_gn.size(); i++) { all_rat[i] = Feature.RELATIVE_PERCENTAGE_SUPPORT(vf_dn.elementAt(i), vf_gn.elementAt(i)); v *= all_rat[i]; } return v; } public static boolean HAS_SINGLETON_DOMAIN(Feature f_node) { // such features MUST NOT be split (important when unknown feature values) if ((Feature.IS_INTEGER(f_node.type)) && (f_node.imin == f_node.imax)) return true; if (Feature.IS_NOMINAL(f_node.type)) { if (f_node.modalities == null) Dataset.perror("Feature.class :: untestable feature"); if (f_node.modalities.size() == 0) Dataset.perror("Feature.class :: feature with empty domain"); if (f_node.modalities.size() == 1) return true; } return false; } public static boolean SPLIT_AUTHORIZED(Feature f_split) { if (!Discriminator_Tree.USE_OBSERVED_FEATURE_VALUES_FOR_SPLITS) return true; if (!Feature.IS_CONTINUOUS(f_split.type)) return true; if ((f_split.dmin_index_in_dsplits_from_training <= f_split.dmax_index_in_dsplits_from_training) && (f_split.dmin_index_in_dsplits_from_training != -1) && (f_split.dmax_index_in_dsplits_from_training != -1)) return true; return false; } public static Vector<Feature>[] SPLIT_SUPPORT_DT_INDUCTION( Discriminator_Node dn, int feature_index, int test_index_in_feature_index, Dataset ds) { // returns two vectors, each being the full support of dn after its split on test_index w/ // feature_index // WARNING: test_index_reference gives the test IN THE ROOT'S FEATURE'S SET ("reference", given // in args) // 0 = left, 1 = right; Vector<Feature>[] split = new Vector[2]; split[0] = new Vector<Feature>(); split[1] = new Vector<Feature>(); Feature[] split_feature; int i, excluded_index = test_index_in_feature_index; for (i = 0; i < dn.support_at_classification_node.size(); i++) { if (i == feature_index) { split_feature = SPLIT_FEATURE( dn.support_at_classification_node.elementAt(i), test_index_in_feature_index, true); if ((Feature.IS_CONTINUOUS(dn.support_at_classification_node.elementAt(i).type)) && (Discriminator_Tree.USE_OBSERVED_FEATURE_VALUES_FOR_SPLITS)) { if ((dn.support_at_classification_node.elementAt(i).dmin_index_in_dsplits_from_training == -1) || (dn.support_at_classification_node.elementAt(i).dmax_index_in_dsplits_from_training == -1)) Dataset.perror("Feature.class :: feature should not be splittable"); if (test_index_in_feature_index > 0) { split_feature[0].dmin_index_in_dsplits_from_training = dn.support_at_classification_node.elementAt(i).dmin_index_in_dsplits_from_training; split_feature[0].dmax_index_in_dsplits_from_training = dn.support_at_classification_node.elementAt(i).dmin_index_in_dsplits_from_training + test_index_in_feature_index - 1; split_feature[0].try_format_tests(ds, i, false); } else { split_feature[0].dmin_index_in_dsplits_from_training = split_feature[0].dmax_index_in_dsplits_from_training = -1; split_feature[0].tests = null; } if (test_index_in_feature_index < dn.support_at_classification_node.elementAt(i).dmax_index_in_dsplits_from_training - dn.support_at_classification_node.elementAt(i) .dmin_index_in_dsplits_from_training) { split_feature[1].dmin_index_in_dsplits_from_training = dn.support_at_classification_node.elementAt(i).dmin_index_in_dsplits_from_training + test_index_in_feature_index + 1; split_feature[1].dmax_index_in_dsplits_from_training = dn.support_at_classification_node.elementAt(i).dmax_index_in_dsplits_from_training; split_feature[1].try_format_tests(ds, i, false); } else { split_feature[1].dmin_index_in_dsplits_from_training = split_feature[1].dmin_index_in_dsplits_from_training = -1; split_feature[1].tests = null; } CHECK_TESTS_DISJOINT_UNION( dn.support_at_classification_node.elementAt(i), split_feature[0], split_feature[1], excluded_index); } split[0].addElement((Feature) split_feature[0]); split[1].addElement((Feature) split_feature[1]); } else if (Feature.IS_CONTINUOUS(dn.support_at_classification_node.elementAt(i).type)) { split[0].addElement( Feature.copyOf( (Feature) dn.support_at_classification_node.elementAt(i), true, Discriminator_Tree.USE_OBSERVED_FEATURE_VALUES_FOR_SPLITS, ds, i)); split[1].addElement( Feature.copyOf( (Feature) dn.support_at_classification_node.elementAt(i), true, Discriminator_Tree.USE_OBSERVED_FEATURE_VALUES_FOR_SPLITS, ds, i)); } else { split[0].addElement( Feature.copyOf((Feature) dn.support_at_classification_node.elementAt(i), true)); split[1].addElement( Feature.copyOf((Feature) dn.support_at_classification_node.elementAt(i), true)); } } return split; } public static void TEST_UNION(Feature f_parent, Feature f_left, Feature f_right) { // controls the union of the children features is the parent // ensures the children have non-empty domain int i; if ((!f_parent.type.equals(f_left.type)) || (!f_parent.type.equals(f_right.type))) Dataset.perror( "Feature.class :: parent feature of type " + f_parent.type + " but children: " + f_left.type + ", " + f_right.type); if (Feature.IS_CONTINUOUS(f_parent.type)) { if ((f_left.dmin != f_parent.dmin) || (f_right.dmax != f_parent.dmax)) Dataset.perror("Feature.class :: double domain does not cover parent's range"); if (f_left.dmax != f_right.dmin) Dataset.perror("Feature.class :: double domain union mismatch"); } else if (Feature.IS_INTEGER(f_parent.type)) { if ((f_left.imin != f_parent.imin) || (f_right.imax != f_parent.imax)) Dataset.perror("Feature.class :: integer domain does not cover parent's range"); if (f_left.imax + 1 != f_right.imin) Dataset.perror( "Feature.class :: integer domain union mismatch : f_left.imax = " + f_left.imax + ", f_right.imin = " + f_right.imin); } else if (Feature.IS_NOMINAL(f_parent.type)) { if ((f_left.modalities == null) || (f_right.modalities == null)) Dataset.perror("Feature.class :: nominal domain has null domain in a child"); if ((f_left.modalities.size() == 0) || (f_right.modalities.size() == 0)) Dataset.perror("Feature.class :: nominal domain has empty domain in a child"); if (f_parent.modalities == null) Dataset.perror("Feature.class :: nominal domain has null domain in parent"); if (f_parent.modalities.size() == 0) Dataset.perror("Feature.class :: nominal domain has empty domain in parent"); for (i = 0; i < f_left.modalities.size(); i++) if (!f_parent.modalities.contains((String) f_left.modalities.elementAt(i))) Dataset.perror( "Feature.class :: parent's nominal domain does not contain left child modality " + ((String) f_left.modalities.elementAt(i))); for (i = 0; i < f_right.modalities.size(); i++) if (!f_parent.modalities.contains((String) f_right.modalities.elementAt(i))) Dataset.perror( "Feature.class :: parent's nominal domain does not contain right child modality " + ((String) f_right.modalities.elementAt(i))); if (f_left.modalities.size() + f_right.modalities.size() != f_parent.modalities.size()) Dataset.perror( "Feature.class :: parent's nominal domain contains modalities not in children"); } } public static Feature[] SPLIT_FEATURE(Feature f, int test_index, boolean compute_tests) { // returns TWO features by applying f.tests.elementAt(test_index) to the domain of f // base_name used to name the features Feature[] ft = new Feature[2]; Feature left = null, right = null; Vector<String> vright; int i, bound; if (Feature.IS_CONTINUOUS(f.type)) { left = new Feature( f.name, f.type, f.modalities, f.dmin, ((Double) f.tests.elementAt(test_index)).doubleValue(), compute_tests); right = new Feature( f.name, f.type, f.modalities, ((Double) f.tests.elementAt(test_index)).doubleValue(), f.dmax, compute_tests); } else if (Feature.IS_INTEGER(f.type)) { if (test_index < f.tests.size() - 1) bound = ((Integer) f.tests.elementAt(test_index + 1)) .intValue(); // takes the next value in the test list else bound = f.imax; // just the max available left = new Feature( f.name, f.type, f.modalities, f.imin, ((Integer) f.tests.elementAt(test_index)).intValue(), compute_tests); right = new Feature(f.name, f.type, f.modalities, bound, f.imax, true); } else if (Feature.IS_NOMINAL(f.type)) { if (f.tests == null) Dataset.perror( "Feature.class :: no test for nominal feature " + f + " at index " + test_index); left = new Feature( f.name, f.type, (Vector<String>) f.tests.elementAt(test_index), f.dmin, f.dmax, compute_tests); vright = new Vector<String>(); for (i = 0; i < f.modalities.size(); i++) { if (!((Vector) f.tests.elementAt(test_index)).contains((String) f.modalities.elementAt(i))) vright.addElement(new String((String) f.modalities.elementAt(i))); } if (vright.size() == 0) Dataset.perror("Feature.class :: no modality to add to the right split"); right = new Feature(f.name, f.type, vright, f.dmin, f.dmax, compute_tests); } ft[0] = left; ft[1] = right; return ft; } public static boolean IS_SUBFEATURE(Feature a, Feature b) { // checks if domain(a) \subseteq domain(b) return IS_SUBFEATURE(a, -1, b, -1); } public static boolean IS_SUBFEATURE(Feature a, int index_a, Feature b, int index_b) { // checks if domain(a) \subseteq domain(b) AND returns an error if index_a != index_b (in // myDomain.myDS.features) // also checks inconsistencies: one of a or b must be a subfeature of the other AND the feature // type values must have been computed boolean anotinb, bnotina; int i, ia, ib; if (index_a != index_b) Dataset.perror("Feature.class :: not the same feature (" + index_a + " != " + index_b + ")"); if (!a.type.equals(b.type)) Dataset.perror( "Feature.class :: not the same type of feature (" + a.type + " != " + b.type + ")"); if (IS_CONTINUOUS(a.type)) { if (a.dmin >= b.dmin) { if (a.dmax <= b.dmax) return true; else Dataset.perror( "Feature.class :: inconsistency for subfeature check for : (" + a.dmin + ", " + a.dmax + ") subseteq (" + b.dmin + ", " + b.dmax + ") ? "); } else if (a.dmax < b.dmax) Dataset.perror( "Feature.class :: inconsistency for subfeature check for : (" + a.dmin + ", " + a.dmax + ") subseteq (" + b.dmin + ", " + b.dmax + ") ? "); } else if (IS_INTEGER(a.type)) { if (a.imin >= b.imin) { if (a.imax <= b.imax) return true; else Dataset.perror( "Feature.class :: inconsistency for subfeature check for : (" + a.imin + ", " + a.imax + ") subseteq (" + b.imin + ", " + b.imax + ") ? "); } else if (a.imax < b.imax) Dataset.perror( "Feature.class :: inconsistency for subfeature check for : (" + a.imin + ", " + a.imax + ") subseteq (" + b.imin + ", " + b.imax + ") ? "); } else if (IS_NOMINAL(a.type)) { if (a.modalities == null) return true; else if (b.modalities != null) { anotinb = bnotina = false; ia = ib = -1; for (i = 0; i < a.modalities.size(); i++) if (!b.modalities.contains((String) a.modalities.elementAt(i))) { anotinb = true; ia = i; } for (i = 0; i < b.modalities.size(); i++) if (!a.modalities.contains((String) b.modalities.elementAt(i))) { bnotina = true; ib = i; } if ((anotinb) && (bnotina)) Dataset.perror( "Feature.class :: inconsistency for subfeature check for : " + ((String) a.modalities.elementAt(ia)) + " not in b and " + ((String) b.modalities.elementAt(ib)) + " not in a "); else if (!anotinb) return true; } } else Dataset.perror("Feature.class :: no Feature type for " + a.type); return false; } public static Vector TEST_LIST(Feature f) { // if continuous, list of evenly spaced ties UNLESS // split_for_a_dt_and_use_observed_values_for_splits = true, in which case uses splits computed // from training sample // if nominal, list of partial non-empty subsets of the whole set // if integer, list of integers Vector v = new Vector(); if (IS_CONTINUOUS(f.type)) { if (f.dmax - f.dmin <= 0.0) { v = null; } else { double vmin = f.dmin; double vmax = f.dmax; double delta = (vmax - vmin) / ((double) (NUMBER_CONTINUOUS_TIES + 1)); double vcur = vmin + delta; int i; for (i = 0; i < NUMBER_CONTINUOUS_TIES; i++) { v.addElement(new Double(vcur)); vcur += delta; } } } else if (IS_INTEGER(f.type)) { if (f.imax - f.imin <= 0) { v = null; } else { int vmin = f.imin; int nvals = f.imax - f.imin; int i; for (i = 0; i < nvals; i++) { v.addElement(new Integer(vmin + i)); } } } else if (IS_NOMINAL(f.type)) { if (!Discriminator_Tree.RANDOMISE_SPLIT_FINDING_WHEN_TOO_MANY_SPLITS) v = Utils.ALL_NON_TRIVIAL_SUBSETS(f.modalities); else if (f.modalities.size() <= Discriminator_Tree.MAX_CARD_MODALITIES_BEFORE_RANDOMISATION) v = Utils.ALL_NON_TRIVIAL_SUBSETS(f.modalities); else v = Utils.ALL_NON_TRIVIAL_BOUNDED_SUBSETS( f.modalities, Discriminator_Tree.MAX_SIZE_FOR_RANDOMISATION); if (v.size() == 0) v = null; } return v; } public String tests(boolean show_all) { int max_display = 5; if (show_all) max_display = tests.size(); int i, j; String v = "{"; Vector dv; if (tests != null) { if (tests.size() == 0) Dataset.perror("Feature.class :: avoid empty but non null test sets"); for (i = 0; i < tests.size(); i++) { if (i < max_display) { if (Feature.IS_CONTINUOUS(type)) v += DF4.format(((Double) tests.elementAt(i)).doubleValue()); else if (Feature.IS_INTEGER(type)) v += ((Integer) tests.elementAt(i)).intValue(); else if (Feature.IS_NOMINAL(type)) { dv = ((Vector) tests.elementAt(i)); for (j = 0; j < dv.size(); j++) v += ((String) dv.elementAt(j)) + " "; } if (i < tests.size() - 1) v += ", "; } else { v += "... "; break; } } } v += "}"; return v; } public static boolean IS_CONTINUOUS(String t) { return (t.equals(Feature.CONTINUOUS)); } public static boolean IS_INTEGER(String t) { // equiv. to Nominal Mono-valued, ordered return (t.equals(Feature.INTEGER)); } static boolean IS_NOMINAL(String t) { // Nominal Mono-Valued, no order return (t.equals(Feature.NOMINAL)); } static int INDEX(String t) { int i = 0; do { if (t.equals(TYPE[i])) return i; i++; } while (i < TYPE.length); Dataset.perror("No type found for " + t); return -1; } public static void CHECK_TESTS_DISJOINT_UNION( Feature parent, Feature f1, Feature f2, int excluded_index) { // various checks if ((!Discriminator_Tree.USE_OBSERVED_FEATURE_VALUES_FOR_SPLITS) || (!Feature.IS_CONTINUOUS(parent.type)) || (!Feature.IS_CONTINUOUS(f1.type)) || (!Feature.IS_CONTINUOUS(f2.type))) return; boolean[] found = new boolean[parent.tests.size()]; boolean found_f = false, duplicate = false; int i, j, k; if (f1.tests != null) for (i = 0; i < f1.tests.size(); i++) { found_f = false; j = 0; do { if (((Double) f1.tests.elementAt(i)).doubleValue() == ((Double) parent.tests.elementAt(j)).doubleValue()) { found[j] = true; found_f = true; } else j++; } while ((!found_f) && (j < parent.tests.size())); if (!found_f) { System.out.print("\n Parent Tests : "); for (k = 0; k < parent.tests.size(); k++) System.out.print((Double) parent.tests.elementAt(k) + ", "); System.out.print("\n F1 Tests : "); for (k = 0; k < f1.tests.size(); k++) System.out.print((Double) f1.tests.elementAt(k) + ", "); Dataset.perror( " Feature.class :: test value " + ((Double) f1.tests.elementAt(i)).doubleValue() + " not found in parent"); } } if (f2.tests != null) for (i = 0; i < f2.tests.size(); i++) { found_f = false; j = 0; do { if (((Double) f2.tests.elementAt(i)).doubleValue() == ((Double) parent.tests.elementAt(j)).doubleValue()) { if (found[j]) duplicate = true; else { found[j] = true; found_f = true; } } else j++; } while ((!found_f) && (!duplicate) && (j < parent.tests.size())); if (duplicate) { // something went wrong System.out.print("\n F1 Tests : "); for (k = 0; k < f1.tests.size(); k++) System.out.print((Double) f1.tests.elementAt(k) + ", "); System.out.print("\n F2 Tests : "); for (k = 0; k < f2.tests.size(); k++) System.out.print((Double) f2.tests.elementAt(k) + ", "); Dataset.perror( " Feature.class :: test value " + ((Double) parent.tests.elementAt(j)).doubleValue() + " duplicate in F1 and F2"); } if (!found_f) { // something went wrong System.out.print("\n Excluded index : " + excluded_index); System.out.print("\n Parent Tests : "); for (k = 0; k < parent.tests.size(); k++) System.out.print((Double) parent.tests.elementAt(k) + ", "); if (f1.tests != null) { System.out.print("\n F1 Tests : "); for (k = 0; k < f1.tests.size(); k++) System.out.print((Double) f1.tests.elementAt(k) + ", "); } System.out.print("\n F2 Tests : "); for (k = 0; k < f2.tests.size(); k++) System.out.print((Double) f2.tests.elementAt(k) + ", "); Dataset.perror( " Feature.class :: test value " + ((Double) f2.tests.elementAt(i)).doubleValue() + " not found in parent"); } } found_f = false; for (i = 0; i < found.length; i++) { if ((!found[i]) && (i != excluded_index)) { found_f = true; System.out.println((Double) parent.tests.elementAt(i) + " not found"); } } if (found_f) System.exit(0); } public void init_splits(Dataset ds, int f_index, int cv_fold) { if (Feature.IS_NOMINAL(type)) Dataset.perror("Feature.class :: bad call of init_splits for Nominal feature " + name); int i; Example e; if (Feature.IS_CONTINUOUS(type)) { Vector<Double> all_observed = new Vector<>(); double[] all_observed_ordered; for (i = 0; i < ds.train_size(cv_fold, true); i++) { e = ds.train_example(cv_fold, i, true); if (!Example.FEATURE_IS_UNKNOWN(e, f_index)) { if (!e.typed_features.elementAt(f_index).getClass().getSimpleName().equals("Double")) Dataset.perror("Feature.class :: Example feature " + f_index + " not a double"); all_observed.addElement( new Double(((Double) e.typed_features.elementAt(f_index)).doubleValue())); } } all_observed_ordered = new double[all_observed.size()]; for (i = 0; i < all_observed.size(); i++) all_observed_ordered[i] = all_observed.elementAt(i).doubleValue(); Arrays.sort(all_observed_ordered); all_observed = new Vector<>(); for (i = 0; i < all_observed_ordered.length; i++) if ((i == 0) || (all_observed_ordered[i] != all_observed_ordered[i - 1])) all_observed.addElement(new Double(all_observed_ordered[i])); dsplits_from_training = new double[all_observed.size() - 1]; for (i = 0; i < dsplits_from_training.length; i++) dsplits_from_training[i] = ((all_observed.elementAt(i).doubleValue()) + (all_observed.elementAt(i + 1).doubleValue())) / 2.0; } else if (Feature.IS_INTEGER(type)) { Vector<Integer> all_observed = new Vector<>(); int[] all_observed_ordered; for (i = 0; i < ds.train_size(cv_fold, true); i++) { e = ds.train_example(cv_fold, i, true); if (!Example.FEATURE_IS_UNKNOWN(e, f_index)) { if (!e.typed_features.elementAt(f_index).getClass().getSimpleName().equals("Integer")) Dataset.perror("Feature.class :: Example feature " + f_index + " not an int"); all_observed.addElement( new Integer(((Integer) e.typed_features.elementAt(f_index)).intValue())); } } all_observed_ordered = new int[all_observed.size()]; for (i = 0; i < all_observed.size(); i++) all_observed_ordered[i] = all_observed.elementAt(i).intValue(); Arrays.sort(all_observed_ordered); all_observed = new Vector<>(); for (i = 0; i < all_observed_ordered.length; i++) if ((i == 0) || (all_observed_ordered[i] != all_observed_ordered[i - 1])) all_observed.addElement(new Integer(all_observed_ordered[i])); isplits_from_training = new int[all_observed.size() - 1]; for (i = 0; i < isplits_from_training.length; i++) isplits_from_training[i] = all_observed.elementAt(i).intValue(); } } Feature(String n, String t, Vector<String> m, double miv, double mav, boolean compute_tests) { formatted_for_a_dt = false; dsplits_from_training = null; isplits_from_training = null; dmin_index_in_dsplits_from_training = dmax_index_in_dsplits_from_training = imin_index_in_dsplits_from_training = imax_index_in_dsplits_from_training = -1; name = n; type = t; modalities = null; empty_domain = false; if (((Feature.IS_CONTINUOUS(t)) || (Feature.IS_INTEGER(t))) && (miv > mav)) Dataset.perror( "Feature.class :: Continuous or Integer feature has min value " + miv + " > max value " + mav); else if ((Feature.IS_NOMINAL(t)) && (miv < mav)) Dataset.perror( "Feature.class :: Nominal feature " + name + " has min value = " + miv + ", max value = " + mav + ", should be default Forbidden value " + Feature.FORBIDDEN_VALUE); if ((Feature.IS_CONTINUOUS(t)) && (miv >= mav)) Dataset.perror( "Feature.class :: Continuous feature " + n + " has min value " + miv + " >= max value " + mav); if ((!Feature.IS_NOMINAL(t)) && ((miv == (double) Feature.FORBIDDEN_VALUE) && (mav == (double) Feature.FORBIDDEN_VALUE))) Dataset.perror( "Feature.class :: Non nominal feature " + n + " has min value " + Feature.FORBIDDEN_VALUE + " == max value " + Feature.FORBIDDEN_VALUE + " = Forbidden value"); if (Feature.IS_CONTINUOUS(t)) { dmin = miv; dmax = mav; dmin_from_data = dmax_from_data = (double) Feature.FORBIDDEN_VALUE; imin = imax = imin_from_data = imax_from_data = Feature.FORBIDDEN_VALUE; } else if (Feature.IS_INTEGER(t)) { imin = (int) miv; imax = (int) mav; imin_from_data = imax_from_data = Feature.FORBIDDEN_VALUE; dmin = dmax = dmin_from_data = dmax_from_data = (double) Feature.FORBIDDEN_VALUE; } else { imin = imax = imin_from_data = imax_from_data = Feature.FORBIDDEN_VALUE; dmin = dmax = dmin_from_data = dmax_from_data = (double) Feature.FORBIDDEN_VALUE; } if (Feature.IS_NOMINAL(t)) modalities = m; // generates tests for DTs if (compute_tests) tests = Feature.TEST_LIST(this); dispertion_statistic_value = -1.0; } // ALL PURPOSE INSTANCE METHODS public void try_format_tests(Dataset ds, int f_index, boolean compute_dmin_dmax) { if ((Discriminator_Tree.USE_OBSERVED_FEATURE_VALUES_FOR_SPLITS) && (Feature.IS_CONTINUOUS(type))) { if ((compute_dmin_dmax) && ((dmin_index_in_dsplits_from_training == -1) || (dmax_index_in_dsplits_from_training == -1))) compute_indexes_in_dsplits_from_training(ds, f_index); format_tests_using_observed_values_for_splits(ds, f_index); } } public void compute_indexes_in_dsplits_from_training(Dataset ds, int f_index) { double vmin = dmin; double vmax = dmax; double[] all_splits = ds.domain_feature(f_index).dsplits_from_training; boolean first_found = false; boolean last_found = false; int i; if (Feature.IS_CONTINUOUS(type)) { for (i = 0; i < all_splits.length; i++) { if ((all_splits[i] > vmin) && (all_splits[i] < vmax) && (!first_found)) { dmin_index_in_dsplits_from_training = i; first_found = true; } else if ((all_splits[i] >= vmax) && (!last_found)) { dmax_index_in_dsplits_from_training = i; last_found = true; } } if (!first_found) { System.out.print("\n Domain splits: "); for (i = 0; i < all_splits.length; i++) System.out.print(all_splits[i] + ", "); Dataset.perror( "Feature.class :: no split found for feature (dmin = " + dmin + ", dmax = " + dmax + ") " + toStringInTree(false, true)); } else if (!last_found) dmax_index_in_dsplits_from_training = all_splits.length - 1; } else Dataset.perror( "Feature.class :: compute_indexes_in_dsplits_from_training sent for non-continuous" + " features"); } public void format_tests_using_observed_values_for_splits(Dataset ds, int f_index) { formatted_for_a_dt = true; double vmin = dmin; double vmax = dmax; double[] all_splits = ds.domain_feature(f_index).dsplits_from_training; int i, j; if (Feature.IS_CONTINUOUS(type)) { Vector v = new Vector<Double>(); if (dmax_index_in_dsplits_from_training >= dmin_index_in_dsplits_from_training) for (i = dmin_index_in_dsplits_from_training; i <= dmax_index_in_dsplits_from_training; i++) { if ((all_splits[i] <= vmin) || (all_splits[i] >= vmax)) { System.out.print("Domain splits\n"); for (j = 0; j < all_splits.length; j++) System.out.print(all_splits[j] + ", "); Dataset.perror( "Feature.class :: vmin = " + vmin + ", all_splits[" + i + "] = " + all_splits[i] + ", vmax = " + vmax + " for feature " + toStringInTree(false, true)); } v.addElement(new Double(all_splits[i])); } if (v.size() > 0) tests = v; else tests = null; // to enforce an Exception if used } else Dataset.perror( "Feature.class :: format_tests_using_observed_values_for_splits sent for non-continuous" + " features"); } public boolean isSplittable() { if ((tests == null) || (tests.size() == 0)) return false; return true; } public boolean has_in_range(double v) { if ((Feature.IS_NOMINAL(type)) || (Feature.IS_INTEGER(type))) Dataset.perror("Feature.class :: feature " + this + " queried for double value " + v); if (!Feature.IS_CONTINUOUS(type)) Dataset.perror("Feature.class :: feature type " + type + " unregistered "); if (v < dmin) return false; if (v > dmax) return false; return true; } public boolean has_in_range(int v) { if ((Feature.IS_NOMINAL(type)) || (Feature.IS_CONTINUOUS(type))) Dataset.perror("Feature.class :: feature " + this + " queried for double value " + v); if (!Feature.IS_INTEGER(type)) Dataset.perror("Feature.class :: feature type " + type + " unregistered "); if (v < imin) return false; if (v > imax) return false; return true; } public boolean has_in_range(String s) { if ((Feature.IS_CONTINUOUS(type)) || (Feature.IS_INTEGER(type))) Dataset.perror( "Feature.class :: Continuous feature " + this + " queried for nominal value " + s); if (!Feature.IS_NOMINAL(type)) Dataset.perror("Feature.class :: feature type " + type + " unregistered "); int i; String ss; for (i = 0; i < modalities.size(); i++) { ss = (String) modalities.elementAt(i); if (ss.equals(s)) return true; } return false; } public String range(boolean in_generator) { String v = ""; int i; if (Feature.IS_NOMINAL(type)) { v += "{"; for (i = 0; i < modalities.size(); i++) { v += "" + modalities.elementAt(i); if (i < modalities.size() - 1) v += ", "; } v += "}"; } else if (Feature.IS_CONTINUOUS(type)) { if ((dmin_from_data != dmin) && (dmax_from_data != dmax) && (!in_generator)) v += "T: "; v += "[" + DF4.format(dmin) + ", " + DF4.format(dmax) + "]"; if ((dmin_from_data != dmin) && (dmax_from_data != dmax) && ((dmin_from_data != dmax_from_data) || (dmin_from_data != (double) Feature.FORBIDDEN_VALUE)) && (!in_generator)) v += "; O: [" + DF4.format(dmin_from_data) + ", " + DF4.format(dmax_from_data) + "]"; } else if (Feature.IS_INTEGER(type)) { if ((imin_from_data != imin) && (imax_from_data != imax) && (!in_generator)) v += "T: "; if (imax == imin) v += "{" + imin + "}"; else { v += "{" + imin + ", " + (imin + 1); if (imax > imin + 2) v += ", ..."; if (imax > imin + 1) v += ", " + imax; v += "}"; } if ((imin_from_data != imin) && (imax_from_data != imax) && ((imin_from_data != imax_from_data) || (imin_from_data != Feature.FORBIDDEN_VALUE)) && (!in_generator)) { v += "; O: {" + imin_from_data + ", " + (imin_from_data + 1); if (imax_from_data > imin_from_data + 1) v += ", ..."; v += ", " + imax_from_data + "}"; } } return v; } public String toString() { String v = ""; int i; v += name + " -- " + type + " in " + range(false) + " [" + Feature.DISPERSION_NAME[Feature.TYPE_INDEX(type)] + " = " + DF4.format(dispertion_statistic_value) + "]"; if (Feature.DISPLAY_TESTS) v += " -- tests[" + tests.size() + "] : " + tests(false); return v; } public String toStringInTree(boolean internalnode, boolean display_tests) { String v = ""; int i; if (internalnode) v += name + " (" + type + ") in " + range(true); else v += "(" + name + " in " + range(true) + ")"; if (display_tests) v += " -- tests : " + tests(display_tests); if ((internalnode) || (display_tests)) v += ";"; return v; } // DISCRIMINATOR METHODS public String display_test(int index_test) { String v = name; int i; Vector ssv; if (Feature.IS_CONTINUOUS(type)) v += " <= " + DF6.format(((Double) tests.elementAt(index_test)).doubleValue()); else if (Feature.IS_INTEGER(type)) v += " <= " + ((Integer) tests.elementAt(index_test)).intValue(); else if (Feature.IS_NOMINAL(type)) { v += " in {"; ssv = (Vector) tests.elementAt(index_test); for (i = 0; i < ssv.size(); i++) { v += (String) ssv.elementAt(i) + " "; if (i < ssv.size() - 1) v += ", "; } v += "}"; } else Dataset.perror("Feature.class :: no type available for feature " + this); return v; } public boolean example_goes_left( Example e, int index_feature_in_e, int index_test, boolean unspecified_attribute_handling_biased) { // path followed in the tree by an example // continuous OR integer values : <= is left, > is right // nominal values : in the set is left, otherwise is right // unspecified_attribute_handling_biased = true => uses local domain and split to decide random // branching, else Bernoulli(0.5) double cv, tv; int ci, ti; String nv; Vector ssv; int i; double p_left; // New: takes into account unknown feature values if (Example.FEATURE_IS_UNKNOWN(e, index_feature_in_e)) { if (!unspecified_attribute_handling_biased) { if (Algorithm.RANDOM_P_NOT_HALF() < 0.5) return true; else return false; } else { p_left = -1.0; if (Feature.IS_CONTINUOUS(type)) { if (dmax == dmin) Dataset.perror("Feature.class :: dmax = " + dmax + " == dmin "); if (((Double) tests.elementAt(index_test)).doubleValue() < dmin) Dataset.perror( "Feature.class :: test = " + ((Double) tests.elementAt(index_test)).doubleValue() + " < dmin = " + dmin); if (((Double) tests.elementAt(index_test)).doubleValue() > dmax) Dataset.perror( "Feature.class :: test = " + ((Double) tests.elementAt(index_test)).doubleValue() + " > dmax = " + dmax); p_left = (((Double) tests.elementAt(index_test)).doubleValue() - dmin) / (dmax - dmin); } else if (Feature.IS_INTEGER(type)) { if (imax == imin) Dataset.perror("Feature.class :: imax = " + imax + " == imin "); if (((Integer) tests.elementAt(index_test)).intValue() < imin) Dataset.perror( "Feature.class :: test = " + ((Integer) tests.elementAt(index_test)).intValue() + " < imin = " + imin); if (((Integer) tests.elementAt(index_test)).intValue() > imax) Dataset.perror( "Feature.class :: test = " + ((Integer) tests.elementAt(index_test)).intValue() + " > imax = " + imax); p_left = ((double) (((Integer) tests.elementAt(index_test)).intValue() - imin + 1)) / ((double) imax - imin + 1); } else if (Feature.IS_NOMINAL(type)) p_left = (((Vector) tests.elementAt(index_test)).size()) / ((double) modalities.size()); else Dataset.perror("Feature.class :: no type available for feature " + this); if (Algorithm.RANDOM_P_NOT(p_left) < p_left) return true; else return false; } } if (Feature.IS_CONTINUOUS(type)) { if ((e.typed_features .elementAt(index_feature_in_e) .getClass() .getSimpleName() .equals("String")) || (e.typed_features .elementAt(index_feature_in_e) .getClass() .getSimpleName() .equals("Integer"))) Dataset.perror( "Feature.class :: wrong class match : " + e.typed_features.elementAt(index_feature_in_e) + " not a Double"); cv = ((Double) e.typed_features.elementAt(index_feature_in_e)).doubleValue(); tv = ((Double) tests.elementAt(index_test)).doubleValue(); if (cv <= tv) return true; return false; } else if (Feature.IS_INTEGER(type)) { if ((e.typed_features .elementAt(index_feature_in_e) .getClass() .getSimpleName() .equals("String")) || (e.typed_features .elementAt(index_feature_in_e) .getClass() .getSimpleName() .equals("Double"))) Dataset.perror( "Feature.class :: wrong class match : " + e.typed_features.elementAt(index_feature_in_e) + " not a Double"); ci = ((Integer) e.typed_features.elementAt(index_feature_in_e)).intValue(); ti = ((Integer) tests.elementAt(index_test)).intValue(); if (ci <= ti) return true; return false; } else if (Feature.IS_NOMINAL(type)) { if ((e.typed_features .elementAt(index_feature_in_e) .getClass() .getSimpleName() .equals("Double")) || (e.typed_features .elementAt(index_feature_in_e) .getClass() .getSimpleName() .equals("Integer"))) Dataset.perror( "Feature.class :: wrong class match : " + e.typed_features.elementAt(index_feature_in_e) + " not a String"); nv = ((String) e.typed_features.elementAt(index_feature_in_e)); ssv = (Vector) tests.elementAt(index_test); for (i = 0; i < ssv.size(); i++) { if (nv.equals((String) ssv.elementAt(i))) return true; } return false; } else Dataset.perror("Feature.class :: no type available for feature " + this); return false; } }
google-research/google-research
generative_trees/src/Feature.java
213
package org.pytorch; import com.facebook.jni.HybridData; import com.facebook.jni.annotations.DoNotStrip; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.DoubleBuffer; import java.nio.FloatBuffer; import java.nio.IntBuffer; import java.nio.LongBuffer; import java.util.Arrays; import java.util.Locale; /** * Representation of a Tensor. Behavior is similar to PyTorch's tensor objects. * * <p>Most tensors will be constructed as {@code Tensor.fromBlob(data, shape)}, where {@code data} * can be an array or a direct {@link Buffer} (of the proper subclass). Helper methods are provided * to allocate buffers properly. * * <p>To access Tensor data, see {@link #dtype()}, {@link #shape()}, and various {@code getDataAs*} * methods. * * <p>When constructing {@code Tensor} objects with {@code data} as an array, it is not specified * whether this data is copied or retained as a reference so it is recommended not to modify it * after constructing. {@code data} passed as a {@link Buffer} is not copied, so it can be modified * between {@link Module} calls to avoid reallocation. Data retrieved from {@code Tensor} objects * may be copied or may be a reference to the {@code Tensor}'s internal data buffer. {@code shape} * is always copied. */ public abstract class Tensor { private static final String ERROR_MSG_DATA_BUFFER_NOT_NULL = "Data buffer must be not null"; private static final String ERROR_MSG_DATA_ARRAY_NOT_NULL = "Data array must be not null"; private static final String ERROR_MSG_SHAPE_NOT_NULL = "Shape must be not null"; private static final String ERROR_MSG_SHAPE_NON_NEGATIVE = "Shape elements must be non negative"; private static final String ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER = "Data buffer must have native byte order (java.nio.ByteOrder#nativeOrder)"; private static final String ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT = "Data buffer must be direct (java.nio.ByteBuffer#allocateDirect)"; @DoNotStrip final long[] shape; final MemoryFormat memoryFormat; private static final int INT_SIZE_BYTES = 4; private static final int FLOAT_SIZE_BYTES = 4; private static final int LONG_SIZE_BYTES = 8; private static final int DOUBLE_SIZE_BYTES = 8; /** * Allocates a new direct {@link java.nio.ByteBuffer} with native byte order with specified * capacity that can be used in {@link Tensor#fromBlob(ByteBuffer, long[])}, {@link * Tensor#fromBlobUnsigned(ByteBuffer, long[])}. * * @param numElements capacity (number of elements) of result buffer. */ public static ByteBuffer allocateByteBuffer(int numElements) { return ByteBuffer.allocateDirect(numElements).order(ByteOrder.nativeOrder()); } /** * Allocates a new direct {@link java.nio.IntBuffer} with native byte order with specified * capacity that can be used in {@link Tensor#fromBlob(IntBuffer, long[])}. * * @param numElements capacity (number of elements) of result buffer. */ public static IntBuffer allocateIntBuffer(int numElements) { return ByteBuffer.allocateDirect(numElements * INT_SIZE_BYTES) .order(ByteOrder.nativeOrder()) .asIntBuffer(); } /** * Allocates a new direct {@link java.nio.FloatBuffer} with native byte order with specified * capacity that can be used in {@link Tensor#fromBlob(FloatBuffer, long[])}. * * @param numElements capacity (number of elements) of result buffer. */ public static FloatBuffer allocateFloatBuffer(int numElements) { return ByteBuffer.allocateDirect(numElements * FLOAT_SIZE_BYTES) .order(ByteOrder.nativeOrder()) .asFloatBuffer(); } /** * Allocates a new direct {@link java.nio.LongBuffer} with native byte order with specified * capacity that can be used in {@link Tensor#fromBlob(LongBuffer, long[])}. * * @param numElements capacity (number of elements) of result buffer. */ public static LongBuffer allocateLongBuffer(int numElements) { return ByteBuffer.allocateDirect(numElements * LONG_SIZE_BYTES) .order(ByteOrder.nativeOrder()) .asLongBuffer(); } /** * Allocates a new direct {@link java.nio.DoubleBuffer} with native byte order with specified * capacity that can be used in {@link Tensor#fromBlob(DoubleBuffer, long[])}. * * @param numElements capacity (number of elements) of result buffer. */ public static DoubleBuffer allocateDoubleBuffer(int numElements) { return ByteBuffer.allocateDirect(numElements * DOUBLE_SIZE_BYTES) .order(ByteOrder.nativeOrder()) .asDoubleBuffer(); } /** * Creates a new Tensor instance with dtype torch.uint8 with specified shape and data as array of * bytes. * * @param data Tensor elements * @param shape Tensor shape */ public static Tensor fromBlobUnsigned(byte[] data, long[] shape, MemoryFormat memoryFormat) { checkArgument(data != null, ERROR_MSG_DATA_ARRAY_NOT_NULL); checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); checkShape(shape); checkShapeAndDataCapacityConsistency(data.length, shape); final ByteBuffer byteBuffer = allocateByteBuffer((int) numel(shape)); byteBuffer.put(data); return new Tensor_uint8(byteBuffer, shape, memoryFormat); } public static Tensor fromBlobUnsigned(byte[] data, long[] shape) { return fromBlobUnsigned(data, shape, MemoryFormat.CONTIGUOUS); } /** * Creates a new Tensor instance with dtype torch.int8 with specified shape and data as array of * bytes. * * @param data Tensor elements * @param shape Tensor shape */ public static Tensor fromBlob(byte[] data, long[] shape, MemoryFormat memoryFormat) { checkArgument(data != null, ERROR_MSG_DATA_ARRAY_NOT_NULL); checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); checkShape(shape); checkShapeAndDataCapacityConsistency(data.length, shape); final ByteBuffer byteBuffer = allocateByteBuffer((int) numel(shape)); byteBuffer.put(data); return new Tensor_int8(byteBuffer, shape, memoryFormat); } public static Tensor fromBlob(byte[] data, long[] shape) { return fromBlob(data, shape, MemoryFormat.CONTIGUOUS); } /** * Creates a new Tensor instance with dtype torch.int32 with specified shape and data as array of * ints. * * @param data Tensor elements * @param shape Tensor shape */ public static Tensor fromBlob(int[] data, long[] shape, MemoryFormat memoryFormat) { checkArgument(data != null, ERROR_MSG_DATA_ARRAY_NOT_NULL); checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); checkShape(shape); checkShapeAndDataCapacityConsistency(data.length, shape); final IntBuffer intBuffer = allocateIntBuffer((int) numel(shape)); intBuffer.put(data); return new Tensor_int32(intBuffer, shape, memoryFormat); } public static Tensor fromBlob(int[] data, long[] shape) { return fromBlob(data, shape, MemoryFormat.CONTIGUOUS); } /** * Creates a new Tensor instance with dtype torch.float32 with specified shape and data as array * of floats. * * @param data Tensor elements * @param shape Tensor shape */ public static Tensor fromBlob(float[] data, long[] shape, MemoryFormat memoryFormat) { checkArgument(data != null, ERROR_MSG_DATA_ARRAY_NOT_NULL); checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); checkShape(shape); checkShapeAndDataCapacityConsistency(data.length, shape); final FloatBuffer floatBuffer = allocateFloatBuffer((int) numel(shape)); floatBuffer.put(data); return new Tensor_float32(floatBuffer, shape, memoryFormat); } public static Tensor fromBlob(float[] data, long[] shape) { return fromBlob(data, shape, MemoryFormat.CONTIGUOUS); } /** * Creates a new Tensor instance with dtype torch.int64 with specified shape and data as array of * longs. * * @param data Tensor elements * @param shape Tensor shape */ public static Tensor fromBlob(long[] data, long[] shape, MemoryFormat memoryFormat) { checkArgument(data != null, ERROR_MSG_DATA_ARRAY_NOT_NULL); checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); checkShape(shape); checkShapeAndDataCapacityConsistency(data.length, shape); final LongBuffer longBuffer = allocateLongBuffer((int) numel(shape)); longBuffer.put(data); return new Tensor_int64(longBuffer, shape, memoryFormat); } public static Tensor fromBlob(long[] data, long[] shape) { return fromBlob(data, shape, MemoryFormat.CONTIGUOUS); } /** * Creates a new Tensor instance with dtype torch.float64 with specified shape and data as array * of doubles. * * @param shape Tensor shape * @param data Tensor elements */ public static Tensor fromBlob(double[] data, long[] shape, MemoryFormat memoryFormat) { checkArgument(data != null, ERROR_MSG_DATA_ARRAY_NOT_NULL); checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); checkShape(shape); checkShapeAndDataCapacityConsistency(data.length, shape); final DoubleBuffer doubleBuffer = allocateDoubleBuffer((int) numel(shape)); doubleBuffer.put(data); return new Tensor_float64(doubleBuffer, shape, memoryFormat); } public static Tensor fromBlob(double[] data, long[] shape) { return fromBlob(data, shape, MemoryFormat.CONTIGUOUS); } /** * Creates a new Tensor instance with dtype torch.uint8 with specified shape and data. * * @param data Direct buffer with native byte order that contains {@code Tensor.numel(shape)} * elements. The buffer is used directly without copying, and changes to its content will * change the tensor. * @param shape Tensor shape */ public static Tensor fromBlobUnsigned(ByteBuffer data, long[] shape, MemoryFormat memoryFormat) { checkArgument(data != null, ERROR_MSG_DATA_BUFFER_NOT_NULL); checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); checkShape(shape); checkShapeAndDataCapacityConsistency(data.capacity(), shape); checkArgument(data.isDirect(), ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT); checkArgument( (data.order() == ByteOrder.nativeOrder()), ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER); return new Tensor_uint8(data, shape, memoryFormat); } public static Tensor fromBlobUnsigned(ByteBuffer data, long[] shape) { return fromBlobUnsigned(data, shape, MemoryFormat.CONTIGUOUS); } /** * Creates a new Tensor instance with dtype torch.int8 with specified shape and data. * * @param data Direct buffer with native byte order that contains {@code Tensor.numel(shape)} * elements. The buffer is used directly without copying, and changes to its content will * change the tensor. * @param shape Tensor shape */ public static Tensor fromBlob(ByteBuffer data, long[] shape, MemoryFormat memoryFormat) { checkArgument(data != null, ERROR_MSG_DATA_BUFFER_NOT_NULL); checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); checkShape(shape); checkShapeAndDataCapacityConsistency(data.capacity(), shape); checkArgument(data.isDirect(), ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT); checkArgument( (data.order() == ByteOrder.nativeOrder()), ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER); return new Tensor_int8(data, shape, memoryFormat); } public static Tensor fromBlob(ByteBuffer data, long[] shape) { return fromBlob(data, shape, MemoryFormat.CONTIGUOUS); } /** * Creates a new Tensor instance with dtype torch.int32 with specified shape and data. * * @param data Direct buffer with native byte order that contains {@code Tensor.numel(shape)} * elements. The buffer is used directly without copying, and changes to its content will * change the tensor. * @param shape Tensor shape */ public static Tensor fromBlob(IntBuffer data, long[] shape, MemoryFormat memoryFormat) { checkArgument(data != null, ERROR_MSG_DATA_BUFFER_NOT_NULL); checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); checkShape(shape); checkShapeAndDataCapacityConsistency(data.capacity(), shape); checkArgument(data.isDirect(), ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT); checkArgument( (data.order() == ByteOrder.nativeOrder()), ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER); return new Tensor_int32(data, shape, memoryFormat); } public static Tensor fromBlob(IntBuffer data, long[] shape) { return fromBlob(data, shape, MemoryFormat.CONTIGUOUS); } /** * Creates a new Tensor instance with dtype torch.float32 with specified shape and data. * * @param data Direct buffer with native byte order that contains {@code Tensor.numel(shape)} * elements. The buffer is used directly without copying, and changes to its content will * change the tensor. * @param shape Tensor shape */ public static Tensor fromBlob(FloatBuffer data, long[] shape, MemoryFormat memoryFormat) { checkArgument(data != null, ERROR_MSG_DATA_BUFFER_NOT_NULL); checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); checkShape(shape); checkShapeAndDataCapacityConsistency(data.capacity(), shape); checkArgument(data.isDirect(), ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT); checkArgument( (data.order() == ByteOrder.nativeOrder()), ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER); return new Tensor_float32(data, shape, memoryFormat); } public static Tensor fromBlob(FloatBuffer data, long[] shape) { return fromBlob(data, shape, MemoryFormat.CONTIGUOUS); } /** * Creates a new Tensor instance with dtype torch.int64 with specified shape and data. * * @param data Direct buffer with native byte order that contains {@code Tensor.numel(shape)} * elements. The buffer is used directly without copying, and changes to its content will * change the tensor. * @param shape Tensor shape */ public static Tensor fromBlob(LongBuffer data, long[] shape, MemoryFormat memoryFormat) { checkArgument(data != null, ERROR_MSG_DATA_BUFFER_NOT_NULL); checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); checkShape(shape); checkShapeAndDataCapacityConsistency(data.capacity(), shape); checkArgument(data.isDirect(), ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT); checkArgument( (data.order() == ByteOrder.nativeOrder()), ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER); return new Tensor_int64(data, shape, memoryFormat); } public static Tensor fromBlob(LongBuffer data, long[] shape) { return fromBlob(data, shape, MemoryFormat.CONTIGUOUS); } /** * Creates a new Tensor instance with dtype torch.float64 with specified shape and data. * * @param data Direct buffer with native byte order that contains {@code Tensor.numel(shape)} * elements. The buffer is used directly without copying, and changes to its content will * change the tensor. * @param shape Tensor shape */ public static Tensor fromBlob(DoubleBuffer data, long[] shape, MemoryFormat memoryFormat) { checkArgument(data != null, ERROR_MSG_DATA_BUFFER_NOT_NULL); checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); checkShape(shape); checkShapeAndDataCapacityConsistency(data.capacity(), shape); checkArgument(data.isDirect(), ERROR_MSG_DATA_BUFFER_MUST_BE_DIRECT); checkArgument( (data.order() == ByteOrder.nativeOrder()), ERROR_MSG_DATA_BUFFER_MUST_HAVE_NATIVE_BYTE_ORDER); return new Tensor_float64(data, shape, memoryFormat); } public static Tensor fromBlob(DoubleBuffer data, long[] shape) { return fromBlob(data, shape, MemoryFormat.CONTIGUOUS); } @DoNotStrip private HybridData mHybridData; private Tensor(long[] shape, MemoryFormat memoryFormat) { checkShape(shape); this.shape = Arrays.copyOf(shape, shape.length); this.memoryFormat = memoryFormat; } /** Returns the number of elements in this tensor. */ public long numel() { return numel(this.shape); } /** Calculates the number of elements in a tensor with the specified shape. */ public static long numel(long[] shape) { checkShape(shape); int result = 1; for (long s : shape) { result *= s; } return result; } /** Returns the shape of this tensor. (The array is a fresh copy.) */ public long[] shape() { return Arrays.copyOf(shape, shape.length); } /** Returns the memory format of this tensor. */ public MemoryFormat memoryFormat() { return memoryFormat; } /** @return data type of this tensor. */ public abstract DType dtype(); // Called from native @DoNotStrip int dtypeJniCode() { return dtype().jniCode; } // Called from native @DoNotStrip int memoryFormatJniCode() { return memoryFormat.jniCode; } /** * @return a Java byte array that contains the tensor data. This may be a copy or reference. * @throws IllegalStateException if it is called for a non-int8 tensor. */ public byte[] getDataAsByteArray() { throw new IllegalStateException( "Tensor of type " + getClass().getSimpleName() + " cannot return data as byte array."); } /** * @return a Java byte array that contains the tensor data. This may be a copy or reference. * @throws IllegalStateException if it is called for a non-uint8 tensor. */ public byte[] getDataAsUnsignedByteArray() { throw new IllegalStateException( "Tensor of type " + getClass().getSimpleName() + " cannot return data as byte array."); } /** * @return a Java int array that contains the tensor data. This may be a copy or reference. * @throws IllegalStateException if it is called for a non-int32 tensor. */ public int[] getDataAsIntArray() { throw new IllegalStateException( "Tensor of type " + getClass().getSimpleName() + " cannot return data as int array."); } /** * @return a Java float array that contains the tensor data. This may be a copy or reference. * @throws IllegalStateException if it is called for a non-float32 tensor. */ public float[] getDataAsFloatArray() { throw new IllegalStateException( "Tensor of type " + getClass().getSimpleName() + " cannot return data as float array."); } /** * @return a Java long array that contains the tensor data. This may be a copy or reference. * @throws IllegalStateException if it is called for a non-int64 tensor. */ public long[] getDataAsLongArray() { throw new IllegalStateException( "Tensor of type " + getClass().getSimpleName() + " cannot return data as long array."); } /** * @return a Java double array that contains the tensor data. This may be a copy or reference. * @throws IllegalStateException if it is called for a non-float64 tensor. */ public double[] getDataAsDoubleArray() { throw new IllegalStateException( "Tensor of type " + getClass().getSimpleName() + " cannot return data as double array."); } @DoNotStrip Buffer getRawDataBuffer() { throw new IllegalStateException( "Tensor of type " + getClass().getSimpleName() + " cannot " + "return raw data buffer."); } static class Tensor_uint8 extends Tensor { private final ByteBuffer data; private Tensor_uint8(ByteBuffer data, long[] shape, MemoryFormat memoryFormat) { super(shape, memoryFormat); this.data = data; } @Override public DType dtype() { return DType.UINT8; } @Override Buffer getRawDataBuffer() { return data; } @Override public byte[] getDataAsUnsignedByteArray() { data.rewind(); byte[] arr = new byte[data.remaining()]; data.get(arr); return arr; } @Override public String toString() { return String.format("Tensor(%s, dtype=torch.uint8)", Arrays.toString(shape)); } } static class Tensor_int8 extends Tensor { private final ByteBuffer data; private Tensor_int8(ByteBuffer data, long[] shape, MemoryFormat memoryFormat) { super(shape, memoryFormat); this.data = data; } @Override public DType dtype() { return DType.INT8; } @Override Buffer getRawDataBuffer() { return data; } @Override public byte[] getDataAsByteArray() { data.rewind(); byte[] arr = new byte[data.remaining()]; data.get(arr); return arr; } @Override public String toString() { return String.format("Tensor(%s, dtype=torch.int8)", Arrays.toString(shape)); } } static class Tensor_int32 extends Tensor { private final IntBuffer data; private Tensor_int32(IntBuffer data, long[] shape, MemoryFormat memoryFormat) { super(shape, memoryFormat); this.data = data; } @Override public DType dtype() { return DType.INT32; } @Override Buffer getRawDataBuffer() { return data; } @Override public int[] getDataAsIntArray() { data.rewind(); int[] arr = new int[data.remaining()]; data.get(arr); return arr; } @Override public String toString() { return String.format("Tensor(%s, dtype=torch.int32)", Arrays.toString(shape)); } } static class Tensor_float32 extends Tensor { private final FloatBuffer data; Tensor_float32(FloatBuffer data, long[] shape, MemoryFormat memoryFormat) { super(shape, memoryFormat); this.data = data; } @Override public float[] getDataAsFloatArray() { data.rewind(); float[] arr = new float[data.remaining()]; data.get(arr); return arr; } @Override public DType dtype() { return DType.FLOAT32; } @Override Buffer getRawDataBuffer() { return data; } @Override public String toString() { return String.format("Tensor(%s, dtype=torch.float32)", Arrays.toString(shape)); } } static class Tensor_int64 extends Tensor { private final LongBuffer data; private Tensor_int64(LongBuffer data, long[] shape, MemoryFormat memoryFormat) { super(shape, memoryFormat); this.data = data; } @Override public DType dtype() { return DType.INT64; } @Override Buffer getRawDataBuffer() { return data; } @Override public long[] getDataAsLongArray() { data.rewind(); long[] arr = new long[data.remaining()]; data.get(arr); return arr; } @Override public String toString() { return String.format("Tensor(%s, dtype=torch.int64)", Arrays.toString(shape)); } } static class Tensor_float64 extends Tensor { private final DoubleBuffer data; private Tensor_float64(DoubleBuffer data, long[] shape, MemoryFormat memoryFormat) { super(shape, memoryFormat); this.data = data; } @Override public DType dtype() { return DType.FLOAT64; } @Override Buffer getRawDataBuffer() { return data; } @Override public double[] getDataAsDoubleArray() { data.rewind(); double[] arr = new double[data.remaining()]; data.get(arr); return arr; } @Override public String toString() { return String.format("Tensor(%s, dtype=torch.float64)", Arrays.toString(shape)); } } // region checks private static void checkArgument(boolean expression, String errorMessage, Object... args) { if (!expression) { throw new IllegalArgumentException(String.format(Locale.US, errorMessage, args)); } } private static void checkShape(long[] shape) { checkArgument(shape != null, ERROR_MSG_SHAPE_NOT_NULL); for (int i = 0; i < shape.length; i++) { checkArgument(shape[i] >= 0, ERROR_MSG_SHAPE_NON_NEGATIVE); } } private static void checkShapeAndDataCapacityConsistency(int dataCapacity, long[] shape) { final long numel = numel(shape); checkArgument( numel == dataCapacity, "Inconsistent data capacity:%d and shape number elements:%d shape:%s", dataCapacity, numel, Arrays.toString(shape)); } // endregion checks // Called from native @DoNotStrip private static Tensor nativeNewTensor( ByteBuffer data, long[] shape, int dtype, int memoryFormatCode, HybridData hybridData) { Tensor tensor = null; MemoryFormat memoryFormat = MemoryFormat.CONTIGUOUS; if (MemoryFormat.CHANNELS_LAST.jniCode == memoryFormatCode) { memoryFormat = MemoryFormat.CHANNELS_LAST; } else if (MemoryFormat.CHANNELS_LAST_3D.jniCode == memoryFormatCode) { memoryFormat = MemoryFormat.CHANNELS_LAST_3D; } if (DType.FLOAT32.jniCode == dtype) { tensor = new Tensor_float32(data.asFloatBuffer(), shape, memoryFormat); } else if (DType.INT32.jniCode == dtype) { tensor = new Tensor_int32(data.asIntBuffer(), shape, memoryFormat); } else if (DType.INT64.jniCode == dtype) { tensor = new Tensor_int64(data.asLongBuffer(), shape, memoryFormat); } else if (DType.FLOAT64.jniCode == dtype) { tensor = new Tensor_float64(data.asDoubleBuffer(), shape, memoryFormat); } else if (DType.UINT8.jniCode == dtype) { tensor = new Tensor_uint8(data, shape, memoryFormat); } else if (DType.INT8.jniCode == dtype) { tensor = new Tensor_int8(data, shape, memoryFormat); } else { new IllegalArgumentException("Unknown Tensor dtype"); } tensor.mHybridData = hybridData; return tensor; } }
pytorch/pytorch
android/pytorch_android/src/main/java/org/pytorch/Tensor.java
214
/* * 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.mapper; import org.apache.lucene.codecs.PostingsFormat; import org.elasticsearch.cluster.metadata.DataStream; import org.elasticsearch.cluster.metadata.InferenceFieldMetadata; import org.elasticsearch.index.IndexSettings; import org.elasticsearch.index.analysis.IndexAnalyzers; import org.elasticsearch.index.analysis.NamedAnalyzer; import org.elasticsearch.inference.InferenceService; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import java.util.function.Function; /** * A (mostly) immutable snapshot of the current mapping of an index with * access to everything we need for the search phase. */ public final class MappingLookup { /** * Key for the lookup to be used in caches. */ public static class CacheKey { private CacheKey() {} } /** * A lookup representing an empty mapping. It can be used to look up fields, although it won't hold any, but it does not * hold a valid {@link DocumentParser}, {@link IndexSettings} or {@link IndexAnalyzers}. */ public static final MappingLookup EMPTY = fromMappers(Mapping.EMPTY, List.of(), List.of()); private final CacheKey cacheKey = new CacheKey(); /** Full field name to mapper */ private final Map<String, Mapper> fieldMappers; private final Map<String, ObjectMapper> objectMappers; private final Map<String, InferenceFieldMetadata> inferenceFields; private final int runtimeFieldMappersCount; private final NestedLookup nestedLookup; private final FieldTypeLookup fieldTypeLookup; private final FieldTypeLookup indexTimeLookup; // for index-time scripts, a lookup that does not include runtime fields private final Map<String, NamedAnalyzer> indexAnalyzersMap; private final List<FieldMapper> indexTimeScriptMappers; private final Mapping mapping; private final Set<String> completionFields; private final int totalFieldsCount; /** * Creates a new {@link MappingLookup} instance by parsing the provided mapping and extracting its field definitions. * * @param mapping the mapping source * @return the newly created lookup instance */ public static MappingLookup fromMapping(Mapping mapping) { List<ObjectMapper> newObjectMappers = new ArrayList<>(); List<FieldMapper> newFieldMappers = new ArrayList<>(); List<FieldAliasMapper> newFieldAliasMappers = new ArrayList<>(); List<PassThroughObjectMapper> newPassThroughMappers = new ArrayList<>(); for (MetadataFieldMapper metadataMapper : mapping.getSortedMetadataMappers()) { if (metadataMapper != null) { newFieldMappers.add(metadataMapper); } } for (Mapper child : mapping.getRoot()) { collect(child, newObjectMappers, newFieldMappers, newFieldAliasMappers, newPassThroughMappers); } return new MappingLookup(mapping, newFieldMappers, newObjectMappers, newFieldAliasMappers, newPassThroughMappers); } private static void collect( Mapper mapper, Collection<ObjectMapper> objectMappers, Collection<FieldMapper> fieldMappers, Collection<FieldAliasMapper> fieldAliasMappers, Collection<PassThroughObjectMapper> passThroughMappers ) { if (mapper instanceof PassThroughObjectMapper passThroughObjectMapper) { passThroughMappers.add(passThroughObjectMapper); objectMappers.add(passThroughObjectMapper); } else if (mapper instanceof ObjectMapper objectMapper) { objectMappers.add(objectMapper); } else if (mapper instanceof FieldMapper fieldMapper) { fieldMappers.add(fieldMapper); } else if (mapper instanceof FieldAliasMapper fieldAliasMapper) { fieldAliasMappers.add(fieldAliasMapper); } else { throw new IllegalStateException("Unrecognized mapper type [" + mapper.getClass().getSimpleName() + "]."); } for (Mapper child : mapper) { collect(child, objectMappers, fieldMappers, fieldAliasMappers, passThroughMappers); } } /** * Creates a new {@link MappingLookup} instance given the provided mappers and mapping. * Note that the provided mappings are not re-parsed but only exposed as-is. No consistency is enforced between * the provided mappings and set of mappers. * This is a commodity method to be used in tests, or whenever no mappings are defined for an index. * When creating a MappingLookup through this method, its exposed functionalities are limited as it does not * hold a valid {@link DocumentParser}, {@link IndexSettings} or {@link IndexAnalyzers}. * * @param mapping the mapping * @param mappers the field mappers * @param objectMappers the object mappers * @param aliasMappers the field alias mappers * @param passThroughMappers the pass-through mappers * @return the newly created lookup instance */ public static MappingLookup fromMappers( Mapping mapping, Collection<FieldMapper> mappers, Collection<ObjectMapper> objectMappers, Collection<FieldAliasMapper> aliasMappers, Collection<PassThroughObjectMapper> passThroughMappers ) { return new MappingLookup(mapping, mappers, objectMappers, aliasMappers, passThroughMappers); } public static MappingLookup fromMappers(Mapping mapping, Collection<FieldMapper> mappers, Collection<ObjectMapper> objectMappers) { return new MappingLookup(mapping, mappers, objectMappers, List.of(), List.of()); } private MappingLookup( Mapping mapping, Collection<FieldMapper> mappers, Collection<ObjectMapper> objectMappers, Collection<FieldAliasMapper> aliasMappers, Collection<PassThroughObjectMapper> passThroughMappers ) { this.totalFieldsCount = mapping.getRoot().getTotalFieldsCount(); this.mapping = mapping; Map<String, Mapper> fieldMappers = new HashMap<>(); Map<String, ObjectMapper> objects = new HashMap<>(); List<NestedObjectMapper> nestedMappers = new ArrayList<>(); for (ObjectMapper mapper : objectMappers) { if (objects.put(mapper.fullPath(), mapper) != null) { throw new MapperParsingException("Object mapper [" + mapper.fullPath() + "] is defined more than once"); } if (mapper.isNested()) { nestedMappers.add((NestedObjectMapper) mapper); } } this.nestedLookup = NestedLookup.build(nestedMappers); final Map<String, NamedAnalyzer> indexAnalyzersMap = new HashMap<>(); final Set<String> completionFields = new HashSet<>(); final List<FieldMapper> indexTimeScriptMappers = new ArrayList<>(); for (FieldMapper mapper : mappers) { if (objects.containsKey(mapper.name())) { throw new MapperParsingException("Field [" + mapper.name() + "] is defined both as an object and a field"); } if (fieldMappers.put(mapper.name(), mapper) != null) { throw new MapperParsingException("Field [" + mapper.name() + "] is defined more than once"); } indexAnalyzersMap.putAll(mapper.indexAnalyzers()); if (mapper.hasScript()) { indexTimeScriptMappers.add(mapper); } if (mapper instanceof CompletionFieldMapper) { completionFields.add(mapper.name()); } } for (FieldAliasMapper aliasMapper : aliasMappers) { if (objects.containsKey(aliasMapper.name())) { throw new MapperParsingException("Alias [" + aliasMapper.name() + "] is defined both as an object and an alias"); } if (fieldMappers.put(aliasMapper.name(), aliasMapper) != null) { throw new MapperParsingException("Alias [" + aliasMapper.name() + "] is defined both as an alias and a concrete field"); } } PassThroughObjectMapper.checkForDuplicatePriorities(passThroughMappers); final Collection<RuntimeField> runtimeFields = mapping.getRoot().runtimeFields(); this.fieldTypeLookup = new FieldTypeLookup(mappers, aliasMappers, passThroughMappers, runtimeFields); Map<String, InferenceFieldMetadata> inferenceFields = new HashMap<>(); for (FieldMapper mapper : mappers) { if (mapper instanceof InferenceFieldMapper inferenceFieldMapper) { inferenceFields.put(mapper.name(), inferenceFieldMapper.getMetadata(fieldTypeLookup.sourcePaths(mapper.name()))); } } this.inferenceFields = Map.copyOf(inferenceFields); if (runtimeFields.isEmpty()) { // without runtime fields this is the same as the field type lookup this.indexTimeLookup = fieldTypeLookup; } else { this.indexTimeLookup = new FieldTypeLookup(mappers, aliasMappers, passThroughMappers, Collections.emptyList()); } // make all fields into compact+fast immutable maps this.fieldMappers = Map.copyOf(fieldMappers); this.objectMappers = Map.copyOf(objects); this.runtimeFieldMappersCount = runtimeFields.size(); this.indexAnalyzersMap = Map.copyOf(indexAnalyzersMap); this.completionFields = Set.copyOf(completionFields); this.indexTimeScriptMappers = List.copyOf(indexTimeScriptMappers); runtimeFields.stream().flatMap(RuntimeField::asMappedFieldTypes).map(MappedFieldType::name).forEach(this::validateDoesNotShadow); assert assertMapperNamesInterned(this.fieldMappers, this.objectMappers); } private static boolean assertMapperNamesInterned(Map<String, Mapper> mappers, Map<String, ObjectMapper> objectMappers) { mappers.forEach(MappingLookup::assertNamesInterned); objectMappers.forEach(MappingLookup::assertNamesInterned); return true; } private static void assertNamesInterned(String name, Mapper mapper) { assert name == name.intern(); assert mapper.name() == mapper.name().intern(); assert mapper.simpleName() == mapper.simpleName().intern(); if (mapper instanceof ObjectMapper) { ((ObjectMapper) mapper).mappers.forEach(MappingLookup::assertNamesInterned); } } /** * Returns the leaf mapper associated with this field name. Note that the returned mapper * could be either a concrete {@link FieldMapper}, or a {@link FieldAliasMapper}. * * To access a field's type information, {@link MapperService#fieldType} should be used instead. */ public Mapper getMapper(String field) { return fieldMappers.get(field); } FieldTypeLookup fieldTypesLookup() { return fieldTypeLookup; } /** * Returns the total number of fields defined in the mappings, including field mappers, object mappers as well as runtime fields. */ public long getTotalFieldsCount() { return totalFieldsCount; } /** * Returns the total number of mappers defined in the mappings, including field mappers and their sub-fields * (which are not explicitly defined in the mappings), multi-fields, object mappers, runtime fields and metadata field mappers. */ public long getTotalMapperCount() { return fieldMappers.size() + objectMappers.size() + runtimeFieldMappersCount; } FieldTypeLookup indexTimeLookup() { return indexTimeLookup; } List<FieldMapper> indexTimeScriptMappers() { return indexTimeScriptMappers; } public NamedAnalyzer indexAnalyzer(String field, Function<String, NamedAnalyzer> unmappedFieldAnalyzer) { final NamedAnalyzer analyzer = indexAnalyzersMap.get(field); if (analyzer != null) { return analyzer; } return unmappedFieldAnalyzer.apply(field); } /** * Returns an iterable over all the registered field mappers (including alias mappers) */ public Iterable<Mapper> fieldMappers() { return fieldMappers.values(); } /** * Gets the postings format for a particular field * @param field the field to retrieve a postings format for * @return the postings format for the field, or {@code null} if the default format should be used */ public PostingsFormat getPostingsFormat(String field) { return completionFields.contains(field) ? CompletionFieldMapper.postingsFormat() : null; } void checkLimits(IndexSettings settings) { checkFieldLimit(settings.getMappingTotalFieldsLimit()); checkObjectDepthLimit(settings.getMappingDepthLimit()); checkFieldNameLengthLimit(settings.getMappingFieldNameLengthLimit()); checkNestedLimit(settings.getMappingNestedFieldsLimit()); checkDimensionFieldLimit(settings.getMappingDimensionFieldsLimit()); } private void checkFieldLimit(long limit) { checkFieldLimit(limit, 0); } void checkFieldLimit(long limit, int additionalFieldsToAdd) { if (exceedsLimit(limit, additionalFieldsToAdd)) { throw new IllegalArgumentException( "Limit of total fields [" + limit + "] has been exceeded" + (additionalFieldsToAdd > 0 ? " while adding new fields [" + additionalFieldsToAdd + "]" : "") ); } } boolean exceedsLimit(long limit, int additionalFieldsToAdd) { return remainingFieldsUntilLimit(limit) < additionalFieldsToAdd; } long remainingFieldsUntilLimit(long mappingTotalFieldsLimit) { return mappingTotalFieldsLimit - totalFieldsCount; } private void checkDimensionFieldLimit(long limit) { long dimensionFieldCount = fieldMappers.values() .stream() .filter(m -> m instanceof FieldMapper && ((FieldMapper) m).fieldType().isDimension()) .count(); if (dimensionFieldCount > limit) { throw new IllegalArgumentException("Limit of total dimension fields [" + limit + "] has been exceeded"); } } private void checkObjectDepthLimit(long limit) { for (String objectPath : objectMappers.keySet()) { checkObjectDepthLimit(limit, objectPath); } } static void checkObjectDepthLimit(long limit, String objectPath) { int numDots = 0; for (int i = 0; i < objectPath.length(); ++i) { if (objectPath.charAt(i) == '.') { numDots += 1; } } final int depth = numDots + 2; if (depth > limit) { throw new IllegalArgumentException( "Limit of mapping depth [" + limit + "] has been exceeded due to object field [" + objectPath + "]" ); } } private void checkFieldNameLengthLimit(long limit) { validateMapperNameIn(objectMappers.values(), limit); validateMapperNameIn(fieldMappers.values(), limit); } private static void validateMapperNameIn(Collection<? extends Mapper> mappers, long limit) { for (Mapper mapper : mappers) { String name = mapper.simpleName(); if (name.length() > limit) { throw new IllegalArgumentException("Field name [" + name + "] is longer than the limit of [" + limit + "] characters"); } } } private void checkNestedLimit(long limit) { long actualNestedFields = 0; for (ObjectMapper objectMapper : objectMappers.values()) { if (objectMapper.isNested()) { actualNestedFields++; } } if (actualNestedFields > limit) { throw new IllegalArgumentException("Limit of nested fields [" + limit + "] has been exceeded"); } } public Map<String, ObjectMapper> objectMappers() { return objectMappers; } /** * Returns a map containing all fields that require to run inference (through the {@link InferenceService} prior to indexation. */ public Map<String, InferenceFieldMetadata> inferenceFields() { return inferenceFields; } public NestedLookup nestedLookup() { return nestedLookup; } public boolean isMultiField(String field) { if (fieldMappers.containsKey(field) == false) { return false; } // Is it a runtime field? if (indexTimeLookup.get(field) != fieldTypeLookup.get(field)) { return false; } String sourceParent = parentObject(field); return sourceParent != null && fieldMappers.containsKey(sourceParent); } public boolean isObjectField(String field) { return objectMappers.containsKey(field); } private static String parentObject(String field) { int lastDot = field.lastIndexOf('.'); if (lastDot == -1) { return null; } return field.substring(0, lastDot); } /** * Returns a set of field names that match a regex-like pattern * * All field names in the returned set are guaranteed to resolve to a field * * @param pattern the pattern to match field names against */ public Set<String> getMatchingFieldNames(String pattern) { return fieldTypeLookup.getMatchingFieldNames(pattern); } /** * @return A map from field name to the MappedFieldType */ public Map<String, MappedFieldType> getFullNameToFieldType() { return fieldTypeLookup.getFullNameToFieldType(); } /** * Returns the mapped field type for the given field name. */ public MappedFieldType getFieldType(String field) { return fieldTypesLookup().get(field); } /** * Given a concrete field name, return its paths in the _source. * * For most fields, the source path is the same as the field itself. However * there are cases where a field's values are found elsewhere in the _source: * - For a multi-field, the source path is the parent field. * - One field's content could have been copied to another through copy_to. * * @param field The field for which to look up the _source path. Note that the field * should be a concrete field and *not* an alias. * @return A set of paths in the _source that contain the field's values. */ public Set<String> sourcePaths(String field) { return fieldTypesLookup().sourcePaths(field); } /** * If field is a leaf multi-field return the path to the parent field. Otherwise, return null. */ public String parentField(String field) { return fieldTypesLookup().parentField(field); } /** * Returns true if the index has mappings. An index does not have mappings only if it was created * without providing mappings explicitly, and no documents have yet been indexed in it. * @return true if the current index has mappings, false otherwise */ public boolean hasMappings() { return this != EMPTY; } /** * Will there be {@code _source}. */ public boolean isSourceEnabled() { SourceFieldMapper sfm = mapping.getMetadataMapperByClass(SourceFieldMapper.class); return sfm != null && sfm.enabled(); } /** * Does the source need to be rebuilt on the fly? */ public boolean isSourceSynthetic() { SourceFieldMapper sfm = mapping.getMetadataMapperByClass(SourceFieldMapper.class); return sfm != null && sfm.isSynthetic(); } /** * Build something to load source {@code _source}. */ public SourceLoader newSourceLoader(SourceFieldMetrics metrics) { SourceFieldMapper sfm = mapping.getMetadataMapperByClass(SourceFieldMapper.class); return sfm == null ? SourceLoader.FROM_STORED_SOURCE : sfm.newSourceLoader(mapping, metrics); } /** * Returns if this mapping contains a data-stream's timestamp meta-field and this field is enabled. * Only indices that are a part of a data-stream have this meta-field enabled. * @return {@code true} if contains an enabled data-stream's timestamp meta-field, {@code false} otherwise. */ public boolean isDataStreamTimestampFieldEnabled() { DataStreamTimestampFieldMapper dtfm = mapping.getMetadataMapperByClass(DataStreamTimestampFieldMapper.class); return dtfm != null && dtfm.isEnabled(); } /** * Returns if this mapping contains a timestamp field that is of type date, indexed and has doc values. * @return {@code true} if contains a timestamp field of type date that is indexed and has doc values, {@code false} otherwise. */ public boolean hasTimestampField() { final MappedFieldType mappedFieldType = fieldTypesLookup().get(DataStream.TIMESTAMP_FIELD_NAME); if (mappedFieldType instanceof DateFieldMapper.DateFieldType) { return mappedFieldType.isIndexed() && mappedFieldType.hasDocValues(); } else { return false; } } /** * Key for the lookup to be used in caches. */ public CacheKey cacheKey() { return cacheKey; } /** * Returns the mapping source that this lookup originated from * @return the mapping source */ public Mapping getMapping() { return mapping; } /** * Check if the provided {@link MappedFieldType} shadows a dimension * or metric field. */ public void validateDoesNotShadow(String name) { MappedFieldType shadowed = indexTimeLookup.get(name); if (shadowed == null) { return; } if (shadowed.isDimension()) { throw new MapperParsingException("Field [" + name + "] attempted to shadow a time_series_dimension"); } if (shadowed.getMetricType() != null) { throw new MapperParsingException("Field [" + name + "] attempted to shadow a time_series_metric"); } } }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/MappingLookup.java
215
/** * An integer greater than 1 is called a prime number if its only positive divisors (factors) are 1 and itself. * Prime numbers have been studied over the years by a lot of mathematicians. Applications of prime * numbers arise in Cryptography and Coding Theory among others. * Have you tried reversing a prime? For most primes, you get a composite (43 becomes 34). An * Emirp (Prime spelt backwards) is a Prime that gives you a different Prime when its digits are reversed. * For example, 17 is Emirp because 17 as well as 71 are Prime. * In this problem, you have to decide whether a number N is Non-prime or Prime or Emirp. Assume * that 1 < N < 1000000. * Interestingly, Emirps are not new to NTU students. We have been boarding 199 and 179 buses for * quite a long time! * Input * Input consists of several lines specifying values for N. * Output * For each N given in the input, output should contain one of the following: * 1. ‘N is not prime.’, if N is not a Prime number. * 2. ‘N is prime.’, if N is Prime and N is not Emirp. * 3. ‘N is emirp.’, if N is Emirp. * Sample Input * 17 * 18 * 19 * 179 * 199 * Sample Output * 17 is emirp. * 18 is not prime. * 19 is prime. * 179 is emirp. * 199 is emirp. */ //https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&problem=1176 import java.math.BigInteger; import java.util.Scanner; public class SimplyEmirp { public static void main(String[] args) { Scanner input = new Scanner(System.in); while (input.hasNext()) { String inputGiven = input.next(); BigInteger number = new BigInteger(inputGiven); if (!number.isProbablePrime(10)) { System.out.println(number + " is not prime."); } else { String numberReversedAsString = new StringBuilder( number.toString()).reverse().toString(); BigInteger numberReversed = new BigInteger( numberReversedAsString); if (numberReversed.isProbablePrime(10) && numberReversed.compareTo(number) != 0) { System.out.println(number + " is emirp."); } else { System.out.println(number + " is prime."); } } } } }
kdn251/interviews
uva/SimplyEmirp.java
217
/** * File: ListNode.java * Created Time: 2022-11-25 * Author: krahets ([email protected]) */ package utils; /* 链表节点 */ public class ListNode { public int val; public ListNode next; public ListNode(int x) { val = x; } /* 将列表反序列化为链表 */ public static ListNode arrToLinkedList(int[] arr) { ListNode dum = new ListNode(0); ListNode head = dum; for (int val : arr) { head.next = new ListNode(val); head = head.next; } return dum.next; } }
krahets/hello-algo
codes/java/utils/ListNode.java
218
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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. package org.openqa.selenium; import java.io.Serializable; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import java.util.Objects; import java.util.TimeZone; import java.util.TreeMap; public class Cookie implements Serializable { private static final long serialVersionUID = 4115876353625612383L; private final String name; private final String value; private final String path; private final String domain; private final Date expiry; private final boolean isSecure; private final boolean isHttpOnly; private final String sameSite; /** * Creates an insecure non-httpOnly cookie with no domain specified. * * @param name The name of the cookie; may not be null or an empty string. * @param value The cookie value; may not be null. * @param path The path the cookie is visible to. If left blank or set to null, will be set to * "/". * @param expiry The cookie's expiration date; may be null. * @see #Cookie(String, String, String, String, Date) */ public Cookie(String name, String value, String path, Date expiry) { this(name, value, null, path, expiry); } /** * Creates an insecure non-httpOnly cookie. * * @param name The name of the cookie; may not be null or an empty string. * @param value The cookie value; may not be null. * @param domain The domain the cookie is visible to. * @param path The path the cookie is visible to. If left blank or set to null, will be set to * "/". * @param expiry The cookie's expiration date; may be null. * @see #Cookie(String, String, String, String, Date, boolean) */ public Cookie(String name, String value, String domain, String path, Date expiry) { this(name, value, domain, path, expiry, false); } /** * Creates a non-httpOnly cookie. * * @param name The name of the cookie; may not be null or an empty string. * @param value The cookie value; may not be null. * @param domain The domain the cookie is visible to. * @param path The path the cookie is visible to. If left blank or set to null, will be set to * "/". * @param expiry The cookie's expiration date; may be null. * @param isSecure Whether this cookie requires a secure connection. */ public Cookie( String name, String value, String domain, String path, Date expiry, boolean isSecure) { this(name, value, domain, path, expiry, isSecure, false); } /** * Creates a cookie. * * @param name The name of the cookie; may not be null or an empty string. * @param value The cookie value; may not be null. * @param domain The domain the cookie is visible to. * @param path The path the cookie is visible to. If left blank or set to null, will be set to * "/". * @param expiry The cookie's expiration date; may be null. * @param isSecure Whether this cookie requires a secure connection. * @param isHttpOnly Whether this cookie is a httpOnly cooke. */ public Cookie( String name, String value, String domain, String path, Date expiry, boolean isSecure, boolean isHttpOnly) { this(name, value, domain, path, expiry, isSecure, isHttpOnly, null); } /** * Creates a cookie. * * @param name The name of the cookie; may not be null or an empty string. * @param value The cookie value; may not be null. * @param domain The domain the cookie is visible to. * @param path The path the cookie is visible to. If left blank or set to null, will be set to * "/". * @param expiry The cookie's expiration date; may be null. * @param isSecure Whether this cookie requires a secure connection. * @param isHttpOnly Whether this cookie is a httpOnly cookie. * @param sameSite The samesite attribute of this cookie; e.g. None, Lax, Strict. */ public Cookie( String name, String value, String domain, String path, Date expiry, boolean isSecure, boolean isHttpOnly, String sameSite) { this.name = name; this.value = value; this.path = path == null || "".equals(path) ? "/" : path; this.domain = stripPort(domain); this.isSecure = isSecure; this.isHttpOnly = isHttpOnly; if (expiry != null) { // Expiration date is specified in seconds since (UTC) epoch time, so truncate the date. this.expiry = new Date(expiry.getTime() / 1000 * 1000); } else { this.expiry = null; } this.sameSite = sameSite; } /** * Create a cookie for the default path with the given name and value with no expiry set. * * @param name The cookie's name * @param value The cookie's value */ public Cookie(String name, String value) { this(name, value, "/", null); } /** * Create a cookie. * * @param name The cookie's name * @param value The cookie's value * @param path The path the cookie is for */ public Cookie(String name, String value, String path) { this(name, value, path, null); } public String getName() { return name; } public String getValue() { return value; } public String getDomain() { return domain; } public String getPath() { return path; } public boolean isSecure() { return isSecure; } public boolean isHttpOnly() { return isHttpOnly; } public Date getExpiry() { return expiry == null ? null : new Date(expiry.getTime()); } public String getSameSite() { return sameSite; } private static String stripPort(String domain) { return (domain == null) ? null : domain.split(":")[0]; } public void validate() { if (name == null || "".equals(name) || value == null || path == null) { throw new IllegalArgumentException( "Required attributes are not set or " + "any non-null attribute set to null"); } if (name.indexOf(';') != -1) { throw new IllegalArgumentException("Cookie names cannot contain a ';': " + name); } if (domain != null && domain.contains(":")) { throw new IllegalArgumentException("Domain should not contain a port: " + domain); } } /** * JSON object keys are defined in * https://w3c.github.io/webdriver/#dfn-table-for-cookie-conversion. */ public Map<String, Object> toJson() { Map<String, Object> toReturn = new TreeMap<>(); if (getDomain() != null) { toReturn.put("domain", getDomain()); } if (getExpiry() != null) { toReturn.put("expiry", getExpiry()); } if (getName() != null) { toReturn.put("name", getName()); } if (getPath() != null) { toReturn.put("path", getPath()); } if (getValue() != null) { toReturn.put("value", getValue()); } toReturn.put("secure", isSecure()); toReturn.put("httpOnly", isHttpOnly()); if (getSameSite() != null) { toReturn.put("sameSite", getSameSite()); } return toReturn; } @Override public String toString() { SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); sdf.setTimeZone(TimeZone.getTimeZone("GMT")); return name + "=" + value + (expiry == null ? "" : "; expires=" + sdf.format(expiry)) + ("".equals(path) ? "" : "; path=" + path) + (domain == null ? "" : "; domain=" + domain) + (isSecure ? ";secure;" : "") + (sameSite == null ? "" : "; sameSite=" + sameSite); } /** Two cookies are equal if the name and value match */ @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Cookie)) { return false; } Cookie cookie = (Cookie) o; if (!name.equals(cookie.name)) { return false; } return Objects.equals(value, cookie.value); } @Override public int hashCode() { return name.hashCode(); } public static class Builder { private final String name; private final String value; private String path; private String domain; private Date expiry; private boolean secure; private boolean httpOnly; private String sameSite; public Builder(String name, String value) { this.name = name; this.value = value; } public Builder domain(String host) { this.domain = stripPort(host); return this; } public Builder path(String path) { this.path = path; return this; } public Builder expiresOn(Date expiry) { this.expiry = expiry == null ? null : new Date(expiry.getTime()); return this; } public Builder isSecure(boolean secure) { this.secure = secure; return this; } public Builder isHttpOnly(boolean httpOnly) { this.httpOnly = httpOnly; return this; } public Builder sameSite(String sameSite) { this.sameSite = sameSite; return this; } public Cookie build() { return new Cookie(name, value, domain, path, expiry, secure, httpOnly, sameSite); } } }
SeleniumHQ/selenium
java/src/org/openqa/selenium/Cookie.java
219
/* * Copyright 2002-2016 the original author or 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 * * https://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.springframework.oxm; import java.io.IOException; import javax.xml.transform.Result; /** * Defines the contract for Object XML Mapping Marshallers. Implementations of this interface * can serialize a given Object to an XML Stream. * * <p>Although the {@code marshal} method accepts a {@code java.lang.Object} as its * first parameter, most {@code Marshaller} implementations cannot handle arbitrary * {@code Object}s. Instead, an object class must be registered with the marshaller, * or have a common base class. * * @author Arjen Poutsma * @since 3.0 * @see Unmarshaller */ public interface Marshaller { /** * Indicate whether this marshaller can marshal instances of the supplied type. * @param clazz the class that this marshaller is being asked if it can marshal * @return {@code true} if this marshaller can indeed marshal instances of the supplied class; * {@code false} otherwise */ boolean supports(Class<?> clazz); /** * Marshal the object graph with the given root into the provided {@link Result}. * @param graph the root of the object graph to marshal * @param result the result to marshal to * @throws IOException if an I/O error occurs * @throws XmlMappingException if the given object cannot be marshalled to the result */ void marshal(Object graph, Result result) throws IOException, XmlMappingException; }
spring-projects/spring-framework
spring-oxm/src/main/java/org/springframework/oxm/Marshaller.java
220
package com.thealgorithms.strings; /* References : https://en.wikipedia.org/wiki/Run-length_encoding * String compression algorithm deals with encoding the string, that is, shortening the size of the * string * @author Swarga-codes (https://github.com/Swarga-codes) */ public final class StringCompression { private StringCompression() { } /** * Returns the compressed or encoded string * * @param ch character array that contains the group of characters to be encoded * @return the compressed character array as string */ public static String compress(String input) { // Keeping the count as 1 since every element present will have atleast a count // of 1 int count = 1; String compressedString = ""; // Base condition to check whether the array is of size 1, if it is then we // return the array if (input.length() == 1) { return "" + input.charAt(0); } // If the array has a length greater than 1 we move into this loop for (int i = 0; i < input.length() - 1; i++) { // here we check for similarity of the adjacent elements and change the count // accordingly if (input.charAt(i) == input.charAt(i + 1)) { count = count + 1; } if ((i + 1) == input.length() - 1 && input.charAt(i + 1) == input.charAt(i)) { compressedString = appendCount(compressedString, count, input.charAt(i)); break; } else if (input.charAt(i) != input.charAt(i + 1)) { if ((i + 1) == input.length() - 1) { compressedString = appendCount(compressedString, count, input.charAt(i)) + input.charAt(i + 1); break; } else { compressedString = appendCount(compressedString, count, input.charAt(i)); count = 1; } } } return compressedString; } /** * @param res the resulting string * @param count current count * @param ch the character at a particular index * @return the res string appended with the count */ public static String appendCount(String res, int count, char ch) { if (count > 1) { res += ch + "" + count; count = 1; } else { res += ch + ""; } return res; } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/strings/StringCompression.java
221
/* 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.lite; import java.io.File; import java.nio.ByteBuffer; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Map; import org.checkerframework.checker.nullness.qual.NonNull; import org.tensorflow.lite.InterpreterApi.Options.TfLiteRuntime; import org.tensorflow.lite.acceleration.ValidatedAccelerationConfig; import org.tensorflow.lite.nnapi.NnApiDelegate; /** * Interface to TensorFlow Lite model interpreter, excluding experimental methods. * * <p>An {@code InterpreterApi} instance encapsulates a pre-trained TensorFlow Lite model, in which * operations are executed for model inference. * * <p>For example, if a model takes only one input and returns only one output: * * <pre>{@code * try (InterpreterApi interpreter = * new InterpreterApi.create(file_of_a_tensorflowlite_model)) { * interpreter.run(input, output); * } * }</pre> * * <p>If a model takes multiple inputs or outputs: * * <pre>{@code * Object[] inputs = {input0, input1, ...}; * Map<Integer, Object> map_of_indices_to_outputs = new HashMap<>(); * FloatBuffer ith_output = FloatBuffer.allocateDirect(3 * 2 * 4); // Float tensor, shape 3x2x4. * ith_output.order(ByteOrder.nativeOrder()); * map_of_indices_to_outputs.put(i, ith_output); * try (InterpreterApi interpreter = * new InterpreterApi.create(file_of_a_tensorflowlite_model)) { * interpreter.runForMultipleInputsOutputs(inputs, map_of_indices_to_outputs); * } * }</pre> * * <p>If a model takes or produces string tensors: * * <pre>{@code * String[] input = {"foo", "bar"}; // Input tensor shape is [2]. * String[][] output = new String[3][2]; // Output tensor shape is [3, 2]. * try (InterpreterApi interpreter = * new InterpreterApi.create(file_of_a_tensorflowlite_model)) { * interpreter.runForMultipleInputsOutputs(input, output); * } * }</pre> * * <p>Note that there's a distinction between shape [] and shape[1]. For scalar string tensor * outputs: * * <pre>{@code * String[] input = {"foo"}; // Input tensor shape is [1]. * ByteBuffer outputBuffer = ByteBuffer.allocate(OUTPUT_BYTES_SIZE); // Output tensor shape is []. * try (Interpreter interpreter = new Interpreter(file_of_a_tensorflowlite_model)) { * interpreter.runForMultipleInputsOutputs(input, outputBuffer); * } * byte[] outputBytes = new byte[outputBuffer.remaining()]; * outputBuffer.get(outputBytes); * // Below, the `charset` can be StandardCharsets.UTF_8. * String output = new String(outputBytes, charset); * }</pre> * * <p>Orders of inputs and outputs are determined when converting TensorFlow model to TensorFlowLite * model with Toco, as are the default shapes of the inputs. * * <p>When inputs are provided as (multi-dimensional) arrays, the corresponding input tensor(s) will * be implicitly resized according to that array's shape. When inputs are provided as {@link * java.nio.Buffer} types, no implicit resizing is done; the caller must ensure that the {@link * java.nio.Buffer} byte size either matches that of the corresponding tensor, or that they first * resize the tensor via {@link #resizeInput(int, int[])}. Tensor shape and type information can be * obtained via the {@link Tensor} class, available via {@link #getInputTensor(int)} and {@link * #getOutputTensor(int)}. * * <p><b>WARNING:</b>{@code InterpreterApi} instances are <b>not</b> thread-safe. * * <p><b>WARNING:</b>An {@code InterpreterApi} instance owns resources that <b>must</b> be * explicitly freed by invoking {@link #close()} * * <p>The TFLite library is built against NDK API 19. It may work for Android API levels below 19, * but is not guaranteed. */ public interface InterpreterApi extends AutoCloseable { /** An options class for controlling runtime interpreter behavior. */ class Options { public Options() { this.delegates = new ArrayList<>(); this.delegateFactories = new ArrayList<>(); } public Options(Options other) { this.numThreads = other.numThreads; this.useNNAPI = other.useNNAPI; this.allowCancellation = other.allowCancellation; this.delegates = new ArrayList<>(other.delegates); this.delegateFactories = new ArrayList<>(other.delegateFactories); this.runtime = other.runtime; this.validatedAccelerationConfig = other.validatedAccelerationConfig; this.useXNNPACK = other.useXNNPACK; } /** * Sets the number of threads to be used for ops that support multi-threading. * * <p>{@code numThreads} should be {@code >= -1}. Setting {@code numThreads} to 0 has the effect * of disabling multithreading, which is equivalent to setting {@code numThreads} to 1. If * unspecified, or set to the value -1, the number of threads used will be * implementation-defined and platform-dependent. */ public Options setNumThreads(int numThreads) { this.numThreads = numThreads; return this; } /** * Returns the number of threads to be used for ops that support multi-threading. * * <p>{@code numThreads} should be {@code >= -1}. Values of 0 (or 1) disable multithreading. * Default value is -1: the number of threads used will be implementation-defined and * platform-dependent. */ public int getNumThreads() { return numThreads; } /** Sets whether to use NN API (if available) for op execution. Defaults to false (disabled). */ public Options setUseNNAPI(boolean useNNAPI) { this.useNNAPI = useNNAPI; return this; } /** * Returns whether to use NN API (if available) for op execution. Default value is false * (disabled). */ public boolean getUseNNAPI() { return useNNAPI != null && useNNAPI; } /** * Advanced: Set if the interpreter is able to be cancelled. * * <p>Interpreters may have an experimental API <a * href="https://www.tensorflow.org/lite/api_docs/java/org/tensorflow/lite/Interpreter#setCancelled(boolean)">setCancelled(boolean)</a>. * If this interpreter is cancellable and such a method is invoked, a cancellation flag will be * set to true. The interpreter will check the flag between Op invocations, and if it's {@code * true}, the interpreter will stop execution. The interpreter will remain a cancelled state * until explicitly "uncancelled" by {@code setCancelled(false)}. */ public Options setCancellable(boolean allow) { this.allowCancellation = allow; return this; } /** * Advanced: Returns whether the interpreter is able to be cancelled. * * <p>Interpreters may have an experimental API <a * href="https://www.tensorflow.org/lite/api_docs/java/org/tensorflow/lite/Interpreter#setCancelled(boolean)">setCancelled(boolean)</a>. * If this interpreter is cancellable and such a method is invoked, a cancellation flag will be * set to true. The interpreter will check the flag between Op invocations, and if it's {@code * true}, the interpreter will stop execution. The interpreter will remain a cancelled state * until explicitly "uncancelled" by {@code setCancelled(false)}. */ public boolean isCancellable() { return allowCancellation != null && allowCancellation; } /** * Adds a {@link Delegate} to be applied during interpreter creation. * * <p>Delegates added here are applied before any delegates created from a {@link * DelegateFactory} that was added with {@link #addDelegateFactory}. * * <p>Note that TF Lite in Google Play Services (see {@link #setRuntime}) does not support * external (developer-provided) delegates, and adding a {@link Delegate} other than {@link * NnApiDelegate} here is not allowed when using TF Lite in Google Play Services. */ public Options addDelegate(Delegate delegate) { delegates.add(delegate); return this; } /** * Returns the list of delegates intended to be applied during interpreter creation that have * been registered via {@code addDelegate}. */ public List<Delegate> getDelegates() { return Collections.unmodifiableList(delegates); } /** * Adds a {@link DelegateFactory} which will be invoked to apply its created {@link Delegate} * during interpreter creation. * * <p>Delegates from a delegated factory that was added here are applied after any delegates * added with {@link #addDelegate}. */ public Options addDelegateFactory(DelegateFactory delegateFactory) { delegateFactories.add(delegateFactory); return this; } /** * Returns the list of delegate factories that have been registered via {@code * addDelegateFactory}). */ public List<DelegateFactory> getDelegateFactories() { return Collections.unmodifiableList(delegateFactories); } /** * Enum to represent where to get the TensorFlow Lite runtime implementation from. * * <p>The difference between this class and the RuntimeFlavor class: This class specifies a * <em>preference</em> which runtime to use, whereas {@link RuntimeFlavor} specifies which exact * runtime <em>is</em> being used. */ public enum TfLiteRuntime { /** * Use a TF Lite runtime implementation that is linked into the application. If there is no * suitable TF Lite runtime implementation linked into the application, then attempting to * create an InterpreterApi instance with this TfLiteRuntime setting will throw an * IllegalStateException exception (even if the OS or system services could provide a TF Lite * runtime implementation). * * <p>This is the default setting. This setting is also appropriate for apps that must run on * systems that don't provide a TF Lite runtime implementation. */ FROM_APPLICATION_ONLY, /** * Use a TF Lite runtime implementation provided by the OS or system services. This will be * obtained from a system library / shared object / service, such as Google Play Services. It * may be newer than the version linked into the application (if any). If there is no suitable * TF Lite runtime implementation provided by the system, then attempting to create an * InterpreterApi instance with this TfLiteRuntime setting will throw an IllegalStateException * exception (even if there is a TF Lite runtime implementation linked into the application). * * <p>This setting is appropriate for code that will use a system-provided TF Lite runtime, * which can reduce app binary size and can be updated more frequently. */ FROM_SYSTEM_ONLY, /** * Use a system-provided TF Lite runtime implementation, if any, otherwise use the TF Lite * runtime implementation linked into the application, if any. If no suitable TF Lite runtime * can be found in any location, then attempting to create an InterpreterApi instance with * this TFLiteRuntime setting will throw an IllegalStateException. If there is both a suitable * TF Lite runtime linked into the application and also a suitable TF Lite runtime provided by * the system, the one provided by the system will be used. * * <p>This setting is suitable for use in code that doesn't care where the TF Lite runtime is * coming from (e.g. middleware layers). */ PREFER_SYSTEM_OVER_APPLICATION, } /** Specify where to get the TF Lite runtime implementation from. */ public Options setRuntime(TfLiteRuntime runtime) { this.runtime = runtime; return this; } /** Return where to get the TF Lite runtime implementation from. */ public TfLiteRuntime getRuntime() { return runtime; } /** Specify the acceleration configuration. */ public Options setAccelerationConfig(ValidatedAccelerationConfig config) { this.validatedAccelerationConfig = config; return this; } /** Return the acceleration configuration. */ public ValidatedAccelerationConfig getAccelerationConfig() { return this.validatedAccelerationConfig; } /** * Enable or disable an optimized set of CPU kernels (provided by XNNPACK). Enabled by default. */ public Options setUseXNNPACK(boolean useXNNPACK) { this.useXNNPACK = useXNNPACK; return this; } public boolean getUseXNNPACK() { // A null value indicates the default behavior, which is currently to apply the delegate. return useXNNPACK == null || useXNNPACK.booleanValue(); } TfLiteRuntime runtime = TfLiteRuntime.FROM_APPLICATION_ONLY; int numThreads = -1; Boolean useNNAPI; /** * Note: the initial "null" value indicates default behavior (XNNPACK delegate will be applied * by default whenever possible). * * <p>Disabling this flag will disable use of a highly optimized set of CPU kernels provided via * the XNNPACK delegate. Currently, this is restricted to a subset of floating point operations. * See * https://github.com/tensorflow/tensorflow/blob/master/tensorflow/lite/delegates/xnnpack/README.md * for more details. */ Boolean useXNNPACK; Boolean allowCancellation; ValidatedAccelerationConfig validatedAccelerationConfig; // See InterpreterApi.Options#addDelegate. final List<Delegate> delegates; // See InterpreterApi.Options#addDelegateFactory. private final List<DelegateFactory> delegateFactories; } /** * Constructs an {@link InterpreterApi} instance, using the specified model and options. The model * will be loaded from a file. * * @param modelFile A file containing a pre-trained TF Lite model. * @param options A set of options for customizing interpreter behavior. * @throws IllegalArgumentException if {@code modelFile} does not encode a valid TensorFlow Lite * model. */ @SuppressWarnings("StaticOrDefaultInterfaceMethod") static InterpreterApi create(@NonNull File modelFile, InterpreterApi.Options options) { TfLiteRuntime runtime = (options == null ? null : options.getRuntime()); InterpreterFactoryApi factory = TensorFlowLite.getFactory(runtime); return factory.create(modelFile, options); } /** * Constructs an {@link InterpreterApi} instance, using the specified model and options. The model * will be read from a {@code ByteBuffer}. * * @param byteBuffer A pre-trained TF Lite model, in binary serialized form. The ByteBuffer should * not be modified after the construction of an {@link InterpreterApi} instance. The {@code * ByteBuffer} can be either a {@code MappedByteBuffer} that memory-maps a model file, or a * direct {@code ByteBuffer} of nativeOrder() that contains the bytes content of a model. * @param options A set of options for customizing interpreter behavior. * @throws IllegalArgumentException if {@code byteBuffer} is not a {@code MappedByteBuffer} nor a * direct {@code ByteBuffer} of nativeOrder. */ @SuppressWarnings("StaticOrDefaultInterfaceMethod") static InterpreterApi create(@NonNull ByteBuffer byteBuffer, InterpreterApi.Options options) { TfLiteRuntime runtime = (options == null ? null : options.getRuntime()); InterpreterFactoryApi factory = TensorFlowLite.getFactory(runtime); return factory.create(byteBuffer, options); } /** * Runs model inference if the model takes only one input, and provides only one output. * * <p>Warning: The API is more efficient if a {@code Buffer} (preferably direct, but not required) * is used as the input/output data type. Please consider using {@code Buffer} to feed and fetch * primitive data for better performance. The following concrete {@code Buffer} types are * supported: * * <ul> * <li>{@code ByteBuffer} - compatible with any underlying primitive Tensor type. * <li>{@code FloatBuffer} - compatible with float Tensors. * <li>{@code IntBuffer} - compatible with int32 Tensors. * <li>{@code LongBuffer} - compatible with int64 Tensors. * </ul> * * Note that boolean types are only supported as arrays, not {@code Buffer}s, or as scalar inputs. * * @param input an array or multidimensional array, or a {@code Buffer} of primitive types * including int, float, long, and byte. {@code Buffer} is the preferred way to pass large * input data for primitive types, whereas string types require using the (multi-dimensional) * array input path. When a {@code Buffer} is used, its content should remain unchanged until * model inference is done, and the caller must ensure that the {@code Buffer} is at the * appropriate read position. A {@code null} value is allowed only if the caller is using a * {@link Delegate} that allows buffer handle interop, and such a buffer has been bound to the * input {@link Tensor}. * @param output a multidimensional array of output data, or a {@code Buffer} of primitive types * including int, float, long, and byte. When a {@code Buffer} is used, the caller must ensure * that it is set the appropriate write position. A null value is allowed, and is useful for * certain cases, e.g., if the caller is using a {@link Delegate} that allows buffer handle * interop, and such a buffer has been bound to the output {@link Tensor} (see also <a * href="https://www.tensorflow.org/lite/api_docs/java/org/tensorflow/lite/Interpreter.Options#setAllowBufferHandleOutput(boolean)">Interpreter.Options#setAllowBufferHandleOutput(boolean)</a>), * or if the graph has dynamically shaped outputs and the caller must query the output {@link * Tensor} shape after inference has been invoked, fetching the data directly from the output * tensor (via {@link Tensor#asReadOnlyBuffer()}). * @throws IllegalArgumentException if {@code input} is null or empty, or if an error occurs when * running inference. * @throws IllegalArgumentException (EXPERIMENTAL, subject to change) if the inference is * interrupted by {@code setCancelled(true)}. */ void run(Object input, Object output); /** * Runs model inference if the model takes multiple inputs, or returns multiple outputs. * * <p>Warning: The API is more efficient if {@code Buffer}s (preferably direct, but not required) * are used as the input/output data types. Please consider using {@code Buffer} to feed and fetch * primitive data for better performance. The following concrete {@code Buffer} types are * supported: * * <ul> * <li>{@code ByteBuffer} - compatible with any underlying primitive Tensor type. * <li>{@code FloatBuffer} - compatible with float Tensors. * <li>{@code IntBuffer} - compatible with int32 Tensors. * <li>{@code LongBuffer} - compatible with int64 Tensors. * </ul> * * Note that boolean types are only supported as arrays, not {@code Buffer}s, or as scalar inputs. * * <p>Note: {@code null} values for invididual elements of {@code inputs} and {@code outputs} is * allowed only if the caller is using a {@link Delegate} that allows buffer handle interop, and * such a buffer has been bound to the corresponding input or output {@link Tensor}(s). * * @param inputs an array of input data. The inputs should be in the same order as inputs of the * model. Each input can be an array or multidimensional array, or a {@code Buffer} of * primitive types including int, float, long, and byte. {@code Buffer} is the preferred way * to pass large input data, whereas string types require using the (multi-dimensional) array * input path. When {@code Buffer} is used, its content should remain unchanged until model * inference is done, and the caller must ensure that the {@code Buffer} is at the appropriate * read position. * @param outputs a map mapping output indices to multidimensional arrays of output data or {@code * Buffer}s of primitive types including int, float, long, and byte. It only needs to keep * entries for the outputs to be used. When a {@code Buffer} is used, the caller must ensure * that it is set the appropriate write position. The map may be empty for cases where either * buffer handles are used for output tensor data, or cases where the outputs are dynamically * shaped and the caller must query the output {@link Tensor} shape after inference has been * invoked, fetching the data directly from the output tensor (via {@link * Tensor#asReadOnlyBuffer()}). * @throws IllegalArgumentException if {@code inputs} is null or empty, if {@code outputs} is * null, or if an error occurs when running inference. */ void runForMultipleInputsOutputs( Object @NonNull [] inputs, @NonNull Map<Integer, Object> outputs); /** * Explicitly updates allocations for all tensors, if necessary. * * <p>This will propagate shapes and memory allocations for dependent tensors using the input * tensor shape(s) as given. * * <p>Note: This call is *purely optional*. Tensor allocation will occur automatically during * execution if any input tensors have been resized. This call is most useful in determining the * shapes for any output tensors before executing the graph, e.g., * * <pre> {@code * interpreter.resizeInput(0, new int[]{1, 4, 4, 3})); * interpreter.allocateTensors(); * FloatBuffer input = FloatBuffer.allocate(interpreter.getInputTensor(0).numElements()); * // Populate inputs... * FloatBuffer output = FloatBuffer.allocate(interpreter.getOutputTensor(0).numElements()); * interpreter.run(input, output) * // Process outputs...}</pre> * * <p>Note: Some graphs have dynamically shaped outputs, in which case the output shape may not * fully propagate until inference is executed. * * @throws IllegalStateException if the graph's tensors could not be successfully allocated. */ void allocateTensors(); /** * Resizes idx-th input of the native model to the given dims. * * @throws IllegalArgumentException if {@code idx} is negative or is not smaller than the number * of model inputs; or if error occurs when resizing the idx-th input. */ void resizeInput(int idx, int @NonNull [] dims); /** * Resizes idx-th input of the native model to the given dims. * * <p>When `strict` is True, only unknown dimensions can be resized. Unknown dimensions are * indicated as `-1` in the array returned by `Tensor.shapeSignature()`. * * @throws IllegalArgumentException if {@code idx} is negative or is not smaller than the number * of model inputs; or if error occurs when resizing the idx-th input. Additionally, the error * occurs when attempting to resize a tensor with fixed dimensions when `strict` is True. */ void resizeInput(int idx, int @NonNull [] dims, boolean strict); /** Gets the number of input tensors. */ int getInputTensorCount(); /** * Gets index of an input given the op name of the input. * * @throws IllegalArgumentException if {@code opName} does not match any input in the model used * to initialize the interpreter. */ int getInputIndex(String opName); /** * Gets the Tensor associated with the provided input index. * * @throws IllegalArgumentException if {@code inputIndex} is negative or is not smaller than the * number of model inputs. */ Tensor getInputTensor(int inputIndex); /** Gets the number of output Tensors. */ int getOutputTensorCount(); /** * Gets index of an output given the op name of the output. * * @throws IllegalArgumentException if {@code opName} does not match any output in the model used * to initialize the interpreter. */ int getOutputIndex(String opName); /** * Gets the Tensor associated with the provided output index. * * <p>Note: Output tensor details (e.g., shape) may not be fully populated until after inference * is executed. If you need updated details *before* running inference (e.g., after resizing an * input tensor, which may invalidate output tensor shapes), use {@link #allocateTensors()} to * explicitly trigger allocation and shape propagation. Note that, for graphs with output shapes * that are dependent on input *values*, the output shape may not be fully determined until * running inference. * * @throws IllegalArgumentException if {@code outputIndex} is negative or is not smaller than the * number of model outputs. */ Tensor getOutputTensor(int outputIndex); /** * Returns native inference timing. * * @throws IllegalArgumentException if the model is not initialized by the interpreter. */ Long getLastNativeInferenceDurationNanoseconds(); /** Release resources associated with the {@code InterpreterApi} instance. */ @Override void close(); }
tensorflow/tensorflow
tensorflow/lite/java/src/main/java/org/tensorflow/lite/InterpreterApi.java
222
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; /** * Static methods pertaining to ASCII characters (those in the range of values {@code 0x00} through * {@code 0x7F}), and to strings containing such characters. * * <p>ASCII utilities also exist in other classes of this package: * * <ul> * <!-- TODO(kevinb): how can we make this not produce a warning when building gwt javadoc? --> * <li>{@link Charsets#US_ASCII} specifies the {@code Charset} of ASCII characters. * <li>{@link CharMatcher#ascii} matches ASCII characters and provides text processing methods * which operate only on the ASCII characters of a string. * </ul> * * @author Catherine Berry * @author Gregory Kick * @since 7.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Ascii { private Ascii() {} /* The ASCII control characters, per RFC 20. */ /** * Null ('\0'): The all-zeros character which may serve to accomplish time fill and media fill. * Normally used as a C string terminator. * * <p>Although RFC 20 names this as "Null", note that it is distinct from the C/C++ "NULL" * pointer. * * @since 8.0 */ public static final byte NUL = 0; /** * Start of Heading: A communication control character used at the beginning of a sequence of * characters which constitute a machine-sensible address or routing information. Such a sequence * is referred to as the "heading." An STX character has the effect of terminating a heading. * * @since 8.0 */ public static final byte SOH = 1; /** * Start of Text: A communication control character which precedes a sequence of characters that * is to be treated as an entity and entirely transmitted through to the ultimate destination. * Such a sequence is referred to as "text." STX may be used to terminate a sequence of characters * started by SOH. * * @since 8.0 */ public static final byte STX = 2; /** * End of Text: A communication control character used to terminate a sequence of characters * started with STX and transmitted as an entity. * * @since 8.0 */ public static final byte ETX = 3; /** * End of Transmission: A communication control character used to indicate the conclusion of a * transmission, which may have contained one or more texts and any associated headings. * * @since 8.0 */ public static final byte EOT = 4; /** * Enquiry: A communication control character used in data communication systems as a request for * a response from a remote station. It may be used as a "Who Are You" (WRU) to obtain * identification, or may be used to obtain station status, or both. * * @since 8.0 */ public static final byte ENQ = 5; /** * Acknowledge: A communication control character transmitted by a receiver as an affirmative * response to a sender. * * @since 8.0 */ public static final byte ACK = 6; /** * Bell ('\a'): A character for use when there is a need to call for human attention. It may * control alarm or attention devices. * * @since 8.0 */ public static final byte BEL = 7; /** * Backspace ('\b'): A format effector which controls the movement of the printing position one * printing space backward on the same printing line. (Applicable also to display devices.) * * @since 8.0 */ public static final byte BS = 8; /** * Horizontal Tabulation ('\t'): A format effector which controls the movement of the printing * position to the next in a series of predetermined positions along the printing line. * (Applicable also to display devices and the skip function on punched cards.) * * @since 8.0 */ public static final byte HT = 9; /** * Line Feed ('\n'): A format effector which controls the movement of the printing position to the * next printing line. (Applicable also to display devices.) Where appropriate, this character may * have the meaning "New Line" (NL), a format effector which controls the movement of the printing * point to the first printing position on the next printing line. Use of this convention requires * agreement between sender and recipient of data. * * @since 8.0 */ public static final byte LF = 10; /** * Alternate name for {@link #LF}. ({@code LF} is preferred.) * * @since 8.0 */ public static final byte NL = 10; /** * Vertical Tabulation ('\v'): A format effector which controls the movement of the printing * position to the next in a series of predetermined printing lines. (Applicable also to display * devices.) * * @since 8.0 */ public static final byte VT = 11; /** * Form Feed ('\f'): A format effector which controls the movement of the printing position to the * first pre-determined printing line on the next form or page. (Applicable also to display * devices.) * * @since 8.0 */ public static final byte FF = 12; /** * Carriage Return ('\r'): A format effector which controls the movement of the printing position * to the first printing position on the same printing line. (Applicable also to display devices.) * * @since 8.0 */ public static final byte CR = 13; /** * Shift Out: A control character indicating that the code combinations which follow shall be * interpreted as outside of the character set of the standard code table until a Shift In * character is reached. * * @since 8.0 */ public static final byte SO = 14; /** * Shift In: A control character indicating that the code combinations which follow shall be * interpreted according to the standard code table. * * @since 8.0 */ public static final byte SI = 15; /** * Data Link Escape: A communication control character which will change the meaning of a limited * number of contiguously following characters. It is used exclusively to provide supplementary * controls in data communication networks. * * @since 8.0 */ public static final byte DLE = 16; /** * Device Control 1. Characters for the control of ancillary devices associated with data * processing or telecommunication systems, more especially switching devices "on" or "off." (If a * single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the * preferred assignment.) * * @since 8.0 */ public static final byte DC1 = 17; // aka XON /** * Transmission On: Although originally defined as DC1, this ASCII control character is now better * known as the XON code used for software flow control in serial communications. The main use is * restarting the transmission after the communication has been stopped by the XOFF control code. * * @since 8.0 */ public static final byte XON = 17; // aka DC1 /** * Device Control 2. Characters for the control of ancillary devices associated with data * processing or telecommunication systems, more especially switching devices "on" or "off." (If a * single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the * preferred assignment.) * * @since 8.0 */ public static final byte DC2 = 18; /** * Device Control 3. Characters for the control of ancillary devices associated with data * processing or telecommunication systems, more especially switching devices "on" or "off." (If a * single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the * preferred assignment.) * * @since 8.0 */ public static final byte DC3 = 19; // aka XOFF /** * Transmission off. See {@link #XON} for explanation. * * @since 8.0 */ public static final byte XOFF = 19; // aka DC3 /** * Device Control 4. Characters for the control of ancillary devices associated with data * processing or telecommunication systems, more especially switching devices "on" or "off." (If a * single "stop" control is required to interrupt or turn off ancillary devices, DC4 is the * preferred assignment.) * * @since 8.0 */ public static final byte DC4 = 20; /** * Negative Acknowledge: A communication control character transmitted by a receiver as a negative * response to the sender. * * @since 8.0 */ public static final byte NAK = 21; /** * Synchronous Idle: A communication control character used by a synchronous transmission system * in the absence of any other character to provide a signal from which synchronism may be * achieved or retained. * * @since 8.0 */ public static final byte SYN = 22; /** * End of Transmission Block: A communication control character used to indicate the end of a * block of data for communication purposes. ETB is used for blocking data where the block * structure is not necessarily related to the processing format. * * @since 8.0 */ public static final byte ETB = 23; /** * Cancel: A control character used to indicate that the data with which it is sent is in error or * is to be disregarded. * * @since 8.0 */ public static final byte CAN = 24; /** * End of Medium: A control character associated with the sent data which may be used to identify * the physical end of the medium, or the end of the used, or wanted, portion of information * recorded on a medium. (The position of this character does not necessarily correspond to the * physical end of the medium.) * * @since 8.0 */ public static final byte EM = 25; /** * Substitute: A character that may be substituted for a character which is determined to be * invalid or in error. * * @since 8.0 */ public static final byte SUB = 26; /** * Escape: A control character intended to provide code extension (supplementary characters) in * general information interchange. The Escape character itself is a prefix affecting the * interpretation of a limited number of contiguously following characters. * * @since 8.0 */ public static final byte ESC = 27; /** * File Separator: These four information separators may be used within data in optional fashion, * except that their hierarchical relationship shall be: FS is the most inclusive, then GS, then * RS, and US is least inclusive. (The content and length of a File, Group, Record, or Unit are * not specified.) * * @since 8.0 */ public static final byte FS = 28; /** * Group Separator: These four information separators may be used within data in optional fashion, * except that their hierarchical relationship shall be: FS is the most inclusive, then GS, then * RS, and US is least inclusive. (The content and length of a File, Group, Record, or Unit are * not specified.) * * @since 8.0 */ public static final byte GS = 29; /** * Record Separator: These four information separators may be used within data in optional * fashion, except that their hierarchical relationship shall be: FS is the most inclusive, then * GS, then RS, and US is least inclusive. (The content and length of a File, Group, Record, or * Unit are not specified.) * * @since 8.0 */ public static final byte RS = 30; /** * Unit Separator: These four information separators may be used within data in optional fashion, * except that their hierarchical relationship shall be: FS is the most inclusive, then GS, then * RS, and US is least inclusive. (The content and length of a File, Group, Record, or Unit are * not specified.) * * @since 8.0 */ public static final byte US = 31; /** * Space: A normally non-printing graphic character used to separate words. It is also a format * effector which controls the movement of the printing position, one printing position forward. * (Applicable also to display devices.) * * @since 8.0 */ public static final byte SP = 32; /** * Alternate name for {@link #SP}. * * @since 8.0 */ public static final byte SPACE = 32; /** * Delete: This character is used primarily to "erase" or "obliterate" erroneous or unwanted * characters in perforated tape. * * @since 8.0 */ public static final byte DEL = 127; /** * The minimum value of an ASCII character. * * @since 9.0 (was type {@code int} before 12.0) */ public static final char MIN = 0; /** * The maximum value of an ASCII character. * * @since 9.0 (was type {@code int} before 12.0) */ public static final char MAX = 127; /** A bit mask which selects the bit encoding ASCII character case. */ private static final char CASE_MASK = 0x20; /** * Returns a copy of the input string in which all {@linkplain #isUpperCase(char) uppercase ASCII * characters} have been converted to lowercase. All other characters are copied without * modification. */ public static String toLowerCase(String string) { int length = string.length(); for (int i = 0; i < length; i++) { if (isUpperCase(string.charAt(i))) { char[] chars = string.toCharArray(); for (; i < length; i++) { char c = chars[i]; if (isUpperCase(c)) { chars[i] = (char) (c ^ CASE_MASK); } } return String.valueOf(chars); } } return string; } /** * Returns a copy of the input character sequence in which all {@linkplain #isUpperCase(char) * uppercase ASCII characters} have been converted to lowercase. All other characters are copied * without modification. * * @since 14.0 */ public static String toLowerCase(CharSequence chars) { if (chars instanceof String) { return toLowerCase((String) chars); } char[] newChars = new char[chars.length()]; for (int i = 0; i < newChars.length; i++) { newChars[i] = toLowerCase(chars.charAt(i)); } return String.valueOf(newChars); } /** * If the argument is an {@linkplain #isUpperCase(char) uppercase ASCII character}, returns the * lowercase equivalent. Otherwise returns the argument. */ public static char toLowerCase(char c) { return isUpperCase(c) ? (char) (c ^ CASE_MASK) : c; } /** * Returns a copy of the input string in which all {@linkplain #isLowerCase(char) lowercase ASCII * characters} have been converted to uppercase. All other characters are copied without * modification. */ public static String toUpperCase(String string) { int length = string.length(); for (int i = 0; i < length; i++) { if (isLowerCase(string.charAt(i))) { char[] chars = string.toCharArray(); for (; i < length; i++) { char c = chars[i]; if (isLowerCase(c)) { chars[i] = (char) (c ^ CASE_MASK); } } return String.valueOf(chars); } } return string; } /** * Returns a copy of the input character sequence in which all {@linkplain #isLowerCase(char) * lowercase ASCII characters} have been converted to uppercase. All other characters are copied * without modification. * * @since 14.0 */ public static String toUpperCase(CharSequence chars) { if (chars instanceof String) { return toUpperCase((String) chars); } char[] newChars = new char[chars.length()]; for (int i = 0; i < newChars.length; i++) { newChars[i] = toUpperCase(chars.charAt(i)); } return String.valueOf(newChars); } /** * If the argument is a {@linkplain #isLowerCase(char) lowercase ASCII character}, returns the * uppercase equivalent. Otherwise returns the argument. */ public static char toUpperCase(char c) { return isLowerCase(c) ? (char) (c ^ CASE_MASK) : c; } /** * Indicates whether {@code c} is one of the twenty-six lowercase ASCII alphabetic characters * between {@code 'a'} and {@code 'z'} inclusive. All others (including non-ASCII characters) * return {@code false}. */ public static boolean isLowerCase(char c) { // Note: This was benchmarked against the alternate expression "(char)(c - 'a') < 26" (Nov '13) // and found to perform at least as well, or better. return (c >= 'a') && (c <= 'z'); } /** * Indicates whether {@code c} is one of the twenty-six uppercase ASCII alphabetic characters * between {@code 'A'} and {@code 'Z'} inclusive. All others (including non-ASCII characters) * return {@code false}. */ public static boolean isUpperCase(char c) { return (c >= 'A') && (c <= 'Z'); } /** * Truncates the given character sequence to the given maximum length. If the length of the * sequence is greater than {@code maxLength}, the returned string will be exactly {@code * maxLength} chars in length and will end with the given {@code truncationIndicator}. Otherwise, * the sequence will be returned as a string with no changes to the content. * * <p>Examples: * * <pre>{@code * Ascii.truncate("foobar", 7, "..."); // returns "foobar" * Ascii.truncate("foobar", 5, "..."); // returns "fo..." * }</pre> * * <p><b>Note:</b> This method <i>may</i> work with certain non-ASCII text but is not safe for use * with arbitrary Unicode text. It is mostly intended for use with text that is known to be safe * for use with it (such as all-ASCII text) and for simple debugging text. When using this method, * consider the following: * * <ul> * <li>it may split surrogate pairs * <li>it may split characters and combining characters * <li>it does not consider word boundaries * <li>if truncating for display to users, there are other considerations that must be taken * into account * <li>the appropriate truncation indicator may be locale-dependent * <li>it is safe to use non-ASCII characters in the truncation indicator * </ul> * * @throws IllegalArgumentException if {@code maxLength} is less than the length of {@code * truncationIndicator} * @since 16.0 */ public static String truncate(CharSequence seq, int maxLength, String truncationIndicator) { checkNotNull(seq); // length to truncate the sequence to, not including the truncation indicator int truncationLength = maxLength - truncationIndicator.length(); // in this worst case, this allows a maxLength equal to the length of the truncationIndicator, // meaning that a string will be truncated to just the truncation indicator itself checkArgument( truncationLength >= 0, "maxLength (%s) must be >= length of the truncation indicator (%s)", maxLength, truncationIndicator.length()); if (seq.length() <= maxLength) { String string = seq.toString(); if (string.length() <= maxLength) { return string; } // if the length of the toString() result was > maxLength for some reason, truncate that seq = string; } return new StringBuilder(maxLength) .append(seq, 0, truncationLength) .append(truncationIndicator) .toString(); } /** * Indicates whether the contents of the given character sequences {@code s1} and {@code s2} are * equal, ignoring the case of any ASCII alphabetic characters between {@code 'a'} and {@code 'z'} * or {@code 'A'} and {@code 'Z'} inclusive. * * <p>This method is significantly faster than {@link String#equalsIgnoreCase} and should be used * in preference if at least one of the parameters is known to contain only ASCII characters. * * <p>Note however that this method does not always behave identically to expressions such as: * * <ul> * <li>{@code string.toUpperCase().equals("UPPER CASE ASCII")} * <li>{@code string.toLowerCase().equals("lower case ascii")} * </ul> * * <p>due to case-folding of some non-ASCII characters (which does not occur in {@link * String#equalsIgnoreCase}). However in almost all cases that ASCII strings are used, the author * probably wanted the behavior provided by this method rather than the subtle and sometimes * surprising behavior of {@code toUpperCase()} and {@code toLowerCase()}. * * @since 16.0 */ public static boolean equalsIgnoreCase(CharSequence s1, CharSequence s2) { // Calling length() is the null pointer check (so do it before we can exit early). int length = s1.length(); if (s1 == s2) { return true; } if (length != s2.length()) { return false; } for (int i = 0; i < length; i++) { char c1 = s1.charAt(i); char c2 = s2.charAt(i); if (c1 == c2) { continue; } int alphaIndex = getAlphaIndex(c1); // This was also benchmarked using '&' to avoid branching (but always evaluate the rhs), // however this showed no obvious improvement. if (alphaIndex < 26 && alphaIndex == getAlphaIndex(c2)) { continue; } return false; } return true; } /** * Returns the non-negative index value of the alpha character {@code c}, regardless of case. Ie, * 'a'/'A' returns 0 and 'z'/'Z' returns 25. Non-alpha characters return a value of 26 or greater. */ private static int getAlphaIndex(char c) { // Fold upper-case ASCII to lower-case and make zero-indexed and unsigned (by casting to char). return (char) ((c | CASE_MASK) - 'a'); } }
google/guava
guava/src/com/google/common/base/Ascii.java
223
/* * 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.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.CompatibleWith; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import java.util.Spliterator; import java.util.function.Consumer; import java.util.function.ObjIntConsumer; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A collection that supports order-independent equality, like {@link Set}, but may have duplicate * elements. A multiset is also sometimes called a <i>bag</i>. * * <p>Elements of a multiset that are equal to one another are referred to as <i>occurrences</i> of * the same single element. The total number of occurrences of an element in a multiset is called * the <i>count</i> of that element (the terms "frequency" and "multiplicity" are equivalent, but * not used in this API). Since the count of an element is represented as an {@code int}, a multiset * may never contain more than {@link Integer#MAX_VALUE} occurrences of any one element. * * <p>{@code Multiset} refines the specifications of several methods from {@code Collection}. It * also defines an additional query operation, {@link #count}, which returns the count of an * element. There are five new bulk-modification operations, for example {@link #add(Object, int)}, * to add or remove multiple occurrences of an element at once, or to set the count of an element to * a specific value. These modification operations are optional, but implementations which support * the standard collection operations {@link #add(Object)} or {@link #remove(Object)} are encouraged * to implement the related methods as well. Finally, two collection views are provided: {@link * #elementSet} contains the distinct elements of the multiset "with duplicates collapsed", and * {@link #entrySet} is similar but contains {@link Entry Multiset.Entry} instances, each providing * both a distinct element and the count of that element. * * <p>In addition to these required methods, implementations of {@code Multiset} are expected to * provide two {@code static} creation methods: {@code create()}, returning an empty multiset, and * {@code create(Iterable<? extends E>)}, returning a multiset containing the given initial * elements. This is simply a refinement of {@code Collection}'s constructor recommendations, * reflecting the new developments of Java 5. * * <p>As with other collection types, the modification operations are optional, and should throw * {@link UnsupportedOperationException} when they are not implemented. Most implementations should * support either all add operations or none of them, all removal operations or none of them, and if * and only if all of these are supported, the {@code setCount} methods as well. * * <p>A multiset uses {@link Object#equals} to determine whether two instances should be considered * "the same," <i>unless specified otherwise</i> by the implementation. * * <p><b>Warning:</b> as with normal {@link Set}s, it is almost always a bad idea to modify an * element (in a way that affects its {@link Object#equals} behavior) while it is contained in a * multiset. Undefined behavior and bugs will result. * * <h3>Implementations</h3> * * <ul> * <li>{@link ImmutableMultiset} * <li>{@link ImmutableSortedMultiset} * <li>{@link HashMultiset} * <li>{@link LinkedHashMultiset} * <li>{@link TreeMultiset} * <li>{@link EnumMultiset} * <li>{@link ConcurrentHashMultiset} * </ul> * * <p>If your values may be zero, negative, or outside the range of an int, you may wish to use * {@link com.google.common.util.concurrent.AtomicLongMap} instead. Note, however, that unlike * {@code Multiset}, {@code AtomicLongMap} does not automatically remove zeros. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multiset">{@code Multiset}</a>. * * @author Kevin Bourrillion * @since 2.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public interface Multiset<E extends @Nullable Object> extends Collection<E> { // Query Operations /** * Returns the total number of all occurrences of all elements in this multiset. * * <p><b>Note:</b> this method does not return the number of <i>distinct elements</i> in the * multiset, which is given by {@code entrySet().size()}. */ @Override int size(); /** * Returns the number of occurrences of an element in this multiset (the <i>count</i> of the * element). Note that for an {@link Object#equals}-based multiset, this gives the same result as * {@link Collections#frequency} (which would presumably perform more poorly). * * <p><b>Note:</b> the utility method {@link Iterables#frequency} generalizes this operation; it * correctly delegates to this method when dealing with a multiset, but it can also accept any * other iterable type. * * @param element the element to count occurrences of * @return the number of occurrences of the element in this multiset; possibly zero but never * negative */ int count(@CompatibleWith("E") @CheckForNull Object element); // Bulk Operations /** * Adds a number of occurrences of an element to this multiset. Note that if {@code occurrences == * 1}, this method has the identical effect to {@link #add(Object)}. This method is functionally * equivalent (except in the case of overflow) to the call {@code * addAll(Collections.nCopies(element, occurrences))}, which would presumably perform much more * poorly. * * @param element the element to add occurrences of; may be null only if explicitly allowed by the * implementation * @param occurrences the number of occurrences of the element to add. May be zero, in which case * no change will be made. * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code occurrences} is negative, or if this operation would * result in more than {@link Integer#MAX_VALUE} occurrences of the element * @throws NullPointerException if {@code element} is null and this implementation does not permit * null elements. Note that if {@code occurrences} is zero, the implementation may opt to * return normally. */ @CanIgnoreReturnValue int add(@ParametricNullness E element, int occurrences); /** * Adds a single occurrence of the specified element to this multiset. * * <p>This method refines {@link Collection#add}, which only <i>ensures</i> the presence of the * element, to further specify that a successful call must always increment the count of the * element, and the overall size of the collection, by one. * * <p>To both add the element and obtain the previous count of that element, use {@link * #add(Object, int) add}{@code (element, 1)} instead. * * @param element the element to add one occurrence of; may be null only if explicitly allowed by * the implementation * @return {@code true} always, since this call is required to modify the multiset, unlike other * {@link Collection} types * @throws NullPointerException if {@code element} is null and this implementation does not permit * null elements * @throws IllegalArgumentException if {@link Integer#MAX_VALUE} occurrences of {@code element} * are already contained in this multiset */ @CanIgnoreReturnValue @Override boolean add(@ParametricNullness E element); /** * Removes a number of occurrences of the specified element from this multiset. If the multiset * contains fewer than this number of occurrences to begin with, all occurrences will be removed. * Note that if {@code occurrences == 1}, this is functionally equivalent to the call {@code * remove(element)}. * * @param element the element to conditionally remove occurrences of * @param occurrences the number of occurrences of the element to remove. May be zero, in which * case no change will be made. * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code occurrences} is negative */ @CanIgnoreReturnValue int remove(@CompatibleWith("E") @CheckForNull Object element, int occurrences); /** * Removes a <i>single</i> occurrence of the specified element from this multiset, if present. * * <p>This method refines {@link Collection#remove} to further specify that it <b>may not</b> * throw an exception in response to {@code element} being null or of the wrong type. * * <p>To both remove the element and obtain the previous count of that element, use {@link * #remove(Object, int) remove}{@code (element, 1)} instead. * * @param element the element to remove one occurrence of * @return {@code true} if an occurrence was found and removed */ @CanIgnoreReturnValue @Override boolean remove(@CheckForNull Object element); /** * Adds or removes the necessary occurrences of an element such that the element attains the * desired count. * * @param element the element to add or remove occurrences of; may be null only if explicitly * allowed by the implementation * @param count the desired count of the element in this multiset * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code count} is negative * @throws NullPointerException if {@code element} is null and this implementation does not permit * null elements. Note that if {@code count} is zero, the implementor may optionally return * zero instead. */ @CanIgnoreReturnValue int setCount(@ParametricNullness E element, int count); /** * Conditionally sets the count of an element to a new value, as described in {@link * #setCount(Object, int)}, provided that the element has the expected current count. If the * current count is not {@code oldCount}, no change is made. * * @param element the element to conditionally set the count of; may be null only if explicitly * allowed by the implementation * @param oldCount the expected present count of the element in this multiset * @param newCount the desired count of the element in this multiset * @return {@code true} if the condition for modification was met. This implies that the multiset * was indeed modified, unless {@code oldCount == newCount}. * @throws IllegalArgumentException if {@code oldCount} or {@code newCount} is negative * @throws NullPointerException if {@code element} is null and the implementation does not permit * null elements. Note that if {@code oldCount} and {@code newCount} are both zero, the * implementor may optionally return {@code true} instead. */ @CanIgnoreReturnValue boolean setCount(@ParametricNullness E element, int oldCount, int newCount); // Views /** * Returns the set of distinct elements contained in this multiset. The element set is backed by * the same data as the multiset, so any change to either is immediately reflected in the other. * The order of the elements in the element set is unspecified. * * <p>If the element set supports any removal operations, these necessarily cause <b>all</b> * occurrences of the removed element(s) to be removed from the multiset. Implementations are not * expected to support the add operations, although this is possible. * * <p>A common use for the element set is to find the number of distinct elements in the multiset: * {@code elementSet().size()}. * * @return a view of the set of distinct elements in this multiset */ Set<E> elementSet(); /** * Returns a view of the contents of this multiset, grouped into {@code Multiset.Entry} instances, * each providing an element of the multiset and the count of that element. This set contains * exactly one entry for each distinct element in the multiset (thus it always has the same size * as the {@link #elementSet}). The order of the elements in the element set is unspecified. * * <p>The entry set is backed by the same data as the multiset, so any change to either is * immediately reflected in the other. However, multiset changes may or may not be reflected in * any {@code Entry} instances already retrieved from the entry set (this is * implementation-dependent). Furthermore, implementations are not required to support * modifications to the entry set at all, and the {@code Entry} instances themselves don't even * have methods for modification. See the specific implementation class for more details on how * its entry set handles modifications. * * @return a set of entries representing the data of this multiset */ Set<Entry<E>> entrySet(); /** * An unmodifiable element-count pair for a multiset. The {@link Multiset#entrySet} method returns * a view of the multiset whose elements are of this class. A multiset implementation may return * Entry instances that are either live "read-through" views to the Multiset, or immutable * snapshots. Note that this type is unrelated to the similarly-named type {@code Map.Entry}. * * @since 2.0 */ interface Entry<E extends @Nullable Object> { /** * Returns the multiset element corresponding to this entry. Multiple calls to this method * always return the same instance. * * @return the element corresponding to this entry */ @ParametricNullness E getElement(); /** * Returns the count of the associated element in the underlying multiset. This count may either * be an unchanging snapshot of the count at the time the entry was retrieved, or a live view of * the current count of the element in the multiset, depending on the implementation. Note that * in the former case, this method can never return zero, while in the latter, it will return * zero if all occurrences of the element were since removed from the multiset. * * @return the count of the element; never negative */ int getCount(); /** * {@inheritDoc} * * <p>Returns {@code true} if the given object is also a multiset entry and the two entries * represent the same element and count. That is, two entries {@code a} and {@code b} are equal * if: * * <pre>{@code * Objects.equal(a.getElement(), b.getElement()) * && a.getCount() == b.getCount() * }</pre> */ @Override // TODO(kevinb): check this wrt TreeMultiset? boolean equals(@CheckForNull Object o); /** * {@inheritDoc} * * <p>The hash code of a multiset entry for element {@code element} and count {@code count} is * defined as: * * <pre>{@code * ((element == null) ? 0 : element.hashCode()) ^ count * }</pre> */ @Override int hashCode(); /** * Returns the canonical string representation of this entry, defined as follows. If the count * for this entry is one, this is simply the string representation of the corresponding element. * Otherwise, it is the string representation of the element, followed by the three characters * {@code " x "} (space, letter x, space), followed by the count. */ @Override String toString(); } /** * Runs the specified action for each distinct element in this multiset, and the number of * occurrences of that element. For some {@code Multiset} implementations, this may be more * efficient than iterating over the {@link #entrySet()} either explicitly or with {@code * entrySet().forEach(action)}. * * @since 21.0 */ default void forEachEntry(ObjIntConsumer<? super E> action) { checkNotNull(action); entrySet().forEach(entry -> action.accept(entry.getElement(), entry.getCount())); } // Comparison and hashing /** * Compares the specified object with this multiset for equality. Returns {@code true} if the * given object is also a multiset and contains equal elements with equal counts, regardless of * order. */ @Override // TODO(kevinb): caveats about equivalence-relation? boolean equals(@CheckForNull Object object); /** * Returns the hash code for this multiset. This is defined as the sum of * * <pre>{@code * ((element == null) ? 0 : element.hashCode()) ^ count(element) * }</pre> * * <p>over all distinct elements in the multiset. It follows that a multiset and its entry set * always have the same hash code. */ @Override int hashCode(); /** * {@inheritDoc} * * <p>It is recommended, though not mandatory, that this method return the result of invoking * {@link #toString} on the {@link #entrySet}, yielding a result such as {@code [a x 3, c, d x 2, * e]}. */ @Override String toString(); // Refined Collection Methods /** * {@inheritDoc} * * <p>Elements that occur multiple times in the multiset will appear multiple times in this * iterator, though not necessarily sequentially. */ @Override Iterator<E> iterator(); /** * Determines whether this multiset contains the specified element. * * <p>This method refines {@link Collection#contains} to further specify that it <b>may not</b> * throw an exception in response to {@code element} being null or of the wrong type. * * @param element the element to check for * @return {@code true} if this multiset contains at least one occurrence of the element */ @Override boolean contains(@CheckForNull Object element); /** * Returns {@code true} if this multiset contains at least one occurrence of each element in the * specified collection. * * <p>This method refines {@link Collection#containsAll} to further specify that it <b>may not</b> * throw an exception in response to any of {@code elements} being null or of the wrong type. * * <p><b>Note:</b> this method does not take into account the occurrence count of an element in * the two collections; it may still return {@code true} even if {@code elements} contains several * occurrences of an element and this multiset contains only one. This is no different than any * other collection type like {@link List}, but it may be unexpected to the user of a multiset. * * @param elements the collection of elements to be checked for containment in this multiset * @return {@code true} if this multiset contains at least one occurrence of each element * contained in {@code elements} * @throws NullPointerException if {@code elements} is null */ @Override boolean containsAll(Collection<?> elements); /** * {@inheritDoc} * * <p><b>Note:</b> This method ignores how often any element might appear in {@code c}, and only * cares whether or not an element appears at all. If you wish to remove one occurrence in this * multiset for every occurrence in {@code c}, see {@link Multisets#removeOccurrences(Multiset, * Multiset)}. * * <p>This method refines {@link Collection#removeAll} to further specify that it <b>may not</b> * throw an exception in response to any of {@code elements} being null or of the wrong type. */ @CanIgnoreReturnValue @Override boolean removeAll(Collection<?> c); /** * {@inheritDoc} * * <p><b>Note:</b> This method ignores how often any element might appear in {@code c}, and only * cares whether or not an element appears at all. If you wish to remove one occurrence in this * multiset for every occurrence in {@code c}, see {@link Multisets#retainOccurrences(Multiset, * Multiset)}. * * <p>This method refines {@link Collection#retainAll} to further specify that it <b>may not</b> * throw an exception in response to any of {@code elements} being null or of the wrong type. * * @see Multisets#retainOccurrences(Multiset, Multiset) */ @CanIgnoreReturnValue @Override boolean retainAll(Collection<?> c); /** * {@inheritDoc} * * <p>Elements that occur multiple times in the multiset will be passed to the {@code Consumer} * correspondingly many times, though not necessarily sequentially. */ @Override default void forEach(Consumer<? super E> action) { checkNotNull(action); entrySet() .forEach( entry -> { E elem = entry.getElement(); int count = entry.getCount(); for (int i = 0; i < count; i++) { action.accept(elem); } }); } @Override default Spliterator<E> spliterator() { return Multisets.spliteratorImpl(this); } }
google/guava
guava/src/com/google/common/collect/Multiset.java
224
/* * 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
225
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtIncompatible; import com.google.errorprone.annotations.DoNotMock; import java.util.NoSuchElementException; import java.util.Set; import javax.annotation.CheckForNull; /** * A set comprising zero or more {@linkplain Range#isEmpty nonempty}, {@linkplain * Range#isConnected(Range) disconnected} ranges of type {@code C}. * * <p>Implementations that choose to support the {@link #add(Range)} operation are required to * ignore empty ranges and coalesce connected ranges. For example: * * <pre>{@code * RangeSet<Integer> rangeSet = TreeRangeSet.create(); * rangeSet.add(Range.closed(1, 10)); // {[1, 10]} * rangeSet.add(Range.closedOpen(11, 15)); // disconnected range; {[1, 10], [11, 15)} * rangeSet.add(Range.closedOpen(15, 20)); // connected range; {[1, 10], [11, 20)} * rangeSet.add(Range.openClosed(0, 0)); // empty range; {[1, 10], [11, 20)} * rangeSet.remove(Range.open(5, 10)); // splits [1, 10]; {[1, 5], [10, 10], [11, 20)} * }</pre> * * <p>Note that the behavior of {@link Range#isEmpty()} and {@link Range#isConnected(Range)} may not * be as expected on discrete ranges. See the Javadoc of those methods for details. * * <p>For a {@link Set} whose contents are specified by a {@link Range}, see {@link ContiguousSet}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#rangeset">RangeSets</a>. * * @author Kevin Bourrillion * @author Louis Wasserman * @since 14.0 */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 @DoNotMock("Use ImmutableRangeSet or TreeRangeSet") @GwtIncompatible @ElementTypesAreNonnullByDefault public interface RangeSet<C extends Comparable> { // Query methods /** Determines whether any of this range set's member ranges contains {@code value}. */ boolean contains(C value); /** * Returns the unique range from this range set that {@linkplain Range#contains contains} {@code * value}, or {@code null} if this range set does not contain {@code value}. */ @CheckForNull Range<C> rangeContaining(C value); /** * Returns {@code true} if there exists a non-empty range enclosed by both a member range in this * range set and the specified range. This is equivalent to calling {@code * subRangeSet(otherRange)} and testing whether the resulting range set is non-empty. * * @since 20.0 */ boolean intersects(Range<C> otherRange); /** * Returns {@code true} if there exists a member range in this range set which {@linkplain * Range#encloses encloses} the specified range. */ boolean encloses(Range<C> otherRange); /** * Returns {@code true} if for each member range in {@code other} there exists a member range in * this range set which {@linkplain Range#encloses encloses} it. It follows that {@code * this.contains(value)} whenever {@code other.contains(value)}. Returns {@code true} if {@code * other} is empty. * * <p>This is equivalent to checking if this range set {@link #encloses} each of the ranges in * {@code other}. */ boolean enclosesAll(RangeSet<C> other); /** * Returns {@code true} if for each range in {@code other} there exists a member range in this * range set which {@linkplain Range#encloses encloses} it. Returns {@code true} if {@code other} * is empty. * * <p>This is equivalent to checking if this range set {@link #encloses} each range in {@code * other}. * * @since 21.0 */ boolean enclosesAll(Iterable<Range<C>> other); /** Returns {@code true} if this range set contains no ranges. */ boolean isEmpty(); /** * Returns the minimal range which {@linkplain Range#encloses(Range) encloses} all ranges in this * range set. * * @throws NoSuchElementException if this range set is {@linkplain #isEmpty() empty} */ Range<C> span(); // Views /** * Returns a view of the {@linkplain Range#isConnected disconnected} ranges that make up this * range set. The returned set may be empty. The iterators returned by its {@link * Iterable#iterator} method return the ranges in increasing order of lower bound (equivalently, * of upper bound). */ Set<Range<C>> asRanges(); /** * Returns a descending view of the {@linkplain Range#isConnected disconnected} ranges that make * up this range set. The returned set may be empty. The iterators returned by its {@link * Iterable#iterator} method return the ranges in decreasing order of lower bound (equivalently, * of upper bound). * * @since 19.0 */ Set<Range<C>> asDescendingSetOfRanges(); /** * Returns a view of the complement of this {@code RangeSet}. * * <p>The returned view supports the {@link #add} operation if this {@code RangeSet} supports * {@link #remove}, and vice versa. */ RangeSet<C> complement(); /** * Returns a view of the intersection of this {@code RangeSet} with the specified range. * * <p>The returned view supports all optional operations supported by this {@code RangeSet}, with * the caveat that an {@link IllegalArgumentException} is thrown on an attempt to {@linkplain * #add(Range) add} any range not {@linkplain Range#encloses(Range) enclosed} by {@code view}. */ RangeSet<C> subRangeSet(Range<C> view); // Modification /** * Adds the specified range to this {@code RangeSet} (optional operation). That is, for equal * range sets a and b, the result of {@code a.add(range)} is that {@code a} will be the minimal * range set for which both {@code a.enclosesAll(b)} and {@code a.encloses(range)}. * * <p>Note that {@code range} will be {@linkplain Range#span(Range) coalesced} with any ranges in * the range set that are {@linkplain Range#isConnected(Range) connected} with it. Moreover, if * {@code range} is empty, this is a no-op. * * @throws UnsupportedOperationException if this range set does not support the {@code add} * operation */ void add(Range<C> range); /** * Removes the specified range from this {@code RangeSet} (optional operation). After this * operation, if {@code range.contains(c)}, {@code this.contains(c)} will return {@code false}. * * <p>If {@code range} is empty, this is a no-op. * * @throws UnsupportedOperationException if this range set does not support the {@code remove} * operation */ void remove(Range<C> range); /** * Removes all ranges from this {@code RangeSet} (optional operation). After this operation, * {@code this.contains(c)} will return false for all {@code c}. * * <p>This is equivalent to {@code remove(Range.all())}. * * @throws UnsupportedOperationException if this range set does not support the {@code clear} * operation */ void clear(); /** * Adds all of the ranges from the specified range set to this range set (optional operation). * After this operation, this range set is the minimal range set that {@linkplain * #enclosesAll(RangeSet) encloses} both the original range set and {@code other}. * * <p>This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn. * * @throws UnsupportedOperationException if this range set does not support the {@code addAll} * operation */ void addAll(RangeSet<C> other); /** * Adds all of the specified ranges to this range set (optional operation). After this operation, * this range set is the minimal range set that {@linkplain #enclosesAll(RangeSet) encloses} both * the original range set and each range in {@code other}. * * <p>This is equivalent to calling {@link #add} on each of the ranges in {@code other} in turn. * * @throws UnsupportedOperationException if this range set does not support the {@code addAll} * operation * @since 21.0 */ void addAll(Iterable<Range<C>> ranges); /** * Removes all of the ranges from the specified range set from this range set (optional * operation). After this operation, if {@code other.contains(c)}, {@code this.contains(c)} will * return {@code false}. * * <p>This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in * turn. * * @throws UnsupportedOperationException if this range set does not support the {@code removeAll} * operation */ void removeAll(RangeSet<C> other); /** * Removes all of the specified ranges from this range set (optional operation). * * <p>This is equivalent to calling {@link #remove} on each of the ranges in {@code other} in * turn. * * @throws UnsupportedOperationException if this range set does not support the {@code removeAll} * operation * @since 21.0 */ void removeAll(Iterable<Range<C>> ranges); // Object methods /** * Returns {@code true} if {@code obj} is another {@code RangeSet} that contains the same ranges * according to {@link Range#equals(Object)}. */ @Override boolean equals(@CheckForNull Object obj); /** Returns {@code asRanges().hashCode()}. */ @Override int hashCode(); /** * Returns a readable string representation of this range set. For example, if this {@code * RangeSet} consisted of {@code Range.closed(1, 3)} and {@code Range.greaterThan(4)}, this might * return {@code " [1..3](4..+∞)}"}. */ @Override String toString(); }
google/guava
android/guava/src/com/google/common/collect/RangeSet.java
226
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.CompatibleWith; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A collection that supports order-independent equality, like {@link Set}, but may have duplicate * elements. A multiset is also sometimes called a <i>bag</i>. * * <p>Elements of a multiset that are equal to one another are referred to as <i>occurrences</i> of * the same single element. The total number of occurrences of an element in a multiset is called * the <i>count</i> of that element (the terms "frequency" and "multiplicity" are equivalent, but * not used in this API). Since the count of an element is represented as an {@code int}, a multiset * may never contain more than {@link Integer#MAX_VALUE} occurrences of any one element. * * <p>{@code Multiset} refines the specifications of several methods from {@code Collection}. It * also defines an additional query operation, {@link #count}, which returns the count of an * element. There are five new bulk-modification operations, for example {@link #add(Object, int)}, * to add or remove multiple occurrences of an element at once, or to set the count of an element to * a specific value. These modification operations are optional, but implementations which support * the standard collection operations {@link #add(Object)} or {@link #remove(Object)} are encouraged * to implement the related methods as well. Finally, two collection views are provided: {@link * #elementSet} contains the distinct elements of the multiset "with duplicates collapsed", and * {@link #entrySet} is similar but contains {@link Entry Multiset.Entry} instances, each providing * both a distinct element and the count of that element. * * <p>In addition to these required methods, implementations of {@code Multiset} are expected to * provide two {@code static} creation methods: {@code create()}, returning an empty multiset, and * {@code create(Iterable<? extends E>)}, returning a multiset containing the given initial * elements. This is simply a refinement of {@code Collection}'s constructor recommendations, * reflecting the new developments of Java 5. * * <p>As with other collection types, the modification operations are optional, and should throw * {@link UnsupportedOperationException} when they are not implemented. Most implementations should * support either all add operations or none of them, all removal operations or none of them, and if * and only if all of these are supported, the {@code setCount} methods as well. * * <p>A multiset uses {@link Object#equals} to determine whether two instances should be considered * "the same," <i>unless specified otherwise</i> by the implementation. * * <p><b>Warning:</b> as with normal {@link Set}s, it is almost always a bad idea to modify an * element (in a way that affects its {@link Object#equals} behavior) while it is contained in a * multiset. Undefined behavior and bugs will result. * * <h3>Implementations</h3> * * <ul> * <li>{@link ImmutableMultiset} * <li>{@link ImmutableSortedMultiset} * <li>{@link HashMultiset} * <li>{@link LinkedHashMultiset} * <li>{@link TreeMultiset} * <li>{@link EnumMultiset} * <li>{@link ConcurrentHashMultiset} * </ul> * * <p>If your values may be zero, negative, or outside the range of an int, you may wish to use * {@link com.google.common.util.concurrent.AtomicLongMap} instead. Note, however, that unlike * {@code Multiset}, {@code AtomicLongMap} does not automatically remove zeros. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multiset">{@code Multiset}</a>. * * @author Kevin Bourrillion * @since 2.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public interface Multiset<E extends @Nullable Object> extends Collection<E> { // Query Operations /** * Returns the total number of all occurrences of all elements in this multiset. * * <p><b>Note:</b> this method does not return the number of <i>distinct elements</i> in the * multiset, which is given by {@code entrySet().size()}. */ @Override int size(); /** * Returns the number of occurrences of an element in this multiset (the <i>count</i> of the * element). Note that for an {@link Object#equals}-based multiset, this gives the same result as * {@link Collections#frequency} (which would presumably perform more poorly). * * <p><b>Note:</b> the utility method {@link Iterables#frequency} generalizes this operation; it * correctly delegates to this method when dealing with a multiset, but it can also accept any * other iterable type. * * @param element the element to count occurrences of * @return the number of occurrences of the element in this multiset; possibly zero but never * negative */ int count(@CompatibleWith("E") @CheckForNull Object element); // Bulk Operations /** * Adds a number of occurrences of an element to this multiset. Note that if {@code occurrences == * 1}, this method has the identical effect to {@link #add(Object)}. This method is functionally * equivalent (except in the case of overflow) to the call {@code * addAll(Collections.nCopies(element, occurrences))}, which would presumably perform much more * poorly. * * @param element the element to add occurrences of; may be null only if explicitly allowed by the * implementation * @param occurrences the number of occurrences of the element to add. May be zero, in which case * no change will be made. * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code occurrences} is negative, or if this operation would * result in more than {@link Integer#MAX_VALUE} occurrences of the element * @throws NullPointerException if {@code element} is null and this implementation does not permit * null elements. Note that if {@code occurrences} is zero, the implementation may opt to * return normally. */ @CanIgnoreReturnValue int add(@ParametricNullness E element, int occurrences); /** * Adds a single occurrence of the specified element to this multiset. * * <p>This method refines {@link Collection#add}, which only <i>ensures</i> the presence of the * element, to further specify that a successful call must always increment the count of the * element, and the overall size of the collection, by one. * * <p>To both add the element and obtain the previous count of that element, use {@link * #add(Object, int) add}{@code (element, 1)} instead. * * @param element the element to add one occurrence of; may be null only if explicitly allowed by * the implementation * @return {@code true} always, since this call is required to modify the multiset, unlike other * {@link Collection} types * @throws NullPointerException if {@code element} is null and this implementation does not permit * null elements * @throws IllegalArgumentException if {@link Integer#MAX_VALUE} occurrences of {@code element} * are already contained in this multiset */ @CanIgnoreReturnValue @Override boolean add(@ParametricNullness E element); /** * Removes a number of occurrences of the specified element from this multiset. If the multiset * contains fewer than this number of occurrences to begin with, all occurrences will be removed. * Note that if {@code occurrences == 1}, this is functionally equivalent to the call {@code * remove(element)}. * * @param element the element to conditionally remove occurrences of * @param occurrences the number of occurrences of the element to remove. May be zero, in which * case no change will be made. * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code occurrences} is negative */ @CanIgnoreReturnValue int remove(@CompatibleWith("E") @CheckForNull Object element, int occurrences); /** * Removes a <i>single</i> occurrence of the specified element from this multiset, if present. * * <p>This method refines {@link Collection#remove} to further specify that it <b>may not</b> * throw an exception in response to {@code element} being null or of the wrong type. * * <p>To both remove the element and obtain the previous count of that element, use {@link * #remove(Object, int) remove}{@code (element, 1)} instead. * * @param element the element to remove one occurrence of * @return {@code true} if an occurrence was found and removed */ @CanIgnoreReturnValue @Override boolean remove(@CheckForNull Object element); /** * Adds or removes the necessary occurrences of an element such that the element attains the * desired count. * * @param element the element to add or remove occurrences of; may be null only if explicitly * allowed by the implementation * @param count the desired count of the element in this multiset * @return the count of the element before the operation; possibly zero * @throws IllegalArgumentException if {@code count} is negative * @throws NullPointerException if {@code element} is null and this implementation does not permit * null elements. Note that if {@code count} is zero, the implementor may optionally return * zero instead. */ @CanIgnoreReturnValue int setCount(@ParametricNullness E element, int count); /** * Conditionally sets the count of an element to a new value, as described in {@link * #setCount(Object, int)}, provided that the element has the expected current count. If the * current count is not {@code oldCount}, no change is made. * * @param element the element to conditionally set the count of; may be null only if explicitly * allowed by the implementation * @param oldCount the expected present count of the element in this multiset * @param newCount the desired count of the element in this multiset * @return {@code true} if the condition for modification was met. This implies that the multiset * was indeed modified, unless {@code oldCount == newCount}. * @throws IllegalArgumentException if {@code oldCount} or {@code newCount} is negative * @throws NullPointerException if {@code element} is null and the implementation does not permit * null elements. Note that if {@code oldCount} and {@code newCount} are both zero, the * implementor may optionally return {@code true} instead. */ @CanIgnoreReturnValue boolean setCount(@ParametricNullness E element, int oldCount, int newCount); // Views /** * Returns the set of distinct elements contained in this multiset. The element set is backed by * the same data as the multiset, so any change to either is immediately reflected in the other. * The order of the elements in the element set is unspecified. * * <p>If the element set supports any removal operations, these necessarily cause <b>all</b> * occurrences of the removed element(s) to be removed from the multiset. Implementations are not * expected to support the add operations, although this is possible. * * <p>A common use for the element set is to find the number of distinct elements in the multiset: * {@code elementSet().size()}. * * @return a view of the set of distinct elements in this multiset */ Set<E> elementSet(); /** * Returns a view of the contents of this multiset, grouped into {@code Multiset.Entry} instances, * each providing an element of the multiset and the count of that element. This set contains * exactly one entry for each distinct element in the multiset (thus it always has the same size * as the {@link #elementSet}). The order of the elements in the element set is unspecified. * * <p>The entry set is backed by the same data as the multiset, so any change to either is * immediately reflected in the other. However, multiset changes may or may not be reflected in * any {@code Entry} instances already retrieved from the entry set (this is * implementation-dependent). Furthermore, implementations are not required to support * modifications to the entry set at all, and the {@code Entry} instances themselves don't even * have methods for modification. See the specific implementation class for more details on how * its entry set handles modifications. * * @return a set of entries representing the data of this multiset */ Set<Entry<E>> entrySet(); /** * An unmodifiable element-count pair for a multiset. The {@link Multiset#entrySet} method returns * a view of the multiset whose elements are of this class. A multiset implementation may return * Entry instances that are either live "read-through" views to the Multiset, or immutable * snapshots. Note that this type is unrelated to the similarly-named type {@code Map.Entry}. * * @since 2.0 */ interface Entry<E extends @Nullable Object> { /** * Returns the multiset element corresponding to this entry. Multiple calls to this method * always return the same instance. * * @return the element corresponding to this entry */ @ParametricNullness E getElement(); /** * Returns the count of the associated element in the underlying multiset. This count may either * be an unchanging snapshot of the count at the time the entry was retrieved, or a live view of * the current count of the element in the multiset, depending on the implementation. Note that * in the former case, this method can never return zero, while in the latter, it will return * zero if all occurrences of the element were since removed from the multiset. * * @return the count of the element; never negative */ int getCount(); /** * {@inheritDoc} * * <p>Returns {@code true} if the given object is also a multiset entry and the two entries * represent the same element and count. That is, two entries {@code a} and {@code b} are equal * if: * * <pre>{@code * Objects.equal(a.getElement(), b.getElement()) * && a.getCount() == b.getCount() * }</pre> */ @Override // TODO(kevinb): check this wrt TreeMultiset? boolean equals(@CheckForNull Object o); /** * {@inheritDoc} * * <p>The hash code of a multiset entry for element {@code element} and count {@code count} is * defined as: * * <pre>{@code * ((element == null) ? 0 : element.hashCode()) ^ count * }</pre> */ @Override int hashCode(); /** * Returns the canonical string representation of this entry, defined as follows. If the count * for this entry is one, this is simply the string representation of the corresponding element. * Otherwise, it is the string representation of the element, followed by the three characters * {@code " x "} (space, letter x, space), followed by the count. */ @Override String toString(); } // Comparison and hashing /** * Compares the specified object with this multiset for equality. Returns {@code true} if the * given object is also a multiset and contains equal elements with equal counts, regardless of * order. */ @Override // TODO(kevinb): caveats about equivalence-relation? boolean equals(@CheckForNull Object object); /** * Returns the hash code for this multiset. This is defined as the sum of * * <pre>{@code * ((element == null) ? 0 : element.hashCode()) ^ count(element) * }</pre> * * <p>over all distinct elements in the multiset. It follows that a multiset and its entry set * always have the same hash code. */ @Override int hashCode(); /** * {@inheritDoc} * * <p>It is recommended, though not mandatory, that this method return the result of invoking * {@link #toString} on the {@link #entrySet}, yielding a result such as {@code [a x 3, c, d x 2, * e]}. */ @Override String toString(); // Refined Collection Methods /** * {@inheritDoc} * * <p>Elements that occur multiple times in the multiset will appear multiple times in this * iterator, though not necessarily sequentially. */ @Override Iterator<E> iterator(); /** * Determines whether this multiset contains the specified element. * * <p>This method refines {@link Collection#contains} to further specify that it <b>may not</b> * throw an exception in response to {@code element} being null or of the wrong type. * * @param element the element to check for * @return {@code true} if this multiset contains at least one occurrence of the element */ @Override boolean contains(@CheckForNull Object element); /** * Returns {@code true} if this multiset contains at least one occurrence of each element in the * specified collection. * * <p>This method refines {@link Collection#containsAll} to further specify that it <b>may not</b> * throw an exception in response to any of {@code elements} being null or of the wrong type. * * <p><b>Note:</b> this method does not take into account the occurrence count of an element in * the two collections; it may still return {@code true} even if {@code elements} contains several * occurrences of an element and this multiset contains only one. This is no different than any * other collection type like {@link List}, but it may be unexpected to the user of a multiset. * * @param elements the collection of elements to be checked for containment in this multiset * @return {@code true} if this multiset contains at least one occurrence of each element * contained in {@code elements} * @throws NullPointerException if {@code elements} is null */ @Override boolean containsAll(Collection<?> elements); /** * {@inheritDoc} * * <p><b>Note:</b> This method ignores how often any element might appear in {@code c}, and only * cares whether or not an element appears at all. If you wish to remove one occurrence in this * multiset for every occurrence in {@code c}, see {@link Multisets#removeOccurrences(Multiset, * Multiset)}. * * <p>This method refines {@link Collection#removeAll} to further specify that it <b>may not</b> * throw an exception in response to any of {@code elements} being null or of the wrong type. */ @CanIgnoreReturnValue @Override boolean removeAll(Collection<?> c); /** * {@inheritDoc} * * <p><b>Note:</b> This method ignores how often any element might appear in {@code c}, and only * cares whether or not an element appears at all. If you wish to remove one occurrence in this * multiset for every occurrence in {@code c}, see {@link Multisets#retainOccurrences(Multiset, * Multiset)}. * * <p>This method refines {@link Collection#retainAll} to further specify that it <b>may not</b> * throw an exception in response to any of {@code elements} being null or of the wrong type. * * @see Multisets#retainOccurrences(Multiset, Multiset) */ @CanIgnoreReturnValue @Override boolean retainAll(Collection<?> c); }
google/guava
android/guava/src/com/google/common/collect/Multiset.java
227
/* * 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.checkRemove; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Function; import com.google.common.base.Optional; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Collection; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.NoSuchElementException; import java.util.Queue; import java.util.RandomAccess; import java.util.Set; import java.util.Spliterator; import java.util.function.Consumer; import java.util.stream.Stream; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.NonNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * An assortment of mainly legacy static utility methods that operate on or return objects of type * {@code Iterable}. Except as noted, each method has a corresponding {@link Iterator}-based method * in the {@link Iterators} class. * * <p><b>Java 8+ users:</b> several common uses for this class are now more comprehensively * addressed by the new {@link java.util.stream.Stream} library. Read the method documentation below * for comparisons. This class is not being deprecated, but we gently encourage you to migrate to * streams. * * <p><i>Performance notes:</i> Unless otherwise noted, all of the iterables produced in this class * are <i>lazy</i>, which means that their iterators only advance the backing iteration when * absolutely necessary. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#iterables">{@code * Iterables}</a>. * * @author Kevin Bourrillion * @author Jared Levy * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Iterables { private Iterables() {} /** Returns an unmodifiable view of {@code iterable}. */ public static <T extends @Nullable Object> Iterable<T> unmodifiableIterable( final Iterable<? extends T> iterable) { checkNotNull(iterable); if (iterable instanceof UnmodifiableIterable || iterable instanceof ImmutableCollection) { @SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe Iterable<T> result = (Iterable<T>) iterable; return result; } return new UnmodifiableIterable<>(iterable); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <E> Iterable<E> unmodifiableIterable(ImmutableCollection<E> iterable) { return checkNotNull(iterable); } private static final class UnmodifiableIterable<T extends @Nullable Object> extends FluentIterable<T> { private final Iterable<? extends T> iterable; private UnmodifiableIterable(Iterable<? extends T> iterable) { this.iterable = iterable; } @Override public Iterator<T> iterator() { return Iterators.unmodifiableIterator(iterable.iterator()); } @Override public void forEach(Consumer<? super T> action) { iterable.forEach(action); } @SuppressWarnings("unchecked") // safe upcast, assuming no one has a crazy Spliterator subclass @Override public Spliterator<T> spliterator() { return (Spliterator<T>) iterable.spliterator(); } @Override public String toString() { return iterable.toString(); } // no equals and hashCode; it would break the contract! } /** Returns the number of elements in {@code iterable}. */ public static int size(Iterable<?> iterable) { return (iterable instanceof Collection) ? ((Collection<?>) iterable).size() : Iterators.size(iterable.iterator()); } /** * Returns {@code true} if {@code iterable} contains any element {@code o} for which {@code * Objects.equals(o, element)} would return {@code true}. Otherwise returns {@code false}, even in * cases where {@link Collection#contains} might throw {@link NullPointerException} or {@link * ClassCastException}. */ // <? extends @Nullable Object> instead of <?> because of Kotlin b/189937072, discussed in Joiner. public static boolean contains( Iterable<? extends @Nullable Object> iterable, @CheckForNull Object element) { if (iterable instanceof Collection) { Collection<?> collection = (Collection<?>) iterable; return Collections2.safeContains(collection, element); } return Iterators.contains(iterable.iterator(), element); } /** * Removes, from an iterable, every element that belongs to the provided collection. * * <p>This method calls {@link Collection#removeAll} if {@code iterable} is a collection, and * {@link Iterators#removeAll} otherwise. * * @param removeFrom the iterable to (potentially) remove elements from * @param elementsToRemove the elements to remove * @return {@code true} if any element was removed from {@code iterable} */ @CanIgnoreReturnValue public static boolean removeAll(Iterable<?> removeFrom, Collection<?> elementsToRemove) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).removeAll(checkNotNull(elementsToRemove)) : Iterators.removeAll(removeFrom.iterator(), elementsToRemove); } /** * Removes, from an iterable, every element that does not belong to the provided collection. * * <p>This method calls {@link Collection#retainAll} if {@code iterable} is a collection, and * {@link Iterators#retainAll} otherwise. * * @param removeFrom the iterable to (potentially) remove elements from * @param elementsToRetain the elements to retain * @return {@code true} if any element was removed from {@code iterable} */ @CanIgnoreReturnValue public static boolean retainAll(Iterable<?> removeFrom, Collection<?> elementsToRetain) { return (removeFrom instanceof Collection) ? ((Collection<?>) removeFrom).retainAll(checkNotNull(elementsToRetain)) : Iterators.retainAll(removeFrom.iterator(), elementsToRetain); } /** * Removes, from an iterable, every element that satisfies the provided predicate. * * <p>Removals may or may not happen immediately as each element is tested against the predicate. * The behavior of this method is not specified if {@code predicate} is dependent on {@code * removeFrom}. * * <p><b>Java 8+ users:</b> if {@code removeFrom} is a {@link Collection}, use {@code * removeFrom.removeIf(predicate)} instead. * * @param removeFrom the iterable to (potentially) remove elements from * @param predicate a predicate that determines whether an element should be removed * @return {@code true} if any elements were removed from the iterable * @throws UnsupportedOperationException if the iterable does not support {@code remove()}. * @since 2.0 */ @CanIgnoreReturnValue public static <T extends @Nullable Object> boolean removeIf( Iterable<T> removeFrom, Predicate<? super T> predicate) { if (removeFrom instanceof Collection) { return ((Collection<T>) removeFrom).removeIf(predicate); } return Iterators.removeIf(removeFrom.iterator(), predicate); } /** Removes and returns the first matching element, or returns {@code null} if there is none. */ @CheckForNull static <T extends @Nullable Object> T removeFirstMatching( Iterable<T> removeFrom, Predicate<? super T> predicate) { checkNotNull(predicate); Iterator<T> iterator = removeFrom.iterator(); while (iterator.hasNext()) { T next = iterator.next(); if (predicate.apply(next)) { iterator.remove(); return next; } } return null; } /** * Determines whether two iterables contain equal elements in the same order. More specifically, * this method returns {@code true} if {@code iterable1} and {@code iterable2} contain the same * number of elements and every element of {@code iterable1} is equal to the corresponding element * of {@code iterable2}. */ public static boolean elementsEqual(Iterable<?> iterable1, Iterable<?> iterable2) { if (iterable1 instanceof Collection && iterable2 instanceof Collection) { Collection<?> collection1 = (Collection<?>) iterable1; Collection<?> collection2 = (Collection<?>) iterable2; if (collection1.size() != collection2.size()) { return false; } } return Iterators.elementsEqual(iterable1.iterator(), iterable2.iterator()); } /** * Returns a string representation of {@code iterable}, with the format {@code [e1, e2, ..., en]} * (that is, identical to {@link java.util.Arrays Arrays}{@code * .toString(Iterables.toArray(iterable))}). Note that for <i>most</i> implementations of {@link * Collection}, {@code collection.toString()} also gives the same result, but that behavior is not * generally guaranteed. */ public static String toString(Iterable<?> iterable) { return Iterators.toString(iterable.iterator()); } /** * Returns the single element contained in {@code iterable}. * * <p><b>Java 8+ users:</b> the {@code Stream} equivalent to this method is {@code * stream.collect(MoreCollectors.onlyElement())}. * * @throws NoSuchElementException if the iterable is empty * @throws IllegalArgumentException if the iterable contains multiple elements */ @ParametricNullness public static <T extends @Nullable Object> T getOnlyElement(Iterable<T> iterable) { return Iterators.getOnlyElement(iterable.iterator()); } /** * Returns the single element contained in {@code iterable}, or {@code defaultValue} if the * iterable is empty. * * <p><b>Java 8+ users:</b> the {@code Stream} equivalent to this method is {@code * stream.collect(MoreCollectors.toOptional()).orElse(defaultValue)}. * * @throws IllegalArgumentException if the iterator contains multiple elements */ @ParametricNullness public static <T extends @Nullable Object> T getOnlyElement( Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { return Iterators.getOnlyElement(iterable.iterator(), defaultValue); } /** * Copies an iterable's elements into an array. * * @param iterable the iterable to copy * @param type the type of the elements * @return a newly-allocated array into which all the elements of the iterable have been copied */ @GwtIncompatible // Array.newInstance(Class, int) public static <T extends @Nullable Object> T[] toArray( Iterable<? extends T> iterable, Class<@NonNull T> type) { return toArray(iterable, ObjectArrays.newArray(type, 0)); } static <T extends @Nullable Object> T[] toArray(Iterable<? extends T> iterable, T[] array) { Collection<? extends T> collection = castOrCopyToCollection(iterable); return collection.toArray(array); } /** * Copies an iterable's elements into an array. * * @param iterable the iterable to copy * @return a newly-allocated array into which all the elements of the iterable have been copied */ static @Nullable Object[] toArray(Iterable<?> iterable) { return castOrCopyToCollection(iterable).toArray(); } /** * Converts an iterable into a collection. If the iterable is already a collection, it is * returned. Otherwise, an {@link java.util.ArrayList} is created with the contents of the * iterable in the same iteration order. */ private static <E extends @Nullable Object> Collection<E> castOrCopyToCollection( Iterable<E> iterable) { return (iterable instanceof Collection) ? (Collection<E>) iterable : Lists.newArrayList(iterable.iterator()); } /** * Adds all elements in {@code iterable} to {@code collection}. * * @return {@code true} if {@code collection} was modified as a result of this operation. */ @CanIgnoreReturnValue public static <T extends @Nullable Object> boolean addAll( Collection<T> addTo, Iterable<? extends T> elementsToAdd) { if (elementsToAdd instanceof Collection) { Collection<? extends T> c = (Collection<? extends T>) elementsToAdd; return addTo.addAll(c); } return Iterators.addAll(addTo, checkNotNull(elementsToAdd).iterator()); } /** * Returns the number of elements in the specified iterable that equal the specified object. This * implementation avoids a full iteration when the iterable is a {@link Multiset} or {@link Set}. * * <p><b>Java 8+ users:</b> In most cases, the {@code Stream} equivalent of this method is {@code * stream.filter(element::equals).count()}. If {@code element} might be null, use {@code * stream.filter(Predicate.isEqual(element)).count()} instead. * * @see java.util.Collections#frequency(Collection, Object) Collections.frequency(Collection, * Object) */ public static int frequency(Iterable<?> iterable, @CheckForNull Object element) { if ((iterable instanceof Multiset)) { return ((Multiset<?>) iterable).count(element); } else if ((iterable instanceof Set)) { return ((Set<?>) iterable).contains(element) ? 1 : 0; } return Iterators.frequency(iterable.iterator(), element); } /** * Returns an iterable whose iterators cycle indefinitely over the elements of {@code iterable}. * * <p>That iterator supports {@code remove()} if {@code iterable.iterator()} does. After {@code * remove()} is called, subsequent cycles omit the removed element, which is no longer in {@code * iterable}. The iterator's {@code hasNext()} method returns {@code true} until {@code iterable} * is empty. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You * should use an explicit {@code break} or be certain that you will eventually remove all the * elements. * * <p>To cycle over the iterable {@code n} times, use the following: {@code * Iterables.concat(Collections.nCopies(n, iterable))} * * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code * Stream.generate(() -> iterable).flatMap(Streams::stream)}. */ public static <T extends @Nullable Object> Iterable<T> cycle(final Iterable<T> iterable) { checkNotNull(iterable); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.cycle(iterable); } @Override public Spliterator<T> spliterator() { return Stream.generate(() -> iterable).<T>flatMap(Streams::stream).spliterator(); } @Override public String toString() { return iterable.toString() + " (cycled)"; } }; } /** * Returns an iterable whose iterators cycle indefinitely over the provided elements. * * <p>After {@code remove} is invoked on a generated iterator, the removed element will no longer * appear in either that iterator or any other iterator created from the same source iterable. * That is, this method behaves exactly as {@code Iterables.cycle(Lists.newArrayList(elements))}. * The iterator's {@code hasNext} method returns {@code true} until all of the original elements * have been removed. * * <p><b>Warning:</b> Typical uses of the resulting iterator may produce an infinite loop. You * should use an explicit {@code break} or be certain that you will eventually remove all the * elements. * * <p>To cycle over the elements {@code n} times, use the following: {@code * Iterables.concat(Collections.nCopies(n, Arrays.asList(elements)))} * * <p><b>Java 8+ users:</b> If passing a single element {@code e}, the {@code Stream} equivalent * of this method is {@code Stream.generate(() -> e)}. Otherwise, put the elements in a collection * and use {@code Stream.generate(() -> collection).flatMap(Collection::stream)}. */ @SafeVarargs public static <T extends @Nullable Object> Iterable<T> cycle(T... elements) { return cycle(Lists.newArrayList(elements)); } /** * Combines two iterables into a single iterable. The returned iterable has an iterator that * traverses the elements in {@code a}, followed by the elements in {@code b}. The source * iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. * * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code * Stream.concat(a, b)}. */ public static <T extends @Nullable Object> Iterable<T> concat( Iterable<? extends T> a, Iterable<? extends T> b) { return FluentIterable.concat(a, b); } /** * Combines three iterables into a single iterable. The returned iterable has an iterator that * traverses the elements in {@code a}, followed by the elements in {@code b}, followed by the * elements in {@code c}. The source iterators are not polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. * * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code * Streams.concat(a, b, c)}. */ public static <T extends @Nullable Object> Iterable<T> concat( Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c) { return FluentIterable.concat(a, b, c); } /** * Combines four iterables into a single iterable. The returned iterable has an iterator that * traverses the elements in {@code a}, followed by the elements in {@code b}, followed by the * elements in {@code c}, followed by the elements in {@code d}. The source iterators are not * polled until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. * * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code * Streams.concat(a, b, c, d)}. */ public static <T extends @Nullable Object> Iterable<T> concat( Iterable<? extends T> a, Iterable<? extends T> b, Iterable<? extends T> c, Iterable<? extends T> d) { return FluentIterable.concat(a, b, c, d); } /** * Combines multiple iterables into a single iterable. The returned iterable has an iterator that * traverses the elements of each iterable in {@code inputs}. The input iterators are not polled * until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. * * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code * Streams.concat(...)}. * * @throws NullPointerException if any of the provided iterables is null */ @SafeVarargs public static <T extends @Nullable Object> Iterable<T> concat(Iterable<? extends T>... inputs) { return FluentIterable.concat(inputs); } /** * Combines multiple iterables into a single iterable. The returned iterable has an iterator that * traverses the elements of each iterable in {@code inputs}. The input iterators are not polled * until necessary. * * <p>The returned iterable's iterator supports {@code remove()} when the corresponding input * iterator supports it. The methods of the returned iterable may throw {@code * NullPointerException} if any of the input iterators is null. * * <p><b>Java 8+ users:</b> The {@code Stream} equivalent of this method is {@code * streamOfStreams.flatMap(s -> s)}. */ public static <T extends @Nullable Object> Iterable<T> concat( Iterable<? extends Iterable<? extends T>> inputs) { return FluentIterable.concat(inputs); } /** * Divides an iterable into unmodifiable sublists of the given size (the final iterable may be * smaller). For example, partitioning an iterable containing {@code [a, b, c, d, e]} with a * partition size of 3 yields {@code [[a, b, c], [d, e]]} -- an outer iterable containing two * inner lists of three and two elements, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link Iterator#remove()} * method. The returned lists implement {@link RandomAccess}, whether or not the input list does. * * <p><b>Note:</b> The current implementation eagerly allocates storage for {@code size} elements. * As a consequence, passing values like {@code Integer.MAX_VALUE} can lead to {@link * OutOfMemoryError}. * * <p><b>Note:</b> if {@code iterable} is a {@link List}, use {@link Lists#partition(List, int)} * instead. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition (the last may be smaller) * @return an iterable of unmodifiable lists containing the elements of {@code iterable} divided * into partitions * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T extends @Nullable Object> Iterable<List<T>> partition( final Iterable<T> iterable, final int size) { checkNotNull(iterable); checkArgument(size > 0); return new FluentIterable<List<T>>() { @Override public Iterator<List<T>> iterator() { return Iterators.partition(iterable.iterator(), size); } }; } /** * Divides an iterable into unmodifiable sublists of the given size, padding the final iterable * with null values if necessary. For example, partitioning an iterable containing {@code [a, b, * c, d, e]} with a partition size of 3 yields {@code [[a, b, c], [d, e, null]]} -- an outer * iterable containing two inner lists of three elements each, all in the original order. * * <p>Iterators returned by the returned iterable do not support the {@link Iterator#remove()} * method. * * @param iterable the iterable to return a partitioned view of * @param size the desired size of each partition * @return an iterable of unmodifiable lists containing the elements of {@code iterable} divided * into partitions (the final iterable may have trailing null elements) * @throws IllegalArgumentException if {@code size} is nonpositive */ public static <T extends @Nullable Object> Iterable<List<@Nullable T>> paddedPartition( final Iterable<T> iterable, final int size) { checkNotNull(iterable); checkArgument(size > 0); return new FluentIterable<List<@Nullable T>>() { @Override public Iterator<List<@Nullable T>> iterator() { return Iterators.paddedPartition(iterable.iterator(), size); } }; } /** * Returns a view of {@code unfiltered} containing all elements that satisfy the input predicate * {@code retainIfTrue}. The returned iterable's iterator does not support {@code remove()}. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#filter}. */ public static <T extends @Nullable Object> Iterable<T> filter( final Iterable<T> unfiltered, final Predicate<? super T> retainIfTrue) { checkNotNull(unfiltered); checkNotNull(retainIfTrue); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.filter(unfiltered.iterator(), retainIfTrue); } @Override public void forEach(Consumer<? super T> action) { checkNotNull(action); unfiltered.forEach( (@ParametricNullness T a) -> { if (retainIfTrue.test(a)) { action.accept(a); } }); } @Override public Spliterator<T> spliterator() { return CollectSpliterators.filter(unfiltered.spliterator(), retainIfTrue); } }; } /** * Returns a view of {@code unfiltered} containing all elements that are of the type {@code * desiredType}. The returned iterable's iterator does not support {@code remove()}. * * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(type::isInstance).map(type::cast)}. * This does perform a little more work than necessary, so another option is to insert an * unchecked cast at some later point: * * <pre> * {@code @SuppressWarnings("unchecked") // safe because of ::isInstance check * ImmutableList<NewType> result = * (ImmutableList) stream.filter(NewType.class::isInstance).collect(toImmutableList());} * </pre> */ @SuppressWarnings("unchecked") @GwtIncompatible // Class.isInstance public static <T> Iterable<T> filter(final Iterable<?> unfiltered, final Class<T> desiredType) { checkNotNull(unfiltered); checkNotNull(desiredType); return (Iterable<T>) filter(unfiltered, Predicates.instanceOf(desiredType)); } /** * Returns {@code true} if any element in {@code iterable} satisfies the predicate. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#anyMatch}. */ public static <T extends @Nullable Object> boolean any( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.any(iterable.iterator(), predicate); } /** * Returns {@code true} if every element in {@code iterable} satisfies the predicate. If {@code * iterable} is empty, {@code true} is returned. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#allMatch}. */ public static <T extends @Nullable Object> boolean all( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.all(iterable.iterator(), predicate); } /** * Returns the first element in {@code iterable} that satisfies the given predicate; use this * method only when such an element is known to exist. If it is possible that <i>no</i> element * will match, use {@link #tryFind} or {@link #find(Iterable, Predicate, Object)} instead. * * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst().get()} * * @throws NoSuchElementException if no element in {@code iterable} matches the given predicate */ @ParametricNullness public static <T extends @Nullable Object> T find( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.find(iterable.iterator(), predicate); } /** * Returns the first element in {@code iterable} that satisfies the given predicate, or {@code * defaultValue} if none found. Note that this can usually be handled more naturally using {@code * tryFind(iterable, predicate).or(defaultValue)}. * * <p><b>{@code Stream} equivalent:</b> {@code * stream.filter(predicate).findFirst().orElse(defaultValue)} * * @since 7.0 */ // The signature we really want here is... // // <T extends @Nullable Object> @JointlyNullable T find( // Iterable<? extends T> iterable, // Predicate<? super T> predicate, // @JointlyNullable T defaultValue); // // ...where "@JointlyNullable" is similar to @PolyNull but slightly different: // // - @PolyNull means "@Nullable or @Nonnull" // (That would be unsound for an input Iterable<@Nullable Foo>. So, if we wanted to use // @PolyNull, we would have to restrict this method to non-null <T>. But it has users who pass // iterables with null elements.) // // - @JointlyNullable means "@Nullable or no annotation" @CheckForNull public static <T extends @Nullable Object> T find( Iterable<? extends T> iterable, Predicate<? super T> predicate, @CheckForNull T defaultValue) { return Iterators.<T>find(iterable.iterator(), predicate, defaultValue); } /** * Returns an {@link Optional} containing the first element in {@code iterable} that satisfies the * given predicate, if such an element exists. * * <p><b>Warning:</b> avoid using a {@code predicate} that matches {@code null}. If {@code null} * is matched in {@code iterable}, a NullPointerException will be thrown. * * <p><b>{@code Stream} equivalent:</b> {@code stream.filter(predicate).findFirst()} * * @since 11.0 */ public static <T> Optional<T> tryFind(Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.tryFind(iterable.iterator(), predicate); } /** * Returns the index in {@code iterable} of the first element that satisfies the provided {@code * predicate}, or {@code -1} if the Iterable has no such elements. * * <p>More formally, returns the lowest index {@code i} such that {@code * predicate.apply(Iterables.get(iterable, i))} returns {@code true}, or {@code -1} if there is no * such index. * * @since 2.0 */ public static <T extends @Nullable Object> int indexOf( Iterable<T> iterable, Predicate<? super T> predicate) { return Iterators.indexOf(iterable.iterator(), predicate); } /** * Returns a view containing the result of applying {@code function} to each element of {@code * fromIterable}. * * <p>The returned iterable's iterator supports {@code remove()} if {@code fromIterable}'s * iterator does. After a successful {@code remove()} call, {@code fromIterable} no longer * contains the corresponding element. * * <p>If the input {@code Iterable} is known to be a {@code List} or other {@code Collection}, * consider {@link Lists#transform} and {@link Collections2#transform}. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#map} */ public static <F extends @Nullable Object, T extends @Nullable Object> Iterable<T> transform( final Iterable<F> fromIterable, final Function<? super F, ? extends T> function) { checkNotNull(fromIterable); checkNotNull(function); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.transform(fromIterable.iterator(), function); } @Override public void forEach(Consumer<? super T> action) { checkNotNull(action); fromIterable.forEach((F f) -> action.accept(function.apply(f))); } @Override public Spliterator<T> spliterator() { return CollectSpliterators.map(fromIterable.spliterator(), function); } }; } /** * Returns the element at the specified position in an iterable. * * <p><b>{@code Stream} equivalent:</b> {@code stream.skip(position).findFirst().get()} (throws * {@code NoSuchElementException} if out of bounds) * * @param position position of the element to return * @return the element at the specified position in {@code iterable} * @throws IndexOutOfBoundsException if {@code position} is negative or greater than or equal to * the size of {@code iterable} */ @ParametricNullness public static <T extends @Nullable Object> T get(Iterable<T> iterable, int position) { checkNotNull(iterable); return (iterable instanceof List) ? ((List<T>) iterable).get(position) : Iterators.get(iterable.iterator(), position); } /** * Returns the element at the specified position in an iterable or a default value otherwise. * * <p><b>{@code Stream} equivalent:</b> {@code * stream.skip(position).findFirst().orElse(defaultValue)} (returns the default value if the index * is out of bounds) * * @param position position of the element to return * @param defaultValue the default value to return if {@code position} is greater than or equal to * the size of the iterable * @return the element at the specified position in {@code iterable} or {@code defaultValue} if * {@code iterable} contains fewer than {@code position + 1} elements. * @throws IndexOutOfBoundsException if {@code position} is negative * @since 4.0 */ @ParametricNullness public static <T extends @Nullable Object> T get( Iterable<? extends T> iterable, int position, @ParametricNullness T defaultValue) { checkNotNull(iterable); Iterators.checkNonnegative(position); if (iterable instanceof List) { List<? extends T> list = Lists.cast(iterable); return (position < list.size()) ? list.get(position) : defaultValue; } else { Iterator<? extends T> iterator = iterable.iterator(); Iterators.advance(iterator, position); return Iterators.getNext(iterator, defaultValue); } } /** * Returns the first element in {@code iterable} or {@code defaultValue} if the iterable is empty. * The {@link Iterators} analog to this method is {@link Iterators#getNext}. * * <p>If no default value is desired (and the caller instead wants a {@link * NoSuchElementException} to be thrown), it is recommended that {@code * iterable.iterator().next()} is used instead. * * <p>To get the only element in a single-element {@code Iterable}, consider using {@link * #getOnlyElement(Iterable)} or {@link #getOnlyElement(Iterable, Object)} instead. * * <p><b>{@code Stream} equivalent:</b> {@code stream.findFirst().orElse(defaultValue)} * * @param defaultValue the default value to return if the iterable is empty * @return the first element of {@code iterable} or the default value * @since 7.0 */ @ParametricNullness public static <T extends @Nullable Object> T getFirst( Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { return Iterators.getNext(iterable.iterator(), defaultValue); } /** * Returns the last element of {@code iterable}. If {@code iterable} is a {@link List} with {@link * RandomAccess} support, then this operation is guaranteed to be {@code O(1)}. * * <p><b>{@code Stream} equivalent:</b> {@link Streams#findLast Streams.findLast(stream).get()} * * @return the last element of {@code iterable} * @throws NoSuchElementException if the iterable is empty */ @ParametricNullness public static <T extends @Nullable Object> T getLast(Iterable<T> iterable) { // TODO(kevinb): Support a concurrently modified collection? if (iterable instanceof List) { List<T> list = (List<T>) iterable; if (list.isEmpty()) { throw new NoSuchElementException(); } return getLastInNonemptyList(list); } return Iterators.getLast(iterable.iterator()); } /** * Returns the last element of {@code iterable} or {@code defaultValue} if the iterable is empty. * If {@code iterable} is a {@link List} with {@link RandomAccess} support, then this operation is * guaranteed to be {@code O(1)}. * * <p><b>{@code Stream} equivalent:</b> {@code Streams.findLast(stream).orElse(defaultValue)} * * @param defaultValue the value to return if {@code iterable} is empty * @return the last element of {@code iterable} or the default value * @since 3.0 */ @ParametricNullness public static <T extends @Nullable Object> T getLast( Iterable<? extends T> iterable, @ParametricNullness T defaultValue) { if (iterable instanceof Collection) { Collection<? extends T> c = (Collection<? extends T>) iterable; if (c.isEmpty()) { return defaultValue; } else if (iterable instanceof List) { return getLastInNonemptyList(Lists.cast(iterable)); } } return Iterators.getLast(iterable.iterator(), defaultValue); } @ParametricNullness private static <T extends @Nullable Object> T getLastInNonemptyList(List<T> list) { return list.get(list.size() - 1); } /** * Returns a view of {@code iterable} that skips its first {@code numberToSkip} elements. If * {@code iterable} contains fewer than {@code numberToSkip} elements, the returned iterable skips * all of its elements. * * <p>Modifications to the underlying {@link Iterable} before a call to {@code iterator()} are * reflected in the returned iterator. That is, the iterator skips the first {@code numberToSkip} * elements that exist when the {@code Iterator} is created, not when {@code skip()} is called. * * <p>The returned iterable's iterator supports {@code remove()} if the iterator of the underlying * iterable supports it. Note that it is <i>not</i> possible to delete the last skipped element by * immediately calling {@code remove()} on that iterator, as the {@code Iterator} contract states * that a call to {@code remove()} before a call to {@code next()} will throw an {@link * IllegalStateException}. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#skip} * * @since 3.0 */ public static <T extends @Nullable Object> Iterable<T> skip( final Iterable<T> iterable, final int numberToSkip) { checkNotNull(iterable); checkArgument(numberToSkip >= 0, "number to skip cannot be negative"); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { if (iterable instanceof List) { final List<T> list = (List<T>) iterable; int toSkip = Math.min(list.size(), numberToSkip); return list.subList(toSkip, list.size()).iterator(); } final Iterator<T> iterator = iterable.iterator(); Iterators.advance(iterator, numberToSkip); /* * We can't just return the iterator because an immediate call to its * remove() method would remove one of the skipped elements instead of * throwing an IllegalStateException. */ return new Iterator<T>() { boolean atStart = true; @Override public boolean hasNext() { return iterator.hasNext(); } @Override @ParametricNullness public T next() { T result = iterator.next(); atStart = false; // not called if next() fails return result; } @Override public void remove() { checkRemove(!atStart); iterator.remove(); } }; } @Override public Spliterator<T> spliterator() { if (iterable instanceof List) { final List<T> list = (List<T>) iterable; int toSkip = Math.min(list.size(), numberToSkip); return list.subList(toSkip, list.size()).spliterator(); } else { return Streams.stream(iterable).skip(numberToSkip).spliterator(); } } }; } /** * Returns a view of {@code iterable} containing its first {@code limitSize} elements. If {@code * iterable} contains fewer than {@code limitSize} elements, the returned view contains all of its * elements. The returned iterable's iterator supports {@code remove()} if {@code iterable}'s * iterator does. * * <p><b>{@code Stream} equivalent:</b> {@link Stream#limit} * * @param iterable the iterable to limit * @param limitSize the maximum number of elements in the returned iterable * @throws IllegalArgumentException if {@code limitSize} is negative * @since 3.0 */ public static <T extends @Nullable Object> Iterable<T> limit( final Iterable<T> iterable, final int limitSize) { checkNotNull(iterable); checkArgument(limitSize >= 0, "limit is negative"); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.limit(iterable.iterator(), limitSize); } @Override public Spliterator<T> spliterator() { return Streams.stream(iterable).limit(limitSize).spliterator(); } }; } /** * Returns a view of the supplied iterable that wraps each generated {@link Iterator} through * {@link Iterators#consumingIterator(Iterator)}. * * <p>Note: If {@code iterable} is a {@link Queue}, the returned iterable will instead use {@link * Queue#isEmpty} and {@link Queue#remove()}, since {@link Queue}'s iteration order is undefined. * Calling {@link Iterator#hasNext()} on a generated iterator from the returned iterable may cause * an item to be immediately dequeued for return on a subsequent call to {@link Iterator#next()}. * * <p>Whether the input {@code iterable} is a {@link Queue} or not, the returned {@code Iterable} * is not thread-safe. * * @param iterable the iterable to wrap * @return a view of the supplied iterable that wraps each generated iterator through {@link * Iterators#consumingIterator(Iterator)}; for queues, an iterable that generates iterators * that return and consume the queue's elements in queue order * @see Iterators#consumingIterator(Iterator) * @since 2.0 */ public static <T extends @Nullable Object> Iterable<T> consumingIterable( final Iterable<T> iterable) { checkNotNull(iterable); return new FluentIterable<T>() { @Override public Iterator<T> iterator() { return (iterable instanceof Queue) ? new ConsumingQueueIterator<>((Queue<T>) iterable) : Iterators.consumingIterator(iterable.iterator()); } @Override public String toString() { return "Iterables.consumingIterable(...)"; } }; } // Methods only in Iterables, not in Iterators /** * Determines if the given iterable contains no elements. * * <p>There is no precise {@link Iterator} equivalent to this method, since one can only ask an * iterator whether it has any elements <i>remaining</i> (which one does using {@link * Iterator#hasNext}). * * <p><b>{@code Stream} equivalent:</b> {@code !stream.findAny().isPresent()} * * @return {@code true} if the iterable contains no elements */ public static boolean isEmpty(Iterable<?> iterable) { if (iterable instanceof Collection) { return ((Collection<?>) iterable).isEmpty(); } return !iterable.iterator().hasNext(); } /** * Returns an iterable over the merged contents of all given {@code iterables}. Equivalent entries * will not be de-duplicated. * * <p>Callers must ensure that the source {@code iterables} are in non-descending order as this * method does not sort its input. * * <p>For any equivalent elements across all {@code iterables}, it is undefined which element is * returned first. * * @since 11.0 */ public static <T extends @Nullable Object> Iterable<T> mergeSorted( final Iterable<? extends Iterable<? extends T>> iterables, final Comparator<? super T> comparator) { checkNotNull(iterables, "iterables"); checkNotNull(comparator, "comparator"); Iterable<T> iterable = new FluentIterable<T>() { @Override public Iterator<T> iterator() { return Iterators.mergeSorted( Iterables.transform(iterables, Iterable::iterator), comparator); } }; return new UnmodifiableIterable<>(iterable); } }
google/guava
guava/src/com/google/common/collect/Iterables.java
228
/* * 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 com.google.common.annotations.GwtCompatible; import com.google.common.base.Equivalence; import com.google.common.base.Predicate; import com.google.errorprone.annotations.Immutable; import java.io.Serializable; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.SortedSet; import javax.annotation.CheckForNull; /** * A range (or "interval") defines the <i>boundaries</i> around a contiguous span of values of some * {@code Comparable} type; for example, "integers from 1 to 100 inclusive." Note that it is not * possible to <i>iterate</i> over these contained values. To do so, pass this range instance and an * appropriate {@link DiscreteDomain} to {@link ContiguousSet#create}. * * <h3>Types of ranges</h3> * * <p>Each end of the range may be bounded or unbounded. If bounded, there is an associated * <i>endpoint</i> value, and the range is considered to be either <i>open</i> (does not include the * endpoint) or <i>closed</i> (includes the endpoint) on that side. With three possibilities on each * side, this yields nine basic types of ranges, enumerated below. (Notation: a square bracket * ({@code [ ]}) indicates that the range is closed on that side; a parenthesis ({@code ( )}) means * it is either open or unbounded. The construct {@code {x | statement}} is read "the set of all * <i>x</i> such that <i>statement</i>.") * * <blockquote> * * <table> * <caption>Range Types</caption> * <tr><th>Notation <th>Definition <th>Factory method * <tr><td>{@code (a..b)} <td>{@code {x | a < x < b}} <td>{@link Range#open open} * <tr><td>{@code [a..b]} <td>{@code {x | a <= x <= b}}<td>{@link Range#closed closed} * <tr><td>{@code (a..b]} <td>{@code {x | a < x <= b}} <td>{@link Range#openClosed openClosed} * <tr><td>{@code [a..b)} <td>{@code {x | a <= x < b}} <td>{@link Range#closedOpen closedOpen} * <tr><td>{@code (a..+∞)} <td>{@code {x | x > a}} <td>{@link Range#greaterThan greaterThan} * <tr><td>{@code [a..+∞)} <td>{@code {x | x >= a}} <td>{@link Range#atLeast atLeast} * <tr><td>{@code (-∞..b)} <td>{@code {x | x < b}} <td>{@link Range#lessThan lessThan} * <tr><td>{@code (-∞..b]} <td>{@code {x | x <= b}} <td>{@link Range#atMost atMost} * <tr><td>{@code (-∞..+∞)}<td>{@code {x}} <td>{@link Range#all all} * </table> * * </blockquote> * * <p>When both endpoints exist, the upper endpoint may not be less than the lower. The endpoints * may be equal only if at least one of the bounds is closed: * * <ul> * <li>{@code [a..a]} : a singleton range * <li>{@code [a..a); (a..a]} : {@linkplain #isEmpty empty} ranges; also valid * <li>{@code (a..a)} : <b>invalid</b>; an exception will be thrown * </ul> * * <h3>Warnings</h3> * * <ul> * <li>Use immutable value types only, if at all possible. If you must use a mutable type, <b>do * not</b> allow the endpoint instances to mutate after the range is created! * <li>Your value type's comparison method should be {@linkplain Comparable consistent with * equals} if at all possible. Otherwise, be aware that concepts used throughout this * documentation such as "equal", "same", "unique" and so on actually refer to whether {@link * Comparable#compareTo compareTo} returns zero, not whether {@link Object#equals equals} * returns {@code true}. * <li>A class which implements {@code Comparable<UnrelatedType>} is very broken, and will cause * undefined horrible things to happen in {@code Range}. For now, the Range API does not * prevent its use, because this would also rule out all ungenerified (pre-JDK1.5) data types. * <b>This may change in the future.</b> * </ul> * * <h3>Other notes</h3> * * <ul> * <li>All ranges are shallow-immutable. * <li>Instances of this type are obtained using the static factory methods in this class. * <li>Ranges are <i>convex</i>: whenever two values are contained, all values in between them * must also be contained. More formally, for any {@code c1 <= c2 <= c3} of type {@code C}, * {@code r.contains(c1) && r.contains(c3)} implies {@code r.contains(c2)}). This means that a * {@code Range<Integer>} can never be used to represent, say, "all <i>prime</i> numbers from * 1 to 100." * <li>When evaluated as a {@link Predicate}, a range yields the same result as invoking {@link * #contains}. * <li>Terminology note: a range {@code a} is said to be the <i>maximal</i> range having property * <i>P</i> if, for all ranges {@code b} also having property <i>P</i>, {@code a.encloses(b)}. * Likewise, {@code a} is <i>minimal</i> when {@code b.encloses(a)} for all {@code b} having * property <i>P</i>. See, for example, the definition of {@link #intersection intersection}. * <li>A {@code Range} is serializable if it has no bounds, or if each bound is serializable. * </ul> * * <h3>Further reading</h3> * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/RangesExplained">{@code Range}</a>. * * @author Kevin Bourrillion * @author Gregory Kick * @since 10.0 */ @GwtCompatible @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 @Immutable(containerOf = "C") @ElementTypesAreNonnullByDefault public final class Range<C extends Comparable> extends RangeGwtSerializationDependencies implements Predicate<C>, Serializable { @SuppressWarnings("unchecked") static <C extends Comparable<?>> Ordering<Range<C>> rangeLexOrdering() { return (Ordering<Range<C>>) RangeLexOrdering.INSTANCE; } static <C extends Comparable<?>> Range<C> create(Cut<C> lowerBound, Cut<C> upperBound) { return new Range<>(lowerBound, upperBound); } /** * Returns a range that contains all values strictly greater than {@code lower} and strictly less * than {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than <i>or equal to</i> {@code * upper} * @throws ClassCastException if {@code lower} and {@code upper} are not mutually comparable * @since 14.0 */ public static <C extends Comparable<?>> Range<C> open(C lower, C upper) { return create(Cut.aboveValue(lower), Cut.belowValue(upper)); } /** * Returns a range that contains all values greater than or equal to {@code lower} and less than * or equal to {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code upper} * @throws ClassCastException if {@code lower} and {@code upper} are not mutually comparable * @since 14.0 */ public static <C extends Comparable<?>> Range<C> closed(C lower, C upper) { return create(Cut.belowValue(lower), Cut.aboveValue(upper)); } /** * Returns a range that contains all values greater than or equal to {@code lower} and strictly * less than {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code upper} * @throws ClassCastException if {@code lower} and {@code upper} are not mutually comparable * @since 14.0 */ public static <C extends Comparable<?>> Range<C> closedOpen(C lower, C upper) { return create(Cut.belowValue(lower), Cut.belowValue(upper)); } /** * Returns a range that contains all values strictly greater than {@code lower} and less than or * equal to {@code upper}. * * @throws IllegalArgumentException if {@code lower} is greater than {@code upper} * @throws ClassCastException if {@code lower} and {@code upper} are not mutually comparable * @since 14.0 */ public static <C extends Comparable<?>> Range<C> openClosed(C lower, C upper) { return create(Cut.aboveValue(lower), Cut.aboveValue(upper)); } /** * Returns a range that contains any value from {@code lower} to {@code upper}, where each * endpoint may be either inclusive (closed) or exclusive (open). * * @throws IllegalArgumentException if {@code lower} is greater than {@code upper} * @throws ClassCastException if {@code lower} and {@code upper} are not mutually comparable * @since 14.0 */ public static <C extends Comparable<?>> Range<C> range( C lower, BoundType lowerType, C upper, BoundType upperType) { checkNotNull(lowerType); checkNotNull(upperType); Cut<C> lowerBound = (lowerType == BoundType.OPEN) ? Cut.aboveValue(lower) : Cut.belowValue(lower); Cut<C> upperBound = (upperType == BoundType.OPEN) ? Cut.belowValue(upper) : Cut.aboveValue(upper); return create(lowerBound, upperBound); } /** * Returns a range that contains all values strictly less than {@code endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> lessThan(C endpoint) { return create(Cut.<C>belowAll(), Cut.belowValue(endpoint)); } /** * Returns a range that contains all values less than or equal to {@code endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> atMost(C endpoint) { return create(Cut.<C>belowAll(), Cut.aboveValue(endpoint)); } /** * Returns a range with no lower bound up to the given endpoint, which may be either inclusive * (closed) or exclusive (open). * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> upTo(C endpoint, BoundType boundType) { switch (boundType) { case OPEN: return lessThan(endpoint); case CLOSED: return atMost(endpoint); default: throw new AssertionError(); } } /** * Returns a range that contains all values strictly greater than {@code endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> greaterThan(C endpoint) { return create(Cut.aboveValue(endpoint), Cut.<C>aboveAll()); } /** * Returns a range that contains all values greater than or equal to {@code endpoint}. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> atLeast(C endpoint) { return create(Cut.belowValue(endpoint), Cut.<C>aboveAll()); } /** * Returns a range from the given endpoint, which may be either inclusive (closed) or exclusive * (open), with no upper bound. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> downTo(C endpoint, BoundType boundType) { switch (boundType) { case OPEN: return greaterThan(endpoint); case CLOSED: return atLeast(endpoint); default: throw new AssertionError(); } } private static final Range<Comparable> ALL = new Range<>(Cut.belowAll(), Cut.aboveAll()); /** * Returns a range that contains every value of type {@code C}. * * @since 14.0 */ @SuppressWarnings("unchecked") public static <C extends Comparable<?>> Range<C> all() { return (Range) ALL; } /** * Returns a range that {@linkplain Range#contains(Comparable) contains} only the given value. The * returned range is {@linkplain BoundType#CLOSED closed} on both ends. * * @since 14.0 */ public static <C extends Comparable<?>> Range<C> singleton(C value) { return closed(value, value); } /** * Returns the minimal range that {@linkplain Range#contains(Comparable) contains} all of the * given values. The returned range is {@linkplain BoundType#CLOSED closed} on both ends. * * @throws ClassCastException if the values are not mutually comparable * @throws NoSuchElementException if {@code values} is empty * @throws NullPointerException if any of {@code values} is null * @since 14.0 */ public static <C extends Comparable<?>> Range<C> encloseAll(Iterable<C> values) { checkNotNull(values); if (values instanceof SortedSet) { SortedSet<C> set = (SortedSet<C>) values; Comparator<?> comparator = set.comparator(); if (Ordering.<C>natural().equals(comparator) || comparator == null) { return closed(set.first(), set.last()); } } Iterator<C> valueIterator = values.iterator(); C min = checkNotNull(valueIterator.next()); C max = min; while (valueIterator.hasNext()) { C value = checkNotNull(valueIterator.next()); min = Ordering.<C>natural().min(min, value); max = Ordering.<C>natural().max(max, value); } return closed(min, max); } final Cut<C> lowerBound; final Cut<C> upperBound; private Range(Cut<C> lowerBound, Cut<C> upperBound) { this.lowerBound = checkNotNull(lowerBound); this.upperBound = checkNotNull(upperBound); if (lowerBound.compareTo(upperBound) > 0 || lowerBound == Cut.<C>aboveAll() || upperBound == Cut.<C>belowAll()) { throw new IllegalArgumentException("Invalid range: " + toString(lowerBound, upperBound)); } } /** Returns {@code true} if this range has a lower endpoint. */ public boolean hasLowerBound() { return lowerBound != Cut.belowAll(); } /** * Returns the lower endpoint of this range. * * @throws IllegalStateException if this range is unbounded below (that is, {@link * #hasLowerBound()} returns {@code false}) */ public C lowerEndpoint() { return lowerBound.endpoint(); } /** * Returns the type of this range's lower bound: {@link BoundType#CLOSED} if the range includes * its lower endpoint, {@link BoundType#OPEN} if it does not. * * @throws IllegalStateException if this range is unbounded below (that is, {@link * #hasLowerBound()} returns {@code false}) */ public BoundType lowerBoundType() { return lowerBound.typeAsLowerBound(); } /** Returns {@code true} if this range has an upper endpoint. */ public boolean hasUpperBound() { return upperBound != Cut.aboveAll(); } /** * Returns the upper endpoint of this range. * * @throws IllegalStateException if this range is unbounded above (that is, {@link * #hasUpperBound()} returns {@code false}) */ public C upperEndpoint() { return upperBound.endpoint(); } /** * Returns the type of this range's upper bound: {@link BoundType#CLOSED} if the range includes * its upper endpoint, {@link BoundType#OPEN} if it does not. * * @throws IllegalStateException if this range is unbounded above (that is, {@link * #hasUpperBound()} returns {@code false}) */ public BoundType upperBoundType() { return upperBound.typeAsUpperBound(); } /** * Returns {@code true} if this range is of the form {@code [v..v)} or {@code (v..v]}. (This does * not encompass ranges of the form {@code (v..v)}, because such ranges are <i>invalid</i> and * can't be constructed at all.) * * <p>Note that certain discrete ranges such as the integer range {@code (3..4)} are <b>not</b> * considered empty, even though they contain no actual values. In these cases, it may be helpful * to preprocess ranges with {@link #canonical(DiscreteDomain)}. */ public boolean isEmpty() { return lowerBound.equals(upperBound); } /** * Returns {@code true} if {@code value} is within the bounds of this range. For example, on the * range {@code [0..2)}, {@code contains(1)} returns {@code true}, while {@code contains(2)} * returns {@code false}. */ public boolean contains(C value) { checkNotNull(value); // let this throw CCE if there is some trickery going on return lowerBound.isLessThan(value) && !upperBound.isLessThan(value); } /** * @deprecated Provided only to satisfy the {@link Predicate} interface; use {@link #contains} * instead. */ @Deprecated @Override public boolean apply(C input) { return contains(input); } /** * Returns {@code true} if every element in {@code values} is {@linkplain #contains contained} in * this range. */ public boolean containsAll(Iterable<? extends C> values) { if (Iterables.isEmpty(values)) { return true; } // this optimizes testing equality of two range-backed sets if (values instanceof SortedSet) { SortedSet<? extends C> set = (SortedSet<? extends C>) values; Comparator<?> comparator = set.comparator(); if (Ordering.natural().equals(comparator) || comparator == null) { return contains(set.first()) && contains(set.last()); } } for (C value : values) { if (!contains(value)) { return false; } } return true; } /** * Returns {@code true} if the bounds of {@code other} do not extend outside the bounds of this * range. Examples: * * <ul> * <li>{@code [3..6]} encloses {@code [4..5]} * <li>{@code (3..6)} encloses {@code (3..6)} * <li>{@code [3..6]} encloses {@code [4..4)} (even though the latter is empty) * <li>{@code (3..6]} does not enclose {@code [3..6]} * <li>{@code [4..5]} does not enclose {@code (3..6)} (even though it contains every value * contained by the latter range) * <li>{@code [3..6]} does not enclose {@code (1..1]} (even though it contains every value * contained by the latter range) * </ul> * * <p>Note that if {@code a.encloses(b)}, then {@code b.contains(v)} implies {@code * a.contains(v)}, but as the last two examples illustrate, the converse is not always true. * * <p>Being reflexive, antisymmetric and transitive, the {@code encloses} relation defines a * <i>partial order</i> over ranges. There exists a unique {@linkplain Range#all maximal} range * according to this relation, and also numerous {@linkplain #isEmpty minimal} ranges. Enclosure * also implies {@linkplain #isConnected connectedness}. */ public boolean encloses(Range<C> other) { return lowerBound.compareTo(other.lowerBound) <= 0 && upperBound.compareTo(other.upperBound) >= 0; } /** * Returns {@code true} if there exists a (possibly empty) range which is {@linkplain #encloses * enclosed} by both this range and {@code other}. * * <p>For example, * * <ul> * <li>{@code [2, 4)} and {@code [5, 7)} are not connected * <li>{@code [2, 4)} and {@code [3, 5)} are connected, because both enclose {@code [3, 4)} * <li>{@code [2, 4)} and {@code [4, 6)} are connected, because both enclose the empty range * {@code [4, 4)} * </ul> * * <p>Note that this range and {@code other} have a well-defined {@linkplain #span union} and * {@linkplain #intersection intersection} (as a single, possibly-empty range) if and only if this * method returns {@code true}. * * <p>The connectedness relation is both reflexive and symmetric, but does not form an {@linkplain * Equivalence equivalence relation} as it is not transitive. * * <p>Note that certain discrete ranges are not considered connected, even though there are no * elements "between them." For example, {@code [3, 5]} is not considered connected to {@code [6, * 10]}. In these cases, it may be desirable for both input ranges to be preprocessed with {@link * #canonical(DiscreteDomain)} before testing for connectedness. */ public boolean isConnected(Range<C> other) { return lowerBound.compareTo(other.upperBound) <= 0 && other.lowerBound.compareTo(upperBound) <= 0; } /** * Returns the maximal range {@linkplain #encloses enclosed} by both this range and {@code * connectedRange}, if such a range exists. * * <p>For example, the intersection of {@code [1..5]} and {@code (3..7)} is {@code (3..5]}. The * resulting range may be empty; for example, {@code [1..5)} intersected with {@code [5..7)} * yields the empty range {@code [5..5)}. * * <p>The intersection exists if and only if the two ranges are {@linkplain #isConnected * connected}. * * <p>The intersection operation is commutative, associative and idempotent, and its identity * element is {@link Range#all}). * * @throws IllegalArgumentException if {@code isConnected(connectedRange)} is {@code false} */ public Range<C> intersection(Range<C> connectedRange) { int lowerCmp = lowerBound.compareTo(connectedRange.lowerBound); int upperCmp = upperBound.compareTo(connectedRange.upperBound); if (lowerCmp >= 0 && upperCmp <= 0) { return this; } else if (lowerCmp <= 0 && upperCmp >= 0) { return connectedRange; } else { Cut<C> newLower = (lowerCmp >= 0) ? lowerBound : connectedRange.lowerBound; Cut<C> newUpper = (upperCmp <= 0) ? upperBound : connectedRange.upperBound; // create() would catch this, but give a confusing error message checkArgument( newLower.compareTo(newUpper) <= 0, "intersection is undefined for disconnected ranges %s and %s", this, connectedRange); // TODO(kevinb): all the precondition checks in the constructor are redundant... return create(newLower, newUpper); } } /** * Returns the maximal range lying between this range and {@code otherRange}, if such a range * exists. The resulting range may be empty if the two ranges are adjacent but non-overlapping. * * <p>For example, the gap of {@code [1..5]} and {@code (7..10)} is {@code (5..7]}. The resulting * range may be empty; for example, the gap between {@code [1..5)} {@code [5..7)} yields the empty * range {@code [5..5)}. * * <p>The gap exists if and only if the two ranges are either disconnected or immediately adjacent * (any intersection must be an empty range). * * <p>The gap operation is commutative. * * @throws IllegalArgumentException if this range and {@code otherRange} have a nonempty * intersection * @since 27.0 */ public Range<C> gap(Range<C> otherRange) { /* * For an explanation of the basic principle behind this check, see * https://stackoverflow.com/a/35754308/28465 * * In that explanation's notation, our `overlap` check would be `x1 < y2 && y1 < x2`. We've * flipped one part of the check so that we're using "less than" in both cases (rather than a * mix of "less than" and "greater than"). We've also switched to "strictly less than" rather * than "less than or equal to" because of *handwave* the difference between "endpoints of * inclusive ranges" and "Cuts." */ if (lowerBound.compareTo(otherRange.upperBound) < 0 && otherRange.lowerBound.compareTo(upperBound) < 0) { throw new IllegalArgumentException( "Ranges have a nonempty intersection: " + this + ", " + otherRange); } boolean isThisFirst = this.lowerBound.compareTo(otherRange.lowerBound) < 0; Range<C> firstRange = isThisFirst ? this : otherRange; Range<C> secondRange = isThisFirst ? otherRange : this; return create(firstRange.upperBound, secondRange.lowerBound); } /** * Returns the minimal range that {@linkplain #encloses encloses} both this range and {@code * other}. For example, the span of {@code [1..3]} and {@code (5..7)} is {@code [1..7)}. * * <p><i>If</i> the input ranges are {@linkplain #isConnected connected}, the returned range can * also be called their <i>union</i>. If they are not, note that the span might contain values * that are not contained in either input range. * * <p>Like {@link #intersection(Range) intersection}, this operation is commutative, associative * and idempotent. Unlike it, it is always well-defined for any two input ranges. */ public Range<C> span(Range<C> other) { int lowerCmp = lowerBound.compareTo(other.lowerBound); int upperCmp = upperBound.compareTo(other.upperBound); if (lowerCmp <= 0 && upperCmp >= 0) { return this; } else if (lowerCmp >= 0 && upperCmp <= 0) { return other; } else { Cut<C> newLower = (lowerCmp <= 0) ? lowerBound : other.lowerBound; Cut<C> newUpper = (upperCmp >= 0) ? upperBound : other.upperBound; return create(newLower, newUpper); } } /** * Returns the canonical form of this range in the given domain. The canonical form has the * following properties: * * <ul> * <li>equivalence: {@code a.canonical().contains(v) == a.contains(v)} for all {@code v} (in * other words, {@code ContiguousSet.create(a.canonical(domain), domain).equals( * ContiguousSet.create(a, domain))} * <li>uniqueness: unless {@code a.isEmpty()}, {@code ContiguousSet.create(a, * domain).equals(ContiguousSet.create(b, domain))} implies {@code * a.canonical(domain).equals(b.canonical(domain))} * <li>idempotence: {@code a.canonical(domain).canonical(domain).equals(a.canonical(domain))} * </ul> * * <p>Furthermore, this method guarantees that the range returned will be one of the following * canonical forms: * * <ul> * <li>[start..end) * <li>[start..+∞) * <li>(-∞..end) (only if type {@code C} is unbounded below) * <li>(-∞..+∞) (only if type {@code C} is unbounded below) * </ul> */ public Range<C> canonical(DiscreteDomain<C> domain) { checkNotNull(domain); Cut<C> lower = lowerBound.canonical(domain); Cut<C> upper = upperBound.canonical(domain); return (lower == lowerBound && upper == upperBound) ? this : create(lower, upper); } /** * Returns {@code true} if {@code object} is a range having the same endpoints and bound types as * this range. Note that discrete ranges such as {@code (1..4)} and {@code [2..3]} are <b>not</b> * equal to one another, despite the fact that they each contain precisely the same set of values. * Similarly, empty ranges are not equal unless they have exactly the same representation, so * {@code [3..3)}, {@code (3..3]}, {@code (4..4]} are all unequal. */ @Override public boolean equals(@CheckForNull Object object) { if (object instanceof Range) { Range<?> other = (Range<?>) object; return lowerBound.equals(other.lowerBound) && upperBound.equals(other.upperBound); } return false; } /** Returns a hash code for this range. */ @Override public int hashCode() { return lowerBound.hashCode() * 31 + upperBound.hashCode(); } /** * Returns a string representation of this range, such as {@code "[3..5)"} (other examples are * listed in the class documentation). */ @Override public String toString() { return toString(lowerBound, upperBound); } // We declare accessors so that we can use method references like `Range::lowerBound`. Cut<C> lowerBound() { return lowerBound; } Cut<C> upperBound() { return upperBound; } private static String toString(Cut<?> lowerBound, Cut<?> upperBound) { StringBuilder sb = new StringBuilder(16); lowerBound.describeAsLowerBound(sb); sb.append(".."); upperBound.describeAsUpperBound(sb); return sb.toString(); } Object readResolve() { if (this.equals(ALL)) { return all(); } else { return this; } } @SuppressWarnings("unchecked") // this method may throw CCE static int compareOrThrow(Comparable left, Comparable right) { return left.compareTo(right); } /** Needed to serialize sorted collections of Ranges. */ private static class RangeLexOrdering extends Ordering<Range<?>> implements Serializable { static final Ordering<?> INSTANCE = new RangeLexOrdering(); @Override public int compare(Range<?> left, Range<?> right) { return ComparisonChain.start() .compare(left.lowerBound, right.lowerBound) .compare(left.upperBound, right.upperBound) .result(); } private static final long serialVersionUID = 0; } private static final long serialVersionUID = 0; }
google/guava
guava/src/com/google/common/collect/Range.java
229
/* * 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
230
/* * 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
231
/* * 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 static com.google.common.base.Preconditions.checkArgument; import static com.google.common.graph.GraphConstants.NODE_NOT_IN_GRAPH; import static java.util.Objects.requireNonNull; import com.google.common.annotations.Beta; import com.google.common.base.Objects; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.collect.Iterators; import com.google.common.collect.Maps; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.util.Collection; import java.util.HashSet; import java.util.Iterator; import java.util.Map; import java.util.Optional; import java.util.Set; import javax.annotation.CheckForNull; /** * Static utility methods for {@link Graph}, {@link ValueGraph}, and {@link Network} instances. * * @author James Sexton * @author Joshua O'Madadhain * @since 20.0 */ @Beta @ElementTypesAreNonnullByDefault public final class Graphs extends GraphsBridgeMethods { private Graphs() {} // Graph query methods /** * Returns true if {@code graph} has at least one cycle. A cycle is defined as a non-empty subset * of edges in a graph arranged to form a path (a sequence of adjacent outgoing edges) starting * and ending with the same node. * * <p>This method will detect any non-empty cycle, including self-loops (a cycle of length 1). */ public static <N> boolean hasCycle(Graph<N> graph) { int numEdges = graph.edges().size(); if (numEdges == 0) { return false; // An edge-free graph is acyclic by definition. } if (!graph.isDirected() && numEdges >= graph.nodes().size()) { return true; // Optimization for the undirected case: at least one cycle must exist. } Map<Object, NodeVisitState> visitedNodes = Maps.newHashMapWithExpectedSize(graph.nodes().size()); for (N node : graph.nodes()) { if (subgraphHasCycle(graph, visitedNodes, node, null)) { return true; } } return false; } /** * Returns true if {@code network} has at least one cycle. A cycle is defined as a non-empty * subset of edges in a graph arranged to form a path (a sequence of adjacent outgoing edges) * starting and ending with the same node. * * <p>This method will detect any non-empty cycle, including self-loops (a cycle of length 1). */ public static boolean hasCycle(Network<?, ?> network) { // In a directed graph, parallel edges cannot introduce a cycle in an acyclic graph. // However, in an undirected graph, any parallel edge induces a cycle in the graph. if (!network.isDirected() && network.allowsParallelEdges() && network.edges().size() > network.asGraph().edges().size()) { return true; } return hasCycle(network.asGraph()); } /** * Performs a traversal of the nodes reachable from {@code node}. If we ever reach a node we've * already visited (following only outgoing edges and without reusing edges), we know there's a * cycle in the graph. */ private static <N> boolean subgraphHasCycle( Graph<N> graph, Map<Object, NodeVisitState> visitedNodes, N node, @CheckForNull N previousNode) { NodeVisitState state = visitedNodes.get(node); if (state == NodeVisitState.COMPLETE) { return false; } if (state == NodeVisitState.PENDING) { return true; } visitedNodes.put(node, NodeVisitState.PENDING); for (N nextNode : graph.successors(node)) { if (canTraverseWithoutReusingEdge(graph, nextNode, previousNode) && subgraphHasCycle(graph, visitedNodes, nextNode, node)) { return true; } } visitedNodes.put(node, NodeVisitState.COMPLETE); return false; } /** * Determines whether an edge has already been used during traversal. In the directed case a cycle * is always detected before reusing an edge, so no special logic is required. In the undirected * case, we must take care not to "backtrack" over an edge (i.e. going from A to B and then going * from B to A). */ private static boolean canTraverseWithoutReusingEdge( Graph<?> graph, Object nextNode, @CheckForNull Object previousNode) { if (graph.isDirected() || !Objects.equal(previousNode, nextNode)) { return true; } // This falls into the undirected A->B->A case. The Graph interface does not support parallel // edges, so this traversal would require reusing the undirected AB edge. return false; } /** * Returns the transitive closure of {@code graph}. The transitive closure of a graph is another * graph with an edge connecting node A to node B if node B is {@link #reachableNodes(Graph, * Object) reachable} from node A. * * <p>This is a "snapshot" based on the current topology of {@code graph}, rather than a live view * of the transitive closure of {@code graph}. In other words, the returned {@link Graph} will not * be updated after modifications to {@code graph}. * * @since 33.1.0 (present with return type {@code Graph} since 20.0) */ // TODO(b/31438252): Consider potential optimizations for this algorithm. public static <N> ImmutableGraph<N> transitiveClosure(Graph<N> graph) { ImmutableGraph.Builder<N> transitiveClosure = GraphBuilder.from(graph).allowsSelfLoops(true).<N>immutable(); // Every node is, at a minimum, reachable from itself. Since the resulting transitive closure // will have no isolated nodes, we can skip adding nodes explicitly and let putEdge() do it. if (graph.isDirected()) { // Note: works for both directed and undirected graphs, but we only use in the directed case. for (N node : graph.nodes()) { for (N reachableNode : reachableNodes(graph, node)) { transitiveClosure.putEdge(node, reachableNode); } } } else { // An optimization for the undirected case: for every node B reachable from node A, // node A and node B have the same reachability set. Set<N> visitedNodes = new HashSet<>(); for (N node : graph.nodes()) { if (!visitedNodes.contains(node)) { Set<N> reachableNodes = reachableNodes(graph, node); visitedNodes.addAll(reachableNodes); int pairwiseMatch = 1; // start at 1 to include self-loops for (N nodeU : reachableNodes) { for (N nodeV : Iterables.limit(reachableNodes, pairwiseMatch++)) { transitiveClosure.putEdge(nodeU, nodeV); } } } } } return transitiveClosure.build(); } /** * Returns the set of nodes that are reachable from {@code node}. Node B is defined as reachable * from node A if there exists a path (a sequence of adjacent outgoing edges) starting at node A * and ending at node B. Note that a node is always reachable from itself via a zero-length path. * * <p>This is a "snapshot" based on the current topology of {@code graph}, rather than a live view * of the set of nodes reachable from {@code node}. In other words, the returned {@link Set} will * not be updated after modifications to {@code graph}. * * @throws IllegalArgumentException if {@code node} is not present in {@code graph} * @since 33.1.0 (present with return type {@code Set} since 20.0) */ public static <N> ImmutableSet<N> reachableNodes(Graph<N> graph, N node) { checkArgument(graph.nodes().contains(node), NODE_NOT_IN_GRAPH, node); return ImmutableSet.copyOf(Traverser.forGraph(graph).breadthFirst(node)); } // Graph mutation methods // Graph view methods /** * Returns a view of {@code graph} with the direction (if any) of every edge reversed. All other * properties remain intact, and further updates to {@code graph} will be reflected in the view. */ public static <N> Graph<N> transpose(Graph<N> graph) { if (!graph.isDirected()) { return graph; // the transpose of an undirected graph is an identical graph } if (graph instanceof TransposedGraph) { return ((TransposedGraph<N>) graph).graph; } return new TransposedGraph<>(graph); } /** * Returns a view of {@code graph} with the direction (if any) of every edge reversed. All other * properties remain intact, and further updates to {@code graph} will be reflected in the view. */ public static <N, V> ValueGraph<N, V> transpose(ValueGraph<N, V> graph) { if (!graph.isDirected()) { return graph; // the transpose of an undirected graph is an identical graph } if (graph instanceof TransposedValueGraph) { return ((TransposedValueGraph<N, V>) graph).graph; } return new TransposedValueGraph<>(graph); } /** * Returns a view of {@code network} with the direction (if any) of every edge reversed. All other * properties remain intact, and further updates to {@code network} will be reflected in the view. */ public static <N, E> Network<N, E> transpose(Network<N, E> network) { if (!network.isDirected()) { return network; // the transpose of an undirected network is an identical network } if (network instanceof TransposedNetwork) { return ((TransposedNetwork<N, E>) network).network; } return new TransposedNetwork<>(network); } static <N> EndpointPair<N> transpose(EndpointPair<N> endpoints) { if (endpoints.isOrdered()) { return EndpointPair.ordered(endpoints.target(), endpoints.source()); } return endpoints; } // NOTE: this should work as long as the delegate graph's implementation of edges() (like that of // AbstractGraph) derives its behavior from calling successors(). private static class TransposedGraph<N> extends ForwardingGraph<N> { private final Graph<N> graph; TransposedGraph(Graph<N> graph) { this.graph = graph; } @Override Graph<N> delegate() { return graph; } @Override public Set<N> predecessors(N node) { return delegate().successors(node); // transpose } @Override public Set<N> successors(N node) { return delegate().predecessors(node); // transpose } @Override public Set<EndpointPair<N>> incidentEdges(N node) { return new IncidentEdgeSet<N>(this, node) { @Override public Iterator<EndpointPair<N>> iterator() { return Iterators.transform( delegate().incidentEdges(node).iterator(), edge -> EndpointPair.of(delegate(), edge.nodeV(), edge.nodeU())); } }; } @Override public int inDegree(N node) { return delegate().outDegree(node); // transpose } @Override public int outDegree(N node) { return delegate().inDegree(node); // transpose } @Override public boolean hasEdgeConnecting(N nodeU, N nodeV) { return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose } @Override public boolean hasEdgeConnecting(EndpointPair<N> endpoints) { return delegate().hasEdgeConnecting(transpose(endpoints)); } } // NOTE: this should work as long as the delegate graph's implementation of edges() (like that of // AbstractValueGraph) derives its behavior from calling successors(). private static class TransposedValueGraph<N, V> extends ForwardingValueGraph<N, V> { private final ValueGraph<N, V> graph; TransposedValueGraph(ValueGraph<N, V> graph) { this.graph = graph; } @Override ValueGraph<N, V> delegate() { return graph; } @Override public Set<N> predecessors(N node) { return delegate().successors(node); // transpose } @Override public Set<N> successors(N node) { return delegate().predecessors(node); // transpose } @Override public int inDegree(N node) { return delegate().outDegree(node); // transpose } @Override public int outDegree(N node) { return delegate().inDegree(node); // transpose } @Override public boolean hasEdgeConnecting(N nodeU, N nodeV) { return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose } @Override public boolean hasEdgeConnecting(EndpointPair<N> endpoints) { return delegate().hasEdgeConnecting(transpose(endpoints)); } @Override public Optional<V> edgeValue(N nodeU, N nodeV) { return delegate().edgeValue(nodeV, nodeU); // transpose } @Override public Optional<V> edgeValue(EndpointPair<N> endpoints) { return delegate().edgeValue(transpose(endpoints)); } @Override @CheckForNull public V edgeValueOrDefault(N nodeU, N nodeV, @CheckForNull V defaultValue) { return delegate().edgeValueOrDefault(nodeV, nodeU, defaultValue); // transpose } @Override @CheckForNull public V edgeValueOrDefault(EndpointPair<N> endpoints, @CheckForNull V defaultValue) { return delegate().edgeValueOrDefault(transpose(endpoints), defaultValue); } } private static class TransposedNetwork<N, E> extends ForwardingNetwork<N, E> { private final Network<N, E> network; TransposedNetwork(Network<N, E> network) { this.network = network; } @Override Network<N, E> delegate() { return network; } @Override public Set<N> predecessors(N node) { return delegate().successors(node); // transpose } @Override public Set<N> successors(N node) { return delegate().predecessors(node); // transpose } @Override public int inDegree(N node) { return delegate().outDegree(node); // transpose } @Override public int outDegree(N node) { return delegate().inDegree(node); // transpose } @Override public Set<E> inEdges(N node) { return delegate().outEdges(node); // transpose } @Override public Set<E> outEdges(N node) { return delegate().inEdges(node); // transpose } @Override public EndpointPair<N> incidentNodes(E edge) { EndpointPair<N> endpointPair = delegate().incidentNodes(edge); return EndpointPair.of(network, endpointPair.nodeV(), endpointPair.nodeU()); // transpose } @Override public Set<E> edgesConnecting(N nodeU, N nodeV) { return delegate().edgesConnecting(nodeV, nodeU); // transpose } @Override public Set<E> edgesConnecting(EndpointPair<N> endpoints) { return delegate().edgesConnecting(transpose(endpoints)); } @Override public Optional<E> edgeConnecting(N nodeU, N nodeV) { return delegate().edgeConnecting(nodeV, nodeU); // transpose } @Override public Optional<E> edgeConnecting(EndpointPair<N> endpoints) { return delegate().edgeConnecting(transpose(endpoints)); } @Override @CheckForNull public E edgeConnectingOrNull(N nodeU, N nodeV) { return delegate().edgeConnectingOrNull(nodeV, nodeU); // transpose } @Override @CheckForNull public E edgeConnectingOrNull(EndpointPair<N> endpoints) { return delegate().edgeConnectingOrNull(transpose(endpoints)); } @Override public boolean hasEdgeConnecting(N nodeU, N nodeV) { return delegate().hasEdgeConnecting(nodeV, nodeU); // transpose } @Override public boolean hasEdgeConnecting(EndpointPair<N> endpoints) { return delegate().hasEdgeConnecting(transpose(endpoints)); } } // Graph copy methods /** * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges} * from {@code graph} for which both nodes are contained by {@code nodes}. * * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph */ public static <N> MutableGraph<N> inducedSubgraph(Graph<N> graph, Iterable<? extends N> nodes) { MutableGraph<N> subgraph = (nodes instanceof Collection) ? GraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build() : GraphBuilder.from(graph).build(); for (N node : nodes) { subgraph.addNode(node); } for (N node : subgraph.nodes()) { for (N successorNode : graph.successors(node)) { if (subgraph.nodes().contains(successorNode)) { subgraph.putEdge(node, successorNode); } } } return subgraph; } /** * Returns the subgraph of {@code graph} induced by {@code nodes}. This subgraph is a new graph * that contains all of the nodes in {@code nodes}, and all of the {@link Graph#edges() edges} * (and associated edge values) from {@code graph} for which both nodes are contained by {@code * nodes}. * * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph */ public static <N, V> MutableValueGraph<N, V> inducedSubgraph( ValueGraph<N, V> graph, Iterable<? extends N> nodes) { MutableValueGraph<N, V> subgraph = (nodes instanceof Collection) ? ValueGraphBuilder.from(graph).expectedNodeCount(((Collection) nodes).size()).build() : ValueGraphBuilder.from(graph).build(); for (N node : nodes) { subgraph.addNode(node); } for (N node : subgraph.nodes()) { for (N successorNode : graph.successors(node)) { if (subgraph.nodes().contains(successorNode)) { // requireNonNull is safe because the endpoint pair comes from the graph. subgraph.putEdgeValue( node, successorNode, requireNonNull(graph.edgeValueOrDefault(node, successorNode, null))); } } } return subgraph; } /** * Returns the subgraph of {@code network} induced by {@code nodes}. This subgraph is a new graph * that contains all of the nodes in {@code nodes}, and all of the {@link Network#edges() edges} * from {@code network} for which the {@link Network#incidentNodes(Object) incident nodes} are * both contained by {@code nodes}. * * @throws IllegalArgumentException if any element in {@code nodes} is not a node in the graph */ public static <N, E> MutableNetwork<N, E> inducedSubgraph( Network<N, E> network, Iterable<? extends N> nodes) { MutableNetwork<N, E> subgraph = (nodes instanceof Collection) ? NetworkBuilder.from(network).expectedNodeCount(((Collection) nodes).size()).build() : NetworkBuilder.from(network).build(); for (N node : nodes) { subgraph.addNode(node); } for (N node : subgraph.nodes()) { for (E edge : network.outEdges(node)) { N successorNode = network.incidentNodes(edge).adjacentNode(node); if (subgraph.nodes().contains(successorNode)) { subgraph.addEdge(node, successorNode, edge); } } } return subgraph; } /** Creates a mutable copy of {@code graph} with the same nodes and edges. */ public static <N> MutableGraph<N> copyOf(Graph<N> graph) { MutableGraph<N> copy = GraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build(); for (N node : graph.nodes()) { copy.addNode(node); } for (EndpointPair<N> edge : graph.edges()) { copy.putEdge(edge.nodeU(), edge.nodeV()); } return copy; } /** Creates a mutable copy of {@code graph} with the same nodes, edges, and edge values. */ public static <N, V> MutableValueGraph<N, V> copyOf(ValueGraph<N, V> graph) { MutableValueGraph<N, V> copy = ValueGraphBuilder.from(graph).expectedNodeCount(graph.nodes().size()).build(); for (N node : graph.nodes()) { copy.addNode(node); } for (EndpointPair<N> edge : graph.edges()) { // requireNonNull is safe because the endpoint pair comes from the graph. copy.putEdgeValue( edge.nodeU(), edge.nodeV(), requireNonNull(graph.edgeValueOrDefault(edge.nodeU(), edge.nodeV(), null))); } return copy; } /** Creates a mutable copy of {@code network} with the same nodes and edges. */ public static <N, E> MutableNetwork<N, E> copyOf(Network<N, E> network) { MutableNetwork<N, E> copy = NetworkBuilder.from(network) .expectedNodeCount(network.nodes().size()) .expectedEdgeCount(network.edges().size()) .build(); for (N node : network.nodes()) { copy.addNode(node); } for (E edge : network.edges()) { EndpointPair<N> endpointPair = network.incidentNodes(edge); copy.addEdge(endpointPair.nodeU(), endpointPair.nodeV(), edge); } return copy; } @CanIgnoreReturnValue static int checkNonNegative(int value) { checkArgument(value >= 0, "Not true that %s is non-negative.", value); return value; } @CanIgnoreReturnValue static long checkNonNegative(long value) { checkArgument(value >= 0, "Not true that %s is non-negative.", value); return value; } @CanIgnoreReturnValue static int checkPositive(int value) { checkArgument(value > 0, "Not true that %s is positive.", value); return value; } @CanIgnoreReturnValue static long checkPositive(long value) { checkArgument(value > 0, "Not true that %s is positive.", value); return value; } /** * An enum representing the state of a node during DFS. {@code PENDING} means that the node is on * the stack of the DFS, while {@code COMPLETE} means that the node and all its successors have * been already explored. Any node that has not been explored will not have a state at all. */ private enum NodeVisitState { PENDING, COMPLETE } }
google/guava
guava/src/com/google/common/graph/Graphs.java
232
// 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 package com.google.protobuf; import static com.google.protobuf.UnsafeUtil.addressOffset; import static com.google.protobuf.UnsafeUtil.hasUnsafeArrayOperations; import static com.google.protobuf.UnsafeUtil.hasUnsafeByteBufferOperations; import static java.lang.Character.MAX_SURROGATE; import static java.lang.Character.MIN_HIGH_SURROGATE; import static java.lang.Character.MIN_LOW_SURROGATE; import static java.lang.Character.MIN_SUPPLEMENTARY_CODE_POINT; import static java.lang.Character.MIN_SURROGATE; import static java.lang.Character.isSurrogatePair; import static java.lang.Character.toCodePoint; import java.nio.ByteBuffer; import java.util.Arrays; /** * A set of low-level, high-performance static utility methods related to the UTF-8 character * encoding. This class has no dependencies outside of the core JDK libraries. * * <p>There are several variants of UTF-8. The one implemented by this class is the restricted * definition of UTF-8 introduced in Unicode 3.1, which mandates the rejection of "overlong" byte * sequences as well as rejection of 3-byte surrogate codepoint byte sequences. Note that the UTF-8 * decoder included in Oracle's JDK has been modified to also reject "overlong" byte sequences, but * (as of 2011) still accepts 3-byte surrogate codepoint byte sequences. * * <p>The byte sequences considered valid by this class are exactly those that can be roundtrip * converted to Strings and back to bytes using the UTF-8 charset, without loss: * * <pre>{@code * Arrays.equals(bytes, new String(bytes, Internal.UTF_8).getBytes(Internal.UTF_8)) * }</pre> * * <p>See the Unicode Standard,</br> Table 3-6. <em>UTF-8 Bit Distribution</em>,</br> Table 3-7. * <em>Well Formed UTF-8 Byte Sequences</em>. * * <p>This class supports decoding of partial byte sequences, so that the bytes in a complete UTF-8 * byte sequence can be stored in multiple segments. Methods typically return {@link #MALFORMED} if * the partial byte sequence is definitely not well-formed; {@link #COMPLETE} if it is well-formed * in the absence of additional input; or, if the byte sequence apparently terminated in the middle * of a character, an opaque integer "state" value containing enough information to decode the * character when passed to a subsequent invocation of a partial decoding method. * * @author [email protected] (Martin Buchholz) */ // TODO: Copy changes in this class back to Guava final class Utf8 { /** * UTF-8 is a runtime hot spot so we attempt to provide heavily optimized implementations * depending on what is available on the platform. The processor is the platform-optimized * delegate for which all methods are delegated directly to. */ private static final Processor processor = (UnsafeProcessor.isAvailable() && !Android.isOnAndroidDevice()) ? new UnsafeProcessor() : new SafeProcessor(); /** * A mask used when performing unsafe reads to determine if a long value contains any non-ASCII * characters (i.e. any byte >= 0x80). */ private static final long ASCII_MASK_LONG = 0x8080808080808080L; /** * Maximum number of bytes per Java UTF-16 char in UTF-8. * * @see java.nio.charset.CharsetEncoder#maxBytesPerChar() */ static final int MAX_BYTES_PER_CHAR = 3; /** * State value indicating that the byte sequence is well-formed and complete (no further bytes are * needed to complete a character). */ static final int COMPLETE = 0; /** State value indicating that the byte sequence is definitely not well-formed. */ static final int MALFORMED = -1; /** * Used by {@code Unsafe} UTF-8 string validation logic to determine the minimum string length * above which to employ an optimized algorithm for counting ASCII characters. The reason for this * threshold is that for small strings, the optimization may not be beneficial or may even * negatively impact performance since it requires additional logic to avoid unaligned reads (when * calling {@code Unsafe.getLong}). This threshold guarantees that even if the initial offset is * unaligned, we're guaranteed to make at least one call to {@code Unsafe.getLong()} which * provides a performance improvement that entirely subsumes the cost of the additional logic. */ private static final int UNSAFE_COUNT_ASCII_THRESHOLD = 16; // Other state values include the partial bytes of the incomplete // character to be decoded in the simplest way: we pack the bytes // into the state int in little-endian order. For example: // // int state = byte1 ^ (byte2 << 8) ^ (byte3 << 16); // // Such a state is unpacked thus (note the ~ operation for byte2 to // undo byte1's sign-extension bits): // // int byte1 = (byte) state; // int byte2 = (byte) ~(state >> 8); // int byte3 = (byte) (state >> 16); // // We cannot store a zero byte in the state because it would be // indistinguishable from the absence of a byte. But we don't need // to, because partial bytes must always be negative. When building // a state, we ensure that byte1 is negative and subsequent bytes // are valid trailing bytes. /** * Returns {@code true} if the given byte array is a well-formed UTF-8 byte sequence. * * <p>This is a convenience method, equivalent to a call to {@code isValidUtf8(bytes, 0, * bytes.length)}. */ static boolean isValidUtf8(byte[] bytes) { return processor.isValidUtf8(bytes, 0, bytes.length); } /** * Returns {@code true} if the given byte array slice is a well-formed UTF-8 byte sequence. The * range of bytes to be checked extends from index {@code index}, inclusive, to {@code limit}, * exclusive. * * <p>This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit) * == Utf8.COMPLETE}. */ static boolean isValidUtf8(byte[] bytes, int index, int limit) { return processor.isValidUtf8(bytes, index, limit); } /** * Tells whether the given byte array slice is a well-formed, malformed, or incomplete UTF-8 byte * sequence. The range of bytes to be checked extends from index {@code index}, inclusive, to * {@code limit}, exclusive. * * @param state either {@link Utf8#COMPLETE} (if this is the initial decoding operation) or the * value returned from a call to a partial decoding method for the previous bytes * @return {@link #MALFORMED} if the partial byte sequence is definitely not well-formed, {@link * #COMPLETE} if it is well-formed (no additional input needed), or if the byte sequence is * "incomplete", i.e. apparently terminated in the middle of a character, an opaque integer * "state" value containing enough information to decode the character when passed to a * subsequent invocation of a partial decoding method. */ static int partialIsValidUtf8(int state, byte[] bytes, int index, int limit) { return processor.partialIsValidUtf8(state, bytes, index, limit); } private static int incompleteStateFor(int byte1) { return (byte1 > (byte) 0xF4) ? MALFORMED : byte1; } private static int incompleteStateFor(int byte1, int byte2) { return (byte1 > (byte) 0xF4 || byte2 > (byte) 0xBF) ? MALFORMED : byte1 ^ (byte2 << 8); } private static int incompleteStateFor(int byte1, int byte2, int byte3) { return (byte1 > (byte) 0xF4 || byte2 > (byte) 0xBF || byte3 > (byte) 0xBF) ? MALFORMED : byte1 ^ (byte2 << 8) ^ (byte3 << 16); } private static int incompleteStateFor(byte[] bytes, int index, int limit) { int byte1 = bytes[index - 1]; switch (limit - index) { case 0: return incompleteStateFor(byte1); case 1: return incompleteStateFor(byte1, bytes[index]); case 2: return incompleteStateFor(byte1, bytes[index], bytes[index + 1]); default: throw new AssertionError(); } } private static int incompleteStateFor( final ByteBuffer buffer, final int byte1, final int index, final int remaining) { switch (remaining) { case 0: return incompleteStateFor(byte1); case 1: return incompleteStateFor(byte1, buffer.get(index)); case 2: return incompleteStateFor(byte1, buffer.get(index), buffer.get(index + 1)); default: throw new AssertionError(); } } // These UTF-8 handling methods are copied from Guava's Utf8 class with a modification to throw // a protocol buffer local exception. This exception is then caught in CodedOutputStream so it can // fallback to more lenient behavior. static class UnpairedSurrogateException extends IllegalArgumentException { UnpairedSurrogateException(int index, int length) { super("Unpaired surrogate at index " + index + " of " + length); } } /** * Returns the number of bytes in the UTF-8-encoded form of {@code sequence}. For a string, this * method is equivalent to {@code string.getBytes(UTF_8).length}, but is more efficient in both * time and space. * * @throws IllegalArgumentException if {@code sequence} contains ill-formed UTF-16 (unpaired * surrogates) */ static int encodedLength(String string) { // Warning to maintainers: this implementation is highly optimized. int utf16Length = string.length(); int utf8Length = utf16Length; int i = 0; // This loop optimizes for pure ASCII. while (i < utf16Length && string.charAt(i) < 0x80) { i++; } // This loop optimizes for chars less than 0x800. for (; i < utf16Length; i++) { char c = string.charAt(i); if (c < 0x800) { utf8Length += ((0x7f - c) >>> 31); // branch free! } else { utf8Length += encodedLengthGeneral(string, i); break; } } if (utf8Length < utf16Length) { // Necessary and sufficient condition for overflow because of maximum 3x expansion throw new IllegalArgumentException( "UTF-8 length does not fit in int: " + (utf8Length + (1L << 32))); } return utf8Length; } private static int encodedLengthGeneral(String string, int start) { int utf16Length = string.length(); int utf8Length = 0; for (int i = start; i < utf16Length; i++) { char c = string.charAt(i); if (c < 0x800) { utf8Length += (0x7f - c) >>> 31; // branch free! } else { utf8Length += 2; // jdk7+: if (Character.isSurrogate(c)) { if (Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE) { // Check that we have a well-formed surrogate pair. int cp = Character.codePointAt(string, i); if (cp < MIN_SUPPLEMENTARY_CODE_POINT) { throw new UnpairedSurrogateException(i, utf16Length); } i++; } } } return utf8Length; } static int encode(String in, byte[] out, int offset, int length) { return processor.encodeUtf8(in, out, offset, length); } // End Guava UTF-8 methods. /** * Determines if the given {@link ByteBuffer} is a valid UTF-8 string. * * <p>Selects an optimal algorithm based on the type of {@link ByteBuffer} (i.e. heap or direct) * and the capabilities of the platform. * * @param buffer the buffer to check. * @see Utf8#isValidUtf8(byte[], int, int) */ static boolean isValidUtf8(ByteBuffer buffer) { return processor.isValidUtf8(buffer, buffer.position(), buffer.remaining()); } /** * Determines if the given {@link ByteBuffer} is a partially valid UTF-8 string. * * <p>Selects an optimal algorithm based on the type of {@link ByteBuffer} (i.e. heap or direct) * and the capabilities of the platform. * * @param buffer the buffer to check. * @see Utf8#partialIsValidUtf8(int, byte[], int, int) */ static int partialIsValidUtf8(int state, ByteBuffer buffer, int index, int limit) { return processor.partialIsValidUtf8(state, buffer, index, limit); } /** * Decodes the given UTF-8 portion of the {@link ByteBuffer} into a {@link String}. * * @throws InvalidProtocolBufferException if the input is not valid UTF-8. */ static String decodeUtf8(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException { return processor.decodeUtf8(buffer, index, size); } /** * Decodes the given UTF-8 encoded byte array slice into a {@link String}. * * @throws InvalidProtocolBufferException if the input is not valid UTF-8. */ static String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException { return processor.decodeUtf8(bytes, index, size); } /** * Encodes the given characters to the target {@link ByteBuffer} using UTF-8 encoding. * * <p>Selects an optimal algorithm based on the type of {@link ByteBuffer} (i.e. heap or direct) * and the capabilities of the platform. * * @param in the source string to be encoded * @param out the target buffer to receive the encoded string. * @see Utf8#encode(String, byte[], int, int) */ static void encodeUtf8(String in, ByteBuffer out) { processor.encodeUtf8(in, out); } /** * Counts (approximately) the number of consecutive ASCII characters in the given buffer. The byte * order of the {@link ByteBuffer} does not matter, so performance can be improved if native byte * order is used (i.e. no byte-swapping in {@link ByteBuffer#getLong(int)}). * * @param buffer the buffer to be scanned for ASCII chars * @param index the starting index of the scan * @param limit the limit within buffer for the scan * @return the number of ASCII characters found. The stopping position will be at or before the * first non-ASCII byte. */ private static int estimateConsecutiveAscii(ByteBuffer buffer, int index, int limit) { int i = index; final int lim = limit - 7; // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). // To speed things up further, we're reading longs instead of bytes so we use a mask to // determine if any byte in the current long is non-ASCII. for (; i < lim && (buffer.getLong(i) & ASCII_MASK_LONG) == 0; i += 8) {} return i - index; } /** A processor of UTF-8 strings, providing methods for checking validity and encoding. */ // TODO: Add support for Memory/MemoryBlock on Android. abstract static class Processor { /** * Returns {@code true} if the given byte array slice is a well-formed UTF-8 byte sequence. The * range of bytes to be checked extends from index {@code index}, inclusive, to {@code limit}, * exclusive. * * <p>This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit) * == Utf8.COMPLETE}. */ final boolean isValidUtf8(byte[] bytes, int index, int limit) { return partialIsValidUtf8(COMPLETE, bytes, index, limit) == COMPLETE; } /** * Tells whether the given byte array slice is a well-formed, malformed, or incomplete UTF-8 * byte sequence. The range of bytes to be checked extends from index {@code index}, inclusive, * to {@code limit}, exclusive. * * @param state either {@link Utf8#COMPLETE} (if this is the initial decoding operation) or the * value returned from a call to a partial decoding method for the previous bytes * @return {@link #MALFORMED} if the partial byte sequence is definitely not well-formed, {@link * #COMPLETE} if it is well-formed (no additional input needed), or if the byte sequence is * "incomplete", i.e. apparently terminated in the middle of a character, an opaque integer * "state" value containing enough information to decode the character when passed to a * subsequent invocation of a partial decoding method. */ abstract int partialIsValidUtf8(int state, byte[] bytes, int index, int limit); /** * Returns {@code true} if the given portion of the {@link ByteBuffer} is a well-formed UTF-8 * byte sequence. The range of bytes to be checked extends from index {@code index}, inclusive, * to {@code limit}, exclusive. * * <p>This is a convenience method, equivalent to {@code partialIsValidUtf8(bytes, index, limit) * == Utf8.COMPLETE}. */ final boolean isValidUtf8(ByteBuffer buffer, int index, int limit) { return partialIsValidUtf8(COMPLETE, buffer, index, limit) == COMPLETE; } /** * Indicates whether or not the given buffer contains a valid UTF-8 string. * * @param buffer the buffer to check. * @return {@code true} if the given buffer contains a valid UTF-8 string. */ final int partialIsValidUtf8( final int state, final ByteBuffer buffer, int index, final int limit) { if (buffer.hasArray()) { final int offset = buffer.arrayOffset(); return partialIsValidUtf8(state, buffer.array(), offset + index, offset + limit); } else if (buffer.isDirect()) { return partialIsValidUtf8Direct(state, buffer, index, limit); } return partialIsValidUtf8Default(state, buffer, index, limit); } /** Performs validation for direct {@link ByteBuffer} instances. */ abstract int partialIsValidUtf8Direct( final int state, final ByteBuffer buffer, int index, final int limit); /** * Performs validation for {@link ByteBuffer} instances using the {@link ByteBuffer} API rather * than potentially faster approaches. This first completes validation for the current character * (provided by {@code state}) and then finishes validation for the sequence. */ final int partialIsValidUtf8Default( final int state, final ByteBuffer buffer, int index, final int limit) { if (state != COMPLETE) { // The previous decoding operation was incomplete (or malformed). // We look for a well-formed sequence consisting of bytes from // the previous decoding operation (stored in state) together // with bytes from the array slice. // // We expect such "straddler characters" to be rare. if (index >= limit) { // No bytes? No progress. return state; } byte byte1 = (byte) state; // byte1 is never ASCII. if (byte1 < (byte) 0xE0) { // two-byte form // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 // byte2 trailing-byte test || buffer.get(index++) > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // three-byte form // Get byte2 from saved state or array byte byte2 = (byte) ~(state >> 8); if (byte2 == 0) { byte2 = buffer.get(index++); if (index >= limit) { return incompleteStateFor(byte1, byte2); } } if (byte2 > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // illegal surrogate codepoint? || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || buffer.get(index++) > (byte) 0xBF) { return MALFORMED; } } else { // four-byte form // Get byte2 and byte3 from saved state or array byte byte2 = (byte) ~(state >> 8); byte byte3 = 0; if (byte2 == 0) { byte2 = buffer.get(index++); if (index >= limit) { return incompleteStateFor(byte1, byte2); } } else { byte3 = (byte) (state >> 16); } if (byte3 == 0) { byte3 = buffer.get(index++); if (index >= limit) { return incompleteStateFor(byte1, byte2, byte3); } } // If we were called with state == MALFORMED, then byte1 is 0xFF, // which never occurs in well-formed UTF-8, and so we will return // MALFORMED again below. if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || byte3 > (byte) 0xBF // byte4 trailing-byte test || buffer.get(index++) > (byte) 0xBF) { return MALFORMED; } } } // Finish validation for the sequence. return partialIsValidUtf8(buffer, index, limit); } /** * Performs validation for {@link ByteBuffer} instances using the {@link ByteBuffer} API rather * than potentially faster approaches. */ private static int partialIsValidUtf8(final ByteBuffer buffer, int index, final int limit) { index += estimateConsecutiveAscii(buffer, index, limit); for (; ; ) { // Optimize for interior runs of ASCII bytes. // TODO: Consider checking 8 bytes at a time after some threshold? // Maybe after seeing a few in a row that are ASCII, go back to fast mode? int byte1; do { if (index >= limit) { return COMPLETE; } } while ((byte1 = buffer.get(index++)) >= 0); // If we're here byte1 is not ASCII. Only need to handle 2-4 byte forms. if (byte1 < (byte) 0xE0) { // Two-byte form (110xxxxx 10xxxxxx) if (index >= limit) { // Incomplete sequence return byte1; } // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 || buffer.get(index) > (byte) 0xBF) { return MALFORMED; } index++; } else if (byte1 < (byte) 0xF0) { // Three-byte form (1110xxxx 10xxxxxx 10xxxxxx) if (index >= limit - 1) { // Incomplete sequence return incompleteStateFor(buffer, byte1, index, limit - index); } byte byte2 = buffer.get(index++); if (byte2 > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // check for illegal surrogate codepoints || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || buffer.get(index) > (byte) 0xBF) { return MALFORMED; } index++; } else { // Four-byte form (1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx) if (index >= limit - 2) { // Incomplete sequence return incompleteStateFor(buffer, byte1, index, limit - index); } // TODO: Consider using getInt() to improve performance. int byte2 = buffer.get(index++); if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || buffer.get(index++) > (byte) 0xBF // byte4 trailing-byte test || buffer.get(index++) > (byte) 0xBF) { return MALFORMED; } } } } /** * Decodes the given byte array slice into a {@link String}. * * @throws InvalidProtocolBufferException if the byte array slice is not valid UTF-8 */ abstract String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException; /** * Decodes the given portion of the {@link ByteBuffer} into a {@link String}. * * @throws InvalidProtocolBufferException if the portion of the buffer is not valid UTF-8 */ final String decodeUtf8(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException { if (buffer.hasArray()) { final int offset = buffer.arrayOffset(); return decodeUtf8(buffer.array(), offset + index, size); } else if (buffer.isDirect()) { return decodeUtf8Direct(buffer, index, size); } return decodeUtf8Default(buffer, index, size); } /** Decodes direct {@link ByteBuffer} instances into {@link String}. */ abstract String decodeUtf8Direct(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException; /** * Decodes {@link ByteBuffer} instances using the {@link ByteBuffer} API rather than potentially * faster approaches. */ final String decodeUtf8Default(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException { // Bitwise OR combines the sign bits so any negative value fails the check. if ((index | size | buffer.limit() - index - size) < 0) { throw new ArrayIndexOutOfBoundsException( String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), index, size)); } int offset = index; int limit = offset + size; // The longest possible resulting String is the same as the number of input bytes, when it is // all ASCII. For other cases, this over-allocates and we will truncate in the end. char[] resultArr = new char[size]; int resultPos = 0; // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). while (offset < limit) { byte b = buffer.get(offset); if (!DecodeUtil.isOneByte(b)) { break; } offset++; DecodeUtil.handleOneByte(b, resultArr, resultPos++); } while (offset < limit) { byte byte1 = buffer.get(offset++); if (DecodeUtil.isOneByte(byte1)) { DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); // It's common for there to be multiple ASCII characters in a run mixed in, so add an // extra optimized loop to take care of these runs. while (offset < limit) { byte b = buffer.get(offset); if (!DecodeUtil.isOneByte(b)) { break; } offset++; DecodeUtil.handleOneByte(b, resultArr, resultPos++); } } else if (DecodeUtil.isTwoBytes(byte1)) { if (offset >= limit) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleTwoBytes( byte1, /* byte2 */ buffer.get(offset++), resultArr, resultPos++); } else if (DecodeUtil.isThreeBytes(byte1)) { if (offset >= limit - 1) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleThreeBytes( byte1, /* byte2 */ buffer.get(offset++), /* byte3 */ buffer.get(offset++), resultArr, resultPos++); } else { if (offset >= limit - 2) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleFourBytes( byte1, /* byte2 */ buffer.get(offset++), /* byte3 */ buffer.get(offset++), /* byte4 */ buffer.get(offset++), resultArr, resultPos++); // 4-byte case requires two chars. resultPos++; } } return new String(resultArr, 0, resultPos); } /** * Encodes an input character sequence ({@code in}) to UTF-8 in the target array ({@code out}). * For a string, this method is similar to * * <pre>{@code * byte[] a = string.getBytes(UTF_8); * System.arraycopy(a, 0, bytes, offset, a.length); * return offset + a.length; * }</pre> * * but is more efficient in both time and space. One key difference is that this method requires * paired surrogates, and therefore does not support chunking. While {@code * String.getBytes(UTF_8)} replaces unpaired surrogates with the default replacement character, * this method throws {@link UnpairedSurrogateException}. * * <p>To ensure sufficient space in the output buffer, either call {@link #encodedLength} to * compute the exact amount needed, or leave room for {@code Utf8.MAX_BYTES_PER_CHAR * * sequence.length()}, which is the largest possible number of bytes that any input can be * encoded to. * * @param in the input character sequence to be encoded * @param out the target array * @param offset the starting offset in {@code bytes} to start writing at * @param length the length of the {@code bytes}, starting from {@code offset} * @throws UnpairedSurrogateException if {@code sequence} contains ill-formed UTF-16 (unpaired * surrogates) * @throws ArrayIndexOutOfBoundsException if {@code sequence} encoded in UTF-8 is longer than * {@code bytes.length - offset} * @return the new offset, equivalent to {@code offset + Utf8.encodedLength(sequence)} */ abstract int encodeUtf8(String in, byte[] out, int offset, int length); /** * Encodes an input character sequence ({@code in}) to UTF-8 in the target buffer ({@code out}). * Upon returning from this method, the {@code out} position will point to the position after * the last encoded byte. This method requires paired surrogates, and therefore does not support * chunking. * * <p>To ensure sufficient space in the output buffer, either call {@link #encodedLength} to * compute the exact amount needed, or leave room for {@code Utf8.MAX_BYTES_PER_CHAR * * in.length()}, which is the largest possible number of bytes that any input can be encoded to. * * @param in the source character sequence to be encoded * @param out the target buffer * @throws UnpairedSurrogateException if {@code in} contains ill-formed UTF-16 (unpaired * surrogates) * @throws ArrayIndexOutOfBoundsException if {@code in} encoded in UTF-8 is longer than {@code * out.remaining()} */ final void encodeUtf8(String in, ByteBuffer out) { if (out.hasArray()) { final int offset = out.arrayOffset(); int endIndex = Utf8.encode(in, out.array(), offset + out.position(), out.remaining()); Java8Compatibility.position(out, endIndex - offset); } else if (out.isDirect()) { encodeUtf8Direct(in, out); } else { encodeUtf8Default(in, out); } } /** Encodes the input character sequence to a direct {@link ByteBuffer} instance. */ abstract void encodeUtf8Direct(String in, ByteBuffer out); /** * Encodes the input character sequence to a {@link ByteBuffer} instance using the {@link * ByteBuffer} API, rather than potentially faster approaches. */ final void encodeUtf8Default(String in, ByteBuffer out) { final int inLength = in.length(); int outIx = out.position(); int inIx = 0; // Since ByteBuffer.putXXX() already checks boundaries for us, no need to explicitly check // access. Assume the buffer is big enough and let it handle the out of bounds exception // if it occurs. try { // Designed to take advantage of // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination for (char c; inIx < inLength && (c = in.charAt(inIx)) < 0x80; ++inIx) { out.put(outIx + inIx, (byte) c); } if (inIx == inLength) { // Successfully encoded the entire string. Java8Compatibility.position(out, outIx + inIx); return; } outIx += inIx; for (char c; inIx < inLength; ++inIx, ++outIx) { c = in.charAt(inIx); if (c < 0x80) { // One byte (0xxx xxxx) out.put(outIx, (byte) c); } else if (c < 0x800) { // Two bytes (110x xxxx 10xx xxxx) // Benchmarks show put performs better than putShort here (for HotSpot). out.put(outIx++, (byte) (0xC0 | (c >>> 6))); out.put(outIx, (byte) (0x80 | (0x3F & c))); } else if (c < MIN_SURROGATE || MAX_SURROGATE < c) { // Three bytes (1110 xxxx 10xx xxxx 10xx xxxx) // Maximum single-char code point is 0xFFFF, 16 bits. // Benchmarks show put performs better than putShort here (for HotSpot). out.put(outIx++, (byte) (0xE0 | (c >>> 12))); out.put(outIx++, (byte) (0x80 | (0x3F & (c >>> 6)))); out.put(outIx, (byte) (0x80 | (0x3F & c))); } else { // Four bytes (1111 xxxx 10xx xxxx 10xx xxxx 10xx xxxx) // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 // bytes final char low; if (inIx + 1 == inLength || !isSurrogatePair(c, (low = in.charAt(++inIx)))) { throw new UnpairedSurrogateException(inIx, inLength); } // TODO: Consider using putInt() to improve performance. int codePoint = toCodePoint(c, low); out.put(outIx++, (byte) ((0xF << 4) | (codePoint >>> 18))); out.put(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 12)))); out.put(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 6)))); out.put(outIx, (byte) (0x80 | (0x3F & codePoint))); } } // Successfully encoded the entire string. Java8Compatibility.position(out, outIx); } catch (IndexOutOfBoundsException e) { // TODO: Consider making the API throw IndexOutOfBoundsException instead. // If we failed in the outer ASCII loop, outIx will not have been updated. In this case, // use inIx to determine the bad write index. int badWriteIndex = out.position() + Math.max(inIx, outIx - out.position() + 1); throw new ArrayIndexOutOfBoundsException( "Failed writing " + in.charAt(inIx) + " at index " + badWriteIndex); } } } /** {@link Processor} implementation that does not use any {@code sun.misc.Unsafe} methods. */ static final class SafeProcessor extends Processor { @Override int partialIsValidUtf8(int state, byte[] bytes, int index, int limit) { if (state != COMPLETE) { // The previous decoding operation was incomplete (or malformed). // We look for a well-formed sequence consisting of bytes from // the previous decoding operation (stored in state) together // with bytes from the array slice. // // We expect such "straddler characters" to be rare. if (index >= limit) { // No bytes? No progress. return state; } int byte1 = (byte) state; // byte1 is never ASCII. if (byte1 < (byte) 0xE0) { // two-byte form // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 // byte2 trailing-byte test || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // three-byte form // Get byte2 from saved state or array int byte2 = (byte) ~(state >> 8); if (byte2 == 0) { byte2 = bytes[index++]; if (index >= limit) { return incompleteStateFor(byte1, byte2); } } if (byte2 > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // illegal surrogate codepoint? || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } else { // four-byte form // Get byte2 and byte3 from saved state or array int byte2 = (byte) ~(state >> 8); int byte3 = 0; if (byte2 == 0) { byte2 = bytes[index++]; if (index >= limit) { return incompleteStateFor(byte1, byte2); } } else { byte3 = (byte) (state >> 16); } if (byte3 == 0) { byte3 = bytes[index++]; if (index >= limit) { return incompleteStateFor(byte1, byte2, byte3); } } // If we were called with state == MALFORMED, then byte1 is 0xFF, // which never occurs in well-formed UTF-8, and so we will return // MALFORMED again below. if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || byte3 > (byte) 0xBF // byte4 trailing-byte test || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } } return partialIsValidUtf8(bytes, index, limit); } @Override int partialIsValidUtf8Direct(int state, ByteBuffer buffer, int index, int limit) { // For safe processing, we have to use the ByteBuffer API. return partialIsValidUtf8Default(state, buffer, index, limit); } @Override String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException { // Bitwise OR combines the sign bits so any negative value fails the check. if ((index | size | bytes.length - index - size) < 0) { throw new ArrayIndexOutOfBoundsException( String.format("buffer length=%d, index=%d, size=%d", bytes.length, index, size)); } int offset = index; final int limit = offset + size; // The longest possible resulting String is the same as the number of input bytes, when it is // all ASCII. For other cases, this over-allocates and we will truncate in the end. char[] resultArr = new char[size]; int resultPos = 0; // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). while (offset < limit) { byte b = bytes[offset]; if (!DecodeUtil.isOneByte(b)) { break; } offset++; DecodeUtil.handleOneByte(b, resultArr, resultPos++); } while (offset < limit) { byte byte1 = bytes[offset++]; if (DecodeUtil.isOneByte(byte1)) { DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); // It's common for there to be multiple ASCII characters in a run mixed in, so add an // extra optimized loop to take care of these runs. while (offset < limit) { byte b = bytes[offset]; if (!DecodeUtil.isOneByte(b)) { break; } offset++; DecodeUtil.handleOneByte(b, resultArr, resultPos++); } } else if (DecodeUtil.isTwoBytes(byte1)) { if (offset >= limit) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleTwoBytes(byte1, /* byte2 */ bytes[offset++], resultArr, resultPos++); } else if (DecodeUtil.isThreeBytes(byte1)) { if (offset >= limit - 1) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleThreeBytes( byte1, /* byte2 */ bytes[offset++], /* byte3 */ bytes[offset++], resultArr, resultPos++); } else { if (offset >= limit - 2) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleFourBytes( byte1, /* byte2 */ bytes[offset++], /* byte3 */ bytes[offset++], /* byte4 */ bytes[offset++], resultArr, resultPos++); // 4-byte case requires two chars. resultPos++; } } return new String(resultArr, 0, resultPos); } @Override String decodeUtf8Direct(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException { // For safe processing, we have to use the ByteBufferAPI. return decodeUtf8Default(buffer, index, size); } @Override int encodeUtf8(String in, byte[] out, int offset, int length) { int utf16Length = in.length(); int j = offset; int i = 0; int limit = offset + length; // Designed to take advantage of // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination for (char c; i < utf16Length && i + j < limit && (c = in.charAt(i)) < 0x80; i++) { out[j + i] = (byte) c; } if (i == utf16Length) { return j + utf16Length; } j += i; for (char c; i < utf16Length; i++) { c = in.charAt(i); if (c < 0x80 && j < limit) { out[j++] = (byte) c; } else if (c < 0x800 && j <= limit - 2) { // 11 bits, two UTF-8 bytes out[j++] = (byte) ((0xF << 6) | (c >>> 6)); out[j++] = (byte) (0x80 | (0x3F & c)); } else if ((c < Character.MIN_SURROGATE || Character.MAX_SURROGATE < c) && j <= limit - 3) { // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes out[j++] = (byte) ((0xF << 5) | (c >>> 12)); out[j++] = (byte) (0x80 | (0x3F & (c >>> 6))); out[j++] = (byte) (0x80 | (0x3F & c)); } else if (j <= limit - 4) { // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, // four UTF-8 bytes final char low; if (i + 1 == in.length() || !Character.isSurrogatePair(c, (low = in.charAt(++i)))) { throw new UnpairedSurrogateException((i - 1), utf16Length); } int codePoint = Character.toCodePoint(c, low); out[j++] = (byte) ((0xF << 4) | (codePoint >>> 18)); out[j++] = (byte) (0x80 | (0x3F & (codePoint >>> 12))); out[j++] = (byte) (0x80 | (0x3F & (codePoint >>> 6))); out[j++] = (byte) (0x80 | (0x3F & codePoint)); } else { // If we are surrogates and we're not a surrogate pair, always throw an // UnpairedSurrogateException instead of an ArrayOutOfBoundsException. if ((Character.MIN_SURROGATE <= c && c <= Character.MAX_SURROGATE) && (i + 1 == in.length() || !Character.isSurrogatePair(c, in.charAt(i + 1)))) { throw new UnpairedSurrogateException(i, utf16Length); } throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + j); } } return j; } @Override void encodeUtf8Direct(String in, ByteBuffer out) { // For safe processing, we have to use the ByteBuffer API. encodeUtf8Default(in, out); } private static int partialIsValidUtf8(byte[] bytes, int index, int limit) { // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). while (index < limit && bytes[index] >= 0) { index++; } return (index >= limit) ? COMPLETE : partialIsValidUtf8NonAscii(bytes, index, limit); } private static int partialIsValidUtf8NonAscii(byte[] bytes, int index, int limit) { for (; ; ) { int byte1; int byte2; // Optimize for interior runs of ASCII bytes. do { if (index >= limit) { return COMPLETE; } } while ((byte1 = bytes[index++]) >= 0); if (byte1 < (byte) 0xE0) { // two-byte form if (index >= limit) { // Incomplete sequence return byte1; } // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // three-byte form if (index >= limit - 1) { // incomplete sequence return incompleteStateFor(bytes, index, limit); } if ((byte2 = bytes[index++]) > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // check for illegal surrogate codepoints || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } else { // four-byte form if (index >= limit - 2) { // incomplete sequence return incompleteStateFor(bytes, index, limit); } if ((byte2 = bytes[index++]) > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || bytes[index++] > (byte) 0xBF // byte4 trailing-byte test || bytes[index++] > (byte) 0xBF) { return MALFORMED; } } } } } /** {@link Processor} that uses {@code sun.misc.Unsafe} where possible to improve performance. */ static final class UnsafeProcessor extends Processor { /** Indicates whether or not all required unsafe operations are supported on this platform. */ static boolean isAvailable() { return hasUnsafeArrayOperations() && hasUnsafeByteBufferOperations(); } @Override int partialIsValidUtf8(int state, byte[] bytes, final int index, final int limit) { // Bitwise OR combines the sign bits so any negative value fails the check. if ((index | limit | bytes.length - limit) < 0) { throw new ArrayIndexOutOfBoundsException( String.format("Array length=%d, index=%d, limit=%d", bytes.length, index, limit)); } long offset = index; final long offsetLimit = limit; if (state != COMPLETE) { // The previous decoding operation was incomplete (or malformed). // We look for a well-formed sequence consisting of bytes from // the previous decoding operation (stored in state) together // with bytes from the array slice. // // We expect such "straddler characters" to be rare. if (offset >= offsetLimit) { // No bytes? No progress. return state; } int byte1 = (byte) state; // byte1 is never ASCII. if (byte1 < (byte) 0xE0) { // two-byte form // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 // byte2 trailing-byte test || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // three-byte form // Get byte2 from saved state or array int byte2 = (byte) ~(state >> 8); if (byte2 == 0) { byte2 = UnsafeUtil.getByte(bytes, offset++); if (offset >= offsetLimit) { return incompleteStateFor(byte1, byte2); } } if (byte2 > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // illegal surrogate codepoint? || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } else { // four-byte form // Get byte2 and byte3 from saved state or array int byte2 = (byte) ~(state >> 8); int byte3 = 0; if (byte2 == 0) { byte2 = UnsafeUtil.getByte(bytes, offset++); if (offset >= offsetLimit) { return incompleteStateFor(byte1, byte2); } } else { byte3 = (byte) (state >> 16); } if (byte3 == 0) { byte3 = UnsafeUtil.getByte(bytes, offset++); if (offset >= offsetLimit) { return incompleteStateFor(byte1, byte2, byte3); } } // If we were called with state == MALFORMED, then byte1 is 0xFF, // which never occurs in well-formed UTF-8, and so we will return // MALFORMED again below. if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || byte3 > (byte) 0xBF // byte4 trailing-byte test || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } } return partialIsValidUtf8(bytes, offset, (int) (offsetLimit - offset)); } @Override int partialIsValidUtf8Direct( final int state, ByteBuffer buffer, final int index, final int limit) { // Bitwise OR combines the sign bits so any negative value fails the check. if ((index | limit | buffer.limit() - limit) < 0) { throw new ArrayIndexOutOfBoundsException( String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), index, limit)); } long address = addressOffset(buffer) + index; final long addressLimit = address + (limit - index); if (state != COMPLETE) { // The previous decoding operation was incomplete (or malformed). // We look for a well-formed sequence consisting of bytes from // the previous decoding operation (stored in state) together // with bytes from the array slice. // // We expect such "straddler characters" to be rare. if (address >= addressLimit) { // No bytes? No progress. return state; } final int byte1 = (byte) state; // byte1 is never ASCII. if (byte1 < (byte) 0xE0) { // two-byte form // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 // byte2 trailing-byte test || UnsafeUtil.getByte(address++) > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // three-byte form // Get byte2 from saved state or array int byte2 = (byte) ~(state >> 8); if (byte2 == 0) { byte2 = UnsafeUtil.getByte(address++); if (address >= addressLimit) { return incompleteStateFor(byte1, byte2); } } if (byte2 > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // illegal surrogate codepoint? || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || UnsafeUtil.getByte(address++) > (byte) 0xBF) { return MALFORMED; } } else { // four-byte form // Get byte2 and byte3 from saved state or array int byte2 = (byte) ~(state >> 8); int byte3 = 0; if (byte2 == 0) { byte2 = UnsafeUtil.getByte(address++); if (address >= addressLimit) { return incompleteStateFor(byte1, byte2); } } else { byte3 = (byte) (state >> 16); } if (byte3 == 0) { byte3 = UnsafeUtil.getByte(address++); if (address >= addressLimit) { return incompleteStateFor(byte1, byte2, byte3); } } // If we were called with state == MALFORMED, then byte1 is 0xFF, // which never occurs in well-formed UTF-8, and so we will return // MALFORMED again below. if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || byte3 > (byte) 0xBF // byte4 trailing-byte test || UnsafeUtil.getByte(address++) > (byte) 0xBF) { return MALFORMED; } } } return partialIsValidUtf8(address, (int) (addressLimit - address)); } @Override String decodeUtf8(byte[] bytes, int index, int size) throws InvalidProtocolBufferException { String s = new String(bytes, index, size, Internal.UTF_8); // '\uFFFD' is the UTF-8 default replacement char, which illegal byte sequences get replaced // with. if (s.indexOf('\uFFFD') < 0) { return s; } // Since s contains '\uFFFD' there are 2 options: // 1) The byte array slice is invalid UTF-8. // 2) The byte array slice is valid UTF-8 and contains encodings for "\uFFFD". // To rule out (1), we encode s and compare it to the byte array slice. // If the byte array slice was invalid UTF-8, then we would get a different sequence of bytes. if (Arrays.equals( s.getBytes(Internal.UTF_8), Arrays.copyOfRange(bytes, index, index + size))) { return s; } throw InvalidProtocolBufferException.invalidUtf8(); } @Override String decodeUtf8Direct(ByteBuffer buffer, int index, int size) throws InvalidProtocolBufferException { // Bitwise OR combines the sign bits so any negative value fails the check. if ((index | size | buffer.limit() - index - size) < 0) { throw new ArrayIndexOutOfBoundsException( String.format("buffer limit=%d, index=%d, limit=%d", buffer.limit(), index, size)); } long address = UnsafeUtil.addressOffset(buffer) + index; final long addressLimit = address + size; // The longest possible resulting String is the same as the number of input bytes, when it is // all ASCII. For other cases, this over-allocates and we will truncate in the end. char[] resultArr = new char[size]; int resultPos = 0; // Optimize for 100% ASCII (Hotspot loves small simple top-level loops like this). // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). while (address < addressLimit) { byte b = UnsafeUtil.getByte(address); if (!DecodeUtil.isOneByte(b)) { break; } address++; DecodeUtil.handleOneByte(b, resultArr, resultPos++); } while (address < addressLimit) { byte byte1 = UnsafeUtil.getByte(address++); if (DecodeUtil.isOneByte(byte1)) { DecodeUtil.handleOneByte(byte1, resultArr, resultPos++); // It's common for there to be multiple ASCII characters in a run mixed in, so add an // extra optimized loop to take care of these runs. while (address < addressLimit) { byte b = UnsafeUtil.getByte(address); if (!DecodeUtil.isOneByte(b)) { break; } address++; DecodeUtil.handleOneByte(b, resultArr, resultPos++); } } else if (DecodeUtil.isTwoBytes(byte1)) { if (address >= addressLimit) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleTwoBytes( byte1, /* byte2 */ UnsafeUtil.getByte(address++), resultArr, resultPos++); } else if (DecodeUtil.isThreeBytes(byte1)) { if (address >= addressLimit - 1) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleThreeBytes( byte1, /* byte2 */ UnsafeUtil.getByte(address++), /* byte3 */ UnsafeUtil.getByte(address++), resultArr, resultPos++); } else { if (address >= addressLimit - 2) { throw InvalidProtocolBufferException.invalidUtf8(); } DecodeUtil.handleFourBytes( byte1, /* byte2 */ UnsafeUtil.getByte(address++), /* byte3 */ UnsafeUtil.getByte(address++), /* byte4 */ UnsafeUtil.getByte(address++), resultArr, resultPos++); // 4-byte case requires two chars. resultPos++; } } return new String(resultArr, 0, resultPos); } @Override int encodeUtf8(final String in, final byte[] out, final int offset, final int length) { long outIx = offset; final long outLimit = outIx + length; final int inLimit = in.length(); if (inLimit > length || out.length - length < offset) { // Not even enough room for an ASCII-encoded string. throw new ArrayIndexOutOfBoundsException( "Failed writing " + in.charAt(inLimit - 1) + " at index " + (offset + length)); } // Designed to take advantage of // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination int inIx = 0; for (char c; inIx < inLimit && (c = in.charAt(inIx)) < 0x80; ++inIx) { UnsafeUtil.putByte(out, outIx++, (byte) c); } if (inIx == inLimit) { // We're done, it was ASCII encoded. return (int) outIx; } for (char c; inIx < inLimit; ++inIx) { c = in.charAt(inIx); if (c < 0x80 && outIx < outLimit) { UnsafeUtil.putByte(out, outIx++, (byte) c); } else if (c < 0x800 && outIx <= outLimit - 2L) { // 11 bits, two UTF-8 bytes UnsafeUtil.putByte(out, outIx++, (byte) ((0xF << 6) | (c >>> 6))); UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & c))); } else if ((c < MIN_SURROGATE || MAX_SURROGATE < c) && outIx <= outLimit - 3L) { // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes UnsafeUtil.putByte(out, outIx++, (byte) ((0xF << 5) | (c >>> 12))); UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & (c >>> 6)))); UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & c))); } else if (outIx <= outLimit - 4L) { // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 // bytes final char low; if (inIx + 1 == inLimit || !isSurrogatePair(c, (low = in.charAt(++inIx)))) { throw new UnpairedSurrogateException((inIx - 1), inLimit); } int codePoint = toCodePoint(c, low); UnsafeUtil.putByte(out, outIx++, (byte) ((0xF << 4) | (codePoint >>> 18))); UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 12)))); UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 6)))); UnsafeUtil.putByte(out, outIx++, (byte) (0x80 | (0x3F & codePoint))); } else { if ((MIN_SURROGATE <= c && c <= MAX_SURROGATE) && (inIx + 1 == inLimit || !isSurrogatePair(c, in.charAt(inIx + 1)))) { // We are surrogates and we're not a surrogate pair. throw new UnpairedSurrogateException(inIx, inLimit); } // Not enough space in the output buffer. throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + outIx); } } // All bytes have been encoded. return (int) outIx; } @Override void encodeUtf8Direct(String in, ByteBuffer out) { final long address = addressOffset(out); long outIx = address + out.position(); final long outLimit = address + out.limit(); final int inLimit = in.length(); if (inLimit > outLimit - outIx) { // Not even enough room for an ASCII-encoded string. throw new ArrayIndexOutOfBoundsException( "Failed writing " + in.charAt(inLimit - 1) + " at index " + out.limit()); } // Designed to take advantage of // https://wiki.openjdk.java.net/display/HotSpotInternals/RangeCheckElimination int inIx = 0; for (char c; inIx < inLimit && (c = in.charAt(inIx)) < 0x80; ++inIx) { UnsafeUtil.putByte(outIx++, (byte) c); } if (inIx == inLimit) { // We're done, it was ASCII encoded. Java8Compatibility.position(out, (int) (outIx - address)); return; } for (char c; inIx < inLimit; ++inIx) { c = in.charAt(inIx); if (c < 0x80 && outIx < outLimit) { UnsafeUtil.putByte(outIx++, (byte) c); } else if (c < 0x800 && outIx <= outLimit - 2L) { // 11 bits, two UTF-8 bytes UnsafeUtil.putByte(outIx++, (byte) ((0xF << 6) | (c >>> 6))); UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & c))); } else if ((c < MIN_SURROGATE || MAX_SURROGATE < c) && outIx <= outLimit - 3L) { // Maximum single-char code point is 0xFFFF, 16 bits, three UTF-8 bytes UnsafeUtil.putByte(outIx++, (byte) ((0xF << 5) | (c >>> 12))); UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & (c >>> 6)))); UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & c))); } else if (outIx <= outLimit - 4L) { // Minimum code point represented by a surrogate pair is 0x10000, 17 bits, four UTF-8 // bytes final char low; if (inIx + 1 == inLimit || !isSurrogatePair(c, (low = in.charAt(++inIx)))) { throw new UnpairedSurrogateException((inIx - 1), inLimit); } int codePoint = toCodePoint(c, low); UnsafeUtil.putByte(outIx++, (byte) ((0xF << 4) | (codePoint >>> 18))); UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 12)))); UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & (codePoint >>> 6)))); UnsafeUtil.putByte(outIx++, (byte) (0x80 | (0x3F & codePoint))); } else { if ((MIN_SURROGATE <= c && c <= MAX_SURROGATE) && (inIx + 1 == inLimit || !isSurrogatePair(c, in.charAt(inIx + 1)))) { // We are surrogates and we're not a surrogate pair. throw new UnpairedSurrogateException(inIx, inLimit); } // Not enough space in the output buffer. throw new ArrayIndexOutOfBoundsException("Failed writing " + c + " at index " + outIx); } } // All bytes have been encoded. Java8Compatibility.position(out, (int) (outIx - address)); } /** * Counts (approximately) the number of consecutive ASCII characters starting from the given * position, using the most efficient method available to the platform. * * @param bytes the array containing the character sequence * @param offset the offset position of the index (same as index + arrayBaseOffset) * @param maxChars the maximum number of characters to count * @return the number of ASCII characters found. The stopping position will be at or before the * first non-ASCII byte. */ private static int unsafeEstimateConsecutiveAscii( byte[] bytes, long offset, final int maxChars) { if (maxChars < UNSAFE_COUNT_ASCII_THRESHOLD) { // Don't bother with small strings. return 0; } // Read bytes until 8-byte aligned so that we can read longs in the loop below. // Byte arrays are already either 8 or 16-byte aligned, so we just need to make sure that // the index (relative to the start of the array) is also 8-byte aligned. We do this by // ANDing the index with 7 to determine the number of bytes that need to be read before // we're 8-byte aligned. final int unaligned = 8 - ((int) offset & 7); int i; for (i = 0; i < unaligned; i++) { if (UnsafeUtil.getByte(bytes, offset++) < 0) { return i; } } for (; i + 8 <= maxChars; i += 8) { if ((UnsafeUtil.getLong(bytes, UnsafeUtil.BYTE_ARRAY_BASE_OFFSET + offset) & ASCII_MASK_LONG) != 0L) { break; } offset += 8; } for (; i < maxChars; i++) { if (UnsafeUtil.getByte(bytes, offset++) < 0) { return i; } } return maxChars; } /** * Same as {@link Utf8#estimateConsecutiveAscii(ByteBuffer, int, int)} except that it uses the * most efficient method available to the platform. */ private static int unsafeEstimateConsecutiveAscii(long address, final int maxChars) { int remaining = maxChars; if (remaining < UNSAFE_COUNT_ASCII_THRESHOLD) { // Don't bother with small strings. return 0; } // Read bytes until 8-byte aligned so that we can read longs in the loop below. // This is equivalent to (8-address) mod 8, the number of bytes we need to read before we're // 8-byte aligned. final int unaligned = (int) (-address & 7); for (int j = unaligned; j > 0; j--) { if (UnsafeUtil.getByte(address++) < 0) { return unaligned - j; } } // This simple loop stops when we encounter a byte >= 0x80 (i.e. non-ASCII). // To speed things up further, we're reading longs instead of bytes so we use a mask to // determine if any byte in the current long is non-ASCII. remaining -= unaligned; for (; remaining >= 8 && (UnsafeUtil.getLong(address) & ASCII_MASK_LONG) == 0; address += 8, remaining -= 8) {} return maxChars - remaining; } private static int partialIsValidUtf8(final byte[] bytes, long offset, int remaining) { // Skip past ASCII characters as quickly as possible. final int skipped = unsafeEstimateConsecutiveAscii(bytes, offset, remaining); remaining -= skipped; offset += skipped; for (; ; ) { // Optimize for interior runs of ASCII bytes. // TODO: Consider checking 8 bytes at a time after some threshold? // Maybe after seeing a few in a row that are ASCII, go back to fast mode? int byte1 = 0; for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(bytes, offset++)) >= 0; --remaining) {} if (remaining == 0) { return COMPLETE; } remaining--; // If we're here byte1 is not ASCII. Only need to handle 2-4 byte forms. if (byte1 < (byte) 0xE0) { // Two-byte form (110xxxxx 10xxxxxx) if (remaining == 0) { // Incomplete sequence return byte1; } remaining--; // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // Three-byte form (1110xxxx 10xxxxxx 10xxxxxx) if (remaining < 2) { // Incomplete sequence return unsafeIncompleteStateFor(bytes, byte1, offset, remaining); } remaining -= 2; final int byte2; if ((byte2 = UnsafeUtil.getByte(bytes, offset++)) > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // check for illegal surrogate codepoints || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } else { // Four-byte form (1110xxxx 10xxxxxx 10xxxxxx 10xxxxxx) if (remaining < 3) { // Incomplete sequence return unsafeIncompleteStateFor(bytes, byte1, offset, remaining); } remaining -= 3; final int byte2; if ((byte2 = UnsafeUtil.getByte(bytes, offset++)) > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF // byte4 trailing-byte test || UnsafeUtil.getByte(bytes, offset++) > (byte) 0xBF) { return MALFORMED; } } } } private static int partialIsValidUtf8(long address, int remaining) { // Skip past ASCII characters as quickly as possible. final int skipped = unsafeEstimateConsecutiveAscii(address, remaining); address += skipped; remaining -= skipped; for (; ; ) { // Optimize for interior runs of ASCII bytes. // TODO: Consider checking 8 bytes at a time after some threshold? // Maybe after seeing a few in a row that are ASCII, go back to fast mode? int byte1 = 0; for (; remaining > 0 && (byte1 = UnsafeUtil.getByte(address++)) >= 0; --remaining) {} if (remaining == 0) { return COMPLETE; } remaining--; if (byte1 < (byte) 0xE0) { // Two-byte form if (remaining == 0) { // Incomplete sequence return byte1; } remaining--; // Simultaneously checks for illegal trailing-byte in // leading position and overlong 2-byte form. if (byte1 < (byte) 0xC2 || UnsafeUtil.getByte(address++) > (byte) 0xBF) { return MALFORMED; } } else if (byte1 < (byte) 0xF0) { // Three-byte form if (remaining < 2) { // Incomplete sequence return unsafeIncompleteStateFor(address, byte1, remaining); } remaining -= 2; final byte byte2 = UnsafeUtil.getByte(address++); if (byte2 > (byte) 0xBF // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // check for illegal surrogate codepoints || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) // byte3 trailing-byte test || UnsafeUtil.getByte(address++) > (byte) 0xBF) { return MALFORMED; } } else { // Four-byte form if (remaining < 3) { // Incomplete sequence return unsafeIncompleteStateFor(address, byte1, remaining); } remaining -= 3; final byte byte2 = UnsafeUtil.getByte(address++); if (byte2 > (byte) 0xBF // Check that 1 <= plane <= 16. Tricky optimized form of: // if (byte1 > (byte) 0xF4 || // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 // byte3 trailing-byte test || UnsafeUtil.getByte(address++) > (byte) 0xBF // byte4 trailing-byte test || UnsafeUtil.getByte(address++) > (byte) 0xBF) { return MALFORMED; } } } } private static int unsafeIncompleteStateFor( byte[] bytes, int byte1, long offset, int remaining) { switch (remaining) { case 0: return incompleteStateFor(byte1); case 1: return incompleteStateFor(byte1, UnsafeUtil.getByte(bytes, offset)); case 2: return incompleteStateFor( byte1, UnsafeUtil.getByte(bytes, offset), UnsafeUtil.getByte(bytes, offset + 1)); default: throw new AssertionError(); } } private static int unsafeIncompleteStateFor(long address, final int byte1, int remaining) { switch (remaining) { case 0: return incompleteStateFor(byte1); case 1: return incompleteStateFor(byte1, UnsafeUtil.getByte(address)); case 2: return incompleteStateFor( byte1, UnsafeUtil.getByte(address), UnsafeUtil.getByte(address + 1)); default: throw new AssertionError(); } } } /** * Utility methods for decoding bytes into {@link String}. Callers are responsible for extracting * bytes (possibly using Unsafe methods), and checking remaining bytes. All other UTF-8 validity * checks and codepoint conversion happen in this class. */ private static class DecodeUtil { /** Returns whether this is a single-byte codepoint (i.e., ASCII) with the form '0XXXXXXX'. */ private static boolean isOneByte(byte b) { return b >= 0; } /** * Returns whether this is a two-byte codepoint with the form '10XXXXXX' iff * {@link #isOneByte(byte)} is false. This private method works in the limited use in * this class where this method is only called when {@link #isOneByte(byte)} has already * returned false. It is not suitable for general or public use. */ private static boolean isTwoBytes(byte b) { return b < (byte) 0xE0; } /** * Returns whether this is a three-byte codepoint with the form '110XXXXX' iff * {@link #isOneByte(byte)} and {@link #isTwoBytes(byte)} are false. * This private method works in the limited use in * this class where this method is only called when {@link #isOneByte(byte)} an * {@link #isTwoBytes(byte)} have already returned false. It is not suitable for general * or public use. */ private static boolean isThreeBytes(byte b) { return b < (byte) 0xF0; } private static void handleOneByte(byte byte1, char[] resultArr, int resultPos) { resultArr[resultPos] = (char) byte1; } private static void handleTwoBytes(byte byte1, byte byte2, char[] resultArr, int resultPos) throws InvalidProtocolBufferException { // Simultaneously checks for illegal trailing-byte in leading position (<= '11000000') and // overlong 2-byte, '11000001'. if (byte1 < (byte) 0xC2 || isNotTrailingByte(byte2)) { throw InvalidProtocolBufferException.invalidUtf8(); } resultArr[resultPos] = (char) (((byte1 & 0x1F) << 6) | trailingByteValue(byte2)); } private static void handleThreeBytes( byte byte1, byte byte2, byte byte3, char[] resultArr, int resultPos) throws InvalidProtocolBufferException { if (isNotTrailingByte(byte2) // overlong? 5 most significant bits must not all be zero || (byte1 == (byte) 0xE0 && byte2 < (byte) 0xA0) // check for illegal surrogate codepoints || (byte1 == (byte) 0xED && byte2 >= (byte) 0xA0) || isNotTrailingByte(byte3)) { throw InvalidProtocolBufferException.invalidUtf8(); } resultArr[resultPos] = (char) (((byte1 & 0x0F) << 12) | (trailingByteValue(byte2) << 6) | trailingByteValue(byte3)); } private static void handleFourBytes( byte byte1, byte byte2, byte byte3, byte byte4, char[] resultArr, int resultPos) throws InvalidProtocolBufferException { if (isNotTrailingByte(byte2) // Check that 1 <= plane <= 16. Tricky optimized form of: // valid 4-byte leading byte? // if (byte1 > (byte) 0xF4 || // overlong? 4 most significant bits must not all be zero // byte1 == (byte) 0xF0 && byte2 < (byte) 0x90 || // codepoint larger than the highest code point (U+10FFFF)? // byte1 == (byte) 0xF4 && byte2 > (byte) 0x8F) || (((byte1 << 28) + (byte2 - (byte) 0x90)) >> 30) != 0 || isNotTrailingByte(byte3) || isNotTrailingByte(byte4)) { throw InvalidProtocolBufferException.invalidUtf8(); } int codepoint = ((byte1 & 0x07) << 18) | (trailingByteValue(byte2) << 12) | (trailingByteValue(byte3) << 6) | trailingByteValue(byte4); resultArr[resultPos] = DecodeUtil.highSurrogate(codepoint); resultArr[resultPos + 1] = DecodeUtil.lowSurrogate(codepoint); } /** Returns whether the byte is not a valid continuation of the form '10XXXXXX'. */ private static boolean isNotTrailingByte(byte b) { return b > (byte) 0xBF; } /** Returns the actual value of the trailing byte (removes the prefix '10') for composition. */ private static int trailingByteValue(byte b) { return b & 0x3F; } private static char highSurrogate(int codePoint) { return (char) ((MIN_HIGH_SURROGATE - (MIN_SUPPLEMENTARY_CODE_POINT >>> 10)) + (codePoint >>> 10)); } private static char lowSurrogate(int codePoint) { return (char) (MIN_LOW_SURROGATE + (codePoint & 0x3ff)); } } private Utf8() {} }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/Utf8.java
233
/* * 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.common.base.Ascii; import com.google.common.base.Optional; import com.google.common.base.Splitter; import com.google.common.collect.AbstractIterator; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.common.collect.Streams; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.MustBeClosed; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.io.UncheckedIOException; import java.io.Writer; import java.nio.charset.Charset; import java.util.Iterator; import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A readable source of characters, such as a text file. Unlike a {@link Reader}, a {@code * CharSource} is not an open, stateful stream of characters that can be read and closed. Instead, * it is an immutable <i>supplier</i> of {@code Reader} instances. * * <p>{@code CharSource} provides two kinds of methods: * * <ul> * <li><b>Methods that return a reader:</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 reader is closed. * <li><b>Convenience methods:</b> These are implementations of common operations that are * typically implemented by opening a reader using one of the methods in the first category, * doing something and finally closing the reader that was opened. * </ul> * * <p>Several methods in this class, such as {@link #readLines()}, break the contents of the source * into lines. Like {@link BufferedReader}, these methods break lines on any of {@code \n}, {@code * \r} or {@code \r\n}, do not include the line separator in each line and do not consider there to * be an empty line at the end if the contents are terminated with a line separator. * * <p>Any {@link ByteSource} containing text encoded with a specific {@linkplain Charset character * encoding} may be viewed as a {@code CharSource} using {@link ByteSource#asCharSource(Charset)}. * * <p><b>Note:</b> In general, {@code CharSource} is intended to be used for "file-like" sources * that provide readers that are: * * <ul> * <li><b>Finite:</b> Many operations, such as {@link #length()} and {@link #read()}, will either * block indefinitely or fail if the source creates an infinite reader. * <li><b>Non-destructive:</b> A <i>destructive</i> reader will consume or otherwise alter the * source as they are read from it. A source that provides such readers will not be reusable, * and operations that read from the stream (including {@link #length()}, in some * implementations) will prevent further operations from completing as expected. * </ul> * * @since 14.0 * @author Colin Decker */ @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public abstract class CharSource { /** Constructor for use by subclasses. */ protected CharSource() {} /** * Returns a {@link ByteSource} view of this char source that encodes chars read from this source * as bytes using the given {@link Charset}. * * <p>If {@link ByteSource#asCharSource} is called on the returned source with the same charset, * the default implementation of this method will ensure that the original {@code CharSource} is * returned, rather than round-trip encoding. Subclasses that override this method should behave * the same way. * * @since 20.0 */ public ByteSource asByteSource(Charset charset) { return new AsByteSource(charset); } /** * Opens a new {@link Reader} for reading from this source. This method returns a new, independent * reader each time it is called. * * <p>The caller is responsible for ensuring that the returned reader is closed. * * @throws IOException if an I/O error occurs while opening the reader */ public abstract Reader openStream() throws IOException; /** * Opens a new {@link BufferedReader} for reading from this source. This method returns a new, * independent reader each time it is called. * * <p>The caller is responsible for ensuring that the returned reader is closed. * * @throws IOException if an I/O error occurs while of opening the reader */ public BufferedReader openBufferedStream() throws IOException { Reader reader = openStream(); return (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader); } /** * Opens a new {@link Stream} for reading text one line at a time from this source. This method * returns a new, independent stream each time it is called. * * <p>The returned stream is lazy and only reads from the source in the terminal operation. If an * I/O error occurs while the stream is reading from the source or when the stream is closed, an * {@link UncheckedIOException} is thrown. * * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code * \n}. If the source's content does not end in a line termination sequence, it is treated as if * it does. * * <p>The caller is responsible for ensuring that the returned stream is closed. For example: * * <pre>{@code * try (Stream<String> lines = source.lines()) { * lines.map(...) * .filter(...) * .forEach(...); * } * }</pre> * * @throws IOException if an I/O error occurs while opening the stream * @since 22.0 */ @MustBeClosed public Stream<String> lines() throws IOException { BufferedReader reader = openBufferedStream(); return reader .lines() .onClose( () -> { try { reader.close(); } catch (IOException e) { throw new UncheckedIOException(e); } }); } /** * Returns the size of this source in chars, if the size can be easily determined without actually * opening the data stream. * * <p>The default implementation returns {@link Optional#absent}. Some sources, such as a {@code * CharSequence}, may return a non-absent value. Note that in such cases, it is <i>possible</i> * that this method will return a different number of chars than would be returned by reading all * of the chars. * * <p>Additionally, for mutable sources such as {@code StringBuilder}s, a subsequent read may * return a different number of chars if the contents are changed. * * @since 19.0 */ public Optional<Long> lengthIfKnown() { return Optional.absent(); } /** * Returns the length of this source in chars, even if doing so requires opening and traversing an * entire stream. To avoid a potentially expensive operation, see {@link #lengthIfKnown}. * * <p>The default implementation calls {@link #lengthIfKnown} and returns the value if present. If * absent, it will fall back to a heavyweight operation that will open a stream, {@link * Reader#skip(long) skip} to the end of the stream, and return the total number of chars that * were skipped. * * <p>Note that for sources that implement {@link #lengthIfKnown} to provide a more efficient * implementation, it is <i>possible</i> that this method will return a different number of chars * than would be returned by reading all of the chars. * * <p>In either case, for mutable sources such as files, a subsequent read may return a different * number of chars if the contents are changed. * * @throws IOException if an I/O error occurs while reading the length of this source * @since 19.0 */ public long length() throws IOException { Optional<Long> lengthIfKnown = lengthIfKnown(); if (lengthIfKnown.isPresent()) { return lengthIfKnown.get(); } Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return countBySkipping(reader); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } private long countBySkipping(Reader reader) throws IOException { long count = 0; long read; while ((read = reader.skip(Long.MAX_VALUE)) != 0) { count += read; } return count; } /** * Appends the contents of this source to the given {@link Appendable} (such as a {@link Writer}). * Does not close {@code appendable} if it is {@code Closeable}. * * @return the number of characters copied * @throws IOException if an I/O error occurs while reading from this source or writing to {@code * appendable} */ @CanIgnoreReturnValue public long copyTo(Appendable appendable) throws IOException { checkNotNull(appendable); Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return CharStreams.copy(reader, appendable); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Copies the contents of this source to the given sink. * * @return the number of characters copied * @throws IOException if an I/O error occurs while reading from this source or writing to {@code * sink} */ @CanIgnoreReturnValue public long copyTo(CharSink sink) throws IOException { checkNotNull(sink); Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); Writer writer = closer.register(sink.openStream()); return CharStreams.copy(reader, writer); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads the contents of this source as a string. * * @throws IOException if an I/O error occurs while reading from this source */ public String read() throws IOException { Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return CharStreams.toString(reader); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads the first line of this source as a string. Returns {@code null} if this source is empty. * * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code * \n}. If the source's content does not end in a line termination sequence, it is treated as if * it does. * * @throws IOException if an I/O error occurs while reading from this source */ @CheckForNull public String readFirstLine() throws IOException { Closer closer = Closer.create(); try { BufferedReader reader = closer.register(openBufferedStream()); return reader.readLine(); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads all the lines of this source as a list of strings. The returned list will be empty if * this source is empty. * * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code * \n}. If the source's content does not end in a line termination sequence, it is treated as if * it does. * * @throws IOException if an I/O error occurs while reading from this source */ public ImmutableList<String> readLines() throws IOException { Closer closer = Closer.create(); try { BufferedReader reader = closer.register(openBufferedStream()); List<String> result = Lists.newArrayList(); String line; while ((line = reader.readLine()) != null) { result.add(line); } return ImmutableList.copyOf(result); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads lines of text from this source, processing each line as it is read using the given {@link * LineProcessor processor}. Stops when all lines have been processed or the processor returns * {@code false} and returns the result produced by the processor. * * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code * \n}. If the source's content does not end in a line termination sequence, it is treated as if * it does. * * @throws IOException if an I/O error occurs while reading from this source or if {@code * processor} throws an {@code IOException} * @since 16.0 */ @CanIgnoreReturnValue // some processors won't return a useful result @ParametricNullness public <T extends @Nullable Object> T readLines(LineProcessor<T> processor) throws IOException { checkNotNull(processor); Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return CharStreams.readLines(reader, processor); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads all lines of text from this source, running the given {@code action} for each line as it * is read. * * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code * \n}. If the source's content does not end in a line termination sequence, it is treated as if * it does. * * @throws IOException if an I/O error occurs while reading from this source or if {@code action} * throws an {@code UncheckedIOException} * @since 22.0 */ public void forEachLine(Consumer<? super String> action) throws IOException { try (Stream<String> lines = lines()) { // The lines should be ordered regardless in most cases, but use forEachOrdered to be sure lines.forEachOrdered(action); } catch (UncheckedIOException e) { throw e.getCause(); } } /** * Returns whether the source has zero chars. The default implementation first checks {@link * #lengthIfKnown}, returning true if it's known to be zero and false if it's known to be * non-zero. If the length is not known, it falls back to opening a stream and checking for EOF. * * <p>Note that, in cases where {@code lengthIfKnown} returns zero, it is <i>possible</i> that * chars are actually available for reading. This means that a source may return {@code true} from * {@code isEmpty()} despite having readable content. * * @throws IOException if an I/O error occurs * @since 15.0 */ public boolean isEmpty() throws IOException { Optional<Long> lengthIfKnown = lengthIfKnown(); if (lengthIfKnown.isPresent()) { return lengthIfKnown.get() == 0L; } Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return reader.read() == -1; } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Concatenates multiple {@link CharSource} instances into a single source. Streams returned from * the source will contain the concatenated data from the streams of the underlying sources. * * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will * close the open underlying stream. * * @param sources the sources to concatenate * @return a {@code CharSource} containing the concatenated data * @since 15.0 */ public static CharSource concat(Iterable<? extends CharSource> sources) { return new ConcatenatedCharSource(sources); } /** * Concatenates multiple {@link CharSource} instances into a single source. Streams returned from * the source will contain the concatenated data from the streams of the underlying sources. * * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will * close the open underlying stream. * * <p>Note: The input {@code Iterator} will be copied to an {@code ImmutableList} when this method * is called. This will fail if the iterator is infinite and may cause problems if the iterator * eagerly fetches data for each source when iterated (rather than producing sources that only * load data through their streams). Prefer using the {@link #concat(Iterable)} overload if * possible. * * @param sources the sources to concatenate * @return a {@code CharSource} containing the concatenated data * @throws NullPointerException if any of {@code sources} is {@code null} * @since 15.0 */ public static CharSource concat(Iterator<? extends CharSource> sources) { return concat(ImmutableList.copyOf(sources)); } /** * Concatenates multiple {@link CharSource} instances into a single source. Streams returned from * the source will contain the concatenated data from the streams of the underlying sources. * * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will * close the open underlying stream. * * @param sources the sources to concatenate * @return a {@code CharSource} containing the concatenated data * @throws NullPointerException if any of {@code sources} is {@code null} * @since 15.0 */ public static CharSource concat(CharSource... sources) { return concat(ImmutableList.copyOf(sources)); } /** * Returns a view of the given character sequence as a {@link CharSource}. The behavior of the * returned {@code CharSource} and any {@code Reader} instances created by it is unspecified if * the {@code charSequence} is mutated while it is being read, so don't do that. * * @since 15.0 (since 14.0 as {@code CharStreams.asCharSource(String)}) */ public static CharSource wrap(CharSequence charSequence) { return charSequence instanceof String ? new StringCharSource((String) charSequence) : new CharSequenceCharSource(charSequence); } /** * Returns an immutable {@link CharSource} that contains no characters. * * @since 15.0 */ public static CharSource empty() { return EmptyCharSource.INSTANCE; } /** A byte source that reads chars from this source and encodes them as bytes using a charset. */ private final class AsByteSource extends ByteSource { final Charset charset; AsByteSource(Charset charset) { this.charset = checkNotNull(charset); } @Override public CharSource asCharSource(Charset charset) { if (charset.equals(this.charset)) { return CharSource.this; } return super.asCharSource(charset); } @Override public InputStream openStream() throws IOException { return new ReaderInputStream(CharSource.this.openStream(), charset, 8192); } @Override public String toString() { return CharSource.this.toString() + ".asByteSource(" + charset + ")"; } } private static class CharSequenceCharSource extends CharSource { private static final Splitter LINE_SPLITTER = Splitter.onPattern("\r\n|\n|\r"); protected final CharSequence seq; protected CharSequenceCharSource(CharSequence seq) { this.seq = checkNotNull(seq); } @Override public Reader openStream() { return new CharSequenceReader(seq); } @Override public String read() { return seq.toString(); } @Override public boolean isEmpty() { return seq.length() == 0; } @Override public long length() { return seq.length(); } @Override public Optional<Long> lengthIfKnown() { return Optional.of((long) seq.length()); } /** * Returns an iterator over the lines in the string. If the string ends in a newline, a final * empty string is not included, to match the behavior of BufferedReader/LineReader.readLine(). */ private Iterator<String> linesIterator() { return new AbstractIterator<String>() { Iterator<String> lines = LINE_SPLITTER.split(seq).iterator(); @Override @CheckForNull protected String computeNext() { if (lines.hasNext()) { String next = lines.next(); // skip last line if it's empty if (lines.hasNext() || !next.isEmpty()) { return next; } } return endOfData(); } }; } @Override public Stream<String> lines() { return Streams.stream(linesIterator()); } @Override @CheckForNull public String readFirstLine() { Iterator<String> lines = linesIterator(); return lines.hasNext() ? lines.next() : null; } @Override public ImmutableList<String> readLines() { return ImmutableList.copyOf(linesIterator()); } @Override @ParametricNullness public <T extends @Nullable Object> T readLines(LineProcessor<T> processor) throws IOException { Iterator<String> lines = linesIterator(); while (lines.hasNext()) { if (!processor.processLine(lines.next())) { break; } } return processor.getResult(); } @Override public String toString() { return "CharSource.wrap(" + Ascii.truncate(seq, 30, "...") + ")"; } } /** * Subclass specialized for string instances. * * <p>Since Strings are immutable and built into the jdk we can optimize some operations * * <ul> * <li>use {@link StringReader} instead of {@link CharSequenceReader}. It is faster since it can * use {@link String#getChars(int, int, char[], int)} instead of copying characters one by * one with {@link CharSequence#charAt(int)}. * <li>use {@link Appendable#append(CharSequence)} in {@link #copyTo(Appendable)} and {@link * #copyTo(CharSink)}. We know this is correct since strings are immutable and so the length * can't change, and it is faster because many writers and appendables are optimized for * appending string instances. * </ul> */ private static class StringCharSource extends CharSequenceCharSource { protected StringCharSource(String seq) { super(seq); } @Override public Reader openStream() { return new StringReader((String) seq); } @Override public long copyTo(Appendable appendable) throws IOException { appendable.append(seq); return seq.length(); } @Override public long copyTo(CharSink sink) throws IOException { checkNotNull(sink); Closer closer = Closer.create(); try { Writer writer = closer.register(sink.openStream()); writer.write((String) seq); return seq.length(); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } } private static final class EmptyCharSource extends StringCharSource { private static final EmptyCharSource INSTANCE = new EmptyCharSource(); private EmptyCharSource() { super(""); } @Override public String toString() { return "CharSource.empty()"; } } private static final class ConcatenatedCharSource extends CharSource { private final Iterable<? extends CharSource> sources; ConcatenatedCharSource(Iterable<? extends CharSource> sources) { this.sources = checkNotNull(sources); } @Override public Reader openStream() throws IOException { return new MultiReader(sources.iterator()); } @Override public boolean isEmpty() throws IOException { for (CharSource source : sources) { if (!source.isEmpty()) { return false; } } return true; } @Override public Optional<Long> lengthIfKnown() { long result = 0L; for (CharSource source : sources) { Optional<Long> lengthIfKnown = source.lengthIfKnown(); if (!lengthIfKnown.isPresent()) { return Optional.absent(); } result += lengthIfKnown.get(); } return Optional.of(result); } @Override public long length() throws IOException { long result = 0L; for (CharSource source : sources) { result += source.length(); } return result; } @Override public String toString() { return "CharSource.concat(" + sources + ")"; } } }
google/guava
guava/src/com/google/common/io/CharSource.java
235
/* * 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
236
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; import javax.annotation.CheckForNull; /** * Static utility methods pertaining to {@code char} primitives, that are not already found in * either {@link Character} or {@link Arrays}. * * <p>All the operations in this class treat {@code char} values strictly numerically; they are * neither Unicode-aware nor locale-dependent. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Chars { private Chars() {} /** * The number of bytes required to represent a primitive {@code char} value. * * <p><b>Java 8+ users:</b> use {@link Character#BYTES} instead. */ public static final int BYTES = Character.SIZE / Byte.SIZE; /** * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Character) * value).hashCode()}. * * <p><b>Java 8+ users:</b> use {@link Character#hashCode(char)} instead. * * @param value a primitive {@code char} value * @return a hash code for the value */ public static int hashCode(char value) { return value; } /** * Returns the {@code char} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code char} type * @return the {@code char} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link Character#MAX_VALUE} * or less than {@link Character#MIN_VALUE} */ public static char checkedCast(long value) { char result = (char) value; checkArgument(result == value, "Out of range: %s", value); return result; } /** * Returns the {@code char} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code char} if it is in the range of the {@code char} type, * {@link Character#MAX_VALUE} if it is too large, or {@link Character#MIN_VALUE} if it is too * small */ public static char saturatedCast(long value) { if (value > Character.MAX_VALUE) { return Character.MAX_VALUE; } if (value < Character.MIN_VALUE) { return Character.MIN_VALUE; } return (char) value; } /** * Compares the two specified {@code char} values. The sign of the value returned is the same as * that of {@code ((Character) a).compareTo(b)}. * * <p><b>Java 7+ users:</b> this method should be treated as deprecated; use the equivalent {@link * Character#compare} method instead. * * @param a the first {@code char} to compare * @param b the second {@code char} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(char a, char b) { return a - b; // safe due to restricted range } /** * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return {@code true} if {@code array[i] == target} for some value of {@code i} */ public static boolean contains(char[] array, char target) { for (char value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int indexOf(char[] array, char target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf(char[] array, char target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code target} within * {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, * i, i + target.length)} contains exactly the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(char[] array, char[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int lastIndexOf(char[] array, char target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf(char[] array, char target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code char} values * @return the value present in {@code array} that is less than or equal to every other value in * the array * @throws IllegalArgumentException if {@code array} is empty */ public static char min(char... array) { checkArgument(array.length > 0); char min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code char} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array * @throws IllegalArgumentException if {@code array} is empty */ public static char max(char... array) { checkArgument(array.length > 0); char max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the 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 char} 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 char constrainToRange(char value, char min, char max) { checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max); return value < min ? min : value < max ? value : max; } /** * Returns the values from each provided array combined into a single array. For example, {@code * concat(new char[] {a, b}, new char[] {}, new char[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code char} arrays * @return a single array containing all the values from the source arrays, in order */ public static char[] concat(char[]... arrays) { int length = 0; for (char[] array : arrays) { length += array.length; } char[] result = new char[length]; int pos = 0; for (char[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in a 2-element byte array; equivalent to * {@code ByteBuffer.allocate(2).putChar(value).array()}. For example, the input value {@code * '\\u5432'} would yield the byte array {@code {0x54, 0x32}}. * * <p>If you need to convert and concatenate several values (possibly even of different types), * use a shared {@link java.nio.ByteBuffer} instance, or use {@link * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. */ @GwtIncompatible // doesn't work public static byte[] toByteArray(char value) { return new byte[] {(byte) (value >> 8), (byte) value}; } /** * Returns the {@code char} value whose big-endian representation is stored in the first 2 bytes * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getChar()}. For example, the * input byte array {@code {0x54, 0x32}} would yield the {@code char} value {@code '\\u5432'}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more * flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements */ @GwtIncompatible // doesn't work public static char fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1]); } /** * Returns the {@code char} value whose byte representation is the given 2 bytes, in big-endian * order; equivalent to {@code Chars.fromByteArray(new byte[] {b1, b2})}. * * @since 7.0 */ @GwtIncompatible // doesn't work public static char fromBytes(byte b1, byte b2) { return (char) ((b1 << 8) | (b2 & 0xFF)); } /** * Returns an array containing the same values as {@code array}, but guaranteed to be of a * specified minimum length. If {@code array} already has a length of at least {@code minLength}, * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is * returned, containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative * @return an array containing the values of {@code array}, with guaranteed minimum length {@code * minLength} */ public static char[] ensureCapacity(char[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; } /** * Returns a string containing the supplied {@code char} values separated by {@code separator}. * For example, {@code join("-", '1', '2', '3')} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting string * (but not at the start or end) * @param array an array of {@code char} values, possibly empty */ public static String join(String separator, char... array) { checkNotNull(separator); int len = array.length; if (len == 0) { return ""; } StringBuilder builder = new StringBuilder(len + separator.length() * (len - 1)); builder.append(array[0]); for (int i = 1; i < len; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code char} arrays <a * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>; not advisable * for sorting user-visible strings as the ordering may not match the conventions of the user's * locale. That is, it compares, using {@link #compare(char, char)}), the first pair of values * that follow any common prefix, or when one array is a prefix of the other, treats the shorter * array as the lesser. For example, {@code [] < ['a'] < ['a', 'b'] < ['b']}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with {@link Arrays#equals(char[], * char[])}. * * @since 2.0 */ public static Comparator<char[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<char[]> { INSTANCE; @Override public int compare(char[] left, char[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Chars.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } @Override public String toString() { return "Chars.lexicographicalComparator()"; } } /** * Copies a collection of {@code Character} instances into a new array of primitive {@code char} * values. * * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. * Calling this method is as thread-safe as calling that method. * * @param collection a collection of {@code Character} objects * @return an array containing the same values as {@code collection}, in the same order, converted * to primitives * @throws NullPointerException if {@code collection} or any of its elements is null */ public static char[] toArray(Collection<Character> collection) { if (collection instanceof CharArrayAsList) { return ((CharArrayAsList) collection).toCharArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; char[] array = new char[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = (Character) checkNotNull(boxedArray[i]); } return array; } /** * Sorts the elements of {@code array} in descending order. * * @since 23.1 */ public static void sortDescending(char[] 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(char[] 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(Chars.asList(array))}, but is likely to be more efficient. * * @since 23.1 */ public static void reverse(char[] 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(Chars.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(char[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { char 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(Chars.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(char[] 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(Chars.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(char[] 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 a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to * set a value to {@code null} will result in a {@link NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of {@code Character} objects * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for * the returned list is unspecified. * * <p>The returned list is serializable. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Character> asList(char... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new CharArrayAsList(backingArray); } @GwtCompatible private static class CharArrayAsList extends AbstractList<Character> implements RandomAccess, Serializable { final char[] array; final int start; final int end; CharArrayAsList(char[] array) { this(array, 0, array.length); } CharArrayAsList(char[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Character get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(@CheckForNull Object target) { // Overridden to prevent a ton of boxing return (target instanceof Character) && Chars.indexOf(array, (Character) target, start, end) != -1; } @Override public int indexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Character) { int i = Chars.indexOf(array, (Character) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Character) { int i = Chars.lastIndexOf(array, (Character) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Character set(int index, Character element) { checkElementIndex(index, size()); char oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Character> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new CharArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(@CheckForNull Object object) { if (object == this) { return true; } if (object instanceof CharArrayAsList) { CharArrayAsList that = (CharArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Chars.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 3); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } char[] toCharArray() { return Arrays.copyOfRange(array, start, end); } private static final long serialVersionUID = 0; } }
google/guava
guava/src/com/google/common/primitives/Chars.java
237
/* * 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 static com.google.common.collect.CollectPreconditions.checkRemove; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import com.google.common.base.Predicate; import com.google.common.base.Predicates; import com.google.common.collect.Multiset.Entry; import com.google.common.math.IntMath; import com.google.common.primitives.Ints; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.concurrent.LazyInit; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.Set; import java.util.Spliterator; import java.util.function.Function; import java.util.function.Supplier; import java.util.function.ToIntFunction; import java.util.stream.Collector; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Provides static utility methods for creating and working with {@link Multiset} instances. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/CollectionUtilitiesExplained#multisets">{@code * Multisets}</a>. * * @author Kevin Bourrillion * @author Mike Bostock * @author Louis Wasserman * @since 2.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Multisets { private Multisets() {} /** * Returns a {@code Collector} that accumulates elements into a multiset created via the specified * {@code Supplier}, whose elements are the result of applying {@code elementFunction} to the * inputs, with counts equal to the result of applying {@code countFunction} to the inputs. * Elements are added in encounter order. * * <p>If the mapped elements contain duplicates (according to {@link Object#equals}), the element * will be added more than once, with the count summed over all appearances of the element. * * <p>Note that {@code stream.collect(toMultiset(function, e -> 1, supplier))} is equivalent to * {@code stream.map(function).collect(Collectors.toCollection(supplier))}. * * <p>To collect to an {@link ImmutableMultiset}, use {@link * ImmutableMultiset#toImmutableMultiset}. * * @since 22.0 */ public static <T extends @Nullable Object, E extends @Nullable Object, M extends Multiset<E>> Collector<T, ?, M> toMultiset( Function<? super T, E> elementFunction, ToIntFunction<? super T> countFunction, Supplier<M> multisetSupplier) { return CollectCollectors.toMultiset(elementFunction, countFunction, multisetSupplier); } /** * Returns an unmodifiable view of the specified multiset. Query operations on the returned * multiset "read through" to the specified multiset, and attempts to modify the returned multiset * result in an {@link UnsupportedOperationException}. * * <p>The returned multiset will be serializable if the specified multiset is serializable. * * @param multiset the multiset for which an unmodifiable view is to be generated * @return an unmodifiable view of the multiset */ public static <E extends @Nullable Object> Multiset<E> unmodifiableMultiset( Multiset<? extends E> multiset) { if (multiset instanceof UnmodifiableMultiset || multiset instanceof ImmutableMultiset) { @SuppressWarnings("unchecked") // Since it's unmodifiable, the covariant cast is safe Multiset<E> result = (Multiset<E>) multiset; return result; } return new UnmodifiableMultiset<>(checkNotNull(multiset)); } /** * Simply returns its argument. * * @deprecated no need to use this * @since 10.0 */ @Deprecated public static <E> Multiset<E> unmodifiableMultiset(ImmutableMultiset<E> multiset) { return checkNotNull(multiset); } static class UnmodifiableMultiset<E extends @Nullable Object> extends ForwardingMultiset<E> implements Serializable { final Multiset<? extends E> delegate; UnmodifiableMultiset(Multiset<? extends E> delegate) { this.delegate = delegate; } @SuppressWarnings("unchecked") @Override protected Multiset<E> delegate() { // This is safe because all non-covariant methods are overridden return (Multiset<E>) delegate; } @LazyInit @CheckForNull transient Set<E> elementSet; Set<E> createElementSet() { return Collections.<E>unmodifiableSet(delegate.elementSet()); } @Override public Set<E> elementSet() { Set<E> es = elementSet; return (es == null) ? elementSet = createElementSet() : es; } @LazyInit @CheckForNull transient Set<Multiset.Entry<E>> entrySet; @SuppressWarnings("unchecked") @Override public Set<Multiset.Entry<E>> entrySet() { Set<Multiset.Entry<E>> es = entrySet; return (es == null) // Safe because the returned set is made unmodifiable and Entry // itself is readonly ? entrySet = (Set) Collections.unmodifiableSet(delegate.entrySet()) : es; } @Override public Iterator<E> iterator() { return Iterators.<E>unmodifiableIterator(delegate.iterator()); } @Override public boolean add(@ParametricNullness E element) { throw new UnsupportedOperationException(); } @Override public int add(@ParametricNullness E element, int occurrences) { throw new UnsupportedOperationException(); } @Override public boolean addAll(Collection<? extends E> elementsToAdd) { throw new UnsupportedOperationException(); } @Override public boolean remove(@CheckForNull Object element) { throw new UnsupportedOperationException(); } @Override public int remove(@CheckForNull Object element, int occurrences) { throw new UnsupportedOperationException(); } @Override public boolean removeAll(Collection<?> elementsToRemove) { throw new UnsupportedOperationException(); } @Override public boolean removeIf(java.util.function.Predicate<? super E> filter) { throw new UnsupportedOperationException(); } @Override public boolean retainAll(Collection<?> elementsToRetain) { throw new UnsupportedOperationException(); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override public int setCount(@ParametricNullness E element, int count) { throw new UnsupportedOperationException(); } @Override public boolean setCount(@ParametricNullness E element, int oldCount, int newCount) { throw new UnsupportedOperationException(); } private static final long serialVersionUID = 0; } /** * Returns an unmodifiable view of the specified sorted multiset. Query operations on the returned * multiset "read through" to the specified multiset, and attempts to modify the returned multiset * result in an {@link UnsupportedOperationException}. * * <p>The returned multiset will be serializable if the specified multiset is serializable. * * @param sortedMultiset the sorted multiset for which an unmodifiable view is to be generated * @return an unmodifiable view of the multiset * @since 11.0 */ public static <E extends @Nullable Object> SortedMultiset<E> unmodifiableSortedMultiset( SortedMultiset<E> sortedMultiset) { // it's in its own file so it can be emulated for GWT return new UnmodifiableSortedMultiset<>(checkNotNull(sortedMultiset)); } /** * Returns an immutable multiset entry with the specified element and count. The entry will be * serializable if {@code e} is. * * @param e the element to be associated with the returned entry * @param n the count to be associated with the returned entry * @throws IllegalArgumentException if {@code n} is negative */ public static <E extends @Nullable Object> Multiset.Entry<E> immutableEntry( @ParametricNullness E e, int n) { return new ImmutableEntry<>(e, n); } static class ImmutableEntry<E extends @Nullable Object> extends AbstractEntry<E> implements Serializable { @ParametricNullness private final E element; private final int count; ImmutableEntry(@ParametricNullness E element, int count) { this.element = element; this.count = count; checkNonnegative(count, "count"); } @Override @ParametricNullness public final E getElement() { return element; } @Override public final int getCount() { return count; } @CheckForNull public ImmutableEntry<E> nextInBucket() { return null; } private static final long serialVersionUID = 0; } /** * Returns a view of the elements of {@code unfiltered} that satisfy a predicate. The returned * multiset is a live view of {@code unfiltered}; changes to one affect the other. * * <p>The resulting multiset's iterators, and those of its {@code entrySet()} and {@code * elementSet()}, do not support {@code remove()}. However, all other multiset methods supported * by {@code unfiltered} are supported by the returned multiset. When given an element that * doesn't satisfy the predicate, the multiset'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 multiset, only elements that satisfy the filter will be * removed from the underlying multiset. * * <p>The returned multiset isn't threadsafe or serializable, even if {@code unfiltered} is. * * <p>Many of the filtered multiset's methods, such as {@code size()}, iterate across every * element in the underlying multiset and determine which elements satisfy the filter. When a live * view is <i>not</i> needed, it may be faster to copy the returned multiset 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 */ public static <E extends @Nullable Object> Multiset<E> filter( Multiset<E> unfiltered, Predicate<? super E> predicate) { if (unfiltered instanceof FilteredMultiset) { // Support clear(), removeAll(), and retainAll() when filtering a filtered // collection. FilteredMultiset<E> filtered = (FilteredMultiset<E>) unfiltered; Predicate<E> combinedPredicate = Predicates.and(filtered.predicate, predicate); return new FilteredMultiset<>(filtered.unfiltered, combinedPredicate); } return new FilteredMultiset<>(unfiltered, predicate); } private static final class FilteredMultiset<E extends @Nullable Object> extends ViewMultiset<E> { final Multiset<E> unfiltered; final Predicate<? super E> predicate; FilteredMultiset(Multiset<E> unfiltered, Predicate<? super E> predicate) { this.unfiltered = checkNotNull(unfiltered); this.predicate = checkNotNull(predicate); } @Override public UnmodifiableIterator<E> iterator() { return Iterators.filter(unfiltered.iterator(), predicate); } @Override Set<E> createElementSet() { return Sets.filter(unfiltered.elementSet(), predicate); } @Override Iterator<E> elementIterator() { throw new AssertionError("should never be called"); } @Override Set<Entry<E>> createEntrySet() { return Sets.filter( unfiltered.entrySet(), new Predicate<Entry<E>>() { @Override public boolean apply(Entry<E> entry) { return predicate.apply(entry.getElement()); } }); } @Override Iterator<Entry<E>> entryIterator() { throw new AssertionError("should never be called"); } @Override public int count(@CheckForNull Object element) { int count = unfiltered.count(element); if (count > 0) { @SuppressWarnings("unchecked") // element is equal to an E E e = (E) element; return predicate.apply(e) ? count : 0; } return 0; } @Override public int add(@ParametricNullness E element, int occurrences) { checkArgument( predicate.apply(element), "Element %s does not match predicate %s", element, predicate); return unfiltered.add(element, occurrences); } @Override public int remove(@CheckForNull Object element, int occurrences) { checkNonnegative(occurrences, "occurrences"); if (occurrences == 0) { return count(element); } else { return contains(element) ? unfiltered.remove(element, occurrences) : 0; } } } /** * Returns the expected number of distinct elements given the specified elements. The number of * distinct elements is only computed if {@code elements} is an instance of {@code Multiset}; * otherwise the default value of 11 is returned. */ static int inferDistinctElements(Iterable<?> elements) { if (elements instanceof Multiset) { return ((Multiset<?>) elements).elementSet().size(); } return 11; // initial capacity will be rounded up to 16 } /** * Returns an unmodifiable view of the union of two multisets. In the returned multiset, the count * of each element is the <i>maximum</i> of its counts in the two backing multisets. The iteration * order of the returned multiset matches that of the element set of {@code multiset1} followed by * the members of the element set of {@code multiset2} that are not contained in {@code * multiset1}, with repeated occurrences of the same element appearing consecutively. * * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are). * * @since 14.0 */ public static <E extends @Nullable Object> Multiset<E> union( final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) { checkNotNull(multiset1); checkNotNull(multiset2); return new ViewMultiset<E>() { @Override public boolean contains(@CheckForNull Object element) { return multiset1.contains(element) || multiset2.contains(element); } @Override public boolean isEmpty() { return multiset1.isEmpty() && multiset2.isEmpty(); } @Override public int count(@CheckForNull Object element) { return Math.max(multiset1.count(element), multiset2.count(element)); } @Override Set<E> createElementSet() { return Sets.union(multiset1.elementSet(), multiset2.elementSet()); } @Override Iterator<E> elementIterator() { throw new AssertionError("should never be called"); } @Override Iterator<Entry<E>> entryIterator() { final Iterator<? extends Entry<? extends E>> iterator1 = multiset1.entrySet().iterator(); final Iterator<? extends Entry<? extends E>> iterator2 = multiset2.entrySet().iterator(); // TODO(lowasser): consider making the entries live views return new AbstractIterator<Entry<E>>() { @Override @CheckForNull protected Entry<E> computeNext() { if (iterator1.hasNext()) { Entry<? extends E> entry1 = iterator1.next(); E element = entry1.getElement(); int count = Math.max(entry1.getCount(), multiset2.count(element)); return immutableEntry(element, count); } while (iterator2.hasNext()) { Entry<? extends E> entry2 = iterator2.next(); E element = entry2.getElement(); if (!multiset1.contains(element)) { return immutableEntry(element, entry2.getCount()); } } return endOfData(); } }; } }; } /** * Returns an unmodifiable view of the intersection of two multisets. In the returned multiset, * the count of each element is the <i>minimum</i> of its counts in the two backing multisets, * with elements that would have a count of 0 not included. The iteration order of the returned * multiset matches that of the element set of {@code multiset1}, with repeated occurrences of the * same element appearing consecutively. * * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are). * * @since 2.0 */ public static <E extends @Nullable Object> Multiset<E> intersection( final Multiset<E> multiset1, final Multiset<?> multiset2) { checkNotNull(multiset1); checkNotNull(multiset2); return new ViewMultiset<E>() { @Override public int count(@CheckForNull Object element) { int count1 = multiset1.count(element); return (count1 == 0) ? 0 : Math.min(count1, multiset2.count(element)); } @Override Set<E> createElementSet() { return Sets.intersection(multiset1.elementSet(), multiset2.elementSet()); } @Override Iterator<E> elementIterator() { throw new AssertionError("should never be called"); } @Override Iterator<Entry<E>> entryIterator() { final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator(); // TODO(lowasser): consider making the entries live views return new AbstractIterator<Entry<E>>() { @Override @CheckForNull protected Entry<E> computeNext() { while (iterator1.hasNext()) { Entry<E> entry1 = iterator1.next(); E element = entry1.getElement(); int count = Math.min(entry1.getCount(), multiset2.count(element)); if (count > 0) { return immutableEntry(element, count); } } return endOfData(); } }; } }; } /** * Returns an unmodifiable view of the sum of two multisets. In the returned multiset, the count * of each element is the <i>sum</i> of its counts in the two backing multisets. The iteration * order of the returned multiset matches that of the element set of {@code multiset1} followed by * the members of the element set of {@code multiset2} that are not contained in {@code * multiset1}, with repeated occurrences of the same element appearing consecutively. * * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are). * * @since 14.0 */ public static <E extends @Nullable Object> Multiset<E> sum( final Multiset<? extends E> multiset1, final Multiset<? extends E> multiset2) { checkNotNull(multiset1); checkNotNull(multiset2); // TODO(lowasser): consider making the entries live views return new ViewMultiset<E>() { @Override public boolean contains(@CheckForNull Object element) { return multiset1.contains(element) || multiset2.contains(element); } @Override public boolean isEmpty() { return multiset1.isEmpty() && multiset2.isEmpty(); } @Override public int size() { return IntMath.saturatedAdd(multiset1.size(), multiset2.size()); } @Override public int count(@CheckForNull Object element) { return multiset1.count(element) + multiset2.count(element); } @Override Set<E> createElementSet() { return Sets.union(multiset1.elementSet(), multiset2.elementSet()); } @Override Iterator<E> elementIterator() { throw new AssertionError("should never be called"); } @Override Iterator<Entry<E>> entryIterator() { final Iterator<? extends Entry<? extends E>> iterator1 = multiset1.entrySet().iterator(); final Iterator<? extends Entry<? extends E>> iterator2 = multiset2.entrySet().iterator(); return new AbstractIterator<Entry<E>>() { @Override @CheckForNull protected Entry<E> computeNext() { if (iterator1.hasNext()) { Entry<? extends E> entry1 = iterator1.next(); E element = entry1.getElement(); int count = entry1.getCount() + multiset2.count(element); return immutableEntry(element, count); } while (iterator2.hasNext()) { Entry<? extends E> entry2 = iterator2.next(); E element = entry2.getElement(); if (!multiset1.contains(element)) { return immutableEntry(element, entry2.getCount()); } } return endOfData(); } }; } }; } /** * Returns an unmodifiable view of the difference of two multisets. In the returned multiset, the * count of each element is the result of the <i>zero-truncated subtraction</i> of its count in * the second multiset from its count in the first multiset, with elements that would have a count * of 0 not included. The iteration order of the returned multiset matches that of the element set * of {@code multiset1}, with repeated occurrences of the same element appearing consecutively. * * <p>Results are undefined if {@code multiset1} and {@code multiset2} are based on different * equivalence relations (as {@code HashMultiset} and {@code TreeMultiset} are). * * @since 14.0 */ public static <E extends @Nullable Object> Multiset<E> difference( final Multiset<E> multiset1, final Multiset<?> multiset2) { checkNotNull(multiset1); checkNotNull(multiset2); // TODO(lowasser): consider making the entries live views return new ViewMultiset<E>() { @Override public int count(@CheckForNull Object element) { int count1 = multiset1.count(element); return (count1 == 0) ? 0 : Math.max(0, count1 - multiset2.count(element)); } @Override public void clear() { throw new UnsupportedOperationException(); } @Override Iterator<E> elementIterator() { final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator(); return new AbstractIterator<E>() { @Override @CheckForNull protected E computeNext() { while (iterator1.hasNext()) { Entry<E> entry1 = iterator1.next(); E element = entry1.getElement(); if (entry1.getCount() > multiset2.count(element)) { return element; } } return endOfData(); } }; } @Override Iterator<Entry<E>> entryIterator() { final Iterator<Entry<E>> iterator1 = multiset1.entrySet().iterator(); return new AbstractIterator<Entry<E>>() { @Override @CheckForNull protected Entry<E> computeNext() { while (iterator1.hasNext()) { Entry<E> entry1 = iterator1.next(); E element = entry1.getElement(); int count = entry1.getCount() - multiset2.count(element); if (count > 0) { return immutableEntry(element, count); } } return endOfData(); } }; } @Override int distinctElements() { return Iterators.size(entryIterator()); } }; } /** * Returns {@code true} if {@code subMultiset.count(o) <= superMultiset.count(o)} for all {@code * o}. * * @since 10.0 */ @CanIgnoreReturnValue public static boolean containsOccurrences(Multiset<?> superMultiset, Multiset<?> subMultiset) { checkNotNull(superMultiset); checkNotNull(subMultiset); for (Entry<?> entry : subMultiset.entrySet()) { int superCount = superMultiset.count(entry.getElement()); if (superCount < entry.getCount()) { return false; } } return true; } /** * Modifies {@code multisetToModify} so that its count for an element {@code e} is at most {@code * multisetToRetain.count(e)}. * * <p>To be precise, {@code multisetToModify.count(e)} is set to {@code * Math.min(multisetToModify.count(e), multisetToRetain.count(e))}. This is similar to {@link * #intersection(Multiset, Multiset) intersection} {@code (multisetToModify, multisetToRetain)}, * but mutates {@code multisetToModify} instead of returning a view. * * <p>In contrast, {@code multisetToModify.retainAll(multisetToRetain)} keeps all occurrences of * elements that appear at all in {@code multisetToRetain}, and deletes all occurrences of all * other elements. * * @return {@code true} if {@code multisetToModify} was changed as a result of this operation * @since 10.0 */ @CanIgnoreReturnValue public static boolean retainOccurrences( Multiset<?> multisetToModify, Multiset<?> multisetToRetain) { return retainOccurrencesImpl(multisetToModify, multisetToRetain); } /** Delegate implementation which cares about the element type. */ private static <E extends @Nullable Object> boolean retainOccurrencesImpl( Multiset<E> multisetToModify, Multiset<?> occurrencesToRetain) { checkNotNull(multisetToModify); checkNotNull(occurrencesToRetain); // Avoiding ConcurrentModificationExceptions is tricky. Iterator<Entry<E>> entryIterator = multisetToModify.entrySet().iterator(); boolean changed = false; while (entryIterator.hasNext()) { Entry<E> entry = entryIterator.next(); int retainCount = occurrencesToRetain.count(entry.getElement()); if (retainCount == 0) { entryIterator.remove(); changed = true; } else if (retainCount < entry.getCount()) { multisetToModify.setCount(entry.getElement(), retainCount); changed = true; } } return changed; } /** * For each occurrence of an element {@code e} in {@code occurrencesToRemove}, removes one * occurrence of {@code e} in {@code multisetToModify}. * * <p>Equivalently, this method modifies {@code multisetToModify} so that {@code * multisetToModify.count(e)} is set to {@code Math.max(0, multisetToModify.count(e) - * Iterables.frequency(occurrencesToRemove, e))}. * * <p>This is <i>not</i> the same as {@code multisetToModify.} {@link Multiset#removeAll * removeAll}{@code (occurrencesToRemove)}, which removes all occurrences of elements that appear * in {@code occurrencesToRemove}. However, this operation <i>is</i> equivalent to, albeit * sometimes more efficient than, the following: * * <pre>{@code * for (E e : occurrencesToRemove) { * multisetToModify.remove(e); * } * }</pre> * * @return {@code true} if {@code multisetToModify} was changed as a result of this operation * @since 18.0 (present in 10.0 with a requirement that the second parameter be a {@code * Multiset}) */ @CanIgnoreReturnValue public static boolean removeOccurrences( Multiset<?> multisetToModify, Iterable<?> occurrencesToRemove) { if (occurrencesToRemove instanceof Multiset) { return removeOccurrences(multisetToModify, (Multiset<?>) occurrencesToRemove); } else { checkNotNull(multisetToModify); checkNotNull(occurrencesToRemove); boolean changed = false; for (Object o : occurrencesToRemove) { changed |= multisetToModify.remove(o); } return changed; } } /** * For each occurrence of an element {@code e} in {@code occurrencesToRemove}, removes one * occurrence of {@code e} in {@code multisetToModify}. * * <p>Equivalently, this method modifies {@code multisetToModify} so that {@code * multisetToModify.count(e)} is set to {@code Math.max(0, multisetToModify.count(e) - * occurrencesToRemove.count(e))}. * * <p>This is <i>not</i> the same as {@code multisetToModify.} {@link Multiset#removeAll * removeAll}{@code (occurrencesToRemove)}, which removes all occurrences of elements that appear * in {@code occurrencesToRemove}. However, this operation <i>is</i> equivalent to, albeit * sometimes more efficient than, the following: * * <pre>{@code * for (E e : occurrencesToRemove) { * multisetToModify.remove(e); * } * }</pre> * * @return {@code true} if {@code multisetToModify} was changed as a result of this operation * @since 10.0 (missing in 18.0 when only the overload taking an {@code Iterable} was present) */ @CanIgnoreReturnValue public static boolean removeOccurrences( Multiset<?> multisetToModify, Multiset<?> occurrencesToRemove) { checkNotNull(multisetToModify); checkNotNull(occurrencesToRemove); boolean changed = false; Iterator<? extends Entry<?>> entryIterator = multisetToModify.entrySet().iterator(); while (entryIterator.hasNext()) { Entry<?> entry = entryIterator.next(); int removeCount = occurrencesToRemove.count(entry.getElement()); if (removeCount >= entry.getCount()) { entryIterator.remove(); changed = true; } else if (removeCount > 0) { multisetToModify.remove(entry.getElement(), removeCount); changed = true; } } return changed; } /** * Implementation of the {@code equals}, {@code hashCode}, and {@code toString} methods of {@link * Multiset.Entry}. */ abstract static class AbstractEntry<E extends @Nullable Object> implements Multiset.Entry<E> { /** * Indicates whether an object equals this entry, following the behavior specified in {@link * Multiset.Entry#equals}. */ @Override public boolean equals(@CheckForNull Object object) { if (object instanceof Multiset.Entry) { Multiset.Entry<?> that = (Multiset.Entry<?>) object; return this.getCount() == that.getCount() && Objects.equal(this.getElement(), that.getElement()); } return false; } /** * Return this entry's hash code, following the behavior specified in {@link * Multiset.Entry#hashCode}. */ @Override public int hashCode() { E e = getElement(); return ((e == null) ? 0 : e.hashCode()) ^ getCount(); } /** * Returns a string representation of this multiset entry. The string representation consists of * the associated element if the associated count is one, and otherwise the associated element * followed by the characters " x " (space, x and space) followed by the count. Elements and * counts are converted to strings as by {@code String.valueOf}. */ @Override public String toString() { String text = String.valueOf(getElement()); int n = getCount(); return (n == 1) ? text : (text + " x " + n); } } /** An implementation of {@link Multiset#equals}. */ static boolean equalsImpl(Multiset<?> multiset, @CheckForNull Object object) { if (object == multiset) { return true; } if (object instanceof Multiset) { Multiset<?> that = (Multiset<?>) object; /* * We can't simply check whether the entry sets are equal, since that * approach fails when a TreeMultiset has a comparator that returns 0 * when passed unequal elements. */ if (multiset.size() != that.size() || multiset.entrySet().size() != that.entrySet().size()) { return false; } for (Entry<?> entry : that.entrySet()) { if (multiset.count(entry.getElement()) != entry.getCount()) { return false; } } return true; } return false; } /** An implementation of {@link Multiset#addAll}. */ static <E extends @Nullable Object> boolean addAllImpl( Multiset<E> self, Collection<? extends E> elements) { checkNotNull(self); checkNotNull(elements); if (elements instanceof Multiset) { return addAllImpl(self, cast(elements)); } else if (elements.isEmpty()) { return false; } else { return Iterators.addAll(self, elements.iterator()); } } /** A specialization of {@code addAllImpl} for when {@code elements} is itself a Multiset. */ private static <E extends @Nullable Object> boolean addAllImpl( Multiset<E> self, Multiset<? extends E> elements) { if (elements.isEmpty()) { return false; } elements.forEachEntry(self::add); return true; } /** An implementation of {@link Multiset#removeAll}. */ static boolean removeAllImpl(Multiset<?> self, Collection<?> elementsToRemove) { Collection<?> collection = (elementsToRemove instanceof Multiset) ? ((Multiset<?>) elementsToRemove).elementSet() : elementsToRemove; return self.elementSet().removeAll(collection); } /** An implementation of {@link Multiset#retainAll}. */ static boolean retainAllImpl(Multiset<?> self, Collection<?> elementsToRetain) { checkNotNull(elementsToRetain); Collection<?> collection = (elementsToRetain instanceof Multiset) ? ((Multiset<?>) elementsToRetain).elementSet() : elementsToRetain; return self.elementSet().retainAll(collection); } /** An implementation of {@link Multiset#setCount(Object, int)}. */ static <E extends @Nullable Object> int setCountImpl( Multiset<E> self, @ParametricNullness E element, int count) { checkNonnegative(count, "count"); int oldCount = self.count(element); int delta = count - oldCount; if (delta > 0) { self.add(element, delta); } else if (delta < 0) { self.remove(element, -delta); } return oldCount; } /** An implementation of {@link Multiset#setCount(Object, int, int)}. */ static <E extends @Nullable Object> boolean setCountImpl( Multiset<E> self, @ParametricNullness E element, int oldCount, int newCount) { checkNonnegative(oldCount, "oldCount"); checkNonnegative(newCount, "newCount"); if (self.count(element) == oldCount) { self.setCount(element, newCount); return true; } else { return false; } } static <E extends @Nullable Object> Iterator<E> elementIterator( Iterator<Entry<E>> entryIterator) { return new TransformedIterator<Entry<E>, E>(entryIterator) { @Override @ParametricNullness E transform(Entry<E> entry) { return entry.getElement(); } }; } abstract static class ElementSet<E extends @Nullable Object> extends Sets.ImprovedAbstractSet<E> { abstract Multiset<E> multiset(); @Override public void clear() { multiset().clear(); } @Override public boolean contains(@CheckForNull Object o) { return multiset().contains(o); } @Override public boolean containsAll(Collection<?> c) { return multiset().containsAll(c); } @Override public boolean isEmpty() { return multiset().isEmpty(); } @Override public abstract Iterator<E> iterator(); @Override public boolean remove(@CheckForNull Object o) { return multiset().remove(o, Integer.MAX_VALUE) > 0; } @Override public int size() { return multiset().entrySet().size(); } } abstract static class EntrySet<E extends @Nullable Object> extends Sets.ImprovedAbstractSet<Entry<E>> { abstract Multiset<E> multiset(); @Override public boolean contains(@CheckForNull Object o) { if (o instanceof Entry) { Entry<?> entry = (Entry<?>) o; if (entry.getCount() <= 0) { return false; } int count = multiset().count(entry.getElement()); return count == entry.getCount(); } return false; } @Override public boolean remove(@CheckForNull Object object) { if (object instanceof Multiset.Entry) { Entry<?> entry = (Entry<?>) object; Object element = entry.getElement(); int entryCount = entry.getCount(); if (entryCount != 0) { // Safe as long as we never add a new entry, which we won't. // (Presumably it can still throw CCE/NPE but only if the underlying Multiset does.) @SuppressWarnings({"unchecked", "nullness"}) Multiset<@Nullable Object> multiset = (Multiset<@Nullable Object>) multiset(); return multiset.setCount(element, entryCount, 0); } } return false; } @Override public void clear() { multiset().clear(); } } /** An implementation of {@link Multiset#iterator}. */ static <E extends @Nullable Object> Iterator<E> iteratorImpl(Multiset<E> multiset) { return new MultisetIteratorImpl<>(multiset, multiset.entrySet().iterator()); } static final class MultisetIteratorImpl<E extends @Nullable Object> implements Iterator<E> { private final Multiset<E> multiset; private final Iterator<Entry<E>> entryIterator; @CheckForNull private Entry<E> currentEntry; /** Count of subsequent elements equal to current element */ private int laterCount; /** Count of all elements equal to current element */ private int totalCount; private boolean canRemove; MultisetIteratorImpl(Multiset<E> multiset, Iterator<Entry<E>> entryIterator) { this.multiset = multiset; this.entryIterator = entryIterator; } @Override public boolean hasNext() { return laterCount > 0 || entryIterator.hasNext(); } @Override @ParametricNullness public E next() { if (!hasNext()) { throw new NoSuchElementException(); } if (laterCount == 0) { currentEntry = entryIterator.next(); totalCount = laterCount = currentEntry.getCount(); } laterCount--; canRemove = true; /* * requireNonNull is safe because laterCount starts at 0, forcing us to initialize * currentEntry above. After that, we never clear it. */ return requireNonNull(currentEntry).getElement(); } @Override public void remove() { checkRemove(canRemove); if (totalCount == 1) { entryIterator.remove(); } else { /* * requireNonNull is safe because canRemove is set to true only after we initialize * currentEntry (which we never subsequently clear). */ multiset.remove(requireNonNull(currentEntry).getElement()); } totalCount--; canRemove = false; } } static <E extends @Nullable Object> Spliterator<E> spliteratorImpl(Multiset<E> multiset) { Spliterator<Entry<E>> entrySpliterator = multiset.entrySet().spliterator(); return CollectSpliterators.flatMap( entrySpliterator, entry -> Collections.nCopies(entry.getCount(), entry.getElement()).spliterator(), Spliterator.SIZED | (entrySpliterator.characteristics() & (Spliterator.ORDERED | Spliterator.NONNULL | Spliterator.IMMUTABLE)), multiset.size()); } /** An implementation of {@link Multiset#size}. */ static int linearTimeSizeImpl(Multiset<?> multiset) { long size = 0; for (Entry<?> entry : multiset.entrySet()) { size += entry.getCount(); } return Ints.saturatedCast(size); } /** Used to avoid http://bugs.sun.com/view_bug.do?bug_id=6558557 */ static <T extends @Nullable Object> Multiset<T> cast(Iterable<T> iterable) { return (Multiset<T>) iterable; } /** * Returns a copy of {@code multiset} as an {@link ImmutableMultiset} whose iteration order puts * the highest count first, with ties broken by the iteration order of the original multiset. * * @since 11.0 */ public static <E> ImmutableMultiset<E> copyHighestCountFirst(Multiset<E> multiset) { @SuppressWarnings("unchecked") // generics+arrays // TODO(cpovirk): Consider storing an Entry<?> instead of Entry<E>. Entry<E>[] entries = (Entry<E>[]) multiset.entrySet().toArray((Entry<E>[]) new Entry<?>[0]); Arrays.sort(entries, DecreasingCount.INSTANCE); return ImmutableMultiset.copyFromEntries(Arrays.asList(entries)); } private static final class DecreasingCount implements Comparator<Entry<?>> { static final Comparator<Entry<?>> INSTANCE = new DecreasingCount(); @Override public int compare(Entry<?> entry1, Entry<?> entry2) { return entry2.getCount() - entry1.getCount(); // subtracting two nonnegative integers } } /** * An {@link AbstractMultiset} with additional default implementations, some of them linear-time * implementations in terms of {@code elementSet} and {@code entrySet}. */ private abstract static class ViewMultiset<E extends @Nullable Object> extends AbstractMultiset<E> { @Override public int size() { return linearTimeSizeImpl(this); } @Override public void clear() { elementSet().clear(); } @Override public Iterator<E> iterator() { return iteratorImpl(this); } @Override int distinctElements() { return elementSet().size(); } } }
google/guava
guava/src/com/google/common/collect/Multisets.java
238
/* * 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
239
/* * 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 javax.annotation.CheckForNull; /** * Static utility methods pertaining to {@code short} primitives, that are not already found in * either {@link Short} or {@link Arrays}. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Shorts extends ShortsMethodsForWeb { private Shorts() {} /** * The number of bytes required to represent a primitive {@code short} value. * * <p><b>Java 8+ users:</b> use {@link Short#BYTES} instead. */ public static final int BYTES = Short.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as a {@code short}. * * @since 10.0 */ public static final short MAX_POWER_OF_TWO = 1 << (Short.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Short) * value).hashCode()}. * * <p><b>Java 8+ users:</b> use {@link Short#hashCode(short)} instead. * * @param value a primitive {@code short} value * @return a hash code for the value */ public static int hashCode(short value) { return value; } /** * Returns the {@code short} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code short} type * @return the {@code short} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link Short#MAX_VALUE} or * less than {@link Short#MIN_VALUE} */ public static short checkedCast(long value) { short result = (short) value; checkArgument(result == value, "Out of range: %s", value); return result; } /** * Returns the {@code short} nearest in value to {@code value}. * * @param value any {@code long} value * @return the same value cast to {@code short} if it is in the range of the {@code short} type, * {@link Short#MAX_VALUE} if it is too large, or {@link Short#MIN_VALUE} if it is too small */ public static short saturatedCast(long value) { if (value > Short.MAX_VALUE) { return Short.MAX_VALUE; } if (value < Short.MIN_VALUE) { return Short.MIN_VALUE; } return (short) value; } /** * Compares the two specified {@code short} values. The sign of the value returned is the same as * that of {@code ((Short) a).compareTo(b)}. * * <p><b>Java 7+ users:</b> this method should be treated as deprecated; use the equivalent {@link * Short#compare} method instead. * * @param a the first {@code short} to compare * @param b the second {@code short} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(short a, short b) { return a - b; // safe due to restricted range } /** * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. * * @param array an array of {@code short} values, possibly empty * @param target a primitive {@code short} value * @return {@code true} if {@code array[i] == target} for some value of {@code i} */ public static boolean contains(short[] array, short target) { for (short value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in {@code array}. * * @param array an array of {@code short} values, possibly empty * @param target a primitive {@code short} value * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int indexOf(short[] array, short target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf(short[] array, short target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code target} within * {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, * i, i + target.length)} contains exactly the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(short[] array, short[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in {@code array}. * * @param array an array of {@code short} values, possibly empty * @param target a primitive {@code short} value * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int lastIndexOf(short[] array, short target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf(short[] array, short target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code short} values * @return the value present in {@code array} that is less than or equal to every other value in * the array * @throws IllegalArgumentException if {@code array} is empty */ @GwtIncompatible( "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static short min(short... array) { checkArgument(array.length > 0); short min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code short} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array * @throws IllegalArgumentException if {@code array} is empty */ @GwtIncompatible( "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static short max(short... array) { checkArgument(array.length > 0); short max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the 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 short} 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 short constrainToRange(short value, short min, short max) { checkArgument(min <= max, "min (%s) must be less than or equal to max (%s)", min, max); return value < min ? min : value < max ? value : max; } /** * Returns the values from each provided array combined into a single array. For example, {@code * concat(new short[] {a, b}, new short[] {}, new short[] {c}} returns the array {@code {a, b, * c}}. * * @param arrays zero or more {@code short} arrays * @return a single array containing all the values from the source arrays, in order */ public static short[] concat(short[]... arrays) { int length = 0; for (short[] array : arrays) { length += array.length; } short[] result = new short[length]; int pos = 0; for (short[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns a big-endian representation of {@code value} in a 2-element byte array; equivalent to * {@code ByteBuffer.allocate(2).putShort(value).array()}. For example, the input value {@code * (short) 0x1234} would yield the byte array {@code {0x12, 0x34}}. * * <p>If you need to convert and concatenate several values (possibly even of different types), * use a shared {@link java.nio.ByteBuffer} instance, or use {@link * com.google.common.io.ByteStreams#newDataOutput()} to get a growable buffer. */ @GwtIncompatible // doesn't work public static byte[] toByteArray(short value) { return new byte[] {(byte) (value >> 8), (byte) value}; } /** * Returns the {@code short} value whose big-endian representation is stored in the first 2 bytes * of {@code bytes}; equivalent to {@code ByteBuffer.wrap(bytes).getShort()}. For example, the * input byte array {@code {0x54, 0x32}} would yield the {@code short} value {@code 0x5432}. * * <p>Arguably, it's preferable to use {@link java.nio.ByteBuffer}; that library exposes much more * flexibility at little cost in readability. * * @throws IllegalArgumentException if {@code bytes} has fewer than 2 elements */ @GwtIncompatible // doesn't work public static short fromByteArray(byte[] bytes) { checkArgument(bytes.length >= BYTES, "array too small: %s < %s", bytes.length, BYTES); return fromBytes(bytes[0], bytes[1]); } /** * Returns the {@code short} value whose byte representation is the given 2 bytes, in big-endian * order; equivalent to {@code Shorts.fromByteArray(new byte[] {b1, b2})}. * * @since 7.0 */ @GwtIncompatible // doesn't work public static short fromBytes(byte b1, byte b2) { return (short) ((b1 << 8) | (b2 & 0xFF)); } private static final class ShortConverter extends Converter<String, Short> implements Serializable { static final Converter<String, Short> INSTANCE = new ShortConverter(); @Override protected Short doForward(String value) { return Short.decode(value); } @Override protected String doBackward(Short value) { return value.toString(); } @Override public String toString() { return "Shorts.stringConverter()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } /** * Returns a serializable converter object that converts between strings and shorts using {@link * Short#decode} and {@link Short#toString()}. The returned converter throws {@link * NumberFormatException} if the input string is invalid. * * <p><b>Warning:</b> please see {@link Short#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, Short> stringConverter() { return ShortConverter.INSTANCE; } /** * Returns an array containing the same values as {@code array}, but guaranteed to be of a * specified minimum length. If {@code array} already has a length of at least {@code minLength}, * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is * returned, containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative * @return an array containing the values of {@code array}, with guaranteed minimum length {@code * minLength} */ public static short[] ensureCapacity(short[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; } /** * Returns a string containing the supplied {@code short} values separated by {@code separator}. * For example, {@code join("-", (short) 1, (short) 2, (short) 3)} returns the string {@code * "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting string * (but not at the start or end) * @param array an array of {@code short} values, possibly empty */ public static String join(String separator, short... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 6); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code short} arrays <a * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it * compares, using {@link #compare(short, short)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the shorter array as the * lesser. For example, {@code [] < [(short) 1] < [(short) 1, (short) 2] < [(short) 2]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with {@link Arrays#equals(short[], * short[])}. * * @since 2.0 */ public static Comparator<short[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<short[]> { INSTANCE; @Override public int compare(short[] left, short[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Shorts.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } @Override public String toString() { return "Shorts.lexicographicalComparator()"; } } /** * Sorts the elements of {@code array} in descending order. * * @since 23.1 */ public static void sortDescending(short[] 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(short[] 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(Shorts.asList(array))}, but is likely to be more efficient. * * @since 23.1 */ public static void reverse(short[] 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(Shorts.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(short[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { short 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(Shorts.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(short[] 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(Shorts.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(short[] 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 short} * value in the manner of {@link Number#shortValue}. * * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. * Calling this method is as thread-safe as calling that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the same order, converted * to primitives * @throws NullPointerException if {@code collection} or any of its elements is null * @since 1.0 (parameter was {@code Collection<Short>} before 12.0) */ public static short[] toArray(Collection<? extends Number> collection) { if (collection instanceof ShortArrayAsList) { return ((ShortArrayAsList) collection).toShortArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; short[] array = new short[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).shortValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to * set a value to {@code null} will result in a {@link NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of {@code Short} objects * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for * the returned list is unspecified. * * <p>The returned list is serializable. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Short> asList(short... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new ShortArrayAsList(backingArray); } @GwtCompatible private static class ShortArrayAsList extends AbstractList<Short> implements RandomAccess, Serializable { final short[] array; final int start; final int end; ShortArrayAsList(short[] array) { this(array, 0, array.length); } ShortArrayAsList(short[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Short get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(@CheckForNull Object target) { // Overridden to prevent a ton of boxing return (target instanceof Short) && Shorts.indexOf(array, (Short) target, start, end) != -1; } @Override public int indexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Short) { int i = Shorts.indexOf(array, (Short) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Short) { int i = Shorts.lastIndexOf(array, (Short) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Short set(int index, Short element) { checkElementIndex(index, size()); short oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Short> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new ShortArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(@CheckForNull Object object) { if (object == this) { return true; } if (object instanceof ShortArrayAsList) { ShortArrayAsList that = (ShortArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Shorts.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 6); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } short[] toShortArray() { return Arrays.copyOfRange(array, start, end); } private static final long serialVersionUID = 0; } }
google/guava
guava/src/com/google/common/primitives/Shorts.java
240
/* * 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
241
// 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 package com.google.protobuf; import java.lang.reflect.Method; import java.nio.Buffer; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.util.AbstractList; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.RandomAccess; import java.util.Set; /** * The classes contained within are used internally by the Protocol Buffer library and generated * message implementations. They are public only because those generated messages do not reside in * the {@code protobuf} package. Others should not use this class directly. * * @author [email protected] (Kenton Varda) */ public final class Internal { private Internal() {} static final Charset US_ASCII = Charset.forName("US-ASCII"); static final Charset UTF_8 = Charset.forName("UTF-8"); static final Charset ISO_8859_1 = Charset.forName("ISO-8859-1"); /** Throws an appropriate {@link NullPointerException} if the given objects is {@code null}. */ static <T> T checkNotNull(T obj) { if (obj == null) { throw new NullPointerException(); } return obj; } /** Throws an appropriate {@link NullPointerException} if the given objects is {@code null}. */ static <T> T checkNotNull(T obj, String message) { if (obj == null) { throw new NullPointerException(message); } return obj; } /** * Helper called by generated code to construct default values for string fields. * * <p>The protocol compiler does not actually contain a UTF-8 decoder -- it just pushes * UTF-8-encoded text around without touching it. The one place where this presents a problem is * when generating Java string literals. Unicode characters in the string literal would normally * need to be encoded using a Unicode escape sequence, which would require decoding them. To get * around this, protoc instead embeds the UTF-8 bytes into the generated code and leaves it to the * runtime library to decode them. * * <p>It gets worse, though. If protoc just generated a byte array, like: new byte[] {0x12, 0x34, * 0x56, 0x78} Java actually generates *code* which allocates an array and then fills in each * value. This is much less efficient than just embedding the bytes directly into the bytecode. To * get around this, we need another work-around. String literals are embedded directly, so protoc * actually generates a string literal corresponding to the bytes. The easiest way to do this is * to use the ISO-8859-1 character set, which corresponds to the first 256 characters of the * Unicode range. Protoc can then use good old CEscape to generate the string. * * <p>So we have a string literal which represents a set of bytes which represents another string. * This function -- stringDefaultValue -- converts from the generated string to the string we * actually want. The generated code calls this automatically. */ public static String stringDefaultValue(String bytes) { return new String(bytes.getBytes(ISO_8859_1), UTF_8); } /** * Helper called by generated code to construct default values for bytes fields. * * <p>This is a lot like {@link #stringDefaultValue}, but for bytes fields. In this case we only * need the second of the two hacks -- allowing us to embed raw bytes as a string literal with * ISO-8859-1 encoding. */ public static ByteString bytesDefaultValue(String bytes) { return ByteString.copyFrom(bytes.getBytes(ISO_8859_1)); } /** * Helper called by generated code to construct default values for bytes fields. * * <p>This is like {@link #bytesDefaultValue}, but returns a byte array. */ public static byte[] byteArrayDefaultValue(String bytes) { return bytes.getBytes(ISO_8859_1); } /** * Helper called by generated code to construct default values for bytes fields. * * <p>This is like {@link #bytesDefaultValue}, but returns a ByteBuffer. */ public static ByteBuffer byteBufferDefaultValue(String bytes) { return ByteBuffer.wrap(byteArrayDefaultValue(bytes)); } /** * Create a new ByteBuffer and copy all the content of {@code source} ByteBuffer to the new * ByteBuffer. The new ByteBuffer's limit and capacity will be source.capacity(), and its position * will be 0. Note that the state of {@code source} ByteBuffer won't be changed. */ public static ByteBuffer copyByteBuffer(ByteBuffer source) { // Make a duplicate of the source ByteBuffer and read data from the // duplicate. This is to avoid affecting the source ByteBuffer's state. ByteBuffer temp = source.duplicate(); // We want to copy all the data in the source ByteBuffer, not just the // remaining bytes. // View ByteBuffer as Buffer to avoid issue with covariant return types // See https://issues.apache.org/jira/browse/MRESOLVER-85 ((Buffer) temp).clear(); ByteBuffer result = ByteBuffer.allocate(temp.capacity()); result.put(temp); ((Buffer) result).clear(); return result; } /** * Helper called by generated code to determine if a byte array is a valid UTF-8 encoded string * such that the original bytes can be converted to a String object and then back to a byte array * round tripping the bytes without loss. More precisely, returns {@code true} whenever: * * <pre>{@code * Arrays.equals(byteString.toByteArray(), * new String(byteString.toByteArray(), "UTF-8").getBytes("UTF-8")) * }</pre> * * <p>This method rejects "overlong" byte sequences, as well as 3-byte sequences that would map to * a surrogate character, in accordance with the restricted definition of UTF-8 introduced in * Unicode 3.1. Note that the UTF-8 decoder included in Oracle's JDK has been modified to also * reject "overlong" byte sequences, but currently (2011) still accepts 3-byte surrogate character * byte sequences. * * <p>See the Unicode Standard,<br> * Table 3-6. <em>UTF-8 Bit Distribution</em>,<br> * Table 3-7. <em>Well Formed UTF-8 Byte Sequences</em>. * * <p>As of 2011-02, this method simply returns the result of {@link ByteString#isValidUtf8()}. * Calling that method directly is preferred. * * @param byteString the string to check * @return whether the byte array is round trippable */ public static boolean isValidUtf8(ByteString byteString) { return byteString.isValidUtf8(); } /** Like {@link #isValidUtf8(ByteString)} but for byte arrays. */ public static boolean isValidUtf8(byte[] byteArray) { return Utf8.isValidUtf8(byteArray); } /** Helper method to get the UTF-8 bytes of a string. */ public static byte[] toByteArray(String value) { return value.getBytes(UTF_8); } /** Helper method to convert a byte array to a string using UTF-8 encoding. */ public static String toStringUtf8(byte[] bytes) { return new String(bytes, UTF_8); } /** * Interface for an enum value or value descriptor, to be used in FieldSet. The lite library * stores enum values directly in FieldSets but the full library stores EnumValueDescriptors in * order to better support reflection. */ public interface EnumLite { int getNumber(); } /** * Interface for an object which maps integers to {@link EnumLite}s. {@link * Descriptors.EnumDescriptor} implements this interface by mapping numbers to {@link * Descriptors.EnumValueDescriptor}s. Additionally, every generated enum type has a static method * internalGetValueMap() which returns an implementation of this type that maps numbers to enum * values. */ public interface EnumLiteMap<T extends EnumLite> { T findValueByNumber(int number); } /** Interface for an object which verifies integers are in range. */ public interface EnumVerifier { boolean isInRange(int number); } /** * Helper method for implementing {@link Message#hashCode()} for longs. * * @see Long#hashCode() */ public static int hashLong(long n) { return (int) (n ^ (n >>> 32)); } /** * Helper method for implementing {@link Message#hashCode()} for booleans. * * @see Boolean#hashCode() */ public static int hashBoolean(boolean b) { return b ? 1231 : 1237; } /** * Helper method for implementing {@link Message#hashCode()} for enums. * * <p>This is needed because {@link java.lang.Enum#hashCode()} is final, but we need to use the * field number as the hash code to ensure compatibility between statically and dynamically * generated enum objects. */ public static int hashEnum(EnumLite e) { return e.getNumber(); } /** Helper method for implementing {@link Message#hashCode()} for enum lists. */ public static int hashEnumList(List<? extends EnumLite> list) { int hash = 1; for (EnumLite e : list) { hash = 31 * hash + hashEnum(e); } return hash; } /** Helper method for implementing {@link Message#equals(Object)} for bytes field. */ public static boolean equals(List<byte[]> a, List<byte[]> b) { if (a.size() != b.size()) { return false; } for (int i = 0; i < a.size(); ++i) { if (!Arrays.equals(a.get(i), b.get(i))) { return false; } } return true; } /** Helper method for implementing {@link Message#hashCode()} for bytes field. */ public static int hashCode(List<byte[]> list) { int hash = 1; for (byte[] bytes : list) { hash = 31 * hash + hashCode(bytes); } return hash; } /** Helper method for implementing {@link Message#hashCode()} for bytes field. */ public static int hashCode(byte[] bytes) { // The hash code for a byte array should be the same as the hash code for a // ByteString with the same content. This is to ensure that the generated // hashCode() method will return the same value as the pure reflection // based hashCode() method. return Internal.hashCode(bytes, 0, bytes.length); } /** Helper method for implementing {@link LiteralByteString#hashCode()}. */ static int hashCode(byte[] bytes, int offset, int length) { // The hash code for a byte array should be the same as the hash code for a // ByteString with the same content. This is to ensure that the generated // hashCode() method will return the same value as the pure reflection // based hashCode() method. int h = Internal.partialHash(length, bytes, offset, length); return h == 0 ? 1 : h; } /** Helper method for continuously hashing bytes. */ static int partialHash(int h, byte[] bytes, int offset, int length) { for (int i = offset; i < offset + length; i++) { h = h * 31 + bytes[i]; } return h; } /** Helper method for implementing {@link Message#equals(Object)} for bytes field. */ public static boolean equalsByteBuffer(ByteBuffer a, ByteBuffer b) { if (a.capacity() != b.capacity()) { return false; } // ByteBuffer.equals() will only compare the remaining bytes, but we want to // compare all the content. ByteBuffer aDuplicate = a.duplicate(); Java8Compatibility.clear(aDuplicate); ByteBuffer bDuplicate = b.duplicate(); Java8Compatibility.clear(bDuplicate); return aDuplicate.equals(bDuplicate); } /** Helper method for implementing {@link Message#equals(Object)} for bytes field. */ public static boolean equalsByteBuffer(List<ByteBuffer> a, List<ByteBuffer> b) { if (a.size() != b.size()) { return false; } for (int i = 0; i < a.size(); ++i) { if (!equalsByteBuffer(a.get(i), b.get(i))) { return false; } } return true; } /** Helper method for implementing {@link Message#hashCode()} for bytes field. */ public static int hashCodeByteBuffer(List<ByteBuffer> list) { int hash = 1; for (ByteBuffer bytes : list) { hash = 31 * hash + hashCodeByteBuffer(bytes); } return hash; } private static final int DEFAULT_BUFFER_SIZE = 4096; /** Helper method for implementing {@link Message#hashCode()} for bytes field. */ public static int hashCodeByteBuffer(ByteBuffer bytes) { if (bytes.hasArray()) { // Fast path. int h = partialHash(bytes.capacity(), bytes.array(), bytes.arrayOffset(), bytes.capacity()); return h == 0 ? 1 : h; } else { // Read the data into a temporary byte array before calculating the // hash value. final int bufferSize = bytes.capacity() > DEFAULT_BUFFER_SIZE ? DEFAULT_BUFFER_SIZE : bytes.capacity(); final byte[] buffer = new byte[bufferSize]; final ByteBuffer duplicated = bytes.duplicate(); Java8Compatibility.clear(duplicated); int h = bytes.capacity(); while (duplicated.remaining() > 0) { final int length = duplicated.remaining() <= bufferSize ? duplicated.remaining() : bufferSize; duplicated.get(buffer, 0, length); h = partialHash(h, buffer, 0, length); } return h == 0 ? 1 : h; } } @SuppressWarnings("unchecked") public static <T extends MessageLite> T getDefaultInstance(Class<T> clazz) { try { Method method = clazz.getMethod("getDefaultInstance"); return (T) method.invoke(method); } catch (Exception e) { throw new RuntimeException("Failed to get default instance for " + clazz, e); } } /** An empty byte array constant used in generated code. */ public static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; /** An empty byte array constant used in generated code. */ public static final ByteBuffer EMPTY_BYTE_BUFFER = ByteBuffer.wrap(EMPTY_BYTE_ARRAY); /** An empty coded input stream constant used in generated code. */ public static final CodedInputStream EMPTY_CODED_INPUT_STREAM = CodedInputStream.newInstance(EMPTY_BYTE_ARRAY); /** Helper method to merge two MessageLite instances. */ static Object mergeMessage(Object destination, Object source) { return ((MessageLite) destination).toBuilder().mergeFrom((MessageLite) source).buildPartial(); } /** * Provides an immutable view of {@code List<T>} around an {@code IntList}. * * <p>Protobuf internal. Used in protobuf generated code only. */ public static class IntListAdapter<T> extends AbstractList<T> { /** Convert individual elements of the List from int to T. */ public interface IntConverter<T> { T convert(int from); } private final IntList fromList; private final IntConverter<T> converter; public IntListAdapter(IntList fromList, IntConverter<T> converter) { this.fromList = fromList; this.converter = converter; } @Override public T get(int index) { return converter.convert(fromList.getInt(index)); } @Override public int size() { return fromList.size(); } } /** * Provides an immutable view of {@code List<T>} around a {@code List<F>}. * * <p>Protobuf internal. Used in protobuf generated code only. */ public static class ListAdapter<F, T> extends AbstractList<T> { /** Convert individual elements of the List from F to T. */ public interface Converter<F, T> { T convert(F from); } private final List<F> fromList; private final Converter<F, T> converter; public ListAdapter(List<F> fromList, Converter<F, T> converter) { this.fromList = fromList; this.converter = converter; } @Override public T get(int index) { return converter.convert(fromList.get(index)); } @Override public int size() { return fromList.size(); } } /** Wrap around a {@code Map<K, RealValue>} and provide a {@code Map<K, V>} interface. */ public static class MapAdapter<K, V, RealValue> extends AbstractMap<K, V> { /** An interface used to convert between two types. */ public interface Converter<A, B> { B doForward(A object); A doBackward(B object); } public static <T extends EnumLite> Converter<Integer, T> newEnumConverter( final EnumLiteMap<T> enumMap, final T unrecognizedValue) { return new Converter<Integer, T>() { @Override public T doForward(Integer value) { T result = enumMap.findValueByNumber(value); return result == null ? unrecognizedValue : result; } @Override public Integer doBackward(T value) { return value.getNumber(); } }; } private final Map<K, RealValue> realMap; private final Converter<RealValue, V> valueConverter; public MapAdapter(Map<K, RealValue> realMap, Converter<RealValue, V> valueConverter) { this.realMap = realMap; this.valueConverter = valueConverter; } @Override public V get(Object key) { RealValue result = realMap.get(key); if (result == null) { return null; } return valueConverter.doForward(result); } @Override public V put(K key, V value) { RealValue oldValue = realMap.put(key, valueConverter.doBackward(value)); if (oldValue == null) { return null; } return valueConverter.doForward(oldValue); } @Override public Set<java.util.Map.Entry<K, V>> entrySet() { return new SetAdapter(realMap.entrySet()); } private class SetAdapter extends AbstractSet<Map.Entry<K, V>> { private final Set<Map.Entry<K, RealValue>> realSet; public SetAdapter(Set<Map.Entry<K, RealValue>> realSet) { this.realSet = realSet; } @Override public Iterator<java.util.Map.Entry<K, V>> iterator() { return new IteratorAdapter(realSet.iterator()); } @Override public int size() { return realSet.size(); } } private class IteratorAdapter implements Iterator<Map.Entry<K, V>> { private final Iterator<Map.Entry<K, RealValue>> realIterator; public IteratorAdapter(Iterator<Map.Entry<K, RealValue>> realIterator) { this.realIterator = realIterator; } @Override public boolean hasNext() { return realIterator.hasNext(); } @Override public java.util.Map.Entry<K, V> next() { return new EntryAdapter(realIterator.next()); } @Override public void remove() { realIterator.remove(); } } private class EntryAdapter implements Map.Entry<K, V> { private final Map.Entry<K, RealValue> realEntry; public EntryAdapter(Map.Entry<K, RealValue> realEntry) { this.realEntry = realEntry; } @Override public K getKey() { return realEntry.getKey(); } @Override public V getValue() { return valueConverter.doForward(realEntry.getValue()); } @Override public V setValue(V value) { RealValue oldValue = realEntry.setValue(valueConverter.doBackward(value)); if (oldValue == null) { return null; } return valueConverter.doForward(oldValue); } @Override public boolean equals(Object o) { if (o == this) { return true; } if (!(o instanceof Map.Entry)) { return false; } Map.Entry<?, ?> other = (Map.Entry<?, ?>) o; return getKey().equals(other.getKey()) && getValue().equals(getValue()); } @Override public int hashCode() { return realEntry.hashCode(); } } } /** * Extends {@link List} to add the capability to make the list immutable and inspect if it is * modifiable. * * <p>All implementations must support efficient random access. */ public static interface ProtobufList<E> extends List<E>, RandomAccess { /** * Makes this list immutable. All subsequent modifications will throw an {@link * UnsupportedOperationException}. */ void makeImmutable(); /** * Returns whether this list can be modified via the publicly accessible {@link List} methods. */ boolean isModifiable(); /** Returns a mutable clone of this list with the specified capacity. */ ProtobufList<E> mutableCopyWithCapacity(int capacity); } /** * A {@link java.util.List} implementation that avoids boxing the elements into Integers if * possible. Does not support null elements. */ public static interface IntList extends ProtobufList<Integer> { /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */ int getInt(int index); /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */ void addInt(int element); /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */ @CanIgnoreReturnValue int setInt(int index, int element); /** Returns a mutable clone of this list with the specified capacity. */ @Override IntList mutableCopyWithCapacity(int capacity); } /** * A {@link java.util.List} implementation that avoids boxing the elements into Booleans if * possible. Does not support null elements. */ public static interface BooleanList extends ProtobufList<Boolean> { /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */ boolean getBoolean(int index); /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */ void addBoolean(boolean element); /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */ @CanIgnoreReturnValue boolean setBoolean(int index, boolean element); /** Returns a mutable clone of this list with the specified capacity. */ @Override BooleanList mutableCopyWithCapacity(int capacity); } /** * A {@link java.util.List} implementation that avoids boxing the elements into Longs if possible. * Does not support null elements. */ public static interface LongList extends ProtobufList<Long> { /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */ long getLong(int index); /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */ void addLong(long element); /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */ @CanIgnoreReturnValue long setLong(int index, long element); /** Returns a mutable clone of this list with the specified capacity. */ @Override LongList mutableCopyWithCapacity(int capacity); } /** * A {@link java.util.List} implementation that avoids boxing the elements into Doubles if * possible. Does not support null elements. */ public static interface DoubleList extends ProtobufList<Double> { /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */ double getDouble(int index); /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */ void addDouble(double element); /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */ @CanIgnoreReturnValue double setDouble(int index, double element); /** Returns a mutable clone of this list with the specified capacity. */ @Override DoubleList mutableCopyWithCapacity(int capacity); } /** * A {@link java.util.List} implementation that avoids boxing the elements into Floats if * possible. Does not support null elements. */ public static interface FloatList extends ProtobufList<Float> { /** Like {@link #get(int)} but more efficient in that it doesn't box the returned value. */ float getFloat(int index); /** Like {@link #add(Object)} but more efficient in that it doesn't box the element. */ void addFloat(float element); /** Like {@link #set(int, Object)} but more efficient in that it doesn't box the element. */ @CanIgnoreReturnValue float setFloat(int index, float element); /** Returns a mutable clone of this list with the specified capacity. */ @Override FloatList mutableCopyWithCapacity(int capacity); } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/Internal.java
242
/* * 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.Preconditions.checkState; import static com.google.common.collect.CollectPreconditions.checkNonnegative; 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.MoreObjects; import com.google.common.primitives.Ints; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.Comparator; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.function.ObjIntConsumer; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A multiset which maintains the ordering of its elements, according to either their natural order * or an explicit {@link Comparator}. In all cases, this implementation uses {@link * Comparable#compareTo} or {@link Comparator#compare} instead of {@link Object#equals} to determine * equivalence of instances. * * <p><b>Warning:</b> The comparison must be <i>consistent with equals</i> as explained by the * {@link Comparable} class specification. Otherwise, the resulting multiset will violate the {@link * java.util.Collection} contract, which is specified in terms of {@link Object#equals}. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multiset">{@code Multiset}</a>. * * @author Louis Wasserman * @author Jared Levy * @since 2.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class TreeMultiset<E extends @Nullable Object> extends AbstractSortedMultiset<E> implements Serializable { /** * Creates a new, empty multiset, sorted according to the elements' natural order. All elements * inserted into the multiset must implement the {@code Comparable} interface. Furthermore, all * such elements must be <i>mutually comparable</i>: {@code e1.compareTo(e2)} must not throw a * {@code ClassCastException} for any elements {@code e1} and {@code e2} in the multiset. If the * user attempts to add an element to the multiset that violates this constraint (for example, the * user attempts to add a string element to a set whose elements are integers), the {@code * add(Object)} call will throw a {@code ClassCastException}. * * <p>The type specification is {@code <E extends Comparable>}, instead of the more specific * {@code <E extends Comparable<? super E>>}, to support classes defined without generics. */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static <E extends Comparable> TreeMultiset<E> create() { return new TreeMultiset<>(Ordering.natural()); } /** * Creates a new, empty multiset, sorted according to the specified comparator. All elements * inserted into the multiset must be <i>mutually comparable</i> by the specified comparator: * {@code comparator.compare(e1, e2)} must not throw a {@code ClassCastException} for any elements * {@code e1} and {@code e2} in the multiset. If the user attempts to add an element to the * multiset that violates this constraint, the {@code add(Object)} call will throw a {@code * ClassCastException}. * * @param comparator the comparator that will be used to sort this multiset. A null value * indicates that the elements' <i>natural ordering</i> should be used. */ @SuppressWarnings("unchecked") public static <E extends @Nullable Object> TreeMultiset<E> create( @CheckForNull Comparator<? super E> comparator) { return (comparator == null) ? new TreeMultiset<E>((Comparator) Ordering.natural()) : new TreeMultiset<E>(comparator); } /** * Creates an empty multiset containing the given initial elements, sorted according to the * elements' natural order. * * <p>This implementation is highly efficient when {@code elements} is itself a {@link Multiset}. * * <p>The type specification is {@code <E extends Comparable>}, instead of the more specific * {@code <E extends Comparable<? super E>>}, to support classes defined without generics. */ @SuppressWarnings("rawtypes") // https://github.com/google/guava/issues/989 public static <E extends Comparable> TreeMultiset<E> create(Iterable<? extends E> elements) { TreeMultiset<E> multiset = create(); Iterables.addAll(multiset, elements); return multiset; } private final transient Reference<AvlNode<E>> rootReference; private final transient GeneralRange<E> range; private final transient AvlNode<E> header; TreeMultiset(Reference<AvlNode<E>> rootReference, GeneralRange<E> range, AvlNode<E> endLink) { super(range.comparator()); this.rootReference = rootReference; this.range = range; this.header = endLink; } TreeMultiset(Comparator<? super E> comparator) { super(comparator); this.range = GeneralRange.all(comparator); this.header = new AvlNode<>(); successor(header, header); this.rootReference = new Reference<>(); } /** A function which can be summed across a subtree. */ private enum Aggregate { SIZE { @Override int nodeAggregate(AvlNode<?> node) { return node.elemCount; } @Override long treeAggregate(@CheckForNull AvlNode<?> root) { return (root == null) ? 0 : root.totalCount; } }, DISTINCT { @Override int nodeAggregate(AvlNode<?> node) { return 1; } @Override long treeAggregate(@CheckForNull AvlNode<?> root) { return (root == null) ? 0 : root.distinctElements; } }; abstract int nodeAggregate(AvlNode<?> node); abstract long treeAggregate(@CheckForNull AvlNode<?> root); } private long aggregateForEntries(Aggregate aggr) { AvlNode<E> root = rootReference.get(); long total = aggr.treeAggregate(root); if (range.hasLowerBound()) { total -= aggregateBelowRange(aggr, root); } if (range.hasUpperBound()) { total -= aggregateAboveRange(aggr, root); } return total; } private long aggregateBelowRange(Aggregate aggr, @CheckForNull AvlNode<E> node) { if (node == null) { return 0; } // The cast is safe because we call this method only if hasLowerBound(). int cmp = comparator() .compare(uncheckedCastNullableTToT(range.getLowerEndpoint()), node.getElement()); if (cmp < 0) { return aggregateBelowRange(aggr, node.left); } else if (cmp == 0) { switch (range.getLowerBoundType()) { case OPEN: return aggr.nodeAggregate(node) + aggr.treeAggregate(node.left); case CLOSED: return aggr.treeAggregate(node.left); default: throw new AssertionError(); } } else { return aggr.treeAggregate(node.left) + aggr.nodeAggregate(node) + aggregateBelowRange(aggr, node.right); } } private long aggregateAboveRange(Aggregate aggr, @CheckForNull AvlNode<E> node) { if (node == null) { return 0; } // The cast is safe because we call this method only if hasUpperBound(). int cmp = comparator() .compare(uncheckedCastNullableTToT(range.getUpperEndpoint()), node.getElement()); if (cmp > 0) { return aggregateAboveRange(aggr, node.right); } else if (cmp == 0) { switch (range.getUpperBoundType()) { case OPEN: return aggr.nodeAggregate(node) + aggr.treeAggregate(node.right); case CLOSED: return aggr.treeAggregate(node.right); default: throw new AssertionError(); } } else { return aggr.treeAggregate(node.right) + aggr.nodeAggregate(node) + aggregateAboveRange(aggr, node.left); } } @Override public int size() { return Ints.saturatedCast(aggregateForEntries(Aggregate.SIZE)); } @Override int distinctElements() { return Ints.saturatedCast(aggregateForEntries(Aggregate.DISTINCT)); } static int distinctElements(@CheckForNull AvlNode<?> node) { return (node == null) ? 0 : node.distinctElements; } @Override public int count(@CheckForNull Object element) { try { @SuppressWarnings("unchecked") E e = (E) element; AvlNode<E> root = rootReference.get(); if (!range.contains(e) || root == null) { return 0; } return root.count(comparator(), e); } catch (ClassCastException | NullPointerException e) { return 0; } } @CanIgnoreReturnValue @Override public int add(@ParametricNullness E element, int occurrences) { checkNonnegative(occurrences, "occurrences"); if (occurrences == 0) { return count(element); } checkArgument(range.contains(element)); AvlNode<E> root = rootReference.get(); if (root == null) { int unused = comparator().compare(element, element); AvlNode<E> newRoot = new AvlNode<>(element, occurrences); successor(header, newRoot, header); rootReference.checkAndSet(root, newRoot); return 0; } int[] result = new int[1]; // used as a mutable int reference to hold result AvlNode<E> newRoot = root.add(comparator(), element, occurrences, result); rootReference.checkAndSet(root, newRoot); return result[0]; } @CanIgnoreReturnValue @Override public int remove(@CheckForNull Object element, int occurrences) { checkNonnegative(occurrences, "occurrences"); if (occurrences == 0) { return count(element); } AvlNode<E> root = rootReference.get(); int[] result = new int[1]; // used as a mutable int reference to hold result AvlNode<E> newRoot; try { @SuppressWarnings("unchecked") E e = (E) element; if (!range.contains(e) || root == null) { return 0; } newRoot = root.remove(comparator(), e, occurrences, result); } catch (ClassCastException | NullPointerException e) { return 0; } rootReference.checkAndSet(root, newRoot); return result[0]; } @CanIgnoreReturnValue @Override public int setCount(@ParametricNullness E element, int count) { checkNonnegative(count, "count"); if (!range.contains(element)) { checkArgument(count == 0); return 0; } AvlNode<E> root = rootReference.get(); if (root == null) { if (count > 0) { add(element, count); } return 0; } int[] result = new int[1]; // used as a mutable int reference to hold result AvlNode<E> newRoot = root.setCount(comparator(), element, count, result); rootReference.checkAndSet(root, newRoot); return result[0]; } @CanIgnoreReturnValue @Override public boolean setCount(@ParametricNullness E element, int oldCount, int newCount) { checkNonnegative(newCount, "newCount"); checkNonnegative(oldCount, "oldCount"); checkArgument(range.contains(element)); AvlNode<E> root = rootReference.get(); if (root == null) { if (oldCount == 0) { if (newCount > 0) { add(element, newCount); } return true; } else { return false; } } int[] result = new int[1]; // used as a mutable int reference to hold result AvlNode<E> newRoot = root.setCount(comparator(), element, oldCount, newCount, result); rootReference.checkAndSet(root, newRoot); return result[0] == oldCount; } @Override public void clear() { if (!range.hasLowerBound() && !range.hasUpperBound()) { // We can do this in O(n) rather than removing one by one, which could force rebalancing. for (AvlNode<E> current = header.succ(); current != header; ) { AvlNode<E> next = current.succ(); current.elemCount = 0; // Also clear these fields so that one deleted Entry doesn't retain all elements. current.left = null; current.right = null; current.pred = null; current.succ = null; current = next; } successor(header, header); rootReference.clear(); } else { // TODO(cpovirk): Perhaps we can optimize in this case, too? Iterators.clear(entryIterator()); } } private Entry<E> wrapEntry(final AvlNode<E> baseEntry) { return new Multisets.AbstractEntry<E>() { @Override @ParametricNullness public E getElement() { return baseEntry.getElement(); } @Override public int getCount() { int result = baseEntry.getCount(); if (result == 0) { return count(getElement()); } else { return result; } } }; } /** Returns the first node in the tree that is in range. */ @CheckForNull private AvlNode<E> firstNode() { AvlNode<E> root = rootReference.get(); if (root == null) { return null; } AvlNode<E> node; if (range.hasLowerBound()) { // The cast is safe because of the hasLowerBound check. E endpoint = uncheckedCastNullableTToT(range.getLowerEndpoint()); node = root.ceiling(comparator(), endpoint); if (node == null) { return null; } if (range.getLowerBoundType() == BoundType.OPEN && comparator().compare(endpoint, node.getElement()) == 0) { node = node.succ(); } } else { node = header.succ(); } return (node == header || !range.contains(node.getElement())) ? null : node; } @CheckForNull private AvlNode<E> lastNode() { AvlNode<E> root = rootReference.get(); if (root == null) { return null; } AvlNode<E> node; if (range.hasUpperBound()) { // The cast is safe because of the hasUpperBound check. E endpoint = uncheckedCastNullableTToT(range.getUpperEndpoint()); node = root.floor(comparator(), endpoint); if (node == null) { return null; } if (range.getUpperBoundType() == BoundType.OPEN && comparator().compare(endpoint, node.getElement()) == 0) { node = node.pred(); } } else { node = header.pred(); } return (node == header || !range.contains(node.getElement())) ? null : node; } @Override Iterator<E> elementIterator() { return Multisets.elementIterator(entryIterator()); } @Override Iterator<Entry<E>> entryIterator() { return new Iterator<Entry<E>>() { @CheckForNull AvlNode<E> current = firstNode(); @CheckForNull Entry<E> prevEntry; @Override public boolean hasNext() { if (current == null) { return false; } else if (range.tooHigh(current.getElement())) { current = null; return false; } else { return true; } } @Override public Entry<E> next() { if (!hasNext()) { throw new NoSuchElementException(); } // requireNonNull is safe because current is only nulled out after iteration is complete. Entry<E> result = wrapEntry(requireNonNull(current)); prevEntry = result; if (current.succ() == header) { current = null; } else { current = current.succ(); } return result; } @Override public void remove() { checkState(prevEntry != null, "no calls to next() since the last call to remove()"); setCount(prevEntry.getElement(), 0); prevEntry = null; } }; } @Override Iterator<Entry<E>> descendingEntryIterator() { return new Iterator<Entry<E>>() { @CheckForNull AvlNode<E> current = lastNode(); @CheckForNull Entry<E> prevEntry = null; @Override public boolean hasNext() { if (current == null) { return false; } else if (range.tooLow(current.getElement())) { current = null; return false; } else { return true; } } @Override public Entry<E> next() { if (!hasNext()) { throw new NoSuchElementException(); } // requireNonNull is safe because current is only nulled out after iteration is complete. requireNonNull(current); Entry<E> result = wrapEntry(current); prevEntry = result; if (current.pred() == header) { current = null; } else { current = current.pred(); } return result; } @Override public void remove() { checkState(prevEntry != null, "no calls to next() since the last call to remove()"); setCount(prevEntry.getElement(), 0); prevEntry = null; } }; } @Override public void forEachEntry(ObjIntConsumer<? super E> action) { checkNotNull(action); for (AvlNode<E> node = firstNode(); node != header && node != null && !range.tooHigh(node.getElement()); node = node.succ()) { action.accept(node.getElement(), node.getCount()); } } @Override public Iterator<E> iterator() { return Multisets.iteratorImpl(this); } @Override public SortedMultiset<E> headMultiset(@ParametricNullness E upperBound, BoundType boundType) { return new TreeMultiset<>( rootReference, range.intersect(GeneralRange.upTo(comparator(), upperBound, boundType)), header); } @Override public SortedMultiset<E> tailMultiset(@ParametricNullness E lowerBound, BoundType boundType) { return new TreeMultiset<>( rootReference, range.intersect(GeneralRange.downTo(comparator(), lowerBound, boundType)), header); } private static final class Reference<T> { @CheckForNull private T value; @CheckForNull public T get() { return value; } public void checkAndSet(@CheckForNull T expected, @CheckForNull T newValue) { if (value != expected) { throw new ConcurrentModificationException(); } value = newValue; } void clear() { value = null; } } private static final class AvlNode<E extends @Nullable Object> { /* * For "normal" nodes, the type of this field is `E`, not `@Nullable E` (though note that E is a * type that can include null, as in a TreeMultiset<@Nullable String>). * * For the header node, though, this field contains `null`, regardless of the type of the * multiset. * * Most code that operates on an AvlNode never operates on the header node. Such code can access * the elem field without a null check by calling getElement(). */ @CheckForNull private final E elem; // elemCount is 0 iff this node has been deleted. private int elemCount; private int distinctElements; private long totalCount; private int height; @CheckForNull private AvlNode<E> left; @CheckForNull private AvlNode<E> right; /* * pred and succ are nullable after construction, but we always call successor() to initialize * them immediately thereafter. * * They may be subsequently nulled out by TreeMultiset.clear(). I think that the only place that * we can reference a node whose fields have been cleared is inside the iterator (and presumably * only under concurrent modification). * * To access these fields when you know that they are not null, call the pred() and succ() * methods, which perform null checks before returning the fields. */ @CheckForNull private AvlNode<E> pred; @CheckForNull private AvlNode<E> succ; AvlNode(@ParametricNullness E elem, int elemCount) { checkArgument(elemCount > 0); this.elem = elem; this.elemCount = elemCount; this.totalCount = elemCount; this.distinctElements = 1; this.height = 1; this.left = null; this.right = null; } /** Constructor for the header node. */ AvlNode() { this.elem = null; this.elemCount = 1; } // For discussion of pred() and succ(), see the comment on the pred and succ fields. private AvlNode<E> pred() { return requireNonNull(pred); } private AvlNode<E> succ() { return requireNonNull(succ); } int count(Comparator<? super E> comparator, @ParametricNullness E e) { int cmp = comparator.compare(e, getElement()); if (cmp < 0) { return (left == null) ? 0 : left.count(comparator, e); } else if (cmp > 0) { return (right == null) ? 0 : right.count(comparator, e); } else { return elemCount; } } private AvlNode<E> addRightChild(@ParametricNullness E e, int count) { right = new AvlNode<>(e, count); successor(this, right, succ()); height = Math.max(2, height); distinctElements++; totalCount += count; return this; } private AvlNode<E> addLeftChild(@ParametricNullness E e, int count) { left = new AvlNode<>(e, count); successor(pred(), left, this); height = Math.max(2, height); distinctElements++; totalCount += count; return this; } AvlNode<E> add( Comparator<? super E> comparator, @ParametricNullness E e, int count, int[] result) { /* * It speeds things up considerably to unconditionally add count to totalCount here, * but that destroys failure atomicity in the case of count overflow. =( */ int cmp = comparator.compare(e, getElement()); if (cmp < 0) { AvlNode<E> initLeft = left; if (initLeft == null) { result[0] = 0; return addLeftChild(e, count); } int initHeight = initLeft.height; left = initLeft.add(comparator, e, count, result); if (result[0] == 0) { distinctElements++; } this.totalCount += count; return (left.height == initHeight) ? this : rebalance(); } else if (cmp > 0) { AvlNode<E> initRight = right; if (initRight == null) { result[0] = 0; return addRightChild(e, count); } int initHeight = initRight.height; right = initRight.add(comparator, e, count, result); if (result[0] == 0) { distinctElements++; } this.totalCount += count; return (right.height == initHeight) ? this : rebalance(); } // adding count to me! No rebalance possible. result[0] = elemCount; long resultCount = (long) elemCount + count; checkArgument(resultCount <= Integer.MAX_VALUE); this.elemCount += count; this.totalCount += count; return this; } @CheckForNull AvlNode<E> remove( Comparator<? super E> comparator, @ParametricNullness E e, int count, int[] result) { int cmp = comparator.compare(e, getElement()); if (cmp < 0) { AvlNode<E> initLeft = left; if (initLeft == null) { result[0] = 0; return this; } left = initLeft.remove(comparator, e, count, result); if (result[0] > 0) { if (count >= result[0]) { this.distinctElements--; this.totalCount -= result[0]; } else { this.totalCount -= count; } } return (result[0] == 0) ? this : rebalance(); } else if (cmp > 0) { AvlNode<E> initRight = right; if (initRight == null) { result[0] = 0; return this; } right = initRight.remove(comparator, e, count, result); if (result[0] > 0) { if (count >= result[0]) { this.distinctElements--; this.totalCount -= result[0]; } else { this.totalCount -= count; } } return rebalance(); } // removing count from me! result[0] = elemCount; if (count >= elemCount) { return deleteMe(); } else { this.elemCount -= count; this.totalCount -= count; return this; } } @CheckForNull AvlNode<E> setCount( Comparator<? super E> comparator, @ParametricNullness E e, int count, int[] result) { int cmp = comparator.compare(e, getElement()); if (cmp < 0) { AvlNode<E> initLeft = left; if (initLeft == null) { result[0] = 0; return (count > 0) ? addLeftChild(e, count) : this; } left = initLeft.setCount(comparator, e, count, result); if (count == 0 && result[0] != 0) { this.distinctElements--; } else if (count > 0 && result[0] == 0) { this.distinctElements++; } this.totalCount += count - result[0]; return rebalance(); } else if (cmp > 0) { AvlNode<E> initRight = right; if (initRight == null) { result[0] = 0; return (count > 0) ? addRightChild(e, count) : this; } right = initRight.setCount(comparator, e, count, result); if (count == 0 && result[0] != 0) { this.distinctElements--; } else if (count > 0 && result[0] == 0) { this.distinctElements++; } this.totalCount += count - result[0]; return rebalance(); } // setting my count result[0] = elemCount; if (count == 0) { return deleteMe(); } this.totalCount += count - elemCount; this.elemCount = count; return this; } @CheckForNull AvlNode<E> setCount( Comparator<? super E> comparator, @ParametricNullness E e, int expectedCount, int newCount, int[] result) { int cmp = comparator.compare(e, getElement()); if (cmp < 0) { AvlNode<E> initLeft = left; if (initLeft == null) { result[0] = 0; if (expectedCount == 0 && newCount > 0) { return addLeftChild(e, newCount); } return this; } left = initLeft.setCount(comparator, e, expectedCount, newCount, result); if (result[0] == expectedCount) { if (newCount == 0 && result[0] != 0) { this.distinctElements--; } else if (newCount > 0 && result[0] == 0) { this.distinctElements++; } this.totalCount += newCount - result[0]; } return rebalance(); } else if (cmp > 0) { AvlNode<E> initRight = right; if (initRight == null) { result[0] = 0; if (expectedCount == 0 && newCount > 0) { return addRightChild(e, newCount); } return this; } right = initRight.setCount(comparator, e, expectedCount, newCount, result); if (result[0] == expectedCount) { if (newCount == 0 && result[0] != 0) { this.distinctElements--; } else if (newCount > 0 && result[0] == 0) { this.distinctElements++; } this.totalCount += newCount - result[0]; } return rebalance(); } // setting my count result[0] = elemCount; if (expectedCount == elemCount) { if (newCount == 0) { return deleteMe(); } this.totalCount += newCount - elemCount; this.elemCount = newCount; } return this; } @CheckForNull private AvlNode<E> deleteMe() { int oldElemCount = this.elemCount; this.elemCount = 0; successor(pred(), succ()); if (left == null) { return right; } else if (right == null) { return left; } else if (left.height >= right.height) { AvlNode<E> newTop = pred(); // newTop is the maximum node in my left subtree newTop.left = left.removeMax(newTop); newTop.right = right; newTop.distinctElements = distinctElements - 1; newTop.totalCount = totalCount - oldElemCount; return newTop.rebalance(); } else { AvlNode<E> newTop = succ(); newTop.right = right.removeMin(newTop); newTop.left = left; newTop.distinctElements = distinctElements - 1; newTop.totalCount = totalCount - oldElemCount; return newTop.rebalance(); } } // Removes the minimum node from this subtree to be reused elsewhere @CheckForNull private AvlNode<E> removeMin(AvlNode<E> node) { if (left == null) { return right; } else { left = left.removeMin(node); distinctElements--; totalCount -= node.elemCount; return rebalance(); } } // Removes the maximum node from this subtree to be reused elsewhere @CheckForNull private AvlNode<E> removeMax(AvlNode<E> node) { if (right == null) { return left; } else { right = right.removeMax(node); distinctElements--; totalCount -= node.elemCount; return rebalance(); } } private void recomputeMultiset() { this.distinctElements = 1 + TreeMultiset.distinctElements(left) + TreeMultiset.distinctElements(right); this.totalCount = elemCount + totalCount(left) + totalCount(right); } private void recomputeHeight() { this.height = 1 + Math.max(height(left), height(right)); } private void recompute() { recomputeMultiset(); recomputeHeight(); } private AvlNode<E> rebalance() { switch (balanceFactor()) { case -2: // requireNonNull is safe because right must exist in order to get a negative factor. requireNonNull(right); if (right.balanceFactor() > 0) { right = right.rotateRight(); } return rotateLeft(); case 2: // requireNonNull is safe because left must exist in order to get a positive factor. requireNonNull(left); if (left.balanceFactor() < 0) { left = left.rotateLeft(); } return rotateRight(); default: recomputeHeight(); return this; } } private int balanceFactor() { return height(left) - height(right); } private AvlNode<E> rotateLeft() { checkState(right != null); AvlNode<E> newTop = right; this.right = newTop.left; newTop.left = this; newTop.totalCount = this.totalCount; newTop.distinctElements = this.distinctElements; this.recompute(); newTop.recomputeHeight(); return newTop; } private AvlNode<E> rotateRight() { checkState(left != null); AvlNode<E> newTop = left; this.left = newTop.right; newTop.right = this; newTop.totalCount = this.totalCount; newTop.distinctElements = this.distinctElements; this.recompute(); newTop.recomputeHeight(); return newTop; } private static long totalCount(@CheckForNull AvlNode<?> node) { return (node == null) ? 0 : node.totalCount; } private static int height(@CheckForNull AvlNode<?> node) { return (node == null) ? 0 : node.height; } @CheckForNull private AvlNode<E> ceiling(Comparator<? super E> comparator, @ParametricNullness E e) { int cmp = comparator.compare(e, getElement()); if (cmp < 0) { return (left == null) ? this : MoreObjects.firstNonNull(left.ceiling(comparator, e), this); } else if (cmp == 0) { return this; } else { return (right == null) ? null : right.ceiling(comparator, e); } } @CheckForNull private AvlNode<E> floor(Comparator<? super E> comparator, @ParametricNullness E e) { int cmp = comparator.compare(e, getElement()); if (cmp > 0) { return (right == null) ? this : MoreObjects.firstNonNull(right.floor(comparator, e), this); } else if (cmp == 0) { return this; } else { return (left == null) ? null : left.floor(comparator, e); } } @ParametricNullness E getElement() { // For discussion of this cast, see the comment on the elem field. return uncheckedCastNullableTToT(elem); } int getCount() { return elemCount; } @Override public String toString() { return Multisets.immutableEntry(getElement(), getCount()).toString(); } } private static <T extends @Nullable Object> void successor(AvlNode<T> a, AvlNode<T> b) { a.succ = b; b.pred = a; } private static <T extends @Nullable Object> void successor( AvlNode<T> a, AvlNode<T> b, AvlNode<T> c) { successor(a, b); successor(b, c); } /* * TODO(jlevy): Decide whether entrySet() should return entries with an equals() method that * calls the comparator to compare the two keys. If that change is made, * AbstractMultiset.equals() can simply check whether two multisets have equal entry sets. */ /** * @serialData the comparator, the number of distinct elements, the first element, its count, the * second element, its count, and so on */ @J2ktIncompatible @GwtIncompatible // java.io.ObjectOutputStream private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeObject(elementSet().comparator()); Serialization.writeMultiset(this, stream); } @J2ktIncompatible @GwtIncompatible // java.io.ObjectInputStream private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); @SuppressWarnings("unchecked") // reading data stored by writeObject Comparator<? super E> comparator = (Comparator<? super E>) requireNonNull(stream.readObject()); Serialization.getFieldSetter(AbstractSortedMultiset.class, "comparator").set(this, comparator); Serialization.getFieldSetter(TreeMultiset.class, "range") .set(this, GeneralRange.all(comparator)); Serialization.getFieldSetter(TreeMultiset.class, "rootReference") .set(this, new Reference<AvlNode<E>>()); AvlNode<E> header = new AvlNode<>(); Serialization.getFieldSetter(TreeMultiset.class, "header").set(this, header); successor(header, header); Serialization.populateMultiset(this, stream); } @GwtIncompatible // not needed in emulated source @J2ktIncompatible private static final long serialVersionUID = 1; }
google/guava
guava/src/com/google/common/collect/TreeMultiset.java
243
/* * 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.Iterators; 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.ArrayList; 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(); } // super.toArray() may misbehave if size() is inaccurate, at least on old versions of Android. // https://code.google.com/p/android/issues/detail?id=36519 / http://r.android.com/47508 @Override public Object[] toArray() { return toArrayList(this).toArray(); } @Override public <E> E[] toArray(E[] a) { return toArrayList(this).toArray(a); } } private static <E> ArrayList<E> toArrayList(Collection<E> c) { // Avoid calling ArrayList(Collection), which may call back into toArray. ArrayList<E> result = new ArrayList<>(c.size()); Iterators.addAll(result, c.iterator()); return result; } 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); } // super.toArray() may misbehave if size() is inaccurate, at least on old versions of Android. // https://code.google.com/p/android/issues/detail?id=36519 / http://r.android.com/47508 @Override public Object[] toArray() { return toArrayList(this).toArray(); } @Override public <E> E[] toArray(E[] a) { return toArrayList(this).toArray(a); } } 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
244
// 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 package com.google.protobuf; import static com.google.protobuf.Internal.checkNotNull; import com.google.protobuf.LazyField.LazyIterator; import java.io.IOException; import java.util.ArrayList; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Map.Entry; /** * A class which represents an arbitrary set of fields of some message type. This is used to * implement {@link DynamicMessage}, and also to represent extensions in {@link GeneratedMessage}. * This class is package-private, since outside users should probably be using {@link * DynamicMessage}. * * @author [email protected] Kenton Varda */ final class FieldSet<T extends FieldSet.FieldDescriptorLite<T>> { /** * Interface for a FieldDescriptor or lite extension descriptor. This prevents FieldSet from * depending on {@link Descriptors.FieldDescriptor}. */ public interface FieldDescriptorLite<T extends FieldDescriptorLite<T>> extends Comparable<T> { int getNumber(); WireFormat.FieldType getLiteType(); WireFormat.JavaType getLiteJavaType(); boolean isRepeated(); boolean isPacked(); Internal.EnumLiteMap<?> getEnumType(); // If getLiteJavaType() == MESSAGE, this merges a message object of the // type into a builder of the type. Returns {@code to}. MessageLite.Builder internalMergeFrom(MessageLite.Builder to, MessageLite from); } private static final int DEFAULT_FIELD_MAP_ARRAY_SIZE = 16; private final SmallSortedMap<T, Object> fields; private boolean isImmutable; private boolean hasLazyField; /** Construct a new FieldSet. */ private FieldSet() { this.fields = SmallSortedMap.newFieldMap(DEFAULT_FIELD_MAP_ARRAY_SIZE); } /** Construct an empty FieldSet. This is only used to initialize DEFAULT_INSTANCE. */ @SuppressWarnings("unused") private FieldSet(final boolean dummy) { this(SmallSortedMap.<T>newFieldMap(0)); makeImmutable(); } private FieldSet(SmallSortedMap<T, Object> fields) { this.fields = fields; makeImmutable(); } /** Construct a new FieldSet. */ public static <T extends FieldSet.FieldDescriptorLite<T>> FieldSet<T> newFieldSet() { return new FieldSet<T>(); } /** Get an immutable empty FieldSet. */ @SuppressWarnings("unchecked") public static <T extends FieldSet.FieldDescriptorLite<T>> FieldSet<T> emptySet() { return DEFAULT_INSTANCE; } /** Construct a new Builder. */ public static <T extends FieldDescriptorLite<T>> Builder<T> newBuilder() { return new Builder<T>(); } @SuppressWarnings("rawtypes") private static final FieldSet DEFAULT_INSTANCE = new FieldSet(true); /** Returns {@code true} if empty, {@code false} otherwise. */ boolean isEmpty() { return fields.isEmpty(); } /** Make this FieldSet immutable from this point forward. */ public void makeImmutable() { if (isImmutable) { return; } for (int i = 0; i < fields.getNumArrayEntries(); ++i) { Entry<T, Object> entry = fields.getArrayEntryAt(i); if (entry.getValue() instanceof GeneratedMessageLite) { ((GeneratedMessageLite<?, ?>) entry.getValue()).makeImmutable(); } } fields.makeImmutable(); isImmutable = true; } /** * Returns whether the FieldSet is immutable. This is true if it is the {@link #emptySet} or if * {@link #makeImmutable} were called. * * @return whether the FieldSet is immutable. */ public boolean isImmutable() { return isImmutable; } @Override public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof FieldSet)) { return false; } FieldSet<?> other = (FieldSet<?>) o; return fields.equals(other.fields); } @Override public int hashCode() { return fields.hashCode(); } /** * Clones the FieldSet. The returned FieldSet will be mutable even if the original FieldSet was * immutable. * * @return the newly cloned FieldSet */ @Override public FieldSet<T> clone() { // We can't just call fields.clone because List objects in the map // should not be shared. FieldSet<T> clone = FieldSet.newFieldSet(); for (int i = 0; i < fields.getNumArrayEntries(); i++) { Map.Entry<T, Object> entry = fields.getArrayEntryAt(i); clone.setField(entry.getKey(), entry.getValue()); } for (Map.Entry<T, Object> entry : fields.getOverflowEntries()) { clone.setField(entry.getKey(), entry.getValue()); } clone.hasLazyField = hasLazyField; return clone; } // ================================================================= /** See {@link Message.Builder#clear()}. */ public void clear() { fields.clear(); hasLazyField = false; } /** Get a simple map containing all the fields. */ public Map<T, Object> getAllFields() { if (hasLazyField) { SmallSortedMap<T, Object> result = cloneAllFieldsMap(fields, /* copyList= */ false, /* resolveLazyFields= */ true); if (fields.isImmutable()) { result.makeImmutable(); } return result; } return fields.isImmutable() ? fields : Collections.unmodifiableMap(fields); } private static <T extends FieldDescriptorLite<T>> SmallSortedMap<T, Object> cloneAllFieldsMap( SmallSortedMap<T, Object> fields, boolean copyList, boolean resolveLazyFields) { SmallSortedMap<T, Object> result = SmallSortedMap.newFieldMap(DEFAULT_FIELD_MAP_ARRAY_SIZE); for (int i = 0; i < fields.getNumArrayEntries(); i++) { cloneFieldEntry(result, fields.getArrayEntryAt(i), copyList, resolveLazyFields); } for (Map.Entry<T, Object> entry : fields.getOverflowEntries()) { cloneFieldEntry(result, entry, copyList, resolveLazyFields); } return result; } private static <T extends FieldDescriptorLite<T>> void cloneFieldEntry( Map<T, Object> map, Map.Entry<T, Object> entry, boolean copyList, boolean resolveLazyFields) { T key = entry.getKey(); Object value = entry.getValue(); if (resolveLazyFields && value instanceof LazyField) { map.put(key, ((LazyField) value).getValue()); } else if (copyList && value instanceof List) { map.put(key, new ArrayList<>((List<?>) value)); } else { map.put(key, value); } } /** * Get an iterator to the field map. This iterator should not be leaked out of the protobuf * library as it is not protected from mutation when fields is not immutable. */ public Iterator<Map.Entry<T, Object>> iterator() { if (hasLazyField) { return new LazyIterator<T>(fields.entrySet().iterator()); } return fields.entrySet().iterator(); } /** * Get an iterator over the fields in the map in descending (i.e. reverse) order. This iterator * should not be leaked out of the protobuf library as it is not protected from mutation when * fields is not immutable. */ Iterator<Map.Entry<T, Object>> descendingIterator() { if (hasLazyField) { return new LazyIterator<T>(fields.descendingEntrySet().iterator()); } return fields.descendingEntrySet().iterator(); } /** Useful for implementing {@link Message#hasField(Descriptors.FieldDescriptor)}. */ public boolean hasField(final T descriptor) { if (descriptor.isRepeated()) { throw new IllegalArgumentException("hasField() can only be called on non-repeated fields."); } return fields.get(descriptor) != null; } /** * Useful for implementing {@link Message#getField(Descriptors.FieldDescriptor)}. This method * returns {@code null} if the field is not set; in this case it is up to the caller to fetch the * field's default value. */ public Object getField(final T descriptor) { Object o = fields.get(descriptor); if (o instanceof LazyField) { return ((LazyField) o).getValue(); } return o; } /** * Useful for implementing {@link Message.Builder#setField(Descriptors.FieldDescriptor,Object)}. */ @SuppressWarnings({"unchecked", "rawtypes"}) public void setField(final T descriptor, Object value) { if (descriptor.isRepeated()) { if (!(value instanceof List)) { throw new IllegalArgumentException( "Wrong object type used with protocol message reflection."); } // Wrap the contents in a new list so that the caller cannot change // the list's contents after setting it. final List newList = new ArrayList<>(); newList.addAll((List) value); for (final Object element : newList) { verifyType(descriptor, element); } value = newList; } else { verifyType(descriptor, value); } if (value instanceof LazyField) { hasLazyField = true; } fields.put(descriptor, value); } /** Useful for implementing {@link Message.Builder#clearField(Descriptors.FieldDescriptor)}. */ public void clearField(final T descriptor) { fields.remove(descriptor); if (fields.isEmpty()) { hasLazyField = false; } } /** Useful for implementing {@link Message#getRepeatedFieldCount(Descriptors.FieldDescriptor)}. */ public int getRepeatedFieldCount(final T descriptor) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "getRepeatedField() can only be called on repeated fields."); } final Object value = getField(descriptor); if (value == null) { return 0; } else { return ((List<?>) value).size(); } } /** Useful for implementing {@link Message#getRepeatedField(Descriptors.FieldDescriptor,int)}. */ public Object getRepeatedField(final T descriptor, final int index) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "getRepeatedField() can only be called on repeated fields."); } final Object value = getField(descriptor); if (value == null) { throw new IndexOutOfBoundsException(); } else { return ((List<?>) value).get(index); } } /** * Useful for implementing {@link * Message.Builder#setRepeatedField(Descriptors.FieldDescriptor,int,Object)}. */ @SuppressWarnings("unchecked") public void setRepeatedField(final T descriptor, final int index, final Object value) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "getRepeatedField() can only be called on repeated fields."); } final Object list = getField(descriptor); if (list == null) { throw new IndexOutOfBoundsException(); } verifyType(descriptor, value); ((List<Object>) list).set(index, value); } /** * Useful for implementing {@link * Message.Builder#addRepeatedField(Descriptors.FieldDescriptor,Object)}. */ @SuppressWarnings("unchecked") public void addRepeatedField(final T descriptor, final Object value) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "addRepeatedField() can only be called on repeated fields."); } verifyType(descriptor, value); final Object existingValue = getField(descriptor); List<Object> list; if (existingValue == null) { list = new ArrayList<Object>(); fields.put(descriptor, list); } else { list = (List<Object>) existingValue; } list.add(value); } /** * Verifies that the given object is of the correct type to be a valid value for the given field. * (For repeated fields, this checks if the object is the right type to be one element of the * field.) * * @throws IllegalArgumentException the value is not of the right type */ private void verifyType(final T descriptor, final Object value) { if (!isValidType(descriptor.getLiteType(), value)) { throw new IllegalArgumentException( String.format( "Wrong object type used with protocol message reflection.\n" + "Field number: %d, field java type: %s, value type: %s\n", descriptor.getNumber(), descriptor.getLiteType().getJavaType(), value.getClass().getName())); } } private static boolean isValidType(final WireFormat.FieldType type, final Object value) { checkNotNull(value); switch (type.getJavaType()) { case INT: return value instanceof Integer; case LONG: return value instanceof Long; case FLOAT: return value instanceof Float; case DOUBLE: return value instanceof Double; case BOOLEAN: return value instanceof Boolean; case STRING: return value instanceof String; case BYTE_STRING: return value instanceof ByteString || value instanceof byte[]; case ENUM: return (value instanceof Integer || value instanceof Internal.EnumLite); case MESSAGE: return (value instanceof MessageLite) || (value instanceof LazyField); } return false; } // ================================================================= // Parsing and serialization /** * See {@link Message#isInitialized()}. Note: Since {@code FieldSet} itself does not have any way * of knowing about required fields that aren't actually present in the set, it is up to the * caller to check that all required fields are present. */ public boolean isInitialized() { for (int i = 0; i < fields.getNumArrayEntries(); i++) { if (!isInitialized(fields.getArrayEntryAt(i))) { return false; } } for (final Map.Entry<T, Object> entry : fields.getOverflowEntries()) { if (!isInitialized(entry)) { return false; } } return true; } private static <T extends FieldDescriptorLite<T>> boolean isInitialized( final Map.Entry<T, Object> entry) { final T descriptor = entry.getKey(); if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { if (descriptor.isRepeated()) { for (final Object element : (List<?>) entry.getValue()) { if (!isMessageFieldValueInitialized(element)) { return false; } } } else { return isMessageFieldValueInitialized(entry.getValue()); } } return true; } private static boolean isMessageFieldValueInitialized(Object value) { if (value instanceof MessageLiteOrBuilder) { // Message fields cannot have builder values in FieldSet, but can in FieldSet.Builder, and // this method is used by FieldSet.Builder.isInitialized. return ((MessageLiteOrBuilder) value).isInitialized(); } else if (value instanceof LazyField) { return true; } else { throw new IllegalArgumentException( "Wrong object type used with protocol message reflection."); } } /** * Given a field type, return the wire type. * * @return One of the {@code WIRETYPE_} constants defined in {@link WireFormat}. */ static int getWireFormatForFieldType(final WireFormat.FieldType type, boolean isPacked) { if (isPacked) { return WireFormat.WIRETYPE_LENGTH_DELIMITED; } else { return type.getWireType(); } } /** Like {@link Message.Builder#mergeFrom(Message)}, but merges from another {@link FieldSet}. */ public void mergeFrom(final FieldSet<T> other) { for (int i = 0; i < other.fields.getNumArrayEntries(); i++) { mergeFromField(other.fields.getArrayEntryAt(i)); } for (final Map.Entry<T, Object> entry : other.fields.getOverflowEntries()) { mergeFromField(entry); } } private static Object cloneIfMutable(Object value) { if (value instanceof byte[]) { byte[] bytes = (byte[]) value; byte[] copy = new byte[bytes.length]; System.arraycopy(bytes, 0, copy, 0, bytes.length); return copy; } else { return value; } } @SuppressWarnings({"unchecked", "rawtypes"}) private void mergeFromField(final Map.Entry<T, Object> entry) { final T descriptor = entry.getKey(); Object otherValue = entry.getValue(); boolean isLazyField = otherValue instanceof LazyField; if (descriptor.isRepeated()) { if (isLazyField) { throw new IllegalStateException("Lazy fields can not be repeated"); } Object value = getField(descriptor); if (value == null) { value = new ArrayList<>(); } for (Object element : (List) otherValue) { ((List) value).add(cloneIfMutable(element)); } fields.put(descriptor, value); } else if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { Object value = getField(descriptor); if (value == null) { // New field. fields.put(descriptor, cloneIfMutable(otherValue)); if (isLazyField) { hasLazyField = true; } } else { // There is an existing field. Need to merge the messages. if (otherValue instanceof LazyField) { // Extract the actual value for lazy fields. otherValue = ((LazyField) otherValue).getValue(); } value = descriptor .internalMergeFrom(((MessageLite) value).toBuilder(), (MessageLite) otherValue) .build(); fields.put(descriptor, value); } } else { if (isLazyField) { throw new IllegalStateException("Lazy fields must be message-valued"); } fields.put(descriptor, cloneIfMutable(otherValue)); } } /** * Read a field of any primitive type for immutable messages from a CodedInputStream. Enums, * groups, and embedded messages are not handled by this method. * * @param input the stream from which to read * @param type declared type of the field * @param checkUtf8 When true, check that the input is valid UTF-8 * @return an object representing the field's value, of the exact type which would be returned by * {@link Message#getField(Descriptors.FieldDescriptor)} for this field */ public static Object readPrimitiveField( CodedInputStream input, final WireFormat.FieldType type, boolean checkUtf8) throws IOException { if (checkUtf8) { return WireFormat.readPrimitiveField(input, type, WireFormat.Utf8Validation.STRICT); } else { return WireFormat.readPrimitiveField(input, type, WireFormat.Utf8Validation.LOOSE); } } /** See {@link Message#writeTo(CodedOutputStream)}. */ public void writeTo(final CodedOutputStream output) throws IOException { for (int i = 0; i < fields.getNumArrayEntries(); i++) { final Map.Entry<T, Object> entry = fields.getArrayEntryAt(i); writeField(entry.getKey(), entry.getValue(), output); } for (final Map.Entry<T, Object> entry : fields.getOverflowEntries()) { writeField(entry.getKey(), entry.getValue(), output); } } /** Like {@link #writeTo} but uses MessageSet wire format. */ public void writeMessageSetTo(final CodedOutputStream output) throws IOException { for (int i = 0; i < fields.getNumArrayEntries(); i++) { writeMessageSetTo(fields.getArrayEntryAt(i), output); } for (final Map.Entry<T, Object> entry : fields.getOverflowEntries()) { writeMessageSetTo(entry, output); } } private void writeMessageSetTo(final Map.Entry<T, Object> entry, final CodedOutputStream output) throws IOException { final T descriptor = entry.getKey(); if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE && !descriptor.isRepeated() && !descriptor.isPacked()) { Object value = entry.getValue(); if (value instanceof LazyField) { ByteString valueBytes = ((LazyField) value).toByteString(); output.writeRawMessageSetExtension(entry.getKey().getNumber(), valueBytes); } else { output.writeMessageSetExtension(entry.getKey().getNumber(), (MessageLite) value); } } else { writeField(descriptor, entry.getValue(), output); } } /** * Write a single tag-value pair to the stream. * * @param output The output stream. * @param type The field's type. * @param number The field's number. * @param value Object representing the field's value. Must be of the exact type which would be * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field. */ static void writeElement( final CodedOutputStream output, final WireFormat.FieldType type, final int number, final Object value) throws IOException { // Special case for groups, which need a start and end tag; other fields // can just use writeTag() and writeFieldNoTag(). if (type == WireFormat.FieldType.GROUP) { output.writeGroup(number, (MessageLite) value); } else { output.writeTag(number, getWireFormatForFieldType(type, false)); writeElementNoTag(output, type, value); } } /** * Write a field of arbitrary type, without its tag, to the stream. * * @param output The output stream. * @param type The field's type. * @param value Object representing the field's value. Must be of the exact type which would be * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field. */ static void writeElementNoTag( final CodedOutputStream output, final WireFormat.FieldType type, final Object value) throws IOException { switch (type) { case DOUBLE: output.writeDoubleNoTag((Double) value); break; case FLOAT: output.writeFloatNoTag((Float) value); break; case INT64: output.writeInt64NoTag((Long) value); break; case UINT64: output.writeUInt64NoTag((Long) value); break; case INT32: output.writeInt32NoTag((Integer) value); break; case FIXED64: output.writeFixed64NoTag((Long) value); break; case FIXED32: output.writeFixed32NoTag((Integer) value); break; case BOOL: output.writeBoolNoTag((Boolean) value); break; case GROUP: output.writeGroupNoTag((MessageLite) value); break; case MESSAGE: output.writeMessageNoTag((MessageLite) value); break; case STRING: if (value instanceof ByteString) { output.writeBytesNoTag((ByteString) value); } else { output.writeStringNoTag((String) value); } break; case BYTES: if (value instanceof ByteString) { output.writeBytesNoTag((ByteString) value); } else { output.writeByteArrayNoTag((byte[]) value); } break; case UINT32: output.writeUInt32NoTag((Integer) value); break; case SFIXED32: output.writeSFixed32NoTag((Integer) value); break; case SFIXED64: output.writeSFixed64NoTag((Long) value); break; case SINT32: output.writeSInt32NoTag((Integer) value); break; case SINT64: output.writeSInt64NoTag((Long) value); break; case ENUM: if (value instanceof Internal.EnumLite) { output.writeEnumNoTag(((Internal.EnumLite) value).getNumber()); } else { output.writeEnumNoTag(((Integer) value).intValue()); } break; } } /** Write a single field. */ public static void writeField( final FieldDescriptorLite<?> descriptor, final Object value, final CodedOutputStream output) throws IOException { WireFormat.FieldType type = descriptor.getLiteType(); int number = descriptor.getNumber(); if (descriptor.isRepeated()) { final List<?> valueList = (List<?>) value; if (descriptor.isPacked()) { if (valueList.isEmpty()) { // The tag should not be written for empty packed fields. return; } output.writeTag(number, WireFormat.WIRETYPE_LENGTH_DELIMITED); // Compute the total data size so the length can be written. int dataSize = 0; for (final Object element : valueList) { dataSize += computeElementSizeNoTag(type, element); } output.writeUInt32NoTag(dataSize); // Write the data itself, without any tags. for (final Object element : valueList) { writeElementNoTag(output, type, element); } } else { for (final Object element : valueList) { writeElement(output, type, number, element); } } } else { if (value instanceof LazyField) { writeElement(output, type, number, ((LazyField) value).getValue()); } else { writeElement(output, type, number, value); } } } /** * See {@link Message#getSerializedSize()}. It's up to the caller to cache the resulting size if * desired. */ public int getSerializedSize() { int size = 0; for (int i = 0; i < fields.getNumArrayEntries(); i++) { final Map.Entry<T, Object> entry = fields.getArrayEntryAt(i); size += computeFieldSize(entry.getKey(), entry.getValue()); } for (final Map.Entry<T, Object> entry : fields.getOverflowEntries()) { size += computeFieldSize(entry.getKey(), entry.getValue()); } return size; } /** Like {@link #getSerializedSize} but uses MessageSet wire format. */ public int getMessageSetSerializedSize() { int size = 0; for (int i = 0; i < fields.getNumArrayEntries(); i++) { size += getMessageSetSerializedSize(fields.getArrayEntryAt(i)); } for (final Map.Entry<T, Object> entry : fields.getOverflowEntries()) { size += getMessageSetSerializedSize(entry); } return size; } private int getMessageSetSerializedSize(final Map.Entry<T, Object> entry) { final T descriptor = entry.getKey(); Object value = entry.getValue(); if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE && !descriptor.isRepeated() && !descriptor.isPacked()) { if (value instanceof LazyField) { return CodedOutputStream.computeLazyFieldMessageSetExtensionSize( entry.getKey().getNumber(), (LazyField) value); } else { return CodedOutputStream.computeMessageSetExtensionSize( entry.getKey().getNumber(), (MessageLite) value); } } else { return computeFieldSize(descriptor, value); } } /** * Compute the number of bytes that would be needed to encode a single tag/value pair of arbitrary * type. * * @param type The field's type. * @param number The field's number. * @param value Object representing the field's value. Must be of the exact type which would be * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field. */ static int computeElementSize( final WireFormat.FieldType type, final int number, final Object value) { int tagSize = CodedOutputStream.computeTagSize(number); if (type == WireFormat.FieldType.GROUP) { // Only count the end group tag for proto2 messages as for proto1 the end // group tag will be counted as a part of getSerializedSize(). tagSize *= 2; } return tagSize + computeElementSizeNoTag(type, value); } /** * Compute the number of bytes that would be needed to encode a particular value of arbitrary * type, excluding tag. * * @param type The field's type. * @param value Object representing the field's value. Must be of the exact type which would be * returned by {@link Message#getField(Descriptors.FieldDescriptor)} for this field. */ static int computeElementSizeNoTag(final WireFormat.FieldType type, final Object value) { switch (type) { case DOUBLE: return CodedOutputStream.computeDoubleSizeNoTag((Double) value); case FLOAT: return CodedOutputStream.computeFloatSizeNoTag((Float) value); case INT64: return CodedOutputStream.computeInt64SizeNoTag((Long) value); case UINT64: return CodedOutputStream.computeUInt64SizeNoTag((Long) value); case INT32: return CodedOutputStream.computeInt32SizeNoTag((Integer) value); case FIXED64: return CodedOutputStream.computeFixed64SizeNoTag((Long) value); case FIXED32: return CodedOutputStream.computeFixed32SizeNoTag((Integer) value); case BOOL: return CodedOutputStream.computeBoolSizeNoTag((Boolean) value); case GROUP: return CodedOutputStream.computeGroupSizeNoTag((MessageLite) value); case BYTES: if (value instanceof ByteString) { return CodedOutputStream.computeBytesSizeNoTag((ByteString) value); } else { return CodedOutputStream.computeByteArraySizeNoTag((byte[]) value); } case STRING: if (value instanceof ByteString) { return CodedOutputStream.computeBytesSizeNoTag((ByteString) value); } else { return CodedOutputStream.computeStringSizeNoTag((String) value); } case UINT32: return CodedOutputStream.computeUInt32SizeNoTag((Integer) value); case SFIXED32: return CodedOutputStream.computeSFixed32SizeNoTag((Integer) value); case SFIXED64: return CodedOutputStream.computeSFixed64SizeNoTag((Long) value); case SINT32: return CodedOutputStream.computeSInt32SizeNoTag((Integer) value); case SINT64: return CodedOutputStream.computeSInt64SizeNoTag((Long) value); case MESSAGE: if (value instanceof LazyField) { return CodedOutputStream.computeLazyFieldSizeNoTag((LazyField) value); } else { return CodedOutputStream.computeMessageSizeNoTag((MessageLite) value); } case ENUM: if (value instanceof Internal.EnumLite) { return CodedOutputStream.computeEnumSizeNoTag(((Internal.EnumLite) value).getNumber()); } else { return CodedOutputStream.computeEnumSizeNoTag((Integer) value); } } throw new RuntimeException("There is no way to get here, but the compiler thinks otherwise."); } /** Compute the number of bytes needed to encode a particular field. */ public static int computeFieldSize(final FieldDescriptorLite<?> descriptor, final Object value) { WireFormat.FieldType type = descriptor.getLiteType(); int number = descriptor.getNumber(); if (descriptor.isRepeated()) { List<?> valueList = (List<?>) value; if (descriptor.isPacked()) { if (valueList.isEmpty()) { return 0; } int dataSize = 0; for (final Object element : valueList) { dataSize += computeElementSizeNoTag(type, element); } return dataSize + CodedOutputStream.computeTagSize(number) + CodedOutputStream.computeUInt32SizeNoTag(dataSize); } else { int size = 0; for (final Object element : valueList) { size += computeElementSize(type, number, element); } return size; } } else { return computeElementSize(type, number, value); } } /** * A FieldSet Builder that accept a {@link MessageLite.Builder} as a field value. This is useful * for implementing methods in {@link MessageLite.Builder}. */ static final class Builder<T extends FieldDescriptorLite<T>> { private SmallSortedMap<T, Object> fields; private boolean hasLazyField; private boolean isMutable; private boolean hasNestedBuilders; private Builder() { this(SmallSortedMap.<T>newFieldMap(DEFAULT_FIELD_MAP_ARRAY_SIZE)); } private Builder(SmallSortedMap<T, Object> fields) { this.fields = fields; this.isMutable = true; } /** * Creates the FieldSet * * @throws UninitializedMessageException if a message field is missing required fields. */ public FieldSet<T> build() { return buildImpl(false); } /** Creates the FieldSet but does not validate that all required fields are present. */ public FieldSet<T> buildPartial() { return buildImpl(true); } /** * Creates the FieldSet. * * @param partial controls whether to do a build() or buildPartial() when converting submessage * builders to messages. */ private FieldSet<T> buildImpl(boolean partial) { if (fields.isEmpty()) { return FieldSet.emptySet(); } isMutable = false; SmallSortedMap<T, Object> fieldsForBuild = fields; if (hasNestedBuilders) { // Make a copy of the fields map with all Builders replaced by Message. fieldsForBuild = cloneAllFieldsMap(fields, /* copyList= */ false, /* resolveLazyFields= */ false); replaceBuilders(fieldsForBuild, partial); } FieldSet<T> fieldSet = new FieldSet<>(fieldsForBuild); fieldSet.hasLazyField = hasLazyField; return fieldSet; } private static <T extends FieldDescriptorLite<T>> void replaceBuilders( SmallSortedMap<T, Object> fieldMap, boolean partial) { for (int i = 0; i < fieldMap.getNumArrayEntries(); i++) { replaceBuilders(fieldMap.getArrayEntryAt(i), partial); } for (Map.Entry<T, Object> entry : fieldMap.getOverflowEntries()) { replaceBuilders(entry, partial); } } private static <T extends FieldDescriptorLite<T>> void replaceBuilders( Map.Entry<T, Object> entry, boolean partial) { entry.setValue(replaceBuilders(entry.getKey(), entry.getValue(), partial)); } private static <T extends FieldDescriptorLite<T>> Object replaceBuilders( T descriptor, Object value, boolean partial) { if (value == null) { return value; } if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { if (descriptor.isRepeated()) { if (!(value instanceof List)) { throw new IllegalStateException( "Repeated field should contains a List but actually contains type: " + value.getClass()); } @SuppressWarnings("unchecked") // We just check that value is an instance of List above. List<Object> list = (List<Object>) value; for (int i = 0; i < list.size(); i++) { Object oldElement = list.get(i); Object newElement = replaceBuilder(oldElement, partial); if (newElement != oldElement) { // If the list contains a Message.Builder, then make a copy of that list and then // modify the Message.Builder into a Message and return the new list. This way, the // existing Message.Builder will still be able to modify the inner fields of the // original FieldSet.Builder. if (list == value) { list = new ArrayList<>(list); } list.set(i, newElement); } } return list; } else { return replaceBuilder(value, partial); } } return value; } private static Object replaceBuilder(Object value, boolean partial) { if (!(value instanceof MessageLite.Builder)) { return value; } MessageLite.Builder builder = (MessageLite.Builder) value; if (partial) { return builder.buildPartial(); } return builder.build(); } /** Returns a new Builder using the fields from {@code fieldSet}. */ public static <T extends FieldDescriptorLite<T>> Builder<T> fromFieldSet(FieldSet<T> fieldSet) { Builder<T> builder = new Builder<T>( cloneAllFieldsMap( fieldSet.fields, /* copyList= */ true, /* resolveLazyFields= */ false)); builder.hasLazyField = fieldSet.hasLazyField; return builder; } // ================================================================= /** Get a simple map containing all the fields. */ public Map<T, Object> getAllFields() { if (hasLazyField) { SmallSortedMap<T, Object> result = cloneAllFieldsMap(fields, /* copyList= */ false, /* resolveLazyFields= */ true); if (fields.isImmutable()) { result.makeImmutable(); } else { replaceBuilders(result, true); } return result; } return fields.isImmutable() ? fields : Collections.unmodifiableMap(fields); } /** Useful for implementing {@link Message#hasField(Descriptors.FieldDescriptor)}. */ public boolean hasField(final T descriptor) { if (descriptor.isRepeated()) { throw new IllegalArgumentException("hasField() can only be called on non-repeated fields."); } return fields.get(descriptor) != null; } /** * Useful for implementing {@link Message#getField(Descriptors.FieldDescriptor)}. This method * returns {@code null} if the field is not set; in this case it is up to the caller to fetch * the field's default value. */ public Object getField(final T descriptor) { Object value = getFieldAllowBuilders(descriptor); return replaceBuilders(descriptor, value, true); } /** Same as {@link #getField(F)}, but allow a {@link MessageLite.Builder} to be returned. */ Object getFieldAllowBuilders(final T descriptor) { Object o = fields.get(descriptor); if (o instanceof LazyField) { return ((LazyField) o).getValue(); } return o; } private void ensureIsMutable() { if (!isMutable) { fields = cloneAllFieldsMap(fields, /* copyList= */ true, /* resolveLazyFields= */ false); isMutable = true; } } /** * Useful for implementing {@link Message.Builder#setField(Descriptors.FieldDescriptor, * Object)}. */ @SuppressWarnings({"unchecked", "rawtypes"}) public void setField(final T descriptor, Object value) { ensureIsMutable(); if (descriptor.isRepeated()) { if (!(value instanceof List)) { throw new IllegalArgumentException( "Wrong object type used with protocol message reflection."); } // Wrap the contents in a new list so that the caller cannot change // the list's contents after setting it. final List newList = new ArrayList((List) value); for (final Object element : newList) { verifyType(descriptor, element); hasNestedBuilders = hasNestedBuilders || element instanceof MessageLite.Builder; } value = newList; } else { verifyType(descriptor, value); } if (value instanceof LazyField) { hasLazyField = true; } hasNestedBuilders = hasNestedBuilders || value instanceof MessageLite.Builder; fields.put(descriptor, value); } /** Useful for implementing {@link Message.Builder#clearField(Descriptors.FieldDescriptor)}. */ public void clearField(final T descriptor) { ensureIsMutable(); fields.remove(descriptor); if (fields.isEmpty()) { hasLazyField = false; } } /** * Useful for implementing {@link Message#getRepeatedFieldCount(Descriptors.FieldDescriptor)}. */ public int getRepeatedFieldCount(final T descriptor) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "getRepeatedFieldCount() can only be called on repeated fields."); } final Object value = getFieldAllowBuilders(descriptor); if (value == null) { return 0; } else { return ((List<?>) value).size(); } } /** * Useful for implementing {@link Message#getRepeatedField(Descriptors.FieldDescriptor, int)}. */ public Object getRepeatedField(final T descriptor, final int index) { if (hasNestedBuilders) { ensureIsMutable(); } Object value = getRepeatedFieldAllowBuilders(descriptor, index); return replaceBuilder(value, true); } /** * Same as {@link #getRepeatedField(F, int)}, but allow a {@link MessageLite.Builder} to be * returned. */ Object getRepeatedFieldAllowBuilders(final T descriptor, final int index) { if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "getRepeatedField() can only be called on repeated fields."); } final Object value = getFieldAllowBuilders(descriptor); if (value == null) { throw new IndexOutOfBoundsException(); } else { return ((List<?>) value).get(index); } } /** * Useful for implementing {@link Message.Builder#setRepeatedField(Descriptors.FieldDescriptor, * int, Object)}. */ @SuppressWarnings("unchecked") public void setRepeatedField(final T descriptor, final int index, final Object value) { ensureIsMutable(); if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "getRepeatedField() can only be called on repeated fields."); } hasNestedBuilders = hasNestedBuilders || value instanceof MessageLite.Builder; final Object list = getFieldAllowBuilders(descriptor); if (list == null) { throw new IndexOutOfBoundsException(); } verifyType(descriptor, value); ((List<Object>) list).set(index, value); } /** * Useful for implementing {@link Message.Builder#addRepeatedField(Descriptors.FieldDescriptor, * Object)}. */ @SuppressWarnings("unchecked") public void addRepeatedField(final T descriptor, final Object value) { ensureIsMutable(); if (!descriptor.isRepeated()) { throw new IllegalArgumentException( "addRepeatedField() can only be called on repeated fields."); } hasNestedBuilders = hasNestedBuilders || value instanceof MessageLite.Builder; verifyType(descriptor, value); final Object existingValue = getFieldAllowBuilders(descriptor); List<Object> list; if (existingValue == null) { list = new ArrayList<>(); fields.put(descriptor, list); } else { list = (List<Object>) existingValue; } list.add(value); } /** * Verifies that the given object is of the correct type to be a valid value for the given * field. (For repeated fields, this checks if the object is the right type to be one element of * the field.) * * @throws IllegalArgumentException The value is not of the right type. */ private void verifyType(final T descriptor, final Object value) { if (!FieldSet.isValidType(descriptor.getLiteType(), value)) { // Builder can accept Message.Builder values even though FieldSet will reject. if (descriptor.getLiteType().getJavaType() == WireFormat.JavaType.MESSAGE && value instanceof MessageLite.Builder) { return; } throw new IllegalArgumentException( String.format( "Wrong object type used with protocol message reflection.\n" + "Field number: %d, field java type: %s, value type: %s\n", descriptor.getNumber(), descriptor.getLiteType().getJavaType(), value.getClass().getName())); } } /** * See {@link Message#isInitialized()}. Note: Since {@code FieldSet} itself does not have any * way of knowing about required fields that aren't actually present in the set, it is up to the * caller to check that all required fields are present. */ public boolean isInitialized() { for (int i = 0; i < fields.getNumArrayEntries(); i++) { if (!FieldSet.isInitialized(fields.getArrayEntryAt(i))) { return false; } } for (final Map.Entry<T, Object> entry : fields.getOverflowEntries()) { if (!FieldSet.isInitialized(entry)) { return false; } } return true; } /** * Like {@link Message.Builder#mergeFrom(Message)}, but merges from another {@link FieldSet}. */ public void mergeFrom(final FieldSet<T> other) { ensureIsMutable(); for (int i = 0; i < other.fields.getNumArrayEntries(); i++) { mergeFromField(other.fields.getArrayEntryAt(i)); } for (final Map.Entry<T, Object> entry : other.fields.getOverflowEntries()) { mergeFromField(entry); } } @SuppressWarnings("unchecked") private void mergeFromField(final Map.Entry<T, Object> entry) { final T descriptor = entry.getKey(); Object otherValue = entry.getValue(); boolean isLazyField = otherValue instanceof LazyField; if (descriptor.isRepeated()) { if (isLazyField) { throw new IllegalStateException("Lazy fields can not be repeated"); } List<Object> value = (List<Object>) getFieldAllowBuilders(descriptor); if (value == null) { value = new ArrayList<>(); fields.put(descriptor, value); } for (Object element : (List<?>) otherValue) { value.add(FieldSet.cloneIfMutable(element)); } } else if (descriptor.getLiteJavaType() == WireFormat.JavaType.MESSAGE) { Object value = getFieldAllowBuilders(descriptor); if (value == null) { // New field. fields.put(descriptor, FieldSet.cloneIfMutable(otherValue)); if (isLazyField) { hasLazyField = true; } } else { // There is an existing field. Need to merge the messages. if (otherValue instanceof LazyField) { // Extract the actual value for lazy fields. otherValue = ((LazyField) otherValue).getValue(); } if (value instanceof MessageLite.Builder) { descriptor.internalMergeFrom((MessageLite.Builder) value, (MessageLite) otherValue); } else { value = descriptor .internalMergeFrom(((MessageLite) value).toBuilder(), (MessageLite) otherValue) .build(); fields.put(descriptor, value); } } } else { if (isLazyField) { throw new IllegalStateException("Lazy fields must be message-valued"); } fields.put(descriptor, cloneIfMutable(otherValue)); } } } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/FieldSet.java
245
/* * 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.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.annotations.GwtIncompatible; import com.google.common.base.Ascii; import com.google.common.base.Equivalence; import com.google.common.base.MoreObjects; import com.google.common.base.Supplier; import com.google.common.base.Suppliers; 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.LocalCache.Strength; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.j2objc.annotations.J2ObjCIncompatible; import java.lang.ref.SoftReference; import java.lang.ref.WeakReference; import java.util.ConcurrentModificationException; import java.util.IdentityHashMap; import java.util.Map; import java.util.concurrent.TimeUnit; import java.util.logging.Level; import java.util.logging.Logger; import javax.annotation.CheckForNull; /** * A builder of {@link LoadingCache} and {@link Cache} instances. * * <h2>Prefer <a href="https://github.com/ben-manes/caffeine/wiki">Caffeine</a> over Guava's caching * API</h2> * * <p>The successor to Guava's caching API is <a * href="https://github.com/ben-manes/caffeine/wiki">Caffeine</a>. Its API is designed to make it a * nearly drop-in replacement. It requires Java 8+, and is not available for Android or GWT/J2CL, * and may have <a href="https://github.com/ben-manes/caffeine/wiki/Guava">different (usually * better) behavior</a> when multiple threads attempt concurrent mutations. Its equivalent to {@code * CacheBuilder} is its <a * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/Caffeine.html">{@code * Caffeine}</a> class. Caffeine offers better performance, more features (including asynchronous * loading), and fewer <a * href="https://github.com/google/guava/issues?q=is%3Aopen+is%3Aissue+label%3Apackage%3Dcache+label%3Atype%3Ddefect">bugs</a>. * * <p>Caffeine defines its own interfaces (<a * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/Cache.html">{@code * Cache}</a>, <a * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/LoadingCache.html">{@code * LoadingCache}</a>, <a * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/CacheLoader.html">{@code * CacheLoader}</a>, etc.), so you can use Caffeine without needing to use any Guava types. * Caffeine's types are better than Guava's, especially for <a * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncLoadingCache.html">their * deep support for asynchronous operations</a>. But if you want to migrate to Caffeine with minimal * code changes, you can use <a * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/guava/latest/com.github.benmanes.caffeine.guava/com/github/benmanes/caffeine/guava/CaffeinatedGuava.html">its * {@code CaffeinatedGuava} adapter class</a>, which lets you build a Guava {@code Cache} or a Guava * {@code LoadingCache} backed by a Guava {@code CacheLoader}. * * <p>Caffeine's API for asynchronous operations uses {@code CompletableFuture}: <a * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncLoadingCache.html#get(K)">{@code * AsyncLoadingCache.get}</a> returns a {@code CompletableFuture}, and implementations of <a * href="https://www.javadoc.io/doc/com.github.ben-manes.caffeine/caffeine/latest/com.github.benmanes.caffeine/com/github/benmanes/caffeine/cache/AsyncCacheLoader.html#asyncLoad(K,java.util.concurrent.Executor)">{@code * AsyncCacheLoader.asyncLoad}</a> must return a {@code CompletableFuture}. Users of Guava's {@link * com.google.common.util.concurrent.ListenableFuture} can adapt between the two {@code Future} * types by using <a href="https://github.com/lukas-krecan/future-converter#java8-guava">{@code * net.javacrumbs.futureconverter.java8guava.FutureConverter}</a>. * * <h2>More on {@code CacheBuilder}</h2> * * {@code CacheBuilder} builds caches with any combination of the following features: * * <ul> * <li>automatic loading of entries into the cache * <li>least-recently-used eviction when a maximum size is exceeded (note that the cache is * divided into segments, each of which does LRU internally) * <li>time-based expiration of entries, measured since last access or last write * <li>keys automatically wrapped in {@code WeakReference} * <li>values automatically wrapped in {@code WeakReference} or {@code SoftReference} * <li>notification of evicted (or otherwise removed) entries * <li>accumulation of cache access statistics * </ul> * * <p>These features are all optional; caches can be created using all or none of them. By default, * cache instances created by {@code CacheBuilder} will not perform any type of eviction. * * <p>Usage example: * * <pre>{@code * LoadingCache<Key, Graph> graphs = CacheBuilder.newBuilder() * .maximumSize(10000) * .expireAfterWrite(Duration.ofMinutes(10)) * .removalListener(MY_LISTENER) * .build( * new CacheLoader<Key, Graph>() { * public Graph load(Key key) throws AnyException { * return createExpensiveGraph(key); * } * }); * }</pre> * * <p>Or equivalently, * * <pre>{@code * // In real life this would come from a command-line flag or config file * String spec = "maximumSize=10000,expireAfterWrite=10m"; * * LoadingCache<Key, Graph> graphs = CacheBuilder.from(spec) * .removalListener(MY_LISTENER) * .build( * new CacheLoader<Key, Graph>() { * public Graph load(Key key) throws AnyException { * return createExpensiveGraph(key); * } * }); * }</pre> * * <p>The returned cache implements all optional operations of the {@link LoadingCache} and {@link * Cache} interfaces. The {@code asMap} view (and its collection views) have <i>weakly consistent * iterators</i>. This means that they are safe for concurrent use, but if other threads modify the * cache after the iterator is created, it is undefined which of these changes, if any, are * reflected in that iterator. These iterators never throw {@link ConcurrentModificationException}. * * <p><b>Note:</b> by default, the returned cache uses equality comparisons (the {@link * Object#equals equals} method) to determine equality for keys or values. However, if {@link * #weakKeys} was specified, the cache uses identity ({@code ==}) comparisons instead for keys. * Likewise, if {@link #weakValues} or {@link #softValues} was specified, the cache uses identity * comparisons for values. * * <p>Entries are automatically evicted from the cache when any of {@link #maximumSize(long) * maximumSize}, {@link #maximumWeight(long) maximumWeight}, {@link #expireAfterWrite * expireAfterWrite}, {@link #expireAfterAccess expireAfterAccess}, {@link #weakKeys weakKeys}, * {@link #weakValues weakValues}, or {@link #softValues softValues} are requested. * * <p>If {@link #maximumSize(long) maximumSize} or {@link #maximumWeight(long) maximumWeight} is * requested entries may be evicted on each cache modification. * * <p>If {@link #expireAfterWrite expireAfterWrite} or {@link #expireAfterAccess expireAfterAccess} * is requested entries may be evicted on each cache modification, on occasional cache accesses, or * on calls to {@link Cache#cleanUp}. Expired entries may be counted by {@link Cache#size}, but will * never be visible to read or write operations. * * <p>If {@link #weakKeys weakKeys}, {@link #weakValues weakValues}, or {@link #softValues * softValues} are requested, it is possible for a key or value present in the cache to be reclaimed * by the garbage collector. Entries with reclaimed keys or values may be removed from the cache on * each cache modification, on occasional cache accesses, or on calls to {@link Cache#cleanUp}; such * entries may be counted in {@link Cache#size}, but will never be visible to read or write * operations. * * <p>Certain cache configurations will result in the accrual of periodic maintenance tasks which * will be performed during write operations, or during occasional read operations in the absence of * writes. The {@link Cache#cleanUp} method of the returned cache will also perform maintenance, but * calling it should not be necessary with a high throughput cache. Only caches built with {@link * #removalListener removalListener}, {@link #expireAfterWrite expireAfterWrite}, {@link * #expireAfterAccess expireAfterAccess}, {@link #weakKeys weakKeys}, {@link #weakValues * weakValues}, or {@link #softValues softValues} perform periodic maintenance. * * <p>The caches produced by {@code CacheBuilder} are serializable, and the deserialized caches * retain all the configuration properties of the original cache. Note that the serialized form does * <i>not</i> include cache contents, but only configuration. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/CachesExplained">caching</a> for a higher-level * explanation. * * @param <K> the most general key type this builder will be able to create caches for. This is * normally {@code Object} unless it is constrained by using a method like {@code * #removalListener}. Cache keys may not be null. * @param <V> the most general value type this builder will be able to create caches for. This is * normally {@code Object} unless it is constrained by using a method like {@code * #removalListener}. Cache values may not be null. * @author Charles Fry * @author Kevin Bourrillion * @since 10.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class CacheBuilder<K, V> { private static final int DEFAULT_INITIAL_CAPACITY = 16; private static final int DEFAULT_CONCURRENCY_LEVEL = 4; @SuppressWarnings("GoodTime") // should be a java.time.Duration private static final int DEFAULT_EXPIRATION_NANOS = 0; @SuppressWarnings("GoodTime") // should be a java.time.Duration private static final int DEFAULT_REFRESH_NANOS = 0; static final Supplier<? extends StatsCounter> NULL_STATS_COUNTER = Suppliers.ofInstance( new StatsCounter() { @Override public void recordHits(int count) {} @Override public void recordMisses(int count) {} @SuppressWarnings("GoodTime") // b/122668874 @Override public void recordLoadSuccess(long loadTime) {} @SuppressWarnings("GoodTime") // b/122668874 @Override public void recordLoadException(long loadTime) {} @Override public void recordEviction() {} @Override public CacheStats snapshot() { return EMPTY_STATS; } }); static final CacheStats EMPTY_STATS = new CacheStats(0, 0, 0, 0, 0, 0); /* * We avoid using a method reference or lambda here for now: * * - method reference: Inside Google, CacheBuilder is used from the implementation of a custom * ClassLoader that is sometimes used as a system classloader. That's a problem because * method-reference linking tries to look up the system classloader, and it fails because there * isn't one yet. * * - lambda: Outside Google, we got a report of a similar problem in * https://github.com/google/guava/issues/6565 */ @SuppressWarnings("AnonymousToLambda") static final Supplier<StatsCounter> CACHE_STATS_COUNTER = new Supplier<StatsCounter>() { @Override public StatsCounter get() { return new SimpleStatsCounter(); } }; enum NullListener implements RemovalListener<Object, Object> { INSTANCE; @Override public void onRemoval(RemovalNotification<Object, Object> notification) {} } enum OneWeigher implements Weigher<Object, Object> { INSTANCE; @Override public int weigh(Object key, Object value) { return 1; } } static final Ticker NULL_TICKER = new Ticker() { @Override public long read() { return 0; } }; // We use a holder class to delay initialization: https://github.com/google/guava/issues/6566 private static final class LoggerHolder { static final Logger logger = Logger.getLogger(CacheBuilder.class.getName()); } static final int UNSET_INT = -1; boolean strictParsing = true; int initialCapacity = UNSET_INT; int concurrencyLevel = UNSET_INT; long maximumSize = UNSET_INT; long maximumWeight = UNSET_INT; @CheckForNull Weigher<? super K, ? super V> weigher; @CheckForNull Strength keyStrength; @CheckForNull Strength valueStrength; @SuppressWarnings("GoodTime") // should be a java.time.Duration long expireAfterWriteNanos = UNSET_INT; @SuppressWarnings("GoodTime") // should be a java.time.Duration long expireAfterAccessNanos = UNSET_INT; @SuppressWarnings("GoodTime") // should be a java.time.Duration long refreshNanos = UNSET_INT; @CheckForNull Equivalence<Object> keyEquivalence; @CheckForNull Equivalence<Object> valueEquivalence; @CheckForNull RemovalListener<? super K, ? super V> removalListener; @CheckForNull Ticker ticker; Supplier<? extends StatsCounter> statsCounterSupplier = NULL_STATS_COUNTER; private CacheBuilder() {} /** * Constructs a new {@code CacheBuilder} instance with default settings, including strong keys, * strong values, and no automatic eviction of any kind. * * <p>Note that while this return type is {@code CacheBuilder<Object, Object>}, type parameters on * the {@link #build} methods allow you to create a cache of any key and value type desired. */ public static CacheBuilder<Object, Object> newBuilder() { return new CacheBuilder<>(); } /** * Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}. * * @since 12.0 */ @GwtIncompatible // To be supported public static CacheBuilder<Object, Object> from(CacheBuilderSpec spec) { return spec.toCacheBuilder().lenientParsing(); } /** * Constructs a new {@code CacheBuilder} instance with the settings specified in {@code spec}. * This is especially useful for command-line configuration of a {@code CacheBuilder}. * * @param spec a String in the format specified by {@link CacheBuilderSpec} * @since 12.0 */ @GwtIncompatible // To be supported public static CacheBuilder<Object, Object> from(String spec) { return from(CacheBuilderSpec.parse(spec)); } /** * Enables lenient parsing. Useful for tests and spec parsing. * * @return this {@code CacheBuilder} instance (for chaining) */ @GwtIncompatible // To be supported @CanIgnoreReturnValue CacheBuilder<K, V> lenientParsing() { strictParsing = false; return this; } /** * Sets a custom {@code Equivalence} strategy for comparing keys. * * <p>By default, the cache uses {@link Equivalence#identity} to determine key equality when * {@link #weakKeys} is specified, and {@link Equivalence#equals()} otherwise. * * @return this {@code CacheBuilder} instance (for chaining) */ @GwtIncompatible // To be supported @CanIgnoreReturnValue CacheBuilder<K, V> keyEquivalence(Equivalence<Object> equivalence) { checkState(keyEquivalence == null, "key equivalence was already set to %s", keyEquivalence); keyEquivalence = checkNotNull(equivalence); return this; } Equivalence<Object> getKeyEquivalence() { return MoreObjects.firstNonNull(keyEquivalence, getKeyStrength().defaultEquivalence()); } /** * Sets a custom {@code Equivalence} strategy for comparing values. * * <p>By default, the cache uses {@link Equivalence#identity} to determine value equality when * {@link #weakValues} or {@link #softValues} is specified, and {@link Equivalence#equals()} * otherwise. * * @return this {@code CacheBuilder} instance (for chaining) */ @GwtIncompatible // To be supported @CanIgnoreReturnValue CacheBuilder<K, V> valueEquivalence(Equivalence<Object> equivalence) { checkState( valueEquivalence == null, "value equivalence was already set to %s", valueEquivalence); this.valueEquivalence = checkNotNull(equivalence); return this; } Equivalence<Object> getValueEquivalence() { return MoreObjects.firstNonNull(valueEquivalence, getValueStrength().defaultEquivalence()); } /** * Sets the minimum total size for the internal hash tables. For example, if the initial capacity * is {@code 60}, and the concurrency level is {@code 8}, then eight segments are created, each * having a hash table of size eight. Providing a large enough estimate at construction time * avoids the need for expensive resizing operations later, but setting this value unnecessarily * high wastes memory. * * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalArgumentException if {@code initialCapacity} is negative * @throws IllegalStateException if an initial capacity was already set */ @CanIgnoreReturnValue public CacheBuilder<K, V> initialCapacity(int initialCapacity) { checkState( this.initialCapacity == UNSET_INT, "initial capacity was already set to %s", this.initialCapacity); checkArgument(initialCapacity >= 0); this.initialCapacity = initialCapacity; return this; } int getInitialCapacity() { return (initialCapacity == UNSET_INT) ? DEFAULT_INITIAL_CAPACITY : initialCapacity; } /** * Guides the allowed concurrency among update operations. Used as a hint for internal sizing. The * table is internally partitioned to try to permit the indicated number of concurrent updates * without contention. Because assignment of entries to these partitions is not necessarily * uniform, the actual concurrency observed may vary. Ideally, you should choose a value to * accommodate as many threads as will ever concurrently modify the table. Using a significantly * higher value than you need can waste space and time, and a significantly lower value can lead * to thread contention. But overestimates and underestimates within an order of magnitude do not * usually have much noticeable impact. A value of one permits only one thread to modify the cache * at a time, but since read operations and cache loading computations can proceed concurrently, * this still yields higher concurrency than full synchronization. * * <p>Defaults to 4. <b>Note:</b>The default may change in the future. If you care about this * value, you should always choose it explicitly. * * <p>The current implementation uses the concurrency level to create a fixed number of hashtable * segments, each governed by its own write lock. The segment lock is taken once for each explicit * write, and twice for each cache loading computation (once prior to loading the new value, and * once after loading completes). Much internal cache management is performed at the segment * granularity. For example, access queues and write queues are kept per segment when they are * required by the selected eviction algorithm. As such, when writing unit tests it is not * uncommon to specify {@code concurrencyLevel(1)} in order to achieve more deterministic eviction * behavior. * * <p>Note that future implementations may abandon segment locking in favor of more advanced * concurrency controls. * * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalArgumentException if {@code concurrencyLevel} is nonpositive * @throws IllegalStateException if a concurrency level was already set */ @CanIgnoreReturnValue public CacheBuilder<K, V> concurrencyLevel(int concurrencyLevel) { checkState( this.concurrencyLevel == UNSET_INT, "concurrency level was already set to %s", this.concurrencyLevel); checkArgument(concurrencyLevel > 0); this.concurrencyLevel = concurrencyLevel; return this; } int getConcurrencyLevel() { return (concurrencyLevel == UNSET_INT) ? DEFAULT_CONCURRENCY_LEVEL : concurrencyLevel; } /** * Specifies the maximum number of entries the cache may contain. * * <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in * the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each * resulting segment inside the cache <i>independently</i> limits its own size to approximately * {@code maximumSize / concurrencyLevel}. * * <p>When eviction is necessary, the cache evicts entries that are less likely to be used again. * For example, the cache may evict an entry because it hasn't been used recently or very often. * * <p>If {@code maximumSize} is zero, elements will be evicted immediately after being loaded into * cache. This can be useful in testing, or to disable caching temporarily. * * <p>This feature cannot be used in conjunction with {@link #maximumWeight}. * * @param maximumSize the maximum size of the cache * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalArgumentException if {@code maximumSize} is negative * @throws IllegalStateException if a maximum size or weight was already set */ @CanIgnoreReturnValue public CacheBuilder<K, V> maximumSize(long maximumSize) { checkState( this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize); checkState( this.maximumWeight == UNSET_INT, "maximum weight was already set to %s", this.maximumWeight); checkState(this.weigher == null, "maximum size can not be combined with weigher"); checkArgument(maximumSize >= 0, "maximum size must not be negative"); this.maximumSize = maximumSize; return this; } /** * Specifies the maximum weight of entries the cache may contain. Weight is determined using the * {@link Weigher} specified with {@link #weigher}, and use of this method requires a * corresponding call to {@link #weigher} prior to calling {@link #build}. * * <p>Note that the cache <b>may evict an entry before this limit is exceeded</b>. For example, in * the current implementation, when {@code concurrencyLevel} is greater than {@code 1}, each * resulting segment inside the cache <i>independently</i> limits its own weight to approximately * {@code maximumWeight / concurrencyLevel}. * * <p>When eviction is necessary, the cache evicts entries that are less likely to be used again. * For example, the cache may evict an entry because it hasn't been used recently or very often. * * <p>If {@code maximumWeight} is zero, elements will be evicted immediately after being loaded * into cache. This can be useful in testing, or to disable caching temporarily. * * <p>Note that weight is only used to determine whether the cache is over capacity; it has no * effect on selecting which entry should be evicted next. * * <p>This feature cannot be used in conjunction with {@link #maximumSize}. * * @param maximumWeight the maximum total weight of entries the cache may contain * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalArgumentException if {@code maximumWeight} is negative * @throws IllegalStateException if a maximum weight or size was already set * @since 11.0 */ @GwtIncompatible // To be supported @CanIgnoreReturnValue public CacheBuilder<K, V> maximumWeight(long maximumWeight) { checkState( this.maximumWeight == UNSET_INT, "maximum weight was already set to %s", this.maximumWeight); checkState( this.maximumSize == UNSET_INT, "maximum size was already set to %s", this.maximumSize); checkArgument(maximumWeight >= 0, "maximum weight must not be negative"); this.maximumWeight = maximumWeight; return this; } /** * Specifies the weigher to use in determining the weight of entries. Entry weight is taken into * consideration by {@link #maximumWeight(long)} when determining which entries to evict, and use * of this method requires a corresponding call to {@link #maximumWeight(long)} prior to calling * {@link #build}. Weights are measured and recorded when entries are inserted into the cache, and * are thus effectively static during the lifetime of a cache entry. * * <p>When the weight of an entry is zero it will not be considered for size-based eviction * (though it still may be evicted by other means). * * <p><b>Important note:</b> Instead of returning <em>this</em> as a {@code CacheBuilder} * instance, this method returns {@code CacheBuilder<K1, V1>}. From this point on, either the * original reference or the returned reference may be used to complete configuration and build * the cache, but only the "generic" one is type-safe. That is, it will properly prevent you from * building caches whose key or value types are incompatible with the types accepted by the * weigher already provided; the {@code CacheBuilder} type cannot do this. For best results, * simply use the standard method-chaining idiom, as illustrated in the documentation at top, * configuring a {@code CacheBuilder} and building your {@link Cache} all in a single statement. * * <p><b>Warning:</b> if you ignore the above advice, and use this {@code CacheBuilder} to build a * cache whose key or value type is incompatible with the weigher, you will likely experience a * {@link ClassCastException} at some <i>undefined</i> point in the future. * * @param weigher the weigher to use in calculating the weight of cache entries * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalStateException if a weigher was already set or {@link #maximumSize} was * previously called * @since 11.0 */ @GwtIncompatible // To be supported @CanIgnoreReturnValue // TODO(b/27479612): consider removing this public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> weigher( Weigher<? super K1, ? super V1> weigher) { checkState(this.weigher == null); if (strictParsing) { checkState( this.maximumSize == UNSET_INT, "weigher can not be combined with maximum size (%s provided)", this.maximumSize); } // safely limiting the kinds of caches this can produce @SuppressWarnings("unchecked") CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this; me.weigher = checkNotNull(weigher); return me; } long getMaximumWeight() { if (expireAfterWriteNanos == 0 || expireAfterAccessNanos == 0) { return 0; } return (weigher == null) ? maximumSize : maximumWeight; } // Make a safe contravariant cast now so we don't have to do it over and over. @SuppressWarnings("unchecked") <K1 extends K, V1 extends V> Weigher<K1, V1> getWeigher() { return (Weigher<K1, V1>) MoreObjects.firstNonNull(weigher, OneWeigher.INSTANCE); } /** * Specifies that each key (not value) stored in the cache should be wrapped in a {@link * WeakReference} (by default, strong references are used). * * <p><b>Warning:</b> when this method is used, the resulting cache will use identity ({@code ==}) * comparison to determine equality of keys. Its {@link Cache#asMap} view will therefore * technically violate the {@link Map} specification (in the same way that {@link IdentityHashMap} * does). * * <p>Entries with keys that have been garbage collected may be counted in {@link Cache#size}, but * will never be visible to read or write operations; such entries are cleaned up as part of the * routine maintenance described in the class javadoc. * * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalStateException if the key strength was already set */ @GwtIncompatible // java.lang.ref.WeakReference @CanIgnoreReturnValue public CacheBuilder<K, V> weakKeys() { return setKeyStrength(Strength.WEAK); } @CanIgnoreReturnValue CacheBuilder<K, V> setKeyStrength(Strength strength) { checkState(keyStrength == null, "Key strength was already set to %s", keyStrength); keyStrength = checkNotNull(strength); return this; } Strength getKeyStrength() { return MoreObjects.firstNonNull(keyStrength, Strength.STRONG); } /** * Specifies that each value (not key) stored in the cache should be wrapped in a {@link * WeakReference} (by default, strong references are used). * * <p>Weak values will be garbage collected once they are weakly reachable. This makes them a poor * candidate for caching; consider {@link #softValues} instead. * * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==}) * comparison to determine equality of values. * * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size}, * but will never be visible to read or write operations; such entries are cleaned up as part of * the routine maintenance described in the class javadoc. * * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalStateException if the value strength was already set */ @GwtIncompatible // java.lang.ref.WeakReference @CanIgnoreReturnValue public CacheBuilder<K, V> weakValues() { return setValueStrength(Strength.WEAK); } /** * Specifies that each value (not key) stored in the cache should be wrapped in a {@link * SoftReference} (by default, strong references are used). Softly-referenced objects will be * garbage-collected in a <i>globally</i> least-recently-used manner, in response to memory * demand. * * <p><b>Warning:</b> in most circumstances it is better to set a per-cache {@linkplain * #maximumSize(long) maximum size} instead of using soft references. You should only use this * method if you are well familiar with the practical consequences of soft references. * * <p><b>Note:</b> when this method is used, the resulting cache will use identity ({@code ==}) * comparison to determine equality of values. * * <p>Entries with values that have been garbage collected may be counted in {@link Cache#size}, * but will never be visible to read or write operations; such entries are cleaned up as part of * the routine maintenance described in the class javadoc. * * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalStateException if the value strength was already set */ @GwtIncompatible // java.lang.ref.SoftReference @CanIgnoreReturnValue public CacheBuilder<K, V> softValues() { return setValueStrength(Strength.SOFT); } @CanIgnoreReturnValue CacheBuilder<K, V> setValueStrength(Strength strength) { checkState(valueStrength == null, "Value strength was already set to %s", valueStrength); valueStrength = checkNotNull(strength); return this; } Strength getValueStrength() { return MoreObjects.firstNonNull(valueStrength, Strength.STRONG); } /** * Specifies that each entry should be automatically removed from the cache once a fixed duration * has elapsed after the entry's creation, or the most recent replacement of its value. * * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long) * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be * useful in testing, or to disable caching temporarily without a code change. * * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or * write operations. Expired entries are cleaned up as part of the routine maintenance described * in the class javadoc. * * @param duration the length of time after an entry is created that it should be automatically * removed * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalArgumentException if {@code duration} is negative * @throws IllegalStateException if {@link #expireAfterWrite} was already set * @throws ArithmeticException for durations greater than +/- approximately 292 years * @since 25.0 */ @J2ObjCIncompatible @GwtIncompatible // java.time.Duration @SuppressWarnings("GoodTime") // java.time.Duration decomposition @CanIgnoreReturnValue public CacheBuilder<K, V> expireAfterWrite(java.time.Duration duration) { return expireAfterWrite(toNanosSaturated(duration), TimeUnit.NANOSECONDS); } /** * Specifies that each entry should be automatically removed from the cache once a fixed duration * has elapsed after the entry's creation, or the most recent replacement of its value. * * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long) * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be * useful in testing, or to disable caching temporarily without a code change. * * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or * write operations. Expired entries are cleaned up as part of the routine maintenance described * in the class javadoc. * * <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred * when feasible), use {@link #expireAfterWrite(Duration)} instead. * * @param duration the length of time after an entry is created that it should be automatically * removed * @param unit the unit that {@code duration} is expressed in * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalArgumentException if {@code duration} is negative * @throws IllegalStateException if {@link #expireAfterWrite} was already set */ @SuppressWarnings("GoodTime") // should accept a java.time.Duration @CanIgnoreReturnValue public CacheBuilder<K, V> expireAfterWrite(long duration, TimeUnit unit) { checkState( expireAfterWriteNanos == UNSET_INT, "expireAfterWrite was already set to %s ns", expireAfterWriteNanos); checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit); this.expireAfterWriteNanos = unit.toNanos(duration); return this; } @SuppressWarnings("GoodTime") // nanos internally, should be Duration long getExpireAfterWriteNanos() { return (expireAfterWriteNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterWriteNanos; } /** * Specifies that each entry should be automatically removed from the cache once a fixed duration * has elapsed after the entry's creation, the most recent replacement of its value, or its last * access. Access time is reset by all cache read and write operations (including {@code * Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by {@code * containsKey(Object)}, nor by operations on the collection-views of {@link Cache#asMap}}. So, * for example, iterating through {@code Cache.asMap().entrySet()} does not reset access time for * the entries you retrieve. * * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long) * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be * useful in testing, or to disable caching temporarily without a code change. * * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or * write operations. Expired entries are cleaned up as part of the routine maintenance described * in the class javadoc. * * @param duration the length of time after an entry is last accessed that it should be * automatically removed * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalArgumentException if {@code duration} is negative * @throws IllegalStateException if {@link #expireAfterAccess} was already set * @throws ArithmeticException for durations greater than +/- approximately 292 years * @since 25.0 */ @J2ObjCIncompatible @GwtIncompatible // java.time.Duration @SuppressWarnings("GoodTime") // java.time.Duration decomposition @CanIgnoreReturnValue public CacheBuilder<K, V> expireAfterAccess(java.time.Duration duration) { return expireAfterAccess(toNanosSaturated(duration), TimeUnit.NANOSECONDS); } /** * Specifies that each entry should be automatically removed from the cache once a fixed duration * has elapsed after the entry's creation, the most recent replacement of its value, or its last * access. Access time is reset by all cache read and write operations (including {@code * Cache.asMap().get(Object)} and {@code Cache.asMap().put(K, V)}), but not by {@code * containsKey(Object)}, nor by operations on the collection-views of {@link Cache#asMap}. So, for * example, iterating through {@code Cache.asMap().entrySet()} does not reset access time for the * entries you retrieve. * * <p>When {@code duration} is zero, this method hands off to {@link #maximumSize(long) * maximumSize}{@code (0)}, ignoring any otherwise-specified maximum size or weight. This can be * useful in testing, or to disable caching temporarily without a code change. * * <p>Expired entries may be counted in {@link Cache#size}, but will never be visible to read or * write operations. Expired entries are cleaned up as part of the routine maintenance described * in the class javadoc. * * <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred * when feasible), use {@link #expireAfterAccess(Duration)} instead. * * @param duration the length of time after an entry is last accessed that it should be * automatically removed * @param unit the unit that {@code duration} is expressed in * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalArgumentException if {@code duration} is negative * @throws IllegalStateException if {@link #expireAfterAccess} was already set */ @SuppressWarnings("GoodTime") // should accept a java.time.Duration @CanIgnoreReturnValue public CacheBuilder<K, V> expireAfterAccess(long duration, TimeUnit unit) { checkState( expireAfterAccessNanos == UNSET_INT, "expireAfterAccess was already set to %s ns", expireAfterAccessNanos); checkArgument(duration >= 0, "duration cannot be negative: %s %s", duration, unit); this.expireAfterAccessNanos = unit.toNanos(duration); return this; } @SuppressWarnings("GoodTime") // nanos internally, should be Duration long getExpireAfterAccessNanos() { return (expireAfterAccessNanos == UNSET_INT) ? DEFAULT_EXPIRATION_NANOS : expireAfterAccessNanos; } /** * Specifies that active entries are eligible for automatic refresh once a fixed duration has * elapsed after the entry's creation, or the most recent replacement of its value. The semantics * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling {@link * CacheLoader#reload}. * * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is * recommended that users of this method override {@link CacheLoader#reload} with an asynchronous * implementation; otherwise refreshes will be performed during unrelated cache read and write * operations. * * <p>Currently automatic refreshes are performed when the first stale request for an entry * occurs. The request triggering refresh will make a synchronous call to {@link * CacheLoader#reload} * to obtain a future of the new value. If the returned future is already complete, it is returned * immediately. Otherwise, the old value is returned. * * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>. * * @param duration the length of time after an entry is created that it should be considered * stale, and thus eligible for refresh * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalArgumentException if {@code duration} is negative * @throws IllegalStateException if {@link #refreshAfterWrite} was already set * @throws ArithmeticException for durations greater than +/- approximately 292 years * @since 25.0 */ @J2ObjCIncompatible @GwtIncompatible // java.time.Duration @SuppressWarnings("GoodTime") // java.time.Duration decomposition @CanIgnoreReturnValue public CacheBuilder<K, V> refreshAfterWrite(java.time.Duration duration) { return refreshAfterWrite(toNanosSaturated(duration), TimeUnit.NANOSECONDS); } /** * Specifies that active entries are eligible for automatic refresh once a fixed duration has * elapsed after the entry's creation, or the most recent replacement of its value. The semantics * of refreshes are specified in {@link LoadingCache#refresh}, and are performed by calling {@link * CacheLoader#reload}. * * <p>As the default implementation of {@link CacheLoader#reload} is synchronous, it is * recommended that users of this method override {@link CacheLoader#reload} with an asynchronous * implementation; otherwise refreshes will be performed during unrelated cache read and write * operations. * * <p>Currently automatic refreshes are performed when the first stale request for an entry * occurs. The request triggering refresh will make a synchronous call to {@link * CacheLoader#reload} * and immediately return the new value if the returned future is complete, and the old value * otherwise. * * <p><b>Note:</b> <i>all exceptions thrown during refresh will be logged and then swallowed</i>. * * <p>If you can represent the duration as a {@link java.time.Duration} (which should be preferred * when feasible), use {@link #refreshAfterWrite(Duration)} instead. * * @param duration the length of time after an entry is created that it should be considered * stale, and thus eligible for refresh * @param unit the unit that {@code duration} is expressed in * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalArgumentException if {@code duration} is negative * @throws IllegalStateException if {@link #refreshAfterWrite} was already set * @since 11.0 */ @GwtIncompatible // To be supported (synchronously). @SuppressWarnings("GoodTime") // should accept a java.time.Duration @CanIgnoreReturnValue public CacheBuilder<K, V> refreshAfterWrite(long duration, TimeUnit unit) { checkNotNull(unit); checkState(refreshNanos == UNSET_INT, "refresh was already set to %s ns", refreshNanos); checkArgument(duration > 0, "duration must be positive: %s %s", duration, unit); this.refreshNanos = unit.toNanos(duration); return this; } @SuppressWarnings("GoodTime") // nanos internally, should be Duration long getRefreshNanos() { return (refreshNanos == UNSET_INT) ? DEFAULT_REFRESH_NANOS : refreshNanos; } /** * Specifies a nanosecond-precision time source for this cache. By default, {@link * System#nanoTime} is used. * * <p>The primary intent of this method is to facilitate testing of caches with a fake or mock * time source. * * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalStateException if a ticker was already set */ @CanIgnoreReturnValue public CacheBuilder<K, V> ticker(Ticker ticker) { checkState(this.ticker == null); this.ticker = checkNotNull(ticker); return this; } Ticker getTicker(boolean recordsTime) { if (ticker != null) { return ticker; } return recordsTime ? Ticker.systemTicker() : NULL_TICKER; } /** * Specifies a listener instance that caches should notify each time an entry is removed for any * {@linkplain RemovalCause reason}. Each cache created by this builder will invoke this listener * as part of the routine maintenance described in the class documentation above. * * <p><b>Warning:</b> after invoking this method, do not continue to use <i>this</i> cache builder * reference; instead use the reference this method <i>returns</i>. At runtime, these point to the * same instance, but only the returned reference has the correct generic type information to * ensure type safety. For best results, use the standard method-chaining idiom illustrated in the * class documentation above, configuring a builder and building your cache in a single statement. * Failure to heed this advice can result in a {@link ClassCastException} being thrown by a cache * operation at some <i>undefined</i> point in the future. * * <p><b>Warning:</b> any exception thrown by {@code listener} will <i>not</i> be propagated to * the {@code Cache} user, only logged via a {@link Logger}. * * @return the cache builder reference that should be used instead of {@code this} for any * remaining configuration and cache building * @return this {@code CacheBuilder} instance (for chaining) * @throws IllegalStateException if a removal listener was already set */ public <K1 extends K, V1 extends V> CacheBuilder<K1, V1> removalListener( RemovalListener<? super K1, ? super V1> listener) { checkState(this.removalListener == null); // safely limiting the kinds of caches this can produce @SuppressWarnings("unchecked") CacheBuilder<K1, V1> me = (CacheBuilder<K1, V1>) this; me.removalListener = checkNotNull(listener); return me; } // Make a safe contravariant cast now so we don't have to do it over and over. @SuppressWarnings("unchecked") <K1 extends K, V1 extends V> RemovalListener<K1, V1> getRemovalListener() { return (RemovalListener<K1, V1>) MoreObjects.firstNonNull(removalListener, NullListener.INSTANCE); } /** * Enable the accumulation of {@link CacheStats} during the operation of the cache. Without this * {@link Cache#stats} will return zero for all statistics. Note that recording stats requires * bookkeeping to be performed with each operation, and thus imposes a performance penalty on * cache operation. * * @return this {@code CacheBuilder} instance (for chaining) * @since 12.0 (previously, stats collection was automatic) */ @CanIgnoreReturnValue public CacheBuilder<K, V> recordStats() { statsCounterSupplier = CACHE_STATS_COUNTER; return this; } boolean isRecordingStats() { return statsCounterSupplier == CACHE_STATS_COUNTER; } Supplier<? extends StatsCounter> getStatsCounterSupplier() { return statsCounterSupplier; } /** * Builds a cache, which either returns an already-loaded value for a given key or atomically * computes or retrieves it using the supplied {@code CacheLoader}. If another thread is currently * loading the value for this key, simply waits for that thread to finish and returns its loaded * value. Note that multiple threads can concurrently load values for distinct keys. * * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be * invoked again to create multiple independent caches. * * @param loader the cache loader used to obtain new values * @return a cache having the requested features */ public <K1 extends K, V1 extends V> LoadingCache<K1, V1> build( CacheLoader<? super K1, V1> loader) { checkWeightWithWeigher(); return new LocalCache.LocalLoadingCache<>(this, loader); } /** * Builds a cache which does not automatically load values when keys are requested. * * <p>Consider {@link #build(CacheLoader)} instead, if it is feasible to implement a {@code * CacheLoader}. * * <p>This method does not alter the state of this {@code CacheBuilder} instance, so it can be * invoked again to create multiple independent caches. * * @return a cache having the requested features * @since 11.0 */ public <K1 extends K, V1 extends V> Cache<K1, V1> build() { checkWeightWithWeigher(); checkNonLoadingCache(); return new LocalCache.LocalManualCache<>(this); } private void checkNonLoadingCache() { checkState(refreshNanos == UNSET_INT, "refreshAfterWrite requires a LoadingCache"); } private void checkWeightWithWeigher() { if (weigher == null) { checkState(maximumWeight == UNSET_INT, "maximumWeight requires weigher"); } else { if (strictParsing) { checkState(maximumWeight != UNSET_INT, "weigher requires maximumWeight"); } else { if (maximumWeight == UNSET_INT) { LoggerHolder.logger.log( Level.WARNING, "ignoring weigher specified without maximumWeight"); } } } } /** * Returns a string representation for this CacheBuilder instance. The exact form of the returned * string is not specified. */ @Override public String toString() { MoreObjects.ToStringHelper s = MoreObjects.toStringHelper(this); if (initialCapacity != UNSET_INT) { s.add("initialCapacity", initialCapacity); } if (concurrencyLevel != UNSET_INT) { s.add("concurrencyLevel", concurrencyLevel); } if (maximumSize != UNSET_INT) { s.add("maximumSize", maximumSize); } if (maximumWeight != UNSET_INT) { s.add("maximumWeight", maximumWeight); } if (expireAfterWriteNanos != UNSET_INT) { s.add("expireAfterWrite", expireAfterWriteNanos + "ns"); } if (expireAfterAccessNanos != UNSET_INT) { s.add("expireAfterAccess", expireAfterAccessNanos + "ns"); } if (keyStrength != null) { s.add("keyStrength", Ascii.toLowerCase(keyStrength.toString())); } if (valueStrength != null) { s.add("valueStrength", Ascii.toLowerCase(valueStrength.toString())); } if (keyEquivalence != null) { s.addValue("keyEquivalence"); } if (valueEquivalence != null) { s.addValue("valueEquivalence"); } if (removalListener != null) { s.addValue("removalListener"); } return s.toString(); } /** * Returns the number of nanoseconds of the given duration without throwing or overflowing. * * <p>Instead of throwing {@link ArithmeticException}, this method silently saturates to either * {@link Long#MAX_VALUE} or {@link Long#MIN_VALUE}. This behavior can be useful when decomposing * a duration in order to call a legacy API which requires a {@code long, TimeUnit} pair. */ @GwtIncompatible // java.time.Duration @SuppressWarnings("GoodTime") // duration decomposition private static long toNanosSaturated(java.time.Duration duration) { // Using a try/catch seems lazy, but the catch block will rarely get invoked (except for // durations longer than approximately +/- 292 years). try { return duration.toNanos(); } catch (ArithmeticException tooBig) { return duration.isNegative() ? Long.MIN_VALUE : Long.MAX_VALUE; } } }
google/guava
guava/src/com/google/common/cache/CacheBuilder.java
246
/* * 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.Beta; 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.TreeMap; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.function.BinaryOperator; 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 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, 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 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, 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) { if (Collections2.safeContains(backingSet(), key)) { @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it K k = (K) key; return function.apply(k); } else { return null; } } @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(); } } 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) { if (Collections2.safeContains(set, key)) { @SuppressWarnings("unchecked") // unsafe, but Javadoc warns about it K k = (K) key; return function.apply(k); } else { return null; } } @Override public void clear() { set.clear(); } @Override Iterator<Entry<K, V>> entryIterator() { return asMapEntryIterator(set, function); } @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 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 */ 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); } // safe as long as the user followed the <b>Warning</b> in the javadoc @SuppressWarnings("unchecked") @Override @CheckForNull public V2 get(@CheckForNull Object key) { 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 null; } // 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 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 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(); } @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(); @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 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 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 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
android/guava/src/com/google/common/collect/Maps.java
247
/* * 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.common.base.Ascii; import com.google.common.base.Optional; import com.google.common.base.Splitter; import com.google.common.collect.AbstractIterator; import com.google.common.collect.ImmutableList; import com.google.common.collect.Lists; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.io.StringReader; import java.io.Writer; import java.nio.charset.Charset; import java.util.Iterator; import java.util.List; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * A readable source of characters, such as a text file. Unlike a {@link Reader}, a {@code * CharSource} is not an open, stateful stream of characters that can be read and closed. Instead, * it is an immutable <i>supplier</i> of {@code Reader} instances. * * <p>{@code CharSource} provides two kinds of methods: * * <ul> * <li><b>Methods that return a reader:</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 reader is closed. * <li><b>Convenience methods:</b> These are implementations of common operations that are * typically implemented by opening a reader using one of the methods in the first category, * doing something and finally closing the reader that was opened. * </ul> * * <p>Several methods in this class, such as {@link #readLines()}, break the contents of the source * into lines. Like {@link BufferedReader}, these methods break lines on any of {@code \n}, {@code * \r} or {@code \r\n}, do not include the line separator in each line and do not consider there to * be an empty line at the end if the contents are terminated with a line separator. * * <p>Any {@link ByteSource} containing text encoded with a specific {@linkplain Charset character * encoding} may be viewed as a {@code CharSource} using {@link ByteSource#asCharSource(Charset)}. * * <p><b>Note:</b> In general, {@code CharSource} is intended to be used for "file-like" sources * that provide readers that are: * * <ul> * <li><b>Finite:</b> Many operations, such as {@link #length()} and {@link #read()}, will either * block indefinitely or fail if the source creates an infinite reader. * <li><b>Non-destructive:</b> A <i>destructive</i> reader will consume or otherwise alter the * source as they are read from it. A source that provides such readers will not be reusable, * and operations that read from the stream (including {@link #length()}, in some * implementations) will prevent further operations from completing as expected. * </ul> * * @since 14.0 * @author Colin Decker */ @J2ktIncompatible @GwtIncompatible @ElementTypesAreNonnullByDefault public abstract class CharSource { /** Constructor for use by subclasses. */ protected CharSource() {} /** * Returns a {@link ByteSource} view of this char source that encodes chars read from this source * as bytes using the given {@link Charset}. * * <p>If {@link ByteSource#asCharSource} is called on the returned source with the same charset, * the default implementation of this method will ensure that the original {@code CharSource} is * returned, rather than round-trip encoding. Subclasses that override this method should behave * the same way. * * @since 20.0 */ public ByteSource asByteSource(Charset charset) { return new AsByteSource(charset); } /** * Opens a new {@link Reader} for reading from this source. This method returns a new, independent * reader each time it is called. * * <p>The caller is responsible for ensuring that the returned reader is closed. * * @throws IOException if an I/O error occurs while opening the reader */ public abstract Reader openStream() throws IOException; /** * Opens a new {@link BufferedReader} for reading from this source. This method returns a new, * independent reader each time it is called. * * <p>The caller is responsible for ensuring that the returned reader is closed. * * @throws IOException if an I/O error occurs while of opening the reader */ public BufferedReader openBufferedStream() throws IOException { Reader reader = openStream(); return (reader instanceof BufferedReader) ? (BufferedReader) reader : new BufferedReader(reader); } /** * Returns the size of this source in chars, if the size can be easily determined without actually * opening the data stream. * * <p>The default implementation returns {@link Optional#absent}. Some sources, such as a {@code * CharSequence}, may return a non-absent value. Note that in such cases, it is <i>possible</i> * that this method will return a different number of chars than would be returned by reading all * of the chars. * * <p>Additionally, for mutable sources such as {@code StringBuilder}s, a subsequent read may * return a different number of chars if the contents are changed. * * @since 19.0 */ public Optional<Long> lengthIfKnown() { return Optional.absent(); } /** * Returns the length of this source in chars, even if doing so requires opening and traversing an * entire stream. To avoid a potentially expensive operation, see {@link #lengthIfKnown}. * * <p>The default implementation calls {@link #lengthIfKnown} and returns the value if present. If * absent, it will fall back to a heavyweight operation that will open a stream, {@link * Reader#skip(long) skip} to the end of the stream, and return the total number of chars that * were skipped. * * <p>Note that for sources that implement {@link #lengthIfKnown} to provide a more efficient * implementation, it is <i>possible</i> that this method will return a different number of chars * than would be returned by reading all of the chars. * * <p>In either case, for mutable sources such as files, a subsequent read may return a different * number of chars if the contents are changed. * * @throws IOException if an I/O error occurs while reading the length of this source * @since 19.0 */ public long length() throws IOException { Optional<Long> lengthIfKnown = lengthIfKnown(); if (lengthIfKnown.isPresent()) { return lengthIfKnown.get(); } Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return countBySkipping(reader); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } private long countBySkipping(Reader reader) throws IOException { long count = 0; long read; while ((read = reader.skip(Long.MAX_VALUE)) != 0) { count += read; } return count; } /** * Appends the contents of this source to the given {@link Appendable} (such as a {@link Writer}). * Does not close {@code appendable} if it is {@code Closeable}. * * @return the number of characters copied * @throws IOException if an I/O error occurs while reading from this source or writing to {@code * appendable} */ @CanIgnoreReturnValue public long copyTo(Appendable appendable) throws IOException { checkNotNull(appendable); Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return CharStreams.copy(reader, appendable); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Copies the contents of this source to the given sink. * * @return the number of characters copied * @throws IOException if an I/O error occurs while reading from this source or writing to {@code * sink} */ @CanIgnoreReturnValue public long copyTo(CharSink sink) throws IOException { checkNotNull(sink); Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); Writer writer = closer.register(sink.openStream()); return CharStreams.copy(reader, writer); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads the contents of this source as a string. * * @throws IOException if an I/O error occurs while reading from this source */ public String read() throws IOException { Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return CharStreams.toString(reader); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads the first line of this source as a string. Returns {@code null} if this source is empty. * * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code * \n}. If the source's content does not end in a line termination sequence, it is treated as if * it does. * * @throws IOException if an I/O error occurs while reading from this source */ @CheckForNull public String readFirstLine() throws IOException { Closer closer = Closer.create(); try { BufferedReader reader = closer.register(openBufferedStream()); return reader.readLine(); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads all the lines of this source as a list of strings. The returned list will be empty if * this source is empty. * * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code * \n}. If the source's content does not end in a line termination sequence, it is treated as if * it does. * * @throws IOException if an I/O error occurs while reading from this source */ public ImmutableList<String> readLines() throws IOException { Closer closer = Closer.create(); try { BufferedReader reader = closer.register(openBufferedStream()); List<String> result = Lists.newArrayList(); String line; while ((line = reader.readLine()) != null) { result.add(line); } return ImmutableList.copyOf(result); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Reads lines of text from this source, processing each line as it is read using the given {@link * LineProcessor processor}. Stops when all lines have been processed or the processor returns * {@code false} and returns the result produced by the processor. * * <p>Like {@link BufferedReader#readLine()}, this method considers a line to be a sequence of * text that is terminated by (but does not include) one of {@code \r\n}, {@code \r} or {@code * \n}. If the source's content does not end in a line termination sequence, it is treated as if * it does. * * @throws IOException if an I/O error occurs while reading from this source or if {@code * processor} throws an {@code IOException} * @since 16.0 */ @CanIgnoreReturnValue // some processors won't return a useful result @ParametricNullness public <T extends @Nullable Object> T readLines(LineProcessor<T> processor) throws IOException { checkNotNull(processor); Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return CharStreams.readLines(reader, processor); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Returns whether the source has zero chars. The default implementation first checks {@link * #lengthIfKnown}, returning true if it's known to be zero and false if it's known to be * non-zero. If the length is not known, it falls back to opening a stream and checking for EOF. * * <p>Note that, in cases where {@code lengthIfKnown} returns zero, it is <i>possible</i> that * chars are actually available for reading. This means that a source may return {@code true} from * {@code isEmpty()} despite having readable content. * * @throws IOException if an I/O error occurs * @since 15.0 */ public boolean isEmpty() throws IOException { Optional<Long> lengthIfKnown = lengthIfKnown(); if (lengthIfKnown.isPresent()) { return lengthIfKnown.get() == 0L; } Closer closer = Closer.create(); try { Reader reader = closer.register(openStream()); return reader.read() == -1; } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } /** * Concatenates multiple {@link CharSource} instances into a single source. Streams returned from * the source will contain the concatenated data from the streams of the underlying sources. * * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will * close the open underlying stream. * * @param sources the sources to concatenate * @return a {@code CharSource} containing the concatenated data * @since 15.0 */ public static CharSource concat(Iterable<? extends CharSource> sources) { return new ConcatenatedCharSource(sources); } /** * Concatenates multiple {@link CharSource} instances into a single source. Streams returned from * the source will contain the concatenated data from the streams of the underlying sources. * * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will * close the open underlying stream. * * <p>Note: The input {@code Iterator} will be copied to an {@code ImmutableList} when this method * is called. This will fail if the iterator is infinite and may cause problems if the iterator * eagerly fetches data for each source when iterated (rather than producing sources that only * load data through their streams). Prefer using the {@link #concat(Iterable)} overload if * possible. * * @param sources the sources to concatenate * @return a {@code CharSource} containing the concatenated data * @throws NullPointerException if any of {@code sources} is {@code null} * @since 15.0 */ public static CharSource concat(Iterator<? extends CharSource> sources) { return concat(ImmutableList.copyOf(sources)); } /** * Concatenates multiple {@link CharSource} instances into a single source. Streams returned from * the source will contain the concatenated data from the streams of the underlying sources. * * <p>Only one underlying stream will be open at a time. Closing the concatenated stream will * close the open underlying stream. * * @param sources the sources to concatenate * @return a {@code CharSource} containing the concatenated data * @throws NullPointerException if any of {@code sources} is {@code null} * @since 15.0 */ public static CharSource concat(CharSource... sources) { return concat(ImmutableList.copyOf(sources)); } /** * Returns a view of the given character sequence as a {@link CharSource}. The behavior of the * returned {@code CharSource} and any {@code Reader} instances created by it is unspecified if * the {@code charSequence} is mutated while it is being read, so don't do that. * * @since 15.0 (since 14.0 as {@code CharStreams.asCharSource(String)}) */ public static CharSource wrap(CharSequence charSequence) { return charSequence instanceof String ? new StringCharSource((String) charSequence) : new CharSequenceCharSource(charSequence); } /** * Returns an immutable {@link CharSource} that contains no characters. * * @since 15.0 */ public static CharSource empty() { return EmptyCharSource.INSTANCE; } /** A byte source that reads chars from this source and encodes them as bytes using a charset. */ private final class AsByteSource extends ByteSource { final Charset charset; AsByteSource(Charset charset) { this.charset = checkNotNull(charset); } @Override public CharSource asCharSource(Charset charset) { if (charset.equals(this.charset)) { return CharSource.this; } return super.asCharSource(charset); } @Override public InputStream openStream() throws IOException { return new ReaderInputStream(CharSource.this.openStream(), charset, 8192); } @Override public String toString() { return CharSource.this.toString() + ".asByteSource(" + charset + ")"; } } private static class CharSequenceCharSource extends CharSource { private static final Splitter LINE_SPLITTER = Splitter.onPattern("\r\n|\n|\r"); protected final CharSequence seq; protected CharSequenceCharSource(CharSequence seq) { this.seq = checkNotNull(seq); } @Override public Reader openStream() { return new CharSequenceReader(seq); } @Override public String read() { return seq.toString(); } @Override public boolean isEmpty() { return seq.length() == 0; } @Override public long length() { return seq.length(); } @Override public Optional<Long> lengthIfKnown() { return Optional.of((long) seq.length()); } /** * Returns an iterator over the lines in the string. If the string ends in a newline, a final * empty string is not included, to match the behavior of BufferedReader/LineReader.readLine(). */ private Iterator<String> linesIterator() { return new AbstractIterator<String>() { Iterator<String> lines = LINE_SPLITTER.split(seq).iterator(); @Override @CheckForNull protected String computeNext() { if (lines.hasNext()) { String next = lines.next(); // skip last line if it's empty if (lines.hasNext() || !next.isEmpty()) { return next; } } return endOfData(); } }; } @Override @CheckForNull public String readFirstLine() { Iterator<String> lines = linesIterator(); return lines.hasNext() ? lines.next() : null; } @Override public ImmutableList<String> readLines() { return ImmutableList.copyOf(linesIterator()); } @Override @ParametricNullness public <T extends @Nullable Object> T readLines(LineProcessor<T> processor) throws IOException { Iterator<String> lines = linesIterator(); while (lines.hasNext()) { if (!processor.processLine(lines.next())) { break; } } return processor.getResult(); } @Override public String toString() { return "CharSource.wrap(" + Ascii.truncate(seq, 30, "...") + ")"; } } /** * Subclass specialized for string instances. * * <p>Since Strings are immutable and built into the jdk we can optimize some operations * * <ul> * <li>use {@link StringReader} instead of {@link CharSequenceReader}. It is faster since it can * use {@link String#getChars(int, int, char[], int)} instead of copying characters one by * one with {@link CharSequence#charAt(int)}. * <li>use {@link Appendable#append(CharSequence)} in {@link #copyTo(Appendable)} and {@link * #copyTo(CharSink)}. We know this is correct since strings are immutable and so the length * can't change, and it is faster because many writers and appendables are optimized for * appending string instances. * </ul> */ private static class StringCharSource extends CharSequenceCharSource { protected StringCharSource(String seq) { super(seq); } @Override public Reader openStream() { return new StringReader((String) seq); } @Override public long copyTo(Appendable appendable) throws IOException { appendable.append(seq); return seq.length(); } @Override public long copyTo(CharSink sink) throws IOException { checkNotNull(sink); Closer closer = Closer.create(); try { Writer writer = closer.register(sink.openStream()); writer.write((String) seq); return seq.length(); } catch (Throwable e) { throw closer.rethrow(e); } finally { closer.close(); } } } private static final class EmptyCharSource extends StringCharSource { private static final EmptyCharSource INSTANCE = new EmptyCharSource(); private EmptyCharSource() { super(""); } @Override public String toString() { return "CharSource.empty()"; } } private static final class ConcatenatedCharSource extends CharSource { private final Iterable<? extends CharSource> sources; ConcatenatedCharSource(Iterable<? extends CharSource> sources) { this.sources = checkNotNull(sources); } @Override public Reader openStream() throws IOException { return new MultiReader(sources.iterator()); } @Override public boolean isEmpty() throws IOException { for (CharSource source : sources) { if (!source.isEmpty()) { return false; } } return true; } @Override public Optional<Long> lengthIfKnown() { long result = 0L; for (CharSource source : sources) { Optional<Long> lengthIfKnown = source.lengthIfKnown(); if (!lengthIfKnown.isPresent()) { return Optional.absent(); } result += lengthIfKnown.get(); } return Optional.of(result); } @Override public long length() throws IOException { long result = 0L; for (CharSource source : sources) { result += source.length(); } return result; } @Override public String toString() { return "CharSource.concat(" + sources + ")"; } } }
google/guava
android/guava/src/com/google/common/io/CharSource.java
248
/* * 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 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}. * * <p><b>For users targeting Android API level 24 or higher:</b> This class will eventually * implement {@code BiPredicate<T, T>} (as it does in the main Guava artifact), but we currently * target a lower API level. In the meantime, if you have support for method references you can use * an equivalence as a bi-predicate like this: {@code myEquivalence::equivalent}. * * @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> { /** 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); } /** * * @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
android/guava/src/com/google/common/base/Equivalence.java
249
/* * 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.NullnessCasts.uncheckedCastNullableTToT; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.errorprone.annotations.CheckReturnValue; import com.google.errorprone.annotations.ForOverride; import com.google.errorprone.annotations.InlineMe; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.j2objc.annotations.RetainedWith; import java.io.Serializable; import java.util.Iterator; import javax.annotation.CheckForNull; /** * A function from {@code A} to {@code B} with an associated <i>reverse</i> function from {@code B} * to {@code A}; used for converting back and forth between <i>different representations of the same * information</i>. * * <h3>Invertibility</h3> * * <p>The reverse operation <b>may</b> be a strict <i>inverse</i> (meaning that {@code * converter.reverse().convert(converter.convert(a)).equals(a)} is always true). However, it is very * common (perhaps <i>more</i> common) for round-trip conversion to be <i>lossy</i>. Consider an * example round-trip using {@link com.google.common.primitives.Doubles#stringConverter}: * * <ol> * <li>{@code stringConverter().convert("1.00")} returns the {@code Double} value {@code 1.0} * <li>{@code stringConverter().reverse().convert(1.0)} returns the string {@code "1.0"} -- * <i>not</i> the same string ({@code "1.00"}) we started with * </ol> * * <p>Note that it should still be the case that the round-tripped and original objects are * <i>similar</i>. * * <h3>Nullability</h3> * * <p>A converter always converts {@code null} to {@code null} and non-null references to non-null * references. It would not make sense to consider {@code null} and a non-null reference to be * "different representations of the same information", since one is distinguishable from * <i>missing</i> information and the other is not. The {@link #convert} method handles this null * behavior for all converters; implementations of {@link #doForward} and {@link #doBackward} are * guaranteed to never be passed {@code null}, and must never return {@code null}. * * <h3>Common ways to use</h3> * * <p>Getting a converter: * * <ul> * <li>Use a provided converter implementation, such as {@link Enums#stringConverter}, {@link * com.google.common.primitives.Ints#stringConverter Ints.stringConverter} or the {@linkplain * #reverse reverse} views of these. * <li>Convert between specific preset values using {@link * com.google.common.collect.Maps#asConverter Maps.asConverter}. For example, use this to * create a "fake" converter for a unit test. It is unnecessary (and confusing) to <i>mock</i> * the {@code Converter} type using a mocking framework. * <li>Extend this class and implement its {@link #doForward} and {@link #doBackward} methods. * <li><b>Java 8+ users:</b> you may prefer to pass two lambda expressions or method references to * the {@link #from from} factory method. * </ul> * * <p>Using a converter: * * <ul> * <li>Convert one instance in the "forward" direction using {@code converter.convert(a)}. * <li>Convert multiple instances "forward" using {@code converter.convertAll(as)}. * <li>Convert in the "backward" direction using {@code converter.reverse().convert(b)} or {@code * converter.reverse().convertAll(bs)}. * <li>Use {@code converter} or {@code converter.reverse()} anywhere a {@link * java.util.function.Function} is accepted (for example {@link java.util.stream.Stream#map * Stream.map}). * <li><b>Do not</b> call {@link #doForward} or {@link #doBackward} directly; these exist only to * be overridden. * </ul> * * <h3>Example</h3> * * <pre> * return new Converter&lt;Integer, String&gt;() { * protected String doForward(Integer i) { * return Integer.toHexString(i); * } * * protected Integer doBackward(String s) { * return parseUnsignedInt(s, 16); * } * };</pre> * * <p>An alternative using Java 8: * * <pre>{@code * return Converter.from( * Integer::toHexString, * s -> parseUnsignedInt(s, 16)); * }</pre> * * @author Mike Ward * @author Kurt Alfred Kluever * @author Gregory Kick * @since 16.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault /* * 1. The type parameter is <T> rather than <T extends @Nullable> so that we can use T in the * doForward and doBackward methods to indicate that the parameter cannot be null. (We also take * advantage of that for convertAll, as discussed on that method.) * * 2. The supertype of this class could be `Function<@Nullable A, @Nullable B>`, since * Converter.apply (like Converter.convert) is capable of accepting null inputs. However, a * supertype of `Function<A, B>` turns out to be massively more useful to callers in practice: They * want their output to be non-null in operations like `stream.map(myConverter)`, and we can * guarantee that as long as we also require the input type to be non-null[*] (which is a * requirement that existing callers already fulfill). * * Disclaimer: Part of the reason that callers are so well adapted to `Function<A, B>` may be that * that is how the signature looked even prior to this comment! So naturally any change can break * existing users, but it can't *fix* existing users because any users who needed * `Function<@Nullable A, @Nullable B>` already had to find a workaround. Still, there is a *ton* of * fallout from trying to switch. I would be shocked if the switch would offer benefits to anywhere * near enough users to justify the costs. * * Fortunately, if anyone does want to use a Converter as a `Function<@Nullable A, @Nullable B>`, * it's easy to get one: `converter::convert`. * * [*] In annotating this class, we're ignoring LegacyConverter. */ public abstract class Converter<A, B> implements Function<A, B> { private final boolean handleNullAutomatically; // We lazily cache the reverse view to avoid allocating on every call to reverse(). @LazyInit @RetainedWith @CheckForNull private transient Converter<B, A> reverse; /** Constructor for use by subclasses. */ protected Converter() { this(true); } /** Constructor used only by {@code LegacyConverter} to suspend automatic null-handling. */ Converter(boolean handleNullAutomatically) { this.handleNullAutomatically = handleNullAutomatically; } // SPI methods (what subclasses must implement) /** * Returns a representation of {@code a} as an instance of type {@code B}. If {@code a} cannot be * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown. * * @param a the instance to convert; will never be null * @return the converted instance; <b>must not</b> be null */ @ForOverride protected abstract B doForward(A a); /** * Returns a representation of {@code b} as an instance of type {@code A}. If {@code b} cannot be * converted, an unchecked exception (such as {@link IllegalArgumentException}) should be thrown. * * @param b the instance to convert; will never be null * @return the converted instance; <b>must not</b> be null * @throws UnsupportedOperationException if backward conversion is not implemented; this should be * very rare. Note that if backward conversion is not only unimplemented but * unimplement<i>able</i> (for example, consider a {@code Converter<Chicken, ChickenNugget>}), * then this is not logically a {@code Converter} at all, and should just implement {@link * Function}. */ @ForOverride protected abstract A doBackward(B b); // API (consumer-side) methods /** * Returns a representation of {@code a} as an instance of type {@code B}. * * @return the converted value; is null <i>if and only if</i> {@code a} is null */ @CheckForNull public final B convert(@CheckForNull A a) { return correctedDoForward(a); } @CheckForNull B correctedDoForward(@CheckForNull A a) { if (handleNullAutomatically) { // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? return a == null ? null : checkNotNull(doForward(a)); } else { return unsafeDoForward(a); } } @CheckForNull A correctedDoBackward(@CheckForNull B b) { if (handleNullAutomatically) { // TODO(kevinb): we shouldn't be checking for a null result at runtime. Assert? return b == null ? null : checkNotNull(doBackward(b)); } else { return unsafeDoBackward(b); } } /* * LegacyConverter violates the contract of Converter by allowing its doForward and doBackward * methods to accept null. We could avoid having unchecked casts in Converter.java itself if we * could perform a cast to LegacyConverter, but we can't because it's an internal-only class. * * TODO(cpovirk): So make it part of the open-source build, albeit package-private there? * * So we use uncheckedCastNullableTToT here. This is a weird usage of that method: The method is * documented as being for use with type parameters that have parametric nullness. But Converter's * type parameters do not. Still, we use it here so that we can suppress a warning at a smaller * level than the whole method but without performing a runtime null check. That way, we can still * pass null inputs to LegacyConverter, and it can violate the contract of Converter. * * TODO(cpovirk): Could this be simplified if we modified implementations of LegacyConverter to * override methods (probably called "unsafeDoForward" and "unsafeDoBackward") with the same * signatures as the methods below, rather than overriding the same doForward and doBackward * methods as implementations of normal converters do? * * But no matter what we do, it's worth remembering that the resulting code is going to be unsound * in the presence of LegacyConverter, at least in the case of users who view the converter as a * Function<A, B> or who call convertAll (and for any checkers that apply @PolyNull-like semantics * to Converter.convert). So maybe we don't want to think too hard about how to prevent our * checkers from issuing errors related to LegacyConverter, since it turns out that * LegacyConverter does violate the assumptions we make elsewhere. */ @CheckForNull private B unsafeDoForward(@CheckForNull A a) { return doForward(uncheckedCastNullableTToT(a)); } @CheckForNull private A unsafeDoBackward(@CheckForNull B b) { return doBackward(uncheckedCastNullableTToT(b)); } /** * Returns an iterable that applies {@code convert} to each element of {@code fromIterable}. The * conversion is done lazily. * * <p>The returned iterable's iterator supports {@code remove()} if the input iterator does. After * a successful {@code remove()} call, {@code fromIterable} no longer contains the corresponding * element. */ /* * Just as Converter could implement `Function<@Nullable A, @Nullable B>` instead of `Function<A, * B>`, convertAll could accept and return iterables with nullable element types. In both cases, * we've chosen to instead use a signature that benefits existing users -- and is still safe. * * For convertAll, I haven't looked as closely at *how* much existing users benefit, so we should * keep an eye out for problems that new users encounter. Note also that convertAll could support * both use cases by using @PolyNull. (By contrast, we can't use @PolyNull for our superinterface * (`implements Function<@PolyNull A, @PolyNull B>`), at least as far as I know.) */ public Iterable<B> convertAll(Iterable<? extends A> fromIterable) { checkNotNull(fromIterable, "fromIterable"); return new Iterable<B>() { @Override public Iterator<B> iterator() { return new Iterator<B>() { private final Iterator<? extends A> fromIterator = fromIterable.iterator(); @Override public boolean hasNext() { return fromIterator.hasNext(); } @Override public B next() { return convert(fromIterator.next()); } @Override public void remove() { fromIterator.remove(); } }; } }; } /** * Returns the reversed view of this converter, which converts {@code this.convert(a)} back to a * value roughly equivalent to {@code a}. * * <p>The returned converter is serializable if {@code this} converter is. * * <p><b>Note:</b> you should not override this method. It is non-final for legacy reasons. */ @CheckReturnValue public Converter<B, A> reverse() { Converter<B, A> result = reverse; return (result == null) ? reverse = new ReverseConverter<>(this) : result; } private static final class ReverseConverter<A, B> extends Converter<B, A> implements Serializable { final Converter<A, B> original; ReverseConverter(Converter<A, B> original) { this.original = original; } /* * These gymnastics are a little confusing. Basically this class has neither legacy nor * non-legacy behavior; it just needs to let the behavior of the backing converter shine * through. So, we override the correctedDo* methods, after which the do* methods should never * be reached. */ @Override protected A doForward(B b) { throw new AssertionError(); } @Override protected B doBackward(A a) { throw new AssertionError(); } @Override @CheckForNull A correctedDoForward(@CheckForNull B b) { return original.correctedDoBackward(b); } @Override @CheckForNull B correctedDoBackward(@CheckForNull A a) { return original.correctedDoForward(a); } @Override public Converter<A, B> reverse() { return original; } @Override public boolean equals(@CheckForNull Object object) { if (object instanceof ReverseConverter) { ReverseConverter<?, ?> that = (ReverseConverter<?, ?>) object; return this.original.equals(that.original); } return false; } @Override public int hashCode() { return ~original.hashCode(); } @Override public String toString() { return original + ".reverse()"; } private static final long serialVersionUID = 0L; } /** * Returns a converter whose {@code convert} method applies {@code secondConverter} to the result * of this converter. Its {@code reverse} method applies the converters in reverse order. * * <p>The returned converter is serializable if {@code this} converter and {@code secondConverter} * are. */ public final <C> Converter<A, C> andThen(Converter<B, C> secondConverter) { return doAndThen(secondConverter); } /** Package-private non-final implementation of andThen() so only we can override it. */ <C> Converter<A, C> doAndThen(Converter<B, C> secondConverter) { return new ConverterComposition<>(this, checkNotNull(secondConverter)); } private static final class ConverterComposition<A, B, C> extends Converter<A, C> implements Serializable { final Converter<A, B> first; final Converter<B, C> second; ConverterComposition(Converter<A, B> first, Converter<B, C> second) { this.first = first; this.second = second; } /* * These gymnastics are a little confusing. Basically this class has neither legacy nor * non-legacy behavior; it just needs to let the behaviors of the backing converters shine * through (which might even differ from each other!). So, we override the correctedDo* methods, * after which the do* methods should never be reached. */ @Override protected C doForward(A a) { throw new AssertionError(); } @Override protected A doBackward(C c) { throw new AssertionError(); } @Override @CheckForNull C correctedDoForward(@CheckForNull A a) { return second.correctedDoForward(first.correctedDoForward(a)); } @Override @CheckForNull A correctedDoBackward(@CheckForNull C c) { return first.correctedDoBackward(second.correctedDoBackward(c)); } @Override public boolean equals(@CheckForNull Object object) { if (object instanceof ConverterComposition) { ConverterComposition<?, ?, ?> that = (ConverterComposition<?, ?, ?>) object; return this.first.equals(that.first) && this.second.equals(that.second); } return false; } @Override public int hashCode() { return 31 * first.hashCode() + second.hashCode(); } @Override public String toString() { return first + ".andThen(" + second + ")"; } private static final long serialVersionUID = 0L; } /** * @deprecated Provided to satisfy the {@code Function} interface; use {@link #convert} instead. */ @Deprecated @Override @InlineMe(replacement = "this.convert(a)") public final B apply(A a) { /* * Given that we declare this method as accepting and returning non-nullable values (because we * implement Function<A, B>, as discussed in a class-level comment), it would make some sense to * perform runtime null checks on the input and output. (That would also make NullPointerTester * happy!) However, since we didn't do that for many years, we're not about to start now. * (Runtime checks could be particularly bad for users of LegacyConverter.) * * Luckily, our nullness checker is smart enough to realize that `convert` has @PolyNull-like * behavior, so it knows that `convert(a)` returns a non-nullable value, and we don't need to * perform even a cast, much less a runtime check. * * All that said, don't forget that everyone should call converter.convert() instead of * converter.apply(), anyway. If clients use only converter.convert(), then their nullness * checkers are unlikely to ever look at the annotations on this declaration. * * Historical note: At one point, we'd declared this method as accepting and returning nullable * values. For details on that, see earlier revisions of this file. */ return convert(a); } /** * Indicates whether another object is equal to this converter. * * <p>Most implementations will have no reason to override the behavior of {@link Object#equals}. * However, an implementation may also choose to return {@code true} whenever {@code object} is a * {@link Converter} that it considers <i>interchangeable</i> with this one. "Interchangeable" * <i>typically</i> means that {@code Objects.equal(this.convert(a), that.convert(a))} is true for * all {@code a} of type {@code A} (and similarly for {@code reverse}). Note that a {@code false} * result from this method does not imply that the converters are known <i>not</i> to be * interchangeable. */ @Override public boolean equals(@CheckForNull Object object) { return super.equals(object); } // Static converters /** * Returns a converter based on separate forward and backward functions. This is useful if the * function instances already exist, or so that you can supply lambda expressions. If those * circumstances don't apply, you probably don't need to use this; subclass {@code Converter} and * implement its {@link #doForward} and {@link #doBackward} methods directly. * * <p>These functions will never be passed {@code null} and must not under any circumstances * return {@code null}. If a value cannot be converted, the function should throw an unchecked * exception (typically, but not necessarily, {@link IllegalArgumentException}). * * <p>The returned converter is serializable if both provided functions are. * * @since 17.0 */ public static <A, B> Converter<A, B> from( Function<? super A, ? extends B> forwardFunction, Function<? super B, ? extends A> backwardFunction) { return new FunctionBasedConverter<>(forwardFunction, backwardFunction); } private static final class FunctionBasedConverter<A, B> extends Converter<A, B> implements Serializable { private final Function<? super A, ? extends B> forwardFunction; private final Function<? super B, ? extends A> backwardFunction; private FunctionBasedConverter( Function<? super A, ? extends B> forwardFunction, Function<? super B, ? extends A> backwardFunction) { this.forwardFunction = checkNotNull(forwardFunction); this.backwardFunction = checkNotNull(backwardFunction); } @Override protected B doForward(A a) { return forwardFunction.apply(a); } @Override protected A doBackward(B b) { return backwardFunction.apply(b); } @Override public boolean equals(@CheckForNull Object object) { if (object instanceof FunctionBasedConverter) { FunctionBasedConverter<?, ?> that = (FunctionBasedConverter<?, ?>) object; return this.forwardFunction.equals(that.forwardFunction) && this.backwardFunction.equals(that.backwardFunction); } return false; } @Override public int hashCode() { return forwardFunction.hashCode() * 31 + backwardFunction.hashCode(); } @Override public String toString() { return "Converter.from(" + forwardFunction + ", " + backwardFunction + ")"; } } /** Returns a serializable converter that always converts or reverses an object to itself. */ @SuppressWarnings("unchecked") // implementation is "fully variant" public static <T> Converter<T, T> identity() { return (IdentityConverter<T>) IdentityConverter.INSTANCE; } /** * A converter that always converts or reverses an object to itself. Note that T is now a * "pass-through type". */ private static final class IdentityConverter<T> extends Converter<T, T> implements Serializable { static final Converter<?, ?> INSTANCE = new IdentityConverter<>(); @Override protected T doForward(T t) { return t; } @Override protected T doBackward(T t) { return t; } @Override public IdentityConverter<T> reverse() { return this; } @Override <S> Converter<T, S> doAndThen(Converter<T, S> otherConverter) { return checkNotNull(otherConverter, "otherConverter"); } /* * We *could* override convertAll() to return its input, but it's a rather pointless * optimization and opened up a weird type-safety problem. */ @Override public String toString() { return "Converter.identity()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 0L; } }
google/guava
android/guava/src/com/google/common/base/Converter.java
250
/* * 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.checkNotNull; import static com.google.common.base.Predicates.alwaysTrue; import static com.google.common.base.Predicates.equalTo; import static com.google.common.base.Predicates.in; import static com.google.common.base.Predicates.not; import static com.google.common.collect.Maps.safeContainsKey; import static com.google.common.collect.Maps.safeGet; import static com.google.common.collect.NullnessCasts.uncheckedCastNullableTToT; import static java.util.Objects.requireNonNull; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.base.Supplier; import com.google.common.collect.Maps.IteratorBasedAbstractMap; import com.google.common.collect.Maps.ViewCachingAbstractMap; import com.google.common.collect.Sets.ImprovedAbstractSet; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.errorprone.annotations.concurrent.LazyInit; import com.google.j2objc.annotations.WeakOuter; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.Map.Entry; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import javax.annotation.CheckForNull; /** * {@link Table} implementation backed by a map that associates row keys with column key / value * secondary maps. This class provides rapid access to records by the row key alone or by both keys, * but not by just the column key. * * <p>The views returned by {@link #column}, {@link #columnKeySet()}, and {@link #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. * * @author Jared Levy */ @GwtCompatible @ElementTypesAreNonnullByDefault class StandardTable<R, C, V> extends AbstractTable<R, C, V> implements Serializable { @GwtTransient final Map<R, Map<C, V>> backingMap; @GwtTransient final Supplier<? extends Map<C, V>> factory; StandardTable(Map<R, Map<C, V>> backingMap, Supplier<? extends Map<C, V>> factory) { this.backingMap = backingMap; this.factory = factory; } // Accessors @Override public boolean contains(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return rowKey != null && columnKey != null && super.contains(rowKey, columnKey); } @Override public boolean containsColumn(@CheckForNull Object columnKey) { if (columnKey == null) { return false; } for (Map<C, V> map : backingMap.values()) { if (safeContainsKey(map, columnKey)) { return true; } } return false; } @Override public boolean containsRow(@CheckForNull Object rowKey) { return rowKey != null && safeContainsKey(backingMap, rowKey); } @Override public boolean containsValue(@CheckForNull Object value) { return value != null && super.containsValue(value); } @Override @CheckForNull public V get(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { return (rowKey == null || columnKey == null) ? null : super.get(rowKey, columnKey); } @Override public boolean isEmpty() { return backingMap.isEmpty(); } @Override public int size() { int size = 0; for (Map<C, V> map : backingMap.values()) { size += map.size(); } return size; } // Mutators @Override public void clear() { backingMap.clear(); } private Map<C, V> getOrCreate(R rowKey) { Map<C, V> map = backingMap.get(rowKey); if (map == null) { map = factory.get(); backingMap.put(rowKey, map); } return map; } @CanIgnoreReturnValue @Override @CheckForNull public V put(R rowKey, C columnKey, V value) { checkNotNull(rowKey); checkNotNull(columnKey); checkNotNull(value); return getOrCreate(rowKey).put(columnKey, value); } @CanIgnoreReturnValue @Override @CheckForNull public V remove(@CheckForNull Object rowKey, @CheckForNull Object columnKey) { if ((rowKey == null) || (columnKey == null)) { return null; } Map<C, V> map = safeGet(backingMap, rowKey); if (map == null) { return null; } V value = map.remove(columnKey); if (map.isEmpty()) { backingMap.remove(rowKey); } return value; } @CanIgnoreReturnValue private Map<R, V> removeColumn(@CheckForNull Object column) { Map<R, V> output = new LinkedHashMap<>(); Iterator<Entry<R, Map<C, V>>> iterator = backingMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<R, Map<C, V>> entry = iterator.next(); V value = entry.getValue().remove(column); if (value != null) { output.put(entry.getKey(), value); if (entry.getValue().isEmpty()) { iterator.remove(); } } } return output; } private boolean containsMapping( @CheckForNull Object rowKey, @CheckForNull Object columnKey, @CheckForNull Object value) { return value != null && value.equals(get(rowKey, columnKey)); } /** Remove a row key / column key / value mapping, if present. */ private boolean removeMapping( @CheckForNull Object rowKey, @CheckForNull Object columnKey, @CheckForNull Object value) { if (containsMapping(rowKey, columnKey, value)) { remove(rowKey, columnKey); return true; } return false; } // Views /** * Abstract set whose {@code isEmpty()} returns whether the table is empty and whose {@code * clear()} clears all table mappings. */ @WeakOuter private abstract class TableSet<T> extends ImprovedAbstractSet<T> { @Override public boolean isEmpty() { return backingMap.isEmpty(); } @Override public void clear() { backingMap.clear(); } } /** * {@inheritDoc} * * <p>The set's iterator traverses the mappings for the first row, the mappings for the second * row, and so on. * * <p>Each cell is an immutable snapshot of a row key / column key / value mapping, taken at the * time the cell is returned by a method call to the set or its iterator. */ @Override public Set<Cell<R, C, V>> cellSet() { return super.cellSet(); } @Override Iterator<Cell<R, C, V>> cellIterator() { return new CellIterator(); } private class CellIterator implements Iterator<Cell<R, C, V>> { final Iterator<Entry<R, Map<C, V>>> rowIterator = backingMap.entrySet().iterator(); @CheckForNull Entry<R, Map<C, V>> rowEntry; Iterator<Entry<C, V>> columnIterator = Iterators.emptyModifiableIterator(); @Override public boolean hasNext() { return rowIterator.hasNext() || columnIterator.hasNext(); } @Override public Cell<R, C, V> next() { if (!columnIterator.hasNext()) { rowEntry = rowIterator.next(); columnIterator = rowEntry.getValue().entrySet().iterator(); } /* * requireNonNull is safe because: * * - columnIterator started off pointing to an empty iterator, so we must have entered the * `if` body above at least once. Thus, if we got this far, that `if` body initialized * rowEntry at least once. * * - The only case in which rowEntry is cleared (during remove() below) happens only if the * caller removed every element from columnIterator. During that process, we would have had * to iterate it to exhaustion. Then we can apply the logic above about an empty * columnIterator. (This assumes no concurrent modification, but behavior under concurrent * modification is undefined, anyway.) */ requireNonNull(rowEntry); Entry<C, V> columnEntry = columnIterator.next(); return Tables.immutableCell(rowEntry.getKey(), columnEntry.getKey(), columnEntry.getValue()); } @Override public void remove() { columnIterator.remove(); /* * requireNonNull is safe because: * * - columnIterator.remove() succeeded, so it must have returned a value, so it must have been * initialized by next() -- which initializes rowEntry, too. * * - rowEntry isn't cleared except below. If it was cleared below, then either * columnIterator.remove() would have failed above (if the user hasn't called next() since * then) or rowEntry would have been initialized by next() (as discussed above). */ if (requireNonNull(rowEntry).getValue().isEmpty()) { rowIterator.remove(); rowEntry = null; } } } @Override Spliterator<Cell<R, C, V>> cellSpliterator() { return CollectSpliterators.flatMap( backingMap.entrySet().spliterator(), (Entry<R, Map<C, V>> rowEntry) -> CollectSpliterators.map( rowEntry.getValue().entrySet().spliterator(), (Entry<C, V> columnEntry) -> Tables.immutableCell( rowEntry.getKey(), columnEntry.getKey(), columnEntry.getValue())), Spliterator.DISTINCT | Spliterator.SIZED, size()); } @Override public Map<C, V> row(R rowKey) { return new Row(rowKey); } class Row extends IteratorBasedAbstractMap<C, V> { final R rowKey; Row(R rowKey) { this.rowKey = checkNotNull(rowKey); } @CheckForNull Map<C, V> backingRowMap; final void updateBackingRowMapField() { if (backingRowMap == null || (backingRowMap.isEmpty() && backingMap.containsKey(rowKey))) { backingRowMap = computeBackingRowMap(); } } @CheckForNull Map<C, V> computeBackingRowMap() { return backingMap.get(rowKey); } // Call this every time we perform a removal. void maintainEmptyInvariant() { updateBackingRowMapField(); if (backingRowMap != null && backingRowMap.isEmpty()) { backingMap.remove(rowKey); backingRowMap = null; } } @Override public boolean containsKey(@CheckForNull Object key) { updateBackingRowMapField(); return (key != null && backingRowMap != null) && Maps.safeContainsKey(backingRowMap, key); } @Override @CheckForNull public V get(@CheckForNull Object key) { updateBackingRowMapField(); return (key != null && backingRowMap != null) ? Maps.safeGet(backingRowMap, key) : null; } @Override @CheckForNull public V put(C key, V value) { checkNotNull(key); checkNotNull(value); if (backingRowMap != null && !backingRowMap.isEmpty()) { return backingRowMap.put(key, value); } return StandardTable.this.put(rowKey, key, value); } @Override @CheckForNull public V remove(@CheckForNull Object key) { updateBackingRowMapField(); if (backingRowMap == null) { return null; } V result = Maps.safeRemove(backingRowMap, key); maintainEmptyInvariant(); return result; } @Override public void clear() { updateBackingRowMapField(); if (backingRowMap != null) { backingRowMap.clear(); } maintainEmptyInvariant(); } @Override public int size() { updateBackingRowMapField(); return (backingRowMap == null) ? 0 : backingRowMap.size(); } @Override Iterator<Entry<C, V>> entryIterator() { updateBackingRowMapField(); if (backingRowMap == null) { return Iterators.emptyModifiableIterator(); } final Iterator<Entry<C, V>> iterator = backingRowMap.entrySet().iterator(); return new Iterator<Entry<C, V>>() { @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry<C, V> next() { return wrapEntry(iterator.next()); } @Override public void remove() { iterator.remove(); maintainEmptyInvariant(); } }; } @Override Spliterator<Entry<C, V>> entrySpliterator() { updateBackingRowMapField(); if (backingRowMap == null) { return Spliterators.emptySpliterator(); } return CollectSpliterators.map(backingRowMap.entrySet().spliterator(), this::wrapEntry); } Entry<C, V> wrapEntry(final Entry<C, V> entry) { return new ForwardingMapEntry<C, V>() { @Override protected Entry<C, V> delegate() { return entry; } @Override public V setValue(V value) { return super.setValue(checkNotNull(value)); } @Override public boolean equals(@CheckForNull Object object) { // TODO(lowasser): identify why this affects GWT tests return standardEquals(object); } }; } } /** * {@inheritDoc} * * <p>The returned map's views have iterators that don't support {@code remove()}. */ @Override public Map<R, V> column(C columnKey) { return new Column(columnKey); } private class Column extends ViewCachingAbstractMap<R, V> { final C columnKey; Column(C columnKey) { this.columnKey = checkNotNull(columnKey); } @Override @CheckForNull public V put(R key, V value) { return StandardTable.this.put(key, columnKey, value); } @Override @CheckForNull public V get(@CheckForNull Object key) { return StandardTable.this.get(key, columnKey); } @Override public boolean containsKey(@CheckForNull Object key) { return StandardTable.this.contains(key, columnKey); } @Override @CheckForNull public V remove(@CheckForNull Object key) { return StandardTable.this.remove(key, columnKey); } /** Removes all {@code Column} mappings whose row key and value satisfy the given predicate. */ @CanIgnoreReturnValue boolean removeFromColumnIf(Predicate<? super Entry<R, V>> predicate) { boolean changed = false; Iterator<Entry<R, Map<C, V>>> iterator = backingMap.entrySet().iterator(); while (iterator.hasNext()) { Entry<R, Map<C, V>> entry = iterator.next(); Map<C, V> map = entry.getValue(); V value = map.get(columnKey); if (value != null && predicate.apply(Maps.immutableEntry(entry.getKey(), value))) { map.remove(columnKey); changed = true; if (map.isEmpty()) { iterator.remove(); } } } return changed; } @Override Set<Entry<R, V>> createEntrySet() { return new EntrySet(); } @WeakOuter private class EntrySet extends ImprovedAbstractSet<Entry<R, V>> { @Override public Iterator<Entry<R, V>> iterator() { return new EntrySetIterator(); } @Override public int size() { int size = 0; for (Map<C, V> map : backingMap.values()) { if (map.containsKey(columnKey)) { size++; } } return size; } @Override public boolean isEmpty() { return !containsColumn(columnKey); } @Override public void clear() { removeFromColumnIf(alwaysTrue()); } @Override public boolean contains(@CheckForNull Object o) { if (o instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) o; return containsMapping(entry.getKey(), columnKey, entry.getValue()); } return false; } @Override public boolean remove(@CheckForNull Object obj) { if (obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; return removeMapping(entry.getKey(), columnKey, entry.getValue()); } return false; } @Override public boolean retainAll(Collection<?> c) { return removeFromColumnIf(not(in(c))); } } private class EntrySetIterator extends AbstractIterator<Entry<R, V>> { final Iterator<Entry<R, Map<C, V>>> iterator = backingMap.entrySet().iterator(); @Override @CheckForNull protected Entry<R, V> computeNext() { while (iterator.hasNext()) { final Entry<R, Map<C, V>> entry = iterator.next(); if (entry.getValue().containsKey(columnKey)) { @WeakOuter class EntryImpl extends AbstractMapEntry<R, V> { @Override public R getKey() { return entry.getKey(); } @Override public V getValue() { return entry.getValue().get(columnKey); } @Override public V setValue(V value) { /* * The cast is safe because of the containsKey check above. (Well, it's possible for * the map to change between that call and this one. But if that happens, the * behavior is undefined because of the concurrent mutation.) * * (Our prototype checker happens to be "smart" enough to understand this for the * *get* call in getValue but not for the *put* call here.) * * (Arguably we should use requireNonNull rather than uncheckedCastNullableTToT: We * know that V is a non-null type because that's the only kind of value type that * StandardTable supports. Thus, requireNonNull is safe as long as the cell is still * present. (And if it's not present, behavior is undefined.) However, that's a * behavior change relative to the old code, so it didn't seem worth risking.) */ return uncheckedCastNullableTToT( entry.getValue().put(columnKey, checkNotNull(value))); } } return new EntryImpl(); } } return endOfData(); } } @Override Set<R> createKeySet() { return new KeySet(); } @WeakOuter private class KeySet extends Maps.KeySet<R, V> { KeySet() { super(Column.this); } @Override public boolean contains(@CheckForNull Object obj) { return StandardTable.this.contains(obj, columnKey); } @Override public boolean remove(@CheckForNull Object obj) { return StandardTable.this.remove(obj, columnKey) != null; } @Override public boolean retainAll(final Collection<?> c) { return removeFromColumnIf(Maps.<R>keyPredicateOnEntries(not(in(c)))); } } @Override Collection<V> createValues() { return new Values(); } @WeakOuter private class Values extends Maps.Values<R, V> { Values() { super(Column.this); } @Override public boolean remove(@CheckForNull Object obj) { return obj != null && removeFromColumnIf(Maps.<V>valuePredicateOnEntries(equalTo(obj))); } @Override public boolean removeAll(final Collection<?> c) { return removeFromColumnIf(Maps.<V>valuePredicateOnEntries(in(c))); } @Override public boolean retainAll(final Collection<?> c) { return removeFromColumnIf(Maps.<V>valuePredicateOnEntries(not(in(c)))); } } } @Override public Set<R> rowKeySet() { return rowMap().keySet(); } @LazyInit @CheckForNull private transient Set<C> columnKeySet; /** * {@inheritDoc} * * <p>The returned set has an iterator that does not support {@code remove()}. * * <p>The set's iterator traverses the columns of the first row, the columns of the second row, * etc., skipping any columns that have appeared previously. */ @Override public Set<C> columnKeySet() { Set<C> result = columnKeySet; return (result == null) ? columnKeySet = new ColumnKeySet() : result; } @WeakOuter private class ColumnKeySet extends TableSet<C> { @Override public Iterator<C> iterator() { return createColumnKeyIterator(); } @Override public int size() { return Iterators.size(iterator()); } @Override public boolean remove(@CheckForNull Object obj) { if (obj == null) { return false; } boolean changed = false; Iterator<Map<C, V>> iterator = backingMap.values().iterator(); while (iterator.hasNext()) { Map<C, V> map = iterator.next(); if (map.keySet().remove(obj)) { changed = true; if (map.isEmpty()) { iterator.remove(); } } } return changed; } @Override public boolean removeAll(Collection<?> c) { checkNotNull(c); boolean changed = false; Iterator<Map<C, V>> iterator = backingMap.values().iterator(); while (iterator.hasNext()) { Map<C, V> map = iterator.next(); // map.keySet().removeAll(c) can throw a NPE when map is a TreeMap with // natural ordering and c contains a null. if (Iterators.removeAll(map.keySet().iterator(), c)) { changed = true; if (map.isEmpty()) { iterator.remove(); } } } return changed; } @Override public boolean retainAll(Collection<?> c) { checkNotNull(c); boolean changed = false; Iterator<Map<C, V>> iterator = backingMap.values().iterator(); while (iterator.hasNext()) { Map<C, V> map = iterator.next(); if (map.keySet().retainAll(c)) { changed = true; if (map.isEmpty()) { iterator.remove(); } } } return changed; } @Override public boolean contains(@CheckForNull Object obj) { return containsColumn(obj); } } /** Creates an iterator that returns each column value with duplicates omitted. */ Iterator<C> createColumnKeyIterator() { return new ColumnKeyIterator(); } private class ColumnKeyIterator extends AbstractIterator<C> { // Use the same map type to support TreeMaps with comparators that aren't // consistent with equals(). final Map<C, V> seen = factory.get(); final Iterator<Map<C, V>> mapIterator = backingMap.values().iterator(); Iterator<Entry<C, V>> entryIterator = Iterators.emptyIterator(); @Override @CheckForNull protected C computeNext() { while (true) { if (entryIterator.hasNext()) { Entry<C, V> entry = entryIterator.next(); if (!seen.containsKey(entry.getKey())) { seen.put(entry.getKey(), entry.getValue()); return entry.getKey(); } } else if (mapIterator.hasNext()) { entryIterator = mapIterator.next().entrySet().iterator(); } else { return endOfData(); } } } } /** * {@inheritDoc} * * <p>The collection's iterator traverses the values for the first row, the values for the second * row, and so on. */ @Override public Collection<V> values() { return super.values(); } @LazyInit @CheckForNull private transient Map<R, Map<C, V>> rowMap; @Override public Map<R, Map<C, V>> rowMap() { Map<R, Map<C, V>> result = rowMap; return (result == null) ? rowMap = createRowMap() : result; } Map<R, Map<C, V>> createRowMap() { return new RowMap(); } @WeakOuter class RowMap extends ViewCachingAbstractMap<R, Map<C, V>> { @Override public boolean containsKey(@CheckForNull Object key) { return containsRow(key); } // performing cast only when key is in backing map and has the correct type @SuppressWarnings("unchecked") @Override @CheckForNull public Map<C, V> get(@CheckForNull Object key) { // requireNonNull is safe because of the containsRow check. return containsRow(key) ? row((R) requireNonNull(key)) : null; } @Override @CheckForNull public Map<C, V> remove(@CheckForNull Object key) { return (key == null) ? null : backingMap.remove(key); } @Override protected Set<Entry<R, Map<C, V>>> createEntrySet() { return new EntrySet(); } @WeakOuter private final class EntrySet extends TableSet<Entry<R, Map<C, V>>> { @Override public Iterator<Entry<R, Map<C, V>>> iterator() { return Maps.asMapEntryIterator( backingMap.keySet(), new Function<R, Map<C, V>>() { @Override public Map<C, V> apply(R rowKey) { return row(rowKey); } }); } @Override public int size() { return backingMap.size(); } @Override public boolean contains(@CheckForNull Object obj) { if (obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; return entry.getKey() != null && entry.getValue() instanceof Map && Collections2.safeContains(backingMap.entrySet(), entry); } return false; } @Override public boolean remove(@CheckForNull Object obj) { if (obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; return entry.getKey() != null && entry.getValue() instanceof Map && backingMap.entrySet().remove(entry); } return false; } } } @LazyInit @CheckForNull private transient ColumnMap columnMap; @Override public Map<C, Map<R, V>> columnMap() { ColumnMap result = columnMap; return (result == null) ? columnMap = new ColumnMap() : result; } @WeakOuter private class ColumnMap extends ViewCachingAbstractMap<C, Map<R, V>> { // The cast to C occurs only when the key is in the map, implying that it // has the correct type. @SuppressWarnings("unchecked") @Override @CheckForNull public Map<R, V> get(@CheckForNull Object key) { // requireNonNull is safe because of the containsColumn check. return containsColumn(key) ? column((C) requireNonNull(key)) : null; } @Override public boolean containsKey(@CheckForNull Object key) { return containsColumn(key); } @Override @CheckForNull public Map<R, V> remove(@CheckForNull Object key) { return containsColumn(key) ? removeColumn(key) : null; } @Override public Set<Entry<C, Map<R, V>>> createEntrySet() { return new ColumnMapEntrySet(); } @Override public Set<C> keySet() { return columnKeySet(); } @Override Collection<Map<R, V>> createValues() { return new ColumnMapValues(); } @WeakOuter private final class ColumnMapEntrySet extends TableSet<Entry<C, Map<R, V>>> { @Override public Iterator<Entry<C, Map<R, V>>> iterator() { return Maps.asMapEntryIterator( columnKeySet(), new Function<C, Map<R, V>>() { @Override public Map<R, V> apply(C columnKey) { return column(columnKey); } }); } @Override public int size() { return columnKeySet().size(); } @Override public boolean contains(@CheckForNull Object obj) { if (obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; if (containsColumn(entry.getKey())) { // requireNonNull is safe because of the containsColumn check. return requireNonNull(get(entry.getKey())).equals(entry.getValue()); } } return false; } @Override public boolean remove(@CheckForNull Object obj) { /* * `o instanceof Entry` is guaranteed by `contains`, but we check it here to satisfy our * nullness checker. */ if (contains(obj) && obj instanceof Entry) { Entry<?, ?> entry = (Entry<?, ?>) obj; removeColumn(entry.getKey()); return true; } return false; } @Override public boolean removeAll(Collection<?> c) { /* * We can't inherit the normal implementation (which calls * Sets.removeAllImpl(Set, *Collection*)) because, under some * circumstances, it attempts to call columnKeySet().iterator().remove, * which is unsupported. */ checkNotNull(c); return Sets.removeAllImpl(this, c.iterator()); } @Override public boolean retainAll(Collection<?> c) { checkNotNull(c); boolean changed = false; for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) { if (!c.contains(Maps.immutableEntry(columnKey, column(columnKey)))) { removeColumn(columnKey); changed = true; } } return changed; } } @WeakOuter private class ColumnMapValues extends Maps.Values<C, Map<R, V>> { ColumnMapValues() { super(ColumnMap.this); } @Override public boolean remove(@CheckForNull Object obj) { for (Entry<C, Map<R, V>> entry : ColumnMap.this.entrySet()) { if (entry.getValue().equals(obj)) { removeColumn(entry.getKey()); return true; } } return false; } @Override public boolean removeAll(Collection<?> c) { checkNotNull(c); boolean changed = false; for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) { if (c.contains(column(columnKey))) { removeColumn(columnKey); changed = true; } } return changed; } @Override public boolean retainAll(Collection<?> c) { checkNotNull(c); boolean changed = false; for (C columnKey : Lists.newArrayList(columnKeySet().iterator())) { if (!c.contains(column(columnKey))) { removeColumn(columnKey); changed = true; } } return changed; } } } private static final long serialVersionUID = 0; }
google/guava
guava/src/com/google/common/collect/StandardTable.java
251
/* * 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 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 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
android/guava/src/com/google/common/primitives/Ints.java
252
// 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 package com.google.protobuf; import static com.google.protobuf.Internal.checkNotNull; import static com.google.protobuf.TextFormatEscaper.escapeBytes; import static java.lang.Integer.toHexString; import static java.lang.System.identityHashCode; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InvalidObjectException; import java.io.ObjectInputStream; import java.io.OutputStream; import java.io.Serializable; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.InvalidMarkException; import java.nio.charset.Charset; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.Iterator; import java.util.List; import java.util.Locale; import java.util.NoSuchElementException; /** * Immutable sequence of bytes. Provides conversions to and from {@code byte[]}, {@link * java.lang.String}, {@link ByteBuffer}, {@link InputStream}, {@link OutputStream}. Also provides a * conversion to {@link CodedInputStream}. * * <p>Like {@link String}, the contents of a {@link ByteString} can never be observed to change, not * even in the presence of a data race or incorrect API usage in the client code. * * <p>Substring is supported by sharing the reference to the immutable underlying bytes. * Concatenation is likewise supported without copying (long strings) by building a tree of pieces * in {@link RopeByteString}. * * @author [email protected] Bob Lee * @author [email protected] Kenton Varda * @author [email protected] Carl Haverl * @author [email protected] Martin Buchholz */ @CheckReturnValue public abstract class ByteString implements Iterable<Byte>, Serializable { private static final long serialVersionUID = 1L; /** * When two strings to be concatenated have a combined length shorter than this, we just copy * their bytes on {@link #concat(ByteString)}. The trade-off is copy size versus the overhead of * creating tree nodes in {@link RopeByteString}. */ static final int CONCATENATE_BY_COPY_SIZE = 128; /** * When copying an InputStream into a ByteString with .readFrom(), the chunks in the underlying * rope start at 256 bytes, but double each iteration up to 8192 bytes. */ static final int MIN_READ_FROM_CHUNK_SIZE = 0x100; // 256b static final int MAX_READ_FROM_CHUNK_SIZE = 0x2000; // 8k /** Empty {@code ByteString}. */ public static final ByteString EMPTY = new LiteralByteString(Internal.EMPTY_BYTE_ARRAY); /** * An interface to efficiently copy {@code byte[]}. * * <p>One of the noticeable costs of copying a byte[] into a new array using {@code * System.arraycopy} is nullification of a new buffer before the copy. It has been shown the * Hotspot VM is capable to intrisicfy {@code Arrays.copyOfRange} operation to avoid this * expensive nullification and provide substantial performance gain. Unfortunately this does not * hold on Android runtimes and could make the copy slightly slower due to additional code in the * {@code Arrays.copyOfRange}. Thus we provide two different implementation for array copier for * Hotspot and Android runtimes. */ private interface ByteArrayCopier { /** Copies the specified range of the specified array into a new array */ byte[] copyFrom(byte[] bytes, int offset, int size); } /** Implementation of {@code ByteArrayCopier} which uses {@link System#arraycopy}. */ private static final class SystemByteArrayCopier implements ByteArrayCopier { @Override public byte[] copyFrom(byte[] bytes, int offset, int size) { byte[] copy = new byte[size]; System.arraycopy(bytes, offset, copy, 0, size); return copy; } } /** Implementation of {@code ByteArrayCopier} which uses {@link Arrays#copyOfRange}. */ private static final class ArraysByteArrayCopier implements ByteArrayCopier { @Override public byte[] copyFrom(byte[] bytes, int offset, int size) { return Arrays.copyOfRange(bytes, offset, offset + size); } } private static final ByteArrayCopier byteArrayCopier; static { byteArrayCopier = Android.isOnAndroidDevice() ? new SystemByteArrayCopier() : new ArraysByteArrayCopier(); } /** * Cached hash value. Intentionally accessed via a data race, which is safe because of the Java * Memory Model's "no out-of-thin-air values" guarantees for ints. A value of 0 implies that the * hash has not been set. */ private int hash = 0; // This constructor is here to prevent subclassing outside of this package, ByteString() {} /** * Gets the byte at the given index. This method should be used only for random access to * individual bytes. To access bytes sequentially, use the {@link ByteIterator} returned by {@link * #iterator()}, and call {@link #substring(int, int)} first if necessary. * * @param index index of byte * @return the value * @throws IndexOutOfBoundsException {@code index < 0 or index >= size} */ public abstract byte byteAt(int index); /** * Gets the byte at the given index, assumes bounds checking has already been performed. * * @param index index of byte * @return the value * @throws IndexOutOfBoundsException {@code index < 0 or index >= size} */ abstract byte internalByteAt(int index); /** * Return a {@link ByteString.ByteIterator} over the bytes in the ByteString. To avoid * auto-boxing, you may get the iterator manually and call {@link ByteIterator#nextByte()}. * * @return the iterator */ @Override public ByteIterator iterator() { return new AbstractByteIterator() { private int position = 0; private final int limit = size(); @Override public boolean hasNext() { return position < limit; } @Override public byte nextByte() { int currentPos = position; if (currentPos >= limit) { throw new NoSuchElementException(); } position = currentPos + 1; return internalByteAt(currentPos); } }; } /** * This interface extends {@code Iterator<Byte>}, so that we can return an unboxed {@code byte}. */ public interface ByteIterator extends Iterator<Byte> { /** * An alternative to {@link Iterator#next()} that returns an unboxed primitive {@code byte}. * * @return the next {@code byte} in the iteration * @throws NoSuchElementException if the iteration has no more elements */ byte nextByte(); } abstract static class AbstractByteIterator implements ByteIterator { @Override public final Byte next() { // Boxing calls Byte.valueOf(byte), which does not instantiate. return nextByte(); } @Override public final void remove() { throw new UnsupportedOperationException(); } } /** * Gets the number of bytes. * * @return size in bytes */ public abstract int size(); /** * Returns {@code true} if the size is {@code 0}, {@code false} otherwise. * * @return true if this is zero bytes long */ public final boolean isEmpty() { return size() == 0; } /** Returns an empty {@code ByteString} of size {@code 0}. */ public static final ByteString empty() { return EMPTY; } // ================================================================= // Comparison private static final int UNSIGNED_BYTE_MASK = 0xFF; /** * Returns the value of the given byte as an integer, interpreting the byte as an unsigned value. * That is, returns {@code value + 256} if {@code value} is negative; {@code value} itself * otherwise. * * <p>Note: This code was copied from {@link com.google.common.primitives.UnsignedBytes#toInt}, as * Guava libraries cannot be used in the {@code com.google.protobuf} package. */ private static int toInt(byte value) { return value & UNSIGNED_BYTE_MASK; } /** Returns the numeric value of the given character in hex, or -1 if invalid. */ private static int hexDigit(char c) { if (c >= '0' && c <= '9') { return c - '0'; } else if (c >= 'A' && c <= 'F') { return c - 'A' + 10; } else if (c >= 'a' && c <= 'f') { return c - 'a' + 10; } else { return -1; } } /** * Returns the numeric value of the given character at index in hexString. * * @throws NumberFormatException if the hexString character is invalid. */ private static int extractHexDigit(String hexString, int index) { int digit = hexDigit(hexString.charAt(index)); if (digit == -1) { throw new NumberFormatException( "Invalid hexString " + hexString + " must only contain [0-9a-fA-F] but contained " + hexString.charAt(index) + " at index " + index); } return digit; } /** * Compares two {@link ByteString}s lexicographically, treating their contents as unsigned byte * values between 0 and 255 (inclusive). * * <p>For example, {@code (byte) -1} is considered to be greater than {@code (byte) 1} because it * is interpreted as an unsigned value, {@code 255}. */ private static final Comparator<ByteString> UNSIGNED_LEXICOGRAPHICAL_COMPARATOR = new Comparator<ByteString>() { @Override public int compare(ByteString former, ByteString latter) { ByteIterator formerBytes = former.iterator(); ByteIterator latterBytes = latter.iterator(); while (formerBytes.hasNext() && latterBytes.hasNext()) { int result = Integer.valueOf(toInt(formerBytes.nextByte())) .compareTo(toInt(latterBytes.nextByte())); if (result != 0) { return result; } } return Integer.valueOf(former.size()).compareTo(Integer.valueOf(latter.size())); } }; /** * Returns a {@link Comparator} which compares {@link ByteString}-s lexicographically as sequences * of unsigned bytes (i.e. values between 0 and 255, inclusive). * * <p>For example, {@code (byte) -1} is considered to be greater than {@code (byte) 1} because it * is interpreted as an unsigned value, {@code 255}: * * <ul> * <li>{@code `-1` -> 0b11111111 (two's complement) -> 255} * <li>{@code `1` -> 0b00000001 -> 1} * </ul> */ public static Comparator<ByteString> unsignedLexicographicalComparator() { return UNSIGNED_LEXICOGRAPHICAL_COMPARATOR; } // ================================================================= // ByteString -> substring /** * Return the substring from {@code beginIndex}, inclusive, to the end of the string. * * @param beginIndex start at this index * @return substring sharing underlying data * @throws IndexOutOfBoundsException if {@code beginIndex < 0} or {@code beginIndex > size()}. */ public final ByteString substring(int beginIndex) { return substring(beginIndex, size()); } /** * Return the substring from {@code beginIndex}, inclusive, to {@code endIndex}, exclusive. * * @param beginIndex start at this index * @param endIndex the last character is the one before this index * @return substring sharing underlying data * @throws IndexOutOfBoundsException if {@code beginIndex < 0}, {@code endIndex > size()}, or * {@code beginIndex > endIndex}. */ public abstract ByteString substring(int beginIndex, int endIndex); /** * Tests if this bytestring starts with the specified prefix. Similar to {@link * String#startsWith(String)} * * @param prefix the prefix. * @return <code>true</code> if the byte sequence represented by the argument is a prefix of the * byte sequence represented by this string; <code>false</code> otherwise. */ public final boolean startsWith(ByteString prefix) { return size() >= prefix.size() && substring(0, prefix.size()).equals(prefix); } /** * Tests if this bytestring ends with the specified suffix. Similar to {@link * String#endsWith(String)} * * @param suffix the suffix. * @return <code>true</code> if the byte sequence represented by the argument is a suffix of the * byte sequence represented by this string; <code>false</code> otherwise. */ public final boolean endsWith(ByteString suffix) { return size() >= suffix.size() && substring(size() - suffix.size()).equals(suffix); } // ================================================================= // String -> ByteString /** * Returns a {@code ByteString} from a hexadecimal String. * * @param hexString String of hexadecimal digits to create {@code ByteString} from. * @throws NumberFormatException if the hexString does not contain a parsable hex String. */ public static ByteString fromHex(@CompileTimeConstant String hexString) { if (hexString.length() % 2 != 0) { throw new NumberFormatException( "Invalid hexString " + hexString + " of length " + hexString.length() + " must be even."); } byte[] bytes = new byte[hexString.length() / 2]; for (int i = 0; i < bytes.length; i++) { int d1 = extractHexDigit(hexString, 2 * i); int d2 = extractHexDigit(hexString, 2 * i + 1); bytes[i] = (byte) (d1 << 4 | d2); } return new LiteralByteString(bytes); } // ================================================================= // byte[] -> ByteString /** * Copies the given bytes into a {@code ByteString}. * * @param bytes source array * @param offset offset in source array * @param size number of bytes to copy * @return new {@code ByteString} * @throws IndexOutOfBoundsException if {@code offset} or {@code size} are out of bounds */ public static ByteString copyFrom(byte[] bytes, int offset, int size) { checkRange(offset, offset + size, bytes.length); return new LiteralByteString(byteArrayCopier.copyFrom(bytes, offset, size)); } /** * Copies the given bytes into a {@code ByteString}. * * @param bytes to copy * @return new {@code ByteString} */ public static ByteString copyFrom(byte[] bytes) { return copyFrom(bytes, 0, bytes.length); } /** * Wraps the given bytes into a {@code ByteString}. Intended for internal usage within the * library. */ static ByteString wrap(ByteBuffer buffer) { if (buffer.hasArray()) { final int offset = buffer.arrayOffset(); return ByteString.wrap(buffer.array(), offset + buffer.position(), buffer.remaining()); } else { return new NioByteString(buffer); } } // For use in tests static ByteString nioByteString(ByteBuffer buffer) { return new NioByteString(buffer); } /** * Wraps the given bytes into a {@code ByteString}. Intended for internal usage within the library * to force a classload of ByteString before LiteralByteString. */ static ByteString wrap(byte[] bytes) { // TODO: Return EMPTY when bytes are empty to reduce allocations? return new LiteralByteString(bytes); } /** * Wraps the given bytes into a {@code ByteString}. Intended for internal usage within the library * to force a classload of ByteString before BoundedByteString and LiteralByteString. */ static ByteString wrap(byte[] bytes, int offset, int length) { return new BoundedByteString(bytes, offset, length); } /** * Copies the next {@code size} bytes from a {@code java.nio.ByteBuffer} into a {@code * ByteString}. * * @param bytes source buffer * @param size number of bytes to copy * @return new {@code ByteString} * @throws IndexOutOfBoundsException if {@code size > bytes.remaining()} */ public static ByteString copyFrom(ByteBuffer bytes, int size) { checkRange(0, size, bytes.remaining()); byte[] copy = new byte[size]; bytes.get(copy); return new LiteralByteString(copy); } /** * Copies the remaining bytes from a {@code java.nio.ByteBuffer} into a {@code ByteString}. * * @param bytes sourceBuffer * @return new {@code ByteString} */ public static ByteString copyFrom(ByteBuffer bytes) { return copyFrom(bytes, bytes.remaining()); } /** * Encodes {@code text} into a sequence of bytes using the named charset and returns the result as * a {@code ByteString}. * * @param text source string * @param charsetName encoding to use * @return new {@code ByteString} * @throws UnsupportedEncodingException if the encoding isn't found */ public static ByteString copyFrom(String text, String charsetName) throws UnsupportedEncodingException { return new LiteralByteString(text.getBytes(charsetName)); } /** * Encodes {@code text} into a sequence of bytes using the named charset and returns the result as * a {@code ByteString}. * * @param text source string * @param charset encode using this charset * @return new {@code ByteString} */ public static ByteString copyFrom(String text, Charset charset) { return new LiteralByteString(text.getBytes(charset)); } /** * Encodes {@code text} into a sequence of UTF-8 bytes and returns the result as a {@code * ByteString}. * * @param text source string * @return new {@code ByteString} */ public static ByteString copyFromUtf8(String text) { return new LiteralByteString(text.getBytes(Internal.UTF_8)); } // ================================================================= // InputStream -> ByteString /** * Completely reads the given stream's bytes into a {@code ByteString}, blocking if necessary * until all bytes are read through to the end of the stream. * * <p><b>Performance notes:</b> The returned {@code ByteString} is an immutable tree of byte * arrays ("chunks") of the stream data. The first chunk is small, with subsequent chunks each * being double the size, up to 8K. * * <p>Each byte read from the input stream will be copied twice to ensure that the resulting * ByteString is truly immutable. * * @param streamToDrain The source stream, which is read completely but not closed. * @return A new {@code ByteString} which is made up of chunks of various sizes, depending on the * behavior of the underlying stream. * @throws IOException if there is a problem reading the underlying stream * @throws IllegalArgumentException if the stream supplies more than Integer.MAX_VALUE bytes */ public static ByteString readFrom(InputStream streamToDrain) throws IOException { return readFrom(streamToDrain, MIN_READ_FROM_CHUNK_SIZE, MAX_READ_FROM_CHUNK_SIZE); } /** * Completely reads the given stream's bytes into a {@code ByteString}, blocking if necessary * until all bytes are read through to the end of the stream. * * <p><b>Performance notes:</b> The returned {@code ByteString} is an immutable tree of byte * arrays ("chunks") of the stream data. The chunkSize parameter sets the size of these byte * arrays. * * <p>Each byte read from the input stream will be copied twice to ensure that the resulting * ByteString is truly immutable. * * @param streamToDrain The source stream, which is read completely but not closed. * @param chunkSize The size of the chunks in which to read the stream. * @return A new {@code ByteString} which is made up of chunks of the given size. * @throws IOException if there is a problem reading the underlying stream * @throws IllegalArgumentException if the stream supplies more than Integer.MAX_VALUE bytes */ public static ByteString readFrom(InputStream streamToDrain, int chunkSize) throws IOException { return readFrom(streamToDrain, chunkSize, chunkSize); } /** * Helper method that takes the chunk size range as a parameter. * * @param streamToDrain the source stream, which is read completely but not closed * @param minChunkSize the minimum size of the chunks in which to read the stream * @param maxChunkSize the maximum size of the chunks in which to read the stream * @return a new {@code ByteString} which is made up of chunks within the given size range * @throws IOException if there is a problem reading the underlying stream * @throws IllegalArgumentException if the stream supplies more than Integer.MAX_VALUE bytes */ public static ByteString readFrom(InputStream streamToDrain, int minChunkSize, int maxChunkSize) throws IOException { Collection<ByteString> results = new ArrayList<ByteString>(); // copy the inbound bytes into a list of chunks; the chunk size // grows exponentially to support both short and long streams. int chunkSize = minChunkSize; while (true) { ByteString chunk = readChunk(streamToDrain, chunkSize); if (chunk == null) { break; } results.add(chunk); chunkSize = Math.min(chunkSize * 2, maxChunkSize); } return ByteString.copyFrom(results); } /** * Blocks until a chunk of the given size can be made from the stream, or EOF is reached. Calls * read() repeatedly in case the given stream implementation doesn't completely fill the given * buffer in one read() call. * * @return A chunk of the desired size, or else a chunk as large as was available when end of * stream was reached. Returns null if the given stream had no more data in it. */ private static ByteString readChunk(InputStream in, final int chunkSize) throws IOException { final byte[] buf = new byte[chunkSize]; int bytesRead = 0; while (bytesRead < chunkSize) { final int count = in.read(buf, bytesRead, chunkSize - bytesRead); if (count == -1) { break; } bytesRead += count; } if (bytesRead == 0) { return null; } // Always make a copy since InputStream could steal a reference to buf. return ByteString.copyFrom(buf, 0, bytesRead); } // ================================================================= // Multiple ByteStrings -> One ByteString /** * Concatenate the given {@code ByteString} to this one. Short concatenations, of total size * smaller than {@link ByteString#CONCATENATE_BY_COPY_SIZE}, are produced by copying the * underlying bytes (as per Rope.java, <a * href="http://www.cs.ubc.ca/local/reading/proceedings/spe91-95/spe/vol25/issue12/spe986.pdf"> * BAP95 </a>. In general, the concatenate involves no copying. * * @param other string to concatenate * @return a new {@code ByteString} instance * @throws IllegalArgumentException if the combined size of the two byte strings exceeds * Integer.MAX_VALUE */ public final ByteString concat(ByteString other) { if (Integer.MAX_VALUE - size() < other.size()) { throw new IllegalArgumentException( "ByteString would be too long: " + size() + "+" + other.size()); } return RopeByteString.concatenate(this, other); } /** * Concatenates all byte strings in the iterable and returns the result. This is designed to run * in O(list size), not O(total bytes). * * <p>The returned {@code ByteString} is not necessarily a unique object. If the list is empty, * the returned object is the singleton empty {@code ByteString}. If the list has only one * element, that {@code ByteString} will be returned without copying. * * @param byteStrings strings to be concatenated * @return new {@code ByteString} * @throws IllegalArgumentException if the combined size of the byte strings exceeds * Integer.MAX_VALUE */ public static ByteString copyFrom(Iterable<ByteString> byteStrings) { // Determine the size; final int size; if (!(byteStrings instanceof Collection)) { int tempSize = 0; for (Iterator<ByteString> iter = byteStrings.iterator(); iter.hasNext(); iter.next(), ++tempSize) {} size = tempSize; } else { size = ((Collection<ByteString>) byteStrings).size(); } if (size == 0) { return EMPTY; } return balancedConcat(byteStrings.iterator(), size); } // Internal function used by copyFrom(Iterable<ByteString>). // Create a balanced concatenation of the next "length" elements from the // iterable. private static ByteString balancedConcat(Iterator<ByteString> iterator, int length) { if (length < 1) { throw new IllegalArgumentException(String.format("length (%s) must be >= 1", length)); } ByteString result; if (length == 1) { result = iterator.next(); } else { int halfLength = length >>> 1; ByteString left = balancedConcat(iterator, halfLength); ByteString right = balancedConcat(iterator, length - halfLength); result = left.concat(right); } return result; } // ================================================================= // ByteString -> byte[] /** * Copies bytes into a buffer at the given offset. * * <p>To copy a subset of bytes, you call this method on the return value of {@link * #substring(int, int)}. Example: {@code byteString.substring(start, end).copyTo(target, offset)} * * @param target buffer to copy into * @param offset in the target buffer * @throws IndexOutOfBoundsException if the offset is negative or too large */ public void copyTo(byte[] target, int offset) { copyTo(target, 0, offset, size()); } /** * Copies bytes into a buffer. * * @param target buffer to copy into * @param sourceOffset offset within these bytes * @param targetOffset offset within the target buffer * @param numberToCopy number of bytes to copy * @throws IndexOutOfBoundsException if an offset or size is negative or too large * @deprecated Instead, call {@code byteString.substring(sourceOffset, sourceOffset + * numberToCopy).copyTo(target, targetOffset)} */ @Deprecated public final void copyTo(byte[] target, int sourceOffset, int targetOffset, int numberToCopy) { checkRange(sourceOffset, sourceOffset + numberToCopy, size()); checkRange(targetOffset, targetOffset + numberToCopy, target.length); if (numberToCopy > 0) { copyToInternal(target, sourceOffset, targetOffset, numberToCopy); } } /** * Internal (package private) implementation of {@link #copyTo(byte[],int,int,int)}. It assumes * that all error checking has already been performed and that {@code numberToCopy > 0}. */ protected abstract void copyToInternal( byte[] target, int sourceOffset, int targetOffset, int numberToCopy); /** * Copies bytes into a ByteBuffer. * * <p>To copy a subset of bytes, you call this method on the return value of {@link * #substring(int, int)}. Example: {@code byteString.substring(start, end).copyTo(target)} * * @param target ByteBuffer to copy into. * @throws java.nio.ReadOnlyBufferException if the {@code target} is read-only * @throws java.nio.BufferOverflowException if the {@code target}'s remaining() space is not large * enough to hold the data. */ public abstract void copyTo(ByteBuffer target); /** * Copies bytes to a {@code byte[]}. * * @return copied bytes */ public final byte[] toByteArray() { final int size = size(); if (size == 0) { return Internal.EMPTY_BYTE_ARRAY; } byte[] result = new byte[size]; copyToInternal(result, 0, 0, size); return result; } /** * Writes a copy of the contents of this byte string to the specified output stream argument. * * @param out the output stream to which to write the data. * @throws IOException if an I/O error occurs. */ public abstract void writeTo(OutputStream out) throws IOException; /** * Writes a specified part of this byte string to an output stream. * * @param out the output stream to which to write the data. * @param sourceOffset offset within these bytes * @param numberToWrite number of bytes to write * @throws IOException if an I/O error occurs. * @throws IndexOutOfBoundsException if an offset or size is negative or too large */ final void writeTo(OutputStream out, int sourceOffset, int numberToWrite) throws IOException { checkRange(sourceOffset, sourceOffset + numberToWrite, size()); if (numberToWrite > 0) { writeToInternal(out, sourceOffset, numberToWrite); } } /** * Internal version of {@link #writeTo(OutputStream,int,int)} that assumes all error checking has * already been done. */ abstract void writeToInternal(OutputStream out, int sourceOffset, int numberToWrite) throws IOException; /** * Writes this {@link ByteString} to the provided {@link ByteOutput}. Calling this method may * result in multiple operations on the target {@link ByteOutput}. * * <p>This method may expose internal backing buffers of the {@link ByteString} to the {@link * ByteOutput} in order to avoid additional copying overhead. It would be possible for a malicious * {@link ByteOutput} to corrupt the {@link ByteString}. Use with caution! * * @param byteOutput the output target to receive the bytes * @throws IOException if an I/O error occurs * @see UnsafeByteOperations#unsafeWriteTo(ByteString, ByteOutput) */ abstract void writeTo(ByteOutput byteOutput) throws IOException; /** * This method behaves exactly the same as {@link #writeTo(ByteOutput)} unless the {@link * ByteString} is a rope. For ropes, the leaf nodes are written in reverse order to the {@code * byteOutput}. * * @param byteOutput the output target to receive the bytes * @throws IOException if an I/O error occurs * @see UnsafeByteOperations#unsafeWriteToReverse(ByteString, ByteOutput) */ abstract void writeToReverse(ByteOutput byteOutput) throws IOException; /** * Constructs a read-only {@code java.nio.ByteBuffer} whose content is equal to the contents of * this byte string. The result uses the same backing array as the byte string, if possible. * * @return wrapped bytes */ public abstract ByteBuffer asReadOnlyByteBuffer(); /** * Constructs a list of read-only {@code java.nio.ByteBuffer} objects such that the concatenation * of their contents is equal to the contents of this byte string. The result uses the same * backing arrays as the byte string. * * <p>By returning a list, implementations of this method may be able to avoid copying even when * there are multiple backing arrays. * * @return a list of wrapped bytes */ public abstract List<ByteBuffer> asReadOnlyByteBufferList(); /** * Constructs a new {@code String} by decoding the bytes using the specified charset. * * @param charsetName encode using this charset * @return new string * @throws UnsupportedEncodingException if charset isn't recognized */ public final String toString(String charsetName) throws UnsupportedEncodingException { try { return toString(Charset.forName(charsetName)); } catch (UnsupportedCharsetException e) { UnsupportedEncodingException exception = new UnsupportedEncodingException(charsetName); exception.initCause(e); throw exception; } } /** * Constructs a new {@code String} by decoding the bytes using the specified charset. Returns the * same empty String if empty. * * @param charset encode using this charset * @return new string */ public final String toString(Charset charset) { return size() == 0 ? "" : toStringInternal(charset); } /** * Constructs a new {@code String} by decoding the bytes using the specified charset. * * @param charset encode using this charset * @return new string */ protected abstract String toStringInternal(Charset charset); // ================================================================= // UTF-8 decoding /** * Constructs a new {@code String} by decoding the bytes as UTF-8. * * @return new string using UTF-8 encoding */ public final String toStringUtf8() { return toString(Internal.UTF_8); } /** * Tells whether this {@code ByteString} represents a well-formed UTF-8 byte sequence, such that * the original bytes can be converted to a String object and then round tripped back to bytes * without loss. * * <p>More precisely, returns {@code true} whenever: * * <pre>{@code * Arrays.equals(byteString.toByteArray(), * new String(byteString.toByteArray(), "UTF-8").getBytes("UTF-8")) * }</pre> * * <p>This method returns {@code false} for "overlong" byte sequences, as well as for 3-byte * sequences that would map to a surrogate character, in accordance with the restricted definition * of UTF-8 introduced in Unicode 3.1. Note that the UTF-8 decoder included in Oracle's JDK has * been modified to also reject "overlong" byte sequences, but (as of 2011) still accepts 3-byte * surrogate character byte sequences. * * <p>See the Unicode Standard,<br> * Table 3-6. <em>UTF-8 Bit Distribution</em>,<br> * Table 3-7. <em>Well Formed UTF-8 Byte Sequences</em>. * * @return whether the bytes in this {@code ByteString} are a well-formed UTF-8 byte sequence */ public abstract boolean isValidUtf8(); /** * Tells whether the given byte sequence is a well-formed, malformed, or incomplete UTF-8 byte * sequence. This method accepts and returns a partial state result, allowing the bytes for a * complete UTF-8 byte sequence to be composed from multiple {@code ByteString} segments. * * @param state either {@code 0} (if this is the initial decoding operation) or the value returned * from a call to a partial decoding method for the previous bytes * @param offset offset of the first byte to check * @param length number of bytes to check * @return {@code -1} if the partial byte sequence is definitely malformed, {@code 0} if it is * well-formed (no additional input needed), or, if the byte sequence is "incomplete", i.e. * apparently terminated in the middle of a character, an opaque integer "state" value * containing enough information to decode the character when passed to a subsequent * invocation of a partial decoding method. */ protected abstract int partialIsValidUtf8(int state, int offset, int length); // ================================================================= // equals() and hashCode() @Override public abstract boolean equals(Object o); /** Base class for leaf {@link ByteString}s (i.e. non-ropes). */ abstract static class LeafByteString extends ByteString { private static final long serialVersionUID = 1L; @Override protected final int getTreeDepth() { return 0; } @Override protected final boolean isBalanced() { return true; } @Override void writeToReverse(ByteOutput byteOutput) throws IOException { writeTo(byteOutput); } /** * Check equality of the substring of given length of this object starting at zero with another * {@code ByteString} substring starting at offset. * * @param other what to compare a substring in * @param offset offset into other * @param length number of bytes to compare * @return true for equality of substrings, else false. */ abstract boolean equalsRange(ByteString other, int offset, int length); private LeafByteString() {} } /** * Compute the hashCode using the traditional algorithm from {@link ByteString}. * * @return hashCode value */ @Override public final int hashCode() { int h = hash; if (h == 0) { int size = size(); h = partialHash(size, 0, size); if (h == 0) { h = 1; } hash = h; } return h; } // ================================================================= // Input stream /** * Creates an {@code InputStream} which can be used to read the bytes. * * <p>The {@link InputStream} returned by this method is guaranteed to be completely non-blocking. * The method {@link InputStream#available()} returns the number of bytes remaining in the stream. * The methods {@link InputStream#read(byte[])}, {@link InputStream#read(byte[],int,int)} and * {@link InputStream#skip(long)} will read/skip as many bytes as are available. The method {@link * InputStream#markSupported()} returns {@code true}. * * <p>The methods in the returned {@link InputStream} might <b>not</b> be thread safe. * * @return an input stream that returns the bytes of this byte string. */ public abstract InputStream newInput(); /** * Creates a {@link CodedInputStream} which can be used to read the bytes. Using this is often * more efficient than creating a {@link CodedInputStream} that wraps the result of {@link * #newInput()}. * * @return stream based on wrapped data */ public abstract CodedInputStream newCodedInput(); // ================================================================= // Output stream /** * Creates a new {@link Output} with the given initial capacity. Call {@link * Output#toByteString()} to create the {@code ByteString} instance. * * <p>A {@link ByteString.Output} offers the same functionality as a {@link * ByteArrayOutputStream}, except that it returns a {@link ByteString} rather than a {@code byte} * array. * * @param initialCapacity estimate of number of bytes to be written * @return {@code OutputStream} for building a {@code ByteString} */ public static Output newOutput(int initialCapacity) { return new Output(initialCapacity); } /** * Creates a new {@link Output}. Call {@link Output#toByteString()} to create the {@code * ByteString} instance. * * <p>A {@link ByteString.Output} offers the same functionality as a {@link * ByteArrayOutputStream}, except that it returns a {@link ByteString} rather than a {@code byte * array}. * * @return {@code OutputStream} for building a {@code ByteString} */ public static Output newOutput() { return new Output(CONCATENATE_BY_COPY_SIZE); } /** * Outputs to a {@code ByteString} instance. Call {@link #toByteString()} to create the {@code * ByteString} instance. */ public static final class Output extends OutputStream { // Implementation note. // The public methods of this class must be synchronized. ByteStrings // are guaranteed to be immutable. Without some sort of locking, it could // be possible for one thread to call toByteSring(), while another thread // is still modifying the underlying byte array. private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; // argument passed by user, indicating initial capacity. private final int initialCapacity; // ByteStrings to be concatenated to create the result private final ArrayList<ByteString> flushedBuffers; // Total number of bytes in the ByteStrings of flushedBuffers private int flushedBuffersTotalBytes; // Current buffer to which we are writing private byte[] buffer; // Location in buffer[] to which we write the next byte. private int bufferPos; /** * Creates a new ByteString output stream with the specified initial capacity. * * @param initialCapacity the initial capacity of the output stream. */ Output(int initialCapacity) { if (initialCapacity < 0) { throw new IllegalArgumentException("Buffer size < 0"); } this.initialCapacity = initialCapacity; this.flushedBuffers = new ArrayList<ByteString>(); this.buffer = new byte[initialCapacity]; } @Override public synchronized void write(int b) { if (bufferPos == buffer.length) { flushFullBuffer(1); } buffer[bufferPos++] = (byte) b; } @Override public synchronized void write(byte[] b, int offset, int length) { if (length <= buffer.length - bufferPos) { // The bytes can fit into the current buffer. System.arraycopy(b, offset, buffer, bufferPos, length); bufferPos += length; } else { // Use up the current buffer int copySize = buffer.length - bufferPos; System.arraycopy(b, offset, buffer, bufferPos, copySize); offset += copySize; length -= copySize; // Flush the buffer, and get a new buffer at least big enough to cover // what we still need to output flushFullBuffer(length); System.arraycopy(b, offset, buffer, /* count= */ 0, length); bufferPos = length; } } /** * Creates a byte string with the size and contents of this output stream. This does not create * a new copy of the underlying bytes. If the stream size grows dynamically, the runtime is * O(log n) in respect to the number of bytes written to the {@link Output}. If the stream size * stays within the initial capacity, the runtime is O(1). * * @return the current contents of this output stream, as a byte string. */ public synchronized ByteString toByteString() { flushLastBuffer(); return ByteString.copyFrom(flushedBuffers); } /** * Writes the complete contents of this byte array output stream to the specified output stream * argument. * * @param out the output stream to which to write the data. * @throws IOException if an I/O error occurs. */ public void writeTo(OutputStream out) throws IOException { ByteString[] cachedFlushBuffers; byte[] cachedBuffer; int cachedBufferPos; synchronized (this) { // Copy the information we need into local variables so as to hold // the lock for as short a time as possible. cachedFlushBuffers = flushedBuffers.toArray(new ByteString[0]); cachedBuffer = buffer; cachedBufferPos = bufferPos; } for (ByteString byteString : cachedFlushBuffers) { byteString.writeTo(out); } out.write(Arrays.copyOf(cachedBuffer, cachedBufferPos)); } /** * Returns the current size of the output stream. * * @return the current size of the output stream */ public synchronized int size() { return flushedBuffersTotalBytes + bufferPos; } /** * Resets this stream, so that all currently accumulated output in the output stream is * discarded. The output stream can be used again, reusing the already allocated buffer space. */ public synchronized void reset() { flushedBuffers.clear(); flushedBuffersTotalBytes = 0; bufferPos = 0; } @Override public String toString() { return String.format( "<ByteString.Output@%s size=%d>", Integer.toHexString(System.identityHashCode(this)), size()); } /** * Internal function used by writers. The current buffer is full, and the writer needs a new * buffer whose size is at least the specified minimum size. */ private void flushFullBuffer(int minSize) { flushedBuffers.add(new LiteralByteString(buffer)); flushedBuffersTotalBytes += buffer.length; // We want to increase our total capacity by 50%, but as a minimum, // the new buffer should also at least be >= minSize and // >= initial Capacity. int newSize = Math.max(initialCapacity, Math.max(minSize, flushedBuffersTotalBytes >>> 1)); buffer = new byte[newSize]; bufferPos = 0; } /** * Internal function used by {@link #toByteString()}. The current buffer may or may not be full, * but it needs to be flushed. */ private void flushLastBuffer() { if (bufferPos < buffer.length) { if (bufferPos > 0) { byte[] bufferCopy = Arrays.copyOf(buffer, bufferPos); flushedBuffers.add(new LiteralByteString(bufferCopy)); } // We reuse this buffer for further writes. } else { // Buffer is completely full. Huzzah. flushedBuffers.add(new LiteralByteString(buffer)); // 99% of the time, we're not going to use this OutputStream again. // We set buffer to an empty byte stream so that we're handling this // case without wasting space. In the rare case that more writes // *do* occur, this empty buffer will be flushed and an appropriately // sized new buffer will be created. buffer = EMPTY_BYTE_ARRAY; } flushedBuffersTotalBytes += bufferPos; bufferPos = 0; } } /** * Constructs a new {@code ByteString} builder, which allows you to efficiently construct a {@code * ByteString} by writing to a {@link CodedOutputStream}. Using this is much more efficient than * calling {@code newOutput()} and wrapping that in a {@code CodedOutputStream}. * * <p>This is package-private because it's a somewhat confusing interface. Users can call {@link * Message#toByteString()} instead of calling this directly. * * @param size The target byte size of the {@code ByteString}. You must write exactly this many * bytes before building the result. * @return the builder */ static CodedBuilder newCodedBuilder(int size) { return new CodedBuilder(size); } /** See {@link ByteString#newCodedBuilder(int)}. */ static final class CodedBuilder { private final CodedOutputStream output; private final byte[] buffer; private CodedBuilder(int size) { buffer = new byte[size]; output = CodedOutputStream.newInstance(buffer); } public ByteString build() { output.checkNoSpaceLeft(); // We can be confident that the CodedOutputStream will not modify the // underlying bytes anymore because it already wrote all of them. So, // no need to make a copy. return new LiteralByteString(buffer); } public CodedOutputStream getCodedOutput() { return output; } } // ================================================================= // Methods {@link RopeByteString} needs on instances, which aren't part of the // public API. /** * Return the depth of the tree representing this {@code ByteString}, if any, whose root is this * node. If this is a leaf node, return 0. * * @return tree depth or zero */ protected abstract int getTreeDepth(); /** * Return {@code true} if this ByteString is literal (a leaf node) or a flat-enough tree in the * sense of {@link RopeByteString}. * * @return true if the tree is flat enough */ protected abstract boolean isBalanced(); /** * Return the cached hash code if available. * * @return value of cached hash code or 0 if not computed yet */ protected final int peekCachedHashCode() { return hash; } /** * Compute the hash across the value bytes starting with the given hash, and return the result. * This is used to compute the hash across strings represented as a set of pieces by allowing the * hash computation to be continued from piece to piece. * * @param h starting hash value * @param offset offset into this value to start looking at data values * @param length number of data values to include in the hash computation * @return ending hash value */ protected abstract int partialHash(int h, int offset, int length); /** * Checks that the given index falls within the specified array size. * * @param index the index position to be tested * @param size the length of the array * @throws IndexOutOfBoundsException if the index does not fall within the array. */ static void checkIndex(int index, int size) { if ((index | (size - (index + 1))) < 0) { if (index < 0) { throw new ArrayIndexOutOfBoundsException("Index < 0: " + index); } throw new ArrayIndexOutOfBoundsException("Index > length: " + index + ", " + size); } } /** * Checks that the given range falls within the bounds of an array * * @param startIndex the start index of the range (inclusive) * @param endIndex the end index of the range (exclusive) * @param size the size of the array. * @return the length of the range. * @throws IndexOutOfBoundsException some or all of the range falls outside of the array. */ @CanIgnoreReturnValue static int checkRange(int startIndex, int endIndex, int size) { final int length = endIndex - startIndex; if ((startIndex | endIndex | length | (size - endIndex)) < 0) { if (startIndex < 0) { throw new IndexOutOfBoundsException("Beginning index: " + startIndex + " < 0"); } if (endIndex < startIndex) { throw new IndexOutOfBoundsException( "Beginning index larger than ending index: " + startIndex + ", " + endIndex); } // endIndex >= size throw new IndexOutOfBoundsException("End index: " + endIndex + " >= " + size); } return length; } @Override public final String toString() { return String.format( Locale.ROOT, "<ByteString@%s size=%d contents=\"%s\">", toHexString(identityHashCode(this)), size(), truncateAndEscapeForDisplay()); } private String truncateAndEscapeForDisplay() { final int limit = 50; return size() <= limit ? escapeBytes(this) : escapeBytes(substring(0, limit - 3)) + "..."; } /** * This class implements a {@link com.google.protobuf.ByteString} backed by a single array of * bytes, contiguous in memory. It supports substring by pointing to only a sub-range of the * underlying byte array, meaning that a substring will reference the full byte-array of the * string it's made from, exactly as with {@link String}. * * @author [email protected] (Carl Haverl) */ // Keep this class private to avoid deadlocks in classloading across threads as ByteString's // static initializer loads LiteralByteString and another thread loads LiteralByteString. private static class LiteralByteString extends ByteString.LeafByteString { private static final long serialVersionUID = 1L; protected final byte[] bytes; /** * Creates a {@code LiteralByteString} backed by the given array, without copying. * * @param bytes array to wrap */ LiteralByteString(byte[] bytes) { if (bytes == null) { throw new NullPointerException(); } this.bytes = bytes; } @Override public byte byteAt(int index) { // Unlike most methods in this class, this one is a direct implementation // ignoring the potential offset because we need to do range-checking in the // substring case anyway. return bytes[index]; } @Override byte internalByteAt(int index) { return bytes[index]; } @Override public int size() { return bytes.length; } // ================================================================= // ByteString -> substring @Override public final ByteString substring(int beginIndex, int endIndex) { final int length = checkRange(beginIndex, endIndex, size()); if (length == 0) { return ByteString.EMPTY; } return new BoundedByteString(bytes, getOffsetIntoBytes() + beginIndex, length); } // ================================================================= // ByteString -> byte[] @Override protected void copyToInternal( byte[] target, int sourceOffset, int targetOffset, int numberToCopy) { // Optimized form, not for subclasses, since we don't call // getOffsetIntoBytes() or check the 'numberToCopy' parameter. // TODO: Is not calling getOffsetIntoBytes really saving that much? System.arraycopy(bytes, sourceOffset, target, targetOffset, numberToCopy); } @Override public final void copyTo(ByteBuffer target) { target.put(bytes, getOffsetIntoBytes(), size()); // Copies bytes } @Override public final ByteBuffer asReadOnlyByteBuffer() { return ByteBuffer.wrap(bytes, getOffsetIntoBytes(), size()).asReadOnlyBuffer(); } @Override public final List<ByteBuffer> asReadOnlyByteBufferList() { return Collections.singletonList(asReadOnlyByteBuffer()); } @Override public final void writeTo(OutputStream outputStream) throws IOException { outputStream.write(toByteArray()); } @Override final void writeToInternal(OutputStream outputStream, int sourceOffset, int numberToWrite) throws IOException { outputStream.write(bytes, getOffsetIntoBytes() + sourceOffset, numberToWrite); } @Override final void writeTo(ByteOutput output) throws IOException { output.writeLazy(bytes, getOffsetIntoBytes(), size()); } @Override protected final String toStringInternal(Charset charset) { return new String(bytes, getOffsetIntoBytes(), size(), charset); } // ================================================================= // UTF-8 decoding @Override public final boolean isValidUtf8() { int offset = getOffsetIntoBytes(); return Utf8.isValidUtf8(bytes, offset, offset + size()); } @Override protected final int partialIsValidUtf8(int state, int offset, int length) { int index = getOffsetIntoBytes() + offset; return Utf8.partialIsValidUtf8(state, bytes, index, index + length); } // ================================================================= // equals() and hashCode() @Override public final boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof ByteString)) { return false; } if (size() != ((ByteString) other).size()) { return false; } if (size() == 0) { return true; } if (other instanceof LiteralByteString) { LiteralByteString otherAsLiteral = (LiteralByteString) other; // If we know the hash codes and they are not equal, we know the byte // strings are not equal. int thisHash = peekCachedHashCode(); int thatHash = otherAsLiteral.peekCachedHashCode(); if (thisHash != 0 && thatHash != 0 && thisHash != thatHash) { return false; } return equalsRange((LiteralByteString) other, 0, size()); } else { // RopeByteString and NioByteString. return other.equals(this); } } /** * Check equality of the substring of given length of this object starting at zero with another * {@code LiteralByteString} substring starting at offset. * * @param other what to compare a substring in * @param offset offset into other * @param length number of bytes to compare * @return true for equality of substrings, else false. */ @Override final boolean equalsRange(ByteString other, int offset, int length) { if (length > other.size()) { throw new IllegalArgumentException("Length too large: " + length + size()); } if (offset + length > other.size()) { throw new IllegalArgumentException( "Ran off end of other: " + offset + ", " + length + ", " + other.size()); } if (other instanceof LiteralByteString) { LiteralByteString lbsOther = (LiteralByteString) other; byte[] thisBytes = bytes; byte[] otherBytes = lbsOther.bytes; int thisLimit = getOffsetIntoBytes() + length; for (int thisIndex = getOffsetIntoBytes(), otherIndex = lbsOther.getOffsetIntoBytes() + offset; (thisIndex < thisLimit); ++thisIndex, ++otherIndex) { if (thisBytes[thisIndex] != otherBytes[otherIndex]) { return false; } } return true; } return other.substring(offset, offset + length).equals(substring(0, length)); } @Override protected final int partialHash(int h, int offset, int length) { return Internal.partialHash(h, bytes, getOffsetIntoBytes() + offset, length); } // ================================================================= // Input stream @Override public final InputStream newInput() { return new ByteArrayInputStream(bytes, getOffsetIntoBytes(), size()); // No copy } @Override public final CodedInputStream newCodedInput() { // We trust CodedInputStream not to modify the bytes, or to give anyone // else access to them. return CodedInputStream.newInstance( bytes, getOffsetIntoBytes(), size(), /* bufferIsImmutable= */ true); } // ================================================================= // Internal methods /** * Offset into {@code bytes[]} to use, non-zero for substrings. * * @return always 0 for this class */ protected int getOffsetIntoBytes() { return 0; } } /** * This class is used to represent the substring of a {@link ByteString} over a single byte array. * In terms of the public API of {@link ByteString}, you end up here by calling {@link * ByteString#copyFrom(byte[])} followed by {@link ByteString#substring(int, int)}. * * <p>This class contains most of the overhead involved in creating a substring from a {@link * LiteralByteString}. The overhead involves some range-checking and two extra fields. * * @author [email protected] (Carl Haverl) */ // Keep this class private to avoid deadlocks in classloading across threads as ByteString's // static initializer loads LiteralByteString and another thread loads BoundedByteString. private static final class BoundedByteString extends LiteralByteString { private final int bytesOffset; private final int bytesLength; /** * Creates a {@code BoundedByteString} backed by the sub-range of given array, without copying. * * @param bytes array to wrap * @param offset index to first byte to use in bytes * @param length number of bytes to use from bytes * @throws IllegalArgumentException if {@code offset < 0}, {@code length < 0}, or if {@code * offset + length > bytes.length}. */ BoundedByteString(byte[] bytes, int offset, int length) { super(bytes); checkRange(offset, offset + length, bytes.length); this.bytesOffset = offset; this.bytesLength = length; } /** * Gets the byte at the given index. Throws {@link ArrayIndexOutOfBoundsException} for * backwards-compatibility reasons although it would more properly be {@link * IndexOutOfBoundsException}. * * @param index index of byte * @return the value * @throws ArrayIndexOutOfBoundsException {@code index} is < 0 or >= size */ @Override public byte byteAt(int index) { // We must check the index ourselves as we cannot rely on Java array index // checking for substrings. checkIndex(index, size()); return bytes[bytesOffset + index]; } @Override byte internalByteAt(int index) { return bytes[bytesOffset + index]; } @Override public int size() { return bytesLength; } @Override protected int getOffsetIntoBytes() { return bytesOffset; } // ================================================================= // ByteString -> byte[] @Override protected void copyToInternal( byte[] target, int sourceOffset, int targetOffset, int numberToCopy) { System.arraycopy( bytes, getOffsetIntoBytes() + sourceOffset, target, targetOffset, numberToCopy); } // ================================================================= // Serializable private static final long serialVersionUID = 1L; Object writeReplace() { return ByteString.wrap(toByteArray()); } private void readObject(@SuppressWarnings("unused") ObjectInputStream in) throws IOException { throw new InvalidObjectException( "BoundedByteStream instances are not to be serialized directly"); } } /** A {@link ByteString} that wraps around a {@link ByteBuffer}. */ // Keep this class private to avoid deadlocks in classloading across threads as ByteString's // static initializer loads LiteralByteString and another thread loads BoundedByteString. private static final class NioByteString extends ByteString.LeafByteString { private final ByteBuffer buffer; NioByteString(ByteBuffer buffer) { checkNotNull(buffer, "buffer"); // Use native byte order for fast fixed32/64 operations. this.buffer = buffer.slice().order(ByteOrder.nativeOrder()); } // ================================================================= // Serializable /** Magic method that lets us override serialization behavior. */ private Object writeReplace() { return ByteString.copyFrom(buffer.slice()); } /** Magic method that lets us override deserialization behavior. */ private void readObject(@SuppressWarnings("unused") ObjectInputStream in) throws IOException { throw new InvalidObjectException("NioByteString instances are not to be serialized directly"); } // ================================================================= @Override public byte byteAt(int index) { try { return buffer.get(index); } catch (ArrayIndexOutOfBoundsException e) { throw e; } catch (IndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException(e.getMessage()); } } @Override public byte internalByteAt(int index) { // it isn't possible to avoid the bounds checking inside of ByteBuffer, so just use the // default // implementation. return byteAt(index); } @Override public int size() { return buffer.remaining(); } @Override public ByteString substring(int beginIndex, int endIndex) { try { ByteBuffer slice = slice(beginIndex, endIndex); return new NioByteString(slice); } catch (ArrayIndexOutOfBoundsException e) { throw e; } catch (IndexOutOfBoundsException e) { throw new ArrayIndexOutOfBoundsException(e.getMessage()); } } @Override protected void copyToInternal( byte[] target, int sourceOffset, int targetOffset, int numberToCopy) { ByteBuffer slice = buffer.slice(); Java8Compatibility.position(slice, sourceOffset); slice.get(target, targetOffset, numberToCopy); } @Override public void copyTo(ByteBuffer target) { target.put(buffer.slice()); } @Override public void writeTo(OutputStream out) throws IOException { out.write(toByteArray()); } @Override boolean equalsRange(ByteString other, int offset, int length) { return substring(0, length).equals(other.substring(offset, offset + length)); } @Override void writeToInternal(OutputStream out, int sourceOffset, int numberToWrite) throws IOException { if (buffer.hasArray()) { // Optimized write for array-backed buffers. // Note that we're taking the risk that a malicious OutputStream could modify the array. int bufferOffset = buffer.arrayOffset() + buffer.position() + sourceOffset; out.write(buffer.array(), bufferOffset, numberToWrite); return; } ByteBufferWriter.write(slice(sourceOffset, sourceOffset + numberToWrite), out); } @Override void writeTo(ByteOutput output) throws IOException { output.writeLazy(buffer.slice()); } @Override public ByteBuffer asReadOnlyByteBuffer() { return buffer.asReadOnlyBuffer(); } @Override public List<ByteBuffer> asReadOnlyByteBufferList() { return Collections.singletonList(asReadOnlyByteBuffer()); } @Override protected String toStringInternal(Charset charset) { final byte[] bytes; final int offset; final int length; if (buffer.hasArray()) { bytes = buffer.array(); offset = buffer.arrayOffset() + buffer.position(); length = buffer.remaining(); } else { // TODO: Can we optimize this? bytes = toByteArray(); offset = 0; length = bytes.length; } return new String(bytes, offset, length, charset); } @Override public boolean isValidUtf8() { return Utf8.isValidUtf8(buffer); } @Override protected int partialIsValidUtf8(int state, int offset, int length) { return Utf8.partialIsValidUtf8(state, buffer, offset, offset + length); } @Override public boolean equals(Object other) { if (other == this) { return true; } if (!(other instanceof ByteString)) { return false; } ByteString otherString = ((ByteString) other); if (size() != otherString.size()) { return false; } if (size() == 0) { return true; } if (other instanceof NioByteString) { return buffer.equals(((NioByteString) other).buffer); } if (other instanceof RopeByteString) { return other.equals(this); } return buffer.equals(otherString.asReadOnlyByteBuffer()); } @Override protected int partialHash(int h, int offset, int length) { for (int i = offset; i < offset + length; i++) { h = h * 31 + buffer.get(i); } return h; } @Override public InputStream newInput() { return new InputStream() { private final ByteBuffer buf = buffer.slice(); @Override public void mark(int readlimit) { Java8Compatibility.mark(buf); } @Override public boolean markSupported() { return true; } @Override public void reset() throws IOException { try { Java8Compatibility.reset(buf); } catch (InvalidMarkException e) { throw new IOException(e); } } @Override public int available() throws IOException { return buf.remaining(); } @Override public int read() throws IOException { if (!buf.hasRemaining()) { return -1; } return buf.get() & 0xFF; } @Override public int read(byte[] bytes, int off, int len) throws IOException { if (!buf.hasRemaining()) { return -1; } len = Math.min(len, buf.remaining()); buf.get(bytes, off, len); return len; } }; } @Override public CodedInputStream newCodedInput() { return CodedInputStream.newInstance(buffer, true); } /** * Creates a slice of a range of this buffer. * * @param beginIndex the beginning index of the slice (inclusive). * @param endIndex the end index of the slice (exclusive). * @return the requested slice. */ private ByteBuffer slice(int beginIndex, int endIndex) { if (beginIndex < buffer.position() || endIndex > buffer.limit() || beginIndex > endIndex) { throw new IllegalArgumentException( String.format("Invalid indices [%d, %d]", beginIndex, endIndex)); } ByteBuffer slice = buffer.slice(); Java8Compatibility.position(slice, beginIndex - buffer.position()); Java8Compatibility.limit(slice, endIndex - buffer.position()); return slice; } } }
protocolbuffers/protobuf
java/core/src/main/java/com/google/protobuf/ByteString.java
253
/* * 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.Strings.lenientFormat; import com.google.common.annotations.GwtCompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Static convenience methods that help a method or constructor check whether it was invoked * correctly (that is, whether its <i>preconditions</i> were met). * * <p>If the precondition is not met, the {@code Preconditions} method throws an unchecked exception * of a specified type, which helps the method in which the exception was thrown communicate that * its caller has made a mistake. This allows constructs such as * * <pre>{@code * public static double sqrt(double value) { * if (value < 0) { * throw new IllegalArgumentException("input is negative: " + value); * } * // calculate square root * } * }</pre> * * <p>to be replaced with the more compact * * <pre>{@code * public static double sqrt(double value) { * checkArgument(value >= 0, "input is negative: %s", value); * // calculate square root * } * }</pre> * * <p>so that a hypothetical bad caller of this method, such as: * * <pre>{@code * void exampleBadCaller() { * double d = sqrt(-1.0); * } * }</pre> * * <p>would be flagged as having called {@code sqrt()} with an illegal argument. * * <h3>Performance</h3> * * <p>Avoid passing message arguments that are expensive to compute; your code will always compute * them, even though they usually won't be needed. If you have such arguments, use the conventional * if/throw idiom instead. * * <p>Depending on your message arguments, memory may be allocated for boxing and varargs array * creation. However, the methods of this class have a large number of overloads that prevent such * allocations in many common cases. * * <p>The message string is not formatted unless the exception will be thrown, so the cost of the * string formatting itself should not be a concern. * * <p>As with any performance concerns, you should consider profiling your code (in a production * environment if possible) before spending a lot of effort on tweaking a particular element. * * <h3>Other types of preconditions</h3> * * <p>Not every type of precondition failure is supported by these methods. Continue to throw * standard JDK exceptions such as {@link java.util.NoSuchElementException} or {@link * UnsupportedOperationException} in the situations they are intended for. * * <h3>Non-preconditions</h3> * * <p>It is of course possible to use the methods of this class to check for invalid conditions * which are <i>not the caller's fault</i>. Doing so is <b>not recommended</b> because it is * misleading to future readers of the code and of stack traces. See <a * href="https://github.com/google/guava/wiki/ConditionalFailuresExplained">Conditional failures * explained</a> in the Guava User Guide for more advice. Notably, {@link Verify} offers assertions * similar to those in this class for non-precondition checks. * * <h3>{@code java.util.Objects.requireNonNull()}</h3> * * <p>Projects which use {@code com.google.common} should generally avoid the use of {@link * java.util.Objects#requireNonNull(Object)}. Instead, use whichever of {@link * #checkNotNull(Object)} or {@link Verify#verifyNotNull(Object)} is appropriate to the situation. * (The same goes for the message-accepting overloads.) * * <h3>Only {@code %s} is supported</h3> * * <p>{@code Preconditions} uses {@link Strings#lenientFormat} to format error message template * strings. This only supports the {@code "%s"} specifier, not the full range of {@link * java.util.Formatter} specifiers. However, note that if the number of arguments does not match the * number of occurrences of {@code "%s"} in the format string, {@code Preconditions} will still * behave as expected, and will still include all argument values in the error message; the message * will simply not be formatted exactly as intended. * * <h3>More information</h3> * * <p>See the Guava User Guide on <a * href="https://github.com/google/guava/wiki/PreconditionsExplained">using {@code * Preconditions}</a>. * * @author Kevin Bourrillion * @since 2.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class Preconditions { private Preconditions() {} private interface Impossible {} /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression) { if (!expression) { throw new IllegalArgumentException(); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument(boolean expression, @CheckForNull Object errorMessage) { if (!expression) { throw new IllegalArgumentException(String.valueOf(errorMessage)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in * square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @throws IllegalArgumentException if {@code expression} is false */ public static void checkArgument( boolean expression, String errorMessageTemplate, @CheckForNull @Nullable Object... errorMessageArgs) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, errorMessageArgs)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument(boolean expression, String errorMessageTemplate, char p1) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument(boolean expression, String errorMessageTemplate, int p1) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument(boolean expression, String errorMessageTemplate, long p1) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, @CheckForNull Object p1) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, char p1, char p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, char p1, int p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, char p1, long p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, char p1, @CheckForNull Object p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, int p1, char p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, int p1, int p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, int p1, long p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, int p1, @CheckForNull Object p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, long p1, char p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, long p1, int p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, long p1, long p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, long p1, @CheckForNull Object p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, char p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, int p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, long p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, // TODO: cl/604933487 - Make errorMessageTemplate consistently @CheckForNull across overloads. @CheckForNull String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2, @CheckForNull Object p3) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2, p3)); } } /** * Ensures the truth of an expression involving one or more parameters to the calling method. * * <p>See {@link #checkArgument(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkArgument( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2, @CheckForNull Object p3, @CheckForNull Object p4) { if (!expression) { throw new IllegalArgumentException(lenientFormat(errorMessageTemplate, p1, p2, p3, p4)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @throws IllegalStateException if {@code expression} is false * @see Verify#verify Verify.verify() */ public static void checkState(boolean expression) { if (!expression) { throw new IllegalStateException(); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @throws IllegalStateException if {@code expression} is false * @see Verify#verify Verify.verify() */ public static void checkState(boolean expression, @CheckForNull Object errorMessage) { if (!expression) { throw new IllegalStateException(String.valueOf(errorMessage)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * @param expression a boolean expression * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in * square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @throws IllegalStateException if {@code expression} is false * @see Verify#verify Verify.verify() */ public static void checkState( boolean expression, /* * TODO(cpovirk): Consider removing @CheckForNull here, as we've done with the other methods' * errorMessageTemplate parameters: It is unlikely that callers intend for their string * template to be null (though we do handle that case gracefully at runtime). I've left this * one as it is because one of our users has defined a wrapper API around Preconditions, * declaring a checkState method that accepts a possibly null template. So we'd need to update * that user first. */ @CheckForNull String errorMessageTemplate, @CheckForNull @Nullable Object... errorMessageArgs) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, errorMessageArgs)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState(boolean expression, String errorMessageTemplate, char p1) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState(boolean expression, String errorMessageTemplate, int p1) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState(boolean expression, String errorMessageTemplate, long p1) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState( boolean expression, String errorMessageTemplate, @CheckForNull Object p1) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState(boolean expression, String errorMessageTemplate, char p1, char p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState(boolean expression, String errorMessageTemplate, char p1, int p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState(boolean expression, String errorMessageTemplate, char p1, long p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState( boolean expression, String errorMessageTemplate, char p1, @CheckForNull Object p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState(boolean expression, String errorMessageTemplate, int p1, char p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState(boolean expression, String errorMessageTemplate, int p1, int p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState(boolean expression, String errorMessageTemplate, int p1, long p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState( boolean expression, String errorMessageTemplate, int p1, @CheckForNull Object p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState(boolean expression, String errorMessageTemplate, long p1, char p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState(boolean expression, String errorMessageTemplate, long p1, int p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState(boolean expression, String errorMessageTemplate, long p1, long p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState( boolean expression, String errorMessageTemplate, long p1, @CheckForNull Object p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, char p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, int p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, long p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2, @CheckForNull Object p3) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2, p3)); } } /** * Ensures the truth of an expression involving the state of the calling instance, but not * involving any parameters to the calling method. * * <p>See {@link #checkState(boolean, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ public static void checkState( boolean expression, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2, @CheckForNull Object p3, @CheckForNull Object p4) { if (!expression) { throw new IllegalStateException(lenientFormat(errorMessageTemplate, p1, p2, p3, p4)); } } /* * Preconditions.checkNotNull is *intended* for performing eager null checks on parameters that a * nullness checker can already "prove" are non-null. That means that the first parameter to * checkNotNull *should* be annotated to require it to be non-null. * * However, for a variety of reasons, Google developers have written a ton of code over the past * decade that assumes that they can use checkNotNull for non-precondition checks. I had hoped to * take a principled stand on this, but the amount of such code is simply overwhelming. To avoid * creating a lot of compile errors that users would not find to be informative, we're giving in * and allowing callers to pass arguments that a nullness checker believes could be null. * * We still encourage people to use requireNonNull over checkNotNull for non-precondition checks. */ /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null * @see Verify#verifyNotNull Verify.verifyNotNull() */ @CanIgnoreReturnValue public static <T> T checkNotNull(@CheckForNull T reference) { if (reference == null) { throw new NullPointerException(); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @param errorMessage the exception message to use if the check fails; will be converted to a * string using {@link String#valueOf(Object)} * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null * @see Verify#verifyNotNull Verify.verifyNotNull() */ @CanIgnoreReturnValue public static <T> T checkNotNull(@CheckForNull T reference, @CheckForNull Object errorMessage) { if (reference == null) { throw new NullPointerException(String.valueOf(errorMessage)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * @param reference an object reference * @param errorMessageTemplate a template for the exception message should the check fail. The * message is formed by replacing each {@code %s} placeholder in the template with an * argument. These are matched by position - the first {@code %s} gets {@code * errorMessageArgs[0]}, etc. Unmatched arguments will be appended to the formatted message in * square braces. Unmatched placeholders will be left as-is. * @param errorMessageArgs the arguments to be substituted into the message template. Arguments * are converted to strings using {@link String#valueOf(Object)}. * @return the non-null reference that was validated * @throws NullPointerException if {@code reference} is null * @see Verify#verifyNotNull Verify.verifyNotNull() */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, @CheckForNull @Nullable Object... errorMessageArgs) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, errorMessageArgs)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, char p1) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull(@CheckForNull T reference, String errorMessageTemplate, int p1) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, long p1) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, char p1, char p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, char p1, int p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, char p1, long p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, char p1, @CheckForNull Object p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, int p1, char p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, int p1, int p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, int p1, long p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, int p1, @CheckForNull Object p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, long p1, char p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, long p1, int p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, long p1, long p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, long p1, @CheckForNull Object p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1, char p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1, int p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1, long p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2, @CheckForNull Object p3) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2, p3)); } return reference; } /** * Ensures that an object reference passed as a parameter to the calling method is not null. * * <p>See {@link #checkNotNull(Object, String, Object...)} for details. * * @since 20.0 (varargs overload since 2.0) */ @CanIgnoreReturnValue public static <T> T checkNotNull( @CheckForNull T reference, String errorMessageTemplate, @CheckForNull Object p1, @CheckForNull Object p2, @CheckForNull Object p3, @CheckForNull Object p4) { if (reference == null) { throw new NullPointerException(lenientFormat(errorMessageTemplate, p1, p2, p3, p4)); } return reference; } /* * All recent hotspots (as of 2009) *really* like to have the natural code * * if (guardExpression) { * throw new BadException(messageExpression); * } * * refactored so that messageExpression is moved to a separate String-returning method. * * if (guardExpression) { * throw new BadException(badMsg(...)); * } * * The alternative natural refactorings into void or Exception-returning methods are much slower. * This is a big deal - we're talking factors of 2-8 in microbenchmarks, not just 10-20%. (This is * a hotspot optimizer bug, which should be fixed, but that's a separate, big project). * * The coding pattern above is heavily used in java.util, e.g. in ArrayList. There is a * RangeCheckMicroBenchmark in the JDK that was used to test this. * * But the methods in this class want to throw different exceptions, depending on the args, so it * appears that this pattern is not directly applicable. But we can use the ridiculous, devious * trick of throwing an exception in the middle of the construction of another exception. Hotspot * is fine with that. */ /** * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive. * * @param index a user-supplied index identifying an element of an array, list or string * @param size the size of that array, list or string * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ @CanIgnoreReturnValue public static int checkElementIndex(int index, int size) { return checkElementIndex(index, size, "index"); } /** * Ensures that {@code index} specifies a valid <i>element</i> in an array, list or string of size * {@code size}. An element index may range from zero, inclusive, to {@code size}, exclusive. * * @param index a user-supplied index identifying an element of an array, list or string * @param size the size of that array, list or string * @param desc the text to use to describe this index in an error message * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is not less than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ @CanIgnoreReturnValue public static int checkElementIndex(int index, int size, String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index >= size) { throw new IndexOutOfBoundsException(badElementIndex(index, size, desc)); } return index; } private static String badElementIndex(int index, int size, String desc) { if (index < 0) { return lenientFormat("%s (%s) must not be negative", desc, index); } else if (size < 0) { throw new IllegalArgumentException("negative size: " + size); } else { // index >= size return lenientFormat("%s (%s) must be less than size (%s)", desc, index, size); } } /** * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of * size {@code size}. A position index may range from zero to {@code size}, inclusive. * * @param index a user-supplied index identifying a position in an array, list or string * @param size the size of that array, list or string * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ @CanIgnoreReturnValue public static int checkPositionIndex(int index, int size) { return checkPositionIndex(index, size, "index"); } /** * Ensures that {@code index} specifies a valid <i>position</i> in an array, list or string of * size {@code size}. A position index may range from zero to {@code size}, inclusive. * * @param index a user-supplied index identifying a position in an array, list or string * @param size the size of that array, list or string * @param desc the text to use to describe this index in an error message * @return the value of {@code index} * @throws IndexOutOfBoundsException if {@code index} is negative or is greater than {@code size} * @throws IllegalArgumentException if {@code size} is negative */ @CanIgnoreReturnValue public static int checkPositionIndex(int index, int size, String desc) { // Carefully optimized for execution by hotspot (explanatory comment above) if (index < 0 || index > size) { throw new IndexOutOfBoundsException(badPositionIndex(index, size, desc)); } return index; } private static String badPositionIndex(int index, int size, String desc) { if (index < 0) { return lenientFormat("%s (%s) must not be negative", desc, index); } else if (size < 0) { throw new IllegalArgumentException("negative size: " + size); } else { // index > size return lenientFormat("%s (%s) must not be greater than size (%s)", desc, index, size); } } /** * Ensures that {@code start} and {@code end} specify valid <i>positions</i> in an array, list or * string of size {@code size}, and are in order. A position index may range from zero to {@code * size}, inclusive. * * @param start a user-supplied index identifying a starting position in an array, list or string * @param end a user-supplied index identifying an ending position in an array, list or string * @param size the size of that array, list or string * @throws IndexOutOfBoundsException if either index is negative or is greater than {@code size}, * or if {@code end} is less than {@code start} * @throws IllegalArgumentException if {@code size} is negative */ public static void checkPositionIndexes(int start, int end, int size) { // Carefully optimized for execution by hotspot (explanatory comment above) if (start < 0 || end < start || end > size) { throw new IndexOutOfBoundsException(badPositionIndexes(start, end, size)); } } private static String badPositionIndexes(int start, int end, int size) { if (start < 0 || start > size) { return badPositionIndex(start, size, "start index"); } if (end < 0 || end > size) { return badPositionIndex(end, size, "end index"); } // end < start return lenientFormat("end index (%s) must not be less than start index (%s)", end, start); } }
google/guava
android/guava/src/com/google/common/base/Preconditions.java
254
/* * 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.Float.NEGATIVE_INFINITY; import static java.lang.Float.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 javax.annotation.CheckForNull; /** * Static utility methods pertaining to {@code float} primitives, that are not already found in * either {@link Float} or {@link Arrays}. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/PrimitivesExplained">primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) @ElementTypesAreNonnullByDefault public final class Floats extends FloatsMethodsForWeb { private Floats() {} /** * The number of bytes required to represent a primitive {@code float} value. * * <p><b>Java 8+ users:</b> use {@link Float#BYTES} instead. * * @since 10.0 */ public static final int BYTES = Float.SIZE / Byte.SIZE; /** * Returns a hash code for {@code value}; equal to the result of invoking {@code ((Float) * value).hashCode()}. * * <p><b>Java 8+ users:</b> use {@link Float#hashCode(float)} instead. * * @param value a primitive {@code float} value * @return a hash code for the value */ public static int hashCode(float value) { // TODO(kevinb): is there a better way, that's still gwt-safe? return ((Float) value).hashCode(); } /** * Compares the two specified {@code float} values using {@link Float#compare(float, float)}. You * may prefer to invoke that method directly; this method exists only for consistency with the * other utilities in this package. * * <p><b>Note:</b> this method simply delegates to the JDK method {@link Float#compare}. It is * provided for consistency with the other primitive types, whose compare methods were not added * to the JDK until JDK 7. * * @param a the first {@code float} to compare * @param b the second {@code float} to compare * @return the result of invoking {@link Float#compare(float, float)} */ public static int compare(float a, float b) { return Float.compare(a, b); } /** * Returns {@code true} if {@code value} represents a real number. This is equivalent to, but not * necessarily implemented as, {@code !(Float.isInfinite(value) || Float.isNaN(value))}. * * <p><b>Java 8+ users:</b> use {@link Float#isFinite(float)} instead. * * @since 10.0 */ public static boolean isFinite(float value) { return NEGATIVE_INFINITY < value && value < POSITIVE_INFINITY; } /** * Returns {@code true} if {@code target} is present as an element anywhere in {@code array}. Note * that this always returns {@code false} when {@code target} is {@code NaN}. * * @param array an array of {@code float} values, possibly empty * @param target a primitive {@code float} value * @return {@code true} if {@code array[i] == target} for some value of {@code i} */ public static boolean contains(float[] array, float target) { for (float value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in {@code array}. Note * that this always returns {@code -1} when {@code target} is {@code NaN}. * * @param array an array of {@code float} values, possibly empty * @param target a primitive {@code float} value * @return the least index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int indexOf(float[] array, float target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf(float[] array, float target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code target} within * {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code Arrays.copyOfRange(array, * i, i + target.length)} contains exactly the same elements as {@code target}. * * <p>Note that this always returns {@code -1} when {@code target} contains {@code NaN}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(float[] array, float[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in {@code array}. Note * that this always returns {@code -1} when {@code target} is {@code NaN}. * * @param array an array of {@code float} values, possibly empty * @param target a primitive {@code float} value * @return the greatest index {@code i} for which {@code array[i] == target}, or {@code -1} if no * such index exists. */ public static int lastIndexOf(float[] array, float target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf(float[] array, float target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}, using the same rules of comparison as {@link * Math#min(float, float)}. * * @param array a <i>nonempty</i> array of {@code float} values * @return the value present in {@code array} that is less than or equal to every other value in * the array * @throws IllegalArgumentException if {@code array} is empty */ @GwtIncompatible( "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static float min(float... array) { checkArgument(array.length > 0); float min = array[0]; for (int i = 1; i < array.length; i++) { min = Math.min(min, array[i]); } return min; } /** * Returns the greatest value present in {@code array}, using the same rules of comparison as * {@link Math#max(float, float)}. * * @param array a <i>nonempty</i> array of {@code float} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array * @throws IllegalArgumentException if {@code array} is empty */ @GwtIncompatible( "Available in GWT! Annotation is to avoid conflict with GWT specialization of base class.") public static float max(float... array) { checkArgument(array.length > 0); float max = array[0]; for (int i = 1; i < array.length; i++) { max = Math.max(max, array[i]); } return max; } /** * Returns the 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 float} 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 float constrainToRange(float value, float min, float 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 float[] {a, b}, new float[] {}, new float[] {c}} returns the array {@code {a, b, * c}}. * * @param arrays zero or more {@code float} arrays * @return a single array containing all the values from the source arrays, in order */ public static float[] concat(float[]... arrays) { int length = 0; for (float[] array : arrays) { length += array.length; } float[] result = new float[length]; int pos = 0; for (float[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } private static final class FloatConverter extends Converter<String, Float> implements Serializable { static final Converter<String, Float> INSTANCE = new FloatConverter(); @Override protected Float doForward(String value) { return Float.valueOf(value); } @Override protected String doBackward(Float value) { return value.toString(); } @Override public String toString() { return "Floats.stringConverter()"; } private Object readResolve() { return INSTANCE; } private static final long serialVersionUID = 1; } /** * Returns a serializable converter object that converts between strings and floats using {@link * Float#valueOf} and {@link Float#toString()}. * * @since 16.0 */ public static Converter<String, Float> stringConverter() { return FloatConverter.INSTANCE; } /** * Returns an array containing the same values as {@code array}, but guaranteed to be of a * specified minimum length. If {@code array} already has a length of at least {@code minLength}, * it is returned directly. Otherwise, a new array of size {@code minLength + padding} is * returned, containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is negative * @return an array containing the values of {@code array}, with guaranteed minimum length {@code * minLength} */ public static float[] ensureCapacity(float[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? Arrays.copyOf(array, minLength + padding) : array; } /** * Returns a string containing the supplied {@code float} values, converted to strings as * specified by {@link Float#toString(float)}, and separated by {@code separator}. For example, * {@code join("-", 1.0f, 2.0f, 3.0f)} returns the string {@code "1.0-2.0-3.0"}. * * <p>Note that {@link Float#toString(float)} formats {@code float} differently in GWT. In the * previous example, it returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting string * (but not at the start or end) * @param array an array of {@code float} values, possibly empty */ public static String join(String separator, float... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 12); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code float} arrays <a * href="http://en.wikipedia.org/wiki/Lexicographical_order">lexicographically</a>. That is, it * compares, using {@link #compare(float, float)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the shorter array as the * lesser. For example, {@code [] < [1.0f] < [1.0f, 2.0f] < [2.0f]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with {@link Arrays#equals(float[], * float[])}. * * @since 2.0 */ public static Comparator<float[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<float[]> { INSTANCE; @Override public int compare(float[] left, float[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Float.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } @Override public String toString() { return "Floats.lexicographicalComparator()"; } } /** * Sorts the elements of {@code array} in descending order. * * <p>Note that this method uses the total order imposed by {@link Float#compare}, which treats * all NaN values as equal and 0.0 as greater than -0.0. * * @since 23.1 */ public static void sortDescending(float[] 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 Float#compare}, which treats * all NaN values as equal and 0.0 as greater than -0.0. * * @since 23.1 */ public static void sortDescending(float[] 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(Floats.asList(array))}, but is likely to be more efficient. * * @since 23.1 */ public static void reverse(float[] 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(Floats.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(float[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); for (int i = fromIndex, j = toIndex - 1; i < j; i++, j--) { float 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(Floats.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(float[] 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(Floats.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(float[] 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 float} * value in the manner of {@link Number#floatValue}. * * <p>Elements are copied from the argument collection as if by {@code collection.toArray()}. * Calling this method is as thread-safe as calling that method. * * @param collection a collection of {@code Number} instances * @return an array containing the same values as {@code collection}, in the same order, converted * to primitives * @throws NullPointerException if {@code collection} or any of its elements is null * @since 1.0 (parameter was {@code Collection<Float>} before 12.0) */ public static float[] toArray(Collection<? extends Number> collection) { if (collection instanceof FloatArrayAsList) { return ((FloatArrayAsList) collection).toFloatArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; float[] array = new float[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = ((Number) checkNotNull(boxedArray[i])).floatValue(); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, but any attempt to * set a value to {@code null} will result in a {@link NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of {@code Float} objects * written to or read from it. For example, whether {@code list.get(0) == list.get(0)} is true for * the returned list is unspecified. * * <p>The returned list may have unexpected behavior if it contains {@code NaN}, or if {@code NaN} * is used as a parameter to any of its methods. * * <p>The returned list is serializable. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Float> asList(float... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new FloatArrayAsList(backingArray); } @GwtCompatible private static class FloatArrayAsList extends AbstractList<Float> implements RandomAccess, Serializable { final float[] array; final int start; final int end; FloatArrayAsList(float[] array) { this(array, 0, array.length); } FloatArrayAsList(float[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Float get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(@CheckForNull Object target) { // Overridden to prevent a ton of boxing return (target instanceof Float) && Floats.indexOf(array, (Float) target, start, end) != -1; } @Override public int indexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Float) { int i = Floats.indexOf(array, (Float) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(@CheckForNull Object target) { // Overridden to prevent a ton of boxing if (target instanceof Float) { int i = Floats.lastIndexOf(array, (Float) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Float set(int index, Float element) { checkElementIndex(index, size()); float oldValue = array[start + index]; // checkNotNull for GWT (do not optimize) array[start + index] = checkNotNull(element); return oldValue; } @Override public List<Float> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new FloatArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(@CheckForNull Object object) { if (object == this) { return true; } if (object instanceof FloatArrayAsList) { FloatArrayAsList that = (FloatArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Floats.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 12); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } float[] toFloatArray() { return Arrays.copyOfRange(array, start, end); } private static final long serialVersionUID = 0; } /** * Parses the specified string as a single-precision floating point value. The ASCII character * {@code '-'} (<code>'&#92;u002D'</code>) is recognized as the minus sign. * * <p>Unlike {@link Float#parseFloat(String)}, this method returns {@code null} instead of * throwing an exception if parsing fails. Valid inputs are exactly those accepted by {@link * Float#valueOf(String)}, except that leading and trailing whitespace is not permitted. * * <p>This implementation is likely to be faster than {@code Float.parseFloat} if many failures * are expected. * * @param string the string representation of a {@code float} value * @return the floating point value represented by {@code string}, or {@code null} if {@code * string} has a length of zero or cannot be parsed as a {@code float} value * @throws NullPointerException if {@code string} is {@code null} * @since 14.0 */ @GwtIncompatible // regular expressions @CheckForNull public static Float tryParse(String string) { if (Doubles.FLOATING_POINT_PATTERN.matcher(string).matches()) { // TODO(lowasser): could be potentially optimized, but only with // extensive testing try { return Float.parseFloat(string); } catch (NumberFormatException e) { // Float.parseFloat has changed specs several times, so fall through // gracefully } } return null; } }
google/guava
android/guava/src/com/google/common/primitives/Floats.java
255
/* * 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.base.Preconditions.checkState; import static com.google.common.collect.CollectPreconditions.checkNonnegative; 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.common.base.Objects; import com.google.errorprone.annotations.CanIgnoreReturnValue; import com.google.j2objc.annotations.WeakOuter; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Iterator; import java.util.Map; import java.util.Map.Entry; import java.util.NoSuchElementException; import java.util.Set; import java.util.Spliterator; import java.util.Spliterators; import java.util.function.Consumer; import javax.annotation.CheckForNull; import org.checkerframework.checker.nullness.qual.Nullable; /** * Implementation of {@code Multimap} that does not allow duplicate key-value entries and that * returns collections whose iterators follow the ordering in which the data was added to the * multimap. * * <p>The collections returned by {@code keySet}, {@code keys}, and {@code asMap} iterate through * the keys in the order they were first added to the multimap. Similarly, {@code get}, {@code * removeAll}, and {@code replaceValues} return collections that iterate through the values in the * order they were added. The collections generated by {@code entries} and {@code values} iterate * across the key-value mappings in the order they were added to the multimap. * * <p>The iteration ordering of the collections generated by {@code keySet}, {@code keys}, and * {@code asMap} has a few subtleties. As long as the set of keys remains unchanged, adding or * removing mappings does not affect the key iteration order. However, if you remove all values * associated with a key and then add the key back to the multimap, that key will come last in the * key iteration order. * * <p>The multimap does not store duplicate key-value pairs. Adding a new key-value pair equal to an * existing key-value pair has no effect. * * <p>Keys and values may be null. All optional multimap methods are supported, and all returned * views are modifiable. * * <p>This class is not threadsafe when any concurrent operations update the multimap. Concurrent * read operations will work correctly. To allow concurrent update operations, wrap your multimap * with a call to {@link Multimaps#synchronizedSetMultimap}. * * <p><b>Warning:</b> Do not modify either a key <i>or a value</i> of a {@code LinkedHashMultimap} * in a way that affects its {@link Object#equals} behavior. Undefined behavior and bugs will * result. * * <p>See the Guava User Guide article on <a href= * "https://github.com/google/guava/wiki/NewCollectionTypesExplained#multimap">{@code Multimap}</a>. * * @author Jared Levy * @author Louis Wasserman * @since 2.0 */ @GwtCompatible(serializable = true, emulated = true) @ElementTypesAreNonnullByDefault public final class LinkedHashMultimap<K extends @Nullable Object, V extends @Nullable Object> extends LinkedHashMultimapGwtSerializationDependencies<K, V> { /** Creates a new, empty {@code LinkedHashMultimap} with the default initial capacities. */ public static <K extends @Nullable Object, V extends @Nullable Object> LinkedHashMultimap<K, V> create() { return new LinkedHashMultimap<>(DEFAULT_KEY_CAPACITY, DEFAULT_VALUE_SET_CAPACITY); } /** * Constructs an empty {@code LinkedHashMultimap} with enough capacity to hold the specified * numbers of keys and values without rehashing. * * @param expectedKeys the expected number of distinct keys * @param expectedValuesPerKey the expected average number of values per key * @throws IllegalArgumentException if {@code expectedKeys} or {@code expectedValuesPerKey} is * negative */ public static <K extends @Nullable Object, V extends @Nullable Object> LinkedHashMultimap<K, V> create(int expectedKeys, int expectedValuesPerKey) { return new LinkedHashMultimap<>( Maps.capacity(expectedKeys), Maps.capacity(expectedValuesPerKey)); } /** * Constructs a {@code LinkedHashMultimap} with the same mappings as the specified multimap. If a * key-value mapping appears multiple times in the input multimap, it only appears once in the * constructed multimap. The new multimap has the same {@link Multimap#entries()} iteration order * as the input multimap, except for excluding duplicate mappings. * * @param multimap the multimap whose contents are copied to this multimap */ public static <K extends @Nullable Object, V extends @Nullable Object> LinkedHashMultimap<K, V> create(Multimap<? extends K, ? extends V> multimap) { LinkedHashMultimap<K, V> result = create(multimap.keySet().size(), DEFAULT_VALUE_SET_CAPACITY); result.putAll(multimap); return result; } private interface ValueSetLink<K extends @Nullable Object, V extends @Nullable Object> { ValueSetLink<K, V> getPredecessorInValueSet(); ValueSetLink<K, V> getSuccessorInValueSet(); void setPredecessorInValueSet(ValueSetLink<K, V> entry); void setSuccessorInValueSet(ValueSetLink<K, V> entry); } private static <K extends @Nullable Object, V extends @Nullable Object> void succeedsInValueSet( ValueSetLink<K, V> pred, ValueSetLink<K, V> succ) { pred.setSuccessorInValueSet(succ); succ.setPredecessorInValueSet(pred); } private static <K extends @Nullable Object, V extends @Nullable Object> void succeedsInMultimap( ValueEntry<K, V> pred, ValueEntry<K, V> succ) { pred.setSuccessorInMultimap(succ); succ.setPredecessorInMultimap(pred); } private static <K extends @Nullable Object, V extends @Nullable Object> void deleteFromValueSet( ValueSetLink<K, V> entry) { succeedsInValueSet(entry.getPredecessorInValueSet(), entry.getSuccessorInValueSet()); } private static <K extends @Nullable Object, V extends @Nullable Object> void deleteFromMultimap( ValueEntry<K, V> entry) { succeedsInMultimap(entry.getPredecessorInMultimap(), entry.getSuccessorInMultimap()); } /** * LinkedHashMultimap entries are in no less than three coexisting linked lists: a bucket in the * hash table for a {@code Set<V>} associated with a key, the linked list of insertion-ordered * entries in that {@code Set<V>}, and the linked list of entries in the LinkedHashMultimap as a * whole. */ @VisibleForTesting static final class ValueEntry<K extends @Nullable Object, V extends @Nullable Object> extends ImmutableEntry<K, V> implements ValueSetLink<K, V> { final int smearedValueHash; @CheckForNull ValueEntry<K, V> nextInValueBucket; /* * The *InValueSet and *InMultimap fields below are null after construction, but we almost * always call succeedsIn*() to initialize them immediately thereafter. * * The exception is the *InValueSet fields of multimapHeaderEntry, which are never set. (That * works out fine as long as we continue to be careful not to try to delete them or iterate * past them.) * * We could consider "lying" and omitting @CheckNotNull from all these fields. Normally, I'm not * a fan of that: What if we someday implement (presumably to be enabled during tests only) * bytecode rewriting that checks for any null value that passes through an API with a * known-non-null type? But that particular problem might not arise here, since we're not * actually reading from the fields in any case in which they might be null (as proven by the * requireNonNull checks below). Plus, we're *already* lying here, since newHeader passes a null * key and value, which we pass to the superconstructor, even though the key and value type for * a given entry might not include null. The right fix for the header problems is probably to * define a separate MultimapLink interface with a separate "header" implementation, which * hopefully could avoid implementing Entry or ValueSetLink at all. (But note that that approach * requires us to define extra classes -- unfortunate under Android.) *Then* we could consider * lying about the fields below on the grounds that we always initialize them just after the * constructor -- an example of the kind of lying that our hypothetical bytecode rewriter would * already have to deal with, thanks to DI frameworks that perform field and method injection, * frameworks like Android that define post-construct hooks like Activity.onCreate, etc. */ @CheckForNull private ValueSetLink<K, V> predecessorInValueSet; @CheckForNull private ValueSetLink<K, V> successorInValueSet; @CheckForNull private ValueEntry<K, V> predecessorInMultimap; @CheckForNull private ValueEntry<K, V> successorInMultimap; ValueEntry( @ParametricNullness K key, @ParametricNullness V value, int smearedValueHash, @CheckForNull ValueEntry<K, V> nextInValueBucket) { super(key, value); this.smearedValueHash = smearedValueHash; this.nextInValueBucket = nextInValueBucket; } @SuppressWarnings("nullness") // see the comment on the class fields, especially about newHeader static <K extends @Nullable Object, V extends @Nullable Object> ValueEntry<K, V> newHeader() { return new ValueEntry<>(null, null, 0, null); } boolean matchesValue(@CheckForNull Object v, int smearedVHash) { return smearedValueHash == smearedVHash && Objects.equal(getValue(), v); } @Override public ValueSetLink<K, V> getPredecessorInValueSet() { return requireNonNull(predecessorInValueSet); // see the comment on the class fields } @Override public ValueSetLink<K, V> getSuccessorInValueSet() { return requireNonNull(successorInValueSet); // see the comment on the class fields } @Override public void setPredecessorInValueSet(ValueSetLink<K, V> entry) { predecessorInValueSet = entry; } @Override public void setSuccessorInValueSet(ValueSetLink<K, V> entry) { successorInValueSet = entry; } public ValueEntry<K, V> getPredecessorInMultimap() { return requireNonNull(predecessorInMultimap); // see the comment on the class fields } public ValueEntry<K, V> getSuccessorInMultimap() { return requireNonNull(successorInMultimap); // see the comment on the class fields } public void setSuccessorInMultimap(ValueEntry<K, V> multimapSuccessor) { this.successorInMultimap = multimapSuccessor; } public void setPredecessorInMultimap(ValueEntry<K, V> multimapPredecessor) { this.predecessorInMultimap = multimapPredecessor; } } private static final int DEFAULT_KEY_CAPACITY = 16; private static final int DEFAULT_VALUE_SET_CAPACITY = 2; @VisibleForTesting static final double VALUE_SET_LOAD_FACTOR = 1.0; @VisibleForTesting transient int valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY; private transient ValueEntry<K, V> multimapHeaderEntry; private LinkedHashMultimap(int keyCapacity, int valueSetCapacity) { super(Platform.<K, Collection<V>>newLinkedHashMapWithExpectedSize(keyCapacity)); checkNonnegative(valueSetCapacity, "expectedValuesPerKey"); this.valueSetCapacity = valueSetCapacity; this.multimapHeaderEntry = ValueEntry.newHeader(); succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); } /** * {@inheritDoc} * * <p>Creates an empty {@code LinkedHashSet} for a collection of values for one key. * * @return a new {@code LinkedHashSet} containing a collection of values for one key */ @Override Set<V> createCollection() { return Platform.newLinkedHashSetWithExpectedSize(valueSetCapacity); } /** * {@inheritDoc} * * <p>Creates a decorated insertion-ordered set that also keeps track of the order in which * key-value pairs are added to the multimap. * * @param key key to associate with values in the collection * @return a new decorated set containing a collection of values for one key */ @Override Collection<V> createCollection(@ParametricNullness K key) { return new ValueSet(key, valueSetCapacity); } /** * {@inheritDoc} * * <p>If {@code values} is not empty and the multimap already contains a mapping for {@code key}, * the {@code keySet()} ordering is unchanged. However, the provided values always come last in * the {@link #entries()} and {@link #values()} iteration orderings. */ @CanIgnoreReturnValue @Override public Set<V> replaceValues(@ParametricNullness K key, Iterable<? extends V> values) { return super.replaceValues(key, values); } /** * Returns a set of all key-value pairs. Changes to the returned set will update the underlying * multimap, and vice versa. The entries set does not support the {@code add} or {@code addAll} * operations. * * <p>The iterator generated by the returned set traverses the entries in the order they were * added to the multimap. * * <p>Each entry is an immutable snapshot of a key-value mapping in the multimap, taken at the * time the entry is returned by a method call to the collection or its iterator. */ @Override public Set<Entry<K, V>> entries() { return super.entries(); } /** * Returns a view collection of all <i>distinct</i> keys contained in this multimap. Note that the * key set contains a key if and only if this multimap maps that key to at least one value. * * <p>The iterator generated by the returned set traverses the keys in the order they were first * added to the multimap. * * <p>Changes to the returned set will update the underlying multimap, and vice versa. However, * <i>adding</i> to the returned set is not possible. */ @Override public Set<K> keySet() { return super.keySet(); } /** * Returns a collection of all values in the multimap. Changes to the returned collection will * update the underlying multimap, and vice versa. * * <p>The iterator generated by the returned collection traverses the values in the order they * were added to the multimap. */ @Override public Collection<V> values() { return super.values(); } @VisibleForTesting @WeakOuter final class ValueSet extends Sets.ImprovedAbstractSet<V> implements ValueSetLink<K, V> { /* * We currently use a fixed load factor of 1.0, a bit higher than normal to reduce memory * consumption. */ @ParametricNullness private final K key; @VisibleForTesting @Nullable ValueEntry<K, V>[] hashTable; private int size = 0; private int modCount = 0; // We use the set object itself as the end of the linked list, avoiding an unnecessary // entry object per key. private ValueSetLink<K, V> firstEntry; private ValueSetLink<K, V> lastEntry; ValueSet(@ParametricNullness K key, int expectedValues) { this.key = key; this.firstEntry = this; this.lastEntry = this; // Round expected values up to a power of 2 to get the table size. int tableSize = Hashing.closedTableSize(expectedValues, VALUE_SET_LOAD_FACTOR); @SuppressWarnings({"rawtypes", "unchecked"}) @Nullable ValueEntry<K, V>[] hashTable = new @Nullable ValueEntry[tableSize]; this.hashTable = hashTable; } private int mask() { return hashTable.length - 1; } @Override public ValueSetLink<K, V> getPredecessorInValueSet() { return lastEntry; } @Override public ValueSetLink<K, V> getSuccessorInValueSet() { return firstEntry; } @Override public void setPredecessorInValueSet(ValueSetLink<K, V> entry) { lastEntry = entry; } @Override public void setSuccessorInValueSet(ValueSetLink<K, V> entry) { firstEntry = entry; } @Override public Iterator<V> iterator() { return new Iterator<V>() { ValueSetLink<K, V> nextEntry = firstEntry; @CheckForNull ValueEntry<K, V> toRemove; int expectedModCount = modCount; private void checkForComodification() { if (modCount != expectedModCount) { throw new ConcurrentModificationException(); } } @Override public boolean hasNext() { checkForComodification(); return nextEntry != ValueSet.this; } @Override @ParametricNullness public V next() { if (!hasNext()) { throw new NoSuchElementException(); } ValueEntry<K, V> entry = (ValueEntry<K, V>) nextEntry; V result = entry.getValue(); toRemove = entry; nextEntry = entry.getSuccessorInValueSet(); return result; } @Override public void remove() { checkForComodification(); checkState(toRemove != null, "no calls to next() since the last call to remove()"); ValueSet.this.remove(toRemove.getValue()); expectedModCount = modCount; toRemove = null; } }; } @Override public void forEach(Consumer<? super V> action) { checkNotNull(action); for (ValueSetLink<K, V> entry = firstEntry; entry != ValueSet.this; entry = entry.getSuccessorInValueSet()) { action.accept(((ValueEntry<K, V>) entry).getValue()); } } @Override public int size() { return size; } @Override public boolean contains(@CheckForNull Object o) { int smearedHash = Hashing.smearedHash(o); for (ValueEntry<K, V> entry = hashTable[smearedHash & mask()]; entry != null; entry = entry.nextInValueBucket) { if (entry.matchesValue(o, smearedHash)) { return true; } } return false; } @Override public boolean add(@ParametricNullness V value) { int smearedHash = Hashing.smearedHash(value); int bucket = smearedHash & mask(); ValueEntry<K, V> rowHead = hashTable[bucket]; for (ValueEntry<K, V> entry = rowHead; entry != null; entry = entry.nextInValueBucket) { if (entry.matchesValue(value, smearedHash)) { return false; } } ValueEntry<K, V> newEntry = new ValueEntry<>(key, value, smearedHash, rowHead); succeedsInValueSet(lastEntry, newEntry); succeedsInValueSet(newEntry, this); succeedsInMultimap(multimapHeaderEntry.getPredecessorInMultimap(), newEntry); succeedsInMultimap(newEntry, multimapHeaderEntry); hashTable[bucket] = newEntry; size++; modCount++; rehashIfNecessary(); return true; } private void rehashIfNecessary() { if (Hashing.needsResizing(size, hashTable.length, VALUE_SET_LOAD_FACTOR)) { @SuppressWarnings("unchecked") ValueEntry<K, V>[] hashTable = (ValueEntry<K, V>[]) new ValueEntry<?, ?>[this.hashTable.length * 2]; this.hashTable = hashTable; int mask = hashTable.length - 1; for (ValueSetLink<K, V> entry = firstEntry; entry != this; entry = entry.getSuccessorInValueSet()) { ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry; int bucket = valueEntry.smearedValueHash & mask; valueEntry.nextInValueBucket = hashTable[bucket]; hashTable[bucket] = valueEntry; } } } @CanIgnoreReturnValue @Override public boolean remove(@CheckForNull Object o) { int smearedHash = Hashing.smearedHash(o); int bucket = smearedHash & mask(); ValueEntry<K, V> prev = null; for (ValueEntry<K, V> entry = hashTable[bucket]; entry != null; prev = entry, entry = entry.nextInValueBucket) { if (entry.matchesValue(o, smearedHash)) { if (prev == null) { // first entry in the bucket hashTable[bucket] = entry.nextInValueBucket; } else { prev.nextInValueBucket = entry.nextInValueBucket; } deleteFromValueSet(entry); deleteFromMultimap(entry); size--; modCount++; return true; } } return false; } @Override public void clear() { Arrays.fill(hashTable, null); size = 0; for (ValueSetLink<K, V> entry = firstEntry; entry != this; entry = entry.getSuccessorInValueSet()) { ValueEntry<K, V> valueEntry = (ValueEntry<K, V>) entry; deleteFromMultimap(valueEntry); } succeedsInValueSet(this, this); modCount++; } } @Override Iterator<Entry<K, V>> entryIterator() { return new Iterator<Entry<K, V>>() { ValueEntry<K, V> nextEntry = multimapHeaderEntry.getSuccessorInMultimap(); @CheckForNull ValueEntry<K, V> toRemove; @Override public boolean hasNext() { return nextEntry != multimapHeaderEntry; } @Override public Entry<K, V> next() { if (!hasNext()) { throw new NoSuchElementException(); } ValueEntry<K, V> result = nextEntry; toRemove = result; nextEntry = nextEntry.getSuccessorInMultimap(); return result; } @Override public void remove() { checkState(toRemove != null, "no calls to next() since the last call to remove()"); LinkedHashMultimap.this.remove(toRemove.getKey(), toRemove.getValue()); toRemove = null; } }; } @Override Spliterator<Entry<K, V>> entrySpliterator() { return Spliterators.spliterator(entries(), Spliterator.DISTINCT | Spliterator.ORDERED); } @Override Iterator<V> valueIterator() { return Maps.valueIterator(entryIterator()); } @Override Spliterator<V> valueSpliterator() { return CollectSpliterators.map(entrySpliterator(), Entry::getValue); } @Override public void clear() { super.clear(); succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); } /** * @serialData the expected values per key, the number of distinct keys, the number of entries, * and the entries in order */ @GwtIncompatible // java.io.ObjectOutputStream @J2ktIncompatible private void writeObject(ObjectOutputStream stream) throws IOException { stream.defaultWriteObject(); stream.writeInt(keySet().size()); for (K key : keySet()) { stream.writeObject(key); } stream.writeInt(size()); for (Entry<K, V> entry : entries()) { stream.writeObject(entry.getKey()); stream.writeObject(entry.getValue()); } } @GwtIncompatible // java.io.ObjectInputStream @J2ktIncompatible private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException { stream.defaultReadObject(); multimapHeaderEntry = ValueEntry.newHeader(); succeedsInMultimap(multimapHeaderEntry, multimapHeaderEntry); valueSetCapacity = DEFAULT_VALUE_SET_CAPACITY; int distinctKeys = stream.readInt(); Map<K, Collection<V>> map = Platform.newLinkedHashMapWithExpectedSize(12); for (int i = 0; i < distinctKeys; i++) { @SuppressWarnings("unchecked") K key = (K) stream.readObject(); map.put(key, createCollection(key)); } int entries = stream.readInt(); for (int i = 0; i < entries; i++) { @SuppressWarnings("unchecked") K key = (K) stream.readObject(); @SuppressWarnings("unchecked") V value = (V) stream.readObject(); /* * requireNonNull is safe for a properly serialized multimap: We've already inserted a * collection for each key that we expect. */ requireNonNull(map.get(key)).add(value); } setMap(map); } @GwtIncompatible // java serialization not supported @J2ktIncompatible private static final long serialVersionUID = 1; }
google/guava
guava/src/com/google/common/collect/LinkedHashMultimap.java
256
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import com.google.errorprone.annotations.CanIgnoreReturnValue; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; /** * Static utility methods pertaining to {@code long} primitives that interpret values as * <i>unsigned</i> (that is, any negative value {@code x} is treated as the positive value {@code * 2^64 + x}). The methods for which signedness is not an issue are in {@link Longs}, as well as * signed versions of methods for which signedness is an issue. * * <p>In addition, this class provides several static methods for converting a {@code long} to a * {@code String} and a {@code String} to a {@code long} that treat the {@code long} as an unsigned * number. * * <p>Users of these utilities must be <i>extremely careful</i> not to mix up signed and unsigned * {@code long} values. When possible, it is recommended that the {@link UnsignedLong} wrapper class * be used, at a small efficiency penalty, to enforce the distinction in the type system. * * <p>See the Guava User Guide article on <a * href="https://github.com/google/guava/wiki/PrimitivesExplained#unsigned-support">unsigned * primitive utilities</a>. * * @author Louis Wasserman * @author Brian Milch * @author Colin Evans * @since 10.0 */ @GwtCompatible @ElementTypesAreNonnullByDefault public final class UnsignedLongs { private UnsignedLongs() {} public static final long MAX_VALUE = -1L; // Equivalent to 2^64 - 1 /** * A (self-inverse) bijection which converts the ordering on unsigned longs to the ordering on * longs, that is, {@code a <= b} as unsigned longs if and only if {@code flip(a) <= flip(b)} as * signed longs. */ private static long flip(long a) { return a ^ Long.MIN_VALUE; } /** * Compares the two specified {@code long} values, treating them as unsigned values between {@code * 0} and {@code 2^64 - 1} inclusive. * * <p><b>Java 8+ users:</b> use {@link Long#compareUnsigned(long, long)} instead. * * @param a the first unsigned {@code long} to compare * @param b the second unsigned {@code long} to compare * @return a negative value if {@code a} is less than {@code b}; a positive value if {@code a} is * greater than {@code b}; or zero if they are equal */ public static int compare(long a, long b) { return Longs.compare(flip(a), flip(b)); } /** * Returns the least value present in {@code array}, treating values as unsigned. * * @param array a <i>nonempty</i> array of unsigned {@code long} values * @return the value present in {@code array} that is less than or equal to every other value in * the array according to {@link #compare} * @throws IllegalArgumentException if {@code array} is empty */ public static long min(long... array) { checkArgument(array.length > 0); long min = flip(array[0]); for (int i = 1; i < array.length; i++) { long next = flip(array[i]); if (next < min) { min = next; } } return flip(min); } /** * Returns the greatest value present in {@code array}, treating values as unsigned. * * @param array a <i>nonempty</i> array of unsigned {@code long} values * @return the value present in {@code array} that is greater than or equal to every other value * in the array according to {@link #compare} * @throws IllegalArgumentException if {@code array} is empty */ public static long max(long... array) { checkArgument(array.length > 0); long max = flip(array[0]); for (int i = 1; i < array.length; i++) { long next = flip(array[i]); if (next > max) { max = next; } } return flip(max); } /** * Returns a string containing the supplied unsigned {@code long} values separated by {@code * separator}. For example, {@code join("-", 1, 2, 3)} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in the resulting string * (but not at the start or end) * @param array an array of unsigned {@code long} values, possibly empty */ public static String join(String separator, long... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(toString(array[0])); for (int i = 1; i < array.length; i++) { builder.append(separator).append(toString(array[i])); } return builder.toString(); } /** * Returns a comparator that compares two arrays of unsigned {@code long} values <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] < [1L << 63]}. * * <p>The returned comparator is inconsistent with {@link Object#equals(Object)} (since arrays * support only identity equality), but it is consistent with {@link Arrays#equals(long[], * long[])}. */ public static Comparator<long[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } enum LexicographicalComparator implements Comparator<long[]> { INSTANCE; @Override public int compare(long[] left, long[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { if (left[i] != right[i]) { return UnsignedLongs.compare(left[i], right[i]); } } return left.length - right.length; } @Override public String toString() { return "UnsignedLongs.lexicographicalComparator()"; } } /** * Sorts the array, treating its elements as unsigned 64-bit integers. * * @since 23.1 */ public static void sort(long[] array) { checkNotNull(array); sort(array, 0, array.length); } /** * Sorts the array between {@code fromIndex} inclusive and {@code toIndex} exclusive, treating its * elements as unsigned 64-bit integers. * * @since 23.1 */ public static void sort(long[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); for (int i = fromIndex; i < toIndex; i++) { array[i] = flip(array[i]); } Arrays.sort(array, fromIndex, toIndex); for (int i = fromIndex; i < toIndex; i++) { array[i] = flip(array[i]); } } /** * Sorts the elements of {@code array} in descending order, interpreting them as unsigned 64-bit * integers. * * @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, interpreting them as unsigned 64-bit integers. * * @since 23.1 */ public static void sortDescending(long[] array, int fromIndex, int toIndex) { checkNotNull(array); checkPositionIndexes(fromIndex, toIndex, array.length); for (int i = fromIndex; i < toIndex; i++) { array[i] ^= Long.MAX_VALUE; } Arrays.sort(array, fromIndex, toIndex); for (int i = fromIndex; i < toIndex; i++) { array[i] ^= Long.MAX_VALUE; } } /** * Returns dividend / divisor, where the dividend and divisor are treated as unsigned 64-bit * quantities. * * <p><b>Java 8+ users:</b> use {@link Long#divideUnsigned(long, long)} instead. * * @param dividend the dividend (numerator) * @param divisor the divisor (denominator) * @throws ArithmeticException if divisor is 0 */ public static long divide(long dividend, long divisor) { if (divisor < 0) { // i.e., divisor >= 2^63: if (compare(dividend, divisor) < 0) { return 0; // dividend < divisor } else { return 1; // dividend >= divisor } } // Optimization - use signed division if dividend < 2^63 if (dividend >= 0) { return dividend / divisor; } /* * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is * guaranteed to be either exact or one less than the correct value. This follows from fact that * floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not quite * trivial. */ long quotient = ((dividend >>> 1) / divisor) << 1; long rem = dividend - quotient * divisor; return quotient + (compare(rem, divisor) >= 0 ? 1 : 0); } /** * Returns dividend % divisor, where the dividend and divisor are treated as unsigned 64-bit * quantities. * * <p><b>Java 8+ users:</b> use {@link Long#remainderUnsigned(long, long)} instead. * * @param dividend the dividend (numerator) * @param divisor the divisor (denominator) * @throws ArithmeticException if divisor is 0 * @since 11.0 */ public static long remainder(long dividend, long divisor) { if (divisor < 0) { // i.e., divisor >= 2^63: if (compare(dividend, divisor) < 0) { return dividend; // dividend < divisor } else { return dividend - divisor; // dividend >= divisor } } // Optimization - use signed modulus if dividend < 2^63 if (dividend >= 0) { return dividend % divisor; } /* * Otherwise, approximate the quotient, check, and correct if necessary. Our approximation is * guaranteed to be either exact or one less than the correct value. This follows from the fact * that floor(floor(x)/i) == floor(x/i) for any real x and integer i != 0. The proof is not * quite trivial. */ long quotient = ((dividend >>> 1) / divisor) << 1; long rem = dividend - quotient * divisor; return rem - (compare(rem, divisor) >= 0 ? divisor : 0); } /** * Returns the unsigned {@code long} value represented by the given decimal string. * * <p><b>Java 8+ users:</b> use {@link Long#parseUnsignedLong(String)} instead. * * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} * value * @throws NullPointerException if {@code string} is null (in contrast to {@link * Long#parseLong(String)}) */ @CanIgnoreReturnValue public static long parseUnsignedLong(String string) { return parseUnsignedLong(string, 10); } /** * Returns the unsigned {@code long} value represented by a string with the given radix. * * <p><b>Java 8+ users:</b> use {@link Long#parseUnsignedLong(String, int)} instead. * * @param string the string containing the unsigned {@code long} representation to be parsed. * @param radix the radix to use while parsing {@code string} * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} with * the given radix, or if {@code radix} is not between {@link Character#MIN_RADIX} and {@link * Character#MAX_RADIX}. * @throws NullPointerException if {@code string} is null (in contrast to {@link * Long#parseLong(String)}) */ @CanIgnoreReturnValue public static long parseUnsignedLong(String string, int radix) { checkNotNull(string); if (string.length() == 0) { throw new NumberFormatException("empty string"); } if (radix < Character.MIN_RADIX || radix > Character.MAX_RADIX) { throw new NumberFormatException("illegal radix: " + radix); } int maxSafePos = ParseOverflowDetection.maxSafeDigits[radix] - 1; long value = 0; for (int pos = 0; pos < string.length(); pos++) { int digit = Character.digit(string.charAt(pos), radix); if (digit == -1) { throw new NumberFormatException(string); } if (pos > maxSafePos && ParseOverflowDetection.overflowInParse(value, digit, radix)) { throw new NumberFormatException("Too large for unsigned long: " + string); } value = (value * radix) + digit; } return value; } /** * Returns the unsigned {@code long} value represented by the given string. * * <p>Accepts a decimal, hexadecimal, or octal number given by specifying the following prefix: * * <ul> * <li>{@code 0x}<i>HexDigits</i> * <li>{@code 0X}<i>HexDigits</i> * <li>{@code #}<i>HexDigits</i> * <li>{@code 0}<i>OctalDigits</i> * </ul> * * @throws NumberFormatException if the string does not contain a valid unsigned {@code long} * value * @since 13.0 */ @CanIgnoreReturnValue public static long decode(String stringValue) { ParseRequest request = ParseRequest.fromString(stringValue); try { return parseUnsignedLong(request.rawValue, request.radix); } catch (NumberFormatException e) { NumberFormatException decodeException = new NumberFormatException("Error parsing value: " + stringValue); decodeException.initCause(e); throw decodeException; } } /* * We move the static constants into this class so ProGuard can inline UnsignedLongs entirely * unless the user is actually calling a parse method. */ private static final class ParseOverflowDetection { private ParseOverflowDetection() {} // calculated as 0xffffffffffffffff / radix static final long[] maxValueDivs = new long[Character.MAX_RADIX + 1]; static final int[] maxValueMods = new int[Character.MAX_RADIX + 1]; static final int[] maxSafeDigits = new int[Character.MAX_RADIX + 1]; static { BigInteger overflow = new BigInteger("10000000000000000", 16); for (int i = Character.MIN_RADIX; i <= Character.MAX_RADIX; i++) { maxValueDivs[i] = divide(MAX_VALUE, i); maxValueMods[i] = (int) remainder(MAX_VALUE, i); maxSafeDigits[i] = overflow.toString(i).length() - 1; } } /** * Returns true if (current * radix) + digit is a number too large to be represented by an * unsigned long. This is useful for detecting overflow while parsing a string representation of * a number. Does not verify whether supplied radix is valid, passing an invalid radix will give * undefined results or an ArrayIndexOutOfBoundsException. */ static boolean overflowInParse(long current, int digit, int radix) { if (current >= 0) { if (current < maxValueDivs[radix]) { return false; } if (current > maxValueDivs[radix]) { return true; } // current == maxValueDivs[radix] return (digit > maxValueMods[radix]); } // current < 0: high bit is set return true; } } /** * Returns a string representation of x, where x is treated as unsigned. * * <p><b>Java 8+ users:</b> use {@link Long#toUnsignedString(long)} instead. */ public static String toString(long x) { return toString(x, 10); } /** * Returns a string representation of {@code x} for the given radix, where {@code x} is treated as * unsigned. * * <p><b>Java 8+ users:</b> use {@link Long#toUnsignedString(long, int)} instead. * * @param x the value to convert to a string. * @param radix the radix to use while working with {@code x} * @throws IllegalArgumentException if {@code radix} is not between {@link Character#MIN_RADIX} * and {@link Character#MAX_RADIX}. */ public static String toString(long x, int radix) { checkArgument( radix >= Character.MIN_RADIX && radix <= Character.MAX_RADIX, "radix (%s) must be between Character.MIN_RADIX and Character.MAX_RADIX", radix); if (x == 0) { // Simply return "0" return "0"; } else if (x > 0) { return Long.toString(x, radix); } else { char[] buf = new char[64]; int i = buf.length; if ((radix & (radix - 1)) == 0) { // Radix is a power of two so we can avoid division. int shift = Integer.numberOfTrailingZeros(radix); int mask = radix - 1; do { buf[--i] = Character.forDigit(((int) x) & mask, radix); x >>>= shift; } while (x != 0); } else { // Separate off the last digit using unsigned division. That will leave // a number that is nonnegative as a signed integer. long quotient; if ((radix & 1) == 0) { // Fast path for the usual case where the radix is even. quotient = (x >>> 1) / (radix >>> 1); } else { quotient = divide(x, radix); } long rem = x - quotient * radix; buf[--i] = Character.forDigit((int) rem, radix); x = quotient; // Simple modulo/division approach while (x > 0) { buf[--i] = Character.forDigit((int) (x % radix), radix); x /= radix; } } // Generate string return new String(buf, i, buf.length - i); } } }
google/guava
android/guava/src/com/google/common/primitives/UnsignedLongs.java
257
/* * 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 crtp; /** * Fighter interface. * * @param <T> The type of fighter. */ public interface Fighter<T> { void fight(T t); }
sarvex/java-design-patterns
crtp/src/main/java/crtp/Fighter.java
258
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx; /** * <p> * An {@link ApplicationListener} that delegates to a {@link Screen}. This allows an application to easily have multiple screens. * </p> * <p> * Screens are not disposed automatically. You must handle whether you want to keep screens around or dispose of them when another * screen is set. * </p> */ public abstract class Game implements ApplicationListener { protected Screen screen; @Override public void dispose () { if (screen != null) screen.hide(); } @Override public void pause () { if (screen != null) screen.pause(); } @Override public void resume () { if (screen != null) screen.resume(); } @Override public void render () { if (screen != null) screen.render(Gdx.graphics.getDeltaTime()); } @Override public void resize (int width, int height) { if (screen != null) screen.resize(width, height); } /** Sets the current screen. {@link Screen#hide()} is called on any old screen, and {@link Screen#show()} is called on the new * screen, if any. * @param screen may be {@code null} */ public void setScreen (Screen screen) { if (this.screen != null) this.screen.hide(); this.screen = screen; if (this.screen != null) { this.screen.show(); this.screen.resize(Gdx.graphics.getWidth(), Gdx.graphics.getHeight()); } } /** @return the currently active {@link Screen}. */ public Screen getScreen () { return screen; } }
tommyettinger/libgdx
gdx/src/com/badlogic/gdx/Game.java
259
/* * 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. */ import lombok.extern.slf4j.Slf4j; /** * Class defining Thief. */ @Slf4j public class Thief { protected void steal() { LOGGER.info("Steal valuable items"); } protected void doNothing() { LOGGER.info("Pretend nothing happened and just leave"); } }
smedals/java-design-patterns
marker/src/main/java/Thief.java
260
/* * 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. */ import lombok.extern.slf4j.Slf4j; /** * Class defining Guard. */ @Slf4j public class Guard implements Permission { protected void enter() { LOGGER.info("You can enter"); } }
smedals/java-design-patterns
marker/src/main/java/Guard.java
261
/* * 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.mapper; import org.apache.lucene.document.FieldType; import org.elasticsearch.common.Strings; import org.elasticsearch.common.util.StringLiteralDeduplicator; import org.elasticsearch.index.IndexVersion; import org.elasticsearch.index.IndexVersions; import org.elasticsearch.xcontent.ToXContentFragment; import java.util.Map; import java.util.Objects; import java.util.concurrent.ConcurrentHashMap; import java.util.function.Function; public abstract class Mapper implements ToXContentFragment, Iterable<Mapper> { public abstract static class Builder { private String name; protected Builder(String name) { setName(name); } // TODO rename this to leafName? public final String name() { return this.name; } /** Returns a newly built mapper. */ public abstract Mapper build(MapperBuilderContext context); void setName(String name) { this.name = internFieldName(name); } } public interface TypeParser { Mapper.Builder parse(String name, Map<String, Object> node, MappingParserContext parserContext) throws MapperParsingException; /** * Whether we can parse this type on indices with the given index created version. */ default boolean supportsVersion(IndexVersion indexCreatedVersion) { return indexCreatedVersion.onOrAfter(IndexVersions.MINIMUM_COMPATIBLE); } } private final String simpleName; public Mapper(String simpleName) { Objects.requireNonNull(simpleName); this.simpleName = internFieldName(simpleName); } /** Returns the simple name, which identifies this mapper against other mappers at the same level in the mappers hierarchy * TODO: make this protected once Mapper and FieldMapper are merged together */ // TODO rename this to leafName? public final String simpleName() { return simpleName; } /** Returns the canonical name which uniquely identifies the mapper against other mappers in a type. */ // TODO rename this to fullPath??? public abstract String name(); /** * Returns a name representing the type of this mapper. */ public abstract String typeName(); /** * Return the merge of {@code mergeWith} into this. * Both {@code this} and {@code mergeWith} will be left unmodified. */ public abstract Mapper merge(Mapper mergeWith, MapperMergeContext mapperMergeContext); /** * Validate any cross-field references made by this mapper * @param mappers a {@link MappingLookup} that can produce references to other mappers */ public abstract void validate(MappingLookup mappers); /** * Create a {@link SourceLoader.SyntheticFieldLoader} to populate synthetic source. * * @throws IllegalArgumentException if the field is configured in a way that doesn't * support synthetic source. This translates nicely into a 400 error when * users configure synthetic source in the mapping without configuring all * fields properly. */ public SourceLoader.SyntheticFieldLoader syntheticFieldLoader() { throw new IllegalArgumentException("field [" + name() + "] of type [" + typeName() + "] doesn't support synthetic source"); } @Override public String toString() { return Strings.toString(this); } private static final StringLiteralDeduplicator fieldNameStringDeduplicator = new StringLiteralDeduplicator(); /** * Interns the given field name string through a {@link StringLiteralDeduplicator}. * @param fieldName field name to intern * @return interned field name string */ public static String internFieldName(String fieldName) { return fieldNameStringDeduplicator.deduplicate(fieldName); } private static final Map<FieldType, FieldType> fieldTypeDeduplicator = new ConcurrentHashMap<>(); /** * Freezes the given {@link FieldType} instances and tries to deduplicate it as long as the field does not return a non-empty value for * {@link FieldType#getAttributes()}. * * @param fieldType field type to deduplicate * @return deduplicated field type */ public static FieldType freezeAndDeduplicateFieldType(FieldType fieldType) { fieldType.freeze(); var attributes = fieldType.getAttributes(); if ((attributes != null && attributes.isEmpty() == false) || fieldType.getClass() != FieldType.class) { // don't deduplicate subclasses or types with non-empty attribute maps to avoid memory leaks return fieldType; } if (fieldTypeDeduplicator.size() > 1000) { // guard against the case where we run up too many combinations via (vector-)dimensions combinations fieldTypeDeduplicator.clear(); } return fieldTypeDeduplicator.computeIfAbsent(fieldType, Function.identity()); } /** * The total number of fields as defined in the mapping. * Defines how this mapper counts towards {@link MapperService#INDEX_MAPPING_TOTAL_FIELDS_LIMIT_SETTING}. */ public abstract int getTotalFieldsCount(); }
elastic/elasticsearch
server/src/main/java/org/elasticsearch/index/mapper/Mapper.java
262
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx; import com.badlogic.gdx.graphics.Cursor; import com.badlogic.gdx.graphics.Cursor.SystemCursor; import com.badlogic.gdx.graphics.GL20; import com.badlogic.gdx.graphics.GL30; import com.badlogic.gdx.graphics.GL31; import com.badlogic.gdx.graphics.GL32; import com.badlogic.gdx.graphics.Mesh; import com.badlogic.gdx.graphics.Pixmap; import com.badlogic.gdx.graphics.g2d.Batch; import com.badlogic.gdx.graphics.g2d.BitmapFont; import com.badlogic.gdx.graphics.glutils.FrameBuffer; import com.badlogic.gdx.graphics.glutils.GLVersion; import com.badlogic.gdx.graphics.glutils.IndexBufferObject; import com.badlogic.gdx.graphics.glutils.ShaderProgram; import com.badlogic.gdx.graphics.glutils.VertexArray; import com.badlogic.gdx.graphics.glutils.VertexBufferObject; /** This interface encapsulates communication with the graphics processor. Depending on the available hardware and the current * {@link Application} configuration, access to {@link GL20} and {@link GL30} are provided here. * <p> * If supported by the backend, this interface lets you query the available display modes (graphics resolution and color depth) * and change it. * <p> * This interface can be used to switch between continuous and non-continuous rendering (see * {@link #setContinuousRendering(boolean)}), and to explicitly {@link #requestRendering()}. * <p> * There are many more utility classes that are not directly generated by the {@link Graphics} interfaces. See {@link VertexArray} * , {@link VertexBufferObject}, {@link IndexBufferObject}, {@link Mesh}, {@link ShaderProgram} and {@link FrameBuffer}, * {@link BitmapFont}, {@link Batch} and so on. All these classes are managed, meaning they don't need to be reloaded on a context * loss. Explore the com.badlogic.gdx.graphics package for more classes that might come in handy. * @author mzechner */ public interface Graphics { /** Enumeration describing different types of {@link Graphics} implementations. * * @author mzechner */ enum GraphicsType { AndroidGL, LWJGL, WebGL, iOSGL, JGLFW, Mock, LWJGL3 } /** Describe a fullscreen display mode * * @author mzechner */ class DisplayMode { /** the width in physical pixels **/ public final int width; /** the height in physical pixels **/ public final int height; /** the refresh rate in Hertz **/ public final int refreshRate; /** the number of bits per pixel, may exclude alpha **/ public final int bitsPerPixel; protected DisplayMode (int width, int height, int refreshRate, int bitsPerPixel) { this.width = width; this.height = height; this.refreshRate = refreshRate; this.bitsPerPixel = bitsPerPixel; } public String toString () { return width + "x" + height + ", bpp: " + bitsPerPixel + ", hz: " + refreshRate; } } /** Describes a monitor * * @author badlogic */ class Monitor { public final int virtualX; public final int virtualY; public final String name; protected Monitor (int virtualX, int virtualY, String name) { this.virtualX = virtualX; this.virtualY = virtualY; this.name = name; } } /** Class describing the bits per pixel, depth buffer precision, stencil precision and number of MSAA samples. */ class BufferFormat { /* number of bits per color channel */ public final int r, g, b, a; /* number of bits for depth and stencil buffer */ public final int depth, stencil; /** number of samples for multi-sample anti-aliasing (MSAA) **/ public final int samples; /** whether coverage sampling anti-aliasing is used. in that case you have to clear the coverage buffer as well! */ public final boolean coverageSampling; public BufferFormat (int r, int g, int b, int a, int depth, int stencil, int samples, boolean coverageSampling) { this.r = r; this.g = g; this.b = b; this.a = a; this.depth = depth; this.stencil = stencil; this.samples = samples; this.coverageSampling = coverageSampling; } public String toString () { return "r: " + r + ", g: " + g + ", b: " + b + ", a: " + a + ", depth: " + depth + ", stencil: " + stencil + ", num samples: " + samples + ", coverage sampling: " + coverageSampling; } } /** Returns whether OpenGL ES 3.0 is available. If it is you can get an instance of {@link GL30} via {@link #getGL30()} to * access OpenGL ES 3.0 functionality. Note that this functionality will only be available if you instructed the * {@link Application} instance to use OpenGL ES 3.0! * * @return whether OpenGL ES 3.0 is available */ boolean isGL30Available (); /** Returns whether OpenGL ES 3.1 is available. If it is you can get an instance of {@link GL31} via {@link #getGL31()} to * access OpenGL ES 3.1 functionality. Note that this functionality will only be available if you instructed the * {@link Application} instance to use OpenGL ES 3.1! * * @return whether OpenGL ES 3.1 is available */ boolean isGL31Available (); /** Returns whether OpenGL ES 3.2 is available. If it is you can get an instance of {@link GL32} via {@link #getGL32()} to * access OpenGL ES 3.2 functionality. Note that this functionality will only be available if you instructed the * {@link Application} instance to use OpenGL ES 3.2! * * @return whether OpenGL ES 3.2 is available */ boolean isGL32Available (); /** @return the {@link GL20} instance */ GL20 getGL20 (); /** @return the {@link GL30} instance or null if not supported */ GL30 getGL30 (); /** @return the {@link GL31} instance or null if not supported */ GL31 getGL31 (); /** @return the {@link GL32} instance or null if not supported */ GL32 getGL32 (); /** Set the GL20 instance **/ void setGL20 (GL20 gl20); /** Set the GL30 instance **/ void setGL30 (GL30 gl30); /** Set the GL31 instance **/ void setGL31 (GL31 gl31); /** Set the GL32 instance **/ void setGL32 (GL32 gl32); /** @return the width of the client area in logical pixels. */ int getWidth (); /** @return the height of the client area in logical pixels */ int getHeight (); /** @return the width of the framebuffer in physical pixels */ int getBackBufferWidth (); /** @return the height of the framebuffer in physical pixels */ int getBackBufferHeight (); /** @return amount of pixels per logical pixel (point) */ float getBackBufferScale (); /** @return the inset from the left which avoids display cutouts in logical pixels */ int getSafeInsetLeft (); /** @return the inset from the top which avoids display cutouts in logical pixels */ int getSafeInsetTop (); /** @return the inset from the bottom which avoids display cutouts or floating gesture bars, in logical pixels */ int getSafeInsetBottom (); /** @return the inset from the right which avoids display cutouts in logical pixels */ int getSafeInsetRight (); /** Returns the id of the current frame. The general contract of this method is that the id is incremented only when the * application is in the running state right before calling the {@link ApplicationListener#render()} method. Also, the id of * the first frame is 0; the id of subsequent frames is guaranteed to take increasing values for 2<sup>63</sup>-1 rendering * cycles. * @return the id of the current frame */ long getFrameId (); /** @return the time span between the current frame and the last frame in seconds. */ float getDeltaTime (); /** @return the time span between the current frame and the last frame in seconds, without smoothing * @deprecated use {@link #getDeltaTime()} instead. */ @Deprecated float getRawDeltaTime (); /** @return the average number of frames per second */ int getFramesPerSecond (); /** @return the {@link GraphicsType} of this Graphics instance */ GraphicsType getType (); /** @return the {@link GLVersion} of this Graphics instance */ GLVersion getGLVersion (); /** @return the pixels per inch on the x-axis */ float getPpiX (); /** @return the pixels per inch on the y-axis */ float getPpiY (); /** @return the pixels per centimeter on the x-axis */ float getPpcX (); /** @return the pixels per centimeter on the y-axis. */ float getPpcY (); /** This is a scaling factor for the Density Independent Pixel unit, following the same conventions as * android.util.DisplayMetrics#density, where one DIP is one pixel on an approximately 160 dpi screen. Thus on a 160dpi screen * this density value will be 1; on a 120 dpi screen it would be .75; etc. * * If the density could not be determined, this returns a default value of 1. * * Depending on the underlying platform implementation this might be a relatively expensive operation. Therefore it should not * be called continously on each frame. * * @return the Density Independent Pixel factor of the display. */ float getDensity (); /** Whether the given backend supports a display mode change via calling {@link Graphics#setFullscreenMode(DisplayMode)} * * @return whether display mode changes are supported or not. */ boolean supportsDisplayModeChange (); /** @return the primary monitor **/ Monitor getPrimaryMonitor (); /** @return the monitor the application's window is located on */ Monitor getMonitor (); /** @return the currently connected {@link Monitor}s */ Monitor[] getMonitors (); /** @return the supported fullscreen {@link DisplayMode}(s) of the monitor the window is on */ DisplayMode[] getDisplayModes (); /** @return the supported fullscreen {@link DisplayMode}s of the given {@link Monitor} */ DisplayMode[] getDisplayModes (Monitor monitor); /** @return the current {@link DisplayMode} of the monitor the window is on. */ DisplayMode getDisplayMode (); /** @return the current {@link DisplayMode} of the given {@link Monitor} */ DisplayMode getDisplayMode (Monitor monitor); /** Sets the window to full-screen mode. * * @param displayMode the display mode. * @return whether the operation succeeded. */ boolean setFullscreenMode (DisplayMode displayMode); /** Sets the window to windowed mode. * * @param width the width in pixels * @param height the height in pixels * @return whether the operation succeeded */ boolean setWindowedMode (int width, int height); /** Sets the title of the window. Ignored on Android. * * @param title the title. */ void setTitle (String title); /** Sets the window decoration as enabled or disabled. On Android, this will enable/disable the menu bar. * * Note that immediate behavior of this method may vary depending on the implementation. It may be necessary for the window to * be recreated in order for the changes to take effect. Consult the documentation for the backend in use for more information. * * Supported on all GDX desktop backends and on Android (to disable the menu bar). * * @param undecorated true if the window border or status bar should be hidden. false otherwise. */ void setUndecorated (boolean undecorated); /** Sets whether or not the window should be resizable. Ignored on Android. * * Note that immediate behavior of this method may vary depending on the implementation. It may be necessary for the window to * be recreated in order for the changes to take effect. Consult the documentation for the backend in use for more information. * * Supported on all GDX desktop backends. * * @param resizable */ void setResizable (boolean resizable); /** Enable/Disable vsynching. This is a best-effort attempt which might not work on all platforms. * * @param vsync vsync enabled or not. */ void setVSync (boolean vsync); /** Sets the target framerate for the application when using continuous rendering. Might not work on all platforms. Is not * generally advised to be used on mobile platforms. * * @param fps the targeted fps; default differs by platform */ public void setForegroundFPS (int fps); /** @return the format of the color, depth and stencil buffer in a {@link BufferFormat} instance */ BufferFormat getBufferFormat (); /** @param extension the extension name * @return whether the extension is supported */ boolean supportsExtension (String extension); /** Sets whether to render continuously. In case rendering is performed non-continuously, the following events will trigger a * redraw: * * <ul> * <li>A call to {@link #requestRendering()}</li> * <li>Input events from the touch screen/mouse or keyboard</li> * <li>A {@link Runnable} is posted to the rendering thread via {@link Application#postRunnable(Runnable)}. In the case of a * multi-window app, all windows will request rendering if a runnable is posted to the application. To avoid this, post a * runnable to the window instead.</li> * </ul> * * Life-cycle events will also be reported as usual, see {@link ApplicationListener}. This method can be called from any * thread. * * @param isContinuous whether the rendering should be continuous or not. */ void setContinuousRendering (boolean isContinuous); /** @return whether rendering is continuous. */ boolean isContinuousRendering (); /** Requests a new frame to be rendered if the rendering mode is non-continuous. This method can be called from any thread. */ void requestRendering (); /** Whether the app is fullscreen or not */ boolean isFullscreen (); /** Create a new cursor represented by the {@link com.badlogic.gdx.graphics.Pixmap}. The Pixmap must be in RGBA8888 format, * width & height must be powers-of-two greater than zero (not necessarily equal) and of a certain minimum size (32x32 is a * safe bet), and alpha transparency must be single-bit (i.e., 0x00 or 0xFF only). This function returns a Cursor object that * can be set as the system cursor by calling {@link #setCursor(Cursor)} . * * @param pixmap the mouse cursor image as a {@link com.badlogic.gdx.graphics.Pixmap} * @param xHotspot the x location of the hotspot pixel within the cursor image (origin top-left corner) * @param yHotspot the y location of the hotspot pixel within the cursor image (origin top-left corner) * @return a cursor object that can be used by calling {@link #setCursor(Cursor)} or null if not supported */ Cursor newCursor (Pixmap pixmap, int xHotspot, int yHotspot); /** Only viable on the lwjgl-backend and on the gwt-backend. Browsers that support cursor:url() and support the png format (the * pixmap is converted to a data-url of type image/png) should also support custom cursors. Will set the mouse cursor image to * the image represented by the {@link com.badlogic.gdx.graphics.Cursor}. It is recommended to call this function in the main * render thread, and maximum one time per frame. * * @param cursor the mouse cursor as a {@link com.badlogic.gdx.graphics.Cursor} */ void setCursor (Cursor cursor); /** Sets one of the predefined {@link SystemCursor}s */ void setSystemCursor (SystemCursor systemCursor); }
tommyettinger/libgdx
gdx/src/com/badlogic/gdx/Graphics.java
263
/* * 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 crtp; import lombok.Data; import lombok.extern.slf4j.Slf4j; /** * MmaFighter class. * * @param <T> MmaFighter derived class that uses itself as type parameter. */ @Slf4j @Data public class MmaFighter<T extends MmaFighter<T>> implements Fighter<T> { private final String name; private final String surname; private final String nickName; private final String speciality; @Override public void fight(T opponent) { LOGGER.info("{} is going to fight against {}", this, opponent); } }
sarvex/java-design-patterns
crtp/src/main/java/crtp/MmaFighter.java
264
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx; import java.io.InputStream; import java.io.OutputStream; import java.util.HashMap; import java.util.List; import java.util.Map; import com.badlogic.gdx.Application.ApplicationType; import com.badlogic.gdx.net.HttpRequestHeader; import com.badlogic.gdx.net.HttpResponseHeader; import com.badlogic.gdx.net.HttpStatus; import com.badlogic.gdx.net.ServerSocket; import com.badlogic.gdx.net.ServerSocketHints; import com.badlogic.gdx.net.Socket; import com.badlogic.gdx.net.SocketHints; import com.badlogic.gdx.utils.GdxRuntimeException; import com.badlogic.gdx.utils.Null; import com.badlogic.gdx.utils.Pool.Poolable; /** Provides methods to perform networking operations, such as simple HTTP get and post requests, and TCP server/client socket * communication. * </p> * * To perform an HTTP request create a {@link HttpRequest} with the HTTP method (see {@link HttpMethods} for common methods) and * invoke {@link #sendHttpRequest(HttpRequest, HttpResponseListener)} with it and a {@link HttpResponseListener}. After the HTTP * request was processed, the {@link HttpResponseListener} is called with a {@link HttpResponse} with the HTTP response values and * an status code to determine if the request was successful or not. * </p> * * To create a TCP client socket to communicate with a remote TCP server, invoke the * {@link #newClientSocket(Protocol, String, int, SocketHints)} method. The returned {@link Socket} offers an {@link InputStream} * and {@link OutputStream} to communicate with the end point. * </p> * * To create a TCP server socket that waits for incoming connections, invoke the * {@link #newServerSocket(Protocol, int, ServerSocketHints)} method. The returned {@link ServerSocket} offers an * {@link ServerSocket#accept(SocketHints options)} method that waits for an incoming connection. * * @author mzechner * @author noblemaster * @author arielsan */ public interface Net { /** HTTP response interface with methods to get the response data as a byte[], a {@link String} or an {@link InputStream}. */ public static interface HttpResponse { /** Returns the data of the HTTP response as a byte[]. * <p> * <b>Note</b>: This method may only be called once per response. * </p> * @return the result as a byte[] or null in case of a timeout or if the operation was canceled/terminated abnormally. The * timeout is specified when creating the HTTP request, with {@link HttpRequest#setTimeOut(int)} */ byte[] getResult (); /** Returns the data of the HTTP response as a {@link String}. * <p> * <b>Note</b>: This method may only be called once per response. * </p> * @return the result as a string or null in case of a timeout or if the operation was canceled/terminated abnormally. The * timeout is specified when creating the HTTP request, with {@link HttpRequest#setTimeOut(int)} */ String getResultAsString (); /** Returns the data of the HTTP response as an {@link InputStream}. <b><br> * Warning:</b> Do not store a reference to this InputStream outside of * {@link HttpResponseListener#handleHttpResponse(HttpResponse)}. The underlying HTTP connection will be closed after that * callback finishes executing. Reading from the InputStream after it's connection has been closed will lead to exception. * @return An {@link InputStream} with the {@link HttpResponse} data. */ InputStream getResultAsStream (); /** Returns the {@link HttpStatus} containing the statusCode of the HTTP response. */ HttpStatus getStatus (); /** Returns the value of the header with the given name as a {@link String}, or null if the header is not set. See * {@link HttpResponseHeader}. */ String getHeader (String name); /** Returns a Map of the headers. The keys are Strings that represent the header name. Each values is a List of Strings that * represent the corresponding header values. See {@link HttpResponseHeader}. */ Map<String, List<String>> getHeaders (); } /** Provides common HTTP methods to use when creating a {@link HttpRequest}. * <ul> * <li><b>HEAD</b> Asks for a response identical to that of a GET request but without the response body.</li> * <li><b>GET</b> requests a representation of the specified resource. Requests using GET should only retrieve data.</li> * <li><b>POST</b> is used to submit an entity to the specified resource, often causing a change in state or side effects on * the server.</li> * <li><b>PUT</b> replaces all current representations of the target resource with the request payload.</li> * <li><b>PATCH</b> method is used to apply partial modifications to a resource.</li> * <li><b>DELETE</b> deletes the specified resource.</li> * </ul> */ public static interface HttpMethods { /** The HEAD method asks for a response identical to that of a GET request, but without the response body. **/ public static final String HEAD = "HEAD"; /** The GET method requests a representation of the specified resource. Requests using GET should only retrieve data. **/ public static final String GET = "GET"; /** The POST method is used to submit an entity to the specified resource, often causing a change in state or side effects * on the server. **/ public static final String POST = "POST"; /** The PUT method replaces all current representations of the target resource with the request payload. **/ public static final String PUT = "PUT"; /** The PATCH method is used to apply partial modifications to a resource. **/ public static final String PATCH = "PATCH"; /** The DELETE method deletes the specified resource. **/ public static final String DELETE = "DELETE"; } /** Contains getters and setters for the following parameters: * <ul> * <li><strong>httpMethod:</strong> GET or POST are most common, can use {@link Net.HttpMethods HttpMethods} for static * references</li> * <li><strong>url:</strong> the url</li> * <li><strong>headers:</strong> a map of the headers, setter can be called multiple times</li> * <li><strong>timeout:</strong> time spent trying to connect before giving up</li> * <li><strong>content:</strong> A string containing the data to be used when processing the HTTP request.</li> * </ul> * * Abstracts the concept of a HTTP Request: * * <pre> * Map<String, String> parameters = new HashMap<String, String>(); * parameters.put("user", "myuser"); * * HttpRequest httpGet = new HttpRequest(HttpMethods.Get); * httpGet.setUrl("http://somewhere.net"); * httpGet.setContent(HttpParametersUtils.convertHttpParameters(parameters)); * ... * Gdx.net.sendHttpRequest (httpGet, new HttpResponseListener() { * public void handleHttpResponse(HttpResponse httpResponse) { * status = httpResponse.getResultAsString(); * //do stuff here based on response * } * * public void failed(Throwable t) { * status = "failed"; * //do stuff here based on the failed attempt * } * }); * </pre> */ public static class HttpRequest implements Poolable { private String httpMethod; private String url; private Map<String, String> headers; private int timeOut = 0; private String content; private InputStream contentStream; private long contentLength; private boolean followRedirects = true; private boolean includeCredentials = false; public HttpRequest () { this.headers = new HashMap<String, String>(); } /** Creates a new HTTP request with the specified HTTP method, see {@link HttpMethods}. * @param httpMethod This is the HTTP method for the request, see {@link HttpMethods} */ public HttpRequest (String httpMethod) { this(); this.httpMethod = httpMethod; } /** Sets the URL of the HTTP request. * @param url The URL to set. */ public void setUrl (String url) { this.url = url; } /** Sets a header to this HTTP request, see {@link HttpRequestHeader}. * @param name the name of the header. * @param value the value of the header. */ public void setHeader (String name, String value) { headers.put(name, value); } /** Sets the content to be used in the HTTP request. * @param content A string encoded in the corresponding Content-Encoding set in the headers, with the data to send with the * HTTP request. For example, in case of HTTP GET, the content is used as the query string of the GET while on a * HTTP POST it is used to send the POST data. */ public void setContent (String content) { this.content = content; } /** Sets the content as a stream to be used for a POST for example, to transmit custom data. * @param contentStream The stream with the content data. */ public void setContent (InputStream contentStream, long contentLength) { this.contentStream = contentStream; this.contentLength = contentLength; } /** Sets the time to wait for the HTTP request to be processed, use 0 block until it is done. The timeout is used for both * the timeout when establishing TCP connection, and the timeout until the first byte of data is received. * @param timeOut the number of milliseconds to wait before giving up, 0 or negative to block until the operation is done */ public void setTimeOut (int timeOut) { this.timeOut = timeOut; } /** Sets whether 301 and 302 redirects are followed. By default true. Can't be changed in the GWT backend because this uses * XmlHttpRequests which always redirect. * @param followRedirects whether to follow redirects. * @exception IllegalArgumentException if redirection is disabled on the GWT backend. */ public void setFollowRedirects (boolean followRedirects) throws IllegalArgumentException { if (followRedirects || Gdx.app.getType() != ApplicationType.WebGL) { this.followRedirects = followRedirects; } else { throw new IllegalArgumentException("Following redirects can't be disabled using the GWT/WebGL backend!"); } } /** Sets whether a cross-origin request will include credentials. Only used on GWT backend to allow cross-origin requests to * include credentials such as cookies, authorization headers, etc... */ public void setIncludeCredentials (boolean includeCredentials) { this.includeCredentials = includeCredentials; } /** Sets the HTTP method of the HttpRequest. */ public void setMethod (String httpMethod) { this.httpMethod = httpMethod; } /** Returns the timeOut of the HTTP request. * @return the timeOut. */ public int getTimeOut () { return timeOut; } /** Returns the HTTP method of the HttpRequest. */ public String getMethod () { return httpMethod; } /** Returns the URL of the HTTP request. */ public String getUrl () { return url; } /** Returns the content string to be used for the HTTP request. */ public String getContent () { return content; } /** Returns the content stream. */ public InputStream getContentStream () { return contentStream; } /** Returns the content length in case content is a stream. */ public long getContentLength () { return contentLength; } /** Returns a Map<String, String> with the headers of the HTTP request. */ public Map<String, String> getHeaders () { return headers; } /** Returns whether 301 and 302 redirects are followed. By default true. Whether to follow redirects. */ public boolean getFollowRedirects () { return followRedirects; } /** Returns whether a cross-origin request will include credentials. By default false. */ public boolean getIncludeCredentials () { return includeCredentials; } @Override public void reset () { httpMethod = null; url = null; headers.clear(); timeOut = 0; content = null; contentStream = null; contentLength = 0; followRedirects = true; } } /** Listener to be able to do custom logic once the {@link HttpResponse} is ready to be processed, register it with * {@link Net#sendHttpRequest(HttpRequest, HttpResponseListener)}. */ public static interface HttpResponseListener { /** Called when the {@link HttpRequest} has been processed and there is a {@link HttpResponse} ready. Passing data to the * rendering thread should be done using {@link Application#postRunnable(java.lang.Runnable runnable)} {@link HttpResponse} * contains the {@link HttpStatus} and should be used to determine if the request was successful or not (see more info at * {@link HttpStatus#getStatusCode()}). For example: * * <pre> * HttpResponseListener listener = new HttpResponseListener() { * public void handleHttpResponse (HttpResponse httpResponse) { * HttpStatus status = httpResponse.getStatus(); * if (status.getStatusCode() >= 200 && status.getStatusCode() < 300) { * // it was successful * } else { * // do something else * } * } * } * </pre> * * @param httpResponse The {@link HttpResponse} with the HTTP response values. */ void handleHttpResponse (HttpResponse httpResponse); /** Called if the {@link HttpRequest} failed because an exception when processing the HTTP request, could be a timeout any * other reason (not an HTTP error). * @param t If the HTTP request failed because an Exception, t encapsulates it to give more information. */ void failed (Throwable t); void cancelled (); } /** Process the specified {@link HttpRequest} and reports the {@link HttpResponse} to the specified * {@link HttpResponseListener}. * @param httpRequest The {@link HttpRequest} to be performed. * @param httpResponseListener The {@link HttpResponseListener} to call once the HTTP response is ready to be processed. Could * be null, in that case no listener is called. */ public void sendHttpRequest (HttpRequest httpRequest, @Null HttpResponseListener httpResponseListener); public void cancelHttpRequest (HttpRequest httpRequest); public boolean isHttpRequestPending (HttpRequest httpRequest); /** Protocol used by {@link Net#newServerSocket(Protocol, int, ServerSocketHints)} and * {@link Net#newClientSocket(Protocol, String, int, SocketHints)}. * @author mzechner */ public enum Protocol { TCP } /** Creates a new server socket on the given address and port, using the given {@link Protocol}, waiting for incoming * connections. * * @param hostname the hostname or ip address to bind the socket to * @param port the port to listen on * @param hints additional {@link ServerSocketHints} used to create the socket. Input null to use the default setting provided * by the system. * @return the {@link ServerSocket} * @throws GdxRuntimeException in case the socket couldn't be opened */ public ServerSocket newServerSocket (Protocol protocol, String hostname, int port, ServerSocketHints hints); /** Creates a new server socket on the given port, using the given {@link Protocol}, waiting for incoming connections. * * @param port the port to listen on * @param hints additional {@link ServerSocketHints} used to create the socket. Input null to use the default setting provided * by the system. * @return the {@link ServerSocket} * @throws GdxRuntimeException in case the socket couldn't be opened */ public ServerSocket newServerSocket (Protocol protocol, int port, ServerSocketHints hints); /** Creates a new TCP client socket that connects to the given host and port. * * @param host the host address * @param port the port * @param hints additional {@link SocketHints} used to create the socket. Input null to use the default setting provided by the * system. * @throws GdxRuntimeException in case the socket couldn't be opened */ public Socket newClientSocket (Protocol protocol, String host, int port, SocketHints hints); /** Launches the default browser to display a URI. If the default browser is not able to handle the specified URI, the * application registered for handling URIs of the specified type is invoked. The application is determined from the protocol * and path of the URI. A best effort is made to open the given URI; however, since external applications are involved, no * guarantee can be made as to whether the URI was actually opened. If it is known that the URI was not opened, false will be * returned; otherwise, true will be returned. * * @param URI the URI to be opened. * @return false if it is known the uri was not opened, true otherwise. */ public boolean openURI (String URI); }
tommyettinger/libgdx
gdx/src/com/badlogic/gdx/Net.java
265
/* * 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. */ /** * Interface without any methods Marker interface is based on that assumption. */ public interface Permission { }
smedals/java-design-patterns
marker/src/main/java/Permission.java
266
/* * 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 crtp; /** * MmaLightweightFighter class. */ class MmaLightweightFighter extends MmaFighter<MmaLightweightFighter> { public MmaLightweightFighter(String name, String surname, String nickName, String speciality) { super(name, surname, nickName, speciality); } }
sarvex/java-design-patterns
crtp/src/main/java/crtp/MmaLightweightFighter.java
267
/* * 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 crtp; /** * MmaHeavyweightFighter. */ public class MmaHeavyweightFighter extends MmaFighter<MmaHeavyweightFighter> { public MmaHeavyweightFighter(String name, String surname, String nickName, String speciality) { super(name, surname, nickName, speciality); } }
sarvex/java-design-patterns
crtp/src/main/java/crtp/MmaHeavyweightFighter.java
268
/* * 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
269
/* * 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.monad; /** * Enumeration of Types of Sex. */ public enum Sex { MALE, FEMALE }
smedals/java-design-patterns
monad/src/main/java/com/iluwatar/monad/Sex.java
270
/* * 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 units; import abstractextensions.UnitExtension; import lombok.Getter; import lombok.Setter; /** * Class defining Unit, other units will extend this class. */ @Setter @Getter public class Unit { private String name; protected UnitExtension unitExtension = null; public Unit(String name) { this.name = name; } public UnitExtension getUnitExtension(String extensionName) { return null; } }
smedals/java-design-patterns
extension-objects/src/main/java/units/Unit.java
271
/* * 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.dao; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.Setter; import lombok.ToString; /** * A customer POJO that represents the data that will be read from the data source. */ @Setter @Getter @ToString @EqualsAndHashCode(onlyExplicitlyIncluded = true) @AllArgsConstructor public class Customer { @EqualsAndHashCode.Include private int id; private String firstName; private String lastName; }
smedals/java-design-patterns
dao/src/main/java/com/iluwatar/dao/Customer.java
272
/* * 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.state; /** * State interface. */ public interface State { void onEnterState(); void observe(); }
smedals/java-design-patterns
state/src/main/java/com/iluwatar/state/State.java
273
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx; import com.badlogic.gdx.input.NativeInputConfiguration; import com.badlogic.gdx.utils.ObjectIntMap; /** * <p> * Interface to the input facilities. This allows polling the state of the keyboard, the touch screen and the accelerometer. On * some backends (desktop, gwt, etc) the touch screen is replaced by mouse input. The accelerometer is of course not available on * all backends. * </p> * * <p> * Instead of polling for events, one can process all input events with an {@link InputProcessor}. You can set the InputProcessor * via the {@link #setInputProcessor(InputProcessor)} method. It will be called before the {@link ApplicationListener#render()} * method in each frame. * </p> * * <p> * Keyboard keys are translated to the constants in {@link Keys} transparently on all systems. Do not use system specific key * constants. * </p> * * <p> * The class also offers methods to use (and test for the presence of) other input systems like vibration, compass, on-screen * keyboards, and cursor capture. Support for simple input dialogs is also provided. * </p> * * @author mzechner */ public interface Input { /** Callback interface for {@link Input#getTextInput(TextInputListener, String, String, String)} * * @author mzechner */ static public interface TextInputListener { public void input (String text); public void canceled (); } /** Mouse buttons. * @author mzechner */ static public class Buttons { public static final int LEFT = 0; public static final int RIGHT = 1; public static final int MIDDLE = 2; public static final int BACK = 3; public static final int FORWARD = 4; } /** Keys. * * @author mzechner */ static public class Keys { public static final int ANY_KEY = -1; public static final int NUM_0 = 7; public static final int NUM_1 = 8; public static final int NUM_2 = 9; public static final int NUM_3 = 10; public static final int NUM_4 = 11; public static final int NUM_5 = 12; public static final int NUM_6 = 13; public static final int NUM_7 = 14; public static final int NUM_8 = 15; public static final int NUM_9 = 16; public static final int A = 29; public static final int ALT_LEFT = 57; public static final int ALT_RIGHT = 58; public static final int APOSTROPHE = 75; public static final int AT = 77; public static final int B = 30; public static final int BACK = 4; public static final int BACKSLASH = 73; public static final int C = 31; public static final int CALL = 5; public static final int CAMERA = 27; public static final int CAPS_LOCK = 115; public static final int CLEAR = 28; public static final int COMMA = 55; public static final int D = 32; public static final int DEL = 67; public static final int BACKSPACE = 67; public static final int FORWARD_DEL = 112; public static final int DPAD_CENTER = 23; public static final int DPAD_DOWN = 20; public static final int DPAD_LEFT = 21; public static final int DPAD_RIGHT = 22; public static final int DPAD_UP = 19; public static final int CENTER = 23; public static final int DOWN = 20; public static final int LEFT = 21; public static final int RIGHT = 22; public static final int UP = 19; public static final int E = 33; public static final int ENDCALL = 6; public static final int ENTER = 66; public static final int ENVELOPE = 65; public static final int EQUALS = 70; public static final int EXPLORER = 64; public static final int F = 34; public static final int FOCUS = 80; public static final int G = 35; public static final int GRAVE = 68; public static final int H = 36; public static final int HEADSETHOOK = 79; public static final int HOME = 3; public static final int I = 37; public static final int J = 38; public static final int K = 39; public static final int L = 40; public static final int LEFT_BRACKET = 71; public static final int M = 41; public static final int MEDIA_FAST_FORWARD = 90; public static final int MEDIA_NEXT = 87; public static final int MEDIA_PLAY_PAUSE = 85; public static final int MEDIA_PREVIOUS = 88; public static final int MEDIA_REWIND = 89; public static final int MEDIA_STOP = 86; public static final int MENU = 82; public static final int MINUS = 69; public static final int MUTE = 91; public static final int N = 42; public static final int NOTIFICATION = 83; public static final int NUM = 78; public static final int O = 43; public static final int P = 44; public static final int PAUSE = 121; // aka break public static final int PERIOD = 56; public static final int PLUS = 81; public static final int POUND = 18; public static final int POWER = 26; public static final int PRINT_SCREEN = 120; // aka SYSRQ public static final int Q = 45; public static final int R = 46; public static final int RIGHT_BRACKET = 72; public static final int S = 47; public static final int SCROLL_LOCK = 116; public static final int SEARCH = 84; public static final int SEMICOLON = 74; public static final int SHIFT_LEFT = 59; public static final int SHIFT_RIGHT = 60; public static final int SLASH = 76; public static final int SOFT_LEFT = 1; public static final int SOFT_RIGHT = 2; public static final int SPACE = 62; public static final int STAR = 17; public static final int SYM = 63; // on MacOS, this is Command (⌘) public static final int T = 48; public static final int TAB = 61; public static final int U = 49; public static final int UNKNOWN = 0; public static final int V = 50; public static final int VOLUME_DOWN = 25; public static final int VOLUME_UP = 24; public static final int W = 51; public static final int X = 52; public static final int Y = 53; public static final int Z = 54; public static final int META_ALT_LEFT_ON = 16; public static final int META_ALT_ON = 2; public static final int META_ALT_RIGHT_ON = 32; public static final int META_SHIFT_LEFT_ON = 64; public static final int META_SHIFT_ON = 1; public static final int META_SHIFT_RIGHT_ON = 128; public static final int META_SYM_ON = 4; public static final int CONTROL_LEFT = 129; public static final int CONTROL_RIGHT = 130; public static final int ESCAPE = 111; public static final int END = 123; public static final int INSERT = 124; public static final int PAGE_UP = 92; public static final int PAGE_DOWN = 93; public static final int PICTSYMBOLS = 94; public static final int SWITCH_CHARSET = 95; public static final int BUTTON_CIRCLE = 255; public static final int BUTTON_A = 96; public static final int BUTTON_B = 97; public static final int BUTTON_C = 98; public static final int BUTTON_X = 99; public static final int BUTTON_Y = 100; public static final int BUTTON_Z = 101; public static final int BUTTON_L1 = 102; public static final int BUTTON_R1 = 103; public static final int BUTTON_L2 = 104; public static final int BUTTON_R2 = 105; public static final int BUTTON_THUMBL = 106; public static final int BUTTON_THUMBR = 107; public static final int BUTTON_START = 108; public static final int BUTTON_SELECT = 109; public static final int BUTTON_MODE = 110; public static final int NUMPAD_0 = 144; public static final int NUMPAD_1 = 145; public static final int NUMPAD_2 = 146; public static final int NUMPAD_3 = 147; public static final int NUMPAD_4 = 148; public static final int NUMPAD_5 = 149; public static final int NUMPAD_6 = 150; public static final int NUMPAD_7 = 151; public static final int NUMPAD_8 = 152; public static final int NUMPAD_9 = 153; public static final int NUMPAD_DIVIDE = 154; public static final int NUMPAD_MULTIPLY = 155; public static final int NUMPAD_SUBTRACT = 156; public static final int NUMPAD_ADD = 157; public static final int NUMPAD_DOT = 158; public static final int NUMPAD_COMMA = 159; public static final int NUMPAD_ENTER = 160; public static final int NUMPAD_EQUALS = 161; public static final int NUMPAD_LEFT_PAREN = 162; public static final int NUMPAD_RIGHT_PAREN = 163; public static final int NUM_LOCK = 143; // public static final int BACKTICK = 0; // public static final int TILDE = 0; // public static final int UNDERSCORE = 0; // public static final int DOT = 0; // public static final int BREAK = 0; // public static final int PIPE = 0; // public static final int EXCLAMATION = 0; // public static final int QUESTIONMARK = 0; // ` | VK_BACKTICK // ~ | VK_TILDE // : | VK_COLON // _ | VK_UNDERSCORE // . | VK_DOT // (break) | VK_BREAK // | | VK_PIPE // ! | VK_EXCLAMATION // ? | VK_QUESTION public static final int COLON = 243; public static final int F1 = 131; public static final int F2 = 132; public static final int F3 = 133; public static final int F4 = 134; public static final int F5 = 135; public static final int F6 = 136; public static final int F7 = 137; public static final int F8 = 138; public static final int F9 = 139; public static final int F10 = 140; public static final int F11 = 141; public static final int F12 = 142; public static final int F13 = 183; public static final int F14 = 184; public static final int F15 = 185; public static final int F16 = 186; public static final int F17 = 187; public static final int F18 = 188; public static final int F19 = 189; public static final int F20 = 190; public static final int F21 = 191; public static final int F22 = 192; public static final int F23 = 193; public static final int F24 = 194; public static final int MAX_KEYCODE = 255; /** @return a human readable representation of the keycode. The returned value can be used in * {@link Input.Keys#valueOf(String)} */ public static String toString (int keycode) { if (keycode < 0) throw new IllegalArgumentException("keycode cannot be negative, keycode: " + keycode); if (keycode > MAX_KEYCODE) throw new IllegalArgumentException("keycode cannot be greater than 255, keycode: " + keycode); switch (keycode) { // META* variables should not be used with this method. case UNKNOWN: return "Unknown"; case SOFT_LEFT: return "Soft Left"; case SOFT_RIGHT: return "Soft Right"; case HOME: return "Home"; case BACK: return "Back"; case CALL: return "Call"; case ENDCALL: return "End Call"; case NUM_0: return "0"; case NUM_1: return "1"; case NUM_2: return "2"; case NUM_3: return "3"; case NUM_4: return "4"; case NUM_5: return "5"; case NUM_6: return "6"; case NUM_7: return "7"; case NUM_8: return "8"; case NUM_9: return "9"; case STAR: return "*"; case POUND: return "#"; case UP: return "Up"; case DOWN: return "Down"; case LEFT: return "Left"; case RIGHT: return "Right"; case CENTER: return "Center"; case VOLUME_UP: return "Volume Up"; case VOLUME_DOWN: return "Volume Down"; case POWER: return "Power"; case CAMERA: return "Camera"; case CLEAR: return "Clear"; case A: return "A"; case B: return "B"; case C: return "C"; case D: return "D"; case E: return "E"; case F: return "F"; case G: return "G"; case H: return "H"; case I: return "I"; case J: return "J"; case K: return "K"; case L: return "L"; case M: return "M"; case N: return "N"; case O: return "O"; case P: return "P"; case Q: return "Q"; case R: return "R"; case S: return "S"; case T: return "T"; case U: return "U"; case V: return "V"; case W: return "W"; case X: return "X"; case Y: return "Y"; case Z: return "Z"; case COMMA: return ","; case PERIOD: return "."; case ALT_LEFT: return "L-Alt"; case ALT_RIGHT: return "R-Alt"; case SHIFT_LEFT: return "L-Shift"; case SHIFT_RIGHT: return "R-Shift"; case TAB: return "Tab"; case SPACE: return "Space"; case SYM: return "SYM"; case EXPLORER: return "Explorer"; case ENVELOPE: return "Envelope"; case ENTER: return "Enter"; case DEL: return "Delete"; // also BACKSPACE case GRAVE: return "`"; case MINUS: return "-"; case EQUALS: return "="; case LEFT_BRACKET: return "["; case RIGHT_BRACKET: return "]"; case BACKSLASH: return "\\"; case SEMICOLON: return ";"; case APOSTROPHE: return "'"; case SLASH: return "/"; case AT: return "@"; case NUM: return "Num"; case HEADSETHOOK: return "Headset Hook"; case FOCUS: return "Focus"; case PLUS: return "Plus"; case MENU: return "Menu"; case NOTIFICATION: return "Notification"; case SEARCH: return "Search"; case MEDIA_PLAY_PAUSE: return "Play/Pause"; case MEDIA_STOP: return "Stop Media"; case MEDIA_NEXT: return "Next Media"; case MEDIA_PREVIOUS: return "Prev Media"; case MEDIA_REWIND: return "Rewind"; case MEDIA_FAST_FORWARD: return "Fast Forward"; case MUTE: return "Mute"; case PAGE_UP: return "Page Up"; case PAGE_DOWN: return "Page Down"; case PICTSYMBOLS: return "PICTSYMBOLS"; case SWITCH_CHARSET: return "SWITCH_CHARSET"; case BUTTON_A: return "A Button"; case BUTTON_B: return "B Button"; case BUTTON_C: return "C Button"; case BUTTON_X: return "X Button"; case BUTTON_Y: return "Y Button"; case BUTTON_Z: return "Z Button"; case BUTTON_L1: return "L1 Button"; case BUTTON_R1: return "R1 Button"; case BUTTON_L2: return "L2 Button"; case BUTTON_R2: return "R2 Button"; case BUTTON_THUMBL: return "Left Thumb"; case BUTTON_THUMBR: return "Right Thumb"; case BUTTON_START: return "Start"; case BUTTON_SELECT: return "Select"; case BUTTON_MODE: return "Button Mode"; case FORWARD_DEL: return "Forward Delete"; case CONTROL_LEFT: return "L-Ctrl"; case CONTROL_RIGHT: return "R-Ctrl"; case ESCAPE: return "Escape"; case END: return "End"; case INSERT: return "Insert"; case NUMPAD_0: return "Numpad 0"; case NUMPAD_1: return "Numpad 1"; case NUMPAD_2: return "Numpad 2"; case NUMPAD_3: return "Numpad 3"; case NUMPAD_4: return "Numpad 4"; case NUMPAD_5: return "Numpad 5"; case NUMPAD_6: return "Numpad 6"; case NUMPAD_7: return "Numpad 7"; case NUMPAD_8: return "Numpad 8"; case NUMPAD_9: return "Numpad 9"; case COLON: return ":"; case F1: return "F1"; case F2: return "F2"; case F3: return "F3"; case F4: return "F4"; case F5: return "F5"; case F6: return "F6"; case F7: return "F7"; case F8: return "F8"; case F9: return "F9"; case F10: return "F10"; case F11: return "F11"; case F12: return "F12"; case F13: return "F13"; case F14: return "F14"; case F15: return "F15"; case F16: return "F16"; case F17: return "F17"; case F18: return "F18"; case F19: return "F19"; case F20: return "F20"; case F21: return "F21"; case F22: return "F22"; case F23: return "F23"; case F24: return "F24"; case NUMPAD_DIVIDE: return "Num /"; case NUMPAD_MULTIPLY: return "Num *"; case NUMPAD_SUBTRACT: return "Num -"; case NUMPAD_ADD: return "Num +"; case NUMPAD_DOT: return "Num ."; case NUMPAD_COMMA: return "Num ,"; case NUMPAD_ENTER: return "Num Enter"; case NUMPAD_EQUALS: return "Num ="; case NUMPAD_LEFT_PAREN: return "Num ("; case NUMPAD_RIGHT_PAREN: return "Num )"; case NUM_LOCK: return "Num Lock"; case CAPS_LOCK: return "Caps Lock"; case SCROLL_LOCK: return "Scroll Lock"; case PAUSE: return "Pause"; case PRINT_SCREEN: return "Print"; // BUTTON_CIRCLE unhandled, as it conflicts with the more likely to be pressed F12 default: // key name not found return null; } } private static ObjectIntMap<String> keyNames; /** @param keyname the keyname returned by the {@link Keys#toString(int)} method * @return the int keycode */ public static int valueOf (String keyname) { if (keyNames == null) initializeKeyNames(); return keyNames.get(keyname, -1); } /** lazily intialized in {@link Keys#valueOf(String)} */ private static void initializeKeyNames () { keyNames = new ObjectIntMap<String>(); for (int i = 0; i < 256; i++) { String name = toString(i); if (name != null) keyNames.put(name, i); } } } /** Enumeration of potentially available peripherals. Use with {@link Input#isPeripheralAvailable(Peripheral)}. * @author mzechner */ public enum Peripheral { HardwareKeyboard, OnscreenKeyboard, MultitouchScreen, Accelerometer, Compass, Vibrator, HapticFeedback, Gyroscope, RotationVector, Pressure } /** @return The acceleration force in m/s^2 applied to the device in the X axis, including the force of gravity */ public float getAccelerometerX (); /** @return The acceleration force in m/s^2 applied to the device in the Y axis, including the force of gravity */ public float getAccelerometerY (); /** @return The acceleration force in m/s^2 applied to the device in the Z axis, including the force of gravity */ public float getAccelerometerZ (); /** @return The rate of rotation in rad/s around the X axis */ public float getGyroscopeX (); /** @return The rate of rotation in rad/s around the Y axis */ public float getGyroscopeY (); /** @return The rate of rotation in rad/s around the Z axis */ public float getGyroscopeZ (); /** @return The maximum number of pointers supported */ public int getMaxPointers (); /** @return The x coordinate of the last touch on touch screen devices and the current mouse position on desktop for the first * pointer in screen coordinates. The screen origin is the top left corner. */ public int getX (); /** Returns the x coordinate in screen coordinates of the given pointer. Pointers are indexed from 0 to n. The pointer id * identifies the order in which the fingers went down on the screen, e.g. 0 is the first finger, 1 is the second and so on. * When two fingers are touched down and the first one is lifted the second one keeps its index. If another finger is placed on * the touch screen the first free index will be used. * * @param pointer the pointer id. * @return the x coordinate */ public int getX (int pointer); /** @return the different between the current pointer location and the last pointer location on the x-axis. */ public int getDeltaX (); /** @return the different between the current pointer location and the last pointer location on the x-axis. */ public int getDeltaX (int pointer); /** @return The y coordinate of the last touch on touch screen devices and the current mouse position on desktop for the first * pointer in screen coordinates. The screen origin is the top left corner. */ public int getY (); /** Returns the y coordinate in screen coordinates of the given pointer. Pointers are indexed from 0 to n. The pointer id * identifies the order in which the fingers went down on the screen, e.g. 0 is the first finger, 1 is the second and so on. * When two fingers are touched down and the first one is lifted the second one keeps its index. If another finger is placed on * the touch screen the first free index will be used. * * @param pointer the pointer id. * @return the y coordinate */ public int getY (int pointer); /** @return the different between the current pointer location and the last pointer location on the y-axis. */ public int getDeltaY (); /** @return the different between the current pointer location and the last pointer location on the y-axis. */ public int getDeltaY (int pointer); /** @return whether the screen is currently touched. */ public boolean isTouched (); /** @return whether a new touch down event just occurred. */ public boolean justTouched (); /** Whether the screen is currently touched by the pointer with the given index. Pointers are indexed from 0 to n. The pointer * id identifies the order in which the fingers went down on the screen, e.g. 0 is the first finger, 1 is the second and so on. * When two fingers are touched down and the first one is lifted the second one keeps its index. If another finger is placed on * the touch screen the first free index will be used. * * @param pointer the pointer * @return whether the screen is touched by the pointer */ public boolean isTouched (int pointer); /** @return the pressure of the first pointer */ public float getPressure (); /** Returns the pressure of the given pointer, where 0 is untouched. On Android it should be up to 1.0, but it can go above * that slightly and its not consistent between devices. On iOS 1.0 is the normal touch and significantly more of hard touch. * Check relevant manufacturer documentation for details. Check availability with * {@link Input#isPeripheralAvailable(Peripheral)}. If not supported, returns 1.0 when touched. * * @param pointer the pointer id. * @return the pressure */ public float getPressure (int pointer); /** Whether a given button is pressed or not. Button constants can be found in {@link Buttons}. On Android only the * Buttons#LEFT constant is meaningful before version 4.0. * @param button the button to check. * @return whether the button is down or not. */ public boolean isButtonPressed (int button); /** Returns whether a given button has just been pressed. Button constants can be found in {@link Buttons}. On Android only the * Buttons#LEFT constant is meaningful before version 4.0. On WebGL (GWT), only LEFT, RIGHT and MIDDLE buttons are supported. * * @param button the button to check. * @return true or false. */ public boolean isButtonJustPressed (int button); /** Returns whether the key is pressed. * * @param key The key code as found in {@link Input.Keys}. * @return true or false. */ public boolean isKeyPressed (int key); /** Returns whether the key has just been pressed. * * @param key The key code as found in {@link Input.Keys}. * @return true or false. */ public boolean isKeyJustPressed (int key); /** System dependent method to input a string of text. A dialog box will be created with the given title and the given text as * a message for the user. Will use the Default keyboard type. Once the dialog has been closed the provided * {@link TextInputListener} will be called on the rendering thread. * * @param listener The TextInputListener. * @param title The title of the text input dialog. * @param text The message presented to the user. */ public void getTextInput (TextInputListener listener, String title, String text, String hint); /** System dependent method to input a string of text. A dialog box will be created with the given title and the given text as * a message for the user. Once the dialog has been closed the provided {@link TextInputListener} will be called on the * rendering thread. * * @param listener The TextInputListener. * @param title The title of the text input dialog. * @param text The message presented to the user. * @param type which type of keyboard we wish to display */ public void getTextInput (TextInputListener listener, String title, String text, String hint, OnscreenKeyboardType type); /** Sets the on-screen keyboard visible if available. Will use the Default keyboard type. * * @param visible visible or not */ public void setOnscreenKeyboardVisible (boolean visible); /** Sets the on-screen keyboard visible if available. * * @param visible visible or not * @param type which type of keyboard we wish to display. Can be null when hiding */ public void setOnscreenKeyboardVisible (boolean visible, OnscreenKeyboardType type); static interface InputStringValidator { /** @param toCheck The string that should be validated * @return true, if the string is acceptable, false if not. */ boolean validate (String toCheck); } /** Sets the on-screen keyboard visible if available. * * @param configuration The configuration for the native input field */ public void openTextInputField (NativeInputConfiguration configuration); /** Closes the native input field and applies the result to the input wrapper. * @param sendReturn Whether a "return" key should be send after processing */ public void closeTextInputField (boolean sendReturn); static interface KeyboardHeightObserver { void onKeyboardHeightChanged (int height); } /** This will set a keyboard height callback. This will get called, whenever the keyboard height changes. Note: When using * openTextInputField, it will report the height of the native input field too. */ public void setKeyboardHeightObserver (KeyboardHeightObserver observer); public enum OnscreenKeyboardType { Default, NumberPad, PhonePad, Email, Password, URI } /** Generates a simple haptic effect of a given duration or a vibration effect on devices without haptic capabilities. Note * that on Android backend you'll need the permission * <code> <uses-permission android:name="android.permission.VIBRATE" /></code> in your manifest file in order for this to work. * On iOS backend you'll need to set <code>useHaptics = true</code> for devices with haptics capabilities to use them. * * @param milliseconds the number of milliseconds to vibrate. */ public void vibrate (int milliseconds); /** Generates a simple haptic effect of a given duration and default amplitude. Note that on Android backend you'll need the * permission <code> <uses-permission android:name="android.permission.VIBRATE" /></code> in your manifest file in order for * this to work. On iOS backend you'll need to set <code>useHaptics = true</code> for devices with haptics capabilities to use * them. * * @param milliseconds the duration of the haptics effect * @param fallback whether to use non-haptic vibrator on devices without haptics capabilities (or haptics disabled). Fallback * non-haptic vibrations may ignore length parameter in some backends. */ public void vibrate (int milliseconds, boolean fallback); /** Generates a simple haptic effect of a given duration and amplitude. Note that on Android backend you'll need the permission * <code> <uses-permission android:name="android.permission.VIBRATE" /></code> in your manifest file in order for this to work. * On iOS backend you'll need to set <code>useHaptics = true</code> for devices with haptics capabilities to use them. * * @param milliseconds the duration of the haptics effect * @param amplitude the amplitude/strength of the haptics effect. Valid values in the range [0, 255]. * @param fallback whether to use non-haptic vibrator on devices without haptics capabilities (or haptics disabled). Fallback * non-haptic vibrations may ignore length and/or amplitude parameters in some backends. */ public void vibrate (int milliseconds, int amplitude, boolean fallback); /** Generates a simple haptic effect of a type. VibrationTypes are length/amplitude haptic effect presets that depend on each * device and are defined by manufacturers. Should give most consistent results across devices and OSs. Note that on Android * backend you'll need the permission <code> <uses-permission android:name="android.permission.VIBRATE" /></code> in your * manifest file in order for this to work. On iOS backend you'll need to set <code>useHaptics = true</code> for devices with * haptics capabilities to use them. * * @param vibrationType the type of vibration */ public void vibrate (VibrationType vibrationType); public enum VibrationType { LIGHT, MEDIUM, HEAVY; } /** The azimuth is the angle of the device's orientation around the z-axis. The positive z-axis points towards the earths * center. * * @see <a * href="http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], float[], float[], float[])">http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], * float[], float[], float[])</a> * @return the azimuth in degrees */ public float getAzimuth (); /** The pitch is the angle of the device's orientation around the x-axis. The positive x-axis roughly points to the west and is * orthogonal to the z- and y-axis. * @see <a * href="http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], float[], float[], float[])">http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], * float[], float[], float[])</a> * @return the pitch in degrees */ public float getPitch (); /** The roll is the angle of the device's orientation around the y-axis. The positive y-axis points to the magnetic north pole * of the earth. * @see <a * href="http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], float[], float[], float[])">http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], * float[], float[], float[])</a> * @return the roll in degrees */ public float getRoll (); /** Returns the rotation matrix describing the devices rotation as per * <a href= "http://developer.android.com/reference/android/hardware/SensorManager.html#getRotationMatrix(float[], float[], * float[], float[])" >SensorManager#getRotationMatrix(float[], float[], float[], float[])</a>. Does not manipulate the matrix * if the platform does not have an accelerometer. * @param matrix */ public void getRotationMatrix (float[] matrix); /** @return the time of the event currently reported to the {@link InputProcessor}. */ public long getCurrentEventTime (); /** @deprecated use {@link Input#setCatchKey(int keycode, boolean catchKey)} instead * * Sets whether the BACK button on Android should be caught. This will prevent the app from being paused. Will have * no effect on the desktop. * * @param catchBack whether to catch the back button */ @Deprecated public void setCatchBackKey (boolean catchBack); /** @deprecated use {@link Input#isCatchKey(int keycode)} instead * @return whether the back button is currently being caught */ @Deprecated public boolean isCatchBackKey (); /** @deprecated use {@link Input#setCatchKey(int keycode, boolean catchKey)} instead * * Sets whether the MENU button on Android should be caught. This will prevent the onscreen keyboard to show up. * Will have no effect on the desktop. * * @param catchMenu whether to catch the menu button */ @Deprecated public void setCatchMenuKey (boolean catchMenu); /** @deprecated use {@link Input#isCatchKey(int keycode)} instead * @return whether the menu button is currently being caught */ @Deprecated public boolean isCatchMenuKey (); /** Sets whether the given key on Android or GWT should be caught. No effect on other platforms. All keys that are not caught * may be handled by other apps or background processes on Android, or may trigger default browser behaviour on GWT. For * example, media or volume buttons are handled by background media players if present, or Space key triggers a scroll. All * keys you need to control your game should be caught to prevent unintended behaviour. * * @param keycode keycode to catch * @param catchKey whether to catch the given keycode */ public void setCatchKey (int keycode, boolean catchKey); /** @param keycode keycode to check if caught * @return true if the given keycode is configured to be caught */ public boolean isCatchKey (int keycode); /** Sets the {@link InputProcessor} that will receive all touch and key input events. It will be called before the * {@link ApplicationListener#render()} method each frame. * * @param processor the InputProcessor */ public void setInputProcessor (InputProcessor processor); /** @return the currently set {@link InputProcessor} or null. */ public InputProcessor getInputProcessor (); /** Queries whether a {@link Peripheral} is currently available. In case of Android and the {@link Peripheral#HardwareKeyboard} * this returns the whether the keyboard is currently slid out or not. * * @param peripheral the {@link Peripheral} * @return whether the peripheral is available or not. */ public boolean isPeripheralAvailable (Peripheral peripheral); /** @return the rotation of the device with respect to its native orientation. */ public int getRotation (); /** @return the native orientation of the device. */ public Orientation getNativeOrientation (); public enum Orientation { Landscape, Portrait } /** Only viable on the desktop. Will confine the mouse cursor location to the window and hide the mouse cursor. X and y * coordinates are still reported as if the mouse was not catched. * @param catched whether to catch or not to catch the mouse cursor */ public void setCursorCatched (boolean catched); /** @return whether the mouse cursor is catched. */ public boolean isCursorCatched (); /** Only viable on the desktop. Will set the mouse cursor location to the given window coordinates (origin top-left corner). * @param x the x-position * @param y the y-position */ public void setCursorPosition (int x, int y); }
tommyettinger/libgdx
gdx/src/com/badlogic/gdx/Input.java
274
/* * 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.proxy; import lombok.RequiredArgsConstructor; /** * Wizard. */ @RequiredArgsConstructor public class Wizard { private final String name; @Override public String toString() { return name; } }
smedals/java-design-patterns
proxy/src/main/java/com/iluwatar/proxy/Wizard.java
275
/* * 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.twin; import lombok.extern.slf4j.Slf4j; /** * GameItem is a common class which provides some common methods for game object. */ @Slf4j public abstract class GameItem { /** * Template method, do some common logic before draw. */ public void draw() { LOGGER.info("draw"); doDraw(); } public abstract void doDraw(); public abstract void click(); }
smedals/java-design-patterns
twin/src/main/java/com/iluwatar/twin/GameItem.java
276
/* * 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.cqrs.dto; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; /** * This is a DTO (Data Transfer Object) book, contains only useful information to be returned. */ @ToString @EqualsAndHashCode @Getter @AllArgsConstructor @NoArgsConstructor public class Book { private String title; private double price; }
smedals/java-design-patterns
cqrs/src/main/java/com/iluwatar/cqrs/dto/Book.java
277
/* * 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.state; /** * Mammoth has internal state that defines its behavior. */ public class Mammoth { private State state; public Mammoth() { state = new PeacefulState(this); } /** * Makes time pass for the mammoth. */ public void timePasses() { if (state.getClass().equals(PeacefulState.class)) { changeStateTo(new AngryState(this)); } else { changeStateTo(new PeacefulState(this)); } } private void changeStateTo(State newState) { this.state = newState; this.state.onEnterState(); } @Override public String toString() { return "The mammoth"; } public void observe() { this.state.observe(); } }
smedals/java-design-patterns
state/src/main/java/com/iluwatar/state/Mammoth.java
278
/* * 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 lombok.RequiredArgsConstructor; /** * Enumeration for target size. */ @RequiredArgsConstructor public enum Size { SMALL("small"), NORMAL("normal"); private final String title; @Override public String toString() { return title; } }
smedals/java-design-patterns
command/src/main/java/com/iluwatar/command/Size.java
279
/* * 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; import lombok.AllArgsConstructor; import lombok.extern.slf4j.Slf4j; /** * Hammer. */ @Slf4j @AllArgsConstructor public class Hammer implements Weapon { private final Enchantment enchantment; @Override public void wield() { LOGGER.info("The hammer is wielded."); enchantment.onActivate(); } @Override public void swing() { LOGGER.info("The hammer is swung."); enchantment.apply(); } @Override public void unwield() { LOGGER.info("The hammer is unwielded."); enchantment.onDeactivate(); } @Override public Enchantment getEnchantment() { return enchantment; } }
smedals/java-design-patterns
bridge/src/main/java/com/iluwatar/bridge/Hammer.java
280
/* * 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.factory; /** * Coin interface. */ public interface Coin { String getDescription(); }
smedals/java-design-patterns
factory/src/main/java/com/iluwatar/factory/Coin.java
281
/* * 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.cqrs.dto; import lombok.AllArgsConstructor; import lombok.EqualsAndHashCode; import lombok.Getter; import lombok.NoArgsConstructor; import lombok.ToString; /** * This is a DTO (Data Transfer Object) author, contains only useful information to be returned. */ @ToString @EqualsAndHashCode @Getter @NoArgsConstructor @AllArgsConstructor public class Author { private String name; private String email; private String username; }
smedals/java-design-patterns
cqrs/src/main/java/com/iluwatar/cqrs/dto/Author.java
282
/* * 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 dao; import entity.CakeLayer; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * CRUD repository for cake layers. */ @Repository public interface CakeLayerDao extends JpaRepository<CakeLayer, Long> { }
rajprins/java-design-patterns
layers/src/main/java/dao/CakeLayerDao.java
283
/* * 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.builder; import lombok.AllArgsConstructor; /** * Armor enumeration. */ @AllArgsConstructor public enum Armor { CLOTHES("clothes"), LEATHER("leather"), CHAIN_MAIL("chain mail"), PLATE_MAIL("plate mail"); private final String title; @Override public String toString() { return title; } }
smedals/java-design-patterns
builder/src/main/java/com/iluwatar/builder/Armor.java
284
/* * 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.servant; /** * Queen. */ public class Queen implements Royalty { private boolean isDrunk = true; private boolean isHungry; private boolean isHappy; private boolean isFlirty = true; private boolean complimentReceived; @Override public void getFed() { isHungry = false; } @Override public void getDrink() { isDrunk = true; } public void receiveCompliments() { complimentReceived = true; } @Override public void changeMood() { if (complimentReceived && isFlirty && isDrunk && !isHungry) { isHappy = true; } } @Override public boolean getMood() { return isHappy; } public void setFlirtiness(boolean f) { this.isFlirty = f; } }
smedals/java-design-patterns
servant/src/main/java/com/iluwatar/servant/Queen.java
285
/* * 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.store; import com.iluwatar.flux.action.Action; import com.iluwatar.flux.view.View; import java.util.LinkedList; import java.util.List; /** * Store is a data model. */ public abstract class Store { private final List<View> views = new LinkedList<>(); public abstract void onAction(Action action); public void registerView(View view) { views.add(view); } protected void notifyChange() { views.forEach(view -> view.storeChanged(this)); } }
smedals/java-design-patterns
flux/src/main/java/com/iluwatar/flux/store/Store.java
286
/* * 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; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import service.CakeBakingService; /** * View implementation for displaying cakes. */ public class CakeViewImpl implements View { private final CakeBakingService cakeBakingService; private static final Logger LOGGER = LoggerFactory.getLogger(CakeViewImpl.class); public CakeViewImpl(CakeBakingService cakeBakingService) { this.cakeBakingService = cakeBakingService; } public void render() { cakeBakingService.getAllCakes().forEach(cake -> LOGGER.info(cake.toString())); } }
rajprins/java-design-patterns
layers/src/main/java/view/CakeViewImpl.java
287
/* * 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 dto; import java.util.Optional; /** * DTO for cake layers. */ public class CakeLayerInfo { public final Optional<Long> id; public final String name; public final int calories; /** * Constructor. */ public CakeLayerInfo(Long id, String name, int calories) { this.id = Optional.of(id); this.name = name; this.calories = calories; } /** * Constructor. */ public CakeLayerInfo(String name, int calories) { this.id = Optional.empty(); this.name = name; this.calories = calories; } @Override public String toString() { return String.format("CakeLayerInfo id=%d name=%s calories=%d", id.orElse(-1L), name, calories); } }
rajprins/java-design-patterns
layers/src/main/java/dto/CakeLayerInfo.java
288
/* * 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; /** * Goblin is the target of the spells. */ public class Goblin extends Target { public Goblin() { setSize(Size.NORMAL); setVisibility(Visibility.VISIBLE); } @Override public String toString() { return "Goblin"; } }
smedals/java-design-patterns
command/src/main/java/com/iluwatar/command/Goblin.java
289
/* * 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.proxy; import lombok.extern.slf4j.Slf4j; /** * The object to be proxied. */ @Slf4j public class IvoryTower implements WizardTower { public void enter(Wizard wizard) { LOGGER.info("{} enters the tower.", wizard); } }
smedals/java-design-patterns
proxy/src/main/java/com/iluwatar/proxy/IvoryTower.java
290
/* * 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.callback; import java.util.Optional; /** * Template-method class for callback hook execution. */ public abstract class Task { /** * Execute with callback. */ final void executeWith(Callback callback) { execute(); Optional.ofNullable(callback).ifPresent(Callback::call); } public abstract void execute(); }
smedals/java-design-patterns
callback/src/main/java/com/iluwatar/callback/Task.java
291
/* * 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.builder; /** * Weapon enumeration. */ public enum Weapon { DAGGER, SWORD, AXE, WARHAMMER, BOW; @Override public String toString() { return name().toLowerCase(); } }
smedals/java-design-patterns
builder/src/main/java/com/iluwatar/builder/Weapon.java
292
/* * 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 dao; import entity.CakeTopping; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.stereotype.Repository; /** * CRUD repository cake toppings. */ @Repository public interface CakeToppingDao extends JpaRepository<CakeTopping, Long> { }
rajprins/java-design-patterns
layers/src/main/java/dao/CakeToppingDao.java
293
/* * 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.servant; import java.util.List; /** * Servant. */ public class Servant { public String name; /** * Constructor. */ public Servant(String name) { this.name = name; } public void feed(Royalty r) { r.getFed(); } public void giveWine(Royalty r) { r.getDrink(); } public void giveCompliments(Royalty r) { r.receiveCompliments(); } /** * Check if we will be hanged. */ public boolean checkIfYouWillBeHanged(List<Royalty> tableGuests) { return tableGuests.stream().allMatch(Royalty::getMood); } }
smedals/java-design-patterns
servant/src/main/java/com/iluwatar/servant/Servant.java
294
/* * 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.action; import lombok.Getter; import lombok.RequiredArgsConstructor; /** * Action is the data payload dispatched to the stores when something happens. */ @RequiredArgsConstructor @Getter public abstract class Action { private final ActionType type; }
smedals/java-design-patterns
flux/src/main/java/com/iluwatar/flux/action/Action.java
295
/* * 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.servant; /** * Royalty. */ interface Royalty { void getFed(); void getDrink(); void changeMood(); void receiveCompliments(); boolean getMood(); }
smedals/java-design-patterns
servant/src/main/java/com/iluwatar/servant/Royalty.java
296
/* * 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 units; import abstractextensions.UnitExtension; import concreteextensions.Sergeant; import java.util.Optional; /** * Class defining SergeantUnit. */ public class SergeantUnit extends Unit { public SergeantUnit(String name) { super(name); } @Override public UnitExtension getUnitExtension(String extensionName) { if (extensionName.equals("SergeantExtension")) { return Optional.ofNullable(unitExtension).orElseGet(() -> new Sergeant(this)); } return super.getUnitExtension(extensionName); } }
smedals/java-design-patterns
extension-objects/src/main/java/units/SergeantUnit.java
297
/* * 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.sharding; import java.util.HashMap; import java.util.Map; /** * The Shard class stored data in a HashMap. */ public class Shard { private final int id; private final Map<Integer, Data> dataStore; public Shard(final int id) { this.id = id; this.dataStore = new HashMap<>(); } public void storeData(Data data) { dataStore.put(data.getKey(), data); } public void clearData() { dataStore.clear(); } public Data getDataById(final int id) { return dataStore.get(id); } public int getId() { return id; } }
smedals/java-design-patterns
sharding/src/main/java/com/iluwatar/sharding/Shard.java
298
/* * 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.adapter; import lombok.AllArgsConstructor; import lombok.NoArgsConstructor; import lombok.Setter; /** * The Captain uses {@link RowingBoat} to sail. <br> This is the client in the pattern. */ @Setter @NoArgsConstructor @AllArgsConstructor public final class Captain { private RowingBoat rowingBoat; void row() { rowingBoat.row(); } }
smedals/java-design-patterns
adapter/src/main/java/com/iluwatar/adapter/Captain.java
299
/* * 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; /** * Party interface. */ public interface Party { void addMember(PartyMember member); void act(PartyMember actor, Action action); }
smedals/java-design-patterns
mediator/src/main/java/com/iluwatar/mediator/Party.java
300
/* * 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.visitor; /** * Soldier. */ public class Soldier extends Unit { public Soldier(Unit... children) { super(children); } /** * Accept a Visitor. * @param visitor UnitVisitor to be accepted */ @Override public void accept(UnitVisitor visitor) { visitor.visit(this); super.accept(visitor); } @Override public String toString() { return "soldier"; } }
smedals/java-design-patterns
visitor/src/main/java/com/iluwatar/visitor/Soldier.java
302
package com.thealgorithms.maths; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; /* * Find the mode of an array of numbers * * The mode of an array of numbers is the most frequently occurring number in the array, * or the most frequently occurring numbers if there are multiple numbers with the same frequency */ public final class Mode { private Mode() { } /* * Find the mode of an array of integers * * @param numbers array of integers * @return mode of the array */ public static int[] mode(final int[] numbers) { if (numbers.length == 0) { return null; } HashMap<Integer, Integer> count = new HashMap<>(); for (int num : numbers) { if (count.containsKey(num)) { count.put(num, count.get(num) + 1); } else { count.put(num, 1); } } int max = Collections.max(count.values()); ArrayList<Integer> modes = new ArrayList<>(); for (int num : count.keySet()) { if (count.get(num) == max) { modes.add(num); } } return modes.stream().mapToInt(n -> n).toArray(); } }
TheAlgorithms/Java
src/main/java/com/thealgorithms/maths/Mode.java
307
// 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
308
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
309
class Solution { public String decodeString(String s) { StringBuilder res = new StringBuilder(); int multi = 0; Stack<Integer> stack_multi = new Stack(); Stack<String> stack_res = new Stack(); for (int i = 0; i < s.length(); i++) { char c = s.charAt(i); if ('[' == c){ stack_multi.push(multi); stack_res.push(res.toString()); multi = 0; res = new StringBuilder(); } else if (']' == c) { StringBuilder tmp = new StringBuilder(); int cur_multi = stack_multi.pop(); for (int j = 0; j < cur_multi; j++){ tmp.append(res); } res = new StringBuilder(stack_res.pop() + tmp); } else if(c >= '0' && c <= '9'){ multi = multi * 10 + (c - '0'); } else{ res.append(c); } } return res.toString(); } }
MisterBooo/LeetCodeAnimation
0394-Decode-String/Code/1.java
310
/* * 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
311
package org.opencv.highgui; import org.opencv.core.Mat; import javax.swing.*; import java.awt.*; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.image.BufferedImage; import java.awt.image.DataBufferByte; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; /** * This class was designed for use in Java applications * to recreate the OpenCV HighGui functionalities. */ public final class HighGui { // Constants for namedWindow public final static int WINDOW_NORMAL = ImageWindow.WINDOW_NORMAL; public final static int WINDOW_AUTOSIZE = ImageWindow.WINDOW_AUTOSIZE; // Control Variables public static int n_closed_windows = 0; public static int pressedKey = -1; public static CountDownLatch latch = new CountDownLatch(1); // Windows Map public static Map<String, ImageWindow> windows = new HashMap<String, ImageWindow>(); public static void namedWindow(String winname) { namedWindow(winname, HighGui.WINDOW_AUTOSIZE); } public static void namedWindow(String winname, int flag) { ImageWindow newWin = new ImageWindow(winname, flag); if (windows.get(winname) == null) windows.put(winname, newWin); } public static void imshow(String winname, Mat img) { if (img.empty()) { System.err.println("Error: Empty image in imshow"); System.exit(-1); } else { ImageWindow tmpWindow = windows.get(winname); if (tmpWindow == null) { ImageWindow newWin = new ImageWindow(winname, img); windows.put(winname, newWin); } else { tmpWindow.setMat(img); } } } public static Image toBufferedImage(Mat m) { int type = BufferedImage.TYPE_BYTE_GRAY; if (m.channels() > 1) { type = BufferedImage.TYPE_3BYTE_BGR; } BufferedImage image = new BufferedImage(m.cols(), m.rows(), type); final byte[] targetPixels = ((DataBufferByte) image.getRaster().getDataBuffer()).getData(); m.get(0, 0, targetPixels); return image; } public static JFrame createJFrame(String title, int flag) { JFrame frame = new JFrame(title); frame.addWindowListener(new java.awt.event.WindowAdapter() { @Override public void windowClosing(java.awt.event.WindowEvent windowEvent) { n_closed_windows++; if (n_closed_windows == windows.size()) latch.countDown(); } }); frame.addKeyListener(new KeyListener() { @Override public void keyTyped(KeyEvent e) { } @Override public void keyReleased(KeyEvent e) { } @Override public void keyPressed(KeyEvent e) { pressedKey = e.getKeyCode(); latch.countDown(); } }); if (flag == WINDOW_AUTOSIZE) frame.setResizable(false); return frame; } public static void waitKey(){ waitKey(0); } public static int waitKey(int delay) { // Reset control values latch = new CountDownLatch(1); n_closed_windows = 0; pressedKey = -1; // If there are no windows to be shown return if (windows.isEmpty()) { System.err.println("Error: waitKey must be used after an imshow"); System.exit(-1); } // Remove the unused windows Iterator<Map.Entry<String, ImageWindow>> iter = windows.entrySet().iterator(); while (iter.hasNext()) { Map.Entry<String, ImageWindow> entry = iter.next(); ImageWindow win = entry.getValue(); if (win.alreadyUsed) { iter.remove(); win.frame.dispose(); } } // (if) Create (else) Update frame for (ImageWindow win : windows.values()) { if (win.img != null) { ImageIcon icon = new ImageIcon(toBufferedImage(win.img)); if (win.lbl == null) { JFrame frame = createJFrame(win.name, win.flag); JLabel lbl = new JLabel(icon); win.setFrameLabelVisible(frame, lbl); } else { win.lbl.setIcon(icon); } } else { System.err.println("Error: no imshow associated with" + " namedWindow: \"" + win.name + "\""); System.exit(-1); } } try { if (delay == 0) { latch.await(); } else { latch.await(delay, TimeUnit.MILLISECONDS); } } catch (InterruptedException e) { e.printStackTrace(); } // Set all windows as already used for (ImageWindow win : windows.values()) win.alreadyUsed = true; return pressedKey; } public static void destroyWindow(String winname) { ImageWindow tmpWin = windows.get(winname); if (tmpWin != null) windows.remove(winname); } public static void destroyAllWindows() { windows.clear(); } public static void resizeWindow(String winname, int width, int height) { ImageWindow tmpWin = windows.get(winname); if (tmpWin != null) tmpWin.setNewDimension(width, height); } public static void moveWindow(String winname, int x, int y) { ImageWindow tmpWin = windows.get(winname); if (tmpWin != null) tmpWin.setNewPosition(x, y); } }
opencv/opencv
modules/highgui/misc/java/src/java/highgui+HighGui.java
313
import java.io.*; import java.util.*; /************************************************************************************************************************************** * Class Feature *****/ class Feature implements Debuggable { public static String NOMINAL = "NOMINAL", CONTINUOUS = "CONTINUOUS", CLASS = "CLASS"; public static String TYPE[] = {Feature.NOMINAL, Feature.CONTINUOUS, Feature.CLASS}; public static boolean MODALITIES[] = {true, false, false}; public static int CLASS_INDEX = 2; public static double MODALITY_PRESENT = 1.0, MODALITY_ABSENT = 0.0; public static double MINV = -1.0, MAXV = 1.0; // values used for normalization in [MINV, MAXV] public static double MAX_CLASS_MAGNITUDE = 1.0; String name; String type; double minn, maxx; Vector modalities; // applies to nominal feature Vector tests; // set of test values as returned by TEST_LIST public static Vector TEST_LIST(Feature f) { // generates a vector of a list of tests -- does not depend on training data for privacy // purposes // if continuous, list of evenly spaces ties // if nominal, list of partial non-empty subsets of the whole set Vector v = new Vector(); if (IS_CONTINUOUS(f.type)) { v = null; } else if (HAS_MODALITIES(f.type)) { v = Utils.ALL_NON_TRIVIAL_SUBSETS(f.modalities); } return v; } public void update_tests(double[] all_vals) { if ((all_vals == null) || (all_vals.length <= 1)) Dataset.perror("Feature.class :: <= 1 observed values for continuous feature"); Vector v = new Vector(); int i; minn = all_vals[0]; maxx = all_vals[all_vals.length - 1]; for (i = 0; i < all_vals.length - 1; i++) { if (all_vals[i] == all_vals[i + 1]) Dataset.perror("Feature.class :: repeated feature values"); v.addElement(new Double((all_vals[i] + all_vals[i + 1]) / 2.0)); } tests = v; } public String tests() { int i, j; String v = "{"; Vector dv; for (i = 0; i < tests.size(); i++) { if (Feature.IS_CONTINUOUS(type)) v += DF6.format(((Double) tests.elementAt(i)).doubleValue()); else if (Feature.HAS_MODALITIES(type)) { dv = ((Vector) tests.elementAt(i)); for (j = 0; j < dv.size(); j++) v += ((String) dv.elementAt(j)); } if (i < tests.size() - 1) v += ", "; } v += "}"; return v; } public static boolean IS_CONTINUOUS(String t) { return (t.equals(Feature.CONTINUOUS)); } public static boolean IS_CLASS(String t) { return (t.equals(Feature.CLASS)); } static int INDEX(String t) { int i = 0; do { if (t.equals(TYPE[i])) return i; i++; } while (i < TYPE.length); Dataset.perror("No type found for " + t); return -1; } static boolean HAS_MODALITIES(String t) { // synonym of is nominal return MODALITIES[Feature.INDEX(t)]; } Feature(String n, String t, Vector m) { name = n; type = t; modalities = null; if (Feature.HAS_MODALITIES(t)) modalities = m; tests = Feature.TEST_LIST(this); } public boolean has_in_range(String s) { if (Feature.IS_CONTINUOUS(type)) Dataset.perror( "Feature.class :: Continuous feature " + this + " queried for nominal value " + s); if (!Feature.HAS_MODALITIES(type)) Dataset.perror("Feature.class :: feature type " + type + " unregistered "); int i; String ss; for (i = 0; i < modalities.size(); i++) { ss = (String) modalities.elementAt(i); if (ss.equals(s)) return true; } return false; } public String range() { String v = ""; int i; if (Feature.HAS_MODALITIES(type)) { v += "{"; for (i = 0; i < modalities.size(); i++) { v += "" + modalities.elementAt(i); if (i < modalities.size() - 1) v += ", "; } v += "}"; } else if (Feature.IS_CONTINUOUS(type)) { v += "[" + minn + ", " + maxx + "]"; } return v; } public boolean example_goes_left(Example e, int index_feature_in_e, int index_test) { // continuous values : <= is left, > is right // nominal values : in the set is left, otherwise is right double cv, tv; String nv; Vector ssv; int i; if (Feature.IS_CONTINUOUS(type)) { if (e.typed_features.elementAt(index_feature_in_e).getClass().getName().equals("String")) Dataset.perror( "Feature.class :: wrong class match : " + e.typed_features.elementAt(index_feature_in_e) + " not a Double"); cv = ((Double) e.typed_features.elementAt(index_feature_in_e)).doubleValue(); tv = ((Double) tests.elementAt(index_test)).doubleValue(); if (cv <= tv) return true; return false; } else if (Feature.HAS_MODALITIES(type)) { if (e.typed_features.elementAt(index_feature_in_e).getClass().getName().equals("Double")) Dataset.perror( "Feature.class :: wrong class match : " + e.typed_features.elementAt(index_feature_in_e) + " not a String"); nv = ((String) e.typed_features.elementAt(index_feature_in_e)); ssv = (Vector) tests.elementAt(index_test); for (i = 0; i < ssv.size(); i++) { if (nv.equals((String) ssv.elementAt(i))) return true; } return false; } else Dataset.perror("Feature.class :: no type available for feature " + this); return false; } public String display_test(int index_test) { String v = name; int i; Vector ssv; if (Feature.IS_CONTINUOUS(type)) v += " <= " + DF.format(((Double) tests.elementAt(index_test)).doubleValue()); else if (Feature.HAS_MODALITIES(type)) { v += " in {"; ssv = (Vector) tests.elementAt(index_test); for (i = 0; i < ssv.size(); i++) { v += (String) ssv.elementAt(i); if (i < ssv.size() - 1) v += ", "; } v += "}"; } else Dataset.perror("Feature.class :: no type available for feature " + this); return v; } public String toString() { String v = ""; int i; v += name + " -- " + type + " in " + range() + " -- tests : " + tests(); return v; } }
google-research/google-research
tempered_boosting/Feature.java
314
package com.genymobile.scrcpy; import java.io.File; import java.io.IOException; import java.io.OutputStream; /** * Handle the cleanup of scrcpy, even if the main process is killed. * <p> * This is useful to restore some state when scrcpy is closed, even on device disconnection (which kills the scrcpy process). */ public final class CleanUp { private static final int MSG_TYPE_MASK = 0b11; private static final int MSG_TYPE_RESTORE_STAY_ON = 0; private static final int MSG_TYPE_DISABLE_SHOW_TOUCHES = 1; private static final int MSG_TYPE_RESTORE_NORMAL_POWER_MODE = 2; private static final int MSG_TYPE_POWER_OFF_SCREEN = 3; private static final int MSG_PARAM_SHIFT = 2; private final OutputStream out; public CleanUp(OutputStream out) { this.out = out; } public static CleanUp configure(int displayId) throws IOException { String[] cmd = {"app_process", "/", CleanUp.class.getName(), String.valueOf(displayId)}; ProcessBuilder builder = new ProcessBuilder(cmd); builder.environment().put("CLASSPATH", Server.SERVER_PATH); Process process = builder.start(); return new CleanUp(process.getOutputStream()); } private boolean sendMessage(int type, int param) { assert (type & ~MSG_TYPE_MASK) == 0; int msg = type | param << MSG_PARAM_SHIFT; try { out.write(msg); out.flush(); return true; } catch (IOException e) { Ln.w("Could not configure cleanup (type=" + type + ", param=" + param + ")", e); return false; } } public boolean setRestoreStayOn(int restoreValue) { // Restore the value (between 0 and 7), -1 to not restore // <https://developer.android.com/reference/android/provider/Settings.Global#STAY_ON_WHILE_PLUGGED_IN> assert restoreValue >= -1 && restoreValue <= 7; return sendMessage(MSG_TYPE_RESTORE_STAY_ON, restoreValue & 0b1111); } public boolean setDisableShowTouches(boolean disableOnExit) { return sendMessage(MSG_TYPE_DISABLE_SHOW_TOUCHES, disableOnExit ? 1 : 0); } public boolean setRestoreNormalPowerMode(boolean restoreOnExit) { return sendMessage(MSG_TYPE_RESTORE_NORMAL_POWER_MODE, restoreOnExit ? 1 : 0); } public boolean setPowerOffScreen(boolean powerOffScreenOnExit) { return sendMessage(MSG_TYPE_POWER_OFF_SCREEN, powerOffScreenOnExit ? 1 : 0); } public static void unlinkSelf() { try { new File(Server.SERVER_PATH).delete(); } catch (Exception e) { Ln.e("Could not unlink server", e); } } public static void main(String... args) { unlinkSelf(); int displayId = Integer.parseInt(args[0]); int restoreStayOn = -1; boolean disableShowTouches = false; boolean restoreNormalPowerMode = false; boolean powerOffScreen = false; try { // Wait for the server to die int msg; while ((msg = System.in.read()) != -1) { int type = msg & MSG_TYPE_MASK; int param = msg >> MSG_PARAM_SHIFT; switch (type) { case MSG_TYPE_RESTORE_STAY_ON: restoreStayOn = param > 7 ? -1 : param; break; case MSG_TYPE_DISABLE_SHOW_TOUCHES: disableShowTouches = param != 0; break; case MSG_TYPE_RESTORE_NORMAL_POWER_MODE: restoreNormalPowerMode = param != 0; break; case MSG_TYPE_POWER_OFF_SCREEN: powerOffScreen = param != 0; break; default: Ln.w("Unexpected msg type: " + type); break; } } } catch (IOException e) { // Expected when the server is dead } Ln.i("Cleaning up"); if (disableShowTouches) { Ln.i("Disabling \"show touches\""); try { Settings.putValue(Settings.TABLE_SYSTEM, "show_touches", "0"); } catch (SettingsException e) { Ln.e("Could not restore \"show_touches\"", e); } } if (restoreStayOn != -1) { Ln.i("Restoring \"stay awake\""); try { Settings.putValue(Settings.TABLE_GLOBAL, "stay_on_while_plugged_in", String.valueOf(restoreStayOn)); } catch (SettingsException e) { Ln.e("Could not restore \"stay_on_while_plugged_in\"", e); } } if (Device.isScreenOn()) { if (powerOffScreen) { Ln.i("Power off screen"); Device.powerOffScreen(displayId); } else if (restoreNormalPowerMode) { Ln.i("Restoring normal power mode"); Device.setScreenPowerMode(Device.POWER_MODE_NORMAL); } } System.exit(0); } }
Genymobile/scrcpy
server/src/main/java/com/genymobile/scrcpy/CleanUp.java