code
stringlengths
3
1.18M
language
stringclasses
1 value
package moa.classifiers; import moa.core.AutoExpandVector; import moa.core.DoubleVector; import moa.options.ClassOption; import moa.options.FlagOption; import moa.options.IntOption; import weka.core.Instance; public class DecisionStumpTutorial extends AbstractClassifier { private static final long serialVersionUID = 1L; public IntOption gracePeriodOption = new IntOption("gracePeriod", 'g', "The number of instances to observe between model changes.", 1000, 0, Integer.MAX_VALUE); public FlagOption binarySplitsOption = new FlagOption("binarySplits", 'b', "Only allow binary splits."); public ClassOption splitCriterionOption = new ClassOption("splitCriterion", 'c', "Split criterion to use.", SplitCriterion.class, "InfoGainSplitCriterion"); protected AttributeSplitSuggestion bestSplit; protected DoubleVector observedClassDistribution; protected AutoExpandVector<AttributeClassObserver> attributeObservers; protected double weightSeenAtLastSplit; public boolean isRandomizable() { return false; } @Override public void resetLearningImpl() { this.bestSplit = null; this.observedClassDistribution = new DoubleVector(); this.attributeObservers = new AutoExpandVector<AttributeClassObserver>(); this.weightSeenAtLastSplit = 0.0; } @Override public void trainOnInstanceImpl(Instance inst) { this.observedClassDistribution.addToValue((int) inst.classValue(), inst .weight()); for (int i = 0; i < inst.numAttributes() - 1; i++) { int instAttIndex = modelAttIndexToInstanceAttIndex(i, inst); AttributeClassObserver obs = this.attributeObservers.get(i); if (obs == null) { obs = inst.attribute(instAttIndex).isNominal() ? newNominalClassObserver() : newNumericClassObserver(); this.attributeObservers.set(i, obs); } obs.observeAttributeClass(inst.value(instAttIndex), (int) inst .classValue(), inst.weight()); } if (this.trainingWeightSeenByModel - this.weightSeenAtLastSplit >= this.gracePeriodOption.getValue()) { this.bestSplit = findBestSplit((SplitCriterion) getPreparedClassOption(this.splitCriterionOption)); this.weightSeenAtLastSplit = this.trainingWeightSeenByModel; } } public double[] getVotesForInstance(Instance inst) { if (this.bestSplit != null) { int branch = this.bestSplit.splitTest.branchForInstance(inst); if (branch >= 0) { return this.bestSplit .resultingClassDistributionFromSplit(branch); } } return this.observedClassDistribution.getArrayCopy(); } protected AttributeClassObserver newNominalClassObserver() { return new NominalAttributeClassObserver(); } protected AttributeClassObserver newNumericClassObserver() { return new GaussianNumericAttributeClassObserver(); } protected AttributeSplitSuggestion findBestSplit(SplitCriterion criterion) { AttributeSplitSuggestion bestFound = null; double bestMerit = Double.NEGATIVE_INFINITY; double[] preSplitDist = this.observedClassDistribution.getArrayCopy(); for (int i = 0; i < this.attributeObservers.size(); i++) { AttributeClassObserver obs = this.attributeObservers.get(i); if (obs != null) { AttributeSplitSuggestion suggestion = obs.getBestEvaluatedSplitSuggestion( criterion, preSplitDist, i, this.binarySplitsOption.isSet()); if (suggestion.merit > bestMerit) { bestMerit = suggestion.merit; bestFound = suggestion; } } } return bestFound; } public void getModelDescription(StringBuilder out, int indent) { } protected moa.core.Measurement[] getModelMeasurementsImpl() { return null; } }
Java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * AbstractMultipleRegressorTestCase.java Copyright (C) 2013 University of Waikato, Hamilton, New * Zealand */ package moa.classifiers; import moa.evaluation.BasicRegressionPerformanceEvaluator; import moa.evaluation.ClassificationPerformanceEvaluator; /** * Ancestor that defines a setting to test a classifier several times with * different parameters using this predefined same setting. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public abstract class AbstractMultipleRegressorTestCase extends AbstractClassifierTestCase { protected int numberTests = 1; /** * Constructs the test case. Called by subclasses. * * @param name the name of the test */ public AbstractMultipleRegressorTestCase(String name) { super(name); } /** * Sets the number of tests to run with this classifier. * * @param name the name of the test * @param numberTests the numbers of tests to run */ public void setNumberTests(int numberTests) { this.numberTests = numberTests; } /** * Called by JUnit before each test method. * * @throws Exception if an error occurs. */ @Override protected void setUp() throws Exception { super.setUp(); m_TestHelper.copyResourceToTmp("regression.arff"); } /** * Called by JUnit after each test method. * * @throws Exception if tear-down fails */ @Override protected void tearDown() throws Exception { m_TestHelper.deleteFileFromTmp("regression.arff"); super.tearDown(); } /** * Returns the filenames (without path) of the input data files to use in * the regression test. * * @return the filenames */ @Override protected String[] getRegressionInputFiles() { String value = "regression.arff"; String[] ret = new String[this.numberTests]; for (int i = 0; i < this.numberTests; i++) { ret[i] = value; } return ret; } /** * Returns the class index for the datasets. * * @return the class indices (0-based) */ @Override protected int[] getRegressionInputClassIndex() { int value = 8; int[] ret = new int[this.numberTests]; for (int i = 0; i < this.numberTests; i++) { ret[i] = value; } return ret; } /** * Returns the index of the instances in the stream to inspect the * performance/classification output of the classifiers. * * @return the inspection indices */ @Override protected int[][] getRegressionInspectionPoints() { int[] value = new int[]{100, 200, 300, 400, 500, 600, 700, 800, 900, 1000}; int[][] ret = new int[this.numberTests][value.length]; for (int i = 0; i < this.numberTests; i++) { ret[i] = value.clone(); } return ret; } /** * Returns the classifier setups to use in the regression test. * * @return the setups */ @Override protected abstract Classifier[] getRegressionClassifierSetups(); /** * Returns the evaluator setups to use in the regression test. * * @return the setups */ @Override protected ClassificationPerformanceEvaluator[] getRegressionEvaluatorSetups() { ClassificationPerformanceEvaluator value = new BasicRegressionPerformanceEvaluator(); ClassificationPerformanceEvaluator[] ret = new ClassificationPerformanceEvaluator[this.numberTests]; for (int i = 0; i < this.numberTests; i++) { ret[i] = (ClassificationPerformanceEvaluator) value.copy(); } return ret; } }
Java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * AbstractClassifierTestCase.java * Copyright (C) 2013 University of Waikato, Hamilton, New Zealand */ package moa.classifiers; import moa.core.InstancesHeader; import moa.core.Measurement; import moa.evaluation.ClassificationPerformanceEvaluator; import moa.test.AbstractTestHelper; import moa.test.MoaTestCase; import moa.test.TestHelper; import moa.test.TmpFile; import weka.core.Instance; import weka.core.Instances; import weka.core.MOAUtils; import weka.core.converters.ArffLoader; /** * Ancestor for all classifier test cases. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public abstract class AbstractClassifierTestCase extends MoaTestCase { /** * Container for the data collected from a classifier at a specified * inspection point in the stream. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public static class InspectionData { /** the inspection point. */ public int index = -1; /** the votes. */ public double[] votes = new double[0]; /** the measurements. */ public Measurement[] measurements = new Measurement[0]; /** the model measurements. */ public Measurement[] modelMeasurements = new Measurement[0]; /** * Returns the container data as string. * * @return the string representation */ @Override public String toString() { StringBuilder result; int i; result = new StringBuilder(); result.append("Index\n"); result.append(" " + index + "\n"); result.append("Votes\n"); for (i = 0; i < votes.length; i++) result.append(" " + i + ": " + MoaTestCase.doubleToString(votes[i], 8) + "\n"); result.append("Measurements\n"); for (Measurement m: measurements) result.append(" " + m.getName() + ": " + MoaTestCase.doubleToString(m.getValue(), 8) + "\n"); result.append("Model measurements\n"); for (Measurement m: modelMeasurements) { if (m.getName().indexOf("serialized") > -1) continue; result.append(" " + m.getName() + ": " + MoaTestCase.doubleToString(m.getValue(), 8) + "\n"); } return result.toString(); } } /** * Constructs the test case. Called by subclasses. * * @param name the name of the test */ public AbstractClassifierTestCase(String name) { super(name); } /** * Returns the test helper class to use. * * @return the helper class instance */ @Override protected AbstractTestHelper newTestHelper() { return new TestHelper(this, "moa/classifiers/data"); } /** * Loads the data to process. * * @param filename the filename to load (without path) * @param classIndex the class index to use * @return the data, null if it could not be loaded * @see #getDataDirectory() */ protected Instances load(String filename, int classIndex) { Instances result; ArffLoader loader; result = null; try { loader = new ArffLoader(); loader.setFile(new TmpFile(filename)); result = loader.getDataSet(); result.setClassIndex(classIndex); } catch (Exception e) { System.err.println("Failed to load dataset: " + filename); e.printStackTrace(); result = null; } return result; } /** * Processes the input data and returns the inspection data. * * @param data the data to work on * @param inspectionPoints the inspection points * @param evaluator the evaluator to use * @param scheme the scheme to process the data with * @return the processed data */ protected InspectionData[] inspect(Instances data, int[] inspectionPoints, ClassificationPerformanceEvaluator evaluator, Classifier scheme) { InspectionData[] result; int i; int point; Instance inst; double[] votes; result = new InspectionData[inspectionPoints.length]; scheme.prepareForUse(); point = 0; for (i = 0; i < data.numInstances(); i++) { inst = data.instance(i); if (i > 0) { votes = scheme.getVotesForInstance(inst); evaluator.addResult(inst, votes); if (point < inspectionPoints.length) { if (i == inspectionPoints[point] - 1) { result[point] = new InspectionData(); result[point].index = inspectionPoints[point]; result[point].votes = votes; result[point].measurements = evaluator.getPerformanceMeasurements(); result[point].modelMeasurements = scheme.getModelMeasurements(); point++; } } } scheme.trainOnInstance(inst); } return result; } /** * Saves the data in the tmp directory. * * @param data the data to save * @param filename the filename to save to (without path) * @return true if successfully saved */ protected boolean save(Classifier cls, InspectionData[] data, String filename) { StringBuilder str; str = new StringBuilder(); str.append(MOAUtils.toCommandLine(cls) + "\n"); str.append("\n"); for (InspectionData d: data) { str.append(d.toString()); str.append("\n"); } return m_TestHelper.save(str, filename); } /** * Returns the filenames (without path) of the input data files to use * in the regression test. * * @return the filenames */ protected abstract String[] getRegressionInputFiles(); /** * Returns the class index for the datasets. * * @return the class indices (0-based) */ protected abstract int[] getRegressionInputClassIndex(); /** * Returns the index of the instances in the stream to inspect the * performance/classification output of the classifiers. * * @return the inspection indices */ protected abstract int[][] getRegressionInspectionPoints(); /** * Returns the classifier setups to use in the regression test. * * @return the setups */ protected abstract Classifier[] getRegressionClassifierSetups(); /** * Returns the evaluator setups to use in the regression test. * * @return the setups */ protected abstract ClassificationPerformanceEvaluator[] getRegressionEvaluatorSetups(); /** * Creates an output filename based on the input filename. * * @param input the input filename (no path) * @param no the number of the test * @return the generated output filename (no path) */ protected String createOutputFilename(String input, int no) { String result; int index; String ext; ext = "-out" + no; index = input.lastIndexOf('.'); if (index == -1) { result = input + ext; } else { result = input.substring(0, index); result += ext; result += input.substring(index); } return result; } /** * Compares the processed data against previously saved output data. */ public void testRegression() { Instances data; InspectionData[] processed; boolean ok; String regression; int i; String[] input; int[] cindices; Classifier[] setups; ClassificationPerformanceEvaluator[] evals; int[][] points; Classifier current; String[] output; TmpFile[] outputFiles; if (m_NoRegressionTest) return; input = getRegressionInputFiles(); cindices = getRegressionInputClassIndex(); output = new String[input.length]; setups = getRegressionClassifierSetups(); evals = getRegressionEvaluatorSetups(); points = getRegressionInspectionPoints(); assertEquals("Number of files and class indices differ!", input.length, cindices.length); assertEquals("Number of files and classifier setups differ!", input.length, setups.length); assertEquals("Number of classifier setups and evaluator setups differ!", setups.length, evals.length); assertEquals("Number of classifier setups and inspection points differ!", setups.length, points.length); // process data for (i = 0; i < input.length; i++) { data = load(input[i], cindices[i]); assertNotNull("Could not load data for regression test from " + input[i], data); current = setups[i].copy(); current.prepareForUse(); current.setModelContext(new InstancesHeader(data)); assertNotNull("Failed to create copy of algorithm: " + MOAUtils.toCommandLine(setups[i]), current); processed = inspect(data, points[i], evals[i], current); assertNotNull("Failed to process data?", processed); output[i] = createOutputFilename(input[i], i); ok = save(current, processed, output[i]); assertTrue("Failed to save regression data?", ok); } // test regression outputFiles = new TmpFile[output.length]; for (i = 0; i < output.length; i++) outputFiles[i] = new TmpFile(output[i]); regression = m_Regression.compare(outputFiles); assertNull("Output differs:\n" + regression, regression); // remove output for (i = 0; i < output.length; i++) m_TestHelper.deleteFileFromTmp(output[i]); } }
Java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * AbstractMultipleClassifierTestCase.java Copyright (C) 2013 University of Waikato, Hamilton, New * Zealand */ package moa.classifiers; import moa.evaluation.BasicClassificationPerformanceEvaluator; import moa.evaluation.ClassificationPerformanceEvaluator; /** * Ancestor that defines a setting to test a classifier several times with * different parameters using this predefined same setting. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public abstract class AbstractMultipleClassifierTestCase extends AbstractClassifierTestCase { protected int numberTests = 1; /** * Constructs the test case. Called by subclasses. * * @param name the name of the test */ public AbstractMultipleClassifierTestCase(String name) { super(name); } /** * Sets the number of tests to run with this classifier. * * @param name the name of the test * @param numberTests the numbers of tests to run */ public void setNumberTests(int numberTests) { this.numberTests = numberTests; } /** * Called by JUnit before each test method. * * @throws Exception if an error occurs. */ @Override protected void setUp() throws Exception { super.setUp(); m_TestHelper.copyResourceToTmp("classification.arff"); } /** * Called by JUnit after each test method. * * @throws Exception if tear-down fails */ @Override protected void tearDown() throws Exception { m_TestHelper.deleteFileFromTmp("classification.arff"); super.tearDown(); } /** * Returns the filenames (without path) of the input data files to use in * the regression test. * * @return the filenames */ @Override protected String[] getRegressionInputFiles() { String value = "classification.arff"; String[] ret = new String[this.numberTests]; for (int i = 0; i < this.numberTests; i++) { ret[i] = value; } return ret; } /** * Returns the class index for the datasets. * * @return the class indices (0-based) */ @Override protected int[] getRegressionInputClassIndex() { int value = 10; int[] ret = new int[this.numberTests]; for (int i = 0; i < this.numberTests; i++) { ret[i] = value; } return ret; } /** * Returns the index of the instances in the stream to inspect the * performance/classification output of the classifiers. * * @return the inspection indices */ @Override protected int[][] getRegressionInspectionPoints() { int[] value = new int[]{10000, 20000, 30000, 40000, 50000, 60000, 70000, 80000, 90000, 100000}; int[][] ret = new int[this.numberTests][value.length]; for (int i = 0; i < this.numberTests; i++) { ret[i] = value.clone(); } return ret; } /** * Returns the classifier setups to use in the regression test. * * @return the setups */ @Override protected abstract Classifier[] getRegressionClassifierSetups(); /** * Returns the evaluator setups to use in the regression test. * * @return the setups */ @Override protected ClassificationPerformanceEvaluator[] getRegressionEvaluatorSetups() { ClassificationPerformanceEvaluator value = new BasicClassificationPerformanceEvaluator(); ClassificationPerformanceEvaluator[] ret = new ClassificationPerformanceEvaluator[this.numberTests]; for (int i = 0; i < this.numberTests; i++) { ret[i] = (ClassificationPerformanceEvaluator) value.copy(); } return ret; } }
Java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Regression.java * Copyright (C) 2010-2013 University of Waikato, Hamilton, New Zealand */ package moa.test; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.HashSet; import java.util.List; /** * Helper class for regression tests. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 8528 $ */ public class Regression { /** the storage place for reference files. */ public final static String REFERENCES = "src/test/resources"; /** the extension for references (incl dot). */ public final static String EXTENSION = ".ref"; /** the class this regression test is for. */ protected Class m_RegressionClass; /** the regression file to use. */ protected File m_ReferenceFile; /** * Initializes the regression check. * * @param cls the class that is being checked */ public Regression(Class cls) { super(); m_RegressionClass = cls; m_ReferenceFile = createReferenceFile(m_RegressionClass); } /** * Returns the class this regression helper is for. * * @return the class */ public Class getRegressionClass() { return m_RegressionClass; } /** * Sets the reference file to use. * <p/> * Normally, the reference file is determined based on the classname. * This method should only be called if a file different from the class * name must be used, for instance for an additional regression test. * * @param value the reference file to use */ public void setReferenceFile(File value) { m_ReferenceFile = value; } /** * Returns the file for storing the reference data in. * * @return the reference file */ public File getReferenceFile() { return m_ReferenceFile; } /** * Compares the content generated by the specified class with the stored * regression data. Creates a new reference file if not present yet. * * @param content the content to check * @return the difference (or an error message), null if no difference */ protected String compare(List<String> content) { String result; List<String> reference; // reference available? if (!getReferenceFile().exists()) { if (!getReferenceFile().getParentFile().exists()) { if (!getReferenceFile().getParentFile().mkdirs()) return "Failed to create reference file: " + m_ReferenceFile; } if (FileUtils.saveToFile(content, getReferenceFile())) { System.err.println("Reference file created: " + m_ReferenceFile); return null; } else { return "Failed to create reference file: " + m_ReferenceFile; } } // compare reference = FileUtils.loadFromFile(getReferenceFile()); result = DiffUtils.unified(reference, content); if (result.length() == 0) return null; else return result.toString(); } /** * Trims the list, i.e., removes the ignored indices from it. * * @param list the list to trim * @param ignore the ignored indices * @return the trimmed list */ public static List<String> trim(List<String> list, int[] ignore) { List<String> result; HashSet<Integer> ignored; int i; if (ignore.length == 0) return list; result = new ArrayList<String>(); ignored = new HashSet<Integer>(); for (int ign: ignore) ignored.add(ign); for (i = 0; i < list.size(); i++) { if (ignored.contains(i)) continue; result.add(list.get(i)); } return result; } /** * Compares the content generated by the specified class with the stored * regression data. Creates a new reference file if not present yet. * Uses "\n" for splitting the string content into lines. * * @param content the content to check * @return the difference, null if no difference */ public String compare(String content) { return compare(content, "\n"); } /** * Compares the content generated by the specified class with the stored * regression data. Creates a new reference file if not present yet. * Uses "\n" for splitting the string content into lines. * * @param content the content to check * @param ignore the indices of the lines to ignore * @return the difference, null if no difference */ public String compare(String content, int[] ignore) { return compare(content, "\n", ignore); } /** * Compares the content generated by the specified class with the stored * regression data. Creates a new reference file if not present yet. * * @param content the content to check * @param nl the new line string to use * @return the difference, null if no difference */ public String compare(String content, String nl) { return compare(content, nl, new int[0]); } /** * Compares the content generated by the specified class with the stored * regression data. Creates a new reference file if not present yet. * * @param content the content to check * @param nl the new line string to use * @param ignore the indices of the lines to ignore * @return the difference, null if no difference */ public String compare(String content, String nl, int[] ignore) { return compare(trim(Arrays.asList(content.split(nl)), ignore)); } /** * Compares the file content generated by the specified class with the stored * regression data. Creates a new reference file if not present yet. * * @param files the files containing the generated output to check * @return the difference, null if no difference */ public String compare(File[] files) { return compare(files, new int[0]); } /** * Compares the file content generated by the specified class with the stored * regression data. Creates a new reference file if not present yet. * * @param files the files containing the generated output to check * @param ignore the line indices in the files to ignore * @return the difference, null if no difference */ public String compare(File[] files, int[] ignore) { List<String> content; int i; content = new ArrayList<String>(); for (i = 0; i < files.length; i++) { content.add("--> " + files[i].getName()); if (!files[i].exists()) content.add("file is missing"); else content.addAll(trim(FileUtils.loadFromFile(files[i]), ignore)); content.add(""); } return compare(content); } /** * Creates a reference file for the specified class. * * @param regressionClass the class to build the reference file name for * @param suffix the suffix to use (between classname and extension), null to omit * @return the generated filename */ public static File createReferenceFile(Class regressionClass) { return createReferenceFile(regressionClass, null); } /** * Creates a reference file for the specified class. * * @param regressionClass the class to build the reference file name for * @param suffix the suffix to use (between classname and extension), null to omit * @return the generated filename */ public static File createReferenceFile(Class regressionClass, String suffix) { return createReferenceFile(regressionClass, suffix, EXTENSION); } /** * Creates a reference file for the specified class. * * @param regressionClass the class to build the reference file name for * @param suffix the suffix to use (between classname and extension), null to omit * @param extension the file extension (incl the dot, eg ".ref") * @return the generated filename */ public static File createReferenceFile(Class regressionClass, String suffix, String extension) { if (suffix == null) suffix = ""; return new File(REFERENCES + "/" + regressionClass.getName().replace(".", "/") + suffix + extension); } }
Java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * Utils.java * Copyright (C) 2013 University of Waikato, Hamilton, New Zealand */ package moa.test; import java.lang.reflect.Array; /** * Class with useful methods. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class Utils { /** * Returns the basic class of an array class (handles multi-dimensional * arrays). * @param c the array to inspect * @return the class of the innermost elements */ public static Class getArrayClass(Class c) { if (c.getComponentType().isArray()) return getArrayClass(c.getComponentType()); else return c.getComponentType(); } /** * Returns the dimensions of the given array. Even though the * parameter is of type "Object" one can hand over primitve arrays, e.g. * int[3] or double[2][4]. * * @param array the array to determine the dimensions for * @return the dimensions of the array */ public static int getArrayDimensions(Class array) { if (array.getComponentType().isArray()) return 1 + getArrayDimensions(array.getComponentType()); else return 1; } /** * Returns the dimensions of the given array. Even though the * parameter is of type "Object" one can hand over primitve arrays, e.g. * int[3] or double[2][4]. * * @param array the array to determine the dimensions for * @return the dimensions of the array */ public static int getArrayDimensions(Object array) { return getArrayDimensions(array.getClass()); } /** * Returns the given Array in a string representation. Even though the * parameter is of type "Object" one can hand over primitve arrays, e.g. * int[3] or double[2][4]. * * @param array the array to return in a string representation * @param outputClass whether to output the class name instead of calling * the object's "toString()" method * @return the array as string */ public static String arrayToString(Object array, boolean outputClass) { StringBuilder result; int dimensions; int i; Object obj; result = new StringBuilder(); dimensions = getArrayDimensions(array); if (dimensions == 0) { result.append("null"); } else if (dimensions == 1) { for (i = 0; i < Array.getLength(array); i++) { if (i > 0) result.append(","); if (Array.get(array, i) == null) { result.append("null"); } else { obj = Array.get(array, i); if (outputClass) { if (obj instanceof Class) result.append(((Class) obj).getName()); else result.append(obj.getClass().getName()); } else { result.append(obj.toString()); } } } } else { for (i = 0; i < Array.getLength(array); i++) { if (i > 0) result.append(","); result.append("[" + arrayToString(Array.get(array, i)) + "]"); } } return result.toString(); } /** * Returns the given Array in a string representation. Even though the * parameter is of type "Object" one can hand over primitve arrays, e.g. * int[3] or double[2][4]. * * @param array the array to return in a string representation * @return the array as string */ public static String arrayToString(Object array) { return arrayToString(array, false); } }
Java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /* * SerializedObject.java * Copyright (C) 2001 University of Waikato, Hamilton, New Zealand * */ package moa.test; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.util.zip.GZIPInputStream; import java.util.zip.GZIPOutputStream; /** * Class for storing an object in serialized form in memory. It can be used * to make deep copies of objects, and also allows compression to conserve * memory. * * @author Richard Kirkby (rbk1@cs.waikato.ac.nz) * @version $Revision: 4584 $ */ public class SerializedObject implements Serializable { /** for serialization. */ private static final long serialVersionUID = 6635502953928860434L; /** The array storing the object. */ private byte[] m_storedObjectArray; /** Whether or not the object is compressed. */ private boolean m_isCompressed; /** * Creates a new serialized object (without compression). * * @param o the object to store * @throws Exception if the object couldn't be serialized */ public SerializedObject(Serializable o) throws Exception { this(o, false); } /** * Creates a new serialized object. * * @param o the object to store * @param compress whether or not to use compression * @throws Exception if the object couldn't be serialized */ public SerializedObject(Serializable o, boolean compress) throws Exception { ByteArrayOutputStream ostream; ObjectOutputStream p; ostream = new ByteArrayOutputStream(); if (!compress) p = new ObjectOutputStream(new BufferedOutputStream(ostream)); else p = new ObjectOutputStream(new BufferedOutputStream(new GZIPOutputStream(ostream))); p.writeObject(o); p.flush(); p.close(); m_storedObjectArray = ostream.toByteArray(); m_isCompressed = compress; } /** * Checks to see whether this object is equal to another. * * @param o the object to compare to * @return whether or not the objects are equal */ @Override public boolean equals(Object o) { byte[] compareArray; int i; if (o == null) return false; if (!o.getClass().equals(this.getClass())) return false; compareArray = ((SerializedObject) o).m_storedObjectArray; if (compareArray.length != m_storedObjectArray.length) return false; for (i = 0; i < compareArray.length; i++) { if (compareArray[i] != m_storedObjectArray[i]) return false; } return true; } /** * Returns a hashcode for this object. * * @return the hashcode */ @Override public int hashCode() { return m_storedObjectArray.length; } /** * Returns a serialized object. * * @return the restored object */ public Object getObject() { ByteArrayInputStream istream; ObjectInputStream p; Object result; result = null; try { istream = new ByteArrayInputStream(m_storedObjectArray); if (!m_isCompressed) p = new ObjectInputStream(new BufferedInputStream(istream)); else p = new ObjectInputStream(new BufferedInputStream(new GZIPInputStream(istream))); result = p.readObject(); istream.close(); } catch (Exception e) { e.printStackTrace(); result = null; } return result; } /** * Returns the size of bytes stored. * * @return the number of bytes */ public int size() { return m_storedObjectArray.length; } /** * Writes the object to the given file. * * @param filename the file to write to * @param o the object to write * @return true if successfully written */ public static boolean write(String filename, Serializable o) { return write(new File(filename), o); } /** * Writes the object to the given file. * * @param file the file to write to * @param o the object to write * @return true if successfully written */ public static boolean write(File file, Serializable o) { boolean result; ObjectOutputStream oo; try { oo = new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(file))); oo.writeObject(o); oo.close(); result = true; } catch (Exception e) { e.printStackTrace(); result = false; } return result; } /** * Reads the object from the given file. * * @param filename the file to read from * @return if successful the object, otherwise null */ public static Object read(String filename) { return read(new File(filename)); } /** * Reads the object from the given file. * * @param file the file to read from * @return if successful the object, otherwise null */ public static Object read(File file) { Object result; ObjectInputStream oi; try { oi = new ObjectInputStream(new BufferedInputStream(new FileInputStream(file))); result = oi.readObject(); oi.close(); } catch (Exception ex) { result = null; } return result; } }
Java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * FileUtils.java * Copyright (C) 2013 University of Waikato, Hamilton, New Zealand */ package moa.test; import java.io.BufferedReader; import java.io.BufferedWriter; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.util.ArrayList; import java.util.List; /** * Basic file-handling stuff. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision$ */ public class FileUtils { /** * Returns the content of the given file, null in case of an error. * * @param file the file to load * @return the content/lines of the file */ public static List<String> loadFromFile(File file) { return loadFromFile(file, null); } /** * Returns the content of the given file, null in case of an error. * * @param file the file to load * @param encoding the encoding to use, null to use default * @return the content/lines of the file */ public static List<String> loadFromFile(File file, String encoding) { List<String> result; BufferedReader reader; String line; result = new ArrayList<String>(); try { if ((encoding != null) && (encoding.length() > 0)) reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getAbsolutePath()), encoding)); else reader = new BufferedReader(new InputStreamReader(new FileInputStream(file.getAbsolutePath()))); while ((line = reader.readLine()) != null) result.add(line); reader.close(); } catch (Exception e) { result = null; e.printStackTrace(); } return result; } /** * Saves the content to the given file. * * @param content the content to save * @param file the file to save the content to * @return true if successfully saved */ public static boolean saveToFile(String[] content, File file) { List<String> lines; int i; lines = new ArrayList<String>(); for (i = 0; i < content.length; i++) lines.add(content[i]); return FileUtils.saveToFile(lines, file); } /** * Saves the content to the given file. * * @param content the content to save * @param file the file to save the content to * @return true if successfully saved */ public static boolean saveToFile(List<String> content, File file) { return saveToFile(content, file, null); } /** * Saves the content to the given file. * * @param content the content to save * @param file the file to save the content to * @param encoding the encoding to use, null for default * @return true if successfully saved */ public static boolean saveToFile(List<String> content, File file, String encoding) { boolean result; BufferedWriter writer; int i; result = true; try { if ((encoding != null) && (encoding.length() > 0)) writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file.getAbsolutePath()), encoding)); else writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file.getAbsolutePath()))); for (i = 0; i < content.size(); i++) { writer.write(content.get(i)); writer.newLine(); } writer.flush(); writer.close(); } catch (Exception e) { result = false; e.printStackTrace(); } return result; } /** * Writes the given object to the specified file. The object is always * appended. * * @param filename the file to write to * @param obj the object to write * @return true if writing was successful */ public static boolean writeToFile(String filename, Object obj) { return writeToFile(filename, obj, null); } /** * Writes the given object to the specified file. The object is always * appended. * * @param filename the file to write to * @param obj the object to write * @param encoding the encoding to use, null for default * @return true if writing was successful */ public static boolean writeToFile(String filename, Object obj, String encoding) { return writeToFile(filename, obj, true, encoding); } /** * Writes the given object to the specified file. The message is either * appended or replaces the current content of the file. * * @param filename the file to write to * @param obj the object to write * @param append whether to append the message or not * @return true if writing was successful */ public static boolean writeToFile(String filename, Object obj, boolean append) { return writeToFile(filename, obj, append, null); } /** * Writes the given object to the specified file. The message is either * appended or replaces the current content of the file. * * @param filename the file to write to * @param obj the object to write * @param append whether to append the message or not * @param encoding the encoding to use, null for default * @return true if writing was successful */ public static boolean writeToFile(String filename, Object obj, boolean append, String encoding) { boolean result; BufferedWriter writer; try { if ((encoding != null) && (encoding.length() > 0)) writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, append), encoding)); else writer = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filename, append))); writer.write("" + obj); writer.newLine(); writer.flush(); writer.close(); result = true; } catch (Exception e) { result = false; } return result; } /** * Copies the file/directory (recursively). * * @param sourceLocation the source file/dir * @param targetLocation the target file/dir * @return if successfully copied * @throws IOException if copying fails */ public static boolean copy(File sourceLocation, File targetLocation) throws IOException { return copyOrMove(sourceLocation, targetLocation, false); } /** * Moves the file/directory (recursively). * * @param sourceLocation the source file/dir * @param targetLocation the target file/dir * @return if successfully moved * @throws IOException if moving fails */ public static boolean move(File sourceLocation, File targetLocation) throws IOException { return copyOrMove(sourceLocation, targetLocation, true); } /** * Copies or moves files and directories (recursively). * If targetLocation does not exist, it will be created. * <p/> * Original code from <a href="http://www.java-tips.org/java-se-tips/java.io/how-to-copy-a-directory-from-one-location-to-another-loc.html" target="_blank">Java-Tips.org</a>. * * @param sourceLocation the source file/dir * @param targetLocation the target file/dir * @param move if true then the source files/dirs get deleted * as soon as copying finished * @return false if failed to delete when moving or failed to create target directory * @throws IOException if copying/moving fails */ public static boolean copyOrMove(File sourceLocation, File targetLocation, boolean move) throws IOException { String[] children; int i; InputStream in; OutputStream out; byte[] buf; int len; if (sourceLocation.isDirectory()) { if (!targetLocation.exists()) { if (!targetLocation.mkdir()) return false; } children = sourceLocation.list(); for (i = 0; i < children.length; i++) { if (!copyOrMove( new File(sourceLocation.getAbsoluteFile(), children[i]), new File(targetLocation.getAbsoluteFile(), children[i]), move)) return false; } if (move) return sourceLocation.delete(); else return true; } else { in = new FileInputStream(sourceLocation.getAbsoluteFile()); // do we need to append the filename? if (targetLocation.isDirectory()) out = new FileOutputStream(targetLocation.getAbsolutePath() + File.separator + sourceLocation.getName()); else out = new FileOutputStream(targetLocation.getAbsoluteFile()); // Copy the content from instream to outstream buf = new byte[1024]; while ((len = in.read(buf)) > 0) out.write(buf, 0, len); in.close(); out.close(); if (move) return sourceLocation.delete(); else return true; } } }
Java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * MoaTestCase.java * Copyright (C) 2010-2013 University of Waikato, Hamilton, New Zealand */ package moa.test; import java.io.Serializable; import java.lang.reflect.Constructor; import junit.framework.Test; import junit.framework.TestCase; import junit.textui.TestRunner; /** * Ancestor for all test cases. * <p/> * Any regression test can be skipped as follows: <br/> * <code>-Dmoa.test.noregression=true</code> * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 8349 $ */ public class MoaTestCase extends TestCase { /** property indicating whether tests should be run in headless mode. */ public final static String PROPERTY_HEADLESS = "moa.test.headless"; /** property indicating whether regression tests should not be executed. */ public final static String PROPERTY_NOREGRESSION = "moa.test.noregression"; /** whether to execute any regression test. */ protected boolean m_NoRegressionTest; /** the helper class for regression. */ protected Regression m_Regression; /** the test class to use. */ protected AbstractTestHelper m_TestHelper; /** whether to run tests in headless mode. */ protected boolean m_Headless; /** * Constructs the test case. Called by subclasses. * * @param name the name of the test */ public MoaTestCase(String name) { super(name); } /** * Tries to load the class based on the test class's name. * * @return the class that is being tested or null if none could * be determined */ protected Class getTestedClass() { Class result; result = null; if (getClass().getName().endsWith("Test")) { try { result = Class.forName(getClass().getName().replaceAll("Test$", "")); } catch (Exception e) { result = null; } } return result; } /** * Returns whether the test can be executed in a headless environment. If not * then the test gets skipped. * * @return true if OK to run in headless mode */ protected boolean canHandleHeadless() { return true; } /** * Called by JUnit before each test method. * * @throws Exception if an error occurs. */ @Override protected void setUp() throws Exception { Class cls; super.setUp(); cls = getTestedClass(); if (cls != null) m_Regression = new Regression(cls); m_TestHelper = newTestHelper(); m_Headless = Boolean.getBoolean(PROPERTY_HEADLESS); m_NoRegressionTest = Boolean.getBoolean(PROPERTY_NOREGRESSION); } /** * Override to run the test and assert its state. Checks whether the test * or test-method is platform-specific. * * @throws Throwable if any exception is thrown */ @Override protected void runTest() throws Throwable { boolean proceed; proceed = true; if (m_Headless && !canHandleHeadless()) proceed = false; if (proceed) super.runTest(); else System.out.println("Skipped"); } /** * Called by JUnit after each test method. * * @throws Exception if tear-down fails */ @Override protected void tearDown() throws Exception { m_Regression = null; super.tearDown(); } /** * Returns the test helper class to use. * * @return the helper class instance */ protected AbstractTestHelper newTestHelper() { return new TestHelper(this, ""); } /** * Tries to obtain an instance of the given class. * * @param cls the class to obtain an instance from * @param intf the required interface that the class must implement * @param fail if true, errors/exceptions will result in a test fail */ protected Object getInstance(Class cls, Class intf, boolean fail) { Object result; Constructor constr; if (!intf.isAssignableFrom(cls)) return null; // default constructor? constr = null; try { constr = cls.getConstructor(new Class[0]); } catch (NoSuchMethodException e) { if (fail) fail("No default constructor, requires custom test method: " + cls.getName()); return null; } // create instance result = null; try { result = constr.newInstance(new Object[0]); } catch (Exception e) { if (fail) fail("Failed to instantiate object using default constructor: " + cls.getName()); return null; } return result; } /** * Creates a deep copy of the given object (must be serializable!). Returns * null in case of an error. * * @param o the object to copy * @return the deep copy */ protected Object deepCopy(Object o) { Object result; SerializedObject so; try { so = new SerializedObject((Serializable) o); result = so.getObject(); } catch (Exception e) { System.err.println("Failed to serialize " + o.getClass().getName() + ":"); e.printStackTrace(); result = null; } return result; } /** * Rounds a double and converts it into String. * * @param value the double value * @param afterDecimalPoint the (maximum) number of digits permitted * after the decimal point * @return the double as a formatted string */ public static String doubleToString(double value, int afterDecimalPoint) { StringBuilder builder; double temp; int dotPosition; int currentPos; long precisionValue; char separator; temp = value * Math.pow(10.0, afterDecimalPoint); if (Math.abs(temp) < Long.MAX_VALUE) { precisionValue = (temp > 0) ? (long)(temp + 0.5) : -(long)(Math.abs(temp) + 0.5); if (precisionValue == 0) builder = new StringBuilder(String.valueOf(0)); else builder = new StringBuilder(String.valueOf(precisionValue)); if (afterDecimalPoint == 0) return builder.toString(); separator = '.'; dotPosition = builder.length() - afterDecimalPoint; while (((precisionValue < 0) && (dotPosition < 1)) || (dotPosition < 0)) { if (precisionValue < 0) builder.insert(1, '0'); else builder.insert(0, '0'); dotPosition++; } builder.insert(dotPosition, separator); if ((precisionValue < 0) && (builder.charAt(1) == separator)) builder.insert(1, '0'); else if (builder.charAt(0) == separator) builder.insert(0, '0'); currentPos = builder.length() - 1; while ((currentPos > dotPosition) && (builder.charAt(currentPos) == '0')) builder.setCharAt(currentPos--, ' '); if (builder.charAt(currentPos) == separator) builder.setCharAt(currentPos, ' '); return builder.toString().trim(); } return new String("" + value); } /** * Performs a serializable test on the given class. * * @param cls the class to test */ protected void performSerializableTest(Class cls) { Object obj; obj = getInstance(cls, Serializable.class, true); if (obj == null) return; assertNotNull("Serialization failed", deepCopy(obj)); } /** * For classes (with default constructor) that are serializable, are tested * whether they are truly serializable. */ public void testSerializable() { if (m_Regression != null) performSerializableTest(m_Regression.getRegressionClass()); } /** * Runs the specified suite. Used for running the test from commandline. * * @param suite the suite to run */ public static void runTest(Test suite) { TestRunner.run(suite); } }
Java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * DiffUtils.java * Copyright (C) 2012 University of Waikato, Hamilton, New Zealand */ package moa.test; import java.io.File; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import difflib.Chunk; import difflib.DeleteDelta; import difflib.Delta; import difflib.InsertDelta; import difflib.Patch; /** * A helper class for generating diffs between two files, lists of strings. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 6358 $ */ public class DiffUtils { /** the indicator for "changed". */ public final static char INDICATOR_CHANGED = 'c'; /** the indicator for "added". */ public final static char INDICATOR_ADDED = 'a'; /** the indicator for "deleted". */ public final static char INDICATOR_DELETED = 'd'; /** the indicator for "same". */ public final static char INDICATOR_SAME = ' '; /** the source indicator. */ public final static String SOURCE = "<"; /** the destination indicator. */ public final static String DESTINATION = ">"; /** the separator for the unified output. */ public final static String SEPARATOR_UNIFIED = "---"; /** the separator for the side-by-side output on the command-line. */ public final static String SEPARATOR_SIDEBYSIDE = " | "; /** the unified option. */ public final static String OPTION_UNIFIED = "unified"; /** the side-by-side option. */ public final static String OPTION_SIDEBYSIDE = "side-by-side"; /** the brief option. */ public final static String OPTION_BRIEF = "brief"; /** the number of array elements in side-by-side diff. */ public final static int SIDEBYSIDE_SIZE = 5; /** the index for the first file in side-by-side diff. */ public final static int SIDEBYSIDE_FIRST = 0; /** the index for the second file in side-by-side diff. */ public final static int SIDEBYSIDE_SECOND = 1; /** the index for the indicator list in side-by-side diff. */ public final static int SIDEBYSIDE_INDICATOR = 2; /** the index for the list of start positions of deltas in side-by-side diff. */ public final static int SIDEBYSIDE_STARTPOS = 3; /** the index for the list of end positions of deltas in side-by-side diff. */ public final static int SIDEBYSIDE_ENDPOS = 4; /** * Container object for a side-by-side diff. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 6358 $ */ public static class SideBySideDiff implements Serializable, Cloneable { /** for serialization. */ private static final long serialVersionUID = -6775907286936991130L; /** the diff information. */ protected List[] m_Diff; /** * Initializes the container with an empty diff. */ public SideBySideDiff() { this( new List[]{ new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList(), new ArrayList()}); } /** * Initializes the container. */ public SideBySideDiff(List[] diff) { if (diff.length != SIDEBYSIDE_SIZE) throw new IllegalArgumentException("Expected array with length " + SIDEBYSIDE_SIZE + " but got: " + diff.length); m_Diff = diff.clone(); } /** * Return the diff of the left/first list/file. * * @return the diff */ public List getLeft() { return m_Diff[SIDEBYSIDE_FIRST]; } /** * Return the diff of the right/second list/file. * * @return the diff */ public List getRight() { return m_Diff[SIDEBYSIDE_SECOND]; } /** * Returns the indicator list. * * @return the indicator */ public List getIndicator() { return m_Diff[SIDEBYSIDE_INDICATOR]; } /** * Return the list with starting positions of the deltas. * * @return the list with start positions */ public List getStartPos() { return m_Diff[SIDEBYSIDE_STARTPOS]; } /** * Returns whether there are any differences between the two files/lists. * * @return true if there are differences */ public boolean hasDifferences() { return (m_Diff[SIDEBYSIDE_STARTPOS].size() > 0); } /** * Returns the number of differences. * * @return the number of differences */ public int differences() { return m_Diff[SIDEBYSIDE_STARTPOS].size(); } /** * Returns the closest patch delta index for the given line number. * * @param line the 0-based line number * @return the index of the delta, -1 if no delta matched */ public int lineToDelta(int line) { int result; int i; List start; List end; result = -1; if (!hasDifferences()) return result; start = m_Diff[SIDEBYSIDE_STARTPOS]; end = m_Diff[SIDEBYSIDE_ENDPOS]; for (i = 0; i < start.size(); i++) { if ((((Integer) start.get(i)) >= line) && (line <= ((Integer) end.get(i)))) { result = i; break; } } return result; } /** * Returns the line number (start or end) of the given delta. * * @param delta the 0-based delta index * @return the line number, -1 if failed to determine */ public int deltaToLine(int delta, boolean start) { int result; result = -1; if ((delta >= 0) && (delta < m_Diff[SIDEBYSIDE_STARTPOS].size())) { if (start) result = (Integer) m_Diff[SIDEBYSIDE_STARTPOS].get(delta); else result = (Integer) m_Diff[SIDEBYSIDE_ENDPOS].get(delta); } return result; } /** * Checks whether there is a next delta after the current line. * * @param line the current line number (0-based) * @return the next delta index, -1 if none available */ public boolean hasNextDelta(int line) { return (getNextDelta(line) != -1); } /** * Returns the next delta after the current line. * * @param line the current line number (0-based) * @return the next delta index, -1 if none available */ public int getNextDelta(int line) { int result; int delta; result = -1; delta = lineToDelta(line); if (delta == -1) return result; delta++; if (delta < m_Diff[SIDEBYSIDE_STARTPOS].size()) result = delta; return result; } /** * Checks whether there is a previous delta after the current line. * * @param line the current line number (0-based) * @return the previous delta index, -1 if none available */ public boolean hasPreviousDelta(int line) { return (getPreviousDelta(line) != -1); } /** * Returns the previous delta after the current line. * * @param line the current line number (0-based) * @return the previous delta index, -1 if none available */ public int getPreviousDelta(int line) { int result; int delta; result = -1; delta = lineToDelta(line); if (delta == -1) return result; delta--; if (delta >= 0) result = delta; return result; } /** * Returns a clone if itself. * * @return the clone */ @Override public SideBySideDiff clone() { return new SideBySideDiff(m_Diff); } /** * Generates a string representation of the diff information. * * @param separator the separator between the columns * @return the string representation */ public String toString(String separator) { StringBuilder result; int i; result = new StringBuilder(); for (i = 0; i < m_Diff[SIDEBYSIDE_FIRST].size(); i++) { result.append(m_Diff[SIDEBYSIDE_INDICATOR].get(i)); result.append(separator); result.append(m_Diff[SIDEBYSIDE_FIRST].get(i)); result.append(separator); result.append(m_Diff[SIDEBYSIDE_SECOND].get(i)); result.append("\n"); } return result.toString(); } /** * Generates a string representation of the diff information. * * @return the string representation */ @Override public String toString() { return toString(SEPARATOR_SIDEBYSIDE); } } /** * A helper class for the side-by-side diff. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 6358 $ */ public static class Filler implements Serializable { /** for serialization. */ private static final long serialVersionUID = 3295616348711569065L; /** * Indicates whether some other object is "equal to" this one. * * @param obj the reference object with which to compare. * @return <code>true</code> if the object is a {@link Filler} instance */ @Override public boolean equals(Object obj) { if (obj == null) return false; else if (obj instanceof Filler) return true; else return false; } /** * Returns a hash code value for the object. This method is * supported for the benefit of hashtables such as those provided by * <code>java.util.Hashtable</code>. * * @return a hash code value for this object. */ @Override public int hashCode() { return toString().hashCode(); } /** * Returns an empty string. * * @return empty string */ @Override public String toString() { return ""; } } /** * Loads the file. If file points to a directory, an empty vector is * returned instead. * * @param file the file to load * @return the content of the file, empty vector if directory */ protected static List<String> loadFromFile(File file) { if (file.isDirectory()) return new ArrayList<String>(); else return FileUtils.loadFromFile(file); } /** * Returns whether the two files differ. * * @param file1 the first text file * @param file2 the second text file * @return true if different */ public static boolean isDifferent(File file1, File file2) { return isDifferent(loadFromFile(file1), loadFromFile(file2)); } /** * Returns whether the two lists differ. * * @param file1 the first list * @param file2 the second list * @return true if different */ public static boolean isDifferent(String[] list1, String[] list2) { return isDifferent(Arrays.asList(list1), Arrays.asList(list2)); } /** * Returns whether the two lists differ. * * @param file1 the first text file * @param file2 the second text file * @return the side-by-side diff (first file: index 0, second file: index 1, indicator: ) */ public static boolean isDifferent(List<String> list1, List<String> list2) { boolean result; Patch patch; patch = difflib.DiffUtils.diff(list1, list2); result = (patch.getDeltas().size() > 0); return result; } /** * Assembles the lines into a string. * * @param ind the indicator string * @param lines the underlying lines * @return the generated string */ protected static String toString(String ind, List lines) { StringBuilder result; result = new StringBuilder(); for (Object line: lines) result.append(ind + " " + line + "\n"); return result.toString(); } /** * Generates a unified diff for the two files. * * @param file1 the first text file * @param file2 the second text file * @return the unified diff */ public static String unified(File file1, File file2) { return unified(loadFromFile(file1), loadFromFile(file2)); } /** * Creates a range string. * * @param chunk the chunk to create the range string for * @return the range string */ protected static String createRange(Chunk chunk) { if (chunk.size() == 1) return (chunk.getPosition() + 1) + ""; else return (chunk.getPosition() + 1) + "," + (chunk.getPosition() + chunk.size()); } /** * Generates a unified diff for the two lists. * * @param file1 the first list * @param file2 the second list * @return the unified diff */ public static String unified(List<String> list1, List<String> list2) { StringBuilder result; Patch patch; patch = difflib.DiffUtils.diff(list1, list2); result = new StringBuilder(); for (Delta delta: patch.getDeltas()) { if (delta instanceof InsertDelta) { result.append(delta.getOriginal().getPosition() + "a" + createRange(delta.getRevised()) + "\n"); result.append(toString(DESTINATION, delta.getRevised().getLines())); } else if (delta instanceof DeleteDelta) { result.append(createRange(delta.getOriginal()) + "d" + delta.getRevised().getPosition() + "\n"); result.append(toString(SOURCE, delta.getOriginal().getLines())); } else { result.append(createRange(delta.getOriginal()) + "c"); result.append(createRange(delta.getRevised()) + "\n"); result.append(toString(SOURCE, delta.getOriginal().getLines())); result.append(SEPARATOR_UNIFIED + "\n"); result.append(toString(DESTINATION, delta.getRevised().getLines())); } } return result.toString(); } /** * Generates a side-by-side diff for the two files. * * @param file1 the first text file * @param file2 the second text file * @return the side-by-side diff */ public static SideBySideDiff sideBySide(File file1, File file2) { return sideBySide(loadFromFile(file1), loadFromFile(file2)); } /** * Generates a side-by-side diff for the two lists. * * @param file1 the first list * @param file2 the second list * @return the side-by-side diff */ public static SideBySideDiff sideBySide(String[] list1, String[] list2) { return sideBySide(Arrays.asList(list1), Arrays.asList(list2)); } /** * Adds the specified contents of the source list to the destination list. * * @param from the starting index * @param to the ending index (included) * @param source the source list * @param dest the destination of the data */ protected static void addToList(int from, int to, List<String> source, List dest) { for (int i = from; i <= to; i++) dest.add(source.get(i)); } /** * Adds the object to the destination list. * * @param from the starting index * @param to the ending index (included) * @param dest the destination of the data */ protected static void addToList(int from, int to, Object obj, List dest) { for (int i = from; i <= to; i++) dest.add(obj); } /** * Generates a side-by-side diff for the two lists. * * @param file1 the first text file * @param file2 the second text file * @return the side-by-side diff */ public static SideBySideDiff sideBySide(List<String> list1, List<String> list2) { List[] result; Patch patch; int from; int to; int sizeDiff; result = new List[SIDEBYSIDE_SIZE]; result[SIDEBYSIDE_FIRST] = new ArrayList(); result[SIDEBYSIDE_SECOND] = new ArrayList(); result[SIDEBYSIDE_INDICATOR] = new ArrayList(); result[SIDEBYSIDE_STARTPOS] = new ArrayList(); result[SIDEBYSIDE_ENDPOS] = new ArrayList(); patch = difflib.DiffUtils.diff(list1, list2); // the same? if (patch.getDeltas().size() == 0) { result[SIDEBYSIDE_FIRST].addAll(list1); result[SIDEBYSIDE_SECOND].addAll(list2); addToList(0, list1.size() - 1, INDICATOR_SAME, result[SIDEBYSIDE_INDICATOR]); return new SideBySideDiff(result); } to = 0; for (Delta delta: patch.getDeltas()) { from = to; // common content to = delta.getOriginal().getPosition() - 1; addToList(from, to, list1, result[SIDEBYSIDE_FIRST]); addToList(from, to, list1, result[SIDEBYSIDE_SECOND]); addToList(from, to, INDICATOR_SAME, result[SIDEBYSIDE_INDICATOR]); // start pos of delta result[SIDEBYSIDE_STARTPOS].add(result[SIDEBYSIDE_FIRST].size()); if (delta instanceof InsertDelta) { // added content addToList(0, delta.getRevised().size() - 1, new Filler(), result[SIDEBYSIDE_FIRST]); result[SIDEBYSIDE_SECOND].addAll(delta.getRevised().getLines()); addToList(0, delta.getRevised().size() - 1, INDICATOR_ADDED, result[SIDEBYSIDE_INDICATOR]); to = delta.getOriginal().getPosition() + delta.getOriginal().size(); } else if (delta instanceof DeleteDelta) { // deleted content result[SIDEBYSIDE_FIRST].addAll(delta.getOriginal().getLines()); addToList(0, delta.getOriginal().size() - 1, new Filler(), result[SIDEBYSIDE_SECOND]); addToList(0, delta.getOriginal().size() - 1, INDICATOR_DELETED, result[SIDEBYSIDE_INDICATOR]); to = delta.getOriginal().getPosition() + delta.getOriginal().size(); } else { // changed content result[SIDEBYSIDE_FIRST].addAll(delta.getOriginal().getLines()); result[SIDEBYSIDE_SECOND].addAll(delta.getRevised().getLines()); addToList(1, Math.max(delta.getOriginal().size(), delta.getRevised().size()), INDICATOR_CHANGED, result[SIDEBYSIDE_INDICATOR]); // filler necessary? sizeDiff = delta.getRevised().size() - delta.getOriginal().size(); if (sizeDiff > 0) addToList(1, sizeDiff, new Filler(), result[SIDEBYSIDE_FIRST]); if (sizeDiff < 0) addToList(1, -sizeDiff, new Filler(), result[SIDEBYSIDE_SECOND]); to = delta.getOriginal().getPosition() + delta.getOriginal().size(); } // end pos of delta result[SIDEBYSIDE_ENDPOS].add(result[SIDEBYSIDE_FIRST].size()); } // trailing common content? if (to < list1.size()) { addToList(to, list1.size() - 1, list1, result[SIDEBYSIDE_FIRST]); addToList(to, list1.size() - 1, list1, result[SIDEBYSIDE_SECOND]); addToList(to, list1.size() - 1, INDICATOR_SAME, result[SIDEBYSIDE_INDICATOR]); } return new SideBySideDiff(result); } /** * Usage: DiffUtils &lt;unified|side-by-side|brief&gt; &lt;file1&gt; &lt;file2&gt; * * @param args the files to compare * @throws Exception if comparison fails */ public static void main(String[] args) throws Exception { if (args.length == 3) { File file1 = new File(args[1]); if (file1.isDirectory()) { System.err.println("File '" + file1 + "' is a directory!"); return; } if (!file1.exists()) { System.err.println("File '" + file1 + "' does not exist!"); return; } File file2 = new File(args[2]); if (file2.isDirectory()) { System.err.println("File '" + file2 + "' is a directory!"); return; } if (!file2.exists()) { System.err.println("File '" + file2 + "' does not exist!"); return; } if (args[0].equals(OPTION_UNIFIED)) { System.out.println(unified(file1, file2)); } else if (args[0].equals(OPTION_SIDEBYSIDE)) { System.out.println(sideBySide(file1, file2)); } else if (args[0].equals(OPTION_BRIEF)) { if (isDifferent(file1, file2)) System.out.println("Files " + file1 + " and " + file2 + " differ"); } else { System.err.println("Only '" + OPTION_UNIFIED + "', '" + OPTION_SIDEBYSIDE + "' and '" + OPTION_BRIEF + "' are available as options!"); return; } } else { System.err.println("\nUsage: " + DiffUtils.class.getName() + " <" + OPTION_UNIFIED + "|" + OPTION_SIDEBYSIDE + "|" + OPTION_BRIEF + "> <file1> <file2>\n"); return; } } }
Java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * TmpFile.java * Copyright (C) 2010 University of Waikato, Hamilton, New Zealand */ package moa.test; import java.io.File; /** * A simple file handler class that automatically places the file in the * system's tmp directory. But the user still needs to delete the file * manually when it's no longer used. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 4584 $ */ public class TmpFile extends File { /** for serialization. */ private static final long serialVersionUID = 4323672645601038764L; /** * Creates a new <code>File</code> instance by converting the given * pathname string into an abstract pathname. If the given string is * the empty string, then the result is the empty abstract pathname. * Creates a file object pointing to the tmp directory. */ public TmpFile() { super(System.getProperty("java.io.tmpdir")); } /** * Creates a new <code>File</code> instance by converting the given * pathname string into an abstract pathname. If the given string is * the empty string, then the result is the empty abstract pathname. * * @param pathname A pathname string */ public TmpFile(String pathname) { super(System.getProperty("java.io.tmpdir") + separator + pathname); } }
Java
/* * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ /** * TestHelper.java * Copyright (C) 2010-2013 University of Waikato, Hamilton, New Zealand */ package moa.test; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; /** * Ancestor for helper classes for tests. * * @author fracpete (fracpete at waikato dot ac dot nz) * @version $Revision: 4584 $ * @param <I> the type of data to process (input) * @param <O> the type of data to process (output) */ public abstract class AbstractTestHelper<I, O> { /** the owning test case. */ protected MoaTestCase m_Owner; /** the data directory to use. */ protected String m_DataDirectory; /** * Initializes the helper class. * * @param owner the owning test case * @param dataDir the data directory to use */ public AbstractTestHelper(MoaTestCase owner, String dataDir) { super(); m_Owner = owner; m_DataDirectory = dataDir; } /** * Returns the data directory in use. * * @return the directory */ public String getDataDirectory() { return m_DataDirectory; } /** * Returns the tmp directory. * * @return the tmp directory */ public String getTmpDirectory() { return System.getProperty("java.io.tmpdir"); } /** * Returns the location in the tmp directory for given resource. * * @param resource the resource (path in project) to get the tmp location for * @return the tmp location * @see #getTmpDirectory() */ public String getTmpLocationFromResource(String resource) { String result; File file; file = new File(resource); result = getTmpDirectory() + File.separator + file.getName(); return result; } /** * Copies the given resource to the tmp directory. * * @param resource the resource (path in project) to copy * @return false if copying failed * @see #getTmpLocationFromResource(String) */ public boolean copyResourceToTmp(String resource) { boolean result; BufferedInputStream input; BufferedOutputStream output; byte[] buffer; int read; String ext; input = null; output = null; resource = getDataDirectory() + "/" + resource; try { input = new BufferedInputStream(ClassLoader.getSystemResourceAsStream(resource)); output = new BufferedOutputStream(new FileOutputStream(getTmpLocationFromResource(resource))); buffer = new byte[1024]; while ((read = input.read(buffer)) != -1) { output.write(buffer, 0, read); if (read < buffer.length) break; } result = true; } catch (IOException e) { if (e.getMessage().equals("Stream closed")) { ext = resource.replaceAll(".*\\.", ""); System.err.println( "Resource '" + resource + "' not available? " + "Or extension '*." + ext + "' not in pom.xml ('project.build.testSourceDirectory') listed?"); } e.printStackTrace(); result = false; } catch (Exception e) { e.printStackTrace(); result = false; } if (input != null) { try { input.close(); } catch (Exception e) { // ignored } } if (output != null) { try { output.close(); } catch (Exception e) { // ignored } } return result; } /** * Copies the given resource to the tmp directory and renames it. * * @param resource the resource (path in project) to copy * @param newName the new name of the file * @return false if copying/renaming failed * @see #copyResourceToTmp(String) * @see #renameTmpFile(String, String) */ public boolean copyResourceToTmp(String resource, String newName) { boolean result; result = copyResourceToTmp(resource); if (result) result = renameTmpFile(resource, newName); return result; } /** * Removes the file from the tmp directory. * * @param filename the file in the tmp directory to delete (no path!) * @return true if deleting succeeded or file not present * @see #getTmpLocationFromResource(String) */ public boolean deleteFileFromTmp(String filename) { boolean result; File file; result = true; file = new File(getTmpDirectory() + File.separator + filename); if (file.exists()) result = file.delete(); return result; } /** * Renames a file in the tmp directory. * * @param oldName the old name of the file * @param newName the new name of the file * @return true if renaming succeeded or file not present */ public boolean renameTmpFile(String oldName, String newName) { boolean result; File oldFile; File newFile; result = true; oldFile = new File(getTmpDirectory() + File.separator + oldName); if (oldFile.exists()) { newFile = new File(getTmpDirectory() + File.separator + newName); try { FileUtils.move(oldFile, newFile); result = newFile.exists(); } catch (Exception e) { System.err.println("Failed to move file '" + oldFile + "' to '" + newFile + "':"); e.printStackTrace(); result = false; } } return result; } /** * Loads the data to process. * * @param filename the filename to load (without path) * @return the data, null if it could not be loaded * @see #getDataDirectory() */ public abstract I load(String filename); /** * Saves the data in the tmp directory. * * @param data the data to save * @param filename the filename to save to (without path) * @return true if successfully saved */ public abstract boolean save(O data, String filename); }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.math; import static java.math.BigInteger.ONE; import static java.math.BigInteger.ZERO; import static java.math.RoundingMode.CEILING; import static java.math.RoundingMode.DOWN; import static java.math.RoundingMode.FLOOR; import static java.math.RoundingMode.HALF_DOWN; import static java.math.RoundingMode.HALF_EVEN; import static java.math.RoundingMode.HALF_UP; import static java.math.RoundingMode.UP; import static java.util.Arrays.asList; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Function; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Iterables; import com.google.common.primitives.Doubles; import java.math.BigInteger; import java.math.RoundingMode; /** * Exhaustive input sets for every integral type. * * @author lowasser@google.com (Louis Wasserman) */ @GwtCompatible public class MathTesting { static final ImmutableSet<RoundingMode> ALL_ROUNDING_MODES = ImmutableSet.copyOf(RoundingMode .values()); static final ImmutableList<RoundingMode> ALL_SAFE_ROUNDING_MODES = ImmutableList.of(DOWN, UP, FLOOR, CEILING, HALF_EVEN, HALF_UP, HALF_DOWN); // Exponents to test for the pow() function. static final ImmutableList<Integer> EXPONENTS = ImmutableList.of(0, 1, 2, 3, 4, 5, 6, 7, 10, 15, 20, 25, 30, 40, 70); /* Helper function to make a Long value from an Integer. */ private static final Function<Integer, Long> TO_LONG = new Function<Integer, Long>() { @Override public Long apply(Integer n) { return Long.valueOf(n); } }; /* Helper function to make a BigInteger value from a Long. */ private static final Function<Long, BigInteger> TO_BIGINTEGER = new Function<Long, BigInteger>() { @Override public BigInteger apply(Long n) { return BigInteger.valueOf(n); } }; private static final Function<Integer, Integer> NEGATE_INT = new Function<Integer, Integer>() { @Override public Integer apply(Integer x) { return -x; } }; private static final Function<Long, Long> NEGATE_LONG = new Function<Long, Long>() { @Override public Long apply(Long x) { return -x; } }; private static final Function<BigInteger, BigInteger> NEGATE_BIGINT = new Function<BigInteger, BigInteger>() { @Override public BigInteger apply(BigInteger x) { return x.negate(); } }; /* * This list contains values that attempt to provoke overflow in integer operations. It contains * positive values on or near 2^N for N near multiples of 8 (near byte boundaries). */ static final ImmutableSet<Integer> POSITIVE_INTEGER_CANDIDATES; static final Iterable<Integer> NEGATIVE_INTEGER_CANDIDATES; static final Iterable<Integer> NONZERO_INTEGER_CANDIDATES; static final Iterable<Integer> ALL_INTEGER_CANDIDATES; static { ImmutableSet.Builder<Integer> intValues = ImmutableSet.builder(); // Add boundary values manually to avoid over/under flow (this covers 2^N for 0 and 31). intValues.add(Integer.MAX_VALUE - 1, Integer.MAX_VALUE); // Add values up to 64. This covers cases like "square of a prime" and such. for (int i = 1; i <= 64; i++) { intValues.add(i); } // Now add values near 2^N for lots of values of N. for (int exponent : asList(2, 3, 4, 5, 6, 7, 8, 9, 15, 16, 17, 23, 24, 25)) { int x = 1 << exponent; intValues.add(x, x + 1, x - 1); } intValues.add(9999).add(10000).add(10001).add(1000000); // near powers of 10 intValues.add(5792).add(5793); // sqrt(2^25) rounded up and down POSITIVE_INTEGER_CANDIDATES = intValues.build(); NEGATIVE_INTEGER_CANDIDATES = Iterables.concat(Iterables.transform(POSITIVE_INTEGER_CANDIDATES, NEGATE_INT), ImmutableList.of(Integer.MIN_VALUE)); NONZERO_INTEGER_CANDIDATES = Iterables.concat(POSITIVE_INTEGER_CANDIDATES, NEGATIVE_INTEGER_CANDIDATES); ALL_INTEGER_CANDIDATES = Iterables.concat(NONZERO_INTEGER_CANDIDATES, ImmutableList.of(0)); } /* * This list contains values that attempt to provoke overflow in long operations. It contains * positive values on or near 2^N for N near multiples of 8 (near byte boundaries). This list is * a superset of POSITIVE_INTEGER_CANDIDATES. */ static final ImmutableSet<Long> POSITIVE_LONG_CANDIDATES; static final Iterable<Long> NEGATIVE_LONG_CANDIDATES; static final Iterable<Long> NONZERO_LONG_CANDIDATES; static final Iterable<Long> ALL_LONG_CANDIDATES; static { ImmutableSet.Builder<Long> longValues = ImmutableSet.builder(); // First of all add all the integer candidate values. longValues.addAll(Iterables.transform(POSITIVE_INTEGER_CANDIDATES, TO_LONG)); // Add boundary values manually to avoid over/under flow (this covers 2^N for 31 and 63). longValues.add(Integer.MAX_VALUE + 1L, Long.MAX_VALUE - 1L, Long.MAX_VALUE); // Now add values near 2^N for lots of values of N. for (int exponent : asList(32, 33, 39, 40, 41, 47, 48, 49, 55, 56, 57)) { long x = 1L << exponent; longValues.add(x, x + 1, x - 1); } longValues.add(194368031998L).add(194368031999L); // sqrt(2^75) rounded up and down POSITIVE_LONG_CANDIDATES = longValues.build(); NEGATIVE_LONG_CANDIDATES = Iterables.concat(Iterables.transform(POSITIVE_LONG_CANDIDATES, NEGATE_LONG), ImmutableList.of(Long.MIN_VALUE)); NONZERO_LONG_CANDIDATES = Iterables.concat(POSITIVE_LONG_CANDIDATES, NEGATIVE_LONG_CANDIDATES); ALL_LONG_CANDIDATES = Iterables.concat(NONZERO_LONG_CANDIDATES, ImmutableList.of(0L)); } /* * This list contains values that attempt to provoke overflow in big integer operations. It * contains positive values on or near 2^N for N near multiples of 8 (near byte boundaries). This * list is a superset of POSITIVE_LONG_CANDIDATES. */ static final ImmutableSet<BigInteger> POSITIVE_BIGINTEGER_CANDIDATES; static final Iterable<BigInteger> NEGATIVE_BIGINTEGER_CANDIDATES; static final Iterable<BigInteger> NONZERO_BIGINTEGER_CANDIDATES; static final Iterable<BigInteger> ALL_BIGINTEGER_CANDIDATES; static { ImmutableSet.Builder<BigInteger> bigValues = ImmutableSet.builder(); // First of all add all the long candidate values. bigValues.addAll(Iterables.transform(POSITIVE_LONG_CANDIDATES, TO_BIGINTEGER)); // Add boundary values manually to avoid over/under flow. bigValues.add(BigInteger.valueOf(Long.MAX_VALUE).add(ONE)); // Now add values near 2^N for lots of values of N. for (int exponent : asList(64, 65, 71, 72, 73, 79, 80, 81, 255, 256, 257, 511, 512, 513, Double.MAX_EXPONENT - 1, Double.MAX_EXPONENT, Double.MAX_EXPONENT + 1)) { BigInteger x = ONE.shiftLeft(exponent); bigValues.add(x, x.add(ONE), x.subtract(ONE)); } bigValues.add(new BigInteger("218838949120258359057546633")); // sqrt(2^175) rounded up and // down bigValues.add(new BigInteger("218838949120258359057546634")); POSITIVE_BIGINTEGER_CANDIDATES = bigValues.build(); NEGATIVE_BIGINTEGER_CANDIDATES = Iterables.transform(POSITIVE_BIGINTEGER_CANDIDATES, NEGATE_BIGINT); NONZERO_BIGINTEGER_CANDIDATES = Iterables.concat(POSITIVE_BIGINTEGER_CANDIDATES, NEGATIVE_BIGINTEGER_CANDIDATES); ALL_BIGINTEGER_CANDIDATES = Iterables.concat(NONZERO_BIGINTEGER_CANDIDATES, ImmutableList.of(ZERO)); } static final ImmutableSet<Double> INTEGRAL_DOUBLE_CANDIDATES; static final ImmutableSet<Double> FRACTIONAL_DOUBLE_CANDIDATES; static final Iterable<Double> FINITE_DOUBLE_CANDIDATES; static final Iterable<Double> POSITIVE_FINITE_DOUBLE_CANDIDATES; static final Iterable<Double> ALL_DOUBLE_CANDIDATES; static { ImmutableSet.Builder<Double> integralBuilder = ImmutableSet.builder(); ImmutableSet.Builder<Double> fractionalBuilder = ImmutableSet.builder(); integralBuilder.addAll(Doubles.asList(0.0, -0.0, Double.MAX_VALUE, -Double.MAX_VALUE)); // Add small multiples of MIN_VALUE and MIN_NORMAL for (int scale = 1; scale <= 4; scale++) { for (double d : Doubles.asList(Double.MIN_VALUE, Double.MIN_NORMAL)) { fractionalBuilder.add(d * scale).add(-d * scale); } } for (double d : Doubles.asList(0, 1, 2, 7, 51, 102, Math.scalb(1.0, 53), Integer.MIN_VALUE, Integer.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE)) { for (double delta : Doubles.asList(0.0, 1.0, 2.0)) { integralBuilder.addAll(Doubles.asList(d + delta, d - delta, -d - delta, -d + delta)); } for (double delta : Doubles.asList(0.01, 0.1, 0.25, 0.499, 0.5, 0.501, 0.7, 0.8)) { double x = d + delta; if (x != Math.round(x)) { fractionalBuilder.add(x); } } } INTEGRAL_DOUBLE_CANDIDATES = integralBuilder.build(); fractionalBuilder.add(1.414).add(1.415).add(Math.sqrt(2)); fractionalBuilder.add(5.656).add(5.657).add(4 * Math.sqrt(2)); for (double d : INTEGRAL_DOUBLE_CANDIDATES) { double x = 1 / d; if (x != Math.rint(x)) { fractionalBuilder.add(x); } } FRACTIONAL_DOUBLE_CANDIDATES = fractionalBuilder.build(); FINITE_DOUBLE_CANDIDATES = Iterables.concat(FRACTIONAL_DOUBLE_CANDIDATES, INTEGRAL_DOUBLE_CANDIDATES); POSITIVE_FINITE_DOUBLE_CANDIDATES = Iterables.filter(FINITE_DOUBLE_CANDIDATES, new Predicate<Double>() { @Override public boolean apply(Double input) { return input.doubleValue() > 0.0; } }); ALL_DOUBLE_CANDIDATES = Iterables.concat(FINITE_DOUBLE_CANDIDATES, asList(Double.POSITIVE_INFINITY, Double.NEGATIVE_INFINITY, Double.NaN)); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.eventbus; import com.google.common.collect.Lists; import java.util.List; import junit.framework.Assert; /** * A simple EventHandler mock that records Strings. * * For testing fun, also includes a landmine method that EventBus tests are * required <em>not</em> to call ({@link #methodWithoutAnnotation(String)}). * * @author Cliff Biffle */ public class StringCatcher { private List<String> events = Lists.newArrayList(); @Subscribe public void hereHaveAString(String string) { events.add(string); } public void methodWithoutAnnotation(String string) { Assert.fail("Event bus must not call methods without @Subscribe!"); } public List<String> getEvents() { return events; } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.Arrays; /** * A class that implements {@code Comparable} without generics, such as those * found in libraries that support Java 1.4 and before. Our library needs to * do the bare minimum to accommodate such types, though their use may still * require an explicit type parameter and/or warning suppression. * * @author Kevin Bourrillion */ @GwtCompatible class LegacyComparable implements Comparable, Serializable { static final LegacyComparable X = new LegacyComparable("x"); static final LegacyComparable Y = new LegacyComparable("y"); static final LegacyComparable Z = new LegacyComparable("z"); static final Iterable<LegacyComparable> VALUES_FORWARD = Arrays.asList(X, Y, Z); static final Iterable<LegacyComparable> VALUES_BACKWARD = Arrays.asList(Z, Y, X); private final String value; LegacyComparable(String value) { this.value = value; } @Override public int compareTo(Object object) { // This method is spec'd to throw CCE if object is of the wrong type LegacyComparable that = (LegacyComparable) object; return this.value.compareTo(that.value); } @Override public boolean equals(Object object) { if (object instanceof LegacyComparable) { LegacyComparable that = (LegacyComparable) object; return this.value.equals(that.value); } return false; } @Override public int hashCode() { return value.hashCode(); } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.base.Function; import com.google.common.base.Joiner; import junit.framework.TestCase; import java.lang.reflect.Array; import java.lang.reflect.InvocationHandler; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Proxy; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; /** * Base test case for testing the variety of forwarding classes. * * @author Robert Konigsberg * @author Louis Wasserman */ public abstract class ForwardingTestCase extends TestCase { private List<String> calls = new ArrayList<String>(); private void called(String id) { calls.add(id); } protected String getCalls() { return calls.toString(); } protected boolean isCalled() { return !calls.isEmpty(); } @SuppressWarnings("unchecked") protected <T> T createProxyInstance(Class<T> c) { /* * This invocation handler only registers that a method was called, * and then returns a bogus, but acceptable, value. */ InvocationHandler handler = new InvocationHandler() { @Override public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { called(asString(method)); return getDefaultValue(method.getReturnType()); } }; return (T) Proxy.newProxyInstance(c.getClassLoader(), new Class[] { c }, handler); } private static final Joiner COMMA_JOINER = Joiner.on(","); /* * Returns string representation of a method. * * If the method takes no parameters, it returns the name (e.g. * "isEmpty". If the method takes parameters, it returns the simple names * of the parameters (e.g. "put(Object,Object)".) */ private String asString(Method method) { String methodName = method.getName(); Class<?>[] parameterTypes = method.getParameterTypes(); if (parameterTypes.length == 0) { return methodName; } Iterable<String> parameterNames = Iterables.transform( Arrays.asList(parameterTypes), new Function<Class<?>, String>() { @Override public String apply(Class<?> from) { return from.getSimpleName(); } }); return methodName + "(" + COMMA_JOINER.join(parameterNames) + ")"; } private static Object getDefaultValue(Class<?> returnType) { if (returnType == boolean.class || returnType == Boolean.class) { return Boolean.FALSE; } else if (returnType == int.class || returnType == Integer.class) { return 0; } else if ((returnType == Set.class) || (returnType == Collection.class)) { return Collections.emptySet(); } else if (returnType == Iterator.class){ return Iterators.emptyModifiableIterator(); } else if (returnType.isArray()) { return Array.newInstance(returnType.getComponentType(), 0); } else { return null; } } protected static <T> void callAllPublicMethods(Class<T> theClass, T object) throws InvocationTargetException { for (Method method : theClass.getMethods()) { Class<?>[] parameterTypes = method.getParameterTypes(); Object[] parameters = new Object[parameterTypes.length]; for (int i = 0; i < parameterTypes.length; i++) { parameters[i] = getDefaultValue(parameterTypes[i]); } try { try { method.invoke(object, parameters); } catch (InvocationTargetException ex) { try { throw ex.getCause(); } catch (UnsupportedOperationException unsupported) { // this is a legit exception } } } catch (Throwable cause) { throw new InvocationTargetException(cause, method.toString() + " with args: " + Arrays.toString(parameters)); } } } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.BstSide.LEFT; import static com.google.common.collect.BstSide.RIGHT; import static junit.framework.Assert.assertEquals; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.base.Objects; import com.google.common.testing.NullPointerTester; import java.util.List; import javax.annotation.Nullable; /** * Testing classes and utilities to be used in tests of the binary search tree framework. * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class BstTesting { static final class SimpleNode extends BstNode<Character, SimpleNode> { SimpleNode(Character key, @Nullable SimpleNode left, @Nullable SimpleNode right) { super(key, left, right); } @Override public String toString() { return getKey().toString(); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof SimpleNode) { SimpleNode node = (SimpleNode) obj; return getKey().equals(node.getKey()) && Objects.equal(childOrNull(LEFT), node.childOrNull(LEFT)) && Objects.equal(childOrNull(RIGHT), node.childOrNull(RIGHT)); } return false; } @Override public int hashCode() { return Objects.hashCode(getKey(), childOrNull(LEFT), childOrNull(RIGHT)); } } static final BstNodeFactory<SimpleNode> nodeFactory = new BstNodeFactory<SimpleNode>() { @Override public SimpleNode createNode( SimpleNode source, @Nullable SimpleNode left, @Nullable SimpleNode right) { return new SimpleNode(source.getKey(), left, right); } }; static final BstBalancePolicy<SimpleNode> balancePolicy = new BstBalancePolicy<SimpleNode>() { @Override public SimpleNode balance(BstNodeFactory<SimpleNode> nodeFactory, SimpleNode source, @Nullable SimpleNode left, @Nullable SimpleNode right) { return checkNotNull(nodeFactory).createNode(source, left, right); } @Nullable @Override public SimpleNode combine(BstNodeFactory<SimpleNode> nodeFactory, @Nullable SimpleNode left, @Nullable SimpleNode right) { // Shove right into the rightmost position in the left tree. if (left == null) { return right; } else if (right == null) { return left; } else if (left.hasChild(RIGHT)) { return nodeFactory.createNode( left, left.childOrNull(LEFT), combine(nodeFactory, left.childOrNull(RIGHT), right)); } else { return nodeFactory.createNode(left, left.childOrNull(LEFT), right); } } }; static final BstPathFactory<SimpleNode, BstInOrderPath<SimpleNode>> pathFactory = BstInOrderPath.inOrderFactory(); // A direct, if dumb, way to count total nodes in a tree. static final BstAggregate<SimpleNode> countAggregate = new BstAggregate<SimpleNode>() { @Override public int entryValue(SimpleNode entry) { return 1; } @Override public long treeValue(@Nullable SimpleNode tree) { if (tree == null) { return 0; } else { return 1 + treeValue(tree.childOrNull(LEFT)) + treeValue(tree.childOrNull(RIGHT)); } } }; static <P extends BstPath<SimpleNode, P>> List<SimpleNode> pathToList(P path) { List<SimpleNode> list = Lists.newArrayList(); for (; path != null; path = path.prefixOrNull()) { list.add(path.getTip()); } return list; } static <N extends BstNode<?, N>, P extends BstPath<N, P>> P extension( BstPathFactory<N, P> factory, N root, BstSide... sides) { P path = factory.initialPath(root); for (BstSide side : sides) { path = factory.extension(path, side); } return path; } static void assertInOrderTraversalIs(@Nullable SimpleNode root, String order) { if (root == null) { assertEquals("", order); } else { BstInOrderPath<SimpleNode> path = pathFactory.initialPath(root); while (path.getTip().hasChild(LEFT)) { path = pathFactory.extension(path, LEFT); } assertEquals(order.charAt(0), path .getTip() .getKey() .charValue()); int i; for (i = 1; path.hasNext(RIGHT); i++) { path = path.next(RIGHT); assertEquals(order.charAt(i), path .getTip() .getKey() .charValue()); } assertEquals(i, order.length()); } } @GwtIncompatible("NullPointerTester") static NullPointerTester defaultNullPointerTester() { NullPointerTester tester = new NullPointerTester(); SimpleNode node = new SimpleNode('a', null, null); tester.setDefault(BstNode.class, node); tester.setDefault(BstSide.class, LEFT); tester.setDefault(BstNodeFactory.class, nodeFactory); tester.setDefault(BstBalancePolicy.class, balancePolicy); tester.setDefault(BstPathFactory.class, pathFactory); tester.setDefault(BstPath.class, pathFactory.initialPath(node)); tester.setDefault(BstInOrderPath.class, pathFactory.initialPath(node)); tester.setDefault(Object.class, 'a'); tester.setDefault(GeneralRange.class, GeneralRange.all(Ordering.natural())); tester.setDefault(BstAggregate.class, countAggregate); BstModifier<Character, SimpleNode> modifier = new BstModifier<Character, SimpleNode>() { @Nullable @Override public BstModificationResult<SimpleNode> modify( Character key, @Nullable SimpleNode originalEntry) { return BstModificationResult.identity(originalEntry); } }; tester.setDefault( BstModificationResult.class, BstModificationResult.<SimpleNode>identity(null)); tester.setDefault(BstModifier.class, modifier); tester.setDefault( BstMutationRule.class, BstMutationRule.createRule(modifier, balancePolicy, nodeFactory)); return tester; } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.testing.SerializableTester.reserialize; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertTrue; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.GwtIncompatible; import com.google.common.testing.SerializableTester; import java.util.Set; /** * Variant of {@link SerializableTester} that does not require the reserialized object's class to be * identical to the original. * * @author Chris Povirk */ /* * The whole thing is really @GwtIncompatible, but GwtJUnitConvertedTestModule doesn't have a * parameter for non-GWT, non-test files, and it didn't seem worth adding one for this unusual case. */ @GwtCompatible(emulated = true) final class LenientSerializableTester { /* * TODO(cpovirk): move this to c.g.c.testing if we allow for c.g.c.annotations dependencies so * that it can be GWTified? */ @GwtIncompatible("SerializableTester") static <E> Set<E> reserializeAndAssertLenient(Set<E> original) { Set<E> copy = reserialize(original); assertEquals(original, copy); assertTrue(copy instanceof ImmutableSet); return copy; } private LenientSerializableTester() {} }
Java
// Copyright 2011 Google Inc. All Rights Reserved. package com.google.common.hash; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Sets; import com.google.common.primitives.Ints; import org.junit.Assert; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.util.Arrays; import java.util.Random; import java.util.Set; /** * Various utilities for testing {@link HashFunction}s. * * @author andreou@google.com (Dimitris Andreou) * @author kak@google.com (Kurt Alfred Kluever) */ final class HashTestUtils { private HashTestUtils() {} /** * Converts a string, which should contain only ascii-representable characters, to a byte[]. */ static byte[] ascii(String string) { byte[] bytes = new byte[string.length()]; for (int i = 0; i < string.length(); i++) { bytes[i] = (byte) string.charAt(i); } return bytes; } /** * Returns a byte array representation for a sequence of longs, in big-endian order. */ static byte[] toBytes(ByteOrder bo, long... longs) { ByteBuffer bb = ByteBuffer.wrap(new byte[longs.length * 8]).order(bo); for (long x : longs) { bb.putLong(x); } return bb.array(); } interface HashFn { byte[] hash(byte[] input, int seed); } static void verifyHashFunction(HashFn hashFunction, int hashbits, int expected) { int hashBytes = hashbits / 8; byte[] key = new byte[256]; byte[] hashes = new byte[hashBytes * 256]; // Hash keys of the form {}, {0}, {0,1}, {0,1,2}... up to N=255,using 256-N as the seed for (int i = 0; i < 256; i++) { key[i] = (byte) i; int seed = 256 - i; byte[] hash = hashFunction.hash(Arrays.copyOf(key, i), seed); System.arraycopy(hash, 0, hashes, i * hashBytes, hash.length); } // Then hash the result array byte[] result = hashFunction.hash(hashes, 0); // interpreted in little-endian order. int verification = Integer.reverseBytes(Ints.fromByteArray(result)); if (expected != verification) { throw new AssertionError("Expected: " + Integer.toHexString(expected) + " got: " + Integer.toHexString(verification)); } } static void assertEqualHashes(byte[] expectedHash, byte[] actualHash) { if (!Arrays.equals(expectedHash, actualHash)) { Assert.fail(String.format("Should be: %x, was %x", expectedHash, actualHash)); } } static final Funnel<Object> BAD_FUNNEL = new Funnel<Object>() { @Override public void funnel(Object object, Sink byteSink) { byteSink.putInt(object.hashCode()); } }; static enum RandomHasherAction { PUT_BOOLEAN() { @Override void performAction(Random random, Iterable<? extends Sink> sinks) { boolean value = random.nextBoolean(); for (Sink sink : sinks) { sink.putBoolean(value); } } }, PUT_BYTE() { @Override void performAction(Random random, Iterable<? extends Sink> sinks) { int value = random.nextInt(); for (Sink sink : sinks) { sink.putByte((byte) value); } } }, PUT_SHORT() { @Override void performAction(Random random, Iterable<? extends Sink> sinks) { short value = (short) random.nextInt(); for (Sink sink : sinks) { sink.putShort(value); } } }, PUT_CHAR() { @Override void performAction(Random random, Iterable<? extends Sink> sinks) { char value = (char) random.nextInt(); for (Sink sink : sinks) { sink.putChar(value); } } }, PUT_INT() { @Override void performAction(Random random, Iterable<? extends Sink> sinks) { int value = random.nextInt(); for (Sink sink : sinks) { sink.putInt(value); } } }, PUT_LONG() { @Override void performAction(Random random, Iterable<? extends Sink> sinks) { long value = random.nextLong(); for (Sink sink : sinks) { sink.putLong(value); } } }, PUT_FLOAT() { @Override void performAction(Random random, Iterable<? extends Sink> sinks) { float value = random.nextFloat(); for (Sink sink : sinks) { sink.putFloat(value); } } }, PUT_DOUBLE() { @Override void performAction(Random random, Iterable<? extends Sink> sinks) { double value = random.nextDouble(); for (Sink sink : sinks) { sink.putDouble(value); } } }, PUT_BYTES() { @Override void performAction(Random random, Iterable<? extends Sink> sinks) { byte[] value = new byte[random.nextInt(128)]; random.nextBytes(value); for (Sink sink : sinks) { sink.putBytes(value); } } }, PUT_BYTES_INT_INT() { @Override void performAction(Random random, Iterable<? extends Sink> sinks) { byte[] value = new byte[random.nextInt(128)]; random.nextBytes(value); int off = random.nextInt(value.length + 1); int len = random.nextInt(value.length - off + 1); for (Sink sink : sinks) { sink.putBytes(value); } } }; abstract void performAction(Random random, Iterable<? extends Sink> sinks); private static final RandomHasherAction[] actions = values(); static RandomHasherAction pickAtRandom(Random random) { return actions[random.nextInt(actions.length)]; } } /** * Test that the hash function contains no funnels. A funnel is a situation where a set of input * (key) bits 'affects' a strictly smaller set of output bits. Funneling is bad because it can * result in more-than-ideal collisions for a non-uniformly distributed key space. In practice, * most key spaces are ANYTHING BUT uniformly distributed. A bit(i) in the input is said to * 'affect' a bit(j) in the output if two inputs, identical but for bit(i), will differ at output * bit(j) about half the time * * <p>Funneling is pretty simple to detect. The key idea is to find example keys which * unequivocably demonstrate that funneling cannot be occuring. This is done bit-by-bit. For * each input bit(i) and output bit(j), two pairs of keys must be found with all bits identical * except bit(i). One pair must differ in output bit(j), and one pair must not. This proves that * input bit(i) can alter output bit(j). */ static void checkNoFunnels(HashFunction function) { Random rand = new Random(0); int keyBits = 32; int hashBits = function.bits(); // output loop tests input bit for (int i = 0; i < keyBits; i++) { int same = 0x0; // bitset for output bits with same values int diff = 0x0; // bitset for output bits with different values int count = 0; int maxCount = (int) (2 * Math.log(2 * keyBits * hashBits) + 0.999); while (same != 0xffffffff || diff != 0xffffffff) { int key1 = rand.nextInt(); // flip input bit for key2 int key2 = key1 ^ (1 << i); // get hashes int hash1 = function.newHasher().putInt(key1).hash().asInt(); int hash2 = function.newHasher().putInt(key2).hash().asInt(); // test whether the hash values have same output bits same |= ~(hash1 ^ hash2); // test whether the hash values have different output bits diff |= (hash1 ^ hash2); count++; // check whether we've exceeded the probabilistically // likely number of trials to have proven no funneling if (count > maxCount) { Assert.fail("input bit(" + i + ") was found not to affect all " + hashBits + " output bits; The unaffected bits are " + "as follows: " + ~(same & diff) + ". This was " + "determined after " + count + " trials."); } } } } /** * Test for avalanche. Avalanche means that output bits differ with roughly 1/2 probability on * different input keys. This test verifies that each possible 1-bit key delta achieves avalanche. * * <p>For more information: http://burtleburtle.net/bob/hash/avalanche.html */ static void checkAvalanche(HashFunction function, int trials, double epsilon) { Random rand = new Random(0); int keyBits = 32; int hashBits = function.bits(); for (int i = 0; i < keyBits; i++) { int[] same = new int[hashBits]; int[] diff = new int[hashBits]; // go through trials to compute probability for (int j = 0; j < trials; j++) { int key1 = rand.nextInt(); // flip input bit for key2 int key2 = key1 ^ (1 << i); // compute hash values int hash1 = function.newHasher().putInt(key1).hash().asInt(); int hash2 = function.newHasher().putInt(key2).hash().asInt(); for (int k = 0; k < hashBits; k++) { if ((hash1 & (1 << k)) == (hash2 & (1 << k))) { same[k] += 1; } else { diff[k] += 1; } } } // measure probability and assert it's within margin of error for (int j = 0; j < hashBits; j++) { double prob = (double) diff[j] / (double) (diff[j] + same[j]); Assert.assertEquals(0.50d, prob, epsilon); } } } /** * Test for 2-bit characteristics. A characteristic is a delta in the input which is repeated in * the output. For example, if f() is a block cipher and c is a characteristic, then * f(x^c) = f(x)^c with greater than expected probability. The test for funneling is merely a test * for 1-bit characteristics. * * <p>There is more general code provided by Bob Jenkins to test arbitrarily sized characteristics * using the magic of gaussian elimination: http://burtleburtle.net/bob/crypto/findingc.html. */ static void checkNo2BitCharacteristics(HashFunction function) { Random rand = new Random(0); int keyBits = 32; // get every one of (keyBits choose 2) deltas: for (int i = 0; i < keyBits; i++) { for (int j = 0; j < keyBits; j++) { if (j <= i) continue; int count = 0; int maxCount = 20; // the probability of error here is miniscule boolean diff = false; while (diff == false) { int delta = (1 << i) | (1 << j); int key1 = rand.nextInt(); // apply delta int key2 = key1 ^ delta; // get hashes int hash1 = function.newHasher().putInt(key1).hash().asInt(); int hash2 = function.newHasher().putInt(key2).hash().asInt(); // this 2-bit candidate delta is not a characteristic // if deltas are different if ((hash1 ^ hash2) != delta) { diff = true; continue; } // check if we've exceeded the probabilistically // likely number of trials to have proven 2-bit candidate // is not a characteristic count++; if (count > maxCount) { Assert.fail("2-bit delta (" + i + ", " + j + ") is likely a " + "characteristic for this hash. This was " + "determined after " + count + " trials"); } } } } } /** * Test for avalanche with 2-bit deltas. Most probabilities of output bit(j) differing are well * within 50%. */ static void check2BitAvalanche(HashFunction function, int trials, double epsilon) { Random rand = new Random(0); int keyBits = 32; int hashBits = function.bits(); for (int bit1 = 0; bit1 < keyBits; bit1++) { for (int bit2 = 0; bit2 < keyBits; bit2++) { if (bit2 <= bit1) continue; int delta = (1 << bit1) | (1 << bit2); int[] same = new int[hashBits]; int[] diff = new int[hashBits]; // go through trials to compute probability for (int j = 0; j < trials; j++) { int key1 = rand.nextInt(); // flip input bit for key2 int key2 = key1 ^ delta; // compute hash values int hash1 = function.newHasher().putInt(key1).hash().asInt(); int hash2 = function.newHasher().putInt(key2).hash().asInt(); for (int k = 0; k < hashBits; k++) { if ((hash1 & (1 << k)) == (hash2 & (1 << k))) { same[k] += 1; } else { diff[k] += 1; } } } // measure probability and assert it's within margin of error for (int j = 0; j < hashBits; j++) { double prob = (double) diff[j] / (double) (diff[j] + same[j]); Assert.assertEquals(0.50d, prob, epsilon); } } } } /** * Checks that a Hasher returns the same HashCode when given the same input, and also * that the collision rate looks sane. */ static void assertInvariants(HashFunction hashFunction) { int objects = 100; Set<HashCode> hashcodes = Sets.newHashSetWithExpectedSize(objects); for (int i = 0; i < objects; i++) { Object o = new Object(); HashCode hashcode1 = hashFunction.newHasher().putObject(o, HashTestUtils.BAD_FUNNEL).hash(); HashCode hashcode2 = hashFunction.newHasher().putObject(o, HashTestUtils.BAD_FUNNEL).hash(); Assert.assertEquals(hashcode1, hashcode2); // idempotent Assert.assertEquals(hashFunction.bits(), hashcode1.bits()); Assert.assertEquals(hashFunction.bits(), hashcode1.asBytes().length * 8); hashcodes.add(hashcode1); } Assert.assertTrue(hashcodes.size() > objects * 0.95); // quite relaxed test assertHashBytesThrowsCorrectExceptions(hashFunction); assertIndependentHashers(hashFunction); } static void assertHashBytesThrowsCorrectExceptions(HashFunction hashFunction) { hashFunction.hashBytes(new byte[64], 0, 0); try { hashFunction.hashBytes(new byte[128], -1, 128); Assert.fail(); } catch (IndexOutOfBoundsException expected) {} try { hashFunction.hashBytes(new byte[128], 64, 256 /* too long len */); Assert.fail(); } catch (IndexOutOfBoundsException expected) {} try { hashFunction.hashBytes(new byte[64], 0, -1); Assert.fail(); } catch (IndexOutOfBoundsException expected) {} } static void assertIndependentHashers(HashFunction hashFunction) { int numActions = 100; // hashcodes from non-overlapping hash computations HashCode expected1 = randomHash(hashFunction, new Random(1L), numActions); HashCode expected2 = randomHash(hashFunction, new Random(2L), numActions); // equivalent, but overlapping, computations (should produce the same results as above) Random random1 = new Random(1L); Random random2 = new Random(2L); Hasher hasher1 = hashFunction.newHasher(); Hasher hasher2 = hashFunction.newHasher(); for (int i = 0; i < numActions; i++) { RandomHasherAction.pickAtRandom(random1).performAction(random1, ImmutableSet.of(hasher1)); RandomHasherAction.pickAtRandom(random2).performAction(random2, ImmutableSet.of(hasher2)); } Assert.assertEquals(expected1, hasher1.hash()); Assert.assertEquals(expected2, hasher2.hash()); } static HashCode randomHash(HashFunction hashFunction, Random random, int numActions) { Hasher hasher = hashFunction.newHasher(); for (int i = 0; i < numActions; i++) { RandomHasherAction.pickAtRandom(random).performAction(random, ImmutableSet.of(hasher)); } return hasher.hash(); } }
Java
/* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ * Other contributors include Andrew Wright, Jeffrey Hayes, * Pat Fisher, Mike Judd. */ /* * Source: * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/test/tck/JSR166TestCase.java?revision=1.90 * (We have made some trivial local modifications (commented out * uncompilable code).) */ package com.google.common.util.concurrent; import junit.framework.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.util.Arrays; import java.util.Date; import java.util.NoSuchElementException; import java.util.PropertyPermission; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import java.security.CodeSource; import java.security.Permission; import java.security.PermissionCollection; import java.security.Permissions; import java.security.Policy; import java.security.ProtectionDomain; import java.security.SecurityPermission; /** * Base class for JSR166 Junit TCK tests. Defines some constants, * utility methods and classes, as well as a simple framework for * helping to make sure that assertions failing in generated threads * cause the associated test that generated them to itself fail (which * JUnit does not otherwise arrange). The rules for creating such * tests are: * * <ol> * * <li> All assertions in code running in generated threads must use * the forms {@link #threadFail}, {@link #threadAssertTrue}, {@link * #threadAssertEquals}, or {@link #threadAssertNull}, (not * {@code fail}, {@code assertTrue}, etc.) It is OK (but not * particularly recommended) for other code to use these forms too. * Only the most typically used JUnit assertion methods are defined * this way, but enough to live with.</li> * * <li> If you override {@link #setUp} or {@link #tearDown}, make sure * to invoke {@code super.setUp} and {@code super.tearDown} within * them. These methods are used to clear and check for thread * assertion failures.</li> * * <li>All delays and timeouts must use one of the constants {@code * SHORT_DELAY_MS}, {@code SMALL_DELAY_MS}, {@code MEDIUM_DELAY_MS}, * {@code LONG_DELAY_MS}. The idea here is that a SHORT is always * discriminable from zero time, and always allows enough time for the * small amounts of computation (creating a thread, calling a few * methods, etc) needed to reach a timeout point. Similarly, a SMALL * is always discriminable as larger than SHORT and smaller than * MEDIUM. And so on. These constants are set to conservative values, * but even so, if there is ever any doubt, they can all be increased * in one spot to rerun tests on slower platforms.</li> * * <li> All threads generated must be joined inside each test case * method (or {@code fail} to do so) before returning from the * method. The {@code joinPool} method can be used to do this when * using Executors.</li> * * </ol> * * <p> <b>Other notes</b> * <ul> * * <li> Usually, there is one testcase method per JSR166 method * covering "normal" operation, and then as many exception-testing * methods as there are exceptions the method can throw. Sometimes * there are multiple tests per JSR166 method when the different * "normal" behaviors differ significantly. And sometimes testcases * cover multiple methods when they cannot be tested in * isolation.</li> * * <li> The documentation style for testcases is to provide as javadoc * a simple sentence or two describing the property that the testcase * method purports to test. The javadocs do not say anything about how * the property is tested. To find out, read the code.</li> * * <li> These tests are "conformance tests", and do not attempt to * test throughput, latency, scalability or other performance factors * (see the separate "jtreg" tests for a set intended to check these * for the most central aspects of functionality.) So, most tests use * the smallest sensible numbers of threads, collection sizes, etc * needed to check basic conformance.</li> * * <li>The test classes currently do not declare inclusion in * any particular package to simplify things for people integrating * them in TCK test suites.</li> * * <li> As a convenience, the {@code main} of this class (JSR166TestCase) * runs all JSR166 unit tests.</li> * * </ul> */ abstract class JSR166TestCase extends TestCase { private static final boolean useSecurityManager = Boolean.getBoolean("jsr166.useSecurityManager"); protected static final boolean expensiveTests = Boolean.getBoolean("jsr166.expensiveTests"); /** * If true, report on stdout all "slow" tests, that is, ones that * take more than profileThreshold milliseconds to execute. */ private static final boolean profileTests = Boolean.getBoolean("jsr166.profileTests"); /** * The number of milliseconds that tests are permitted for * execution without being reported, when profileTests is set. */ private static final long profileThreshold = Long.getLong("jsr166.profileThreshold", 100); protected void runTest() throws Throwable { if (profileTests) runTestProfiled(); else super.runTest(); } protected void runTestProfiled() throws Throwable { long t0 = System.nanoTime(); try { super.runTest(); } finally { long elapsedMillis = (System.nanoTime() - t0) / (1000L * 1000L); if (elapsedMillis >= profileThreshold) System.out.printf("%n%s: %d%n", toString(), elapsedMillis); } } // /** // * Runs all JSR166 unit tests using junit.textui.TestRunner // */ // public static void main(String[] args) { // if (useSecurityManager) { // System.err.println("Setting a permissive security manager"); // Policy.setPolicy(permissivePolicy()); // System.setSecurityManager(new SecurityManager()); // } // int iters = (args.length == 0) ? 1 : Integer.parseInt(args[0]); // Test s = suite(); // for (int i = 0; i < iters; ++i) { // junit.textui.TestRunner.run(s); // System.gc(); // System.runFinalization(); // } // System.exit(0); // } // public static TestSuite newTestSuite(Object... suiteOrClasses) { // TestSuite suite = new TestSuite(); // for (Object suiteOrClass : suiteOrClasses) { // if (suiteOrClass instanceof TestSuite) // suite.addTest((TestSuite) suiteOrClass); // else if (suiteOrClass instanceof Class) // suite.addTest(new TestSuite((Class<?>) suiteOrClass)); // else // throw new ClassCastException("not a test suite or class"); // } // return suite; // } // /** // * Collects all JSR166 unit tests as one suite. // */ // public static Test suite() { // return newTestSuite( // ForkJoinPoolTest.suite(), // ForkJoinTaskTest.suite(), // RecursiveActionTest.suite(), // RecursiveTaskTest.suite(), // LinkedTransferQueueTest.suite(), // PhaserTest.suite(), // ThreadLocalRandomTest.suite(), // AbstractExecutorServiceTest.suite(), // AbstractQueueTest.suite(), // AbstractQueuedSynchronizerTest.suite(), // AbstractQueuedLongSynchronizerTest.suite(), // ArrayBlockingQueueTest.suite(), // ArrayDequeTest.suite(), // AtomicBooleanTest.suite(), // AtomicIntegerArrayTest.suite(), // AtomicIntegerFieldUpdaterTest.suite(), // AtomicIntegerTest.suite(), // AtomicLongArrayTest.suite(), // AtomicLongFieldUpdaterTest.suite(), // AtomicLongTest.suite(), // AtomicMarkableReferenceTest.suite(), // AtomicReferenceArrayTest.suite(), // AtomicReferenceFieldUpdaterTest.suite(), // AtomicReferenceTest.suite(), // AtomicStampedReferenceTest.suite(), // ConcurrentHashMapTest.suite(), // ConcurrentLinkedDequeTest.suite(), // ConcurrentLinkedQueueTest.suite(), // ConcurrentSkipListMapTest.suite(), // ConcurrentSkipListSubMapTest.suite(), // ConcurrentSkipListSetTest.suite(), // ConcurrentSkipListSubSetTest.suite(), // CopyOnWriteArrayListTest.suite(), // CopyOnWriteArraySetTest.suite(), // CountDownLatchTest.suite(), // CyclicBarrierTest.suite(), // DelayQueueTest.suite(), // EntryTest.suite(), // ExchangerTest.suite(), // ExecutorsTest.suite(), // ExecutorCompletionServiceTest.suite(), // FutureTaskTest.suite(), // LinkedBlockingDequeTest.suite(), // LinkedBlockingQueueTest.suite(), // LinkedListTest.suite(), // LockSupportTest.suite(), // PriorityBlockingQueueTest.suite(), // PriorityQueueTest.suite(), // ReentrantLockTest.suite(), // ReentrantReadWriteLockTest.suite(), // ScheduledExecutorTest.suite(), // ScheduledExecutorSubclassTest.suite(), // SemaphoreTest.suite(), // SynchronousQueueTest.suite(), // SystemTest.suite(), // ThreadLocalTest.suite(), // ThreadPoolExecutorTest.suite(), // ThreadPoolExecutorSubclassTest.suite(), // ThreadTest.suite(), // TimeUnitTest.suite(), // TreeMapTest.suite(), // TreeSetTest.suite(), // TreeSubMapTest.suite(), // TreeSubSetTest.suite()); // } public static long SHORT_DELAY_MS; public static long SMALL_DELAY_MS; public static long MEDIUM_DELAY_MS; public static long LONG_DELAY_MS; /** * Returns the shortest timed delay. This could * be reimplemented to use for example a Property. */ protected long getShortDelay() { return 50; } /** * Sets delays as multiples of SHORT_DELAY. */ protected void setDelays() { SHORT_DELAY_MS = getShortDelay(); SMALL_DELAY_MS = SHORT_DELAY_MS * 5; MEDIUM_DELAY_MS = SHORT_DELAY_MS * 10; LONG_DELAY_MS = SHORT_DELAY_MS * 200; } /** * Returns a timeout in milliseconds to be used in tests that * verify that operations block or time out. */ long timeoutMillis() { return SHORT_DELAY_MS / 4; } /** * Returns a new Date instance representing a time delayMillis * milliseconds in the future. */ Date delayedDate(long delayMillis) { return new Date(System.currentTimeMillis() + delayMillis); } /** * The first exception encountered if any threadAssertXXX method fails. */ private final AtomicReference<Throwable> threadFailure = new AtomicReference<Throwable>(null); /** * Records an exception so that it can be rethrown later in the test * harness thread, triggering a test case failure. Only the first * failure is recorded; subsequent calls to this method from within * the same test have no effect. */ public void threadRecordFailure(Throwable t) { threadFailure.compareAndSet(null, t); } public void setUp() { setDelays(); } /** * Extra checks that get done for all test cases. * * Triggers test case failure if any thread assertions have failed, * by rethrowing, in the test harness thread, any exception recorded * earlier by threadRecordFailure. * * Triggers test case failure if interrupt status is set in the main thread. */ public void tearDown() throws Exception { Throwable t = threadFailure.getAndSet(null); if (t != null) { if (t instanceof Error) throw (Error) t; else if (t instanceof RuntimeException) throw (RuntimeException) t; else if (t instanceof Exception) throw (Exception) t; else { AssertionFailedError afe = new AssertionFailedError(t.toString()); afe.initCause(t); throw afe; } } if (Thread.interrupted()) throw new AssertionFailedError("interrupt status set in main thread"); } /** * Just like fail(reason), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadFail(String reason) { try { fail(reason); } catch (AssertionFailedError t) { threadRecordFailure(t); fail(reason); } } /** * Just like assertTrue(b), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadAssertTrue(boolean b) { try { assertTrue(b); } catch (AssertionFailedError t) { threadRecordFailure(t); throw t; } } /** * Just like assertFalse(b), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadAssertFalse(boolean b) { try { assertFalse(b); } catch (AssertionFailedError t) { threadRecordFailure(t); throw t; } } /** * Just like assertNull(x), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadAssertNull(Object x) { try { assertNull(x); } catch (AssertionFailedError t) { threadRecordFailure(t); throw t; } } /** * Just like assertEquals(x, y), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadAssertEquals(long x, long y) { try { assertEquals(x, y); } catch (AssertionFailedError t) { threadRecordFailure(t); throw t; } } /** * Just like assertEquals(x, y), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadAssertEquals(Object x, Object y) { try { assertEquals(x, y); } catch (AssertionFailedError t) { threadRecordFailure(t); throw t; } catch (Throwable t) { threadUnexpectedException(t); } } /** * Just like assertSame(x, y), but additionally recording (using * threadRecordFailure) any AssertionFailedError thrown, so that * the current testcase will fail. */ public void threadAssertSame(Object x, Object y) { try { assertSame(x, y); } catch (AssertionFailedError t) { threadRecordFailure(t); throw t; } } /** * Calls threadFail with message "should throw exception". */ public void threadShouldThrow() { threadFail("should throw exception"); } /** * Calls threadFail with message "should throw" + exceptionName. */ public void threadShouldThrow(String exceptionName) { threadFail("should throw " + exceptionName); } /** * Records the given exception using {@link #threadRecordFailure}, * then rethrows the exception, wrapping it in an * AssertionFailedError if necessary. */ public void threadUnexpectedException(Throwable t) { threadRecordFailure(t); t.printStackTrace(); if (t instanceof RuntimeException) throw (RuntimeException) t; else if (t instanceof Error) throw (Error) t; else { AssertionFailedError afe = new AssertionFailedError("unexpected exception: " + t); afe.initCause(t); throw afe; } } /** * Delays, via Thread.sleep, for the given millisecond delay, but * if the sleep is shorter than specified, may re-sleep or yield * until time elapses. */ static void delay(long millis) throws InterruptedException { long startTime = System.nanoTime(); long ns = millis * 1000 * 1000; for (;;) { if (millis > 0L) Thread.sleep(millis); else // too short to sleep Thread.yield(); long d = ns - (System.nanoTime() - startTime); if (d > 0L) millis = d / (1000 * 1000); else break; } } /** * Waits out termination of a thread pool or fails doing so. */ void joinPool(ExecutorService exec) { try { exec.shutdown(); assertTrue("ExecutorService did not terminate in a timely manner", exec.awaitTermination(2 * LONG_DELAY_MS, MILLISECONDS)); } catch (SecurityException ok) { // Allowed in case test doesn't have privs } catch (InterruptedException ie) { fail("Unexpected InterruptedException"); } } /** * Checks that thread does not terminate within the default * millisecond delay of {@code timeoutMillis()}. */ void assertThreadStaysAlive(Thread thread) { assertThreadStaysAlive(thread, timeoutMillis()); } /** * Checks that thread does not terminate within the given millisecond delay. */ void assertThreadStaysAlive(Thread thread, long millis) { try { // No need to optimize the failing case via Thread.join. delay(millis); assertTrue(thread.isAlive()); } catch (InterruptedException ie) { fail("Unexpected InterruptedException"); } } /** * Checks that the threads do not terminate within the default * millisecond delay of {@code timeoutMillis()}. */ void assertThreadsStayAlive(Thread... threads) { assertThreadsStayAlive(timeoutMillis(), threads); } /** * Checks that the threads do not terminate within the given millisecond delay. */ void assertThreadsStayAlive(long millis, Thread... threads) { try { // No need to optimize the failing case via Thread.join. delay(millis); for (Thread thread : threads) assertTrue(thread.isAlive()); } catch (InterruptedException ie) { fail("Unexpected InterruptedException"); } } /** * Checks that future.get times out, with the default timeout of * {@code timeoutMillis()}. */ void assertFutureTimesOut(Future future) { assertFutureTimesOut(future, timeoutMillis()); } /** * Checks that future.get times out, with the given millisecond timeout. */ void assertFutureTimesOut(Future future, long timeoutMillis) { long startTime = System.nanoTime(); try { future.get(timeoutMillis, MILLISECONDS); shouldThrow(); } catch (TimeoutException success) { } catch (Exception e) { threadUnexpectedException(e); } finally { future.cancel(true); } assertTrue(millisElapsedSince(startTime) >= timeoutMillis); } /** * Fails with message "should throw exception". */ public void shouldThrow() { fail("Should throw exception"); } /** * Fails with message "should throw " + exceptionName. */ public void shouldThrow(String exceptionName) { fail("Should throw " + exceptionName); } /** * The number of elements to place in collections, arrays, etc. */ public static final int SIZE = 20; // Some convenient Integer constants public static final Integer zero = new Integer(0); public static final Integer one = new Integer(1); public static final Integer two = new Integer(2); public static final Integer three = new Integer(3); public static final Integer four = new Integer(4); public static final Integer five = new Integer(5); public static final Integer six = new Integer(6); public static final Integer seven = new Integer(7); public static final Integer eight = new Integer(8); public static final Integer nine = new Integer(9); public static final Integer m1 = new Integer(-1); public static final Integer m2 = new Integer(-2); public static final Integer m3 = new Integer(-3); public static final Integer m4 = new Integer(-4); public static final Integer m5 = new Integer(-5); public static final Integer m6 = new Integer(-6); public static final Integer m10 = new Integer(-10); /** * Runs Runnable r with a security policy that permits precisely * the specified permissions. If there is no current security * manager, the runnable is run twice, both with and without a * security manager. We require that any security manager permit * getPolicy/setPolicy. */ public void runWithPermissions(Runnable r, Permission... permissions) { SecurityManager sm = System.getSecurityManager(); if (sm == null) { r.run(); Policy savedPolicy = Policy.getPolicy(); try { Policy.setPolicy(permissivePolicy()); System.setSecurityManager(new SecurityManager()); runWithPermissions(r, permissions); } finally { System.setSecurityManager(null); Policy.setPolicy(savedPolicy); } } else { Policy savedPolicy = Policy.getPolicy(); AdjustablePolicy policy = new AdjustablePolicy(permissions); Policy.setPolicy(policy); try { r.run(); } finally { policy.addPermission(new SecurityPermission("setPolicy")); Policy.setPolicy(savedPolicy); } } } /** * Runs a runnable without any permissions. */ public void runWithoutPermissions(Runnable r) { runWithPermissions(r); } /** * A security policy where new permissions can be dynamically added * or all cleared. */ public static class AdjustablePolicy extends java.security.Policy { Permissions perms = new Permissions(); AdjustablePolicy(Permission... permissions) { for (Permission permission : permissions) perms.add(permission); } void addPermission(Permission perm) { perms.add(perm); } void clearPermissions() { perms = new Permissions(); } public PermissionCollection getPermissions(CodeSource cs) { return perms; } public PermissionCollection getPermissions(ProtectionDomain pd) { return perms; } public boolean implies(ProtectionDomain pd, Permission p) { return perms.implies(p); } public void refresh() {} } /** * Returns a policy containing all the permissions we ever need. */ public static Policy permissivePolicy() { return new AdjustablePolicy // Permissions j.u.c. needs directly (new RuntimePermission("modifyThread"), new RuntimePermission("getClassLoader"), new RuntimePermission("setContextClassLoader"), // Permissions needed to change permissions! new SecurityPermission("getPolicy"), new SecurityPermission("setPolicy"), new RuntimePermission("setSecurityManager"), // Permissions needed by the junit test harness new RuntimePermission("accessDeclaredMembers"), new PropertyPermission("*", "read"), new java.io.FilePermission("<<ALL FILES>>", "read")); } /** * Sleeps until the given time has elapsed. * Throws AssertionFailedError if interrupted. */ void sleep(long millis) { try { delay(millis); } catch (InterruptedException ie) { AssertionFailedError afe = new AssertionFailedError("Unexpected InterruptedException"); afe.initCause(ie); throw afe; } } /** * Spin-waits up to the specified number of milliseconds for the given * thread to enter a wait state: BLOCKED, WAITING, or TIMED_WAITING. */ void waitForThreadToEnterWaitState(Thread thread, long timeoutMillis) { long startTime = System.nanoTime(); for (;;) { Thread.State s = thread.getState(); if (s == Thread.State.BLOCKED || s == Thread.State.WAITING || s == Thread.State.TIMED_WAITING) return; else if (s == Thread.State.TERMINATED) fail("Unexpected thread termination"); else if (millisElapsedSince(startTime) > timeoutMillis) { threadAssertTrue(thread.isAlive()); return; } Thread.yield(); } } /** * Waits up to LONG_DELAY_MS for the given thread to enter a wait * state: BLOCKED, WAITING, or TIMED_WAITING. */ void waitForThreadToEnterWaitState(Thread thread) { waitForThreadToEnterWaitState(thread, LONG_DELAY_MS); } /** * Returns the number of milliseconds since time given by * startNanoTime, which must have been previously returned from a * call to {@link System.nanoTime()}. */ long millisElapsedSince(long startNanoTime) { return NANOSECONDS.toMillis(System.nanoTime() - startNanoTime); } /** * Returns a new started daemon Thread running the given runnable. */ Thread newStartedThread(Runnable runnable) { Thread t = new Thread(runnable); t.setDaemon(true); t.start(); return t; } /** * Waits for the specified time (in milliseconds) for the thread * to terminate (using {@link Thread#join(long)}), else interrupts * the thread (in the hope that it may terminate later) and fails. */ void awaitTermination(Thread t, long timeoutMillis) { try { t.join(timeoutMillis); } catch (InterruptedException ie) { threadUnexpectedException(ie); } finally { if (t.getState() != Thread.State.TERMINATED) { t.interrupt(); fail("Test timed out"); } } } /** * Waits for LONG_DELAY_MS milliseconds for the thread to * terminate (using {@link Thread#join(long)}), else interrupts * the thread (in the hope that it may terminate later) and fails. */ void awaitTermination(Thread t) { awaitTermination(t, LONG_DELAY_MS); } // Some convenient Runnable classes public abstract class CheckedRunnable implements Runnable { protected abstract void realRun() throws Throwable; public final void run() { try { realRun(); } catch (Throwable t) { threadUnexpectedException(t); } } } public abstract class RunnableShouldThrow implements Runnable { protected abstract void realRun() throws Throwable; final Class<?> exceptionClass; <T extends Throwable> RunnableShouldThrow(Class<T> exceptionClass) { this.exceptionClass = exceptionClass; } public final void run() { try { realRun(); threadShouldThrow(exceptionClass.getSimpleName()); } catch (Throwable t) { if (! exceptionClass.isInstance(t)) threadUnexpectedException(t); } } } public abstract class ThreadShouldThrow extends Thread { protected abstract void realRun() throws Throwable; final Class<?> exceptionClass; <T extends Throwable> ThreadShouldThrow(Class<T> exceptionClass) { this.exceptionClass = exceptionClass; } public final void run() { try { realRun(); threadShouldThrow(exceptionClass.getSimpleName()); } catch (Throwable t) { if (! exceptionClass.isInstance(t)) threadUnexpectedException(t); } } } public abstract class CheckedInterruptedRunnable implements Runnable { protected abstract void realRun() throws Throwable; public final void run() { try { realRun(); threadShouldThrow("InterruptedException"); } catch (InterruptedException success) { threadAssertFalse(Thread.interrupted()); } catch (Throwable t) { threadUnexpectedException(t); } } } public abstract class CheckedCallable<T> implements Callable<T> { protected abstract T realCall() throws Throwable; public final T call() { try { return realCall(); } catch (Throwable t) { threadUnexpectedException(t); return null; } } } public abstract class CheckedInterruptedCallable<T> implements Callable<T> { protected abstract T realCall() throws Throwable; public final T call() { try { T result = realCall(); threadShouldThrow("InterruptedException"); return result; } catch (InterruptedException success) { threadAssertFalse(Thread.interrupted()); } catch (Throwable t) { threadUnexpectedException(t); } return null; } } public static class NoOpRunnable implements Runnable { public void run() {} } public static class NoOpCallable implements Callable { public Object call() { return Boolean.TRUE; } } public static final String TEST_STRING = "a test string"; public static class StringTask implements Callable<String> { public String call() { return TEST_STRING; } } public Callable<String> latchAwaitingStringTask(final CountDownLatch latch) { return new CheckedCallable<String>() { protected String realCall() { try { latch.await(); } catch (InterruptedException quittingTime) {} return TEST_STRING; }}; } public Runnable awaiter(final CountDownLatch latch) { return new CheckedRunnable() { public void realRun() throws InterruptedException { await(latch); }}; } public void await(CountDownLatch latch) { try { assertTrue(latch.await(LONG_DELAY_MS, MILLISECONDS)); } catch (Throwable t) { threadUnexpectedException(t); } } public void await(Semaphore semaphore) { try { assertTrue(semaphore.tryAcquire(LONG_DELAY_MS, MILLISECONDS)); } catch (Throwable t) { threadUnexpectedException(t); } } // /** // * Spin-waits up to LONG_DELAY_MS until flag becomes true. // */ // public void await(AtomicBoolean flag) { // await(flag, LONG_DELAY_MS); // } // /** // * Spin-waits up to the specified timeout until flag becomes true. // */ // public void await(AtomicBoolean flag, long timeoutMillis) { // long startTime = System.nanoTime(); // while (!flag.get()) { // if (millisElapsedSince(startTime) > timeoutMillis) // throw new AssertionFailedError("timed out"); // Thread.yield(); // } // } public static class NPETask implements Callable<String> { public String call() { throw new NullPointerException(); } } public static class CallableOne implements Callable<Integer> { public Integer call() { return one; } } public class ShortRunnable extends CheckedRunnable { protected void realRun() throws Throwable { delay(SHORT_DELAY_MS); } } public class ShortInterruptedRunnable extends CheckedInterruptedRunnable { protected void realRun() throws InterruptedException { delay(SHORT_DELAY_MS); } } public class SmallRunnable extends CheckedRunnable { protected void realRun() throws Throwable { delay(SMALL_DELAY_MS); } } public class SmallPossiblyInterruptedRunnable extends CheckedRunnable { protected void realRun() { try { delay(SMALL_DELAY_MS); } catch (InterruptedException ok) {} } } public class SmallCallable extends CheckedCallable { protected Object realCall() throws InterruptedException { delay(SMALL_DELAY_MS); return Boolean.TRUE; } } public class MediumRunnable extends CheckedRunnable { protected void realRun() throws Throwable { delay(MEDIUM_DELAY_MS); } } public class MediumInterruptedRunnable extends CheckedInterruptedRunnable { protected void realRun() throws InterruptedException { delay(MEDIUM_DELAY_MS); } } public Runnable possiblyInterruptedRunnable(final long timeoutMillis) { return new CheckedRunnable() { protected void realRun() { try { delay(timeoutMillis); } catch (InterruptedException ok) {} }}; } public class MediumPossiblyInterruptedRunnable extends CheckedRunnable { protected void realRun() { try { delay(MEDIUM_DELAY_MS); } catch (InterruptedException ok) {} } } public class LongPossiblyInterruptedRunnable extends CheckedRunnable { protected void realRun() { try { delay(LONG_DELAY_MS); } catch (InterruptedException ok) {} } } /** * For use as ThreadFactory in constructors */ public static class SimpleThreadFactory implements ThreadFactory { public Thread newThread(Runnable r) { return new Thread(r); } } public interface TrackedRunnable extends Runnable { boolean isDone(); } public static TrackedRunnable trackedRunnable(final long timeoutMillis) { return new TrackedRunnable() { private volatile boolean done = false; public boolean isDone() { return done; } public void run() { try { delay(timeoutMillis); done = true; } catch (InterruptedException ok) {} } }; } public static class TrackedShortRunnable implements Runnable { public volatile boolean done = false; public void run() { try { delay(SHORT_DELAY_MS); done = true; } catch (InterruptedException ok) {} } } public static class TrackedSmallRunnable implements Runnable { public volatile boolean done = false; public void run() { try { delay(SMALL_DELAY_MS); done = true; } catch (InterruptedException ok) {} } } public static class TrackedMediumRunnable implements Runnable { public volatile boolean done = false; public void run() { try { delay(MEDIUM_DELAY_MS); done = true; } catch (InterruptedException ok) {} } } public static class TrackedLongRunnable implements Runnable { public volatile boolean done = false; public void run() { try { delay(LONG_DELAY_MS); done = true; } catch (InterruptedException ok) {} } } public static class TrackedNoOpRunnable implements Runnable { public volatile boolean done = false; public void run() { done = true; } } public static class TrackedCallable implements Callable { public volatile boolean done = false; public Object call() { try { delay(SMALL_DELAY_MS); done = true; } catch (InterruptedException ok) {} return Boolean.TRUE; } } // /** // * Analog of CheckedRunnable for RecursiveAction // */ // public abstract class CheckedRecursiveAction extends RecursiveAction { // protected abstract void realCompute() throws Throwable; // public final void compute() { // try { // realCompute(); // } catch (Throwable t) { // threadUnexpectedException(t); // } // } // } // /** // * Analog of CheckedCallable for RecursiveTask // */ // public abstract class CheckedRecursiveTask<T> extends RecursiveTask<T> { // protected abstract T realCompute() throws Throwable; // public final T compute() { // try { // return realCompute(); // } catch (Throwable t) { // threadUnexpectedException(t); // return null; // } // } // } /** * For use as RejectedExecutionHandler in constructors */ public static class NoOpREHandler implements RejectedExecutionHandler { public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {} } /** * A CyclicBarrier that uses timed await and fails with * AssertionFailedErrors instead of throwing checked exceptions. */ public class CheckedBarrier extends CyclicBarrier { public CheckedBarrier(int parties) { super(parties); } public int await() { try { return super.await(2 * LONG_DELAY_MS, MILLISECONDS); } catch (TimeoutException e) { throw new AssertionFailedError("timed out"); } catch (Exception e) { AssertionFailedError afe = new AssertionFailedError("Unexpected exception: " + e); afe.initCause(e); throw afe; } } } void checkEmpty(BlockingQueue q) { try { assertTrue(q.isEmpty()); assertEquals(0, q.size()); assertNull(q.peek()); assertNull(q.poll()); assertNull(q.poll(0, MILLISECONDS)); assertEquals(q.toString(), "[]"); assertTrue(Arrays.equals(q.toArray(), new Object[0])); assertFalse(q.iterator().hasNext()); try { q.element(); shouldThrow(); } catch (NoSuchElementException success) {} try { q.iterator().next(); shouldThrow(); } catch (NoSuchElementException success) {} try { q.remove(); shouldThrow(); } catch (NoSuchElementException success) {} } catch (InterruptedException ie) { threadUnexpectedException(ie); } } @SuppressWarnings("unchecked") <T> T serialClone(T o) { try { ByteArrayOutputStream bos = new ByteArrayOutputStream(); ObjectOutputStream oos = new ObjectOutputStream(bos); oos.writeObject(o); oos.flush(); oos.close(); ObjectInputStream ois = new ObjectInputStream (new ByteArrayInputStream(bos.toByteArray())); T clone = (T) ois.readObject(); assertSame(o.getClass(), clone.getClass()); return clone; } catch (Throwable t) { threadUnexpectedException(t); return null; } } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; import static junit.framework.Assert.assertTrue; import static junit.framework.Assert.fail; import java.util.concurrent.CancellationException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; /** * Used to test listenable future implementations. * * @author Sven Mawson */ public class ListenableFutureTester { private final ExecutorService exec; private final ListenableFuture<?> future; private final CountDownLatch latch; public ListenableFutureTester(ListenableFuture<?> future) { this.exec = Executors.newCachedThreadPool(); this.future = future; this.latch = new CountDownLatch(1); } public void setUp() { future.addListener(new Runnable() { @Override public void run() { latch.countDown(); } }, exec); assertEquals(1, latch.getCount()); assertFalse(future.isDone()); assertFalse(future.isCancelled()); } public void tearDown() { exec.shutdown(); } public void testCompletedFuture(Object expectedValue) throws InterruptedException, ExecutionException { assertTrue(future.isDone()); assertFalse(future.isCancelled()); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertTrue(future.isDone()); assertFalse(future.isCancelled()); assertEquals(expectedValue, future.get()); } public void testCancelledFuture() throws InterruptedException, ExecutionException { assertTrue(future.isDone()); assertTrue(future.isCancelled()); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertTrue(future.isDone()); assertTrue(future.isCancelled()); try { future.get(); fail("Future should throw CancellationException on cancel."); } catch (CancellationException expected) {} } public void testFailedFuture(String message) throws InterruptedException { assertTrue(future.isDone()); assertFalse(future.isCancelled()); assertTrue(latch.await(5, TimeUnit.SECONDS)); assertTrue(future.isDone()); assertFalse(future.isCancelled()); try { future.get(); fail("Future should rethrow the exception."); } catch (ExecutionException e) { assertEquals(message, e.getCause().getMessage()); } } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.util.concurrent; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static junit.framework.Assert.fail; import com.google.common.testing.TearDown; import com.google.common.testing.TearDownAccepter; import java.util.concurrent.TimeUnit; import java.util.logging.Logger; /** * Utilities for performing thread interruption in tests * * @author Kevin Bourrillion * @author Chris Povirk */ final class InterruptionUtil { private static final Logger logger = Logger.getLogger(InterruptionUtil.class.getName()); /** * Runnable which will interrupt the target thread repeatedly when run. */ private static final class Interruptenator implements Runnable { private final long everyMillis; private final Thread interruptee; private volatile boolean shouldStop = false; Interruptenator(Thread interruptee, long everyMillis) { this.everyMillis = everyMillis; this.interruptee = interruptee; } @Override public void run() { while (true) { try { Thread.sleep(everyMillis); } catch (InterruptedException e) { // ok. just stop sleeping. } if (shouldStop) { break; } interruptee.interrupt(); } } void stopInterrupting() { shouldStop = true; } } /** * Interrupts the current thread after sleeping for the specified delay. */ static void requestInterruptIn(final long time, final TimeUnit unit) { final Thread interruptee = Thread.currentThread(); new Thread(new Runnable() { @Override public void run() { try { unit.sleep(time); } catch (InterruptedException wontHappen) { throw new AssertionError(wontHappen); } interruptee.interrupt(); } }).start(); } static void repeatedlyInterruptTestThread( long interruptPeriodMillis, TearDownAccepter tearDownAccepter) { final Interruptenator interruptingTask = new Interruptenator(Thread.currentThread(), interruptPeriodMillis); final Thread interruptingThread = new Thread(interruptingTask); interruptingThread.start(); tearDownAccepter.addTearDown(new TearDown() { @Override public void tearDown() throws Exception { interruptingTask.stopInterrupting(); interruptingThread.interrupt(); joinUninterruptibly(interruptingThread, 2500, MILLISECONDS); Thread.interrupted(); if (interruptingThread.isAlive()) { // This will be hidden by test-output redirection: logger.severe( "InterruptenatorTask did not exit; future tests may be affected"); /* * This won't do any good under JUnit 3, but I'll leave it around in * case we ever switch to JUnit 4: */ fail(); } } }); } // TODO(cpovirk): promote to Uninterruptibles, and add untimed version private static void joinUninterruptibly( Thread thread, long timeout, TimeUnit unit) { boolean interrupted = false; try { long remainingNanos = unit.toNanos(timeout); long end = System.nanoTime() + remainingNanos; while (true) { try { // TimeUnit.timedJoin() treats negative timeouts just like zero. NANOSECONDS.timedJoin(thread, remainingNanos); return; } catch (InterruptedException e) { interrupted = true; remainingNanos = end - System.nanoTime(); } } } finally { if (interrupted) { Thread.currentThread().interrupt(); } } } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import com.google.common.collect.Sets; import java.io.IOException; import java.util.Set; /** * The purpose of the CheckCloseSupplier is to report when all closeable objects * supplied by the delegate supplier are closed. To do this, the factory method * returns a decorated version of the {@code delegate} supplied in the * constructor. The decoration mechanism is left up to the subclass via the * abstract {@link #wrap} method. * * <p>The decorated object returned from {@link #wrap} should ideally override * its {@code close} method to not only call {@code super.close()} but to also * call {@code callback.delegateClosed()}. * * @author Chris Nokleberg */ abstract class CheckCloseSupplier<T> { private final Set<Callback> open = Sets.newHashSet(); abstract static class Input<T> extends CheckCloseSupplier<T> implements InputSupplier<T> { private final InputSupplier<? extends T> delegate; public Input(InputSupplier<? extends T> delegate) { this.delegate = delegate; } @Override public T getInput() throws IOException { return wrap(delegate.getInput(), newCallback()); } } abstract static class Output<T> extends CheckCloseSupplier<T> implements OutputSupplier<T> { private final OutputSupplier<? extends T> delegate; public Output(OutputSupplier<? extends T> delegate) { this.delegate = delegate; } @Override public T getOutput() throws IOException { return wrap(delegate.getOutput(), newCallback()); } } public final class Callback { public void delegateClosed() { open.remove(this); } } protected Callback newCallback() { Callback callback = new Callback(); open.add(callback); return callback; } /** * Subclasses should wrap the given object and call * {@link Callback#delegateClosed} when the close method of the delegate is * called, to inform the supplier that the underlying * {@code Closeable} is not longer open. * * @param object the object to wrap. * @param callback the object that the wrapper should call to signal that the */ protected abstract T wrap(T object, Callback callback); /** Returns true if all the closeables have been closed closed */ public boolean areClosed() { return open.isEmpty(); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import java.io.FilterInputStream; import java.io.IOException; import java.io.InputStream; import java.util.Random; /** Returns a random portion of the requested bytes on each call. */ class RandomAmountInputStream extends FilterInputStream { private final Random random; public RandomAmountInputStream(InputStream in, Random random) { super(in); this.random = random; } @Override public int read(byte[] b, int off, int len) throws IOException { return super.read(b, off, random.nextInt(len) + 1); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.io; import junit.framework.TestCase; /** * Base test case class for I/O tests. * * @author Chris Nokleberg */ public abstract class IoTestCase extends TestCase { static final String I18N = "\u00CE\u00F1\u0163\u00E9\u0072\u00F1\u00E5\u0163\u00EE\u00F6" + "\u00F1\u00E5\u013C\u00EE\u017E\u00E5\u0163\u00EE\u00F6\u00F1"; static final String ASCII = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ" + "[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"; /** Returns a byte array of length size that has values 0 .. size - 1. */ protected static byte[] newPreFilledByteArray(int size) { return newPreFilledByteArray(0, size); } /** * Returns a byte array of length size that has values * offset .. offset + size - 1. */ protected static byte[] newPreFilledByteArray(int offset, int size) { byte[] array = new byte[size]; for (int i = 0; i < size; i++) { array[i] = (byte) (offset + i); } return array; } }
Java
/* * This file is a modified version of * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/src/main/java/util/concurrent/ExecutorService.java?revision=1.51 * which contained the following notice: * * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/publicdomain/zero/1.0/ */ package java.util.concurrent; import java.util.Collection; import java.util.List; public interface ExecutorService extends Executor { void shutdown(); List<Runnable> shutdownNow(); boolean isShutdown(); boolean isTerminated(); boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException; <T> Future<T> submit(Callable<T> task); <T> Future<T> submit(Runnable task, T result); Future<?> submit(Runnable task); <T> List<Future<T>> invokeAll(Collection<? extends Callable<T>> tasks) throws InterruptedException; <T> List<Future<T>> invokeAll( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException; <T> T invokeAny(Collection<? extends Callable<T>> tasks) throws InterruptedException, ExecutionException; <T> T invokeAny( Collection<? extends Callable<T>> tasks, long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException; }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * GWT serialization logic for {@link PairwiseEquivalence}. * * @author kkanitkar@google.com (Kedar Kanitkar) */ public class PairwiseEquivalence_CustomFieldSerializer { private PairwiseEquivalence_CustomFieldSerializer() {} public static void deserialize(SerializationStreamReader reader, PairwiseEquivalence<?> instance) {} public static PairwiseEquivalence<?> instantiate(SerializationStreamReader reader) throws SerializationException { return create((Equivalence<?>) reader.readObject()); } private static <T> PairwiseEquivalence<T> create(Equivalence<T> elementEquivalence) { return new PairwiseEquivalence<T>(elementEquivalence); } public static void serialize(SerializationStreamWriter writer, PairwiseEquivalence<?> instance) throws SerializationException { writer.writeObject(instance.elementEquivalence); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import java.util.Set; import javax.annotation.Nullable; /** * Contains dummy collection implementations to convince GWT that part of * serializing a collection is serializing its elements. * * <p>See {@linkplain com.google.common.collect.GwtSerializationDependencies the * com.google.common.collect version} for more details. * * @author Chris Povirk */ @GwtCompatible // None of these classes are instantiated, let alone serialized: @SuppressWarnings("serial") final class GwtSerializationDependencies { private GwtSerializationDependencies() {} static final class OptionalDependencies<T> extends Optional<T> { T value; OptionalDependencies() { super(); } @Override public boolean isPresent() { throw new AssertionError(); } @Override public T get() { throw new AssertionError(); } @Override public T or(T defaultValue) { throw new AssertionError(); } @Override public Optional<T> or(Optional<? extends T> secondChoice) { throw new AssertionError(); } @Override public T or(Supplier<? extends T> supplier) { throw new AssertionError(); } @Override public T orNull() { throw new AssertionError(); } @Override public Set<T> asSet() { throw new AssertionError(); } @Override public boolean equals(@Nullable Object object) { throw new AssertionError(); } @Override public int hashCode() { throw new AssertionError(); } @Override public String toString() { throw new AssertionError(); } } }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * Custom GWT serializer for {@link Absent}. * * <p>GWT can serialize an absent {@code Optional} on its own, but the resulting object is a * different instance than the singleton {@code Absent.INSTANCE}, which breaks equality. We * implement a custom serializer to maintain the singleton property. * * @author Chris Povirk */ @GwtCompatible public class Absent_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, Absent instance) {} public static Absent instantiate(SerializationStreamReader reader) { return Absent.INSTANCE; } public static void serialize(SerializationStreamWriter writer, Absent instance) {} }
Java
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * Custom GWT serializer for {@link Present}. * * @author Chris Povirk */ @GwtCompatible public class Present_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, Present<?> instance) {} public static Present<Object> instantiate(SerializationStreamReader reader) throws SerializationException { return (Present<Object>) Optional.of(reader.readObject()); } public static void serialize(SerializationStreamWriter writer, Present<?> instance) throws SerializationException { writer.writeObject(instance.get()); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Comparator; /** * This class implements the GWT serialization of {@link TreeMultimap}. * * @author Nikhil Singhal */ public class TreeMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader in, TreeMultimap<?, ?> out) { } @SuppressWarnings("unchecked") public static TreeMultimap<Object, Object> instantiate( SerializationStreamReader in) throws SerializationException { Comparator keyComparator = (Comparator) in.readObject(); Comparator valueComparator = (Comparator) in.readObject(); return (TreeMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.populate( in, TreeMultimap.create(keyComparator, valueComparator)); } public static void serialize(SerializationStreamWriter out, TreeMultimap<?, ?> multimap) throws SerializationException { out.writeObject(multimap.keyComparator()); out.writeObject(multimap.valueComparator()); Multimap_CustomFieldSerializerBase.serialize(out, multimap); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link NullsFirstOrdering}. * * @author Chris Povirk */ public class NullsFirstOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, NullsFirstOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static NullsFirstOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new NullsFirstOrdering<Object>( (Ordering<Object>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, NullsFirstOrdering<?> instance) throws SerializationException { writer.writeObject(instance.ordering); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link EmptyImmutableListMultimap}. * * @author Chris Povirk */ public class EmptyImmutableListMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableListMultimap instance) { } public static EmptyImmutableListMultimap instantiate( SerializationStreamReader reader) { return EmptyImmutableListMultimap.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableListMultimap instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase; import java.util.ArrayList; import java.util.List; /** * This class implements the GWT serialization of {@link * RegularImmutableList}. * * @author Hayward Chan */ public class RegularImmutableList_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableList<?> instance) { } public static RegularImmutableList<Object> instantiate( SerializationStreamReader reader) throws SerializationException { List<Object> elements = new ArrayList<Object>(); Collection_CustomFieldSerializerBase.deserialize(reader, elements); /* * For this custom field serializer to be invoked, the list must have been * RegularImmutableList before it's serialized. Since RegularImmutableList * always have one or more elements, ImmutableList.copyOf always return * a RegularImmutableList back. */ return (RegularImmutableList<Object>) ImmutableList.copyOf(elements); } public static void serialize(SerializationStreamWriter writer, RegularImmutableList<?> instance) throws SerializationException { Collection_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link UsingToStringOrdering}. * * @author Chris Povirk */ public class UsingToStringOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, UsingToStringOrdering instance) { } public static UsingToStringOrdering instantiate( SerializationStreamReader reader) { return UsingToStringOrdering.INSTANCE; } public static void serialize(SerializationStreamWriter writer, UsingToStringOrdering instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link ArrayListMultimap}. * * @author Chris Povirk */ public class ArrayListMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader in, ArrayListMultimap<?, ?> out) { } public static ArrayListMultimap<Object, Object> instantiate( SerializationStreamReader in) throws SerializationException { return (ArrayListMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.populate( in, ArrayListMultimap.create()); } public static void serialize(SerializationStreamWriter out, ArrayListMultimap<?, ?> multimap) throws SerializationException { Multimap_CustomFieldSerializerBase.serialize(out, multimap); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Map; import java.util.Map.Entry; /** * This class implements the GWT serialization of {@link HashBasedTable}. * * @author Hayward Chan */ public class HashBasedTable_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, HashBasedTable<?, ?, ?> instance) { } public static HashBasedTable<Object, Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { Map<?, ?> hashMap = (Map<?, ?>) reader.readObject(); HashBasedTable<Object, Object, Object> table = HashBasedTable.create(); for (Entry<?, ?> row : hashMap.entrySet()) { table.row(row.getKey()).putAll((Map<?, ?>) row.getValue()); } return table; } public static void serialize(SerializationStreamWriter writer, HashBasedTable<?, ?, ?> instance) throws SerializationException { /* * The backing map of a HashBasedTable is a hash map of hash map. * Therefore, the backing map is serializable (assuming the row, * column and values are all serializable). */ writer.writeObject(instance.backingMap); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link ImmutableListMultimap}. * * @author Chris Povirk */ public class ImmutableListMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableListMultimap<?, ?> instance) { } public static ImmutableListMultimap<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { return (ImmutableListMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.instantiate( reader, ImmutableListMultimap.builder()); } public static void serialize(SerializationStreamWriter writer, ImmutableListMultimap<?, ?> instance) throws SerializationException { Multimap_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class contains static utility methods for writing {@code Multiset} GWT * field serializers. Serializers should delegate to * {@link #serialize(SerializationStreamWriter, Multiset)} and to either * {@link #instantiate(SerializationStreamReader, ImmutableMultiset.Builder)} or * {@link #populate(SerializationStreamReader, Multiset)}. * * @author Chris Povirk */ final class Multiset_CustomFieldSerializerBase { static ImmutableMultiset<Object> instantiate( SerializationStreamReader reader, ImmutableMultiset.Builder<Object> builder) throws SerializationException { int distinctElements = reader.readInt(); for (int i = 0; i < distinctElements; i++) { Object element = reader.readObject(); int count = reader.readInt(); builder.addCopies(element, count); } return builder.build(); } static Multiset<Object> populate( SerializationStreamReader reader, Multiset<Object> multiset) throws SerializationException { int distinctElements = reader.readInt(); for (int i = 0; i < distinctElements; i++) { Object element = reader.readObject(); int count = reader.readInt(); multiset.add(element, count); } return multiset; } static void serialize(SerializationStreamWriter writer, Multiset<?> instance) throws SerializationException { int entryCount = instance.entrySet().size(); writer.writeInt(entryCount); for (Multiset.Entry<?> entry : instance.entrySet()) { writer.writeObject(entry.getElement()); writer.writeInt(entry.getCount()); } } private Multiset_CustomFieldSerializerBase() {} }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link LexicographicalOrdering}. * * @author Chris Povirk */ public class LexicographicalOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, LexicographicalOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static LexicographicalOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new LexicographicalOrdering<Object>( (Ordering<Object>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, LexicographicalOrdering<?> instance) throws SerializationException { writer.writeObject(instance.elementOrder); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link HashMultiset}. * * @author Chris Povirk */ public class HashMultiset_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, HashMultiset<?> instance) { } public static HashMultiset<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return (HashMultiset<Object>) Multiset_CustomFieldSerializerBase.populate( reader, HashMultiset.create()); } public static void serialize(SerializationStreamWriter writer, HashMultiset<?> instance) throws SerializationException { Multiset_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Map_CustomFieldSerializerBase; import java.util.Comparator; import java.util.SortedMap; import java.util.TreeMap; /** * This class implements the GWT serialization of {@link ImmutableSortedMap}. * * @author Chris Povirk */ public class ImmutableSortedMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableSortedMap<?, ?> instance) { } public static ImmutableSortedMap<?, ?> instantiate( SerializationStreamReader reader) throws SerializationException { /* * Nothing we can do, but we're already assuming the serialized form is * correctly typed, anyway. */ @SuppressWarnings("unchecked") Comparator<Object> comparator = (Comparator<Object>) reader.readObject(); SortedMap<Object, Object> entries = new TreeMap<Object, Object>(comparator); Map_CustomFieldSerializerBase.deserialize(reader, entries); return ImmutableSortedMap.orderedBy(comparator).putAll(entries).build(); } public static void serialize(SerializationStreamWriter writer, ImmutableSortedMap<?, ?> instance) throws SerializationException { writer.writeObject(instance.comparator()); Map_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Map_CustomFieldSerializerBase; import java.util.LinkedHashMap; import java.util.Map; /** * This class implements the GWT serialization of * {@link RegularImmutableBiMap}. * * @author Chris Povirk */ public class RegularImmutableBiMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableBiMap<?, ?> instance) { } public static RegularImmutableBiMap<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { Map<Object, Object> entries = new LinkedHashMap<Object, Object>(); Map_CustomFieldSerializerBase.deserialize(reader, entries); /* * For this custom field serializer to be invoked, the map must have been * RegularImmutableBiMap before it's serialized. Since RegularImmutableBiMap * always have one or more elements, ImmutableBiMap.copyOf always return a * RegularImmutableBiMap back. */ return (RegularImmutableBiMap<Object, Object>) ImmutableBiMap.copyOf(entries); } public static void serialize(SerializationStreamWriter writer, RegularImmutableBiMap<?, ?> instance) throws SerializationException { Map_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Collection; import java.util.Map; /** * This class contains static utility methods for writing {@code Multimap} GWT * field serializers. Serializers should delegate to * {@link #serialize(SerializationStreamWriter, Multimap)} and to either * {@link #instantiate(SerializationStreamReader, ImmutableMultimap.Builder)} or * {@link #populate(SerializationStreamReader, Multimap)}. * * @author Chris Povirk */ public final class Multimap_CustomFieldSerializerBase { static ImmutableMultimap<Object, Object> instantiate( SerializationStreamReader reader, ImmutableMultimap.Builder<Object, Object> builder) throws SerializationException { int keyCount = reader.readInt(); for (int i = 0; i < keyCount; ++i) { Object key = reader.readObject(); int valueCount = reader.readInt(); for (int j = 0; j < valueCount; ++j) { Object value = reader.readObject(); builder.put(key, value); } } return builder.build(); } public static Multimap<Object, Object> populate( SerializationStreamReader reader, Multimap<Object, Object> multimap) throws SerializationException { int keyCount = reader.readInt(); for (int i = 0; i < keyCount; ++i) { Object key = reader.readObject(); int valueCount = reader.readInt(); for (int j = 0; j < valueCount; ++j) { Object value = reader.readObject(); multimap.put(key, value); } } return multimap; } public static void serialize( SerializationStreamWriter writer, Multimap<?, ?> instance) throws SerializationException { writer.writeInt(instance.asMap().size()); for (Map.Entry<?, ? extends Collection<?>> entry : instance.asMap().entrySet()) { writer.writeObject(entry.getKey()); writer.writeInt(entry.getValue().size()); for (Object value : entry.getValue()) { writer.writeObject(value); } } } private Multimap_CustomFieldSerializerBase() {} }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link NaturalOrdering}. * * @author Chris Povirk */ public class NaturalOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, NaturalOrdering instance) { } public static NaturalOrdering instantiate( SerializationStreamReader reader) { return NaturalOrdering.INSTANCE; } public static void serialize(SerializationStreamWriter writer, NaturalOrdering instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * Even though {@link ImmutableList} cannot be instantiated, we still need * a custom field serializer to unify the type signature of * {@code ImmutableList[]} on server and client side. * * @author Hayward Chan */ public final class ImmutableList_CustomFieldSerializer {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase; import java.util.List; /** * This class implements the GWT serialization of {@link ImmutableEnumSet}. * * @author Hayward Chan */ public class ImmutableEnumSet_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableEnumSet<?> instance) { } public static <E extends Enum<E>> ImmutableEnumSet<?> instantiate( SerializationStreamReader reader) throws SerializationException { List<E> deserialized = Lists.newArrayList(); Collection_CustomFieldSerializerBase.deserialize(reader, deserialized); /* * It is safe to cast to ImmutableEnumSet because in order for it to be * serialized as an ImmutableEnumSet, it must be non-empty to start * with. */ return (ImmutableEnumSet<?>) Sets.immutableEnumSet(deserialized); } public static void serialize(SerializationStreamWriter writer, ImmutableEnumSet<?> instance) throws SerializationException { Collection_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link SingletonImmutableMap}. * * @author Chris Povirk */ public class SingletonImmutableMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, SingletonImmutableMap<?, ?> instance) { } public static SingletonImmutableMap<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { Object key = checkNotNull(reader.readObject()); Object value = checkNotNull(reader.readObject()); return new SingletonImmutableMap<Object, Object>(key, value); } public static void serialize(SerializationStreamWriter writer, SingletonImmutableMap<?, ?> instance) throws SerializationException { writer.writeObject(instance.singleKey); writer.writeObject(instance.singleValue); } }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase; import java.util.ArrayList; import java.util.List; /** * This class implements the server-side GWT serialization of * {@link ImmutableAsList}. * * @author Hayward Chan */ @GwtCompatible(emulated = true) public class ImmutableAsList_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableAsList<?> instance) { } public static ImmutableAsList<Object> instantiate( SerializationStreamReader reader) throws SerializationException { List<Object> elements = new ArrayList<Object>(); Collection_CustomFieldSerializerBase.deserialize(reader, elements); ImmutableList<Object> asImmutableList = ImmutableList.copyOf(elements); return new ImmutableAsList<Object>( asImmutableList.toArray(new Object[asImmutableList.size()]), asImmutableList); } public static void serialize(SerializationStreamWriter writer, ImmutableAsList<?> instance) throws SerializationException { Collection_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import java.util.Comparator; import java.util.HashMap; import java.util.TreeMap; /** * Contains dummy collection implementations to convince GWT that part of * serializing a collection is serializing its elements. * * <p>Because of our use of final fields in our collections, GWT's normal * heuristic for determining which classes might be serialized fails. That * heuristic is, roughly speaking, to look at each parameter and return type of * each RPC interface and to assume that implementations of those types might be * serialized. Those types have their own dependencies -- their fields -- which * are analyzed recursively and analogously. * * <p>For classes with final fields, GWT assumes that the class itself might be * serialized but doesn't assume the same about its final fields. To work around * this, we provide dummy implementations of our collections with their * dependencies as non-final fields. Even though these implementations are never * instantiated, they are visible to GWT when it performs its serialization * analysis, and it assumes that their fields may be serialized. * * <p>Currently we provide dummy implementations of all the immutable * collection classes necessary to support declarations like * {@code ImmutableMultiset<String>} in RPC interfaces. Support for * {@code ImmutableMultiset} in the interface is support for {@code Multiset}, * so there is nothing further to be done to support the new collection * interfaces. It is not support, however, for an RPC interface in terms of * {@code HashMultiset}. It is still possible to send a {@code HashMultiset} * over GWT RPC; it is only the declaration of an interface in terms of * {@code HashMultiset} that we haven't tried to support. (We may wish to * revisit this decision in the future.) * * @author Chris Povirk */ @GwtCompatible // None of these classes are instantiated, let alone serialized: @SuppressWarnings("serial") final class GwtSerializationDependencies { private GwtSerializationDependencies() {} static final class ImmutableListMultimapDependencies<K, V> extends ImmutableListMultimap<K, V> { K key; V value; ImmutableListMultimapDependencies() { super(null, 0); } } // ImmutableMap is covered by ImmutableSortedMap/ImmutableBiMap. // ImmutableMultimap is covered by ImmutableSetMultimap/ImmutableListMultimap. static final class ImmutableSetMultimapDependencies<K, V> extends ImmutableSetMultimap<K, V> { K key; V value; ImmutableSetMultimapDependencies() { super(null, 0, null); } } /* * We support an interface declared in terms of LinkedListMultimap because it * supports entry ordering not supported by other implementations. */ static final class LinkedListMultimapDependencies<K, V> extends LinkedListMultimap<K, V> { K key; V value; LinkedListMultimapDependencies() { super(); } } static final class HashBasedTableDependencies<R, C, V> extends HashBasedTable<R, C, V> { HashMap<R, HashMap<C, V>> data; HashBasedTableDependencies() { super(null, null); } } static final class TreeBasedTableDependencies<R, C, V> extends TreeBasedTable<R, C, V> { TreeMap<R, TreeMap<C, V>> data; TreeBasedTableDependencies() { super(null, null); } } static final class TreeMultimapDependencies<K, V> extends TreeMultimap<K, V> { Comparator<? super K> keyComparator; Comparator<? super V> valueComparator; K key; V value; TreeMultimapDependencies() { super(null, null); } } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Comparator; /** * This class implements the GWT serialization of {@link CompoundOrdering}. * * @author Chris Povirk */ public class CompoundOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, CompoundOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static CompoundOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new CompoundOrdering<Object>( (ImmutableList<Comparator<Object>>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, CompoundOrdering<?> instance) throws SerializationException { writer.writeObject(instance.comparators); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link ImmutableEntry}. * * @author iteratee@google.com (Kyle Butt) */ public class ImmutableEntry_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableEntry<?, ?> instance) { } public static ImmutableEntry<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { Object key = reader.readObject(); Object value = reader.readObject(); return new ImmutableEntry<Object, Object>(key, value); } public static void serialize(SerializationStreamWriter writer, ImmutableEntry<?, ?> instance) throws SerializationException { writer.writeObject(instance.getKey()); writer.writeObject(instance.getValue()); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase; import java.util.ArrayList; import java.util.Comparator; import java.util.List; /** * This class implements the GWT serialization of * {@link RegularImmutableSortedSet}. * * @author Chris Povirk */ public class RegularImmutableSortedSet_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableSortedSet<?> instance) { } public static RegularImmutableSortedSet<Object> instantiate( SerializationStreamReader reader) throws SerializationException { /* * Nothing we can do, but we're already assuming the serialized form is * correctly typed, anyway. */ @SuppressWarnings("unchecked") Comparator<Object> comparator = (Comparator<Object>) reader.readObject(); List<Object> elements = new ArrayList<Object>(); Collection_CustomFieldSerializerBase.deserialize(reader, elements); /* * For this custom field serializer to be invoked, the set must have been * RegularImmutableSortedSet before it's serialized. Since * RegularImmutableSortedSet always have one or more elements, * ImmutableSortedSet.copyOf always return a RegularImmutableSortedSet back. */ return (RegularImmutableSortedSet<Object>) ImmutableSortedSet.copyOf(comparator, elements); } public static void serialize(SerializationStreamWriter writer, RegularImmutableSortedSet<?> instance) throws SerializationException { writer.writeObject(instance.comparator()); Collection_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link SingletonImmutableList}. * * @author Chris Povirk */ public class SingletonImmutableList_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, SingletonImmutableList<?> instance) { } public static SingletonImmutableList<Object> instantiate( SerializationStreamReader reader) throws SerializationException { Object element = reader.readObject(); return new SingletonImmutableList<Object>(element); } public static void serialize(SerializationStreamWriter writer, SingletonImmutableList<?> instance) throws SerializationException { writer.writeObject(instance.element); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link EmptyImmutableSet}. * * @author Chris Povirk */ public class EmptyImmutableSet_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableSet instance) { } public static EmptyImmutableSet instantiate( SerializationStreamReader reader) { return EmptyImmutableSet.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableSet instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link ExplicitOrdering}. * * @author Chris Povirk */ public class ExplicitOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ExplicitOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static ExplicitOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new ExplicitOrdering<Object>( (ImmutableMap<Object, Integer>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, ExplicitOrdering<?> instance) throws SerializationException { writer.writeObject(instance.rankMap); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link NullsLastOrdering}. * * @author Chris Povirk */ public class NullsLastOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, NullsLastOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static NullsLastOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new NullsLastOrdering<Object>( (Ordering<Object>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, NullsLastOrdering<?> instance) throws SerializationException { writer.writeObject(instance.ordering); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Comparator; import java.util.Map; import java.util.Map.Entry; /** * This class implements the GWT serialization of {@link TreeBasedTable}. * * @author Hayward Chan */ public class TreeBasedTable_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, TreeBasedTable<?, ?, ?> instance) { } public static TreeBasedTable<Object, Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { @SuppressWarnings("unchecked") // The comparator isn't used statically. Comparator<Object> rowComparator = (Comparator<Object>) reader.readObject(); @SuppressWarnings("unchecked") // The comparator isn't used statically. Comparator<Object> columnComparator = (Comparator<Object>) reader.readObject(); Map<?, ?> backingMap = (Map<?, ?>) reader.readObject(); TreeBasedTable<Object, Object, Object> table = TreeBasedTable.create(rowComparator, columnComparator); for (Entry<?, ?> row : backingMap.entrySet()) { table.row(row.getKey()).putAll((Map<?, ?>) row.getValue()); } return table; } public static void serialize(SerializationStreamWriter writer, TreeBasedTable<?, ?, ?> instance) throws SerializationException { /* * The backing map of a TreeBasedTable is a tree map of tree map. * Therefore, the backing map is GWT serializable (assuming the row, * column, value, the row comparator and column comparator are all * serializable). */ writer.writeObject(instance.rowComparator()); writer.writeObject(instance.columnComparator()); writer.writeObject(instance.backingMap); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link LinkedHashMultiset}. * * @author Chris Povirk */ public class LinkedHashMultiset_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, LinkedHashMultiset<?> instance) { } public static LinkedHashMultiset<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return (LinkedHashMultiset<Object>) Multiset_CustomFieldSerializerBase.populate( reader, LinkedHashMultiset.create()); } public static void serialize(SerializationStreamWriter writer, LinkedHashMultiset<?> instance) throws SerializationException { Multiset_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * Even though {@link ImmutableMultiset} cannot be instantiated, we still need * a custom field serializer to unify the type signature of * {@code ImmutableMultiset[]} on server and client side. * * @author Chris Povirk */ public class ImmutableMultiset_CustomFieldSerializer {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * Even though {@link ImmutableSet} cannot be instantiated, we still need * a custom field serializer to unify the type signature of * {@code ImmutableSet[]} on server and client side. * * @author Hayward Chan */ public final class ImmutableSet_CustomFieldSerializer {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Map; /** * This class implements the GWT serialization of {@link LinkedListMultimap}. * * @author Chris Povirk */ public class LinkedListMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader in, LinkedListMultimap<?, ?> out) { } public static LinkedListMultimap<Object, Object> instantiate( SerializationStreamReader in) throws SerializationException { LinkedListMultimap<Object, Object> multimap = LinkedListMultimap.create(); int size = in.readInt(); for (int i = 0; i < size; i++) { Object key = in.readObject(); Object value = in.readObject(); multimap.put(key, value); } return multimap; } public static void serialize(SerializationStreamWriter out, LinkedListMultimap<?, ?> multimap) throws SerializationException { out.writeInt(multimap.size()); for (Map.Entry<?, ?> entry : multimap.entries()) { out.writeObject(entry.getKey()); out.writeObject(entry.getValue()); } } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link SingletonImmutableSet}. * * @author Hayward Chan */ public class SingletonImmutableSet_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, SingletonImmutableSet<?> instance) { } public static SingletonImmutableSet<Object> instantiate( SerializationStreamReader reader) throws SerializationException { Object element = reader.readObject(); return new SingletonImmutableSet<Object>(element); } public static void serialize(SerializationStreamWriter writer, SingletonImmutableSet<?> instance) throws SerializationException { writer.writeObject(instance.element); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link HashMultimap}. * * @author Jord Sonneveld * */ public class HashMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader in, HashMultimap<?, ?> out) { } public static HashMultimap<Object, Object> instantiate( SerializationStreamReader in) throws SerializationException { return (HashMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.populate(in, HashMultimap.create()); } public static void serialize(SerializationStreamWriter out, HashMultimap<?, ?> multimap) throws SerializationException { Multimap_CustomFieldSerializerBase.serialize(out, multimap); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link EmptyImmutableMultiset}. * * @author Chris Povirk */ public class EmptyImmutableMultiset_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableMultiset instance) { } public static EmptyImmutableMultiset instantiate( SerializationStreamReader reader) { return EmptyImmutableMultiset.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableMultiset instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Map_CustomFieldSerializerBase; import java.util.LinkedHashMap; import java.util.Map; /** * This class implements the GWT serialization of {@link RegularImmutableMap}. * * @author Hayward Chan */ public class RegularImmutableMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableMap<?, ?> instance) { } public static RegularImmutableMap<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { Map<Object, Object> entries = new LinkedHashMap<Object, Object>(); Map_CustomFieldSerializerBase.deserialize(reader, entries); /* * For this custom field serializer to be invoked, the map must have been * RegularImmutableMap before it's serialized. Since RegularImmutableMap * always have two or more elements, ImmutableMap.copyOf always return * a RegularImmutableMap back. */ return (RegularImmutableMap<Object, Object>) ImmutableMap.copyOf(entries); } public static void serialize(SerializationStreamWriter writer, RegularImmutableMap<?, ?> instance) throws SerializationException { Map_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link EmptyImmutableMap}. * * @author Chris Povirk */ public class EmptyImmutableMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableMap instance) { } public static EmptyImmutableMap instantiate( SerializationStreamReader reader) { return EmptyImmutableMap.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableMap instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link ReverseOrdering}. * * @author Chris Povirk */ public class ReverseOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ReverseOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static ReverseOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new ReverseOrdering<Object>( (Ordering<Object>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, ReverseOrdering<?> instance) throws SerializationException { writer.writeObject(instance.forwardOrder); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Comparator; /** * This class implements the GWT serialization of {@link ComparatorOrdering}. * * @author Chris Povirk */ public class ComparatorOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ComparatorOrdering<?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static ComparatorOrdering<Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new ComparatorOrdering<Object>( (Comparator<Object>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, ComparatorOrdering<?> instance) throws SerializationException { writer.writeObject(instance.comparator); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link EmptyImmutableList}. * * @author Chris Povirk */ public class EmptyImmutableList_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableList instance) { } public static EmptyImmutableList instantiate( SerializationStreamReader reader) { return EmptyImmutableList.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableList instance) { } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase; import java.util.List; /** * This class implements the GWT serialization of {@link RegularImmutableMultiset}. * * @author Louis Wasserman */ public class RegularImmutableMultiset_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableMultiset<?> instance) { } public static RegularImmutableMultiset<Object> instantiate( SerializationStreamReader reader) throws SerializationException { List<Object> elements = Lists.newArrayList(); Collection_CustomFieldSerializerBase.deserialize(reader, elements); /* * For this custom field serializer to be invoked, the set must have been * RegularImmutableMultiset before it's serialized. Since * RegularImmutableMultiset always have one or more elements, * ImmutableMultiset.copyOf always return a RegularImmutableMultiset back. */ return (RegularImmutableMultiset<Object>) ImmutableMultiset .copyOf(elements); } public static void serialize(SerializationStreamWriter writer, RegularImmutableMultiset<?> instance) throws SerializationException { Collection_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * Even though {@link ImmutableSortedSet} cannot be instantiated, we still need * a custom field serializer to unify the type signature of * {@code ImmutableSortedSet[]} on server and client side. * * @author Hayward Chan */ public final class ImmutableSortedSet_CustomFieldSerializer {}
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Map; /** * This class implements the GWT serialization of {@link LinkedHashMultimap}. * * @author Chris Povirk */ public class LinkedHashMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader in, LinkedHashMultimap<?, ?> out) { } public static LinkedHashMultimap<Object, Object> instantiate( SerializationStreamReader in) throws SerializationException { LinkedHashMultimap<Object, Object> multimap = (LinkedHashMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.populate( in, LinkedHashMultimap.create()); multimap.linkedEntries.clear(); // will clear and repopulate entries for (int i = 0; i < multimap.size(); i++) { Object key = in.readObject(); Object value = in.readObject(); multimap.linkedEntries.add(Maps.immutableEntry(key, value)); } return multimap; } public static void serialize(SerializationStreamWriter out, LinkedHashMultimap<?, ?> multimap) throws SerializationException { Multimap_CustomFieldSerializerBase.serialize(out, multimap); for (Map.Entry<?, ?> entry : multimap.entries()) { out.writeObject(entry.getKey()); out.writeObject(entry.getValue()); } } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import java.util.Comparator; /** * This class implements the GWT serialization of * {@link EmptyImmutableSortedSet}. * * @author Chris Povirk */ public class EmptyImmutableSortedSet_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableSortedSet<?> instance) { } public static EmptyImmutableSortedSet<Object> instantiate( SerializationStreamReader reader) throws SerializationException { /* * Nothing we can do, but we're already assuming the serialized form is * correctly typed, anyway. */ @SuppressWarnings("unchecked") Comparator<Object> comparator = (Comparator<Object>) reader.readObject(); /* * For this custom field serializer to be invoked, the set must have been * EmptyImmutableSortedSet before it's serialized. Since * EmptyImmutableSortedSet always has no elements, ImmutableSortedSet.copyOf * always return an EmptyImmutableSortedSet back. */ return (EmptyImmutableSortedSet<Object>) ImmutableSortedSet.orderedBy(comparator).build(); } public static void serialize(SerializationStreamWriter writer, EmptyImmutableSortedSet<?> instance) throws SerializationException { writer.writeObject(instance.comparator()); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; import com.google.gwt.user.client.rpc.core.java.util.Collection_CustomFieldSerializerBase; import java.util.List; /** * This class implements the GWT serialization of {@link RegularImmutableSet}. * * @author Hayward Chan */ public class RegularImmutableSet_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableSet<?> instance) { } public static RegularImmutableSet<Object> instantiate( SerializationStreamReader reader) throws SerializationException { List<Object> elements = Lists.newArrayList(); Collection_CustomFieldSerializerBase.deserialize(reader, elements); /* * For this custom field serializer to be invoked, the set must have been * RegularImmutableSet before it's serialized. Since RegularImmutableSet * always have two or more elements, ImmutableSet.copyOf always return * a RegularImmutableSet back. */ return (RegularImmutableSet<Object>) ImmutableSet.copyOf(elements); } public static void serialize(SerializationStreamWriter writer, RegularImmutableSet<?> instance) throws SerializationException { Collection_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link ReverseNaturalOrdering}. * * @author Chris Povirk */ public class ReverseNaturalOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ReverseNaturalOrdering instance) { } public static ReverseNaturalOrdering instantiate( SerializationStreamReader reader) { return ReverseNaturalOrdering.INSTANCE; } public static void serialize(SerializationStreamWriter writer, ReverseNaturalOrdering instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link EmptyImmutableSetMultimap}. * * @author Chris Povirk */ public class EmptyImmutableSetMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableSetMultimap instance) { } public static EmptyImmutableSetMultimap instantiate( SerializationStreamReader reader) { return EmptyImmutableSetMultimap.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableSetMultimap instance) { } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.base.Function; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link ByFunctionOrdering}. * * @author Chris Povirk */ public class ByFunctionOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ByFunctionOrdering<?, ?> instance) { } @SuppressWarnings("unchecked") // deserialization is unsafe public static ByFunctionOrdering<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { return new ByFunctionOrdering<Object, Object>( (Function<Object, Object>) reader.readObject(), (Ordering<Object>) reader.readObject()); } public static void serialize(SerializationStreamWriter writer, ByFunctionOrdering<?, ?> instance) throws SerializationException { writer.writeObject(instance.function); writer.writeObject(instance.ordering); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.gwt.user.client.rpc.SerializationException; import com.google.gwt.user.client.rpc.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link ImmutableSetMultimap}. * * @author Chris Povirk */ public class ImmutableSetMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableSetMultimap<?, ?> instance) { } public static ImmutableSetMultimap<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { return (ImmutableSetMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.instantiate( reader, ImmutableSetMultimap.builder()); } public static void serialize(SerializationStreamWriter writer, ImmutableSetMultimap<?, ?> instance) throws SerializationException { Multimap_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import javax.annotation.Nullable; /** * Static utility methods pertaining to {@code Predicate} instances. * * <p>All methods returns serializable predicates as long as they're given * serializable parameters. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/FunctionalExplained">the use of {@code * Predicate}</a>. * * @author Kevin Bourrillion * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class Predicates { private Predicates() {} // TODO(kevinb): considering having these implement a VisitablePredicate // interface which specifies an accept(PredicateVisitor) method. /** * Returns a predicate that always evaluates to {@code true}. */ @GwtCompatible(serializable = true) public static <T> Predicate<T> alwaysTrue() { return ObjectPredicate.ALWAYS_TRUE.withNarrowedType(); } /** * Returns a predicate that always evaluates to {@code false}. */ @GwtCompatible(serializable = true) public static <T> Predicate<T> alwaysFalse() { return ObjectPredicate.ALWAYS_FALSE.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the object reference * being tested is null. */ @GwtCompatible(serializable = true) public static <T> Predicate<T> isNull() { return ObjectPredicate.IS_NULL.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the object reference * being tested is not null. */ @GwtCompatible(serializable = true) public static <T> Predicate<T> notNull() { return ObjectPredicate.NOT_NULL.withNarrowedType(); } /** * Returns a predicate that evaluates to {@code true} if the given predicate * evaluates to {@code false}. */ public static <T> Predicate<T> not(Predicate<T> predicate) { return new NotPredicate<T>(predicate); } /** * Returns a predicate that evaluates to {@code true} if each of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a false * predicate is found. It defensively copies the iterable passed in, so future * changes to it won't alter the behavior of this predicate. If {@code * components} is empty, the returned predicate will always evaluate to {@code * true}. */ public static <T> Predicate<T> and( Iterable<? extends Predicate<? super T>> components) { return new AndPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if each of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a false * predicate is found. It defensively copies the array passed in, so future * changes to it won't alter the behavior of this predicate. If {@code * components} is empty, the returned predicate will always evaluate to {@code * true}. */ public static <T> Predicate<T> and(Predicate<? super T>... components) { return new AndPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if both of its * components evaluate to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a false * predicate is found. */ public static <T> Predicate<T> and(Predicate<? super T> first, Predicate<? super T> second) { return new AndPredicate<T>(Predicates.<T>asList( checkNotNull(first), checkNotNull(second))); } /** * Returns a predicate that evaluates to {@code true} if any one of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a * true predicate is found. It defensively copies the iterable passed in, so * future changes to it won't alter the behavior of this predicate. If {@code * components} is empty, the returned predicate will always evaluate to {@code * false}. */ public static <T> Predicate<T> or( Iterable<? extends Predicate<? super T>> components) { return new OrPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if any one of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a * true predicate is found. It defensively copies the array passed in, so * future changes to it won't alter the behavior of this predicate. If {@code * components} is empty, the returned predicate will always evaluate to {@code * false}. */ public static <T> Predicate<T> or(Predicate<? super T>... components) { return new OrPredicate<T>(defensiveCopy(components)); } /** * Returns a predicate that evaluates to {@code true} if either of its * components evaluates to {@code true}. The components are evaluated in * order, and evaluation will be "short-circuited" as soon as a * true predicate is found. */ public static <T> Predicate<T> or( Predicate<? super T> first, Predicate<? super T> second) { return new OrPredicate<T>(Predicates.<T>asList( checkNotNull(first), checkNotNull(second))); } /** * Returns a predicate that evaluates to {@code true} if the object being * tested {@code equals()} the given target or both are null. */ public static <T> Predicate<T> equalTo(@Nullable T target) { return (target == null) ? Predicates.<T>isNull() : new IsEqualToPredicate<T>(target); } /** * Returns a predicate that evaluates to {@code true} if the object reference * being tested is a member of the given collection. It does not defensively * copy the collection passed in, so future changes to it will alter the * behavior of the predicate. * * <p>This method can technically accept any {@code Collection<?>}, but using * a typed collection helps prevent bugs. This approach doesn't block any * potential users since it is always possible to use {@code * Predicates.<Object>in()}. * * @param target the collection that may contain the function input */ public static <T> Predicate<T> in(Collection<? extends T> target) { return new InPredicate<T>(target); } /** * Returns the composition of a function and a predicate. For every {@code x}, * the generated predicate returns {@code predicate(function(x))}. * * @return the composition of the provided function and predicate */ public static <A, B> Predicate<A> compose( Predicate<B> predicate, Function<A, ? extends B> function) { return new CompositionPredicate<A, B>(predicate, function); } // End public API, begin private implementation classes. // Package private for GWT serialization. enum ObjectPredicate implements Predicate<Object> { ALWAYS_TRUE { @Override public boolean apply(@Nullable Object o) { return true; } }, ALWAYS_FALSE { @Override public boolean apply(@Nullable Object o) { return false; } }, IS_NULL { @Override public boolean apply(@Nullable Object o) { return o == null; } }, NOT_NULL { @Override public boolean apply(@Nullable Object o) { return o != null; } }; @SuppressWarnings("unchecked") // these Object predicates work for any T <T> Predicate<T> withNarrowedType() { return (Predicate<T>) this; } } /** @see Predicates#not(Predicate) */ private static class NotPredicate<T> implements Predicate<T>, Serializable { final Predicate<T> predicate; NotPredicate(Predicate<T> predicate) { this.predicate = checkNotNull(predicate); } @Override public boolean apply(T t) { return !predicate.apply(t); } @Override public int hashCode() { return ~predicate.hashCode(); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof NotPredicate) { NotPredicate<?> that = (NotPredicate<?>) obj; return predicate.equals(that.predicate); } return false; } @Override public String toString() { return "Not(" + predicate.toString() + ")"; } private static final long serialVersionUID = 0; } private static final Joiner COMMA_JOINER = Joiner.on(","); /** @see Predicates#and(Iterable) */ private static class AndPredicate<T> implements Predicate<T>, Serializable { private final List<? extends Predicate<? super T>> components; private AndPredicate(List<? extends Predicate<? super T>> components) { this.components = components; } @Override public boolean apply(T t) { for (int i = 0; i < components.size(); i++) { if (!components.get(i).apply(t)) { return false; } } return true; } @Override public int hashCode() { // 0x12472c2c is a random number to help avoid collisions with OrPredicate return components.hashCode() + 0x12472c2c; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof AndPredicate) { AndPredicate<?> that = (AndPredicate<?>) obj; return components.equals(that.components); } return false; } @Override public String toString() { return "And(" + COMMA_JOINER.join(components) + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#or(Iterable) */ private static class OrPredicate<T> implements Predicate<T>, Serializable { private final List<? extends Predicate<? super T>> components; private OrPredicate(List<? extends Predicate<? super T>> components) { this.components = components; } @Override public boolean apply(T t) { for (int i = 0; i < components.size(); i++) { if (components.get(i).apply(t)) { return true; } } return false; } @Override public int hashCode() { // 0x053c91cf is a random number to help avoid collisions with AndPredicate return components.hashCode() + 0x053c91cf; } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof OrPredicate) { OrPredicate<?> that = (OrPredicate<?>) obj; return components.equals(that.components); } return false; } @Override public String toString() { return "Or(" + COMMA_JOINER.join(components) + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#equalTo(Object) */ private static class IsEqualToPredicate<T> implements Predicate<T>, Serializable { private final T target; private IsEqualToPredicate(T target) { this.target = target; } @Override public boolean apply(T t) { return target.equals(t); } @Override public int hashCode() { return target.hashCode(); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof IsEqualToPredicate) { IsEqualToPredicate<?> that = (IsEqualToPredicate<?>) obj; return target.equals(that.target); } return false; } @Override public String toString() { return "IsEqualTo(" + target + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#in(Collection) */ private static class InPredicate<T> implements Predicate<T>, Serializable { private final Collection<?> target; private InPredicate(Collection<?> target) { this.target = checkNotNull(target); } @Override public boolean apply(T t) { try { return target.contains(t); } catch (NullPointerException e) { return false; } catch (ClassCastException e) { return false; } } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof InPredicate) { InPredicate<?> that = (InPredicate<?>) obj; return target.equals(that.target); } return false; } @Override public int hashCode() { return target.hashCode(); } @Override public String toString() { return "In(" + target + ")"; } private static final long serialVersionUID = 0; } /** @see Predicates#compose(Predicate, Function) */ private static class CompositionPredicate<A, B> implements Predicate<A>, Serializable { final Predicate<B> p; final Function<A, ? extends B> f; private CompositionPredicate(Predicate<B> p, Function<A, ? extends B> f) { this.p = checkNotNull(p); this.f = checkNotNull(f); } @Override public boolean apply(A a) { return p.apply(f.apply(a)); } @Override public boolean equals(@Nullable Object obj) { if (obj instanceof CompositionPredicate) { CompositionPredicate<?, ?> that = (CompositionPredicate<?, ?>) obj; return f.equals(that.f) && p.equals(that.p); } return false; } @Override public int hashCode() { return f.hashCode() ^ p.hashCode(); } @Override public String toString() { return p.toString() + "(" + f.toString() + ")"; } private static final long serialVersionUID = 0; } @SuppressWarnings("unchecked") private static <T> List<Predicate<? super T>> asList( Predicate<? super T> first, Predicate<? super T> second) { return Arrays.<Predicate<? super T>>asList(first, second); } private static <T> List<T> defensiveCopy(T... array) { return defensiveCopy(Arrays.asList(array)); } static <T> List<T> defensiveCopy(Iterable<T> iterable) { ArrayList<T> list = new ArrayList<T>(); for (T element : iterable) { list.add(checkNotNull(element)); } return list; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkState; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import static java.util.concurrent.TimeUnit.SECONDS; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.concurrent.TimeUnit; /** * An object that measures elapsed time in nanoseconds. It is useful to measure * elapsed time using this class instead of direct calls to {@link * System#nanoTime} for a few reasons: * * <ul> * <li>An alternate time source can be substituted, for testing or performance * reasons. * <li>As documented by {@code nanoTime}, the value returned has no absolute * meaning, and can only be interpreted as relative to another timestamp * returned by {@code nanoTime} at a different time. {@code Stopwatch} is a * more effective abstraction because it exposes only these relative values, * not the absolute ones. * </ul> * * <p>Basic usage: * <pre> * Stopwatch stopwatch = new Stopwatch().{@link #start start}(); * doSomething(); * stopwatch.{@link #stop stop}(); // optional * * long millis = stopwatch.{@link #elapsedMillis elapsedMillis}(); * * log.info("that took: " + stopwatch); // formatted string like "12.3 ms" * </pre> * * <p>Stopwatch methods are not idempotent; it is an error to start or stop a * stopwatch that is already in the desired state. * * <p>When testing code that uses this class, use the {@linkplain * #Stopwatch(Ticker) alternate constructor} to supply a fake or mock ticker. * <!-- TODO(kevinb): restore the "such as" --> This allows you to * simulate any valid behavior of the stopwatch. * * <p><b>Note:</b> This class is not thread-safe. * * @author Kevin Bourrillion * @since 10.0 */ @Beta @GwtCompatible(emulated=true) public final class Stopwatch { private final Ticker ticker; private boolean isRunning; private long elapsedNanos; private long startTick; /** * Creates (but does not start) a new stopwatch using {@link System#nanoTime} * as its time source. */ public Stopwatch() { this(Ticker.systemTicker()); } /** * Creates (but does not start) a new stopwatch, using the specified time * source. */ public Stopwatch(Ticker ticker) { this.ticker = checkNotNull(ticker); } /** * Returns {@code true} if {@link #start()} has been called on this stopwatch, * and {@link #stop()} has not been called since the last call to {@code * start()}. */ public boolean isRunning() { return isRunning; } /** * Starts the stopwatch. * * @return this {@code Stopwatch} instance * @throws IllegalStateException if the stopwatch is already running. */ public Stopwatch start() { checkState(!isRunning); isRunning = true; startTick = ticker.read(); return this; } /** * Stops the stopwatch. Future reads will return the fixed duration that had * elapsed up to this point. * * @return this {@code Stopwatch} instance * @throws IllegalStateException if the stopwatch is already stopped. */ public Stopwatch stop() { long tick = ticker.read(); checkState(isRunning); isRunning = false; elapsedNanos += tick - startTick; return this; } /** * Sets the elapsed time for this stopwatch to zero, * and places it in a stopped state. * * @return this {@code Stopwatch} instance */ public Stopwatch reset() { elapsedNanos = 0; isRunning = false; return this; } private long elapsedNanos() { return isRunning ? ticker.read() - startTick + elapsedNanos : elapsedNanos; } /** * Returns the current elapsed time shown on this stopwatch, expressed * in the desired time unit, with any fraction rounded down. * * <p>Note that the overhead of measurement can be more than a microsecond, so * it is generally not useful to specify {@link TimeUnit#NANOSECONDS} * precision here. */ public long elapsedTime(TimeUnit desiredUnit) { return desiredUnit.convert(elapsedNanos(), NANOSECONDS); } /** * Returns the current elapsed time shown on this stopwatch, expressed * in milliseconds, with any fraction rounded down. This is identical to * {@code elapsedTime(TimeUnit.MILLISECONDS}. */ public long elapsedMillis() { return elapsedTime(MILLISECONDS); } private static TimeUnit chooseUnit(long nanos) { if (SECONDS.convert(nanos, NANOSECONDS) > 0) { return SECONDS; } if (MILLISECONDS.convert(nanos, NANOSECONDS) > 0) { return MILLISECONDS; } if (MICROSECONDS.convert(nanos, NANOSECONDS) > 0) { return MICROSECONDS; } return NANOSECONDS; } private static String abbreviate(TimeUnit unit) { switch (unit) { case NANOSECONDS: return "ns"; case MICROSECONDS: return "\u03bcs"; // μs case MILLISECONDS: return "ms"; case SECONDS: return "s"; default: throw new AssertionError(); } } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import java.util.concurrent.TimeUnit; /** * @author Jesse Wilson */ class Platform { private static final char[] CHAR_BUFFER = new char[1024]; static char[] charBufferFromThreadLocal() { // ThreadLocal is not available to GWT, so we always reuse the same // instance. It is always safe to return the same instance because // javascript is single-threaded, and only used by blocks that doesn't // involve async callbacks. return CHAR_BUFFER; } static CharMatcher precomputeCharMatcher(CharMatcher matcher) { // CharMatcher.precomputed() produces CharMatchers that are maybe a little // faster (and that's debatable), but definitely more memory-hungry. We're // choosing to turn .precomputed() into a no-op in GWT, because it doesn't // seem to be a worthwhile tradeoff in a browser. return matcher; } static long systemNanoTime() { // System.nanoTime() is not available in GWT, so we get milliseconds // and convert to nanos. return TimeUnit.MILLISECONDS.toNanos(System.currentTimeMillis()); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import java.util.Collections; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import javax.annotation.CheckReturnValue; /** * An object that divides strings (or other instances of {@code CharSequence}) * into substrings, by recognizing a <i>separator</i> (a.k.a. "delimiter") * which can be expressed as a single character, literal string, regular * expression, {@code CharMatcher}, or by using a fixed substring length. This * class provides the complementary functionality to {@link Joiner}. * * <p>Here is the most basic example of {@code Splitter} usage: <pre> {@code * * Splitter.on(',').split("foo,bar")}</pre> * * This invocation returns an {@code Iterable<String>} containing {@code "foo"} * and {@code "bar"}, in that order. * * <p>By default {@code Splitter}'s behavior is very simplistic: <pre> {@code * * Splitter.on(',').split("foo,,bar, quux")}</pre> * * This returns an iterable containing {@code ["foo", "", "bar", " quux"]}. * Notice that the splitter does not assume that you want empty strings removed, * or that you wish to trim whitespace. If you want features like these, simply * ask for them: <pre> {@code * * private static final Splitter MY_SPLITTER = Splitter.on(',') * .trimResults() * .omitEmptyStrings();}</pre> * * Now {@code MY_SPLITTER.split("foo, ,bar, quux,")} returns an iterable * containing just {@code ["foo", "bar", "quux"]}. Note that the order in which * the configuration methods are called is never significant; for instance, * trimming is always applied first before checking for an empty result, * regardless of the order in which the {@link #trimResults()} and * {@link #omitEmptyStrings()} methods were invoked. * * <p><b>Warning: splitter instances are always immutable</b>; a configuration * method such as {@code omitEmptyStrings} has no effect on the instance it * is invoked on! You must store and use the new splitter instance returned by * the method. This makes splitters thread-safe, and safe to store as {@code * static final} constants (as illustrated above). <pre> {@code * * // Bad! Do not do this! * Splitter splitter = Splitter.on('/'); * splitter.trimResults(); // does nothing! * return splitter.split("wrong / wrong / wrong");}</pre> * * The separator recognized by the splitter does not have to be a single * literal character as in the examples above. See the methods {@link * #on(String)}, {@link #on(Pattern)} and {@link #on(CharMatcher)} for examples * of other ways to specify separators. * * <p><b>Note:</b> this class does not mimic any of the quirky behaviors of * similar JDK methods; for instance, it does not silently discard trailing * separators, as does {@link String#split(String)}, nor does it have a default * behavior of using five particular whitespace characters as separators, like * {@link java.util.StringTokenizer}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/StringsExplained#Splitter"> * {@code Splitter}</a>. * * @author Julien Silland * @author Jesse Wilson * @author Kevin Bourrillion * @author Louis Wasserman * @since 1.0 */ @GwtCompatible(emulated = true) public final class Splitter { private final CharMatcher trimmer; private final boolean omitEmptyStrings; private final Strategy strategy; private final int limit; private Splitter(Strategy strategy) { this(strategy, false, CharMatcher.NONE, Integer.MAX_VALUE); } private Splitter(Strategy strategy, boolean omitEmptyStrings, CharMatcher trimmer, int limit) { this.strategy = strategy; this.omitEmptyStrings = omitEmptyStrings; this.trimmer = trimmer; this.limit = limit; } /** * Returns a splitter that uses the given single-character separator. For * example, {@code Splitter.on(',').split("foo,,bar")} returns an iterable * containing {@code ["foo", "", "bar"]}. * * @param separator the character to recognize as a separator * @return a splitter, with default settings, that recognizes that separator */ public static Splitter on(char separator) { return on(CharMatcher.is(separator)); } /** * Returns a splitter that considers any single character matched by the * given {@code CharMatcher} to be a separator. For example, {@code * Splitter.on(CharMatcher.anyOf(";,")).split("foo,;bar,quux")} returns an * iterable containing {@code ["foo", "", "bar", "quux"]}. * * @param separatorMatcher a {@link CharMatcher} that determines whether a * character is a separator * @return a splitter, with default settings, that uses this matcher */ public static Splitter on(final CharMatcher separatorMatcher) { checkNotNull(separatorMatcher); return new Splitter(new Strategy() { @Override public SplittingIterator iterator( Splitter splitter, final CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override int separatorStart(int start) { return separatorMatcher.indexIn(toSplit, start); } @Override int separatorEnd(int separatorPosition) { return separatorPosition + 1; } }; } }); } /** * Returns a splitter that uses the given fixed string as a separator. For * example, {@code Splitter.on(", ").split("foo, bar, baz,qux")} returns an * iterable containing {@code ["foo", "bar", "baz,qux"]}. * * @param separator the literal, nonempty string to recognize as a separator * @return a splitter, with default settings, that recognizes that separator */ public static Splitter on(final String separator) { checkArgument(separator.length() != 0, "The separator may not be the empty string."); return new Splitter(new Strategy() { @Override public SplittingIterator iterator( Splitter splitter, CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { int delimeterLength = separator.length(); positions: for (int p = start, last = toSplit.length() - delimeterLength; p <= last; p++) { for (int i = 0; i < delimeterLength; i++) { if (toSplit.charAt(i + p) != separator.charAt(i)) { continue positions; } } return p; } return -1; } @Override public int separatorEnd(int separatorPosition) { return separatorPosition + separator.length(); } }; } }); } /** * Returns a splitter that divides strings into pieces of the given length. * For example, {@code Splitter.fixedLength(2).split("abcde")} returns an * iterable containing {@code ["ab", "cd", "e"]}. The last piece can be * smaller than {@code length} but will never be empty. * * @param length the desired length of pieces after splitting * @return a splitter, with default settings, that can split into fixed sized * pieces */ public static Splitter fixedLength(final int length) { checkArgument(length > 0, "The length may not be less than 1"); return new Splitter(new Strategy() { @Override public SplittingIterator iterator( final Splitter splitter, CharSequence toSplit) { return new SplittingIterator(splitter, toSplit) { @Override public int separatorStart(int start) { int nextChunkStart = start + length; return (nextChunkStart < toSplit.length() ? nextChunkStart : -1); } @Override public int separatorEnd(int separatorPosition) { return separatorPosition; } }; } }); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but * automatically omits empty strings from the results. For example, {@code * Splitter.on(',').omitEmptyStrings().split(",a,,,b,c,,")} returns an * iterable containing only {@code ["a", "b", "c"]}. * * <p>If either {@code trimResults} option is also specified when creating a * splitter, that splitter always trims results first before checking for * emptiness. So, for example, {@code * Splitter.on(':').omitEmptyStrings().trimResults().split(": : : ")} returns * an empty iterable. * * <p>Note that it is ordinarily not possible for {@link #split(CharSequence)} * to return an empty iterable, but when using this option, it can (if the * input sequence consists of nothing but separators). * * @return a splitter with the desired configuration */ @CheckReturnValue public Splitter omitEmptyStrings() { return new Splitter(strategy, true, trimmer, limit); } /** * Returns a splitter that behaves equivalently to {@code this} splitter but * stops splitting after it reaches the limit. * The limit defines the maximum number of items returned by the iterator. * * <p>For example, * {@code Splitter.on(',').limit(3).split("a,b,c,d")} returns an iterable * containing {@code ["a", "b", "c,d"]}. When omitting empty strings, the * omitted strings do no count. Hence, * {@code Splitter.on(',').limit(3).omitEmptyStrings().split("a,,,b,,,c,d")} * returns an iterable containing {@code ["a", "b", "c,d"}. * When trim is requested, all entries, including the last are trimmed. Hence * {@code Splitter.on(',').limit(3).trimResults().split(" a , b , c , d ")} * results in @{code ["a", "b", "c , d"]}. * * @param limit the maximum number of items returns * @return a splitter with the desired configuration * @since 9.0 */ @CheckReturnValue public Splitter limit(int limit) { checkArgument(limit > 0, "must be greater than zero: %s", limit); return new Splitter(strategy, omitEmptyStrings, trimmer, limit); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but * automatically removes leading and trailing {@linkplain * CharMatcher#WHITESPACE whitespace} from each returned substring; equivalent * to {@code trimResults(CharMatcher.WHITESPACE)}. For example, {@code * Splitter.on(',').trimResults().split(" a, b ,c ")} returns an iterable * containing {@code ["a", "b", "c"]}. * * @return a splitter with the desired configuration */ @CheckReturnValue public Splitter trimResults() { return trimResults(CharMatcher.WHITESPACE); } /** * Returns a splitter that behaves equivalently to {@code this} splitter, but * removes all leading or trailing characters matching the given {@code * CharMatcher} from each returned substring. For example, {@code * Splitter.on(',').trimResults(CharMatcher.is('_')).split("_a ,_b_ ,c__")} * returns an iterable containing {@code ["a ", "b_ ", "c"]}. * * @param trimmer a {@link CharMatcher} that determines whether a character * should be removed from the beginning/end of a subsequence * @return a splitter with the desired configuration */ // TODO(kevinb): throw if a trimmer was already specified! @CheckReturnValue public Splitter trimResults(CharMatcher trimmer) { checkNotNull(trimmer); return new Splitter(strategy, omitEmptyStrings, trimmer, limit); } /** * Splits {@code sequence} into string components and makes them available * through an {@link Iterator}, which may be lazily evaluated. * * @param sequence the sequence of characters to split * @return an iteration over the segments split from the parameter. */ public Iterable<String> split(final CharSequence sequence) { checkNotNull(sequence); return new Iterable<String>() { @Override public Iterator<String> iterator() { return spliterator(sequence); } }; } private Iterator<String> spliterator(CharSequence sequence) { return strategy.iterator(this, sequence); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, * and splits entries into keys and values using the specified separator. * * @since 10.0 */ @CheckReturnValue @Beta public MapSplitter withKeyValueSeparator(String separator) { return withKeyValueSeparator(on(separator)); } /** * Returns a {@code MapSplitter} which splits entries based on this splitter, * and splits entries into keys and values using the specified key-value * splitter. * * @since 10.0 */ @CheckReturnValue @Beta public MapSplitter withKeyValueSeparator(Splitter keyValueSplitter) { return new MapSplitter(this, keyValueSplitter); } /** * An object that splits strings into maps as {@code Splitter} splits * iterables and lists. Like {@code Splitter}, it is thread-safe and * immutable. * * @since 10.0 */ @Beta public static final class MapSplitter { private static final String INVALID_ENTRY_MESSAGE = "Chunk [%s] is not a valid entry"; private final Splitter outerSplitter; private final Splitter entrySplitter; private MapSplitter(Splitter outerSplitter, Splitter entrySplitter) { this.outerSplitter = outerSplitter; // only "this" is passed this.entrySplitter = checkNotNull(entrySplitter); } /** * Splits {@code sequence} into substrings, splits each substring into * an entry, and returns an unmodifiable map with each of the entries. For * example, <code> * Splitter.on(';').trimResults().withKeyValueSeparator("=>") * .split("a=>b ; c=>b") * </code> will return a mapping from {@code "a"} to {@code "b"} and * {@code "c"} to {@code b}. * * <p>The returned map preserves the order of the entries from * {@code sequence}. * * @throws IllegalArgumentException if the specified sequence does not split * into valid map entries, or if there are duplicate keys */ public Map<String, String> split(CharSequence sequence) { Map<String, String> map = new LinkedHashMap<String, String>(); for (String entry : outerSplitter.split(sequence)) { Iterator<String> entryFields = entrySplitter.spliterator(entry); checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); String key = entryFields.next(); checkArgument(!map.containsKey(key), "Duplicate key [%s] found.", key); checkArgument(entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); String value = entryFields.next(); map.put(key, value); checkArgument(!entryFields.hasNext(), INVALID_ENTRY_MESSAGE, entry); } return Collections.unmodifiableMap(map); } } private interface Strategy { Iterator<String> iterator(Splitter splitter, CharSequence toSplit); } private abstract static class SplittingIterator extends AbstractIterator<String> { final CharSequence toSplit; final CharMatcher trimmer; final boolean omitEmptyStrings; /** * Returns the first index in {@code toSplit} at or after {@code start} * that contains the separator. */ abstract int separatorStart(int start); /** * Returns the first index in {@code toSplit} after {@code * separatorPosition} that does not contain a separator. This method is only * invoked after a call to {@code separatorStart}. */ abstract int separatorEnd(int separatorPosition); int offset = 0; int limit; protected SplittingIterator(Splitter splitter, CharSequence toSplit) { this.trimmer = splitter.trimmer; this.omitEmptyStrings = splitter.omitEmptyStrings; this.limit = splitter.limit; this.toSplit = toSplit; } @Override protected String computeNext() { while (offset != -1) { int start = offset; int end; int separatorPosition = separatorStart(offset); if (separatorPosition == -1) { end = toSplit.length(); offset = -1; } else { end = separatorPosition; offset = separatorEnd(separatorPosition); } while (start < end && trimmer.matches(toSplit.charAt(start))) { start++; } while (end > start && trimmer.matches(toSplit.charAt(end - 1))) { end--; } if (omitEmptyStrings && start == end) { continue; } if (limit == 1) { // The limit has been reached, return the rest of the string as the // final item. This is tested after empty string removal so that // empty strings do not count towards the limit. end = toSplit.length(); offset = -1; // Since we may have changed the end, we need to trim it again. while (end > start && trimmer.matches(toSplit.charAt(end - 1))) { end--; } } else { limit--; } return toSplit.subSequence(start, end).toString(); } return endOfData(); } } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code int} primitives, that are not * already found in either {@link Integer} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Ints { private Ints() {} /** * The number of bytes required to represent a primitive {@code int} * value. */ public static final int BYTES = Integer.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as an {@code int}. * * @since 10.0 */ public static final int MAX_POWER_OF_TWO = 1 << (Integer.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Integer) value).hashCode()}. * * @param value a primitive {@code int} value * @return a hash code for the value */ public static int hashCode(int value) { return value; } /** * Returns the {@code int} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code int} type * @return the {@code int} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link * Integer#MAX_VALUE} or less than {@link Integer#MIN_VALUE} */ public static int checkedCast(long value) { int result = (int) value; 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)}. * * @param a the first {@code int} to compare * @param b the second {@code int} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(int a, int b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(int[] array, int target) { for (int value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(int[] array, int target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( int[] array, int target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(int[] array, int[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code int} values, possibly empty * @param target a primitive {@code int} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(int[] array, int target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( int[] array, int target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code int} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static int min(int... array) { checkArgument(array.length > 0); int min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code int} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static int max(int... array) { checkArgument(array.length > 0); int max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new int[] {a, b}, new int[] {}, new * int[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code int} arrays * @return a single array containing all the values from the source arrays, in * order */ public static int[] concat(int[]... arrays) { int length = 0; for (int[] array : arrays) { length += array.length; } int[] result = new int[length]; int pos = 0; for (int[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static int[] ensureCapacity( int[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static int[] copyOf(int[] original, int length) { int[] copy = new int[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code int} values separated * by {@code separator}. For example, {@code join("-", 1, 2, 3)} returns * the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code int} values, possibly empty */ public static String join(String separator, int... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 5); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code int} arrays * lexicographically. That is, it compares, using {@link * #compare(int, int)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, {@code [] < [1] < [1, 2] < [2]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(int[], int[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<int[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<int[]> { INSTANCE; @Override public int compare(int[] left, int[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Ints.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Copies a collection of {@code Integer} instances into a new array of * primitive {@code int} 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 Integer} 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 int[] toArray(Collection<Integer> 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] = (Integer) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Integer} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Integer> asList(int... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new IntArrayAsList(backingArray); } @GwtCompatible private static class IntArrayAsList extends AbstractList<Integer> implements RandomAccess, Serializable { final int[] array; final int start; final int end; IntArrayAsList(int[] array) { this(array, 0, array.length); } IntArrayAsList(int[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Integer get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Integer) && Ints.indexOf(array, (Integer) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Integer) { int i = Ints.indexOf(array, (Integer) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Integer) { int i = Ints.lastIndexOf(array, (Integer) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Integer set(int index, Integer element) { checkElementIndex(index, size()); int oldValue = array[start + index]; array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) return oldValue; } @Override public List<Integer> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new IntArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof IntArrayAsList) { IntArrayAsList that = (IntArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Ints.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 5); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } int[] toIntArray() { // Arrays.copyOfRange() requires Java 6 int size = size(); int[] result = new int[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code char} primitives, that are not * already found in either {@link Character} or {@link Arrays}. * * <p>All the operations in this class treat {@code char} values strictly * numerically; they are neither Unicode-aware nor locale-dependent. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Chars { private Chars() {} /** * The number of bytes required to represent a primitive {@code char} * value. */ public static final int BYTES = Character.SIZE / Byte.SIZE; /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Character) value).hashCode()}. * * @param value a primitive {@code char} value * @return a hash code for the value */ public static int hashCode(char value) { return value; } /** * Returns the {@code char} value that is equal to {@code value}, if possible. * * @param value any value in the range of the {@code char} type * @return the {@code char} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link * Character#MAX_VALUE} or less than {@link Character#MIN_VALUE} */ public static char checkedCast(long value) { char result = (char) value; 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)}. * * @param a the first {@code char} to compare * @param b the second {@code char} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(char a, char b) { return a - b; // safe due to restricted range } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(char[] array, char target) { for (char value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(char[] array, char target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( char[] array, char target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(char[] array, char[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code char} values, possibly empty * @param target a primitive {@code char} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(char[] array, char target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( char[] array, char target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code char} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static char min(char... array) { checkArgument(array.length > 0); char min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code char} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static char max(char... array) { checkArgument(array.length > 0); char max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new char[] {a, b}, new char[] {}, new * char[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code char} arrays * @return a single array containing all the values from the source arrays, in * order */ public static char[] concat(char[]... arrays) { int length = 0; for (char[] array : arrays) { length += array.length; } char[] result = new char[length]; int pos = 0; for (char[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static char[] ensureCapacity( char[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static char[] copyOf(char[] original, int length) { char[] copy = new char[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code char} values separated * by {@code separator}. For example, {@code join("-", '1', '2', '3')} returns * the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code char} values, possibly empty */ public static String join(String separator, char... array) { checkNotNull(separator); int len = array.length; if (len == 0) { return ""; } StringBuilder builder = new StringBuilder(len + separator.length() * (len - 1)); builder.append(array[0]); for (int i = 1; i < len; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code char} arrays * lexicographically. That is, it compares, using {@link * #compare(char, char)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, * {@code [] < ['a'] < ['a', 'b'] < ['b']}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(char[], char[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<char[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<char[]> { INSTANCE; @Override public int compare(char[] left, char[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Chars.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Copies a collection of {@code Character} instances into a new array of * primitive {@code char} values. * * <p>Elements are copied from the argument collection as if by {@code * collection.toArray()}. Calling this method is as thread-safe as calling * that method. * * @param collection a collection of {@code Character} objects * @return an array containing the same values as {@code collection}, in the * same order, converted to primitives * @throws NullPointerException if {@code collection} or any of its elements * is null */ public static char[] toArray(Collection<Character> collection) { if (collection instanceof CharArrayAsList) { return ((CharArrayAsList) collection).toCharArray(); } Object[] boxedArray = collection.toArray(); int len = boxedArray.length; char[] array = new char[len]; for (int i = 0; i < len; i++) { // checkNotNull for GWT (do not optimize) array[i] = (Character) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Character} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Character> asList(char... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new CharArrayAsList(backingArray); } @GwtCompatible private static class CharArrayAsList extends AbstractList<Character> implements RandomAccess, Serializable { final char[] array; final int start; final int end; CharArrayAsList(char[] array) { this(array, 0, array.length); } CharArrayAsList(char[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Character get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Character) && Chars.indexOf(array, (Character) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Character) { int i = Chars.indexOf(array, (Character) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Character) { int i = Chars.lastIndexOf(array, (Character) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Character set(int index, Character element) { checkElementIndex(index, size()); char oldValue = array[start + index]; array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) return oldValue; } @Override public List<Character> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new CharArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof CharArrayAsList) { CharArrayAsList that = (CharArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Chars.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 3); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } char[] toCharArray() { // Arrays.copyOfRange() requires Java 6 int size = size(); char[] result = new char[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code long} primitives, that are not * already found in either {@link Long} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Longs { private Longs() {} /** * The number of bytes required to represent a primitive {@code long} * value. */ public static final int BYTES = Long.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as a {@code long}. * * @since 10.0 */ public static final long MAX_POWER_OF_TWO = 1L << (Long.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Long) value).hashCode()}. * * <p>This method always return the value specified by {@link * Long#hashCode()} in java, which might be different from * {@code ((Long) value).hashCode()} in GWT because {@link Long#hashCode()} * in GWT does not obey the JRE contract. * * @param value a primitive {@code long} value * @return a hash code for the value */ public static int hashCode(long value) { return (int) (value ^ (value >>> 32)); } /** * Compares the two specified {@code long} values. The sign of the value * returned is the same as that of {@code ((Long) a).compareTo(b)}. * * @param a the first {@code long} to compare * @param b the second {@code long} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(long a, long b) { return (a < b) ? -1 : ((a > b) ? 1 : 0); } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(long[] array, long target) { for (long value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(long[] array, long target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( long[] array, long target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(long[] array, long[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code long} values, possibly empty * @param target a primitive {@code long} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(long[] array, long target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( long[] array, long target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code long} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static long min(long... array) { checkArgument(array.length > 0); long min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code long} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static long max(long... array) { checkArgument(array.length > 0); long max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new long[] {a, b}, new long[] {}, new * long[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code long} arrays * @return a single array containing all the values from the source arrays, in * order */ public static long[] concat(long[]... arrays) { int length = 0; for (long[] array : arrays) { length += array.length; } long[] result = new long[length]; int pos = 0; for (long[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static long[] ensureCapacity( long[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static long[] copyOf(long[] original, int length) { long[] copy = new long[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code long} values separated * by {@code separator}. For example, {@code join("-", 1L, 2L, 3L)} returns * the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code long} values, possibly empty */ public static String join(String separator, long... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 10); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code long} arrays * lexicographically. That is, it compares, using {@link * #compare(long, long)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, * {@code [] < [1L] < [1L, 2L] < [2L]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(long[], long[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<long[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<long[]> { INSTANCE; @Override public int compare(long[] left, long[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Longs.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Copies a collection of {@code Long} instances into a new array of * primitive {@code long} 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 Long} 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 long[] toArray(Collection<Long> 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] = (Long) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Long} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Long> asList(long... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new LongArrayAsList(backingArray); } @GwtCompatible private static class LongArrayAsList extends AbstractList<Long> implements RandomAccess, Serializable { final long[] array; final int start; final int end; LongArrayAsList(long[] array) { this(array, 0, array.length); } LongArrayAsList(long[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Long get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Long) && Longs.indexOf(array, (Long) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Long) { int i = Longs.indexOf(array, (Long) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Long) { int i = Longs.lastIndexOf(array, (Long) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Long set(int index, Long element) { checkElementIndex(index, size()); long oldValue = array[start + index]; array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) return oldValue; } @Override public List<Long> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new LongArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof LongArrayAsList) { LongArrayAsList that = (LongArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Longs.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 10); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } long[] toLongArray() { // Arrays.copyOfRange() requires Java 6 int size = size(); long[] result = new long[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkElementIndex; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.base.Preconditions.checkPositionIndexes; import com.google.common.annotations.GwtCompatible; import java.io.Serializable; import java.util.AbstractList; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.RandomAccess; /** * Static utility methods pertaining to {@code short} primitives, that are not * already found in either {@link Short} or {@link Arrays}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/PrimitivesExplained"> * primitive utilities</a>. * * @author Kevin Bourrillion * @since 1.0 */ @GwtCompatible(emulated = true) public final class Shorts { private Shorts() {} /** * The number of bytes required to represent a primitive {@code short} * value. */ public static final int BYTES = Short.SIZE / Byte.SIZE; /** * The largest power of two that can be represented as a {@code short}. * * @since 10.0 */ public static final short MAX_POWER_OF_TWO = 1 << (Short.SIZE - 2); /** * Returns a hash code for {@code value}; equal to the result of invoking * {@code ((Short) value).hashCode()}. * * @param value a primitive {@code short} value * @return a hash code for the value */ public static int hashCode(short value) { return value; } /** * Returns the {@code short} value that is equal to {@code value}, if * possible. * * @param value any value in the range of the {@code short} type * @return the {@code short} value that equals {@code value} * @throws IllegalArgumentException if {@code value} is greater than {@link * Short#MAX_VALUE} or less than {@link Short#MIN_VALUE} */ public static short checkedCast(long value) { short result = (short) value; 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)}. * * @param a the first {@code short} to compare * @param b the second {@code short} to compare * @return a negative value if {@code a} is less than {@code b}; a positive * value if {@code a} is greater than {@code b}; or zero if they are equal */ public static int compare(short a, short b) { return a - b; // safe due to restricted range } /** * Returns {@code true} if {@code target} is present as an element anywhere in * {@code array}. * * @param array an array of {@code short} values, possibly empty * @param target a primitive {@code short} value * @return {@code true} if {@code array[i] == target} for some value of {@code * i} */ public static boolean contains(short[] array, short target) { for (short value : array) { if (value == target) { return true; } } return false; } /** * Returns the index of the first appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code short} values, possibly empty * @param target a primitive {@code short} value * @return the least index {@code i} for which {@code array[i] == target}, or * {@code -1} if no such index exists. */ public static int indexOf(short[] array, short target) { return indexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int indexOf( short[] array, short target, int start, int end) { for (int i = start; i < end; i++) { if (array[i] == target) { return i; } } return -1; } /** * Returns the start position of the first occurrence of the specified {@code * target} within {@code array}, or {@code -1} if there is no such occurrence. * * <p>More formally, returns the lowest index {@code i} such that {@code * java.util.Arrays.copyOfRange(array, i, i + target.length)} contains exactly * the same elements as {@code target}. * * @param array the array to search for the sequence {@code target} * @param target the array to search for as a sub-sequence of {@code array} */ public static int indexOf(short[] array, short[] target) { checkNotNull(array, "array"); checkNotNull(target, "target"); if (target.length == 0) { return 0; } outer: for (int i = 0; i < array.length - target.length + 1; i++) { for (int j = 0; j < target.length; j++) { if (array[i + j] != target[j]) { continue outer; } } return i; } return -1; } /** * Returns the index of the last appearance of the value {@code target} in * {@code array}. * * @param array an array of {@code short} values, possibly empty * @param target a primitive {@code short} value * @return the greatest index {@code i} for which {@code array[i] == target}, * or {@code -1} if no such index exists. */ public static int lastIndexOf(short[] array, short target) { return lastIndexOf(array, target, 0, array.length); } // TODO(kevinb): consider making this public private static int lastIndexOf( short[] array, short target, int start, int end) { for (int i = end - 1; i >= start; i--) { if (array[i] == target) { return i; } } return -1; } /** * Returns the least value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code short} values * @return the value present in {@code array} that is less than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static short min(short... array) { checkArgument(array.length > 0); short min = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] < min) { min = array[i]; } } return min; } /** * Returns the greatest value present in {@code array}. * * @param array a <i>nonempty</i> array of {@code short} values * @return the value present in {@code array} that is greater than or equal to * every other value in the array * @throws IllegalArgumentException if {@code array} is empty */ public static short max(short... array) { checkArgument(array.length > 0); short max = array[0]; for (int i = 1; i < array.length; i++) { if (array[i] > max) { max = array[i]; } } return max; } /** * Returns the values from each provided array combined into a single array. * For example, {@code concat(new short[] {a, b}, new short[] {}, new * short[] {c}} returns the array {@code {a, b, c}}. * * @param arrays zero or more {@code short} arrays * @return a single array containing all the values from the source arrays, in * order */ public static short[] concat(short[]... arrays) { int length = 0; for (short[] array : arrays) { length += array.length; } short[] result = new short[length]; int pos = 0; for (short[] array : arrays) { System.arraycopy(array, 0, result, pos, array.length); pos += array.length; } return result; } /** * Returns an array containing the same values as {@code array}, but * guaranteed to be of a specified minimum length. If {@code array} already * has a length of at least {@code minLength}, it is returned directly. * Otherwise, a new array of size {@code minLength + padding} is returned, * containing the values of {@code array}, and zeroes in the remaining places. * * @param array the source array * @param minLength the minimum length the returned array must guarantee * @param padding an extra amount to "grow" the array by if growth is * necessary * @throws IllegalArgumentException if {@code minLength} or {@code padding} is * negative * @return an array containing the values of {@code array}, with guaranteed * minimum length {@code minLength} */ public static short[] ensureCapacity( short[] array, int minLength, int padding) { checkArgument(minLength >= 0, "Invalid minLength: %s", minLength); checkArgument(padding >= 0, "Invalid padding: %s", padding); return (array.length < minLength) ? copyOf(array, minLength + padding) : array; } // Arrays.copyOf() requires Java 6 private static short[] copyOf(short[] original, int length) { short[] copy = new short[length]; System.arraycopy(original, 0, copy, 0, Math.min(original.length, length)); return copy; } /** * Returns a string containing the supplied {@code short} values separated * by {@code separator}. For example, {@code join("-", (short) 1, (short) 2, * (short) 3)} returns the string {@code "1-2-3"}. * * @param separator the text that should appear between consecutive values in * the resulting string (but not at the start or end) * @param array an array of {@code short} values, possibly empty */ public static String join(String separator, short... array) { checkNotNull(separator); if (array.length == 0) { return ""; } // For pre-sizing a builder, just get the right order of magnitude StringBuilder builder = new StringBuilder(array.length * 6); builder.append(array[0]); for (int i = 1; i < array.length; i++) { builder.append(separator).append(array[i]); } return builder.toString(); } /** * Returns a comparator that compares two {@code short} arrays * lexicographically. That is, it compares, using {@link * #compare(short, short)}), the first pair of values that follow any * common prefix, or when one array is a prefix of the other, treats the * shorter array as the lesser. For example, {@code [] < [(short) 1] < * [(short) 1, (short) 2] < [(short) 2]}. * * <p>The returned comparator is inconsistent with {@link * Object#equals(Object)} (since arrays support only identity equality), but * it is consistent with {@link Arrays#equals(short[], short[])}. * * @see <a href="http://en.wikipedia.org/wiki/Lexicographical_order"> * Lexicographical order article at Wikipedia</a> * @since 2.0 */ public static Comparator<short[]> lexicographicalComparator() { return LexicographicalComparator.INSTANCE; } private enum LexicographicalComparator implements Comparator<short[]> { INSTANCE; @Override public int compare(short[] left, short[] right) { int minLength = Math.min(left.length, right.length); for (int i = 0; i < minLength; i++) { int result = Shorts.compare(left[i], right[i]); if (result != 0) { return result; } } return left.length - right.length; } } /** * Copies a collection of {@code Short} instances into a new array of * primitive {@code short} 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 Short} 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 short[] toArray(Collection<Short> 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] = (Short) checkNotNull(boxedArray[i]); } return array; } /** * Returns a fixed-size list backed by the specified array, similar to {@link * Arrays#asList(Object[])}. The list supports {@link List#set(int, Object)}, * but any attempt to set a value to {@code null} will result in a {@link * NullPointerException}. * * <p>The returned list maintains the values, but not the identities, of * {@code Short} objects written to or read from it. For example, whether * {@code list.get(0) == list.get(0)} is true for the returned list is * unspecified. * * @param backingArray the array to back the list * @return a list view of the array */ public static List<Short> asList(short... backingArray) { if (backingArray.length == 0) { return Collections.emptyList(); } return new ShortArrayAsList(backingArray); } @GwtCompatible private static class ShortArrayAsList extends AbstractList<Short> implements RandomAccess, Serializable { final short[] array; final int start; final int end; ShortArrayAsList(short[] array) { this(array, 0, array.length); } ShortArrayAsList(short[] array, int start, int end) { this.array = array; this.start = start; this.end = end; } @Override public int size() { return end - start; } @Override public boolean isEmpty() { return false; } @Override public Short get(int index) { checkElementIndex(index, size()); return array[start + index]; } @Override public boolean contains(Object target) { // Overridden to prevent a ton of boxing return (target instanceof Short) && Shorts.indexOf(array, (Short) target, start, end) != -1; } @Override public int indexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Short) { int i = Shorts.indexOf(array, (Short) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public int lastIndexOf(Object target) { // Overridden to prevent a ton of boxing if (target instanceof Short) { int i = Shorts.lastIndexOf(array, (Short) target, start, end); if (i >= 0) { return i - start; } } return -1; } @Override public Short set(int index, Short element) { checkElementIndex(index, size()); short oldValue = array[start + index]; array[start + index] = checkNotNull(element); // checkNotNull for GWT (do not optimize) return oldValue; } @Override public List<Short> subList(int fromIndex, int toIndex) { int size = size(); checkPositionIndexes(fromIndex, toIndex, size); if (fromIndex == toIndex) { return Collections.emptyList(); } return new ShortArrayAsList(array, start + fromIndex, start + toIndex); } @Override public boolean equals(Object object) { if (object == this) { return true; } if (object instanceof ShortArrayAsList) { ShortArrayAsList that = (ShortArrayAsList) object; int size = size(); if (that.size() != size) { return false; } for (int i = 0; i < size; i++) { if (array[start + i] != that.array[that.start + i]) { return false; } } return true; } return super.equals(object); } @Override public int hashCode() { int result = 1; for (int i = start; i < end; i++) { result = 31 * result + Shorts.hashCode(array[i]); } return result; } @Override public String toString() { StringBuilder builder = new StringBuilder(size() * 6); builder.append('[').append(array[start]); for (int i = start + 1; i < end; i++) { builder.append(", ").append(array[i]); } return builder.append(']').toString(); } short[] toShortArray() { // Arrays.copyOfRange() requires Java 6 int size = size(); short[] result = new short[size]; System.arraycopy(array, start, result, 0, size); return result; } private static final long serialVersionUID = 0; } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.math; import static com.google.common.math.MathPreconditions.checkNoOverflow; import static com.google.common.math.MathPreconditions.checkNonNegative; import com.google.common.annotations.Beta; import com.google.common.annotations.GwtCompatible; import com.google.common.annotations.VisibleForTesting; /** * 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 */ @Beta @GwtCompatible(emulated = true) public final class IntMath { // NOTE: Whenever both tests are cheap and functional, it's faster to use &, | instead of &&, || /** * Returns {@code true} if {@code x} represents a power of two. * * <p>This differs from {@code Integer.bitCount(x) == 1}, because * {@code Integer.bitCount(Integer.MIN_VALUE) == 1}, but {@link Integer#MIN_VALUE} is not a power * of two. */ public static boolean isPowerOfTwo(int x) { return x > 0 & (x & (x - 1)) == 0; } /** The biggest half power of two that can fit in an unsigned int. */ @VisibleForTesting static final int MAX_POWER_OF_SQRT2_UNSIGNED = 0xB504F333; private static int log10Floor(int x) { for (int i = 1; i < POWERS_OF_10.length; i++) { if (x < POWERS_OF_10[i]) { return i - 1; } } return POWERS_OF_10.length - 1; } @VisibleForTesting static final int[] POWERS_OF_10 = {1, 10, 100, 1000, 10000, 100000, 1000000, 10000000, 100000000, 1000000000}; // HALF_POWERS_OF_10[i] = largest int less than 10^(i + 0.5) @VisibleForTesting static final int[] HALF_POWERS_OF_10 = {3, 31, 316, 3162, 31622, 316227, 3162277, 31622776, 316227766, Integer.MAX_VALUE}; 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 {@code x mod m}. This differs from {@code x % m} in that it always returns a * non-negative result. * * <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} */ 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); // The simple Euclidean algorithm is the fastest for ints, and is easily the most readable. while (b != 0) { int t = b; b = a % b; a = t; } return a; } /** * Returns the sum of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a + b} overflows in signed {@code int} arithmetic */ public static int checkedAdd(int a, int b) { long result = (long) a + b; checkNoOverflow(result == (int) result); return (int) result; } /** * Returns the difference of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a - b} overflows in signed {@code int} arithmetic */ public static int checkedSubtract(int a, int b) { long result = (long) a - b; checkNoOverflow(result == (int) result); return (int) result; } /** * Returns the product of {@code a} and {@code b}, provided it does not overflow. * * @throws ArithmeticException if {@code a * b} overflows in signed {@code int} arithmetic */ public static int checkedMultiply(int a, int b) { long result = (long) a * b; checkNoOverflow(result == (int) result); return (int) result; } @VisibleForTesting static final int FLOOR_SQRT_MAX_INT = 46340; 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}; // binomial(BIGGEST_BINOMIALS[k], k) fits in an int, but not binomial(BIGGEST_BINOMIALS[k]+1,k). @VisibleForTesting static int[] BIGGEST_BINOMIALS = { Integer.MAX_VALUE, Integer.MAX_VALUE, 65536, 2345, 477, 193, 110, 75, 58, 49, 43, 39, 37, 35, 34, 34, 33 }; private IntMath() {} }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.escape; /** * @author Jesse Wilson */ class Platform { private static final char[] CHAR_BUFFER = new char[1024]; static char[] charBufferFromThreadLocal() { // ThreadLocal is not available to GWT, so we always reuse the same // instance. It is always safe to return the same instance because // javascript is single-threaded, and only used by blocks that doesn't // involve async callbacks. return CHAR_BUFFER; } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.common.annotations.GwtCompatible; import com.google.gwt.core.client.GwtScriptOnly; import com.google.gwt.lang.Array; /** * Version of {@link GwtPlatform} used in web-mode. It includes methods in * {@link Platform} that requires different implementions in web mode and * hosted mode. It is factored out from {@link Platform} because <code> * {@literal @}GwtScriptOnly</code> only supports public classes and methods. * * @author Hayward Chan */ @GwtCompatible @GwtScriptOnly public final class GwtPlatform { private GwtPlatform() {} public static <T> T[] clone(T[] array) { return (T[]) Array.clone(array); } public static <T> T[] newArray(T[] reference, int length) { return Array.createFrom(reference, length); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import java.util.Set; /** * GWT emulation of {@link ImmutableEnumSet}. The type parameter is not bounded * by {@code Enum<E>} to avoid code-size bloat. * * @author Hayward Chan */ final class ImmutableEnumSet<E> extends ImmutableSet<E> { public ImmutableEnumSet(Set<E> delegate) { super(delegate); } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * GWT emulation of {@link EmptyImmutableSet}. * * @author Hayward Chan */ final class EmptyImmutableSet extends ImmutableSet<Object> { static final EmptyImmutableSet INSTANCE = new EmptyImmutableSet(); }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import java.io.Serializable; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import javax.annotation.Nullable; import static com.google.common.base.Preconditions.checkNotNull; /** * GWT emulated version of {@link ImmutableCollection}. * * @author Jesse Wilson */ @SuppressWarnings("serial") // we're overriding default serialization public abstract class ImmutableCollection<E> implements Collection<E>, Serializable { static final ImmutableCollection<Object> EMPTY_IMMUTABLE_COLLECTION = new ForwardingImmutableCollection<Object>(Collections.emptyList()); ImmutableCollection() {} public abstract UnmodifiableIterator<E> iterator(); public Object[] toArray() { Object[] newArray = new Object[size()]; return toArray(newArray); } public <T> T[] toArray(T[] other) { int size = size(); if (other.length < size) { other = ObjectArrays.newArray(other, size); } else if (other.length > size) { other[size] = null; } // Writes will produce ArrayStoreException when the toArray() doc requires. Object[] otherAsObjectArray = other; int index = 0; for (E element : this) { otherAsObjectArray[index++] = element; } return other; } public boolean contains(@Nullable Object object) { if (object == null) { return false; } for (E element : this) { if (element.equals(object)) { return true; } } return false; } public boolean containsAll(Collection<?> targets) { for (Object target : targets) { if (!contains(target)) { return false; } } return true; } public boolean isEmpty() { return size() == 0; } public final boolean add(E e) { throw new UnsupportedOperationException(); } public final boolean remove(Object object) { throw new UnsupportedOperationException(); } public final boolean addAll(Collection<? extends E> newElements) { throw new UnsupportedOperationException(); } public final boolean removeAll(Collection<?> oldElements) { throw new UnsupportedOperationException(); } public final boolean retainAll(Collection<?> elementsToKeep) { throw new UnsupportedOperationException(); } public final void clear() { throw new UnsupportedOperationException(); } private transient ImmutableList<E> asList; public ImmutableList<E> asList() { ImmutableList<E> list = asList; return (list == null) ? (asList = createAsList()) : list; } ImmutableList<E> createAsList() { switch (size()) { case 0: return ImmutableList.of(); case 1: return ImmutableList.of(iterator().next()); default: @SuppressWarnings("unchecked") E[] castedArray = (E[]) toArray(); return new ImmutableAsList<E>(Arrays.asList(castedArray)); } } static <E> ImmutableCollection<E> unsafeDelegate(Collection<E> delegate) { return new ForwardingImmutableCollection<E>(delegate); } boolean isPartialView(){ return false; } abstract static class Builder<E> { public abstract Builder<E> add(E element); public Builder<E> add(E... elements) { checkNotNull(elements); // for GWT for (E element : elements) { add(checkNotNull(element)); } return this; } public Builder<E> addAll(Iterable<? extends E> elements) { checkNotNull(elements); // for GWT for (E element : elements) { add(checkNotNull(element)); } return this; } public Builder<E> addAll(Iterator<? extends E> elements) { checkNotNull(elements); // for GWT while (elements.hasNext()) { add(checkNotNull(elements.next())); } return this; } public abstract ImmutableCollection<E> build(); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; /** * GWT emulation of {@link RegularImmutableBiMap}. * * @author Jared Levy * @author Hayward Chan */ @SuppressWarnings("serial") class RegularImmutableBiMap<K, V> extends ImmutableBiMap<K, V> { // This reference is used both by the GWT compiler to infer the elements // of the lists that needs to be serialized. private ImmutableBiMap<V, K> inverse; RegularImmutableBiMap(ImmutableMap<K, V> delegate) { super(delegate); ImmutableMap.Builder<V, K> builder = ImmutableMap.builder(); for (Entry<K, V> entry : delegate.entrySet()) { builder.put(entry.getValue(), entry.getKey()); } ImmutableMap<V, K> backwardMap = builder.build(); this.inverse = new RegularImmutableBiMap<V, K>(backwardMap, this); } RegularImmutableBiMap(ImmutableMap<K, V> delegate, ImmutableBiMap<V, K> inverse) { super(delegate); this.inverse = inverse; } @Override public ImmutableBiMap<V, K> inverse() { return inverse; } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import java.util.Collection; import javax.annotation.Nullable; /** * A GWT-only class only used by GWT emulations. It is used to consolidate the * definitions of method delegation to save code size. * * @author Hayward Chan */ // TODO: Make this class GWT serializable. class ForwardingImmutableCollection<E> extends ImmutableCollection<E> { transient final Collection<E> delegate; ForwardingImmutableCollection(Collection<E> delegate) { this.delegate = delegate; } @Override public UnmodifiableIterator<E> iterator() { return Iterators.unmodifiableIterator(delegate.iterator()); } @Override public boolean contains(@Nullable Object object) { return object != null && delegate.contains(object); } @Override public boolean containsAll(Collection<?> targets) { return delegate.containsAll(targets); } public int size() { return delegate.size(); } @Override public boolean isEmpty() { return delegate.isEmpty(); } @Override public Object[] toArray() { return delegate.toArray(); } @Override public <T> T[] toArray(T[] other) { return delegate.toArray(other); } @Override public String toString() { return delegate.toString(); } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import com.google.common.annotations.GwtCompatible; import java.util.EnumMap; import java.util.Iterator; /** * Multiset implementation backed by an {@link EnumMap}. * * <p>See the Guava User Guide article on <a href= * "http://code.google.com/p/guava-libraries/wiki/NewCollectionTypesExplained#Multiset"> * {@code Multiset}</a>. * * @author Jared Levy * @since 2.0 (imported from Google Collections Library) */ @GwtCompatible(emulated = true) public final class EnumMultiset<E extends Enum<E>> extends AbstractMapBasedMultiset<E> { /** Creates an empty {@code EnumMultiset}. */ public static <E extends Enum<E>> EnumMultiset<E> create(Class<E> type) { return new EnumMultiset<E>(type); } /** * Creates a new {@code EnumMultiset} containing the specified elements. * * <p>This implementation is highly efficient when {@code elements} is itself a {@link * Multiset}. * * @param elements the elements that the multiset should contain * @throws IllegalArgumentException if {@code elements} is empty */ public static <E extends Enum<E>> EnumMultiset<E> create(Iterable<E> elements) { Iterator<E> iterator = elements.iterator(); checkArgument(iterator.hasNext(), "EnumMultiset constructor passed empty Iterable"); EnumMultiset<E> multiset = new EnumMultiset<E>(iterator.next().getDeclaringClass()); Iterables.addAll(multiset, elements); return multiset; } private transient Class<E> type; /** Creates an empty {@code EnumMultiset}. */ private EnumMultiset(Class<E> type) { super(WellBehavedMap.wrap(new EnumMap<E, Count>(type))); this.type = type; } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkNotNull; import static com.google.common.collect.BoundType.CLOSED; import com.google.common.annotations.GwtCompatible; import java.util.Collection; import javax.annotation.Nullable; /** * An implementation of {@link ContiguousSet} that contains one or more elements. * * @author Gregory Kick */ @GwtCompatible(emulated = true) @SuppressWarnings("unchecked") // allow ungenerified Comparable types final class RegularContiguousSet<C extends Comparable> extends ContiguousSet<C> { private final Range<C> range; RegularContiguousSet(Range<C> range, DiscreteDomain<C> domain) { super(domain); this.range = range; } // Abstract method doesn't exist in GWT emulation /* @Override */ ContiguousSet<C> headSetImpl(C toElement, boolean inclusive) { return range.intersection(Ranges.upTo(toElement, BoundType.forBoolean(inclusive))) .asSet(domain); } // Abstract method doesn't exist in GWT emulation /* @Override */ int indexOf(Object target) { return contains(target) ? (int) domain.distance(first(), (C) target) : -1; } // Abstract method doesn't exist in GWT emulation /* @Override */ ContiguousSet<C> subSetImpl(C fromElement, boolean fromInclusive, C toElement, boolean toInclusive) { return range.intersection(Ranges.range(fromElement, BoundType.forBoolean(fromInclusive), toElement, BoundType.forBoolean(toInclusive))).asSet(domain); } // Abstract method doesn't exist in GWT emulation /* @Override */ ContiguousSet<C> tailSetImpl(C fromElement, boolean inclusive) { return range.intersection(Ranges.downTo(fromElement, BoundType.forBoolean(inclusive))) .asSet(domain); } @Override public UnmodifiableIterator<C> iterator() { return new AbstractSequentialIterator<C>(first()) { final C last = last(); @Override protected C computeNext(C previous) { return equalsOrThrow(previous, last) ? null : domain.next(previous); } }; } private static boolean equalsOrThrow(Comparable<?> left, @Nullable Comparable<?> right) { return right != null && Range.compareOrThrow(left, right) == 0; } @Override boolean isPartialView() { return false; } @Override public C first() { return range.lowerBound.leastValueAbove(domain); } @Override public C last() { return range.upperBound.greatestValueBelow(domain); } @Override public int size() { long distance = domain.distance(first(), last()); return (distance >= Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int) distance + 1; } @Override public boolean contains(Object object) { try { return range.contains((C) object); } catch (ClassCastException e) { return false; } } @Override public boolean containsAll(Collection<?> targets) { try { return range.containsAll((Iterable<? extends C>) targets); } catch (ClassCastException e) { return false; } } @Override public boolean isEmpty() { return false; } // copied to make sure not to use the GWT-emulated version @Override public Object[] toArray() { return ObjectArrays.toArrayImpl(this); } // copied to make sure not to use the GWT-emulated version @Override public <T> T[] toArray(T[] other) { return ObjectArrays.toArrayImpl(this, other); } @Override public ContiguousSet<C> intersection(ContiguousSet<C> other) { checkNotNull(other); checkArgument(this.domain.equals(other.domain)); if (other.isEmpty()) { return other; } else { C lowerEndpoint = Ordering.natural().max(this.first(), other.first()); C upperEndpoint = Ordering.natural().min(this.last(), other.last()); return (lowerEndpoint.compareTo(upperEndpoint) < 0) ? Ranges.closed(lowerEndpoint, upperEndpoint).asSet(domain) : new EmptyContiguousSet<C>(domain); } } @Override public Range<C> range() { return range(CLOSED, CLOSED); } @Override public Range<C> range(BoundType lowerBoundType, BoundType upperBoundType) { return Ranges.create(range.lowerBound.withLowerBoundType(lowerBoundType, domain), range.upperBound.withUpperBoundType(upperBoundType, domain)); } @Override public boolean equals(Object object) { if (object == this) { return true; } else if (object instanceof RegularContiguousSet<?>) { RegularContiguousSet<?> that = (RegularContiguousSet<?>) object; if (this.domain.equals(that.domain)) { return this.first().equals(that.first()) && this.last().equals(that.last()); } } return super.equals(object); } // copied to make sure not to use the GWT-emulated version @Override public int hashCode() { return Sets.hashCodeImpl(this); } private static final long serialVersionUID = 0; }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import java.util.Collections; /** * GWT emulation of {@link SingletonImmutableMap}. * * @author Hayward Chan */ final class SingletonImmutableMap<K, V> extends ImmutableMap<K, V> { // These references are used both by the custom field serializer, and by the // GWT compiler to infer the keys and values of the map that needs to be // serialized. // // Although they are non-final, they are package private and the reference is // never modified after a map is constructed. K singleKey; V singleValue; SingletonImmutableMap(K key, V value) { super(Collections.singletonMap(checkNotNull(key), checkNotNull(value))); this.singleKey = key; this.singleValue = value; } }
Java
/* * Copyright (C) 2007 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Objects; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; /** * A general-purpose bimap implementation using any two backing {@code Map} * instances. * * <p>Note that this class contains {@code equals()} calls that keep it from * supporting {@code IdentityHashMap} backing maps. * * @author Kevin Bourrillion * @author Mike Bostock */ @GwtCompatible(emulated = true) abstract class AbstractBiMap<K, V> extends ForwardingMap<K, V> implements BiMap<K, V>, Serializable { private transient Map<K, V> delegate; transient AbstractBiMap<V, K> inverse; /** Package-private constructor for creating a map-backed bimap. */ AbstractBiMap(Map<K, V> forward, Map<V, K> backward) { setDelegates(forward, backward); } /** Private constructor for inverse bimap. */ private AbstractBiMap(Map<K, V> backward, AbstractBiMap<V, K> forward) { delegate = backward; inverse = forward; } @Override protected Map<K, V> delegate() { return delegate; } /** * Returns its input, or throws an exception if this is not a valid key. */ K checkKey(K key) { return key; } /** * Returns its input, or throws an exception if this is not a valid value. */ V checkValue(V value) { return value; } /** * Specifies the delegate maps going in each direction. Called by the * constructor and by subclasses during deserialization. */ void setDelegates(Map<K, V> forward, Map<V, K> backward) { checkState(delegate == null); checkState(inverse == null); checkArgument(forward.isEmpty()); checkArgument(backward.isEmpty()); checkArgument(forward != backward); delegate = forward; inverse = new Inverse<V, K>(backward, this); } void setInverse(AbstractBiMap<V, K> inverse) { this.inverse = inverse; } // Query Operations (optimizations) @Override public boolean containsValue(Object value) { return inverse.containsKey(value); } // Modification Operations @Override public V put(K key, V value) { return putInBothMaps(key, value, false); } @Override public V forcePut(K key, V value) { return putInBothMaps(key, value, true); } private V putInBothMaps(@Nullable K key, @Nullable V value, boolean force) { checkKey(key); checkValue(value); boolean containedKey = containsKey(key); if (containedKey && Objects.equal(value, get(key))) { return value; } if (force) { inverse().remove(value); } else { checkArgument(!containsValue(value), "value already present: %s", value); } V oldValue = delegate.put(key, value); updateInverseMap(key, containedKey, oldValue, value); return oldValue; } private void updateInverseMap( K key, boolean containedKey, V oldValue, V newValue) { if (containedKey) { removeFromInverseMap(oldValue); } inverse.delegate.put(newValue, key); } @Override public V remove(Object key) { return containsKey(key) ? removeFromBothMaps(key) : null; } private V removeFromBothMaps(Object key) { V oldValue = delegate.remove(key); removeFromInverseMap(oldValue); return oldValue; } private void removeFromInverseMap(V oldValue) { inverse.delegate.remove(oldValue); } // Bulk Operations @Override public void putAll(Map<? extends K, ? extends V> map) { for (Entry<? extends K, ? extends V> entry : map.entrySet()) { put(entry.getKey(), entry.getValue()); } } @Override public void clear() { delegate.clear(); inverse.delegate.clear(); } // Views @Override public BiMap<V, K> inverse() { return inverse; } private transient Set<K> keySet; @Override public Set<K> keySet() { Set<K> result = keySet; return (result == null) ? keySet = new KeySet() : result; } private class KeySet extends ForwardingSet<K> { @Override protected Set<K> delegate() { return delegate.keySet(); } @Override public void clear() { AbstractBiMap.this.clear(); } @Override public boolean remove(Object key) { if (!contains(key)) { return false; } removeFromBothMaps(key); return true; } @Override public boolean removeAll(Collection<?> keysToRemove) { return standardRemoveAll(keysToRemove); } @Override public boolean retainAll(Collection<?> keysToRetain) { return standardRetainAll(keysToRetain); } @Override public Iterator<K> iterator() { final Iterator<Entry<K, V>> iterator = delegate.entrySet().iterator(); return new Iterator<K>() { Entry<K, V> entry; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public K next() { entry = iterator.next(); return entry.getKey(); } @Override public void remove() { checkState(entry != null); V value = entry.getValue(); iterator.remove(); removeFromInverseMap(value); } }; } } private transient Set<V> valueSet; @Override public Set<V> values() { /* * We can almost reuse the inverse's keySet, except we have to fix the * iteration order so that it is consistent with the forward map. */ Set<V> result = valueSet; return (result == null) ? valueSet = new ValueSet() : result; } private class ValueSet extends ForwardingSet<V> { final Set<V> valuesDelegate = inverse.keySet(); @Override protected Set<V> delegate() { return valuesDelegate; } @Override public Iterator<V> iterator() { final Iterator<V> iterator = delegate.values().iterator(); return new Iterator<V>() { V valueToRemove; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public V next() { return valueToRemove = iterator.next(); } @Override public void remove() { iterator.remove(); removeFromInverseMap(valueToRemove); } }; } @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public String toString() { return standardToString(); } } private transient Set<Entry<K, V>> entrySet; @Override public Set<Entry<K, V>> entrySet() { Set<Entry<K, V>> result = entrySet; return (result == null) ? entrySet = new EntrySet() : result; } private class EntrySet extends ForwardingSet<Entry<K, V>> { final Set<Entry<K, V>> esDelegate = delegate.entrySet(); @Override protected Set<Entry<K, V>> delegate() { return esDelegate; } @Override public void clear() { AbstractBiMap.this.clear(); } @Override public boolean remove(Object object) { if (!esDelegate.contains(object)) { return false; } // safe because esDelgate.contains(object). Entry<?, ?> entry = (Entry<?, ?>) object; inverse.delegate.remove(entry.getValue()); /* * Remove the mapping in inverse before removing from esDelegate because * if entry is part of esDelegate, entry might be invalidated after the * mapping is removed from esDelegate. */ esDelegate.remove(entry); return true; } @Override public Iterator<Entry<K, V>> iterator() { final Iterator<Entry<K, V>> iterator = esDelegate.iterator(); return new Iterator<Entry<K, V>>() { Entry<K, V> entry; @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Entry<K, V> next() { entry = iterator.next(); final Entry<K, V> finalEntry = entry; return new ForwardingMapEntry<K, V>() { @Override protected Entry<K, V> delegate() { return finalEntry; } @Override public V setValue(V value) { // Preconditions keep the map and inverse consistent. checkState(contains(this), "entry no longer in map"); // similar to putInBothMaps, but set via entry if (Objects.equal(value, getValue())) { return value; } checkArgument(!containsValue(value), "value already present: %s", value); V oldValue = finalEntry.setValue(value); checkState(Objects.equal(value, get(getKey())), "entry no longer in map"); updateInverseMap(getKey(), true, oldValue, value); return oldValue; } }; } @Override public void remove() { checkState(entry != null); V value = entry.getValue(); iterator.remove(); removeFromInverseMap(value); } }; } // See java.util.Collections.CheckedEntrySet for details on attacks. @Override public Object[] toArray() { return standardToArray(); } @Override public <T> T[] toArray(T[] array) { return standardToArray(array); } @Override public boolean contains(Object o) { return Maps.containsEntryImpl(delegate(), o); } @Override public boolean containsAll(Collection<?> c) { return standardContainsAll(c); } @Override public boolean removeAll(Collection<?> c) { return standardRemoveAll(c); } @Override public boolean retainAll(Collection<?> c) { return standardRetainAll(c); } } /** The inverse of any other {@code AbstractBiMap} subclass. */ private static class Inverse<K, V> extends AbstractBiMap<K, V> { private Inverse(Map<K, V> backward, AbstractBiMap<V, K> forward) { super(backward, forward); } /* * Serialization stores the forward bimap, the inverse of this inverse. * Deserialization calls inverse() on the forward bimap and returns that * inverse. * * If a bimap and its inverse are serialized together, the deserialized * instances have inverse() methods that return the other. */ @Override K checkKey(K key) { return inverse.checkValue(key); } @Override V checkValue(V value) { return inverse.checkKey(value); } } }
Java
/* * Copyright (C) 2009 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import static com.google.common.base.Preconditions.checkNotNull; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import java.util.Set; /** * GWT emulated version of {@link ImmutableSet}. For the unsorted sets, they * are thin wrapper around {@link java.util.Collections#emptySet()}, {@link * Collections#singleton(Object)} and {@link java.util.LinkedHashSet} for * empty, singleton and regular sets respectively. For the sorted sets, it's * a thin wrapper around {@link java.util.TreeSet}. * * @see ImmutableSortedSet * * @author Hayward Chan */ @SuppressWarnings("serial") // Serialization only done in GWT. public abstract class ImmutableSet<E> extends ForwardingImmutableCollection<E> implements Set<E> { ImmutableSet(Set<E> delegate) { super(Collections.unmodifiableSet(delegate)); } ImmutableSet() { this(Collections.<E>emptySet()); } // Casting to any type is safe because the set will never hold any elements. @SuppressWarnings({"unchecked"}) public static <E> ImmutableSet<E> of() { return (ImmutableSet<E>) EmptyImmutableSet.INSTANCE; } public static <E> ImmutableSet<E> of(E element) { return new SingletonImmutableSet<E>(element); } @SuppressWarnings("unchecked") public static <E> ImmutableSet<E> of(E e1, E e2) { return create(e1, e2); } @SuppressWarnings("unchecked") public static <E> ImmutableSet<E> of(E e1, E e2, E e3) { return create(e1, e2, e3); } @SuppressWarnings("unchecked") public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4) { return create(e1, e2, e3, e4); } @SuppressWarnings("unchecked") public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5) { return create(e1, e2, e3, e4, e5); } @SuppressWarnings("unchecked") public static <E> ImmutableSet<E> of(E e1, E e2, E e3, E e4, E e5, E e6, E... others) { int size = others.length + 6; List<E> all = new ArrayList<E>(size); Collections.addAll(all, e1, e2, e3, e4, e5, e6); Collections.addAll(all, others); return copyOf(all.iterator()); } /** @deprecated */ @Deprecated public static <E> ImmutableSet<E> of(E[] elements) { return copyOf(elements); } public static <E> ImmutableSet<E> copyOf(E[] elements) { checkNotNull(elements); switch (elements.length) { case 0: return of(); case 1: return of(elements[0]); default: return create(elements); } } public static <E> ImmutableSet<E> copyOf(Collection<? extends E> elements) { Iterable<? extends E> iterable = elements; return copyOf(iterable); } public static <E> ImmutableSet<E> copyOf(Iterable<? extends E> elements) { if (elements instanceof ImmutableSet && !(elements instanceof ImmutableSortedSet)) { @SuppressWarnings("unchecked") // all supported methods are covariant ImmutableSet<E> set = (ImmutableSet<E>) elements; return set; } return copyOf(elements.iterator()); } public static <E> ImmutableSet<E> copyOf(Iterator<? extends E> elements) { if (!elements.hasNext()) { return of(); } E first = elements.next(); if (!elements.hasNext()) { // TODO: Remove "ImmutableSet.<E>" when eclipse bug is fixed. return ImmutableSet.<E>of(first); } Set<E> delegate = Sets.newLinkedHashSet(); delegate.add(checkNotNull(first)); do { delegate.add(checkNotNull(elements.next())); } while (elements.hasNext()); return unsafeDelegate(delegate); } // Factory methods that skips the null checks on elements, only used when // the elements are known to be non-null. static <E> ImmutableSet<E> unsafeDelegate(Set<E> delegate) { switch (delegate.size()) { case 0: return of(); case 1: return new SingletonImmutableSet<E>(delegate.iterator().next()); default: return new RegularImmutableSet<E>(delegate); } } private static <E> ImmutableSet<E> create(E... elements) { // Create the set first, to remove duplicates if necessary. Set<E> set = Sets.newLinkedHashSet(); Collections.addAll(set, elements); for (E element : set) { checkNotNull(element); } switch (set.size()) { case 0: return of(); case 1: return new SingletonImmutableSet<E>(set.iterator().next()); default: return new RegularImmutableSet<E>(set); } } @Override public boolean equals(Object obj) { return Sets.equalsImpl(this, obj); } @Override public int hashCode() { return delegate.hashCode(); } public static <E> Builder<E> builder() { return new Builder<E>(); } public static class Builder<E> extends ImmutableCollection.Builder<E> { // accessed directly by ImmutableSortedSet final ArrayList<E> contents = Lists.newArrayList(); public Builder() {} @Override public Builder<E> add(E element) { contents.add(checkNotNull(element)); return this; } @Override public Builder<E> add(E... elements) { checkNotNull(elements); // for GWT contents.ensureCapacity(contents.size() + elements.length); super.add(elements); return this; } @Override public Builder<E> addAll(Iterable<? extends E> elements) { if (elements instanceof Collection) { Collection<?> collection = (Collection<?>) elements; contents.ensureCapacity(contents.size() + collection.size()); } super.addAll(elements); return this; } @Override public Builder<E> addAll(Iterator<? extends E> elements) { super.addAll(elements); return this; } @Override public ImmutableSet<E> build() { return copyOf(contents.iterator()); } } }
Java