code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * 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 junit.framework.TestCase; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; /** * Base test case class for I/O tests. * * @author Chris Nokleberg * @author Colin Decker */ public abstract class IoTestCase extends TestCase { private static final Logger logger = Logger.getLogger(IoTestCase.class.getName()); 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{|}~"; private File testDir; private File tempDir; private final Set<File> filesToDelete = Sets.newHashSet(); @Override protected void tearDown() { for (File file : filesToDelete) { if (file.exists()) { delete(file); } } filesToDelete.clear(); } private File getTestDir() throws IOException { if (testDir != null) { return testDir; } URL testFileUrl = IoTestCase.class.getResource("testdata/i18n.txt"); if (testFileUrl == null) { throw new RuntimeException("unable to locate testdata directory"); } if (testFileUrl.getProtocol().equals("file")) { try { File testFile = new File(testFileUrl.toURI()); testDir = testFile.getParentFile(); // the testdata directory } catch (Exception ignore) { // probably URISyntaxException or IllegalArgumentException // fall back to copying URLs to files in the testDir == null block below } } if (testDir == null) { // testdata resources aren't file:// urls, so create a directory to store them in and then // copy the resources to the filesystem as needed testDir = createTempDir(); } return testDir; } /** * Returns the file with the given name under the testdata directory. */ protected final File getTestFile(String name) throws IOException { File file = new File(getTestDir(), name); if (!file.exists()) { URL resourceUrl = IoTestCase.class.getResource("testdata/" + name); if (resourceUrl == null) { return null; } copy(resourceUrl, file); } return file; } /** * Creates a new temp dir for testing. The returned directory and all contents of it will be * deleted in the tear-down for this test. */ protected final File createTempDir() throws IOException { File tempFile = File.createTempFile("IoTestCase", ""); if (!tempFile.delete() || !tempFile.mkdir()) { throw new IOException("failed to create temp dir"); } filesToDelete.add(tempFile); return tempFile; } /** * Gets a temp dir for testing. The returned directory and all contents of it will be deleted in * the tear-down for this test. Subsequent invocations of this method will return the same * directory. */ protected final File getTempDir() throws IOException { if (tempDir == null) { tempDir = createTempDir(); } return tempDir; } /** * Creates a new temp file in the temp directory returned by {@link #getTempDir()}. The file will * be deleted in the tear-down for this test. */ protected final File createTempFile() throws IOException { return File.createTempFile("test", null, getTempDir()); } /** * Returns a byte array of length size that has values 0 .. size - 1. */ static byte[] newPreFilledByteArray(int size) { return newPreFilledByteArray(0, size); } /** * Returns a byte array of length size that has values offset .. offset + size - 1. */ 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; } private static void copy(URL url, File file) throws IOException { InputStream in = url.openStream(); try { OutputStream out = new FileOutputStream(file); try { byte[] buf = new byte[4096]; for (int read = in.read(buf); read != -1; read = in.read(buf)) { out.write(buf, 0, read); } } finally { out.close(); } } finally { in.close(); } } private boolean delete(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); if (files != null) { for (File f : files) { if (!delete(f)) { return false; } } } } if (!file.delete()) { logger.log(Level.WARNING, "couldn't delete file: {0}", new Object[] {file}); return false; } return true; } }
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.io; import static com.google.common.io.SourceSinkFactory.ByteSinkFactory; import static com.google.common.io.SourceSinkFactory.CharSinkFactory; import static org.junit.Assert.assertArrayEquals; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import junit.framework.TestSuite; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.Map; /** * A generator of {@code TestSuite} instances for testing {@code ByteSink} implementations. * Generates tests of a all methods on a {@code ByteSink} given various inputs written to it as well * as sub-suites for testing the {@code CharSink} view in the same way. * * @author Colin Decker */ public class ByteSinkTester extends SourceSinkTester<ByteSink, byte[], ByteSinkFactory> { private static final ImmutableList<Method> testMethods = getTestMethods(ByteSinkTester.class); static TestSuite tests(String name, ByteSinkFactory factory) { TestSuite suite = new TestSuite(name); for (Map.Entry<String, String> entry : TEST_STRINGS.entrySet()) { String desc = entry.getKey(); TestSuite stringSuite = suiteForString(name, factory, entry.getValue(), desc); suite.addTest(stringSuite); } return suite; } private static TestSuite suiteForString(String name, ByteSinkFactory factory, String string, String desc) { byte[] bytes = string.getBytes(Charsets.UTF_8); TestSuite suite = suiteForBytes(name, factory, desc, bytes); CharSinkFactory charSinkFactory = SourceSinkFactories.asCharSinkFactory(factory); suite.addTest(CharSinkTester.suiteForString(name + ".asCharSink[Charset]", charSinkFactory, string, desc)); return suite; } private static TestSuite suiteForBytes(String name, ByteSinkFactory factory, String desc, byte[] bytes) { TestSuite suite = new TestSuite(name + " [" + desc + "]"); for (final Method method : testMethods) { suite.addTest(new ByteSinkTester(factory, bytes, name, desc, method)); } return suite; } private ByteSink sink; ByteSinkTester(ByteSinkFactory factory, byte[] data, String suiteName, String caseDesc, Method method) { super(factory, data, suiteName, caseDesc, method); } @Override protected void setUp() throws Exception { sink = factory.createSink(); } public void testOpenStream() throws IOException { OutputStream out = sink.openStream(); try { ByteStreams.copy(new ByteArrayInputStream(data), out); } finally { out.close(); } assertContainsExpectedBytes(); } public void testOpenBufferedStream() throws IOException { OutputStream out = sink.openBufferedStream(); try { ByteStreams.copy(new ByteArrayInputStream(data), out); } finally { out.close(); } assertContainsExpectedBytes(); } public void testWrite() throws IOException { sink.write(data); assertContainsExpectedBytes(); } public void testWriteFrom_inputStream() throws IOException { sink.writeFrom(new ByteArrayInputStream(data)); assertContainsExpectedBytes(); } private void assertContainsExpectedBytes() throws IOException { assertArrayEquals(expected, factory.getSinkContents()); } }
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.io; import static com.google.common.io.SourceSinkFactory.CharSinkFactory; import com.google.common.base.Joiner; import com.google.common.collect.ImmutableList; import junit.framework.TestSuite; import java.io.IOException; import java.io.Writer; import java.lang.reflect.Method; import java.util.Map; /** * A generator of {@code TestSuite} instances for testing {@code CharSink} implementations. * Generates tests of a all methods on a {@code CharSink} given various inputs written to it. * * @author Colin Decker */ public class CharSinkTester extends SourceSinkTester<CharSink, String, CharSinkFactory> { private static final ImmutableList<Method> testMethods = getTestMethods(CharSinkTester.class); static TestSuite tests(String name, CharSinkFactory factory) { TestSuite suite = new TestSuite(name); for (Map.Entry<String, String> entry : TEST_STRINGS.entrySet()) { String desc = entry.getKey(); TestSuite stringSuite = suiteForString(name, factory, entry.getValue(), desc); suite.addTest(stringSuite); } return suite; } static TestSuite suiteForString(String name, CharSinkFactory factory, String string, String desc) { TestSuite stringSuite = new TestSuite(name + " [" + desc + "]"); for (final Method method : testMethods) { stringSuite.addTest(new CharSinkTester(factory, string, name, desc, method)); } return stringSuite; } private final ImmutableList<String> lines; private final ImmutableList<String> expectedLines; private CharSink sink; public CharSinkTester(CharSinkFactory factory, String string, String suiteName, String caseDesc, Method method) { super(factory, string, suiteName, caseDesc, method); this.lines = getLines(string); this.expectedLines = getLines(expected); } @Override protected void setUp() throws Exception { this.sink = factory.createSink(); } public void testOpenStream() throws IOException { Writer writer = sink.openStream(); try { writer.write(data); } finally { writer.close(); } assertContainsExpectedString(); } public void testOpenBufferedStream() throws IOException { Writer writer = sink.openBufferedStream(); try { writer.write(data); } finally { writer.close(); } assertContainsExpectedString(); } public void testWrite() throws IOException { sink.write(data); assertContainsExpectedString(); } public void testWriteLines_systemDefaultSeparator() throws IOException { String separator = System.getProperty("line.separator"); sink.writeLines(lines); assertContainsExpectedLines(separator); } public void testWriteLines_specificSeparator() throws IOException { String separator = "\r\n"; sink.writeLines(lines, separator); assertContainsExpectedLines(separator); } private void assertContainsExpectedString() throws IOException { assertEquals(expected, factory.getSinkContents()); } private void assertContainsExpectedLines(String separator) throws IOException { String expected = expectedLines.isEmpty() ? "" : Joiner.on(separator).join(expectedLines); if (!lines.isEmpty()) { // if we wrote any lines in writeLines(), there will be a trailing newline expected += separator; } assertEquals(expected, factory.getSinkContents()); } }
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.io; import static com.google.common.io.SourceSinkFactory.CharSourceFactory; import com.google.common.collect.ImmutableList; import junit.framework.TestSuite; import java.io.BufferedReader; import java.io.IOException; import java.io.Reader; import java.io.StringWriter; import java.lang.reflect.Method; import java.util.List; import java.util.Map; /** * A generator of {@code TestSuite} instances for testing {@code CharSource} implementations. * Generates tests of a all methods on a {@code CharSource} given various inputs the source is * expected to contain. * * @author Colin Decker */ public class CharSourceTester extends SourceSinkTester<CharSource, String, CharSourceFactory> { private static final ImmutableList<Method> testMethods = getTestMethods(CharSourceTester.class); static TestSuite tests(String name, CharSourceFactory factory) { TestSuite suite = new TestSuite(name); for (Map.Entry<String, String> entry : TEST_STRINGS.entrySet()) { suite.addTest(suiteForString(factory, entry.getValue(), name, entry.getKey())); } return suite; } static TestSuite suiteForString(CharSourceFactory factory, String string, String name, String desc) { TestSuite suite = new TestSuite(name + " [" + desc + "]"); for (Method method : testMethods) { suite.addTest(new CharSourceTester(factory, string, name, desc, method)); } return suite; } private final ImmutableList<String> expectedLines; private CharSource source; public CharSourceTester(CharSourceFactory factory, String string, String suiteName, String caseDesc, Method method) { super(factory, string, suiteName, caseDesc, method); this.expectedLines = getLines(expected); } @Override protected void setUp() throws Exception { this.source = factory.createSource(data); } public void testOpenStream() throws IOException { Reader reader = source.openStream(); StringWriter writer = new StringWriter(); char[] buf = new char[64]; int read; while ((read = reader.read(buf)) != -1) { writer.write(buf, 0, read); } reader.close(); writer.close(); assertExpectedString(writer.toString()); } public void testOpenBufferedStream() throws IOException { BufferedReader reader = source.openBufferedStream(); StringWriter writer = new StringWriter(); char[] buf = new char[64]; int read; while ((read = reader.read(buf)) != -1) { writer.write(buf, 0, read); } reader.close(); writer.close(); assertExpectedString(writer.toString()); } public void testCopyTo_appendable() throws IOException { StringBuilder builder = new StringBuilder(); assertEquals(expected.length(), source.copyTo(builder)); assertExpectedString(builder.toString()); } public void testCopyTo_charSink() throws IOException { TestCharSink sink = new TestCharSink(); assertEquals(expected.length(), source.copyTo(sink)); assertExpectedString(sink.getString()); } public void testRead_toString() throws IOException { String string = source.read(); assertExpectedString(string); } public void testReadFirstLine() throws IOException { if (expectedLines.isEmpty()) { assertNull(source.readFirstLine()); } else { assertEquals(expectedLines.get(0), source.readFirstLine()); } } public void testReadLines_toList() throws IOException { assertExpectedLines(source.readLines()); } public void testIsEmpty() throws IOException { assertEquals(expected.isEmpty(), source.isEmpty()); } private void assertExpectedString(String string) { assertEquals(expected, string); } private void assertExpectedLines(List<String> list) { assertEquals(expectedLines, list); } }
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.io; import static com.google.common.io.SourceSinkFactory.ByteSourceFactory; import static com.google.common.io.SourceSinkFactory.CharSourceFactory; import static org.junit.Assert.assertArrayEquals; import com.google.common.base.Charsets; import com.google.common.collect.ImmutableList; import com.google.common.hash.HashCode; import com.google.common.hash.Hashing; import junit.framework.TestSuite; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.lang.reflect.Method; import java.util.Map; import java.util.Random; /** * A generator of {@code TestSuite} instances for testing {@code ByteSource} implementations. * Generates tests of a all methods on a {@code ByteSource} given various inputs the source is * expected to contain as well as as sub-suites for testing the {@code CharSource} view and * {@code slice()} views in the same way. * * @author Colin Decker */ public class ByteSourceTester extends SourceSinkTester<ByteSource, byte[], ByteSourceFactory> { private static final ImmutableList<Method> testMethods = getTestMethods(ByteSourceTester.class); static TestSuite tests(String name, ByteSourceFactory factory, boolean testAsCharSource) { TestSuite suite = new TestSuite(name); for (Map.Entry<String, String> entry : TEST_STRINGS.entrySet()) { if (testAsCharSource) { suite.addTest(suiteForString(factory, entry.getValue(), name, entry.getKey())); } else { suite.addTest(suiteForBytes( factory, entry.getValue().getBytes(Charsets.UTF_8), name, entry.getKey(), true)); } } return suite; } private static TestSuite suiteForString(ByteSourceFactory factory, String string, String name, String desc) { TestSuite suite = suiteForBytes(factory, string.getBytes(Charsets.UTF_8), name, desc, true); CharSourceFactory charSourceFactory = SourceSinkFactories.asCharSourceFactory(factory); suite.addTest(CharSourceTester.suiteForString(charSourceFactory, string, name + ".asCharSource[Charset]", desc)); return suite; } private static TestSuite suiteForBytes(ByteSourceFactory factory, byte[] bytes, String name, String desc, boolean slice) { TestSuite suite = new TestSuite(name + " [" + desc + "]"); for (Method method : testMethods) { suite.addTest(new ByteSourceTester(factory, bytes, name, desc, method)); } if (slice && bytes.length > 0) { // test a random slice() of the ByteSource Random random = new Random(); byte[] expected = factory.getExpected(bytes); // if expected.length == 0, off has to be 0 but length doesn't matter--result will be empty int off = expected.length == 0 ? 0 : random.nextInt(expected.length); int len = expected.length == 0 ? 4 : random.nextInt(expected.length - off); ByteSourceFactory sliced = SourceSinkFactories.asSlicedByteSourceFactory(factory, off, len); suite.addTest(suiteForBytes(sliced, bytes, name + ".slice[int, int]", desc, false)); } return suite; } private ByteSource source; public ByteSourceTester(ByteSourceFactory factory, byte[] bytes, String suiteName, String caseDesc, Method method) { super(factory, bytes, suiteName, caseDesc, method); } @Override public void setUp() throws IOException { source = factory.createSource(data); } public void testOpenStream() throws IOException { InputStream in = source.openStream(); try { byte[] readBytes = ByteStreams.toByteArray(in); assertExpectedBytes(readBytes); } finally { in.close(); } } public void testOpenBufferedStream() throws IOException { InputStream in = source.openBufferedStream(); try { byte[] readBytes = ByteStreams.toByteArray(in); assertExpectedBytes(readBytes); } finally { in.close(); } } public void testRead() throws IOException { byte[] readBytes = source.read(); assertExpectedBytes(readBytes); } public void testCopyTo_outputStream() throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); source.copyTo(out); assertExpectedBytes(out.toByteArray()); } public void testCopyTo_byteSink() throws IOException { final ByteArrayOutputStream out = new ByteArrayOutputStream(); // HERESY! but it's ok just for this I guess source.copyTo(new ByteSink() { @Override public OutputStream openStream() throws IOException { return out; } }); assertExpectedBytes(out.toByteArray()); } public void testIsEmpty() throws IOException { assertEquals(expected.length == 0, source.isEmpty()); } public void testSize() throws IOException { assertEquals(expected.length, source.size()); } public void testContentEquals() throws IOException { assertTrue(source.contentEquals(new ByteSource() { @Override public InputStream openStream() throws IOException { return new RandomAmountInputStream( new ByteArrayInputStream(expected), new Random()); } })); } public void testHash() throws IOException { HashCode expectedHash = Hashing.md5().hashBytes(expected); assertEquals(expectedHash, source.hash(Hashing.md5())); } public void testSlice_illegalArguments() { try { source.slice(-1, 0); fail("expected IllegalArgumentException for call to slice with offset -1: " + source); } catch (IllegalArgumentException expected) { } try { source.slice(0, -1); fail("expected IllegalArgumentException for call to slice with length -1: " + source); } catch (IllegalArgumentException expected) { } } private void assertExpectedBytes(byte[] readBytes) { assertArrayEquals(expected, readBytes); } }
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 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 <V> Optional<V> transform( Function<? super T, V> function) { 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) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import com.google.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 {@code UnsignedLong}. * * @author Louis Wasserman */ public class UnsignedLong_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, UnsignedLong instance) {} public static UnsignedLong instantiate(SerializationStreamReader reader) throws SerializationException { return UnsignedLong.fromLongBits(reader.readLong()); } public static void serialize(SerializationStreamWriter writer, UnsignedLong instance) throws SerializationException { writer.writeLong(instance.longValue()); } }
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; import com.google.gwt.core.client.EntryPoint; /** * A dummy entry point to convince Maven to compile our classes. * * @author Chris Povirk */ public class ForceGuavaCompilationEntryPoint implements EntryPoint { @Override public void onModuleLoad() { } }
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.lang.reflect.Array; // TODO(kevinb): guava javadoc path seems set wrong, doesn't find that last // import /** * Version of {@link GwtPlatform} used in hosted-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 * GwtScriptOnly} (which is applied to the emul version) supports only public * classes and methods. * * @author Hayward Chan */ // TODO(hhchan): Once we start using server-side source in hosted mode, we won't // need this. @GwtCompatible(emulated = true) public final class GwtPlatform { private GwtPlatform() {} /** See {@link Platform#newArray(Object[], int)} */ public static <T> T[] newArray(T[] reference, int length) { Class<?> type = reference.getClass().getComponentType(); // the cast is safe because // result.getClass() == reference.getClass().getComponentType() @SuppressWarnings("unchecked") T[] result = (T[]) Array.newInstance(type, length); return result; } }
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.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 EmptyImmutableSortedMap}. * * @author Chris Povirk */ public class EmptyImmutableSortedMap_CustomFieldSerializer { public static void deserialize( SerializationStreamReader reader, EmptyImmutableSortedMap<?, ?> instance) { } public static EmptyImmutableSortedMap<?, ?> instantiate( SerializationStreamReader reader) throws SerializationException { return (EmptyImmutableSortedMap<?, ?>) ImmutableSortedMap_CustomFieldSerializerBase.instantiate(reader); } public static void serialize( SerializationStreamWriter writer, EmptyImmutableSortedMap<?, ?> instance) throws SerializationException { ImmutableSortedMap_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 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) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import com.google.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 SparseImmutableTable}. * * @author Chris Povirk */ public class SparseImmutableTable_CustomFieldSerializer { public static void deserialize( SerializationStreamReader reader, SparseImmutableTable<?, ?, ?> instance) { } public static SparseImmutableTable<Object, Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { return (SparseImmutableTable<Object, Object, Object>) ImmutableTable_CustomFieldSerializerBase.instantiate(reader); } public static void serialize( SerializationStreamWriter writer, SparseImmutableTable<Object, Object, Object> table) throws SerializationException { ImmutableTable_CustomFieldSerializerBase.serialize(writer, table); } }
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; /** * This class implements the GWT serialization of {@link HashBasedTable}. * * @author Hayward Chan */ public class HashBasedTable_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, HashBasedTable<?, ?, ?> table) { } public static HashBasedTable<Object, Object, Object> instantiate(SerializationStreamReader reader) throws SerializationException { return Table_CustomFieldSerializerBase.populate(reader, HashBasedTable.create()); } public static void serialize(SerializationStreamWriter writer, HashBasedTable<?, ?, ?> table) throws SerializationException { Table_CustomFieldSerializerBase.serialize(writer, table); } }
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 ForwardingImmutableList} cannot be instantiated, we still * need a custom field serializer. TODO(cpovirk): why? * * @author Hayward Chan */ public final class ForwardingImmutableList_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; /** * 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 * {@link #populate(SerializationStreamReader, Multiset)}. * * @author Chris Povirk */ final class Multiset_CustomFieldSerializerBase { 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; /** * Even though {@link ImmutableSortedMap} cannot be instantiated, we still need a custom field * serializer. TODO(cpovirk): why? Does it help if ensure that the GWT and non-GWT classes have the * same fields? Is that worth the trouble? * * @author Chris Povirk */ public final class ImmutableSortedMap_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.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) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import com.google.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; /** * This class contains static utility methods for writing {@link ImmutableTable} GWT field * serializers. Serializers should delegate to {@link #serialize} and {@link #instantiate}. * * @author Chris Povirk */ final class ImmutableTable_CustomFieldSerializerBase { public static ImmutableTable<Object, Object, Object> instantiate(SerializationStreamReader reader) throws SerializationException { ImmutableTable.Builder<Object, Object, Object> builder = ImmutableTable.builder(); int rowCount = reader.readInt(); for (int i = 0; i < rowCount; i++) { Object rowKey = reader.readObject(); int colCount = reader.readInt(); for (int j = 0; j < colCount; j++) { builder.put(rowKey, reader.readObject(), reader.readObject()); } } return builder.build(); } public static void serialize( SerializationStreamWriter writer, ImmutableTable<Object, Object, Object> table) throws SerializationException { writer.writeInt(table.rowKeySet().size()); for (Object rowKey : table.rowKeySet()) { writer.writeObject(rowKey); Map_CustomFieldSerializerBase.serialize(writer, table.row(rowKey)); } } private ImmutableTable_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; 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; /** * Even though {@link ImmutableAsList} cannot be instantiated, we still need * a custom field serializer. TODO(cpovirk): why? * * @author Hayward Chan */ public final class ImmutableAsList_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.common.annotations.GwtCompatible; import java.io.Serializable; 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() {} } 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); } } /* * We don't normally need "implements Serializable," but we do here. That's * because ImmutableTable itself is not Serializable as of this writing. We * need for GWT to believe that this dummy class is serializable, or else it * won't generate serialization code for R, C, and V. */ static final class ImmutableTableDependencies<R, C, V> extends SingletonImmutableTable<R, C, V> implements Serializable { R rowKey; C columnKey; V value; ImmutableTableDependencies() { super(null, 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 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 contains static utility methods for writing {@code ImmutableSortedMap} GWT field * serializers. * * @author Chris Povirk */ final class ImmutableSortedMap_CustomFieldSerializerBase { static ImmutableSortedMap<Object, 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(); SortedMap<Object, Object> entries = new TreeMap<Object, Object>(comparator); Map_CustomFieldSerializerBase.deserialize(reader, entries); return ImmutableSortedMap.orderedBy(comparator).putAll(entries).build(); } static void serialize(SerializationStreamWriter writer, ImmutableSortedMap<?, ?> instance) throws SerializationException { writer.writeObject(instance.comparator()); Map_CustomFieldSerializerBase.serialize(writer, instance); } private ImmutableSortedMap_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 SingletonImmutableTable}. * * @author Chris Povirk */ public class SingletonImmutableTable_CustomFieldSerializer { public static void deserialize( SerializationStreamReader reader, SingletonImmutableTable<?, ?, ?> instance) { } public static SingletonImmutableTable<Object, Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { Object rowKey = reader.readObject(); Object columnKey = reader.readObject(); Object value = reader.readObject(); return new SingletonImmutableTable<Object, Object, Object>(rowKey, columnKey, value); } public static void serialize( SerializationStreamWriter writer, SingletonImmutableTable<?, ?, ?> instance) throws SerializationException { writer.writeObject(instance.singleRowKey); writer.writeObject(instance.singleColumnKey); writer.writeObject(instance.singleValue); } }
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 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 java.util.Map; import java.util.Map.Entry; /** * This class contains static utility methods for writing {@link Table} GWT field serializers. * Serializers should delegate to {@link #serialize} and {@link #populate}. * * <p>For {@link ImmutableTable}, see {@link ImmutableTable_CustomFieldSerializerBase}. * * @author Chris Povirk */ final class Table_CustomFieldSerializerBase { static <T extends StandardTable<Object, Object, Object>> T populate( SerializationStreamReader reader, T table) throws SerializationException { Map<?, ?> hashMap = (Map<?, ?>) reader.readObject(); for (Entry<?, ?> row : hashMap.entrySet()) { table.row(row.getKey()).putAll((Map<?, ?>) row.getValue()); } return table; } static void serialize(SerializationStreamWriter writer, StandardTable<?, ?, ?> table) throws SerializationException { /* * The backing map of a {Hash,Tree}BasedTable is a {Hash,Tree}Map of {Hash,Tree}Maps. Therefore, * the backing map is serializable (assuming that the row, column and values, along with any * comparators, are all serializable). */ writer.writeObject(table.backingMap); } private Table_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; 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) 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; /** * This class implements the server-side GWT serialization of * {@link RegularImmutableAsList}. * * @author Hayward Chan */ @GwtCompatible(emulated = true) public class RegularImmutableAsList_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, RegularImmutableAsList<?> instance) { } public static RegularImmutableAsList<Object> instantiate( SerializationStreamReader reader) throws SerializationException { @SuppressWarnings("unchecked") // serialization is necessarily type unsafe ImmutableCollection<Object> delegateCollection = (ImmutableCollection) reader.readObject(); ImmutableList<?> delegateList = (ImmutableList<?>) reader.readObject(); return new RegularImmutableAsList<Object>(delegateCollection, delegateList); } public static void serialize(SerializationStreamWriter writer, RegularImmutableAsList<?> instance) throws SerializationException { writer.writeObject(instance.delegateCollection()); writer.writeObject(instance.delegateList()); } }
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 TreeBasedTable}. * * @author Hayward Chan */ public class TreeBasedTable_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, TreeBasedTable<?, ?, ?> table) { } 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(); TreeBasedTable<Object, Object, Object> table = TreeBasedTable.create(rowComparator, columnComparator); return Table_CustomFieldSerializerBase.populate(reader, table); } public static void serialize(SerializationStreamWriter writer, TreeBasedTable<?, ?, ?> table) throws SerializationException { writer.writeObject(table.rowComparator()); writer.writeObject(table.columnComparator()); Table_CustomFieldSerializerBase.serialize(writer, table); } }
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; 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 SingletonImmutableBiMap}. * * @author Chris Povirk */ public class SingletonImmutableBiMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, SingletonImmutableBiMap<?, ?> instance) { } public static SingletonImmutableBiMap<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { Object key = checkNotNull(reader.readObject()); Object value = checkNotNull(reader.readObject()); return new SingletonImmutableBiMap<Object, Object>(key, value); } public static void serialize(SerializationStreamWriter writer, SingletonImmutableBiMap<?, ?> instance) throws SerializationException { writer.writeObject(instance.singleKey); writer.writeObject(instance.singleValue); } }
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; /** * Even though {@link ForwardingImmutableSet} cannot be instantiated, we still * need a custom field serializer. TODO(cpovirk): why? * * @author Hayward Chan */ public final class ForwardingImmutableSet_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; /** * 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) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.collect; import com.google.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.Map; /** * This class implements the GWT serialization of {@link ImmutableEnumMap}. * * @author Louis Wasserman */ public class ImmutableEnumMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableEnumMap<?, ?> instance) { } public static <K extends Enum<K>, V> ImmutableEnumMap<?, ?> instantiate( SerializationStreamReader reader) throws SerializationException { Map<K, V> deserialized = Maps.newHashMap(); Map_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 (ImmutableEnumMap<?, ?>) Maps.immutableEnumMap(deserialized); } public static void serialize(SerializationStreamWriter writer, ImmutableEnumMap<?, ?> 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 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.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.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of * {@link EmptyImmutableBiMap}. * * @author Chris Povirk */ public class EmptyImmutableBiMap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, EmptyImmutableBiMap instance) { } public static EmptyImmutableBiMap instantiate(SerializationStreamReader reader) { return EmptyImmutableBiMap.INSTANCE; } public static void serialize(SerializationStreamWriter writer, EmptyImmutableBiMap 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 RegularImmutableSortedMap}. * * @author Chris Povirk */ public class RegularImmutableSortedMap_CustomFieldSerializer { public static void deserialize( SerializationStreamReader reader, RegularImmutableSortedMap<?, ?> instance) { } public static RegularImmutableSortedMap<?, ?> instantiate( SerializationStreamReader reader) throws SerializationException { return (RegularImmutableSortedMap<?, ?>) ImmutableSortedMap_CustomFieldSerializerBase.instantiate(reader); } public static void serialize( SerializationStreamWriter writer, RegularImmutableSortedMap<?, ?> instance) throws SerializationException { ImmutableSortedMap_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.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; /** * Even though {@link ImmutableBiMap} cannot be instantiated, we still need * a custom field serializer to unify the type signature of * {@code ImmutableBiMap[]} on server and client side. * * @author Hayward Chan */ public final class ImmutableBiMap_CustomFieldSerializer {}
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.Collection; import java.util.LinkedHashMap; 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 stream) throws SerializationException { LinkedHashMultimap<Object, Object> multimap = LinkedHashMultimap.create(); multimap.valueSetCapacity = stream.readInt(); int distinctKeys = stream.readInt(); Map<Object, Collection<Object>> map = new LinkedHashMap<Object, Collection<Object>>(Maps.capacity(distinctKeys)); for (int i = 0; i < distinctKeys; i++) { Object key = stream.readObject(); map.put(key, multimap.createCollection(key)); } int entries = stream.readInt(); for (int i = 0; i < entries; i++) { Object key = stream.readObject(); Object value = stream.readObject(); map.get(key).add(value); } multimap.setMap(map); return multimap; } public static void serialize(SerializationStreamWriter stream, LinkedHashMultimap<?, ?> multimap) throws SerializationException { stream.writeInt(multimap.valueSetCapacity); stream.writeInt(multimap.keySet().size()); for (Object key : multimap.keySet()) { stream.writeObject(key); } stream.writeInt(multimap.size()); for (Map.Entry<?, ?> entry : multimap.entries()) { stream.writeObject(entry.getKey()); stream.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.SerializationStreamReader; import com.google.gwt.user.client.rpc.SerializationStreamWriter; /** * This class implements the GWT serialization of {@link AllEqualOrdering}. * * @author Chris Povirk */ public class AllEqualOrdering_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, AllEqualOrdering instance) { } public static AllEqualOrdering instantiate(SerializationStreamReader reader) { return AllEqualOrdering.INSTANCE; } public static void serialize(SerializationStreamWriter writer, AllEqualOrdering 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.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) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package com.google.common.collect; import com.google.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 DenseImmutableTable}. * * @author Chris Povirk */ public class DenseImmutableTable_CustomFieldSerializer { public static void deserialize( SerializationStreamReader reader, DenseImmutableTable<?, ?, ?> instance) { } public static DenseImmutableTable<Object, Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { return (DenseImmutableTable<Object, Object, Object>) ImmutableTable_CustomFieldSerializerBase.instantiate(reader); } public static void serialize( SerializationStreamWriter writer, DenseImmutableTable<Object, Object, Object> table) throws SerializationException { ImmutableTable_CustomFieldSerializerBase.serialize(writer, table); } }
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; import java.util.Comparator; /** * This class implements the GWT serialization of {@link ImmutableSetMultimap}. * * @author Chris Povirk */ public class ImmutableSetMultimap_CustomFieldSerializer { public static void deserialize(SerializationStreamReader reader, ImmutableSetMultimap<?, ?> instance) { } // Serialization type safety is at the caller's mercy. @SuppressWarnings("unchecked") public static ImmutableSetMultimap<Object, Object> instantiate( SerializationStreamReader reader) throws SerializationException { Comparator<Object> valueComparator = (Comparator<Object>) reader.readObject(); ImmutableSetMultimap.Builder<Object, Object> builder = ImmutableSetMultimap.builder(); if (valueComparator != null) { builder.orderValuesBy(valueComparator); } return (ImmutableSetMultimap<Object, Object>) Multimap_CustomFieldSerializerBase.instantiate(reader, builder); } public static void serialize(SerializationStreamWriter writer, ImmutableSetMultimap<?, ?> instance) throws SerializationException { writer.writeObject(instance.valueComparator()); Multimap_CustomFieldSerializerBase.serialize(writer, instance); } }
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import static com.google.common.base.CaseFormat.LOWER_CAMEL; import static com.google.common.base.CaseFormat.LOWER_HYPHEN; import static com.google.common.base.CaseFormat.LOWER_UNDERSCORE; import static com.google.common.base.CaseFormat.UPPER_CAMEL; import static com.google.common.base.CaseFormat.UPPER_UNDERSCORE; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; /** * Unit test for {@link CaseFormat}. * * @author Mike Bostock */ @GwtCompatible(emulated = true) public class CaseFormatTest extends TestCase { public void testIdentity() { for (CaseFormat from : CaseFormat.values()) { assertSame(from + " to " + from, "foo", from.to(from, "foo")); for (CaseFormat to : CaseFormat.values()) { assertEquals(from + " to " + to, "", from.to(to, "")); assertEquals(from + " to " + to, " ", from.to(to, " ")); } } } public void testLowerHyphenToLowerHyphen() { assertEquals("foo", LOWER_HYPHEN.to(LOWER_HYPHEN, "foo")); assertEquals("foo-bar", LOWER_HYPHEN.to(LOWER_HYPHEN, "foo-bar")); } public void testLowerHyphenToLowerUnderscore() { assertEquals("foo", LOWER_HYPHEN.to(LOWER_UNDERSCORE, "foo")); assertEquals("foo_bar", LOWER_HYPHEN.to(LOWER_UNDERSCORE, "foo-bar")); } public void testLowerHyphenToLowerCamel() { assertEquals("foo", LOWER_HYPHEN.to(LOWER_CAMEL, "foo")); assertEquals("fooBar", LOWER_HYPHEN.to(LOWER_CAMEL, "foo-bar")); } public void testLowerHyphenToUpperCamel() { assertEquals("Foo", LOWER_HYPHEN.to(UPPER_CAMEL, "foo")); assertEquals("FooBar", LOWER_HYPHEN.to(UPPER_CAMEL, "foo-bar")); } public void testLowerHyphenToUpperUnderscore() { assertEquals("FOO", LOWER_HYPHEN.to(UPPER_UNDERSCORE, "foo")); assertEquals("FOO_BAR", LOWER_HYPHEN.to(UPPER_UNDERSCORE, "foo-bar")); } public void testLowerUnderscoreToLowerHyphen() { assertEquals("foo", LOWER_UNDERSCORE.to(LOWER_HYPHEN, "foo")); assertEquals("foo-bar", LOWER_UNDERSCORE.to(LOWER_HYPHEN, "foo_bar")); } public void testLowerUnderscoreToLowerUnderscore() { assertEquals("foo", LOWER_UNDERSCORE.to(LOWER_UNDERSCORE, "foo")); assertEquals("foo_bar", LOWER_UNDERSCORE.to(LOWER_UNDERSCORE, "foo_bar")); } public void testLowerUnderscoreToLowerCamel() { assertEquals("foo", LOWER_UNDERSCORE.to(LOWER_CAMEL, "foo")); assertEquals("fooBar", LOWER_UNDERSCORE.to(LOWER_CAMEL, "foo_bar")); } public void testLowerUnderscoreToUpperCamel() { assertEquals("Foo", LOWER_UNDERSCORE.to(UPPER_CAMEL, "foo")); assertEquals("FooBar", LOWER_UNDERSCORE.to(UPPER_CAMEL, "foo_bar")); } public void testLowerUnderscoreToUpperUnderscore() { assertEquals("FOO", LOWER_UNDERSCORE.to(UPPER_UNDERSCORE, "foo")); assertEquals("FOO_BAR", LOWER_UNDERSCORE.to(UPPER_UNDERSCORE, "foo_bar")); } public void testLowerCamelToLowerHyphen() { assertEquals("foo", LOWER_CAMEL.to(LOWER_HYPHEN, "foo")); assertEquals("foo-bar", LOWER_CAMEL.to(LOWER_HYPHEN, "fooBar")); assertEquals("h-t-t-p", LOWER_CAMEL.to(LOWER_HYPHEN, "HTTP")); } public void testLowerCamelToLowerUnderscore() { assertEquals("foo", LOWER_CAMEL.to(LOWER_UNDERSCORE, "foo")); assertEquals("foo_bar", LOWER_CAMEL.to(LOWER_UNDERSCORE, "fooBar")); assertEquals("h_t_t_p", LOWER_CAMEL.to(LOWER_UNDERSCORE, "hTTP")); } public void testLowerCamelToLowerCamel() { assertEquals("foo", LOWER_CAMEL.to(LOWER_CAMEL, "foo")); assertEquals("fooBar", LOWER_CAMEL.to(LOWER_CAMEL, "fooBar")); } public void testLowerCamelToUpperCamel() { assertEquals("Foo", LOWER_CAMEL.to(UPPER_CAMEL, "foo")); assertEquals("FooBar", LOWER_CAMEL.to(UPPER_CAMEL, "fooBar")); assertEquals("HTTP", LOWER_CAMEL.to(UPPER_CAMEL, "hTTP")); } public void testLowerCamelToUpperUnderscore() { assertEquals("FOO", LOWER_CAMEL.to(UPPER_UNDERSCORE, "foo")); assertEquals("FOO_BAR", LOWER_CAMEL.to(UPPER_UNDERSCORE, "fooBar")); } public void testUpperCamelToLowerHyphen() { assertEquals("foo", UPPER_CAMEL.to(LOWER_HYPHEN, "Foo")); assertEquals("foo-bar", UPPER_CAMEL.to(LOWER_HYPHEN, "FooBar")); } public void testUpperCamelToLowerUnderscore() { assertEquals("foo", UPPER_CAMEL.to(LOWER_UNDERSCORE, "Foo")); assertEquals("foo_bar", UPPER_CAMEL.to(LOWER_UNDERSCORE, "FooBar")); } public void testUpperCamelToLowerCamel() { assertEquals("foo", UPPER_CAMEL.to(LOWER_CAMEL, "Foo")); assertEquals("fooBar", UPPER_CAMEL.to(LOWER_CAMEL, "FooBar")); assertEquals("hTTP", UPPER_CAMEL.to(LOWER_CAMEL, "HTTP")); } public void testUpperCamelToUpperCamel() { assertEquals("Foo", UPPER_CAMEL.to(UPPER_CAMEL, "Foo")); assertEquals("FooBar", UPPER_CAMEL.to(UPPER_CAMEL, "FooBar")); } public void testUpperCamelToUpperUnderscore() { assertEquals("FOO", UPPER_CAMEL.to(UPPER_UNDERSCORE, "Foo")); assertEquals("FOO_BAR", UPPER_CAMEL.to(UPPER_UNDERSCORE, "FooBar")); assertEquals("H_T_T_P", UPPER_CAMEL.to(UPPER_UNDERSCORE, "HTTP")); assertEquals("H__T__T__P", UPPER_CAMEL.to(UPPER_UNDERSCORE, "H_T_T_P")); } public void testUpperUnderscoreToLowerHyphen() { assertEquals("foo", UPPER_UNDERSCORE.to(LOWER_HYPHEN, "FOO")); assertEquals("foo-bar", UPPER_UNDERSCORE.to(LOWER_HYPHEN, "FOO_BAR")); } public void testUpperUnderscoreToLowerUnderscore() { assertEquals("foo", UPPER_UNDERSCORE.to(LOWER_UNDERSCORE, "FOO")); assertEquals("foo_bar", UPPER_UNDERSCORE.to(LOWER_UNDERSCORE, "FOO_BAR")); } public void testUpperUnderscoreToLowerCamel() { assertEquals("foo", UPPER_UNDERSCORE.to(LOWER_CAMEL, "FOO")); assertEquals("fooBar", UPPER_UNDERSCORE.to(LOWER_CAMEL, "FOO_BAR")); } public void testUpperUnderscoreToUpperCamel() { assertEquals("Foo", UPPER_UNDERSCORE.to(UPPER_CAMEL, "FOO")); assertEquals("FooBar", UPPER_UNDERSCORE.to(UPPER_CAMEL, "FOO_BAR")); assertEquals("HTTP", UPPER_UNDERSCORE.to(UPPER_CAMEL, "H_T_T_P")); } public void testUpperUnderscoreToUpperUnderscore() { assertEquals("FOO", UPPER_UNDERSCORE.to(UPPER_UNDERSCORE, "FOO")); assertEquals("FOO_BAR", UPPER_UNDERSCORE.to(UPPER_UNDERSCORE, "FOO_BAR")); } }
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 * diOBJECTibuted under the License is diOBJECTibuted on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.base.Equivalence.Wrapper; import com.google.common.collect.ImmutableList; import com.google.common.testing.EqualsTester; import com.google.common.testing.EquivalenceTester; import junit.framework.TestCase; /** * Unit test for {@link Equivalence}. * * @author Jige Yu */ @GwtCompatible(emulated = true) public class EquivalenceTest extends TestCase { @SuppressWarnings("unchecked") // Iterable<String>... public void testPairwiseEquivalent() { EquivalenceTester.of(Equivalence.equals().<String>pairwise()) .addEquivalenceGroup(ImmutableList.<String>of()) .addEquivalenceGroup(ImmutableList.of("a")) .addEquivalenceGroup(ImmutableList.of("b")) .addEquivalenceGroup(ImmutableList.of("a", "b"), ImmutableList.of("a", "b")) .test(); } public void testPairwiseEquivalent_equals() { new EqualsTester() .addEqualityGroup(Equivalence.equals().pairwise(), Equivalence.equals().pairwise()) .addEqualityGroup(Equivalence.identity().pairwise()) .testEquals(); } private enum LengthFunction implements Function<String, Integer> { INSTANCE; @Override public Integer apply(String input) { return input.length(); } } private static final Equivalence<String> LENGTH_EQUIVALENCE = Equivalence.equals() .onResultOf(LengthFunction.INSTANCE); public void testWrap() { new EqualsTester() .addEqualityGroup( LENGTH_EQUIVALENCE.wrap("hello"), LENGTH_EQUIVALENCE.wrap("hello"), LENGTH_EQUIVALENCE.wrap("world")) .addEqualityGroup( LENGTH_EQUIVALENCE.wrap("hi"), LENGTH_EQUIVALENCE.wrap("yo")) .addEqualityGroup( LENGTH_EQUIVALENCE.wrap(null), LENGTH_EQUIVALENCE.wrap(null)) .addEqualityGroup(Equivalence.equals().wrap("hello")) .addEqualityGroup(Equivalence.equals().wrap(null)) .testEquals(); } public void testWrap_get() { String test = "test"; Wrapper<String> wrapper = LENGTH_EQUIVALENCE.wrap(test); assertSame(test, wrapper.get()); } private static class IntValue { private final int value; IntValue(int value) { this.value = value; } @Override public String toString() { return "value = " + value; } } public void testOnResultOf() { EquivalenceTester.of(Equivalence.equals().onResultOf(Functions.toStringFunction())) .addEquivalenceGroup(new IntValue(1), new IntValue(1)) .addEquivalenceGroup(new IntValue(2)) .test(); } public void testOnResultOf_equals() { new EqualsTester() .addEqualityGroup( Equivalence.identity().onResultOf(Functions.toStringFunction()), Equivalence.identity().onResultOf(Functions.toStringFunction())) .addEqualityGroup(Equivalence.equals().onResultOf(Functions.toStringFunction())) .addEqualityGroup(Equivalence.identity().onResultOf(Functions.identity())) .testEquals(); } public void testEquivalentTo() { Predicate<Object> equalTo1 = Equivalence.equals().equivalentTo("1"); assertTrue(equalTo1.apply("1")); assertFalse(equalTo1.apply("2")); assertFalse(equalTo1.apply(null)); Predicate<Object> isNull = Equivalence.equals().equivalentTo(null); assertFalse(isNull.apply("1")); assertFalse(isNull.apply("2")); assertTrue(isNull.apply(null)); new EqualsTester() .addEqualityGroup(equalTo1, Equivalence.equals().equivalentTo("1")) .addEqualityGroup(isNull) .addEqualityGroup(Equivalence.identity().equivalentTo("1")) .testEquals(); } public void testEqualsEquivalent() { EquivalenceTester.of(Equivalence.equals()) .addEquivalenceGroup(new Integer(42), 42) .addEquivalenceGroup("a") .test(); } public void testIdentityEquivalent() { EquivalenceTester.of(Equivalence.identity()) .addEquivalenceGroup(new Integer(42)) .addEquivalenceGroup(new Integer(42)) .addEquivalenceGroup("a") .test(); } public void testEquals() { new EqualsTester() .addEqualityGroup(Equivalence.equals(), Equivalence.equals()) .addEqualityGroup(Equivalence.identity(), Equivalence.identity()) .testEquals(); } }
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 static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import junit.framework.TestCase; import java.util.Collections; import java.util.List; import java.util.Set; /** * Unit test for {@link Optional}. * * @author Kurt Alfred Kluever */ @GwtCompatible(emulated = true) public final class OptionalTest extends TestCase { public void testAbsent() { Optional<String> optionalName = Optional.absent(); assertFalse(optionalName.isPresent()); } public void testOf() { assertEquals("training", Optional.of("training").get()); } public void testOf_null() { try { Optional.of(null); fail(); } catch (NullPointerException expected) { } } public void testFromNullable() { Optional<String> optionalName = Optional.fromNullable("bob"); assertEquals("bob", optionalName.get()); } public void testFromNullable_null() { // not promised by spec, but easier to test assertSame(Optional.absent(), Optional.fromNullable(null)); } public void testIsPresent_no() { assertFalse(Optional.absent().isPresent()); } public void testIsPresent_yes() { assertTrue(Optional.of("training").isPresent()); } public void testGet_absent() { Optional<String> optional = Optional.absent(); try { optional.get(); fail(); } catch (IllegalStateException expected) { } } public void testGet_present() { assertEquals("training", Optional.of("training").get()); } public void testOr_T_present() { assertEquals("a", Optional.of("a").or("default")); } public void testOr_T_absent() { assertEquals("default", Optional.absent().or("default")); } public void testOr_supplier_present() { assertEquals("a", Optional.of("a").or(Suppliers.ofInstance("fallback"))); } public void testOr_supplier_absent() { assertEquals("fallback", Optional.absent().or(Suppliers.ofInstance("fallback"))); } public void testOr_nullSupplier_absent() { Supplier<Object> nullSupplier = Suppliers.ofInstance(null); Optional<Object> absentOptional = Optional.absent(); try { absentOptional.or(nullSupplier); fail(); } catch (NullPointerException expected) { } } public void testOr_nullSupplier_present() { Supplier<String> nullSupplier = Suppliers.ofInstance(null); assertEquals("a", Optional.of("a").or(nullSupplier)); } public void testOr_Optional_present() { assertEquals(Optional.of("a"), Optional.of("a").or(Optional.of("fallback"))); } public void testOr_Optional_absent() { assertEquals(Optional.of("fallback"), Optional.absent().or(Optional.of("fallback"))); } public void testOrNull_present() { assertEquals("a", Optional.of("a").orNull()); } public void testOrNull_absent() { assertNull(Optional.absent().orNull()); } public void testAsSet_present() { Set<String> expected = Collections.singleton("a"); assertEquals(expected, Optional.of("a").asSet()); } public void testAsSet_absent() { assertTrue("Returned set should be empty", Optional.absent().asSet().isEmpty()); } public void testAsSet_presentIsImmutable() { Set<String> presentAsSet = Optional.of("a").asSet(); try { presentAsSet.add("b"); fail(); } catch (UnsupportedOperationException expected) { } } public void testAsSet_absentIsImmutable() { Set<Object> absentAsSet = Optional.absent().asSet(); try { absentAsSet.add("foo"); fail(); } catch (UnsupportedOperationException expected) { } } public void testTransform_absent() { assertEquals(Optional.absent(), Optional.absent().transform(Functions.identity())); assertEquals(Optional.absent(), Optional.absent().transform(Functions.toStringFunction())); } public void testTransform_presentIdentity() { assertEquals(Optional.of("a"), Optional.of("a").transform(Functions.identity())); } public void testTransform_presentToString() { assertEquals(Optional.of("42"), Optional.of(42).transform(Functions.toStringFunction())); } public void testTransform_present_functionReturnsNull() { try { Optional.of("a").transform( new Function<String, String>() { @Override public String apply(String input) { return null; } }); fail("Should throw if Function returns null."); } catch (NullPointerException expected) { } } public void testTransform_abssent_functionReturnsNull() { assertEquals(Optional.absent(), Optional.absent().transform( new Function<Object, Object>() { @Override public Object apply(Object input) { return null; } })); } // TODO(kevinb): use EqualsTester public void testEqualsAndHashCode_absent() { assertEquals(Optional.<String>absent(), Optional.<Integer>absent()); assertEquals(Optional.absent().hashCode(), Optional.absent().hashCode()); } public void testEqualsAndHashCode_present() { assertEquals(Optional.of("training"), Optional.of("training")); assertFalse(Optional.of("a").equals(Optional.of("b"))); assertFalse(Optional.of("a").equals(Optional.absent())); assertEquals(Optional.of("training").hashCode(), Optional.of("training").hashCode()); } public void testToString_absent() { assertEquals("Optional.absent()", Optional.absent().toString()); } public void testToString_present() { assertEquals("Optional.of(training)", Optional.of("training").toString()); } public void testPresentInstances_allPresent() { List<Optional<String>> optionals = ImmutableList.of(Optional.of("a"), Optional.of("b"), Optional.of("c")); ASSERT.that(Optional.presentInstances(optionals)).iteratesOverSequence("a", "b", "c"); } public void testPresentInstances_allAbsent() { List<Optional<Object>> optionals = ImmutableList.of(Optional.absent(), Optional.absent()); ASSERT.that(Optional.presentInstances(optionals)).isEmpty(); } public void testPresentInstances_somePresent() { List<Optional<String>> optionals = ImmutableList.of(Optional.of("a"), Optional.<String>absent(), Optional.of("c")); ASSERT.that(Optional.presentInstances(optionals)).iteratesOverSequence("a", "c"); } public void testPresentInstances_callingIteratorTwice() { List<Optional<String>> optionals = ImmutableList.of(Optional.of("a"), Optional.<String>absent(), Optional.of("c")); Iterable<String> onlyPresent = Optional.presentInstances(optionals); ASSERT.that(onlyPresent).iteratesOverSequence("a", "c"); ASSERT.that(onlyPresent).iteratesOverSequence("a", "c"); } public void testPresentInstances_wildcards() { List<Optional<? extends Number>> optionals = ImmutableList.<Optional<? extends Number>>of(Optional.<Double>absent(), Optional.of(2)); Iterable<Number> onlyPresent = Optional.presentInstances(optionals); ASSERT.that(onlyPresent).iteratesOverSequence(2); } private static Optional<Integer> getSomeOptionalInt() { return Optional.of(1); } private static FluentIterable<? extends Number> getSomeNumbers() { return FluentIterable.from(ImmutableList.<Number>of()); } /* * The following tests demonstrate the shortcomings of or() and test that the casting workaround * mentioned in the method Javadoc does in fact compile. */ public void testSampleCodeError1() { Optional<Integer> optionalInt = getSomeOptionalInt(); // Number value = optionalInt.or(0.5); // error } public void testSampleCodeError2() { FluentIterable<? extends Number> numbers = getSomeNumbers(); Optional<? extends Number> first = numbers.first(); // Number value = first.or(0.5); // error } @SuppressWarnings("unchecked") // safe covariant cast public void testSampleCodeFine1() { Optional<Number> optionalInt = (Optional) getSomeOptionalInt(); Number value = optionalInt.or(0.5); // fine } @SuppressWarnings("unchecked") // safe covariant cast public void testSampleCodeFine2() { FluentIterable<? extends Number> numbers = getSomeNumbers(); Optional<Number> first = (Optional) numbers.first(); Number value = first.or(0.5); // fine } }
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 org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import junit.framework.TestCase; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.Map; /** * @author Julien Silland */ @GwtCompatible(emulated = true) public class SplitterTest extends TestCase { private static final Splitter COMMA_SPLITTER = Splitter.on(','); public void testSplitNullString() { try { COMMA_SPLITTER.split(null); fail(); } catch (NullPointerException expected) { } } public void testCharacterSimpleSplit() { String simple = "a,b,c"; Iterable<String> letters = COMMA_SPLITTER.split(simple); ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); } /** * All of the infrastructure of split and splitToString is identical, so we * do one test of splitToString. All other cases should be covered by testing * of split. * * <p>TODO(user): It would be good to make all the relevant tests run on * both split and splitToString automatically. */ public void testCharacterSimpleSplitToList() { String simple = "a,b,c"; List<String> letters = COMMA_SPLITTER.splitToList(simple); ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); } public void testToString() { assertEquals("[]", Splitter.on(',').split("").toString()); assertEquals("[a, b, c]", Splitter.on(',').split("a,b,c").toString()); assertEquals("[yam, bam, jam, ham]", Splitter.on(", ").split("yam, bam, jam, ham").toString()); } public void testCharacterSimpleSplitWithNoDelimiter() { String simple = "a,b,c"; Iterable<String> letters = Splitter.on('.').split(simple); ASSERT.that(letters).iteratesOverSequence("a,b,c"); } public void testCharacterSplitWithDoubleDelimiter() { String doubled = "a,,b,c"; Iterable<String> letters = COMMA_SPLITTER.split(doubled); ASSERT.that(letters).iteratesOverSequence("a", "", "b", "c"); } public void testCharacterSplitWithDoubleDelimiterAndSpace() { String doubled = "a,, b,c"; Iterable<String> letters = COMMA_SPLITTER.split(doubled); ASSERT.that(letters).iteratesOverSequence("a", "", " b", "c"); } public void testCharacterSplitWithTrailingDelimiter() { String trailing = "a,b,c,"; Iterable<String> letters = COMMA_SPLITTER.split(trailing); ASSERT.that(letters).iteratesOverSequence("a", "b", "c", ""); } public void testCharacterSplitWithLeadingDelimiter() { String leading = ",a,b,c"; Iterable<String> letters = COMMA_SPLITTER.split(leading); ASSERT.that(letters).iteratesOverSequence("", "a", "b", "c"); } public void testCharacterSplitWithMulitpleLetters() { Iterable<String> testCharacteringMotto = Splitter.on('-').split( "Testing-rocks-Debugging-sucks"); ASSERT.that(testCharacteringMotto).iteratesOverSequence( "Testing", "rocks", "Debugging", "sucks"); } public void testCharacterSplitWithMatcherDelimiter() { Iterable<String> testCharacteringMotto = Splitter .on(CharMatcher.WHITESPACE) .split("Testing\nrocks\tDebugging sucks"); ASSERT.that(testCharacteringMotto).iteratesOverSequence( "Testing", "rocks", "Debugging", "sucks"); } public void testCharacterSplitWithDoubleDelimiterOmitEmptyStrings() { String doubled = "a..b.c"; Iterable<String> letters = Splitter.on('.') .omitEmptyStrings().split(doubled); ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); } public void testCharacterSplitEmptyToken() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on('.').trimResults() .split(emptyToken); ASSERT.that(letters).iteratesOverSequence("a", "", "c"); } public void testCharacterSplitEmptyTokenOmitEmptyStrings() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on('.') .omitEmptyStrings().trimResults().split(emptyToken); ASSERT.that(letters).iteratesOverSequence("a", "c"); } public void testCharacterSplitOnEmptyString() { Iterable<String> nothing = Splitter.on('.').split(""); ASSERT.that(nothing).iteratesOverSequence(""); } public void testCharacterSplitOnEmptyStringOmitEmptyStrings() { ASSERT.that(Splitter.on('.').omitEmptyStrings().split("")).isEmpty(); } public void testCharacterSplitOnOnlyDelimiter() { Iterable<String> blankblank = Splitter.on('.').split("."); ASSERT.that(blankblank).iteratesOverSequence("", ""); } public void testCharacterSplitOnOnlyDelimitersOmitEmptyStrings() { Iterable<String> empty = Splitter.on('.').omitEmptyStrings().split("..."); ASSERT.that(empty); } public void testCharacterSplitWithTrim() { String jacksons = "arfo(Marlon)aorf, (Michael)orfa, afro(Jackie)orfa, " + "ofar(Jemaine), aff(Tito)"; Iterable<String> family = COMMA_SPLITTER .trimResults(CharMatcher.anyOf("afro").or(CharMatcher.WHITESPACE)) .split(jacksons); ASSERT.that(family).iteratesOverSequence( "(Marlon)", "(Michael)", "(Jackie)", "(Jemaine)", "(Tito)"); } public void testStringSimpleSplit() { String simple = "a,b,c"; Iterable<String> letters = Splitter.on(',').split(simple); ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); } public void testStringSimpleSplitWithNoDelimiter() { String simple = "a,b,c"; Iterable<String> letters = Splitter.on('.').split(simple); ASSERT.that(letters).iteratesOverSequence("a,b,c"); } public void testStringSplitWithDoubleDelimiter() { String doubled = "a,,b,c"; Iterable<String> letters = Splitter.on(',').split(doubled); ASSERT.that(letters).iteratesOverSequence("a", "", "b", "c"); } public void testStringSplitWithDoubleDelimiterAndSpace() { String doubled = "a,, b,c"; Iterable<String> letters = Splitter.on(',').split(doubled); ASSERT.that(letters).iteratesOverSequence("a", "", " b", "c"); } public void testStringSplitWithTrailingDelimiter() { String trailing = "a,b,c,"; Iterable<String> letters = Splitter.on(',').split(trailing); ASSERT.that(letters).iteratesOverSequence("a", "b", "c", ""); } public void testStringSplitWithLeadingDelimiter() { String leading = ",a,b,c"; Iterable<String> letters = Splitter.on(',').split(leading); ASSERT.that(letters).iteratesOverSequence("", "a", "b", "c"); } public void testStringSplitWithMultipleLetters() { Iterable<String> testStringingMotto = Splitter.on('-').split( "Testing-rocks-Debugging-sucks"); ASSERT.that(testStringingMotto).iteratesOverSequence( "Testing", "rocks", "Debugging", "sucks"); } public void testStringSplitWithDoubleDelimiterOmitEmptyStrings() { String doubled = "a..b.c"; Iterable<String> letters = Splitter.on('.') .omitEmptyStrings().split(doubled); ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); } public void testStringSplitEmptyToken() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on('.').trimResults() .split(emptyToken); ASSERT.that(letters).iteratesOverSequence("a", "", "c"); } public void testStringSplitEmptyTokenOmitEmptyStrings() { String emptyToken = "a. .c"; Iterable<String> letters = Splitter.on('.') .omitEmptyStrings().trimResults().split(emptyToken); ASSERT.that(letters).iteratesOverSequence("a", "c"); } public void testStringSplitWithLongDelimiter() { String longDelimiter = "a, b, c"; Iterable<String> letters = Splitter.on(", ").split(longDelimiter); ASSERT.that(letters).iteratesOverSequence("a", "b", "c"); } public void testStringSplitWithLongLeadingDelimiter() { String longDelimiter = ", a, b, c"; Iterable<String> letters = Splitter.on(", ").split(longDelimiter); ASSERT.that(letters).iteratesOverSequence("", "a", "b", "c"); } public void testStringSplitWithLongTrailingDelimiter() { String longDelimiter = "a, b, c, "; Iterable<String> letters = Splitter.on(", ").split(longDelimiter); ASSERT.that(letters).iteratesOverSequence("a", "b", "c", ""); } public void testStringSplitWithDelimiterSubstringInValue() { String fourCommasAndFourSpaces = ",,,, "; Iterable<String> threeCommasThenThreeSpaces = Splitter.on(", ").split( fourCommasAndFourSpaces); ASSERT.that(threeCommasThenThreeSpaces).iteratesOverSequence(",,,", " "); } public void testStringSplitWithEmptyString() { try { Splitter.on(""); fail(); } catch (IllegalArgumentException expected) { } } public void testStringSplitOnEmptyString() { Iterable<String> notMuch = Splitter.on('.').split(""); ASSERT.that(notMuch).iteratesOverSequence(""); } public void testStringSplitOnEmptyStringOmitEmptyString() { ASSERT.that(Splitter.on('.').omitEmptyStrings().split("")).isEmpty(); } public void testStringSplitOnOnlyDelimiter() { Iterable<String> blankblank = Splitter.on('.').split("."); ASSERT.that(blankblank).iteratesOverSequence("", ""); } public void testStringSplitOnOnlyDelimitersOmitEmptyStrings() { Iterable<String> empty = Splitter.on('.').omitEmptyStrings().split("..."); ASSERT.that(empty).isEmpty(); } public void testStringSplitWithTrim() { String jacksons = "arfo(Marlon)aorf, (Michael)orfa, afro(Jackie)orfa, " + "ofar(Jemaine), aff(Tito)"; Iterable<String> family = Splitter.on(',') .trimResults(CharMatcher.anyOf("afro").or(CharMatcher.WHITESPACE)) .split(jacksons); ASSERT.that(family).iteratesOverSequence( "(Marlon)", "(Michael)", "(Jackie)", "(Jemaine)", "(Tito)"); } // TODO(kevinb): the name of this method suggests it might not actually be testing what it // intends to be testing? public void testSplitterIterableIsUnmodifiable_char() { assertIteratorIsUnmodifiable(COMMA_SPLITTER.split("a,b").iterator()); } public void testSplitterIterableIsUnmodifiable_string() { assertIteratorIsUnmodifiable(Splitter.on(',').split("a,b").iterator()); } private void assertIteratorIsUnmodifiable(Iterator<?> iterator) { iterator.next(); try { iterator.remove(); fail(); } catch (UnsupportedOperationException expected) { } } public void testSplitterIterableIsLazy_char() { assertSplitterIterableIsLazy(COMMA_SPLITTER); } public void testSplitterIterableIsLazy_string() { assertSplitterIterableIsLazy(Splitter.on(',')); } /** * This test really pushes the boundaries of what we support. In general the * splitter's behaviour is not well defined if the char sequence it's * splitting is mutated during iteration. */ private void assertSplitterIterableIsLazy(Splitter splitter) { StringBuilder builder = new StringBuilder(); Iterator<String> iterator = splitter.split(builder).iterator(); builder.append("A,"); assertEquals("A", iterator.next()); builder.append("B,"); assertEquals("B", iterator.next()); builder.append("C"); assertEquals("C", iterator.next()); assertFalse(iterator.hasNext()); } public void testFixedLengthSimpleSplit() { String simple = "abcde"; Iterable<String> letters = Splitter.fixedLength(2).split(simple); ASSERT.that(letters).iteratesOverSequence("ab", "cd", "e"); } public void testFixedLengthSplitEqualChunkLength() { String simple = "abcdef"; Iterable<String> letters = Splitter.fixedLength(2).split(simple); ASSERT.that(letters).iteratesOverSequence("ab", "cd", "ef"); } public void testFixedLengthSplitOnlyOneChunk() { String simple = "abc"; Iterable<String> letters = Splitter.fixedLength(3).split(simple); ASSERT.that(letters).iteratesOverSequence("abc"); } public void testFixedLengthSplitSmallerString() { String simple = "ab"; Iterable<String> letters = Splitter.fixedLength(3).split(simple); ASSERT.that(letters).iteratesOverSequence("ab"); } public void testFixedLengthSplitEmptyString() { String simple = ""; Iterable<String> letters = Splitter.fixedLength(3).split(simple); ASSERT.that(letters).iteratesOverSequence(""); } public void testFixedLengthSplitEmptyStringWithOmitEmptyStrings() { ASSERT.that(Splitter.fixedLength(3).omitEmptyStrings().split("")).isEmpty(); } public void testFixedLengthSplitIntoChars() { String simple = "abcd"; Iterable<String> letters = Splitter.fixedLength(1).split(simple); ASSERT.that(letters).iteratesOverSequence("a", "b", "c", "d"); } public void testFixedLengthSplitZeroChunkLen() { try { Splitter.fixedLength(0); fail(); } catch (IllegalArgumentException expected) { } } public void testFixedLengthSplitNegativeChunkLen() { try { Splitter.fixedLength(-1); fail(); } catch (IllegalArgumentException expected) { } } public void testLimitLarge() { String simple = "abcd"; Iterable<String> letters = Splitter.fixedLength(1).limit(100).split(simple); ASSERT.that(letters).iteratesOverSequence("a", "b", "c", "d"); } public void testLimitOne() { String simple = "abcd"; Iterable<String> letters = Splitter.fixedLength(1).limit(1).split(simple); ASSERT.that(letters).iteratesOverSequence("abcd"); } public void testLimitFixedLength() { String simple = "abcd"; Iterable<String> letters = Splitter.fixedLength(1).limit(2).split(simple); ASSERT.that(letters).iteratesOverSequence("a", "bcd"); } public void testLimitSeparator() { String simple = "a,b,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(2).split(simple); ASSERT.that(items).iteratesOverSequence("a", "b,c,d"); } public void testLimitExtraSeparators() { String text = "a,,,b,,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(2).split(text); ASSERT.that(items).iteratesOverSequence("a", ",,b,,c,d"); } public void testLimitExtraSeparatorsOmitEmpty() { String text = "a,,,b,,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(2).omitEmptyStrings().split(text); ASSERT.that(items).iteratesOverSequence("a", "b,,c,d"); } public void testLimitExtraSeparatorsOmitEmpty3() { String text = "a,,,b,,c,d"; Iterable<String> items = COMMA_SPLITTER.limit(3).omitEmptyStrings().split(text); ASSERT.that(items).iteratesOverSequence("a", "b", "c,d"); } public void testLimitExtraSeparatorsTrim() { String text = ",,a,, , b ,, c,d "; Iterable<String> items = COMMA_SPLITTER.limit(2).omitEmptyStrings().trimResults().split(text); ASSERT.that(items).iteratesOverSequence("a", "b ,, c,d"); } public void testLimitExtraSeparatorsTrim3() { String text = ",,a,, , b ,, c,d "; Iterable<String> items = COMMA_SPLITTER.limit(3).omitEmptyStrings().trimResults().split(text); ASSERT.that(items).iteratesOverSequence("a", "b", "c,d"); } public void testLimitExtraSeparatorsTrim1() { String text = ",,a,, , b ,, c,d "; Iterable<String> items = COMMA_SPLITTER.limit(1).omitEmptyStrings().trimResults().split(text); ASSERT.that(items).iteratesOverSequence("a,, , b ,, c,d"); } public void testLimitExtraSeparatorsTrim1NoOmit() { String text = ",,a,, , b ,, c,d "; Iterable<String> items = COMMA_SPLITTER.limit(1).trimResults().split(text); ASSERT.that(items).iteratesOverSequence(",,a,, , b ,, c,d"); } public void testLimitExtraSeparatorsTrim1Empty() { String text = ""; Iterable<String> items = COMMA_SPLITTER.limit(1).split(text); ASSERT.that(items).iteratesOverSequence(""); } public void testLimitExtraSeparatorsTrim1EmptyOmit() { String text = ""; Iterable<String> items = COMMA_SPLITTER.omitEmptyStrings().limit(1).split(text); ASSERT.that(items).isEmpty(); } @SuppressWarnings("ReturnValueIgnored") public void testInvalidZeroLimit() { try { COMMA_SPLITTER.limit(0); fail(); } catch (IllegalArgumentException expected) { } } private static <E> List<E> asList(Collection<E> collection) { return ImmutableList.copyOf(collection); } public void testMapSplitter_trimmedBoth() { Map<String, String> m = COMMA_SPLITTER .trimResults() .withKeyValueSeparator(Splitter.on(':').trimResults()) .split("boy : tom , girl: tina , cat : kitty , dog: tommy "); ImmutableMap<String, String> expected = ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"); ASSERT.that(m).isEqualTo(expected); ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet())); } public void testMapSplitter_trimmedEntries() { Map<String, String> m = COMMA_SPLITTER .trimResults() .withKeyValueSeparator(":") .split("boy : tom , girl: tina , cat : kitty , dog: tommy "); ImmutableMap<String, String> expected = ImmutableMap.of("boy ", " tom", "girl", " tina", "cat ", " kitty", "dog", " tommy"); ASSERT.that(m).isEqualTo(expected); ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet())); } public void testMapSplitter_trimmedKeyValue() { Map<String, String> m = COMMA_SPLITTER.withKeyValueSeparator(Splitter.on(':').trimResults()).split( "boy : tom , girl: tina , cat : kitty , dog: tommy "); ImmutableMap<String, String> expected = ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"); ASSERT.that(m).isEqualTo(expected); ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet())); } public void testMapSplitter_notTrimmed() { Map<String, String> m = COMMA_SPLITTER.withKeyValueSeparator(":").split( " boy:tom , girl: tina , cat :kitty , dog: tommy "); ImmutableMap<String, String> expected = ImmutableMap.of(" boy", "tom ", " girl", " tina ", " cat ", "kitty ", " dog", " tommy "); ASSERT.that(m).isEqualTo(expected); ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet())); } public void testMapSplitter_CharacterSeparator() { // try different delimiters. Map<String, String> m = Splitter .on(",") .withKeyValueSeparator(':') .split("boy:tom,girl:tina,cat:kitty,dog:tommy"); ImmutableMap<String, String> expected = ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"); ASSERT.that(m).isEqualTo(expected); ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet())); } public void testMapSplitter_multiCharacterSeparator() { // try different delimiters. Map<String, String> m = Splitter .on(",") .withKeyValueSeparator(":^&") .split("boy:^&tom,girl:^&tina,cat:^&kitty,dog:^&tommy"); ImmutableMap<String, String> expected = ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy"); ASSERT.that(m).isEqualTo(expected); ASSERT.that(asList(m.entrySet())).is(asList(expected.entrySet())); } @SuppressWarnings("ReturnValueIgnored") public void testMapSplitter_emptySeparator() { try { COMMA_SPLITTER.withKeyValueSeparator(""); fail(); } catch (IllegalArgumentException expected) { } } public void testMapSplitter_malformedEntry() { try { COMMA_SPLITTER.withKeyValueSeparator("=").split("a=1,b,c=2"); fail(); } catch(IllegalArgumentException expected) { } } public void testMapSplitter_orderedResults() { Map<String, String> m = Splitter.on(',') .withKeyValueSeparator(":") .split("boy:tom,girl:tina,cat:kitty,dog:tommy"); ASSERT.that(m.keySet()).iteratesOverSequence("boy", "girl", "cat", "dog"); ASSERT.that(m).isEqualTo( ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy")); // try in a different order m = Splitter.on(',') .withKeyValueSeparator(":") .split("girl:tina,boy:tom,dog:tommy,cat:kitty"); ASSERT.that(m.keySet()).iteratesOverSequence("girl", "boy", "dog", "cat"); ASSERT.that(m).isEqualTo( ImmutableMap.of("boy", "tom", "girl", "tina", "cat", "kitty", "dog", "tommy")); } public void testMapSplitter_duplicateKeys() { try { Splitter.on(',').withKeyValueSeparator(":").split("a:1,b:2,a:3"); fail(); } catch (IllegalArgumentException expected) { } } }
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; /** * Unit test for {@link Preconditions}. * * @author Kevin Bourrillion * @author Jared Levy */ @GwtCompatible(emulated = true) public class PreconditionsTest extends TestCase { public void testCheckArgument_simple_success() { Preconditions.checkArgument(true); } public void testCheckArgument_simple_failure() { try { Preconditions.checkArgument(false); fail("no exception thrown"); } catch (IllegalArgumentException expected) { } } public void testCheckArgument_simpleMessage_success() { Preconditions.checkArgument(true, IGNORE_ME); } public void testCheckArgument_simpleMessage_failure() { try { Preconditions.checkArgument(false, new Message()); fail("no exception thrown"); } catch (IllegalArgumentException expected) { verifySimpleMessage(expected); } } public void testCheckArgument_nullMessage_failure() { try { Preconditions.checkArgument(false, null); fail("no exception thrown"); } catch (IllegalArgumentException expected) { assertEquals("null", expected.getMessage()); } } public void testCheckArgument_complexMessage_success() { Preconditions.checkArgument(true, "%s", IGNORE_ME); } public void testCheckArgument_complexMessage_failure() { try { Preconditions.checkArgument(false, FORMAT, 5); fail("no exception thrown"); } catch (IllegalArgumentException expected) { verifyComplexMessage(expected); } } public void testCheckState_simple_success() { Preconditions.checkState(true); } public void testCheckState_simple_failure() { try { Preconditions.checkState(false); fail("no exception thrown"); } catch (IllegalStateException expected) { } } public void testCheckState_simpleMessage_success() { Preconditions.checkState(true, IGNORE_ME); } public void testCheckState_simpleMessage_failure() { try { Preconditions.checkState(false, new Message()); fail("no exception thrown"); } catch (IllegalStateException expected) { verifySimpleMessage(expected); } } public void testCheckState_nullMessage_failure() { try { Preconditions.checkState(false, null); fail("no exception thrown"); } catch (IllegalStateException expected) { assertEquals("null", expected.getMessage()); } } public void testCheckState_complexMessage_success() { Preconditions.checkState(true, "%s", IGNORE_ME); } public void testCheckState_complexMessage_failure() { try { Preconditions.checkState(false, FORMAT, 5); fail("no exception thrown"); } catch (IllegalStateException expected) { verifyComplexMessage(expected); } } private static final String NON_NULL_STRING = "foo"; public void testCheckNotNull_simple_success() { String result = Preconditions.checkNotNull(NON_NULL_STRING); assertSame(NON_NULL_STRING, result); } public void testCheckNotNull_simple_failure() { try { Preconditions.checkNotNull(null); fail("no exception thrown"); } catch (NullPointerException expected) { } } public void testCheckNotNull_simpleMessage_success() { String result = Preconditions.checkNotNull(NON_NULL_STRING, IGNORE_ME); assertSame(NON_NULL_STRING, result); } public void testCheckNotNull_simpleMessage_failure() { try { Preconditions.checkNotNull(null, new Message()); fail("no exception thrown"); } catch (NullPointerException expected) { verifySimpleMessage(expected); } } public void testCheckNotNull_complexMessage_success() { String result = Preconditions.checkNotNull( NON_NULL_STRING, "%s", IGNORE_ME); assertSame(NON_NULL_STRING, result); } public void testCheckNotNull_complexMessage_failure() { try { Preconditions.checkNotNull(null, FORMAT, 5); fail("no exception thrown"); } catch (NullPointerException expected) { verifyComplexMessage(expected); } } public void testCheckElementIndex_ok() { assertEquals(0, Preconditions.checkElementIndex(0, 1)); assertEquals(0, Preconditions.checkElementIndex(0, 2)); assertEquals(1, Preconditions.checkElementIndex(1, 2)); } public void testCheckElementIndex_badSize() { try { Preconditions.checkElementIndex(1, -1); fail(); } catch (IllegalArgumentException expected) { // don't care what the message text is, as this is an invalid usage of // the Preconditions class, unlike all the other exceptions it throws } } public void testCheckElementIndex_negative() { try { Preconditions.checkElementIndex(-1, 1); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("index (-1) must not be negative", expected.getMessage()); } } public void testCheckElementIndex_tooHigh() { try { Preconditions.checkElementIndex(1, 1); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("index (1) must be less than size (1)", expected.getMessage()); } } public void testCheckElementIndex_withDesc_negative() { try { Preconditions.checkElementIndex(-1, 1, "foo"); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("foo (-1) must not be negative", expected.getMessage()); } } public void testCheckElementIndex_withDesc_tooHigh() { try { Preconditions.checkElementIndex(1, 1, "foo"); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("foo (1) must be less than size (1)", expected.getMessage()); } } public void testCheckPositionIndex_ok() { assertEquals(0, Preconditions.checkPositionIndex(0, 0)); assertEquals(0, Preconditions.checkPositionIndex(0, 1)); assertEquals(1, Preconditions.checkPositionIndex(1, 1)); } public void testCheckPositionIndex_badSize() { try { Preconditions.checkPositionIndex(1, -1); fail(); } catch (IllegalArgumentException expected) { // don't care what the message text is, as this is an invalid usage of // the Preconditions class, unlike all the other exceptions it throws } } public void testCheckPositionIndex_negative() { try { Preconditions.checkPositionIndex(-1, 1); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("index (-1) must not be negative", expected.getMessage()); } } public void testCheckPositionIndex_tooHigh() { try { Preconditions.checkPositionIndex(2, 1); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("index (2) must not be greater than size (1)", expected.getMessage()); } } public void testCheckPositionIndex_withDesc_negative() { try { Preconditions.checkPositionIndex(-1, 1, "foo"); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("foo (-1) must not be negative", expected.getMessage()); } } public void testCheckPositionIndex_withDesc_tooHigh() { try { Preconditions.checkPositionIndex(2, 1, "foo"); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("foo (2) must not be greater than size (1)", expected.getMessage()); } } public void testCheckPositionIndexes_ok() { Preconditions.checkPositionIndexes(0, 0, 0); Preconditions.checkPositionIndexes(0, 0, 1); Preconditions.checkPositionIndexes(0, 1, 1); Preconditions.checkPositionIndexes(1, 1, 1); } public void testCheckPositionIndexes_badSize() { try { Preconditions.checkPositionIndexes(1, 1, -1); fail(); } catch (IllegalArgumentException expected) { } } public void testCheckPositionIndex_startNegative() { try { Preconditions.checkPositionIndexes(-1, 1, 1); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("start index (-1) must not be negative", expected.getMessage()); } } public void testCheckPositionIndexes_endTooHigh() { try { Preconditions.checkPositionIndexes(0, 2, 1); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("end index (2) must not be greater than size (1)", expected.getMessage()); } } public void testCheckPositionIndexes_reversed() { try { Preconditions.checkPositionIndexes(1, 0, 1); fail(); } catch (IndexOutOfBoundsException expected) { assertEquals("end index (0) must not be less than start index (1)", expected.getMessage()); } } public void testFormat() { assertEquals("%s", Preconditions.format("%s")); assertEquals("5", Preconditions.format("%s", 5)); assertEquals("foo [5]", Preconditions.format("foo", 5)); assertEquals("foo [5, 6, 7]", Preconditions.format("foo", 5, 6, 7)); assertEquals("%s 1 2", Preconditions.format("%s %s %s", "%s", 1, 2)); assertEquals(" [5, 6]", Preconditions.format("", 5, 6)); assertEquals("123", Preconditions.format("%s%s%s", 1, 2, 3)); assertEquals("1%s%s", Preconditions.format("%s%s%s", 1)); assertEquals("5 + 6 = 11", Preconditions.format("%s + 6 = 11", 5)); assertEquals("5 + 6 = 11", Preconditions.format("5 + %s = 11", 6)); assertEquals("5 + 6 = 11", Preconditions.format("5 + 6 = %s", 11)); assertEquals("5 + 6 = 11", Preconditions.format("%s + %s = %s", 5, 6, 11)); assertEquals("null [null, null]", Preconditions.format("%s", null, null, null)); assertEquals("null [5, 6]", Preconditions.format(null, 5, 6)); } private static final Object IGNORE_ME = new Object() { @Override public String toString() { fail(); return null; } }; private static class Message { boolean invoked; @Override public String toString() { assertFalse(invoked); invoked = true; return "A message"; } } private static final String FORMAT = "I ate %s pies."; private static void verifySimpleMessage(Exception e) { assertEquals("A message", e.getMessage()); } private static void verifyComplexMessage(Exception e) { assertEquals("I ate 5 pies.", e.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.base; import com.google.common.annotations.GwtCompatible; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; /** * Tests for {@link Enums}. * * @author Steve McKay */ @GwtCompatible(emulated = true) public class EnumsTest extends TestCase { private enum TestEnum { CHEETO, HONDA, POODLE, } private enum OtherEnum {} public void testValueOfFunction() { Function<String, TestEnum> function = Enums.valueOfFunction(TestEnum.class); assertEquals(TestEnum.CHEETO, function.apply("CHEETO")); assertEquals(TestEnum.HONDA, function.apply("HONDA")); assertEquals(TestEnum.POODLE, function.apply("POODLE")); } public void testValueOfFunction_caseSensitive() { Function<String, TestEnum> function = Enums.valueOfFunction(TestEnum.class); assertNull(function.apply("cHEETO")); assertNull(function.apply("Honda")); assertNull(function.apply("poodlE")); } public void testValueOfFunction_nullWhenNoMatchingConstant() { Function<String, TestEnum> function = Enums.valueOfFunction(TestEnum.class); assertNull(function.apply("WOMBAT")); } public void testValueOfFunction_equals() { new EqualsTester() .addEqualityGroup( Enums.valueOfFunction(TestEnum.class), Enums.valueOfFunction(TestEnum.class)) .addEqualityGroup(Enums.valueOfFunction(OtherEnum.class)) .testEquals(); } public void testGetIfPresent() { assertEquals(Optional.of(TestEnum.CHEETO), Enums.getIfPresent(TestEnum.class, "CHEETO")); assertEquals(Optional.of(TestEnum.HONDA), Enums.getIfPresent(TestEnum.class, "HONDA")); assertEquals(Optional.of(TestEnum.POODLE), Enums.getIfPresent(TestEnum.class, "POODLE")); assertTrue(Enums.getIfPresent(TestEnum.class, "CHEETO").isPresent()); assertTrue(Enums.getIfPresent(TestEnum.class, "HONDA").isPresent()); assertTrue(Enums.getIfPresent(TestEnum.class, "POODLE").isPresent()); assertEquals(TestEnum.CHEETO, Enums.getIfPresent(TestEnum.class, "CHEETO").get()); assertEquals(TestEnum.HONDA, Enums.getIfPresent(TestEnum.class, "HONDA").get()); assertEquals(TestEnum.POODLE, Enums.getIfPresent(TestEnum.class, "POODLE").get()); } public void testGetIfPresent_caseSensitive() { assertFalse(Enums.getIfPresent(TestEnum.class, "cHEETO").isPresent()); assertFalse(Enums.getIfPresent(TestEnum.class, "Honda").isPresent()); assertFalse(Enums.getIfPresent(TestEnum.class, "poodlE").isPresent()); } public void testGetIfPresent_whenNoMatchingConstant() { assertEquals(Optional.absent(), Enums.getIfPresent(TestEnum.class, "WOMBAT")); } @Retention(RetentionPolicy.RUNTIME) private @interface ExampleAnnotation {} private enum AnEnum { @ExampleAnnotation FOO, BAR } }
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 com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; import java.nio.charset.Charset; /** * Unit test for {@link Charsets}. * * @author Mike Bostock */ @GwtCompatible(emulated = true) public class CharsetsTest extends TestCase { public void testUtf8() { assertEquals(Charset.forName("UTF-8"), Charsets.UTF_8); } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.Lists; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.io.Serializable; import java.util.ArrayList; import java.util.List; /** * Tests com.google.common.base.Suppliers. * * @author Laurence Gonsalves * @author Harry Heymann */ @GwtCompatible(emulated = true) public class SuppliersTest extends TestCase { public void testCompose() { Supplier<Integer> fiveSupplier = new Supplier<Integer>() { @Override public Integer get() { return 5; } }; Function<Number, Integer> intValueFunction = new Function<Number, Integer>() { @Override public Integer apply(Number x) { return x.intValue(); } }; Supplier<Integer> squareSupplier = Suppliers.compose(intValueFunction, fiveSupplier); assertEquals(Integer.valueOf(5), squareSupplier.get()); } public void testComposeWithLists() { Supplier<ArrayList<Integer>> listSupplier = new Supplier<ArrayList<Integer>>() { @Override public ArrayList<Integer> get() { return Lists.newArrayList(0); } }; Function<List<Integer>, List<Integer>> addElementFunction = new Function<List<Integer>, List<Integer>>() { @Override public List<Integer> apply(List<Integer> list) { ArrayList<Integer> result = Lists.newArrayList(list); result.add(1); return result; } }; Supplier<List<Integer>> addSupplier = Suppliers.compose(addElementFunction, listSupplier); List<Integer> result = addSupplier.get(); assertEquals(Integer.valueOf(0), result.get(0)); assertEquals(Integer.valueOf(1), result.get(1)); } static class CountingSupplier implements Supplier<Integer>, Serializable { private static final long serialVersionUID = 0L; transient int calls = 0; @Override public Integer get() { calls++; return calls * 10; } } public void testMemoize() { CountingSupplier countingSupplier = new CountingSupplier(); Supplier<Integer> memoizedSupplier = Suppliers.memoize(countingSupplier); checkMemoize(countingSupplier, memoizedSupplier); } public void testMemoize_redudantly() { CountingSupplier countingSupplier = new CountingSupplier(); Supplier<Integer> memoizedSupplier = Suppliers.memoize(countingSupplier); assertSame(memoizedSupplier, Suppliers.memoize(memoizedSupplier)); } private void checkMemoize( CountingSupplier countingSupplier, Supplier<Integer> memoizedSupplier) { // the underlying supplier hasn't executed yet assertEquals(0, countingSupplier.calls); assertEquals(10, (int) memoizedSupplier.get()); // now it has assertEquals(1, countingSupplier.calls); assertEquals(10, (int) memoizedSupplier.get()); // it still should only have executed once due to memoization assertEquals(1, countingSupplier.calls); } public void testMemoizeExceptionThrown() { Supplier<Integer> exceptingSupplier = new Supplier<Integer>() { @Override public Integer get() { throw new NullPointerException(); } }; Supplier<Integer> memoizedSupplier = Suppliers.memoize(exceptingSupplier); // call get() twice to make sure that memoization doesn't interfere // with throwing the exception for (int i = 0; i < 2; i++) { try { memoizedSupplier.get(); fail("failed to throw NullPointerException"); } catch (NullPointerException e) { // this is what should happen } } } public void testOfInstanceSuppliesSameInstance() { Object toBeSupplied = new Object(); Supplier<Object> objectSupplier = Suppliers.ofInstance(toBeSupplied); assertSame(toBeSupplied,objectSupplier.get()); assertSame(toBeSupplied,objectSupplier.get()); // idempotent } public void testOfInstanceSuppliesNull() { Supplier<Integer> nullSupplier = Suppliers.ofInstance(null); assertNull(nullSupplier.get()); } public void testSupplierFunction() { Supplier<Integer> supplier = Suppliers.ofInstance(14); Function<Supplier<Integer>, Integer> supplierFunction = Suppliers.supplierFunction(); assertEquals(14, (int) supplierFunction.apply(supplier)); } public void testOfInstance_equals() { new EqualsTester() .addEqualityGroup( Suppliers.ofInstance("foo"), Suppliers.ofInstance("foo")) .addEqualityGroup(Suppliers.ofInstance("bar")) .testEquals(); } public void testCompose_equals() { new EqualsTester() .addEqualityGroup( Suppliers.compose(Functions.constant(1), Suppliers.ofInstance("foo")), Suppliers.compose(Functions.constant(1), Suppliers.ofInstance("foo"))) .addEqualityGroup( Suppliers.compose(Functions.constant(2), Suppliers.ofInstance("foo"))) .addEqualityGroup( Suppliers.compose(Functions.constant(1), Suppliers.ofInstance("bar"))) .testEquals(); } }
Java
/* * Copyright (C) 2005 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.CharMatcher.WHITESPACE; import static com.google.common.collect.Lists.newArrayList; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.ImmutableSet; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.io.Serializable; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; /** * Unit test for {@link Predicates}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class PredicatesTest extends TestCase { private static final Predicate<Integer> TRUE = Predicates.alwaysTrue(); private static final Predicate<Integer> FALSE = Predicates.alwaysFalse(); private static final Predicate<Integer> NEVER_REACHED = new Predicate<Integer>() { @Override public boolean apply(Integer i) { fail("This predicate should never have been evaluated"); return false; } }; /** Instantiable predicate with reasonable hashCode() and equals() methods. */ static class IsOdd implements Predicate<Integer>, Serializable { private static final long serialVersionUID = 0x150ddL; @Override public boolean apply(Integer i) { return (i.intValue() & 1) == 1; } @Override public int hashCode() { return 0x150dd; } @Override public boolean equals(Object obj) { return obj instanceof IsOdd; } @Override public String toString() { return "IsOdd"; } } /** * Generates a new Predicate per call. * * <p>Creating a new Predicate each time helps catch cases where code is * using {@code x == y} instead of {@code x.equals(y)}. */ private static IsOdd isOdd() { return new IsOdd(); } /* * Tests for Predicates.alwaysTrue(). */ public void testAlwaysTrue_apply() { assertEvalsToTrue(Predicates.alwaysTrue()); } public void testAlwaysTrue_equality() throws Exception { new EqualsTester() .addEqualityGroup(TRUE, Predicates.alwaysTrue()) .addEqualityGroup(isOdd()) .addEqualityGroup(Predicates.alwaysFalse()) .testEquals(); } /* * Tests for Predicates.alwaysFalse(). */ public void testAlwaysFalse_apply() throws Exception { assertEvalsToFalse(Predicates.alwaysFalse()); } public void testAlwaysFalse_equality() throws Exception { new EqualsTester() .addEqualityGroup(FALSE, Predicates.alwaysFalse()) .addEqualityGroup(isOdd()) .addEqualityGroup(Predicates.alwaysTrue()) .testEquals(); } /* * Tests for Predicates.not(predicate). */ public void testNot_apply() { assertEvalsToTrue(Predicates.not(FALSE)); assertEvalsToFalse(Predicates.not(TRUE)); assertEvalsLikeOdd(Predicates.not(Predicates.not(isOdd()))); } public void testNot_equality() { new EqualsTester() .addEqualityGroup(Predicates.not(isOdd()), Predicates.not(isOdd())) .addEqualityGroup(Predicates.not(TRUE)) .addEqualityGroup(isOdd()) .testEquals(); } public void testNot_equalityForNotOfKnownValues() { new EqualsTester() .addEqualityGroup(TRUE, Predicates.alwaysTrue()) .addEqualityGroup(FALSE) .addEqualityGroup(Predicates.not(TRUE)) .testEquals(); new EqualsTester() .addEqualityGroup(FALSE, Predicates.alwaysFalse()) .addEqualityGroup(TRUE) .addEqualityGroup(Predicates.not(FALSE)) .testEquals(); new EqualsTester() .addEqualityGroup(Predicates.isNull(), Predicates.isNull()) .addEqualityGroup(Predicates.notNull()) .addEqualityGroup(Predicates.not(Predicates.isNull())) .testEquals(); new EqualsTester() .addEqualityGroup(Predicates.notNull(), Predicates.notNull()) .addEqualityGroup(Predicates.isNull()) .addEqualityGroup(Predicates.not(Predicates.notNull())) .testEquals(); } /* * Tests for all the different flavors of Predicates.and(). */ @SuppressWarnings("unchecked") public void testAnd_applyNoArgs() { assertEvalsToTrue(Predicates.and()); } @SuppressWarnings("unchecked") public void testAnd_equalityNoArgs() { new EqualsTester() .addEqualityGroup(Predicates.and(), Predicates.and()) .addEqualityGroup(Predicates.and(FALSE)) .addEqualityGroup(Predicates.or()) .testEquals(); } @SuppressWarnings("unchecked") public void testAnd_applyOneArg() { assertEvalsLikeOdd(Predicates.and(isOdd())); } @SuppressWarnings("unchecked") public void testAnd_equalityOneArg() { Object[] notEqualObjects = {Predicates.and(NEVER_REACHED, FALSE)}; new EqualsTester() .addEqualityGroup( Predicates.and(NEVER_REACHED), Predicates.and(NEVER_REACHED)) .addEqualityGroup(notEqualObjects) .addEqualityGroup(Predicates.and(isOdd())) .addEqualityGroup(Predicates.and()) .addEqualityGroup(Predicates.or(NEVER_REACHED)) .testEquals(); } public void testAnd_applyBinary() { assertEvalsLikeOdd(Predicates.and(isOdd(), TRUE)); assertEvalsLikeOdd(Predicates.and(TRUE, isOdd())); assertEvalsToFalse(Predicates.and(FALSE, NEVER_REACHED)); } @SuppressWarnings("unchecked") public void testAnd_equalityBinary() { new EqualsTester() .addEqualityGroup( Predicates.and(TRUE, NEVER_REACHED), Predicates.and(TRUE, NEVER_REACHED)) .addEqualityGroup(Predicates.and(NEVER_REACHED, TRUE)) .addEqualityGroup(Predicates.and(TRUE)) .addEqualityGroup(Predicates.or(TRUE, NEVER_REACHED)) .testEquals(); } @SuppressWarnings("unchecked") public void testAnd_applyTernary() { assertEvalsLikeOdd(Predicates.and(isOdd(), TRUE, TRUE)); assertEvalsLikeOdd(Predicates.and(TRUE, isOdd(), TRUE)); assertEvalsLikeOdd(Predicates.and(TRUE, TRUE, isOdd())); assertEvalsToFalse(Predicates.and(TRUE, FALSE, NEVER_REACHED)); } @SuppressWarnings("unchecked") public void testAnd_equalityTernary() { new EqualsTester() .addEqualityGroup( Predicates.and(TRUE, isOdd(), NEVER_REACHED), Predicates.and(TRUE, isOdd(), NEVER_REACHED)) .addEqualityGroup(Predicates.and(isOdd(), NEVER_REACHED, TRUE)) .addEqualityGroup(Predicates.and(TRUE)) .addEqualityGroup(Predicates.or(TRUE, isOdd(), NEVER_REACHED)) .testEquals(); } @SuppressWarnings("unchecked") public void testAnd_applyIterable() { Collection<Predicate<Integer>> empty = Arrays.asList(); assertEvalsToTrue(Predicates.and(empty)); assertEvalsLikeOdd(Predicates.and(Arrays.asList(isOdd()))); assertEvalsLikeOdd(Predicates.and(Arrays.asList(TRUE, isOdd()))); assertEvalsToFalse(Predicates.and(Arrays.asList(FALSE, NEVER_REACHED))); } @SuppressWarnings("unchecked") public void testAnd_equalityIterable() { new EqualsTester() .addEqualityGroup( Predicates.and(Arrays.asList(TRUE, NEVER_REACHED)), Predicates.and(Arrays.asList(TRUE, NEVER_REACHED)), Predicates.and(TRUE, NEVER_REACHED)) .addEqualityGroup(Predicates.and(FALSE, NEVER_REACHED)) .addEqualityGroup(Predicates.or(TRUE, NEVER_REACHED)) .testEquals(); } @SuppressWarnings("unchecked") public void testAnd_arrayDefensivelyCopied() { Predicate[] array = {Predicates.alwaysFalse()}; Predicate<Object> predicate = Predicates.and(array); assertFalse(predicate.apply(1)); array[0] = Predicates.alwaysTrue(); assertFalse(predicate.apply(1)); } public void testAnd_listDefensivelyCopied() { List<Predicate<Object>> list = newArrayList(); Predicate<Object> predicate = Predicates.and(list); assertTrue(predicate.apply(1)); list.add(Predicates.alwaysFalse()); assertTrue(predicate.apply(1)); } public void testAnd_iterableDefensivelyCopied() { final List<Predicate<Object>> list = newArrayList(); Iterable<Predicate<Object>> iterable = new Iterable<Predicate<Object>>() { @Override public Iterator<Predicate<Object>> iterator() { return list.iterator(); } }; Predicate<Object> predicate = Predicates.and(iterable); assertTrue(predicate.apply(1)); list.add(Predicates.alwaysFalse()); assertTrue(predicate.apply(1)); } /* * Tests for all the different flavors of Predicates.or(). */ @SuppressWarnings("unchecked") public void testOr_applyNoArgs() { assertEvalsToFalse(Predicates.or()); } @SuppressWarnings("unchecked") public void testOr_equalityNoArgs() { new EqualsTester() .addEqualityGroup(Predicates.or(), Predicates.or()) .addEqualityGroup(Predicates.or(TRUE)) .addEqualityGroup(Predicates.and()) .testEquals(); } @SuppressWarnings("unchecked") public void testOr_applyOneArg() { assertEvalsToTrue(Predicates.or(TRUE)); assertEvalsToFalse(Predicates.or(FALSE)); } @SuppressWarnings("unchecked") public void testOr_equalityOneArg() { new EqualsTester() .addEqualityGroup( Predicates.or(NEVER_REACHED), Predicates.or(NEVER_REACHED)) .addEqualityGroup(Predicates.or(NEVER_REACHED, TRUE)) .addEqualityGroup(Predicates.or(TRUE)) .addEqualityGroup(Predicates.or()) .addEqualityGroup(Predicates.and(NEVER_REACHED)) .testEquals(); } public void testOr_applyBinary() { Predicate<Integer> falseOrFalse = Predicates.or(FALSE, FALSE); Predicate<Integer> falseOrTrue = Predicates.or(FALSE, TRUE); Predicate<Integer> trueOrAnything = Predicates.or(TRUE, NEVER_REACHED); assertEvalsToFalse(falseOrFalse); assertEvalsToTrue(falseOrTrue); assertEvalsToTrue(trueOrAnything); } @SuppressWarnings("unchecked") public void testOr_equalityBinary() { new EqualsTester() .addEqualityGroup( Predicates.or(FALSE, NEVER_REACHED), Predicates.or(FALSE, NEVER_REACHED)) .addEqualityGroup(Predicates.or(NEVER_REACHED, FALSE)) .addEqualityGroup(Predicates.or(TRUE)) .addEqualityGroup(Predicates.and(FALSE, NEVER_REACHED)) .testEquals(); } @SuppressWarnings("unchecked") public void testOr_applyTernary() { assertEvalsLikeOdd(Predicates.or(isOdd(), FALSE, FALSE)); assertEvalsLikeOdd(Predicates.or(FALSE, isOdd(), FALSE)); assertEvalsLikeOdd(Predicates.or(FALSE, FALSE, isOdd())); assertEvalsToTrue(Predicates.or(FALSE, TRUE, NEVER_REACHED)); } @SuppressWarnings("unchecked") public void testOr_equalityTernary() { new EqualsTester() .addEqualityGroup( Predicates.or(FALSE, NEVER_REACHED, TRUE), Predicates.or(FALSE, NEVER_REACHED, TRUE)) .addEqualityGroup(Predicates.or(TRUE, NEVER_REACHED, FALSE)) .addEqualityGroup(Predicates.or(TRUE)) .addEqualityGroup(Predicates.and(FALSE, NEVER_REACHED, TRUE)) .testEquals(); } @SuppressWarnings("unchecked") public void testOr_applyIterable() { Predicate<Integer> vacuouslyFalse = Predicates.or(Collections.<Predicate<Integer>>emptyList()); Predicate<Integer> troo = Predicates.or(Collections.singletonList(TRUE)); /* * newLinkedList() takes varargs. TRUE and FALSE are both instances of * Predicate<Integer>, so the call is safe. */ Predicate<Integer> trueAndFalse = Predicates.or(Arrays.asList(TRUE, FALSE)); assertEvalsToFalse(vacuouslyFalse); assertEvalsToTrue(troo); assertEvalsToTrue(trueAndFalse); } @SuppressWarnings("unchecked") public void testOr_equalityIterable() { new EqualsTester() .addEqualityGroup( Predicates.or(Arrays.asList(FALSE, NEVER_REACHED)), Predicates.or(Arrays.asList(FALSE, NEVER_REACHED)), Predicates.or(FALSE, NEVER_REACHED)) .addEqualityGroup(Predicates.or(TRUE, NEVER_REACHED)) .addEqualityGroup(Predicates.and(FALSE, NEVER_REACHED)) .testEquals(); } @SuppressWarnings("unchecked") public void testOr_arrayDefensivelyCopied() { Predicate[] array = {Predicates.alwaysFalse()}; Predicate<Object> predicate = Predicates.or(array); assertFalse(predicate.apply(1)); array[0] = Predicates.alwaysTrue(); assertFalse(predicate.apply(1)); } public void testOr_listDefensivelyCopied() { List<Predicate<Object>> list = newArrayList(); Predicate<Object> predicate = Predicates.or(list); assertFalse(predicate.apply(1)); list.add(Predicates.alwaysTrue()); assertFalse(predicate.apply(1)); } public void testOr_iterableDefensivelyCopied() { final List<Predicate<Object>> list = newArrayList(); Iterable<Predicate<Object>> iterable = new Iterable<Predicate<Object>>() { @Override public Iterator<Predicate<Object>> iterator() { return list.iterator(); } }; Predicate<Object> predicate = Predicates.or(iterable); assertFalse(predicate.apply(1)); list.add(Predicates.alwaysTrue()); assertFalse(predicate.apply(1)); } /* * Tests for Predicates.equalTo(x). */ public void testIsEqualTo_apply() { Predicate<Integer> isOne = Predicates.equalTo(1); assertTrue(isOne.apply(1)); assertFalse(isOne.apply(2)); assertFalse(isOne.apply(null)); } public void testIsEqualTo_equality() { new EqualsTester() .addEqualityGroup(Predicates.equalTo(1), Predicates.equalTo(1)) .addEqualityGroup(Predicates.equalTo(2)) .addEqualityGroup(Predicates.equalTo(null)) .testEquals(); } public void testIsEqualToNull_apply() { Predicate<Integer> isNull = Predicates.equalTo(null); assertTrue(isNull.apply(null)); assertFalse(isNull.apply(1)); } public void testIsEqualToNull_equality() { new EqualsTester() .addEqualityGroup(Predicates.equalTo(null), Predicates.equalTo(null)) .addEqualityGroup(Predicates.equalTo(1)) .addEqualityGroup(Predicates.equalTo("null")) .testEquals(); } /* * Tests for Predicates.isNull() */ public void testIsNull_apply() { Predicate<Integer> isNull = Predicates.isNull(); assertTrue(isNull.apply(null)); assertFalse(isNull.apply(1)); } public void testIsNull_equality() { new EqualsTester() .addEqualityGroup(Predicates.isNull(), Predicates.isNull()) .addEqualityGroup(Predicates.notNull()) .testEquals(); } public void testNotNull_apply() { Predicate<Integer> notNull = Predicates.notNull(); assertFalse(notNull.apply(null)); assertTrue(notNull.apply(1)); } public void testNotNull_equality() { new EqualsTester() .addEqualityGroup(Predicates.notNull(), Predicates.notNull()) .addEqualityGroup(Predicates.isNull()) .testEquals(); } public void testIn_apply() { Collection<Integer> nums = Arrays.asList(1, 5); Predicate<Integer> isOneOrFive = Predicates.in(nums); assertTrue(isOneOrFive.apply(1)); assertTrue(isOneOrFive.apply(5)); assertFalse(isOneOrFive.apply(3)); assertFalse(isOneOrFive.apply(null)); } public void testIn_equality() { Collection<Integer> nums = ImmutableSet.of(1, 5); Collection<Integer> sameOrder = ImmutableSet.of(1, 5); Collection<Integer> differentOrder = ImmutableSet.of(5, 1); Collection<Integer> differentNums = ImmutableSet.of(1, 3, 5); new EqualsTester() .addEqualityGroup(Predicates.in(nums), Predicates.in(nums), Predicates.in(sameOrder), Predicates.in(differentOrder)) .addEqualityGroup(Predicates.in(differentNums)) .testEquals(); } public void testIn_handlesNullPointerException() { class CollectionThatThrowsNPE<T> extends ArrayList<T> { private static final long serialVersionUID = 1L; @Override public boolean contains(Object element) { Preconditions.checkNotNull(element); return super.contains(element); } } Collection<Integer> nums = new CollectionThatThrowsNPE<Integer>(); Predicate<Integer> isFalse = Predicates.in(nums); assertFalse(isFalse.apply(null)); } public void testIn_handlesClassCastException() { class CollectionThatThrowsCCE<T> extends ArrayList<T> { private static final long serialVersionUID = 1L; @Override public boolean contains(Object element) { throw new ClassCastException(""); } } Collection<Integer> nums = new CollectionThatThrowsCCE<Integer>(); nums.add(3); Predicate<Integer> isThree = Predicates.in(nums); assertFalse(isThree.apply(3)); } /* * Tests that compilation will work when applying explicit types. */ @SuppressWarnings("unused") public void testIn_compilesWithExplicitSupertype() { Collection<Number> nums = ImmutableSet.of(); Predicate<Number> p1 = Predicates.in(nums); Predicate<Object> p2 = Predicates.<Object>in(nums); // The next two lines are not expected to compile. // Predicate<Integer> p3 = Predicates.in(nums); // Predicate<Integer> p4 = Predicates.<Integer>in(nums); } // enum singleton pattern private enum TrimStringFunction implements Function<String, String> { INSTANCE; @Override public String apply(String string) { return WHITESPACE.trimFrom(string); } } public void testCompose() { Function<String, String> trim = TrimStringFunction.INSTANCE; Predicate<String> equalsFoo = Predicates.equalTo("Foo"); Predicate<String> equalsBar = Predicates.equalTo("Bar"); Predicate<String> trimEqualsFoo = Predicates.compose(equalsFoo, trim); Function<String, String> identity = Functions.identity(); assertTrue(trimEqualsFoo.apply("Foo")); assertTrue(trimEqualsFoo.apply(" Foo ")); assertFalse(trimEqualsFoo.apply("Foo-b-que")); new EqualsTester() .addEqualityGroup(trimEqualsFoo, Predicates.compose(equalsFoo, trim)) .addEqualityGroup(equalsFoo) .addEqualityGroup(trim) .addEqualityGroup(Predicates.compose(equalsFoo, identity)) .addEqualityGroup(Predicates.compose(equalsBar, trim)) .testEquals(); } public void assertEqualHashCode( Predicate<? super Integer> expected, Predicate<? super Integer> actual) { assertEquals(actual.toString() + " should hash like " + expected.toString(), expected.hashCode(), actual.hashCode()); } public void testHashCodeForBooleanOperations() { Predicate<Integer> p1 = Predicates.isNull(); Predicate<Integer> p2 = isOdd(); // Make sure that hash codes are not computed per-instance. assertEqualHashCode( Predicates.not(p1), Predicates.not(p1)); assertEqualHashCode( Predicates.and(p1, p2), Predicates.and(p1, p2)); assertEqualHashCode( Predicates.or(p1, p2), Predicates.or(p1, p2)); // While not a contractual requirement, we'd like the hash codes for ands // & ors of the same predicates to not collide. assertTrue(Predicates.and(p1, p2).hashCode() != Predicates.or(p1, p2).hashCode()); } private static void assertEvalsToTrue(Predicate<? super Integer> predicate) { assertTrue(predicate.apply(0)); assertTrue(predicate.apply(1)); assertTrue(predicate.apply(null)); } private static void assertEvalsToFalse(Predicate<? super Integer> predicate) { assertFalse(predicate.apply(0)); assertFalse(predicate.apply(1)); assertFalse(predicate.apply(null)); } private static void assertEvalsLikeOdd(Predicate<? super Integer> predicate) { assertEvalsLike(isOdd(), predicate); } private static void assertEvalsLike( Predicate<? super Integer> expected, Predicate<? super Integer> actual) { assertEvalsLike(expected, actual, 0); assertEvalsLike(expected, actual, 1); assertEvalsLike(expected, actual, null); } private static <T> void assertEvalsLike( Predicate<? super T> expected, Predicate<? super T> actual, T input) { Boolean expectedResult = null; RuntimeException expectedRuntimeException = null; try { expectedResult = expected.apply(input); } catch (RuntimeException e) { expectedRuntimeException = e; } Boolean actualResult = null; RuntimeException actualRuntimeException = null; try { actualResult = actual.apply(input); } catch (RuntimeException e) { actualRuntimeException = e; } assertEquals(expectedResult, actualResult); if (expectedRuntimeException != null) { assertNotNull(actualRuntimeException); assertEquals( expectedRuntimeException.getClass(), actualRuntimeException.getClass()); } } }
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.CharMatcher.anyOf; import static com.google.common.base.CharMatcher.forPredicate; import static com.google.common.base.CharMatcher.inRange; import static com.google.common.base.CharMatcher.is; import static com.google.common.base.CharMatcher.isNot; import static com.google.common.base.CharMatcher.noneOf; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.Sets; import junit.framework.AssertionFailedError; import junit.framework.TestCase; import java.util.Arrays; import java.util.HashSet; import java.util.Random; import java.util.Set; /** * Unit test for {@link CharMatcher}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class CharMatcherTest extends TestCase { private static final CharMatcher WHATEVER = new CharMatcher() { @Override public boolean matches(char c) { throw new AssertionFailedError( "You weren't supposed to actually invoke me!"); } }; public void testAnyAndNone_logicalOps() throws Exception { // These are testing behavior that's never promised by the API, but since // we're lucky enough that these do pass, it saves us from having to write // more excruciating tests! Hooray! assertSame(CharMatcher.ANY, CharMatcher.NONE.negate()); assertSame(CharMatcher.NONE, CharMatcher.ANY.negate()); assertSame(WHATEVER, CharMatcher.ANY.and(WHATEVER)); assertSame(CharMatcher.ANY, CharMatcher.ANY.or(WHATEVER)); assertSame(CharMatcher.NONE, CharMatcher.NONE.and(WHATEVER)); assertSame(WHATEVER, CharMatcher.NONE.or(WHATEVER)); } // The rest of the behavior of ANY and DEFAULT will be covered in the tests for // the text processing methods below. // The next tests require ICU4J and have, at least for now, been sliced out // of the open-source view of the tests. // Omitting tests for the rest of the JAVA_* constants as these are defined // as extremely straightforward pass-throughs to the JDK methods. // We're testing the is(), isNot(), anyOf(), noneOf() and inRange() methods // below by testing their text-processing methods. // The organization of this test class is unusual, as it's not done by // method, but by overall "scenario". Also, the variety of actual tests we // do borders on absurd overkill. Better safe than sorry, though? public void testEmpty() throws Exception { doTestEmpty(CharMatcher.ANY); doTestEmpty(CharMatcher.NONE); doTestEmpty(is('a')); doTestEmpty(isNot('a')); doTestEmpty(anyOf("")); doTestEmpty(anyOf("x")); doTestEmpty(anyOf("xy")); doTestEmpty(anyOf("CharMatcher")); doTestEmpty(noneOf("CharMatcher")); doTestEmpty(inRange('n', 'q')); doTestEmpty(forPredicate(Predicates.equalTo('c'))); } private void doTestEmpty(CharMatcher matcher) throws Exception { reallyTestEmpty(matcher); reallyTestEmpty(matcher.negate()); reallyTestEmpty(matcher.precomputed()); } private void reallyTestEmpty(CharMatcher matcher) throws Exception { assertEquals(-1, matcher.indexIn("")); assertEquals(-1, matcher.indexIn("", 0)); try { matcher.indexIn("", 1); fail(); } catch (IndexOutOfBoundsException expected) { } try { matcher.indexIn("", -1); fail(); } catch (IndexOutOfBoundsException expected) { } assertEquals(-1, matcher.lastIndexIn("")); assertFalse(matcher.matchesAnyOf("")); assertTrue(matcher.matchesAllOf("")); assertTrue(matcher.matchesNoneOf("")); assertEquals("", matcher.removeFrom("")); assertEquals("", matcher.replaceFrom("", 'z')); assertEquals("", matcher.replaceFrom("", "ZZ")); assertEquals("", matcher.trimFrom("")); assertEquals(0, matcher.countIn("")); } public void testNoMatches() { doTestNoMatches(CharMatcher.NONE, "blah"); doTestNoMatches(is('a'), "bcde"); doTestNoMatches(isNot('a'), "aaaa"); doTestNoMatches(anyOf(""), "abcd"); doTestNoMatches(anyOf("x"), "abcd"); doTestNoMatches(anyOf("xy"), "abcd"); doTestNoMatches(anyOf("CharMatcher"), "zxqy"); doTestNoMatches(noneOf("CharMatcher"), "ChMa"); doTestNoMatches(inRange('p', 'x'), "mom"); doTestNoMatches(forPredicate(Predicates.equalTo('c')), "abe"); doTestNoMatches(inRange('A', 'Z').and(inRange('F', 'K').negate()), "F1a"); doTestNoMatches(CharMatcher.DIGIT, "\tAz()"); doTestNoMatches(CharMatcher.JAVA_DIGIT, "\tAz()"); doTestNoMatches(CharMatcher.DIGIT.and(CharMatcher.ASCII), "\tAz()"); doTestNoMatches(CharMatcher.SINGLE_WIDTH, "\u05bf\u3000"); } private void doTestNoMatches(CharMatcher matcher, String s) { reallyTestNoMatches(matcher, s); reallyTestAllMatches(matcher.negate(), s); reallyTestNoMatches(matcher.precomputed(), s); reallyTestAllMatches(matcher.negate().precomputed(), s); reallyTestAllMatches(matcher.precomputed().negate(), s); reallyTestNoMatches(forPredicate(matcher), s); reallyTestNoMatches(matcher, new StringBuilder(s)); } public void testAllMatches() { doTestAllMatches(CharMatcher.ANY, "blah"); doTestAllMatches(isNot('a'), "bcde"); doTestAllMatches(is('a'), "aaaa"); doTestAllMatches(noneOf("CharMatcher"), "zxqy"); doTestAllMatches(anyOf("x"), "xxxx"); doTestAllMatches(anyOf("xy"), "xyyx"); doTestAllMatches(anyOf("CharMatcher"), "ChMa"); doTestAllMatches(inRange('m', 'p'), "mom"); doTestAllMatches(forPredicate(Predicates.equalTo('c')), "ccc"); doTestAllMatches(CharMatcher.DIGIT, "0123456789\u0ED0\u1B59"); doTestAllMatches(CharMatcher.JAVA_DIGIT, "0123456789"); doTestAllMatches(CharMatcher.DIGIT.and(CharMatcher.ASCII), "0123456789"); doTestAllMatches(CharMatcher.SINGLE_WIDTH, "\t0123ABCdef~\u00A0\u2111"); } private void doTestAllMatches(CharMatcher matcher, String s) { reallyTestAllMatches(matcher, s); reallyTestNoMatches(matcher.negate(), s); reallyTestAllMatches(matcher.precomputed(), s); reallyTestNoMatches(matcher.negate().precomputed(), s); reallyTestNoMatches(matcher.precomputed().negate(), s); reallyTestAllMatches(forPredicate(matcher), s); reallyTestAllMatches(matcher, new StringBuilder(s)); } private void reallyTestNoMatches(CharMatcher matcher, CharSequence s) { assertFalse(matcher.matches(s.charAt(0))); assertEquals(-1, matcher.indexIn(s)); assertEquals(-1, matcher.indexIn(s, 0)); assertEquals(-1, matcher.indexIn(s, 1)); assertEquals(-1, matcher.indexIn(s, s.length())); try { matcher.indexIn(s, s.length() + 1); fail(); } catch (IndexOutOfBoundsException expected) { } try { matcher.indexIn(s, -1); fail(); } catch (IndexOutOfBoundsException expected) { } assertEquals(-1, matcher.lastIndexIn(s)); assertFalse(matcher.matchesAnyOf(s)); assertFalse(matcher.matchesAllOf(s)); assertTrue(matcher.matchesNoneOf(s)); assertEquals(s.toString(), matcher.removeFrom(s)); assertEquals(s.toString(), matcher.replaceFrom(s, 'z')); assertEquals(s.toString(), matcher.replaceFrom(s, "ZZ")); assertEquals(s.toString(), matcher.trimFrom(s)); assertEquals(0, matcher.countIn(s)); } private void reallyTestAllMatches(CharMatcher matcher, CharSequence s) { assertTrue(matcher.matches(s.charAt(0))); assertEquals(0, matcher.indexIn(s)); assertEquals(0, matcher.indexIn(s, 0)); assertEquals(1, matcher.indexIn(s, 1)); assertEquals(-1, matcher.indexIn(s, s.length())); assertEquals(s.length() - 1, matcher.lastIndexIn(s)); assertTrue(matcher.matchesAnyOf(s)); assertTrue(matcher.matchesAllOf(s)); assertFalse(matcher.matchesNoneOf(s)); assertEquals("", matcher.removeFrom(s)); assertEquals(Strings.repeat("z", s.length()), matcher.replaceFrom(s, 'z')); assertEquals(Strings.repeat("ZZ", s.length()), matcher.replaceFrom(s, "ZZ")); assertEquals("", matcher.trimFrom(s)); assertEquals(s.length(), matcher.countIn(s)); } public void testGeneral() { doTestGeneral(is('a'), 'a', 'b'); doTestGeneral(isNot('a'), 'b', 'a'); doTestGeneral(anyOf("x"), 'x', 'z'); doTestGeneral(anyOf("xy"), 'y', 'z'); doTestGeneral(anyOf("CharMatcher"), 'C', 'z'); doTestGeneral(noneOf("CharMatcher"), 'z', 'C'); doTestGeneral(inRange('p', 'x'), 'q', 'z'); } private void doTestGeneral(CharMatcher matcher, char match, char noMatch) { doTestOneCharMatch(matcher, "" + match); doTestOneCharNoMatch(matcher, "" + noMatch); doTestMatchThenNoMatch(matcher, "" + match + noMatch); doTestNoMatchThenMatch(matcher, "" + noMatch + match); } private void doTestOneCharMatch(CharMatcher matcher, String s) { reallyTestOneCharMatch(matcher, s); reallyTestOneCharNoMatch(matcher.negate(), s); reallyTestOneCharMatch(matcher.precomputed(), s); reallyTestOneCharNoMatch(matcher.negate().precomputed(), s); reallyTestOneCharNoMatch(matcher.precomputed().negate(), s); } private void doTestOneCharNoMatch(CharMatcher matcher, String s) { reallyTestOneCharNoMatch(matcher, s); reallyTestOneCharMatch(matcher.negate(), s); reallyTestOneCharNoMatch(matcher.precomputed(), s); reallyTestOneCharMatch(matcher.negate().precomputed(), s); reallyTestOneCharMatch(matcher.precomputed().negate(), s); } private void doTestMatchThenNoMatch(CharMatcher matcher, String s) { reallyTestMatchThenNoMatch(matcher, s); reallyTestNoMatchThenMatch(matcher.negate(), s); reallyTestMatchThenNoMatch(matcher.precomputed(), s); reallyTestNoMatchThenMatch(matcher.negate().precomputed(), s); reallyTestNoMatchThenMatch(matcher.precomputed().negate(), s); } private void doTestNoMatchThenMatch(CharMatcher matcher, String s) { reallyTestNoMatchThenMatch(matcher, s); reallyTestMatchThenNoMatch(matcher.negate(), s); reallyTestNoMatchThenMatch(matcher.precomputed(), s); reallyTestMatchThenNoMatch(matcher.negate().precomputed(), s); reallyTestMatchThenNoMatch(matcher.precomputed().negate(), s); } private void reallyTestOneCharMatch(CharMatcher matcher, String s) { assertTrue(matcher.matches(s.charAt(0))); assertTrue(matcher.apply(s.charAt(0))); assertEquals(0, matcher.indexIn(s)); assertEquals(0, matcher.indexIn(s, 0)); assertEquals(-1, matcher.indexIn(s, 1)); assertEquals(0, matcher.lastIndexIn(s)); assertTrue(matcher.matchesAnyOf(s)); assertTrue(matcher.matchesAllOf(s)); assertFalse(matcher.matchesNoneOf(s)); assertEquals("", matcher.removeFrom(s)); assertEquals("z", matcher.replaceFrom(s, 'z')); assertEquals("ZZ", matcher.replaceFrom(s, "ZZ")); assertEquals("", matcher.trimFrom(s)); assertEquals(1, matcher.countIn(s)); } private void reallyTestOneCharNoMatch(CharMatcher matcher, String s) { assertFalse(matcher.matches(s.charAt(0))); assertFalse(matcher.apply(s.charAt(0))); assertEquals(-1, matcher.indexIn(s)); assertEquals(-1, matcher.indexIn(s, 0)); assertEquals(-1, matcher.indexIn(s, 1)); assertEquals(-1, matcher.lastIndexIn(s)); assertFalse(matcher.matchesAnyOf(s)); assertFalse(matcher.matchesAllOf(s)); assertTrue(matcher.matchesNoneOf(s)); assertSame(s, matcher.removeFrom(s)); assertSame(s, matcher.replaceFrom(s, 'z')); assertSame(s, matcher.replaceFrom(s, "ZZ")); assertSame(s, matcher.trimFrom(s)); assertSame(0, matcher.countIn(s)); } private void reallyTestMatchThenNoMatch(CharMatcher matcher, String s) { assertEquals(0, matcher.indexIn(s)); assertEquals(0, matcher.indexIn(s, 0)); assertEquals(-1, matcher.indexIn(s, 1)); assertEquals(-1, matcher.indexIn(s, 2)); assertEquals(0, matcher.lastIndexIn(s)); assertTrue(matcher.matchesAnyOf(s)); assertFalse(matcher.matchesAllOf(s)); assertFalse(matcher.matchesNoneOf(s)); assertEquals(s.substring(1), matcher.removeFrom(s)); assertEquals("z" + s.substring(1), matcher.replaceFrom(s, 'z')); assertEquals("ZZ" + s.substring(1), matcher.replaceFrom(s, "ZZ")); assertEquals(s.substring(1), matcher.trimFrom(s)); assertEquals(1, matcher.countIn(s)); } private void reallyTestNoMatchThenMatch(CharMatcher matcher, String s) { assertEquals(1, matcher.indexIn(s)); assertEquals(1, matcher.indexIn(s, 0)); assertEquals(1, matcher.indexIn(s, 1)); assertEquals(-1, matcher.indexIn(s, 2)); assertEquals(1, matcher.lastIndexIn(s)); assertTrue(matcher.matchesAnyOf(s)); assertFalse(matcher.matchesAllOf(s)); assertFalse(matcher.matchesNoneOf(s)); assertEquals(s.substring(0, 1), matcher.removeFrom(s)); assertEquals(s.substring(0, 1) + "z", matcher.replaceFrom(s, 'z')); assertEquals(s.substring(0, 1) + "ZZ", matcher.replaceFrom(s, "ZZ")); assertEquals(s.substring(0, 1), matcher.trimFrom(s)); assertEquals(1, matcher.countIn(s)); } /** * Checks that expected is equals to out, and further, if in is * equals to expected, then out is successfully optimized to be * identical to in, i.e. that "in" is simply returned. */ private void assertEqualsSame(String expected, String in, String out) { if (expected.equals(in)) { assertSame(in, out); } else { assertEquals(expected, out); } } // Test collapse() a little differently than the rest, as we really want to // cover lots of different configurations of input text public void testCollapse() { // collapsing groups of '-' into '_' or '-' doTestCollapse("-", "_"); doTestCollapse("x-", "x_"); doTestCollapse("-x", "_x"); doTestCollapse("--", "_"); doTestCollapse("x--", "x_"); doTestCollapse("--x", "_x"); doTestCollapse("-x-", "_x_"); doTestCollapse("x-x", "x_x"); doTestCollapse("---", "_"); doTestCollapse("--x-", "_x_"); doTestCollapse("--xx", "_xx"); doTestCollapse("-x--", "_x_"); doTestCollapse("-x-x", "_x_x"); doTestCollapse("-xx-", "_xx_"); doTestCollapse("x--x", "x_x"); doTestCollapse("x-x-", "x_x_"); doTestCollapse("x-xx", "x_xx"); doTestCollapse("x-x--xx---x----x", "x_x_xx_x_x"); doTestCollapseWithNoChange(""); doTestCollapseWithNoChange("x"); doTestCollapseWithNoChange("xx"); } private void doTestCollapse(String in, String out) { // Try a few different matchers which all match '-' and not 'x' // Try replacement chars that both do and do not change the value. for (char replacement : new char[] { '_', '-' }) { String expected = out.replace('_', replacement); assertEqualsSame(expected, in, is('-').collapseFrom(in, replacement)); assertEqualsSame(expected, in, is('-').collapseFrom(in, replacement)); assertEqualsSame(expected, in, is('-').or(is('#')).collapseFrom(in, replacement)); assertEqualsSame(expected, in, isNot('x').collapseFrom(in, replacement)); assertEqualsSame(expected, in, is('x').negate().collapseFrom(in, replacement)); assertEqualsSame(expected, in, anyOf("-").collapseFrom(in, replacement)); assertEqualsSame(expected, in, anyOf("-#").collapseFrom(in, replacement)); assertEqualsSame(expected, in, anyOf("-#123").collapseFrom(in, replacement)); } } private void doTestCollapseWithNoChange(String inout) { assertSame(inout, is('-').collapseFrom(inout, '_')); assertSame(inout, is('-').or(is('#')).collapseFrom(inout, '_')); assertSame(inout, isNot('x').collapseFrom(inout, '_')); assertSame(inout, is('x').negate().collapseFrom(inout, '_')); assertSame(inout, anyOf("-").collapseFrom(inout, '_')); assertSame(inout, anyOf("-#").collapseFrom(inout, '_')); assertSame(inout, anyOf("-#123").collapseFrom(inout, '_')); assertSame(inout, CharMatcher.NONE.collapseFrom(inout, '_')); } public void testCollapse_any() { assertEquals("", CharMatcher.ANY.collapseFrom("", '_')); assertEquals("_", CharMatcher.ANY.collapseFrom("a", '_')); assertEquals("_", CharMatcher.ANY.collapseFrom("ab", '_')); assertEquals("_", CharMatcher.ANY.collapseFrom("abcd", '_')); } public void testTrimFrom() { // trimming - doTestTrimFrom("-", ""); doTestTrimFrom("x-", "x"); doTestTrimFrom("-x", "x"); doTestTrimFrom("--", ""); doTestTrimFrom("x--", "x"); doTestTrimFrom("--x", "x"); doTestTrimFrom("-x-", "x"); doTestTrimFrom("x-x", "x-x"); doTestTrimFrom("---", ""); doTestTrimFrom("--x-", "x"); doTestTrimFrom("--xx", "xx"); doTestTrimFrom("-x--", "x"); doTestTrimFrom("-x-x", "x-x"); doTestTrimFrom("-xx-", "xx"); doTestTrimFrom("x--x", "x--x"); doTestTrimFrom("x-x-", "x-x"); doTestTrimFrom("x-xx", "x-xx"); doTestTrimFrom("x-x--xx---x----x", "x-x--xx---x----x"); // additional testing using the doc example assertEquals("cat", anyOf("ab").trimFrom("abacatbab")); } private void doTestTrimFrom(String in, String out) { // Try a few different matchers which all match '-' and not 'x' assertEquals(out, is('-').trimFrom(in)); assertEquals(out, is('-').or(is('#')).trimFrom(in)); assertEquals(out, isNot('x').trimFrom(in)); assertEquals(out, is('x').negate().trimFrom(in)); assertEquals(out, anyOf("-").trimFrom(in)); assertEquals(out, anyOf("-#").trimFrom(in)); assertEquals(out, anyOf("-#123").trimFrom(in)); } public void testTrimLeadingFrom() { // trimming - doTestTrimLeadingFrom("-", ""); doTestTrimLeadingFrom("x-", "x-"); doTestTrimLeadingFrom("-x", "x"); doTestTrimLeadingFrom("--", ""); doTestTrimLeadingFrom("x--", "x--"); doTestTrimLeadingFrom("--x", "x"); doTestTrimLeadingFrom("-x-", "x-"); doTestTrimLeadingFrom("x-x", "x-x"); doTestTrimLeadingFrom("---", ""); doTestTrimLeadingFrom("--x-", "x-"); doTestTrimLeadingFrom("--xx", "xx"); doTestTrimLeadingFrom("-x--", "x--"); doTestTrimLeadingFrom("-x-x", "x-x"); doTestTrimLeadingFrom("-xx-", "xx-"); doTestTrimLeadingFrom("x--x", "x--x"); doTestTrimLeadingFrom("x-x-", "x-x-"); doTestTrimLeadingFrom("x-xx", "x-xx"); doTestTrimLeadingFrom("x-x--xx---x----x", "x-x--xx---x----x"); // additional testing using the doc example assertEquals("catbab", anyOf("ab").trimLeadingFrom("abacatbab")); } private void doTestTrimLeadingFrom(String in, String out) { // Try a few different matchers which all match '-' and not 'x' assertEquals(out, is('-').trimLeadingFrom(in)); assertEquals(out, is('-').or(is('#')).trimLeadingFrom(in)); assertEquals(out, isNot('x').trimLeadingFrom(in)); assertEquals(out, is('x').negate().trimLeadingFrom(in)); assertEquals(out, anyOf("-#").trimLeadingFrom(in)); assertEquals(out, anyOf("-#123").trimLeadingFrom(in)); } public void testTrimTrailingFrom() { // trimming - doTestTrimTrailingFrom("-", ""); doTestTrimTrailingFrom("x-", "x"); doTestTrimTrailingFrom("-x", "-x"); doTestTrimTrailingFrom("--", ""); doTestTrimTrailingFrom("x--", "x"); doTestTrimTrailingFrom("--x", "--x"); doTestTrimTrailingFrom("-x-", "-x"); doTestTrimTrailingFrom("x-x", "x-x"); doTestTrimTrailingFrom("---", ""); doTestTrimTrailingFrom("--x-", "--x"); doTestTrimTrailingFrom("--xx", "--xx"); doTestTrimTrailingFrom("-x--", "-x"); doTestTrimTrailingFrom("-x-x", "-x-x"); doTestTrimTrailingFrom("-xx-", "-xx"); doTestTrimTrailingFrom("x--x", "x--x"); doTestTrimTrailingFrom("x-x-", "x-x"); doTestTrimTrailingFrom("x-xx", "x-xx"); doTestTrimTrailingFrom("x-x--xx---x----x", "x-x--xx---x----x"); // additional testing using the doc example assertEquals("abacat", anyOf("ab").trimTrailingFrom("abacatbab")); } private void doTestTrimTrailingFrom(String in, String out) { // Try a few different matchers which all match '-' and not 'x' assertEquals(out, is('-').trimTrailingFrom(in)); assertEquals(out, is('-').or(is('#')).trimTrailingFrom(in)); assertEquals(out, isNot('x').trimTrailingFrom(in)); assertEquals(out, is('x').negate().trimTrailingFrom(in)); assertEquals(out, anyOf("-#").trimTrailingFrom(in)); assertEquals(out, anyOf("-#123").trimTrailingFrom(in)); } public void testTrimAndCollapse() { // collapsing groups of '-' into '_' or '-' doTestTrimAndCollapse("", ""); doTestTrimAndCollapse("x", "x"); doTestTrimAndCollapse("-", ""); doTestTrimAndCollapse("x-", "x"); doTestTrimAndCollapse("-x", "x"); doTestTrimAndCollapse("--", ""); doTestTrimAndCollapse("x--", "x"); doTestTrimAndCollapse("--x", "x"); doTestTrimAndCollapse("-x-", "x"); doTestTrimAndCollapse("x-x", "x_x"); doTestTrimAndCollapse("---", ""); doTestTrimAndCollapse("--x-", "x"); doTestTrimAndCollapse("--xx", "xx"); doTestTrimAndCollapse("-x--", "x"); doTestTrimAndCollapse("-x-x", "x_x"); doTestTrimAndCollapse("-xx-", "xx"); doTestTrimAndCollapse("x--x", "x_x"); doTestTrimAndCollapse("x-x-", "x_x"); doTestTrimAndCollapse("x-xx", "x_xx"); doTestTrimAndCollapse("x-x--xx---x----x", "x_x_xx_x_x"); } private void doTestTrimAndCollapse(String in, String out) { // Try a few different matchers which all match '-' and not 'x' for (char replacement : new char[] { '_', '-' }) { String expected = out.replace('_', replacement); assertEqualsSame(expected, in, is('-').trimAndCollapseFrom(in, replacement)); assertEqualsSame(expected, in, is('-').or(is('#')).trimAndCollapseFrom(in, replacement)); assertEqualsSame(expected, in, isNot('x').trimAndCollapseFrom(in, replacement)); assertEqualsSame(expected, in, is('x').negate().trimAndCollapseFrom(in, replacement)); assertEqualsSame(expected, in, anyOf("-").trimAndCollapseFrom(in, replacement)); assertEqualsSame(expected, in, anyOf("-#").trimAndCollapseFrom(in, replacement)); assertEqualsSame(expected, in, anyOf("-#123").trimAndCollapseFrom(in, replacement)); } } public void testReplaceFrom() { assertEquals("yoho", is('a').replaceFrom("yaha", 'o')); assertEquals("yh", is('a').replaceFrom("yaha", "")); assertEquals("yoho", is('a').replaceFrom("yaha", "o")); assertEquals("yoohoo", is('a').replaceFrom("yaha", "oo")); assertEquals("12 &gt; 5", is('>').replaceFrom("12 > 5", "&gt;")); } public void testPrecomputedOptimizations() { // These are testing behavior that's never promised by the API. // Some matchers are so efficient that it is a waste of effort to // build a precomputed version. CharMatcher m1 = is('x'); assertSame(m1, m1.precomputed()); assertSame(m1.toString(), m1.precomputed().toString()); CharMatcher m2 = anyOf("Az"); assertSame(m2, m2.precomputed()); assertSame(m2.toString(), m2.precomputed().toString()); CharMatcher m3 = inRange('A', 'Z'); assertSame(m3, m3.precomputed()); assertSame(m3.toString(), m3.precomputed().toString()); assertSame(CharMatcher.NONE, CharMatcher.NONE.precomputed()); assertSame(CharMatcher.ANY, CharMatcher.ANY.precomputed()); } static void checkExactMatches(CharMatcher m, char[] chars) { Set<Character> positive = Sets.newHashSetWithExpectedSize(chars.length); for (int i = 0; i < chars.length; i++) { positive.add(chars[i]); } for (int c = 0; c <= Character.MAX_VALUE; c++) { assertFalse(positive.contains(new Character((char) c)) ^ m.matches((char) c)); } } static char[] randomChars(Random rand, int size) { Set<Character> chars = new HashSet<Character>(size); for (int i = 0; i < size; i++) { char c; while (true) { c = (char) rand.nextInt(Character.MAX_VALUE - Character.MIN_VALUE + 1); if (!chars.contains(c)) { break; } } chars.add(c); } char[] retValue = new char[chars.size()]; int i = 0; for (char c : chars) { retValue[i++] = c; } Arrays.sort(retValue); return retValue; } public void testToString() { assertEquals("CharMatcher.NONE", CharMatcher.anyOf("").toString()); assertEquals("CharMatcher.is('\\u0031')", CharMatcher.anyOf("1").toString()); assertEquals("CharMatcher.anyOf(\"\\u0031\\u0032\")", CharMatcher.anyOf("12").toString()); assertEquals("CharMatcher.anyOf(\"\\u0031\\u0032\\u0033\")", CharMatcher.anyOf("321").toString()); assertEquals("CharMatcher.inRange('\\u0031', '\\u0033')", CharMatcher.inRange('1', '3').toString()); } }
Java
/* * Copyright (C) 2006 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; /** * Tests for {@link Objects}. * * @author Laurence Gonsalves */ @GwtCompatible(emulated = true) public class ObjectsTest extends TestCase { public void testEqual() throws Exception { assertTrue(Objects.equal(1, 1)); assertTrue(Objects.equal(null, null)); // test distinct string objects String s1 = "foobar"; String s2 = new String(s1); assertTrue(Objects.equal(s1, s2)); assertFalse(Objects.equal(s1, null)); assertFalse(Objects.equal(null, s1)); assertFalse(Objects.equal("foo", "bar")); assertFalse(Objects.equal("1", 1)); } public void testHashCode() throws Exception { int h1 = Objects.hashCode(1, "two", 3.0); int h2 = Objects.hashCode(new Integer(1), new String("two"), new Double(3.0)); // repeatable assertEquals(h1, h2); // These don't strictly need to be true, but they're nice properties. assertTrue(Objects.hashCode(1, 2, null) != Objects.hashCode(1, 2)); assertTrue(Objects.hashCode(1, 2, null) != Objects.hashCode(1, null, 2)); assertTrue(Objects.hashCode(1, null, 2) != Objects.hashCode(1, 2)); assertTrue(Objects.hashCode(1, 2, 3) != Objects.hashCode(3, 2, 1)); assertTrue(Objects.hashCode(1, 2, 3) != Objects.hashCode(2, 3, 1)); } public void testFirstNonNull_withNonNull() throws Exception { String s1 = "foo"; String s2 = Objects.firstNonNull(s1, "bar"); assertSame(s1, s2); Long n1 = new Long(42); Long n2 = Objects.firstNonNull(null, n1); assertSame(n1, n2); } public void testFirstNonNull_throwsNullPointerException() throws Exception { try { Objects.firstNonNull(null, null); fail("expected NullPointerException"); } catch (NullPointerException expected) { } } }
Java
/* * Copyright (C) 2010 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import junit.framework.TestCase; /** * Unit test for {@link Strings}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class StringsTest extends TestCase { public void testNullToEmpty() { assertEquals("", Strings.nullToEmpty(null)); assertEquals("", Strings.nullToEmpty("")); assertEquals("a", Strings.nullToEmpty("a")); } public void testEmptyToNull() { assertNull(Strings.emptyToNull(null)); assertNull(Strings.emptyToNull("")); assertEquals("a", Strings.emptyToNull("a")); } public void testIsNullOrEmpty() { assertTrue(Strings.isNullOrEmpty(null)); assertTrue(Strings.isNullOrEmpty("")); assertFalse(Strings.isNullOrEmpty("a")); } public void testPadStart_noPadding() { assertSame("", Strings.padStart("", 0, '-')); assertSame("x", Strings.padStart("x", 0, '-')); assertSame("x", Strings.padStart("x", 1, '-')); assertSame("xx", Strings.padStart("xx", 0, '-')); assertSame("xx", Strings.padStart("xx", 2, '-')); } public void testPadStart_somePadding() { assertEquals("-", Strings.padStart("", 1, '-')); assertEquals("--", Strings.padStart("", 2, '-')); assertEquals("-x", Strings.padStart("x", 2, '-')); assertEquals("--x", Strings.padStart("x", 3, '-')); assertEquals("-xx", Strings.padStart("xx", 3, '-')); } public void testPadStart_negativeMinLength() { assertSame("x", Strings.padStart("x", -1, '-')); } // TODO: could remove if we got NPT working in GWT somehow public void testPadStart_null() { try { Strings.padStart(null, 5, '0'); fail(); } catch (NullPointerException expected) { } } public void testPadEnd_noPadding() { assertSame("", Strings.padEnd("", 0, '-')); assertSame("x", Strings.padEnd("x", 0, '-')); assertSame("x", Strings.padEnd("x", 1, '-')); assertSame("xx", Strings.padEnd("xx", 0, '-')); assertSame("xx", Strings.padEnd("xx", 2, '-')); } public void testPadEnd_somePadding() { assertEquals("-", Strings.padEnd("", 1, '-')); assertEquals("--", Strings.padEnd("", 2, '-')); assertEquals("x-", Strings.padEnd("x", 2, '-')); assertEquals("x--", Strings.padEnd("x", 3, '-')); assertEquals("xx-", Strings.padEnd("xx", 3, '-')); } public void testPadEnd_negativeMinLength() { assertSame("x", Strings.padEnd("x", -1, '-')); } // TODO: could remove if we got NPT working in GWT somehow public void testPadEnd_null() { try { Strings.padEnd(null, 5, '0'); fail(); } catch (NullPointerException expected) { } } public void testRepeat() { String input = "20"; assertEquals("", Strings.repeat(input, 0)); assertEquals("20", Strings.repeat(input, 1)); assertEquals("2020", Strings.repeat(input, 2)); assertEquals("202020", Strings.repeat(input, 3)); assertEquals("", Strings.repeat("", 4)); for (int i = 0; i < 100; ++i) { assertEquals(2 * i, Strings.repeat(input, i).length()); } try { Strings.repeat("x", -1); fail(); } catch (IllegalArgumentException expected) { } try { // Massive string Strings.repeat("12345678", (1 << 30) + 3); fail(); } catch (ArrayIndexOutOfBoundsException expected) { } } // TODO: could remove if we got NPT working in GWT somehow public void testRepeat_null() { try { Strings.repeat(null, 5); fail(); } catch (NullPointerException expected) { } } public void testCommonPrefix() { assertEquals("", Strings.commonPrefix("", "")); assertEquals("", Strings.commonPrefix("abc", "")); assertEquals("", Strings.commonPrefix("", "abc")); assertEquals("", Strings.commonPrefix("abcde", "xyz")); assertEquals("", Strings.commonPrefix("xyz", "abcde")); assertEquals("", Strings.commonPrefix("xyz", "abcxyz")); assertEquals("a", Strings.commonPrefix("abc", "aaaaa")); assertEquals("aa", Strings.commonPrefix("aa", "aaaaa")); assertEquals("abc", Strings.commonPrefix(new StringBuffer("abcdef"), "abcxyz")); // Identical valid surrogate pairs. assertEquals("abc\uD8AB\uDCAB", Strings.commonPrefix("abc\uD8AB\uDCABdef", "abc\uD8AB\uDCABxyz")); // Differing valid surrogate pairs. assertEquals("abc", Strings.commonPrefix("abc\uD8AB\uDCABdef", "abc\uD8AB\uDCACxyz")); // One invalid pair. assertEquals("abc", Strings.commonPrefix("abc\uD8AB\uDCABdef", "abc\uD8AB\uD8ABxyz")); // Two identical invalid pairs. assertEquals("abc\uD8AB\uD8AC", Strings.commonPrefix("abc\uD8AB\uD8ACdef", "abc\uD8AB\uD8ACxyz")); // Two differing invalid pairs. assertEquals("abc\uD8AB", Strings.commonPrefix("abc\uD8AB\uD8ABdef", "abc\uD8AB\uD8ACxyz")); // One orphan high surrogate. assertEquals("", Strings.commonPrefix("\uD8AB\uDCAB", "\uD8AB")); // Two orphan high surrogates. assertEquals("\uD8AB", Strings.commonPrefix("\uD8AB", "\uD8AB")); } public void testCommonSuffix() { assertEquals("", Strings.commonSuffix("", "")); assertEquals("", Strings.commonSuffix("abc", "")); assertEquals("", Strings.commonSuffix("", "abc")); assertEquals("", Strings.commonSuffix("abcde", "xyz")); assertEquals("", Strings.commonSuffix("xyz", "abcde")); assertEquals("", Strings.commonSuffix("xyz", "xyzabc")); assertEquals("c", Strings.commonSuffix("abc", "ccccc")); assertEquals("aa", Strings.commonSuffix("aa", "aaaaa")); assertEquals("abc", Strings.commonSuffix(new StringBuffer("xyzabc"), "xxxabc")); // Identical valid surrogate pairs. assertEquals("\uD8AB\uDCABdef", Strings.commonSuffix("abc\uD8AB\uDCABdef", "xyz\uD8AB\uDCABdef")); // Differing valid surrogate pairs. assertEquals("def", Strings.commonSuffix("abc\uD8AB\uDCABdef", "abc\uD8AC\uDCABdef")); // One invalid pair. assertEquals("def", Strings.commonSuffix("abc\uD8AB\uDCABdef", "xyz\uDCAB\uDCABdef")); // Two identical invalid pairs. assertEquals("\uD8AB\uD8ABdef", Strings.commonSuffix("abc\uD8AB\uD8ABdef", "xyz\uD8AB\uD8ABdef")); // Two differing invalid pairs. assertEquals("\uDCABdef", Strings.commonSuffix("abc\uDCAB\uDCABdef", "abc\uDCAC\uDCABdef")); // One orphan low surrogate. assertEquals("", Strings.commonSuffix("x\uD8AB\uDCAB", "\uDCAB")); // Two orphan low surrogates. assertEquals("\uDCAB", Strings.commonSuffix("\uDCAB", "\uDCAB")); } public void testValidSurrogatePairAt() { assertTrue(Strings.validSurrogatePairAt("\uD8AB\uDCAB", 0)); assertTrue(Strings.validSurrogatePairAt("abc\uD8AB\uDCAB", 3)); assertTrue(Strings.validSurrogatePairAt("abc\uD8AB\uDCABxyz", 3)); assertFalse(Strings.validSurrogatePairAt("\uD8AB\uD8AB", 0)); assertFalse(Strings.validSurrogatePairAt("\uDCAB\uDCAB", 0)); assertFalse(Strings.validSurrogatePairAt("\uD8AB\uDCAB", -1)); assertFalse(Strings.validSurrogatePairAt("\uD8AB\uDCAB", 1)); assertFalse(Strings.validSurrogatePairAt("\uD8AB\uDCAB", -2)); assertFalse(Strings.validSurrogatePairAt("\uD8AB\uDCAB", 2)); assertFalse(Strings.validSurrogatePairAt("x\uDCAB", 0)); assertFalse(Strings.validSurrogatePairAt("\uD8ABx", 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.base; import static java.util.concurrent.TimeUnit.MICROSECONDS; import static java.util.concurrent.TimeUnit.MILLISECONDS; import static java.util.concurrent.TimeUnit.NANOSECONDS; import com.google.common.annotations.GwtCompatible; import com.google.common.testing.FakeTicker; import junit.framework.TestCase; /** * Unit test for {@link Stopwatch}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class StopwatchTest extends TestCase { private final FakeTicker ticker = new FakeTicker(); private final Stopwatch stopwatch = new Stopwatch(ticker); public void testCreateStarted() { Stopwatch startedStopwatch = Stopwatch.createStarted(); assertTrue(startedStopwatch.isRunning()); } public void testCreateUnstarted() { Stopwatch unstartedStopwatch = Stopwatch.createUnstarted(); assertFalse(unstartedStopwatch.isRunning()); assertEquals(0, unstartedStopwatch.elapsed(NANOSECONDS)); } public void testInitialState() { assertFalse(stopwatch.isRunning()); assertEquals(0, stopwatch.elapsed(NANOSECONDS)); } public void testStart() { assertSame(stopwatch, stopwatch.start()); assertTrue(stopwatch.isRunning()); } public void testStart_whileRunning() { stopwatch.start(); try { stopwatch.start(); fail(); } catch (IllegalStateException expected) { } assertTrue(stopwatch.isRunning()); } public void testStop() { stopwatch.start(); assertSame(stopwatch, stopwatch.stop()); assertFalse(stopwatch.isRunning()); } public void testStop_new() { try { stopwatch.stop(); fail(); } catch (IllegalStateException expected) { } assertFalse(stopwatch.isRunning()); } public void testStop_alreadyStopped() { stopwatch.start(); stopwatch.stop(); try { stopwatch.stop(); fail(); } catch (IllegalStateException expected) { } assertFalse(stopwatch.isRunning()); } public void testReset_new() { ticker.advance(1); stopwatch.reset(); assertFalse(stopwatch.isRunning()); ticker.advance(2); assertEquals(0, stopwatch.elapsed(NANOSECONDS)); stopwatch.start(); ticker.advance(3); assertEquals(3, stopwatch.elapsed(NANOSECONDS)); } public void testReset_whileRunning() { ticker.advance(1); stopwatch.start(); assertEquals(0, stopwatch.elapsed(NANOSECONDS)); ticker.advance(2); assertEquals(2, stopwatch.elapsed(NANOSECONDS)); stopwatch.reset(); assertFalse(stopwatch.isRunning()); ticker.advance(3); assertEquals(0, stopwatch.elapsed(NANOSECONDS)); } public void testElapsed_whileRunning() { ticker.advance(78); stopwatch.start(); assertEquals(0, stopwatch.elapsed(NANOSECONDS)); ticker.advance(345); assertEquals(345, stopwatch.elapsed(NANOSECONDS)); } public void testElapsed_notRunning() { ticker.advance(1); stopwatch.start(); ticker.advance(4); stopwatch.stop(); ticker.advance(9); assertEquals(4, stopwatch.elapsed(NANOSECONDS)); } public void testElapsed_multipleSegments() { stopwatch.start(); ticker.advance(9); stopwatch.stop(); ticker.advance(16); stopwatch.start(); assertEquals(9, stopwatch.elapsed(NANOSECONDS)); ticker.advance(25); assertEquals(34, stopwatch.elapsed(NANOSECONDS)); stopwatch.stop(); ticker.advance(36); assertEquals(34, stopwatch.elapsed(NANOSECONDS)); } public void testElapsed_micros() { stopwatch.start(); ticker.advance(999); assertEquals(0, stopwatch.elapsed(MICROSECONDS)); ticker.advance(1); assertEquals(1, stopwatch.elapsed(MICROSECONDS)); } public void testElapsed_millis() { stopwatch.start(); ticker.advance(999999); assertEquals(0, stopwatch.elapsed(MILLISECONDS)); ticker.advance(1); assertEquals(1, stopwatch.elapsed(MILLISECONDS)); } public void testElapsedMillis() { stopwatch.start(); ticker.advance(999999); assertEquals(0, stopwatch.elapsed(MILLISECONDS)); ticker.advance(1); assertEquals(1, stopwatch.elapsed(MILLISECONDS)); } public void testElapsedMillis_whileRunning() { ticker.advance(78000000); stopwatch.start(); assertEquals(0, stopwatch.elapsed(MILLISECONDS)); ticker.advance(345000000); assertEquals(345, stopwatch.elapsed(MILLISECONDS)); } public void testElapsedMillis_notRunning() { ticker.advance(1000000); stopwatch.start(); ticker.advance(4000000); stopwatch.stop(); ticker.advance(9000000); assertEquals(4, stopwatch.elapsed(MILLISECONDS)); } public void testElapsedMillis_multipleSegments() { stopwatch.start(); ticker.advance(9000000); stopwatch.stop(); ticker.advance(16000000); stopwatch.start(); assertEquals(9, stopwatch.elapsed(MILLISECONDS)); ticker.advance(25000000); assertEquals(34, stopwatch.elapsed(MILLISECONDS)); stopwatch.stop(); ticker.advance(36000000); assertEquals(34, stopwatch.elapsed(MILLISECONDS)); } }
Java
/* * Copyright (C) 2008 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.base; import com.google.common.annotations.GwtCompatible; import com.google.common.base.Joiner.MapJoiner; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.ImmutableSet; import com.google.common.collect.Lists; import com.google.common.collect.Maps; import junit.framework.TestCase; import java.io.IOException; import java.util.Arrays; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * Unit test for {@link Joiner}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class JoinerTest extends TestCase { private static final Joiner J = Joiner.on("-"); // <Integer> needed to prevent warning :( private static final Iterable<Integer> ITERABLE_ = Arrays.<Integer>asList(); private static final Iterable<Integer> ITERABLE_1 = Arrays.asList(1); private static final Iterable<Integer> ITERABLE_12 = Arrays.asList(1, 2); private static final Iterable<Integer> ITERABLE_123 = Arrays.asList(1, 2, 3); private static final Iterable<Integer> ITERABLE_NULL = Arrays.asList((Integer) null); private static final Iterable<Integer> ITERABLE_NULL_NULL = Arrays.asList((Integer) null, null); private static final Iterable<Integer> ITERABLE_NULL_1 = Arrays.asList(null, 1); private static final Iterable<Integer> ITERABLE_1_NULL = Arrays.asList(1, null); private static final Iterable<Integer> ITERABLE_1_NULL_2 = Arrays.asList(1, null, 2); private static final Iterable<Integer> ITERABLE_FOUR_NULLS = Arrays.asList((Integer) null, null, null, null); public void testNoSpecialNullBehavior() { checkNoOutput(J, ITERABLE_); checkResult(J, ITERABLE_1, "1"); checkResult(J, ITERABLE_12, "1-2"); checkResult(J, ITERABLE_123, "1-2-3"); try { J.join(ITERABLE_NULL); fail(); } catch (NullPointerException expected) { } try { J.join(ITERABLE_1_NULL_2); fail(); } catch (NullPointerException expected) { } try { J.join(ITERABLE_NULL.iterator()); fail(); } catch (NullPointerException expected) { } try { J.join(ITERABLE_1_NULL_2.iterator()); fail(); } catch (NullPointerException expected) { } } public void testOnCharOverride() { Joiner onChar = Joiner.on('-'); checkNoOutput(onChar, ITERABLE_); checkResult(onChar, ITERABLE_1, "1"); checkResult(onChar, ITERABLE_12, "1-2"); checkResult(onChar, ITERABLE_123, "1-2-3"); } public void testSkipNulls() { Joiner skipNulls = J.skipNulls(); checkNoOutput(skipNulls, ITERABLE_); checkNoOutput(skipNulls, ITERABLE_NULL); checkNoOutput(skipNulls, ITERABLE_NULL_NULL); checkNoOutput(skipNulls, ITERABLE_FOUR_NULLS); checkResult(skipNulls, ITERABLE_1, "1"); checkResult(skipNulls, ITERABLE_12, "1-2"); checkResult(skipNulls, ITERABLE_123, "1-2-3"); checkResult(skipNulls, ITERABLE_NULL_1, "1"); checkResult(skipNulls, ITERABLE_1_NULL, "1"); checkResult(skipNulls, ITERABLE_1_NULL_2, "1-2"); } public void testUseForNull() { Joiner zeroForNull = J.useForNull("0"); checkNoOutput(zeroForNull, ITERABLE_); checkResult(zeroForNull, ITERABLE_1, "1"); checkResult(zeroForNull, ITERABLE_12, "1-2"); checkResult(zeroForNull, ITERABLE_123, "1-2-3"); checkResult(zeroForNull, ITERABLE_NULL, "0"); checkResult(zeroForNull, ITERABLE_NULL_NULL, "0-0"); checkResult(zeroForNull, ITERABLE_NULL_1, "0-1"); checkResult(zeroForNull, ITERABLE_1_NULL, "1-0"); checkResult(zeroForNull, ITERABLE_1_NULL_2, "1-0-2"); checkResult(zeroForNull, ITERABLE_FOUR_NULLS, "0-0-0-0"); } private static void checkNoOutput(Joiner joiner, Iterable<Integer> set) { assertEquals("", joiner.join(set)); assertEquals("", joiner.join(set.iterator())); Object[] array = Lists.newArrayList(set).toArray(new Integer[0]); assertEquals("", joiner.join(array)); StringBuilder sb1FromIterable = new StringBuilder(); assertSame(sb1FromIterable, joiner.appendTo(sb1FromIterable, set)); assertEquals(0, sb1FromIterable.length()); StringBuilder sb1FromIterator = new StringBuilder(); assertSame(sb1FromIterator, joiner.appendTo(sb1FromIterator, set)); assertEquals(0, sb1FromIterator.length()); StringBuilder sb2 = new StringBuilder(); assertSame(sb2, joiner.appendTo(sb2, array)); assertEquals(0, sb2.length()); try { joiner.appendTo(NASTY_APPENDABLE, set); } catch (IOException e) { throw new AssertionError(e); } try { joiner.appendTo(NASTY_APPENDABLE, set.iterator()); } catch (IOException e) { throw new AssertionError(e); } try { joiner.appendTo(NASTY_APPENDABLE, array); } catch (IOException e) { throw new AssertionError(e); } } private static final Appendable NASTY_APPENDABLE = new Appendable() { @Override public Appendable append(CharSequence csq) throws IOException { throw new IOException(); } @Override public Appendable append(CharSequence csq, int start, int end) throws IOException { throw new IOException(); } @Override public Appendable append(char c) throws IOException { throw new IOException(); } }; private static void checkResult(Joiner joiner, Iterable<Integer> parts, String expected) { assertEquals(expected, joiner.join(parts)); assertEquals(expected, joiner.join(parts.iterator())); StringBuilder sb1FromIterable = new StringBuilder().append('x'); joiner.appendTo(sb1FromIterable, parts); assertEquals("x" + expected, sb1FromIterable.toString()); StringBuilder sb1FromIterator = new StringBuilder().append('x'); joiner.appendTo(sb1FromIterator, parts.iterator()); assertEquals("x" + expected, sb1FromIterator.toString()); Integer[] partsArray = Lists.newArrayList(parts).toArray(new Integer[0]); assertEquals(expected, joiner.join(partsArray)); StringBuilder sb2 = new StringBuilder().append('x'); joiner.appendTo(sb2, partsArray); assertEquals("x" + expected, sb2.toString()); int num = partsArray.length - 2; if (num >= 0) { Object[] rest = new Integer[num]; for (int i = 0; i < num; i++) { rest[i] = partsArray[i + 2]; } assertEquals(expected, joiner.join(partsArray[0], partsArray[1], rest)); StringBuilder sb3 = new StringBuilder().append('x'); joiner.appendTo(sb3, partsArray[0], partsArray[1], rest); assertEquals("x" + expected, sb3.toString()); } } public void test_useForNull_skipNulls() { Joiner j = Joiner.on("x").useForNull("y"); try { j = j.skipNulls(); fail(); } catch (UnsupportedOperationException expected) { } } public void test_skipNulls_useForNull() { Joiner j = Joiner.on("x").skipNulls(); try { j = j.useForNull("y"); fail(); } catch (UnsupportedOperationException expected) { } } public void test_useForNull_twice() { Joiner j = Joiner.on("x").useForNull("y"); try { j = j.useForNull("y"); fail(); } catch (UnsupportedOperationException expected) { } } public void testMap() { MapJoiner j = Joiner.on(";").withKeyValueSeparator(":"); assertEquals("", j.join(ImmutableMap.of())); assertEquals(":", j.join(ImmutableMap.of("", ""))); Map<String, String> mapWithNulls = Maps.newLinkedHashMap(); mapWithNulls.put("a", null); mapWithNulls.put(null, "b"); try { j.join(mapWithNulls); fail(); } catch (NullPointerException expected) { } assertEquals("a:00;00:b", j.useForNull("00").join(mapWithNulls)); StringBuilder sb = new StringBuilder(); j.appendTo(sb, ImmutableMap.of(1, 2, 3, 4, 5, 6)); assertEquals("1:2;3:4;5:6", sb.toString()); } public void testEntries() { MapJoiner j = Joiner.on(";").withKeyValueSeparator(":"); assertEquals("", j.join(ImmutableMultimap.of().entries())); assertEquals("", j.join(ImmutableMultimap.of().entries().iterator())); assertEquals(":", j.join(ImmutableMultimap.of("", "").entries())); assertEquals(":", j.join(ImmutableMultimap.of("", "").entries().iterator())); assertEquals("1:a;1:b", j.join(ImmutableMultimap.of("1", "a", "1", "b").entries())); assertEquals("1:a;1:b", j.join(ImmutableMultimap.of("1", "a", "1", "b").entries().iterator())); Map<String, String> mapWithNulls = Maps.newLinkedHashMap(); mapWithNulls.put("a", null); mapWithNulls.put(null, "b"); Set<Map.Entry<String, String>> entriesWithNulls = mapWithNulls.entrySet(); try { j.join(entriesWithNulls); fail(); } catch (NullPointerException expected) { } try { j.join(entriesWithNulls.iterator()); fail(); } catch (NullPointerException expected) { } assertEquals("a:00;00:b", j.useForNull("00").join(entriesWithNulls)); assertEquals("a:00;00:b", j.useForNull("00").join(entriesWithNulls.iterator())); StringBuilder sb1 = new StringBuilder(); j.appendTo(sb1, ImmutableMultimap.of(1, 2, 3, 4, 5, 6, 1, 3, 5, 10).entries()); assertEquals("1:2;1:3;3:4;5:6;5:10", sb1.toString()); StringBuilder sb2 = new StringBuilder(); j.appendTo(sb2, ImmutableMultimap.of(1, 2, 3, 4, 5, 6, 1, 3, 5, 10).entries().iterator()); assertEquals("1:2;1:3;3:4;5:6;5:10", sb2.toString()); } @SuppressWarnings("ReturnValueIgnored") public void test_skipNulls_onMap() { Joiner j = Joiner.on(",").skipNulls(); try { j.withKeyValueSeparator("/"); fail(); } catch (UnsupportedOperationException expected) { } } private static class DontStringMeBro implements CharSequence { @Override public int length() { return 3; } @Override public char charAt(int index) { return "foo".charAt(index); } @Override public CharSequence subSequence(int start, int end) { return "foo".subSequence(start, end); } @Override public String toString() { fail("shouldn't be invoked"); return null; } } // Don't do this. private static class IterableIterator implements Iterable<Integer>, Iterator<Integer> { private static final ImmutableSet<Integer> INTEGERS = ImmutableSet.of(1, 2, 3, 4); private final Iterator<Integer> iterator; public IterableIterator() { this.iterator = iterator(); } @Override public Iterator<Integer> iterator() { return INTEGERS.iterator(); } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public Integer next() { return iterator.next(); } @Override public void remove() { iterator.remove(); } } }
Java
/* * Copyright (C) 2005 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF 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.common.collect.ImmutableMap; import com.google.common.collect.Maps; import com.google.common.testing.EqualsTester; import junit.framework.TestCase; import java.io.Serializable; import java.util.Map; /** * Tests for {@link Functions}. * * @author Mike Bostock * @author Vlad Patryshev */ @GwtCompatible(emulated = true) public class FunctionsTest extends TestCase { public void testIdentity_same() { Function<String, String> identity = Functions.identity(); assertNull(identity.apply(null)); assertSame("foo", identity.apply("foo")); } public void testIdentity_notSame() { Function<Long, Long> identity = Functions.identity(); assertNotSame(new Long(135135L), identity.apply(new Long(135135L))); } public void testToStringFunction_apply() { assertEquals("3", Functions.toStringFunction().apply(3)); assertEquals("hiya", Functions.toStringFunction().apply("hiya")); assertEquals("I'm a string", Functions.toStringFunction().apply( new Object() { @Override public String toString() { return "I'm a string"; } })); try { Functions.toStringFunction().apply(null); fail("expected NullPointerException"); } catch (NullPointerException e) { // expected } } public void testForMapWithoutDefault() { Map<String, Integer> map = Maps.newHashMap(); map.put("One", 1); map.put("Three", 3); map.put("Null", null); Function<String, Integer> function = Functions.forMap(map); assertEquals(1, function.apply("One").intValue()); assertEquals(3, function.apply("Three").intValue()); assertNull(function.apply("Null")); try { function.apply("Two"); fail(); } catch (IllegalArgumentException expected) { } new EqualsTester() .addEqualityGroup(function, Functions.forMap(map)) .addEqualityGroup(Functions.forMap(map, 42)) .testEquals(); } public void testForMapWithDefault() { Map<String, Integer> map = Maps.newHashMap(); map.put("One", 1); map.put("Three", 3); map.put("Null", null); Function<String, Integer> function = Functions.forMap(map, 42); assertEquals(1, function.apply("One").intValue()); assertEquals(42, function.apply("Two").intValue()); assertEquals(3, function.apply("Three").intValue()); assertNull(function.apply("Null")); new EqualsTester() .addEqualityGroup(function, Functions.forMap(map, 42)) .addEqualityGroup(Functions.forMap(map)) .addEqualityGroup(Functions.forMap(map, null)) .addEqualityGroup(Functions.forMap(map, 43)) .testEquals(); } public void testForMapWithDefault_null() { ImmutableMap<String, Integer> map = ImmutableMap.of("One", 1); Function<String, Integer> function = Functions.forMap(map, null); assertEquals((Integer) 1, function.apply("One")); assertNull(function.apply("Two")); // check basic sanity of equals and hashCode new EqualsTester() .addEqualityGroup(function) .addEqualityGroup(Functions.forMap(map, 1)) .testEquals(); } public void testForMapWildCardWithDefault() { Map<String, Integer> map = Maps.newHashMap(); map.put("One", 1); map.put("Three", 3); Number number = Double.valueOf(42); Function<String, Number> function = Functions.forMap(map, number); assertEquals(1, function.apply("One").intValue()); assertEquals(number, function.apply("Two")); assertEquals(3L, function.apply("Three").longValue()); } public void testComposition() { Map<String, Integer> mJapaneseToInteger = Maps.newHashMap(); mJapaneseToInteger.put("Ichi", 1); mJapaneseToInteger.put("Ni", 2); mJapaneseToInteger.put("San", 3); Function<String, Integer> japaneseToInteger = Functions.forMap(mJapaneseToInteger); Map<Integer, String> mIntegerToSpanish = Maps.newHashMap(); mIntegerToSpanish.put(1, "Uno"); mIntegerToSpanish.put(3, "Tres"); mIntegerToSpanish.put(4, "Cuatro"); Function<Integer, String> integerToSpanish = Functions.forMap(mIntegerToSpanish); Function<String, String> japaneseToSpanish = Functions.compose(integerToSpanish, japaneseToInteger); assertEquals("Uno", japaneseToSpanish.apply("Ichi")); try { japaneseToSpanish.apply("Ni"); fail(); } catch (IllegalArgumentException e) { } assertEquals("Tres", japaneseToSpanish.apply("San")); try { japaneseToSpanish.apply("Shi"); fail(); } catch (IllegalArgumentException e) { } new EqualsTester() .addEqualityGroup( japaneseToSpanish, Functions.compose(integerToSpanish, japaneseToInteger)) .addEqualityGroup(japaneseToInteger) .addEqualityGroup(integerToSpanish) .addEqualityGroup( Functions.compose(japaneseToInteger, integerToSpanish)) .testEquals(); } public void testCompositionWildcard() { Map<String, Integer> mapJapaneseToInteger = Maps.newHashMap(); Function<String, Integer> japaneseToInteger = Functions.forMap(mapJapaneseToInteger); Function<Object, String> numberToSpanish = Functions.constant("Yo no se"); Function<String, String> japaneseToSpanish = Functions.compose(numberToSpanish, japaneseToInteger); } private static class HashCodeFunction implements Function<Object, Integer> { @Override public Integer apply(Object o) { return (o == null) ? 0 : o.hashCode(); } } public void testComposeOfFunctionsIsAssociative() { Map<Float, String> m = ImmutableMap.of( 4.0f, "A", 3.0f, "B", 2.0f, "C", 1.0f, "D"); Function<? super Integer, Boolean> h = Functions.constant(Boolean.TRUE); Function<? super String, Integer> g = new HashCodeFunction(); Function<Float, String> f = Functions.forMap(m, "F"); Function<Float, Boolean> c1 = Functions.compose(Functions.compose(h, g), f); Function<Float, Boolean> c2 = Functions.compose(h, Functions.compose(g, f)); // Might be nice (eventually) to have: // assertEquals(c1, c2); // But for now, settle for this: assertEquals(c1.hashCode(), c2.hashCode()); assertEquals(c1.apply(1.0f), c2.apply(1.0f)); assertEquals(c1.apply(5.0f), c2.apply(5.0f)); } public void testComposeOfPredicateAndFunctionIsAssociative() { Map<Float, String> m = ImmutableMap.of( 4.0f, "A", 3.0f, "B", 2.0f, "C", 1.0f, "D"); Predicate<? super Integer> h = Predicates.equalTo(42); Function<? super String, Integer> g = new HashCodeFunction(); Function<Float, String> f = Functions.forMap(m, "F"); Predicate<Float> p1 = Predicates.compose(Predicates.compose(h, g), f); Predicate<Float> p2 = Predicates.compose(h, Functions.compose(g, f)); // Might be nice (eventually) to have: // assertEquals(p1, p2); // But for now, settle for this: assertEquals(p1.hashCode(), p2.hashCode()); assertEquals(p1.apply(1.0f), p2.apply(1.0f)); assertEquals(p1.apply(5.0f), p2.apply(5.0f)); } public void testForPredicate() { Function<Object, Boolean> alwaysTrue = Functions.forPredicate(Predicates.alwaysTrue()); Function<Object, Boolean> alwaysFalse = Functions.forPredicate(Predicates.alwaysFalse()); assertTrue(alwaysTrue.apply(0)); assertFalse(alwaysFalse.apply(0)); new EqualsTester() .addEqualityGroup( alwaysTrue, Functions.forPredicate(Predicates.alwaysTrue())) .addEqualityGroup(alwaysFalse) .addEqualityGroup(Functions.identity()) .testEquals(); } public void testConstant() { Function<Object, Object> f = Functions.<Object>constant("correct"); assertEquals("correct", f.apply(new Object())); assertEquals("correct", f.apply(null)); Function<Object, String> g = Functions.constant(null); assertEquals(null, g.apply(2)); assertEquals(null, g.apply(null)); new EqualsTester() .addEqualityGroup(f, Functions.constant("correct")) .addEqualityGroup(Functions.constant("incorrect")) .addEqualityGroup(Functions.toStringFunction()) .addEqualityGroup(g) .testEquals(); new EqualsTester() .addEqualityGroup(g, Functions.constant(null)) .addEqualityGroup(Functions.constant("incorrect")) .addEqualityGroup(Functions.toStringFunction()) .addEqualityGroup(f) .testEquals(); } private static class CountingSupplier implements Supplier<Integer>, Serializable { private static final long serialVersionUID = 0; private int value; @Override public Integer get() { return ++value; } @Override public boolean equals(Object obj) { if (obj instanceof CountingSupplier) { return this.value == ((CountingSupplier) obj).value; } return false; } @Override public int hashCode() { return value; } } public void testForSupplier() { Supplier<Integer> supplier = new CountingSupplier(); Function<Object, Integer> function = Functions.forSupplier(supplier); assertEquals(1, (int) function.apply(null)); assertEquals(2, (int) function.apply("foo")); new EqualsTester() .addEqualityGroup(function, Functions.forSupplier(supplier)) .addEqualityGroup(Functions.forSupplier(new CountingSupplier())) .addEqualityGroup(Functions.forSupplier(Suppliers.ofInstance(12))) .addEqualityGroup(Functions.toStringFunction()) .testEquals(); } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Unit test for {@link Ints}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) @SuppressWarnings("cast") // redundant casts are intentional and harmless public class IntsTest extends TestCase { private static final int[] EMPTY = {}; private static final int[] ARRAY1 = {(int) 1}; private static final int[] ARRAY234 = {(int) 2, (int) 3, (int) 4}; private static final int LEAST = Integer.MIN_VALUE; private static final int GREATEST = Integer.MAX_VALUE; private static final int[] VALUES = { LEAST, (int) -1, (int) 0, (int) 1, GREATEST }; public void testHashCode() { for (int value : VALUES) { assertEquals(((Integer) value).hashCode(), Ints.hashCode(value)); } } public void testCheckedCast() { for (int value : VALUES) { assertEquals(value, Ints.checkedCast((long) value)); } assertCastFails(GREATEST + 1L); assertCastFails(LEAST - 1L); assertCastFails(Long.MAX_VALUE); assertCastFails(Long.MIN_VALUE); } public void testSaturatedCast() { for (int value : VALUES) { assertEquals(value, Ints.saturatedCast((long) value)); } assertEquals(GREATEST, Ints.saturatedCast(GREATEST + 1L)); assertEquals(LEAST, Ints.saturatedCast(LEAST - 1L)); assertEquals(GREATEST, Ints.saturatedCast(Long.MAX_VALUE)); assertEquals(LEAST, Ints.saturatedCast(Long.MIN_VALUE)); } private static void assertCastFails(long value) { try { Ints.checkedCast(value); fail("Cast to int should have failed: " + value); } catch (IllegalArgumentException ex) { assertTrue(value + " not found in exception text: " + ex.getMessage(), ex.getMessage().contains(String.valueOf(value))); } } public void testCompare() { for (int x : VALUES) { for (int y : VALUES) { // note: spec requires only that the sign is the same assertEquals(x + ", " + y, Integer.valueOf(x).compareTo(y), Ints.compare(x, y)); } } } public void testContains() { assertFalse(Ints.contains(EMPTY, (int) 1)); assertFalse(Ints.contains(ARRAY1, (int) 2)); assertFalse(Ints.contains(ARRAY234, (int) 1)); assertTrue(Ints.contains(new int[] {(int) -1}, (int) -1)); assertTrue(Ints.contains(ARRAY234, (int) 2)); assertTrue(Ints.contains(ARRAY234, (int) 3)); assertTrue(Ints.contains(ARRAY234, (int) 4)); } public void testIndexOf() { assertEquals(-1, Ints.indexOf(EMPTY, (int) 1)); assertEquals(-1, Ints.indexOf(ARRAY1, (int) 2)); assertEquals(-1, Ints.indexOf(ARRAY234, (int) 1)); assertEquals(0, Ints.indexOf( new int[] {(int) -1}, (int) -1)); assertEquals(0, Ints.indexOf(ARRAY234, (int) 2)); assertEquals(1, Ints.indexOf(ARRAY234, (int) 3)); assertEquals(2, Ints.indexOf(ARRAY234, (int) 4)); assertEquals(1, Ints.indexOf( new int[] { (int) 2, (int) 3, (int) 2, (int) 3 }, (int) 3)); } public void testIndexOf_arrayTarget() { assertEquals(0, Ints.indexOf(EMPTY, EMPTY)); assertEquals(0, Ints.indexOf(ARRAY234, EMPTY)); assertEquals(-1, Ints.indexOf(EMPTY, ARRAY234)); assertEquals(-1, Ints.indexOf(ARRAY234, ARRAY1)); assertEquals(-1, Ints.indexOf(ARRAY1, ARRAY234)); assertEquals(0, Ints.indexOf(ARRAY1, ARRAY1)); assertEquals(0, Ints.indexOf(ARRAY234, ARRAY234)); assertEquals(0, Ints.indexOf( ARRAY234, new int[] { (int) 2, (int) 3 })); assertEquals(1, Ints.indexOf( ARRAY234, new int[] { (int) 3, (int) 4 })); assertEquals(1, Ints.indexOf(ARRAY234, new int[] { (int) 3 })); assertEquals(2, Ints.indexOf(ARRAY234, new int[] { (int) 4 })); assertEquals(1, Ints.indexOf(new int[] { (int) 2, (int) 3, (int) 3, (int) 3, (int) 3 }, new int[] { (int) 3 } )); assertEquals(2, Ints.indexOf( new int[] { (int) 2, (int) 3, (int) 2, (int) 3, (int) 4, (int) 2, (int) 3}, new int[] { (int) 2, (int) 3, (int) 4} )); assertEquals(1, Ints.indexOf( new int[] { (int) 2, (int) 2, (int) 3, (int) 4, (int) 2, (int) 3, (int) 4}, new int[] { (int) 2, (int) 3, (int) 4} )); assertEquals(-1, Ints.indexOf( new int[] { (int) 4, (int) 3, (int) 2}, new int[] { (int) 2, (int) 3, (int) 4} )); } public void testLastIndexOf() { assertEquals(-1, Ints.lastIndexOf(EMPTY, (int) 1)); assertEquals(-1, Ints.lastIndexOf(ARRAY1, (int) 2)); assertEquals(-1, Ints.lastIndexOf(ARRAY234, (int) 1)); assertEquals(0, Ints.lastIndexOf( new int[] {(int) -1}, (int) -1)); assertEquals(0, Ints.lastIndexOf(ARRAY234, (int) 2)); assertEquals(1, Ints.lastIndexOf(ARRAY234, (int) 3)); assertEquals(2, Ints.lastIndexOf(ARRAY234, (int) 4)); assertEquals(3, Ints.lastIndexOf( new int[] { (int) 2, (int) 3, (int) 2, (int) 3 }, (int) 3)); } public void testMax_noArgs() { try { Ints.max(); fail(); } catch (IllegalArgumentException expected) { } } public void testMax() { assertEquals(LEAST, Ints.max(LEAST)); assertEquals(GREATEST, Ints.max(GREATEST)); assertEquals((int) 9, Ints.max( (int) 8, (int) 6, (int) 7, (int) 5, (int) 3, (int) 0, (int) 9)); } public void testMin_noArgs() { try { Ints.min(); fail(); } catch (IllegalArgumentException expected) { } } public void testMin() { assertEquals(LEAST, Ints.min(LEAST)); assertEquals(GREATEST, Ints.min(GREATEST)); assertEquals((int) 0, Ints.min( (int) 8, (int) 6, (int) 7, (int) 5, (int) 3, (int) 0, (int) 9)); } public void testConcat() { assertTrue(Arrays.equals(EMPTY, Ints.concat())); assertTrue(Arrays.equals(EMPTY, Ints.concat(EMPTY))); assertTrue(Arrays.equals(EMPTY, Ints.concat(EMPTY, EMPTY, EMPTY))); assertTrue(Arrays.equals(ARRAY1, Ints.concat(ARRAY1))); assertNotSame(ARRAY1, Ints.concat(ARRAY1)); assertTrue(Arrays.equals(ARRAY1, Ints.concat(EMPTY, ARRAY1, EMPTY))); assertTrue(Arrays.equals( new int[] {(int) 1, (int) 1, (int) 1}, Ints.concat(ARRAY1, ARRAY1, ARRAY1))); assertTrue(Arrays.equals( new int[] {(int) 1, (int) 2, (int) 3, (int) 4}, Ints.concat(ARRAY1, ARRAY234))); } public void testEnsureCapacity() { assertSame(EMPTY, Ints.ensureCapacity(EMPTY, 0, 1)); assertSame(ARRAY1, Ints.ensureCapacity(ARRAY1, 0, 1)); assertSame(ARRAY1, Ints.ensureCapacity(ARRAY1, 1, 1)); assertTrue(Arrays.equals( new int[] {(int) 1, (int) 0, (int) 0}, Ints.ensureCapacity(ARRAY1, 2, 1))); } public void testEnsureCapacity_fail() { try { Ints.ensureCapacity(ARRAY1, -1, 1); fail(); } catch (IllegalArgumentException expected) { } try { // notice that this should even fail when no growth was needed Ints.ensureCapacity(ARRAY1, 1, -1); fail(); } catch (IllegalArgumentException expected) { } } public void testJoin() { assertEquals("", Ints.join(",", EMPTY)); assertEquals("1", Ints.join(",", ARRAY1)); assertEquals("1,2", Ints.join(",", (int) 1, (int) 2)); assertEquals("123", Ints.join("", (int) 1, (int) 2, (int) 3)); } public void testLexicographicalComparator() { List<int[]> ordered = Arrays.asList( new int[] {}, new int[] {LEAST}, new int[] {LEAST, LEAST}, new int[] {LEAST, (int) 1}, new int[] {(int) 1}, new int[] {(int) 1, LEAST}, new int[] {GREATEST, GREATEST - (int) 1}, new int[] {GREATEST, GREATEST}, new int[] {GREATEST, GREATEST, GREATEST}); Comparator<int[]> comparator = Ints.lexicographicalComparator(); Helpers.testComparator(comparator, ordered); } public void testToArray() { // need explicit type parameter to avoid javac warning!? List<Integer> none = Arrays.<Integer>asList(); assertTrue(Arrays.equals(EMPTY, Ints.toArray(none))); List<Integer> one = Arrays.asList((int) 1); assertTrue(Arrays.equals(ARRAY1, Ints.toArray(one))); int[] array = {(int) 0, (int) 1, (int) 0xdeadbeef}; List<Integer> three = Arrays.asList((int) 0, (int) 1, (int) 0xdeadbeef); assertTrue(Arrays.equals(array, Ints.toArray(three))); assertTrue(Arrays.equals(array, Ints.toArray(Ints.asList(array)))); } public void testToArray_threadSafe() { for (int delta : new int[] { +1, 0, -1 }) { for (int i = 0; i < VALUES.length; i++) { List<Integer> list = Ints.asList(VALUES).subList(0, i); Collection<Integer> misleadingSize = Helpers.misleadingSizeCollection(delta); misleadingSize.addAll(list); int[] arr = Ints.toArray(misleadingSize); assertEquals(i, arr.length); for (int j = 0; j < i; j++) { assertEquals(VALUES[j], arr[j]); } } } } public void testToArray_withNull() { List<Integer> list = Arrays.asList((int) 0, (int) 1, null); try { Ints.toArray(list); fail(); } catch (NullPointerException expected) { } } public void testToArray_withConversion() { int[] array = {0, 1, 2}; List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2); List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2); List<Integer> ints = Arrays.asList(0, 1, 2); List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2); List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2); List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2); assertTrue(Arrays.equals(array, Ints.toArray(bytes))); assertTrue(Arrays.equals(array, Ints.toArray(shorts))); assertTrue(Arrays.equals(array, Ints.toArray(ints))); assertTrue(Arrays.equals(array, Ints.toArray(floats))); assertTrue(Arrays.equals(array, Ints.toArray(longs))); assertTrue(Arrays.equals(array, Ints.toArray(doubles))); } public void testAsList_isAView() { int[] array = {(int) 0, (int) 1}; List<Integer> list = Ints.asList(array); list.set(0, (int) 2); assertTrue(Arrays.equals(new int[] {(int) 2, (int) 1}, array)); array[1] = (int) 3; assertEquals(Arrays.asList((int) 2, (int) 3), list); } public void testAsList_toArray_roundTrip() { int[] array = { (int) 0, (int) 1, (int) 2 }; List<Integer> list = Ints.asList(array); int[] newArray = Ints.toArray(list); // Make sure it returned a copy list.set(0, (int) 4); assertTrue(Arrays.equals( new int[] { (int) 0, (int) 1, (int) 2 }, newArray)); newArray[1] = (int) 5; assertEquals((int) 1, (int) list.get(1)); } // This test stems from a real bug found by andrewk public void testAsList_subList_toArray_roundTrip() { int[] array = { (int) 0, (int) 1, (int) 2, (int) 3 }; List<Integer> list = Ints.asList(array); assertTrue(Arrays.equals(new int[] { (int) 1, (int) 2 }, Ints.toArray(list.subList(1, 3)))); assertTrue(Arrays.equals(new int[] {}, Ints.toArray(list.subList(2, 2)))); } public void testAsListEmpty() { assertSame(Collections.emptyList(), Ints.asList(EMPTY)); } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import junit.framework.TestCase; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** * Tests for UnsignedInts * * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class UnsignedIntsTest extends TestCase { private static final long[] UNSIGNED_INTS = { 0L, 1L, 2L, 3L, 0x12345678L, 0x5a4316b8L, 0x6cf78a4bL, 0xff1a618bL, 0xfffffffdL, 0xfffffffeL, 0xffffffffL}; private static final int LEAST = (int) 0L; private static final int GREATEST = (int) 0xffffffffL; public void testToLong() { for (long a : UNSIGNED_INTS) { assertEquals(a, UnsignedInts.toLong((int) a)); } } public void testCompare() { for (long a : UNSIGNED_INTS) { for (long b : UNSIGNED_INTS) { int cmpAsLongs = Longs.compare(a, b); int cmpAsUInt = UnsignedInts.compare((int) a, (int) b); assertEquals(Integer.signum(cmpAsLongs), Integer.signum(cmpAsUInt)); } } } public void testMax_noArgs() { try { UnsignedInts.max(); fail(); } catch (IllegalArgumentException expected) { } } public void testMax() { assertEquals(LEAST, UnsignedInts.max(LEAST)); assertEquals(GREATEST, UnsignedInts.max(GREATEST)); assertEquals((int) 0xff1a618bL, UnsignedInts.max( (int) 8L, (int) 6L, (int) 7L, (int) 0x12345678L, (int) 0x5a4316b8L, (int) 0xff1a618bL, (int) 0L)); } public void testMin_noArgs() { try { UnsignedInts.min(); fail(); } catch (IllegalArgumentException expected) { } } public void testMin() { assertEquals(LEAST, UnsignedInts.min(LEAST)); assertEquals(GREATEST, UnsignedInts.min(GREATEST)); assertEquals((int) 0L, UnsignedInts.min( (int) 8L, (int) 6L, (int) 7L, (int) 0x12345678L, (int) 0x5a4316b8L, (int) 0xff1a618bL, (int) 0L)); } public void testLexicographicalComparator() { List<int[]> ordered = Arrays.asList( new int[] {}, new int[] {LEAST}, new int[] {LEAST, LEAST}, new int[] {LEAST, (int) 1L}, new int[] {(int) 1L}, new int[] {(int) 1L, LEAST}, new int[] {GREATEST, (GREATEST - (int) 1L)}, new int[] {GREATEST, GREATEST}, new int[] {GREATEST, GREATEST, GREATEST} ); Comparator<int[]> comparator = UnsignedInts.lexicographicalComparator(); Helpers.testComparator(comparator, ordered); } public void testDivide() { for (long a : UNSIGNED_INTS) { for (long b : UNSIGNED_INTS) { try { assertEquals((int) (a / b), UnsignedInts.divide((int) a, (int) b)); assertFalse(b == 0); } catch (ArithmeticException e) { assertEquals(0, b); } } } } public void testRemainder() { for (long a : UNSIGNED_INTS) { for (long b : UNSIGNED_INTS) { try { assertEquals((int) (a % b), UnsignedInts.remainder((int) a, (int) b)); assertFalse(b == 0); } catch (ArithmeticException e) { assertEquals(0, b); } } } } public void testParseInt() { try { for (long a : UNSIGNED_INTS) { assertEquals((int) a, UnsignedInts.parseUnsignedInt(Long.toString(a))); } } catch (NumberFormatException e) { fail(e.getMessage()); } try { UnsignedInts.parseUnsignedInt(Long.toString(1L << 32)); fail("Expected NumberFormatException"); } catch (NumberFormatException expected) {} } public void testParseIntWithRadix() throws NumberFormatException { for (long a : UNSIGNED_INTS) { for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) { assertEquals((int) a, UnsignedInts.parseUnsignedInt(Long.toString(a, radix), radix)); } } // loops through all legal radix values. for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) { // tests can successfully parse a number string with this radix. String maxAsString = Long.toString((1L << 32) - 1, radix); assertEquals(-1, UnsignedInts.parseUnsignedInt(maxAsString, radix)); try { // tests that we get exception whre an overflow would occur. long overflow = 1L << 32; String overflowAsString = Long.toString(overflow, radix); UnsignedInts.parseUnsignedInt(overflowAsString, radix); fail(); } catch (NumberFormatException expected) {} } } public void testParseIntThrowsExceptionForInvalidRadix() { // Valid radix values are Character.MIN_RADIX to Character.MAX_RADIX, // inclusive. try { UnsignedInts.parseUnsignedInt("0", Character.MIN_RADIX - 1); fail(); } catch (NumberFormatException expected) {} try { UnsignedInts.parseUnsignedInt("0", Character.MAX_RADIX + 1); fail(); } catch (NumberFormatException expected) {} // The radix is used as an array index, so try a negative value. try { UnsignedInts.parseUnsignedInt("0", -1); fail(); } catch (NumberFormatException expected) {} } public void testDecodeInt() { assertEquals(0xffffffff, UnsignedInts.decode("0xffffffff")); assertEquals(01234567, UnsignedInts.decode("01234567")); // octal assertEquals(0x12345678, UnsignedInts.decode("#12345678")); assertEquals(76543210, UnsignedInts.decode("76543210")); assertEquals(0x13579135, UnsignedInts.decode("0x13579135")); assertEquals(0x13579135, UnsignedInts.decode("0X13579135")); assertEquals(0, UnsignedInts.decode("0")); } public void testDecodeIntFails() { try { // One more than maximum value UnsignedInts.decode("0xfffffffff"); fail(); } catch (NumberFormatException expected) { } try { UnsignedInts.decode("-5"); fail(); } catch (NumberFormatException expected) { } try { UnsignedInts.decode("-0x5"); fail(); } catch (NumberFormatException expected) { } try { UnsignedInts.decode("-05"); fail(); } catch (NumberFormatException expected) { } } public void testToString() { int[] bases = {2, 5, 7, 8, 10, 16}; for (long a : UNSIGNED_INTS) { for (int base : bases) { assertEquals(UnsignedInts.toString((int) a, base), Long.toString(a, base)); } } } public void testJoin() { assertEquals("", join()); assertEquals("1", join(1)); assertEquals("1,2", join(1, 2)); assertEquals("4294967295,2147483648", join(-1, Integer.MIN_VALUE)); assertEquals("123", UnsignedInts.join("", 1, 2, 3)); } private static String join(int... values) { return UnsignedInts.join(",", values); } }
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 java.lang.Double.NaN; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Unit test for {@link Doubles}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) @SuppressWarnings("cast") // redundant casts are intentional and harmless public class DoublesTest extends TestCase { private static final double[] EMPTY = {}; private static final double[] ARRAY1 = {(double) 1}; private static final double[] ARRAY234 = {(double) 2, (double) 3, (double) 4}; private static final double LEAST = Double.NEGATIVE_INFINITY; private static final double GREATEST = Double.POSITIVE_INFINITY; private static final double[] NUMBERS = new double[] { LEAST, -Double.MAX_VALUE, -1.0, -0.5, -0.1, -0.0, 0.0, 0.1, 0.5, 1.0, Double.MAX_VALUE, GREATEST, Double.MIN_NORMAL, -Double.MIN_NORMAL, Double.MIN_VALUE, -Double.MIN_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE }; private static final double[] VALUES = Doubles.concat(NUMBERS, new double[] {NaN}); public void testHashCode() { for (double value : VALUES) { assertEquals(((Double) value).hashCode(), Doubles.hashCode(value)); } } public void testIsFinite() { for (double value : NUMBERS) { assertEquals(!(Double.isNaN(value) || Double.isInfinite(value)), Doubles.isFinite(value)); } } public void testCompare() { for (double x : VALUES) { for (double y : VALUES) { // note: spec requires only that the sign is the same assertEquals(x + ", " + y, Double.valueOf(x).compareTo(y), Doubles.compare(x, y)); } } } public void testContains() { assertFalse(Doubles.contains(EMPTY, (double) 1)); assertFalse(Doubles.contains(ARRAY1, (double) 2)); assertFalse(Doubles.contains(ARRAY234, (double) 1)); assertTrue(Doubles.contains(new double[] {(double) -1}, (double) -1)); assertTrue(Doubles.contains(ARRAY234, (double) 2)); assertTrue(Doubles.contains(ARRAY234, (double) 3)); assertTrue(Doubles.contains(ARRAY234, (double) 4)); for (double value : NUMBERS) { assertTrue("" + value, Doubles.contains(new double[] {5.0, value}, value)); } assertFalse(Doubles.contains(new double[] {5.0, NaN}, NaN)); } public void testIndexOf() { assertEquals(-1, Doubles.indexOf(EMPTY, (double) 1)); assertEquals(-1, Doubles.indexOf(ARRAY1, (double) 2)); assertEquals(-1, Doubles.indexOf(ARRAY234, (double) 1)); assertEquals(0, Doubles.indexOf( new double[] {(double) -1}, (double) -1)); assertEquals(0, Doubles.indexOf(ARRAY234, (double) 2)); assertEquals(1, Doubles.indexOf(ARRAY234, (double) 3)); assertEquals(2, Doubles.indexOf(ARRAY234, (double) 4)); assertEquals(1, Doubles.indexOf( new double[] { (double) 2, (double) 3, (double) 2, (double) 3 }, (double) 3)); for (double value : NUMBERS) { assertEquals("" + value, 1, Doubles.indexOf(new double[] {5.0, value}, value)); } assertEquals(-1, Doubles.indexOf(new double[] {5.0, NaN}, NaN)); } public void testIndexOf_arrayTarget() { assertEquals(0, Doubles.indexOf(EMPTY, EMPTY)); assertEquals(0, Doubles.indexOf(ARRAY234, EMPTY)); assertEquals(-1, Doubles.indexOf(EMPTY, ARRAY234)); assertEquals(-1, Doubles.indexOf(ARRAY234, ARRAY1)); assertEquals(-1, Doubles.indexOf(ARRAY1, ARRAY234)); assertEquals(0, Doubles.indexOf(ARRAY1, ARRAY1)); assertEquals(0, Doubles.indexOf(ARRAY234, ARRAY234)); assertEquals(0, Doubles.indexOf( ARRAY234, new double[] { (double) 2, (double) 3 })); assertEquals(1, Doubles.indexOf( ARRAY234, new double[] { (double) 3, (double) 4 })); assertEquals(1, Doubles.indexOf(ARRAY234, new double[] { (double) 3 })); assertEquals(2, Doubles.indexOf(ARRAY234, new double[] { (double) 4 })); assertEquals(1, Doubles.indexOf(new double[] { (double) 2, (double) 3, (double) 3, (double) 3, (double) 3 }, new double[] { (double) 3 } )); assertEquals(2, Doubles.indexOf( new double[] { (double) 2, (double) 3, (double) 2, (double) 3, (double) 4, (double) 2, (double) 3}, new double[] { (double) 2, (double) 3, (double) 4} )); assertEquals(1, Doubles.indexOf( new double[] { (double) 2, (double) 2, (double) 3, (double) 4, (double) 2, (double) 3, (double) 4}, new double[] { (double) 2, (double) 3, (double) 4} )); assertEquals(-1, Doubles.indexOf( new double[] { (double) 4, (double) 3, (double) 2}, new double[] { (double) 2, (double) 3, (double) 4} )); for (double value : NUMBERS) { assertEquals("" + value, 1, Doubles.indexOf( new double[] {5.0, value, value, 5.0}, new double[] {value, value})); } assertEquals(-1, Doubles.indexOf( new double[] {5.0, NaN, NaN, 5.0}, new double[] {NaN, NaN})); } public void testLastIndexOf() { assertEquals(-1, Doubles.lastIndexOf(EMPTY, (double) 1)); assertEquals(-1, Doubles.lastIndexOf(ARRAY1, (double) 2)); assertEquals(-1, Doubles.lastIndexOf(ARRAY234, (double) 1)); assertEquals(0, Doubles.lastIndexOf( new double[] {(double) -1}, (double) -1)); assertEquals(0, Doubles.lastIndexOf(ARRAY234, (double) 2)); assertEquals(1, Doubles.lastIndexOf(ARRAY234, (double) 3)); assertEquals(2, Doubles.lastIndexOf(ARRAY234, (double) 4)); assertEquals(3, Doubles.lastIndexOf( new double[] { (double) 2, (double) 3, (double) 2, (double) 3 }, (double) 3)); for (double value : NUMBERS) { assertEquals("" + value, 0, Doubles.lastIndexOf(new double[] {value, 5.0}, value)); } assertEquals(-1, Doubles.lastIndexOf(new double[] {NaN, 5.0}, NaN)); } public void testMax_noArgs() { try { Doubles.max(); fail(); } catch (IllegalArgumentException expected) { } } public void testMax() { assertEquals(LEAST, Doubles.max(LEAST)); assertEquals(GREATEST, Doubles.max(GREATEST)); assertEquals((double) 9, Doubles.max( (double) 8, (double) 6, (double) 7, (double) 5, (double) 3, (double) 0, (double) 9)); assertEquals(0.0, Doubles.max(-0.0, 0.0)); assertEquals(0.0, Doubles.max(0.0, -0.0)); assertEquals(GREATEST, Doubles.max(NUMBERS)); assertTrue(Double.isNaN(Doubles.max(VALUES))); } public void testMin_noArgs() { try { Doubles.min(); fail(); } catch (IllegalArgumentException expected) { } } public void testMin() { assertEquals(LEAST, Doubles.min(LEAST)); assertEquals(GREATEST, Doubles.min(GREATEST)); assertEquals((double) 0, Doubles.min( (double) 8, (double) 6, (double) 7, (double) 5, (double) 3, (double) 0, (double) 9)); assertEquals(-0.0, Doubles.min(-0.0, 0.0)); assertEquals(-0.0, Doubles.min(0.0, -0.0)); assertEquals(LEAST, Doubles.min(NUMBERS)); assertTrue(Double.isNaN(Doubles.min(VALUES))); } public void testConcat() { assertTrue(Arrays.equals(EMPTY, Doubles.concat())); assertTrue(Arrays.equals(EMPTY, Doubles.concat(EMPTY))); assertTrue(Arrays.equals(EMPTY, Doubles.concat(EMPTY, EMPTY, EMPTY))); assertTrue(Arrays.equals(ARRAY1, Doubles.concat(ARRAY1))); assertNotSame(ARRAY1, Doubles.concat(ARRAY1)); assertTrue(Arrays.equals(ARRAY1, Doubles.concat(EMPTY, ARRAY1, EMPTY))); assertTrue(Arrays.equals( new double[] {(double) 1, (double) 1, (double) 1}, Doubles.concat(ARRAY1, ARRAY1, ARRAY1))); assertTrue(Arrays.equals( new double[] {(double) 1, (double) 2, (double) 3, (double) 4}, Doubles.concat(ARRAY1, ARRAY234))); } public void testEnsureCapacity() { assertSame(EMPTY, Doubles.ensureCapacity(EMPTY, 0, 1)); assertSame(ARRAY1, Doubles.ensureCapacity(ARRAY1, 0, 1)); assertSame(ARRAY1, Doubles.ensureCapacity(ARRAY1, 1, 1)); assertTrue(Arrays.equals( new double[] {(double) 1, (double) 0, (double) 0}, Doubles.ensureCapacity(ARRAY1, 2, 1))); } public void testEnsureCapacity_fail() { try { Doubles.ensureCapacity(ARRAY1, -1, 1); fail(); } catch (IllegalArgumentException expected) { } try { // notice that this should even fail when no growth was needed Doubles.ensureCapacity(ARRAY1, 1, -1); fail(); } catch (IllegalArgumentException expected) { } } public void testJoinNonTrivialDoubles() { assertEquals("", Doubles.join(",", EMPTY)); assertEquals("1.2", Doubles.join(",", 1.2)); assertEquals("1.3,2.4", Doubles.join(",", 1.3, 2.4)); assertEquals("1.42.53.6", Doubles.join("", 1.4, 2.5, 3.6)); } public void testLexicographicalComparator() { List<double[]> ordered = Arrays.asList( new double[] {}, new double[] {LEAST}, new double[] {LEAST, LEAST}, new double[] {LEAST, (double) 1}, new double[] {(double) 1}, new double[] {(double) 1, LEAST}, new double[] {GREATEST, Double.MAX_VALUE}, new double[] {GREATEST, GREATEST}, new double[] {GREATEST, GREATEST, GREATEST}); Comparator<double[]> comparator = Doubles.lexicographicalComparator(); Helpers.testComparator(comparator, ordered); } public void testToArray() { // need explicit type parameter to avoid javac warning!? List<Double> none = Arrays.<Double>asList(); assertTrue(Arrays.equals(EMPTY, Doubles.toArray(none))); List<Double> one = Arrays.asList((double) 1); assertTrue(Arrays.equals(ARRAY1, Doubles.toArray(one))); double[] array = {(double) 0, (double) 1, Math.PI}; List<Double> three = Arrays.asList((double) 0, (double) 1, Math.PI); assertTrue(Arrays.equals(array, Doubles.toArray(three))); assertTrue(Arrays.equals(array, Doubles.toArray(Doubles.asList(array)))); } public void testToArray_threadSafe() { for (int delta : new int[] { +1, 0, -1 }) { for (int i = 0; i < VALUES.length; i++) { List<Double> list = Doubles.asList(VALUES).subList(0, i); Collection<Double> misleadingSize = Helpers.misleadingSizeCollection(delta); misleadingSize.addAll(list); double[] arr = Doubles.toArray(misleadingSize); assertEquals(i, arr.length); for (int j = 0; j < i; j++) { assertEquals(VALUES[j], arr[j]); } } } } public void testToArray_withNull() { List<Double> list = Arrays.asList((double) 0, (double) 1, null); try { Doubles.toArray(list); fail(); } catch (NullPointerException expected) { } } public void testToArray_withConversion() { double[] array = {(double) 0, (double) 1, (double) 2}; List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2); List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2); List<Integer> ints = Arrays.asList(0, 1, 2); List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2); List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2); List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2); assertTrue(Arrays.equals(array, Doubles.toArray(bytes))); assertTrue(Arrays.equals(array, Doubles.toArray(shorts))); assertTrue(Arrays.equals(array, Doubles.toArray(ints))); assertTrue(Arrays.equals(array, Doubles.toArray(floats))); assertTrue(Arrays.equals(array, Doubles.toArray(longs))); assertTrue(Arrays.equals(array, Doubles.toArray(doubles))); } public void testAsList_isAView() { double[] array = {(double) 0, (double) 1}; List<Double> list = Doubles.asList(array); list.set(0, (double) 2); assertTrue(Arrays.equals(new double[] {(double) 2, (double) 1}, array)); array[1] = (double) 3; ASSERT.that(list).has().exactly((double) 2, (double) 3).inOrder(); } public void testAsList_toArray_roundTrip() { double[] array = { (double) 0, (double) 1, (double) 2 }; List<Double> list = Doubles.asList(array); double[] newArray = Doubles.toArray(list); // Make sure it returned a copy list.set(0, (double) 4); assertTrue(Arrays.equals( new double[] { (double) 0, (double) 1, (double) 2 }, newArray)); newArray[1] = (double) 5; assertEquals((double) 1, (double) list.get(1)); } // This test stems from a real bug found by andrewk public void testAsList_subList_toArray_roundTrip() { double[] array = { (double) 0, (double) 1, (double) 2, (double) 3 }; List<Double> list = Doubles.asList(array); assertTrue(Arrays.equals(new double[] { (double) 1, (double) 2 }, Doubles.toArray(list.subList(1, 3)))); assertTrue(Arrays.equals(new double[] {}, Doubles.toArray(list.subList(2, 2)))); } public void testAsListEmpty() { assertSame(Collections.emptyList(), Doubles.asList(EMPTY)); } /** * A reference implementation for {@code tryParse} that just catches the exception from * {@link Double#valueOf}. */ private static Double referenceTryParse(String input) { if (input.trim().length() < input.length()) { return null; } try { return Double.valueOf(input); } catch (NumberFormatException e) { return null; } } private static final String[] BAD_TRY_PARSE_INPUTS = { "", "+-", "+-0", " 5", "32 ", " 55 ", "infinity", "POSITIVE_INFINITY", "0x9A", "0x9A.bE-5", ".", ".e5", "NaNd", "InfinityF" }; }
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.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.TestListGenerator; import junit.framework.TestCase; import java.util.List; /** * Test suite covering {@link Doubles#asList(double[])}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class DoubleArrayAsListTest extends TestCase { private static List<Double> asList(Double[] values) { double[] temp = new double[values.length]; for (int i = 0; i < values.length; i++) { temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize). } return Doubles.asList(temp); } // Test generators. To let the GWT test suite generator access them, they need to be // public named classes with a public default constructor. public static final class DoublesAsListGenerator extends TestDoubleListGenerator { @Override protected List<Double> create(Double[] elements) { return asList(elements); } } public static final class DoublsAsListHeadSubListGenerator extends TestDoubleListGenerator { @Override protected List<Double> create(Double[] elements) { Double[] suffix = {Double.MIN_VALUE, Double.MAX_VALUE}; Double[] all = concat(elements, suffix); return asList(all).subList(0, elements.length); } } public static final class DoublesAsListTailSubListGenerator extends TestDoubleListGenerator { @Override protected List<Double> create(Double[] elements) { Double[] prefix = {(double) 86, (double) 99}; Double[] all = concat(prefix, elements); return asList(all).subList(2, elements.length + 2); } } public static final class DoublesAsListMiddleSubListGenerator extends TestDoubleListGenerator { @Override protected List<Double> create(Double[] elements) { Double[] prefix = {Double.MIN_VALUE, Double.MAX_VALUE}; Double[] suffix = {(double) 86, (double) 99}; Double[] all = concat(concat(prefix, elements), suffix); return asList(all).subList(2, elements.length + 2); } } private static Double[] concat(Double[] left, Double[] right) { Double[] result = new Double[left.length + right.length]; System.arraycopy(left, 0, result, 0, left.length); System.arraycopy(right, 0, result, left.length, right.length); return result; } public static abstract class TestDoubleListGenerator implements TestListGenerator<Double> { @Override public SampleElements<Double> samples() { return new SampleDoubles(); } @Override public List<Double> create(Object... elements) { Double[] array = new Double[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (Double) e; } return create(array); } /** * Creates a new collection containing the given elements; implement this * method instead of {@link #create(Object...)}. */ protected abstract List<Double> create(Double[] elements); @Override public Double[] createArray(int length) { return new Double[length]; } /** Returns the original element list, unchanged. */ @Override public List<Double> order(List<Double> insertionOrder) { return insertionOrder; } } public static class SampleDoubles extends SampleElements<Double> { public SampleDoubles() { super((double) 0, (double) 1, (double) 2, (double) 3, (double) 4); } } }
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.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.TestListGenerator; import junit.framework.TestCase; import java.util.List; /** * Test suite covering {@link Floats#asList(float[])})}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class FloatArrayAsListTest extends TestCase { private static List<Float> asList(Float[] values) { float[] temp = new float[values.length]; for (int i = 0; i < values.length; i++) { temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize). } return Floats.asList(temp); } // Test generators. To let the GWT test suite generator access them, they need to be // public named classes with a public default constructor. public static final class FloatsAsListGenerator extends TestFloatListGenerator { @Override protected List<Float> create(Float[] elements) { return asList(elements); } } public static final class FloatsAsListHeadSubListGenerator extends TestFloatListGenerator { @Override protected List<Float> create(Float[] elements) { Float[] suffix = {Float.MIN_VALUE, Float.MAX_VALUE}; Float[] all = concat(elements, suffix); return asList(all).subList(0, elements.length); } } public static final class FloatsAsListTailSubListGenerator extends TestFloatListGenerator { @Override protected List<Float> create(Float[] elements) { Float[] prefix = {(float) 86, (float) 99}; Float[] all = concat(prefix, elements); return asList(all).subList(2, elements.length + 2); } } public static final class FloatsAsListMiddleSubListGenerator extends TestFloatListGenerator { @Override protected List<Float> create(Float[] elements) { Float[] prefix = {Float.MIN_VALUE, Float.MAX_VALUE}; Float[] suffix = {(float) 86, (float) 99}; Float[] all = concat(concat(prefix, elements), suffix); return asList(all).subList(2, elements.length + 2); } } private static Float[] concat(Float[] left, Float[] right) { Float[] result = new Float[left.length + right.length]; System.arraycopy(left, 0, result, 0, left.length); System.arraycopy(right, 0, result, left.length, right.length); return result; } public static abstract class TestFloatListGenerator implements TestListGenerator<Float> { @Override public SampleElements<Float> samples() { return new SampleFloats(); } @Override public List<Float> create(Object... elements) { Float[] array = new Float[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (Float) e; } return create(array); } /** * Creates a new collection containing the given elements; implement this * method instead of {@link #create(Object...)}. */ protected abstract List<Float> create(Float[] elements); @Override public Float[] createArray(int length) { return new Float[length]; } /** Returns the original element list, unchanged. */ @Override public List<Float> order(List<Float> insertionOrder) { return insertionOrder; } } public static class SampleFloats extends SampleElements<Float> { public SampleFloats() { super((float) 0, (float) 1, (float) 2, (float) 3, (float) 4); } } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import junit.framework.TestCase; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** * Unit test for {@link SignedBytes}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) @SuppressWarnings("cast") // redundant casts are intentional and harmless public class SignedBytesTest extends TestCase { private static final byte[] EMPTY = {}; private static final byte[] ARRAY1 = {(byte) 1}; private static final byte LEAST = Byte.MIN_VALUE; private static final byte GREATEST = Byte.MAX_VALUE; private static final byte[] VALUES = {LEAST, -1, 0, 1, GREATEST}; public void testCheckedCast() { for (byte value : VALUES) { assertEquals(value, SignedBytes.checkedCast((long) value)); } assertCastFails(GREATEST + 1L); assertCastFails(LEAST - 1L); assertCastFails(Long.MAX_VALUE); assertCastFails(Long.MIN_VALUE); } public void testSaturatedCast() { for (byte value : VALUES) { assertEquals(value, SignedBytes.saturatedCast((long) value)); } assertEquals(GREATEST, SignedBytes.saturatedCast(GREATEST + 1L)); assertEquals(LEAST, SignedBytes.saturatedCast(LEAST - 1L)); assertEquals(GREATEST, SignedBytes.saturatedCast(Long.MAX_VALUE)); assertEquals(LEAST, SignedBytes.saturatedCast(Long.MIN_VALUE)); } private static void assertCastFails(long value) { try { SignedBytes.checkedCast(value); fail("Cast to byte should have failed: " + value); } catch (IllegalArgumentException ex) { assertTrue(value + " not found in exception text: " + ex.getMessage(), ex.getMessage().contains(String.valueOf(value))); } } public void testCompare() { for (byte x : VALUES) { for (byte y : VALUES) { // Only compare the sign of the result of compareTo(). int expected = Byte.valueOf(x).compareTo(y); int actual = SignedBytes.compare(x, y); if (expected == 0) { assertEquals(x + ", " + y, expected, actual); } else if (expected < 0) { assertTrue(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")", actual < 0); } else { assertTrue(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")", actual > 0); } } } } public void testMax_noArgs() { try { SignedBytes.max(); fail(); } catch (IllegalArgumentException expected) { } } public void testMax() { assertEquals(LEAST, SignedBytes.max(LEAST)); assertEquals(GREATEST, SignedBytes.max(GREATEST)); assertEquals((byte) 127, SignedBytes.max( (byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1)); } public void testMin_noArgs() { try { SignedBytes.min(); fail(); } catch (IllegalArgumentException expected) { } } public void testMin() { assertEquals(LEAST, SignedBytes.min(LEAST)); assertEquals(GREATEST, SignedBytes.min(GREATEST)); assertEquals((byte) -128, SignedBytes.min( (byte) 0, (byte) -128, (byte) -1, (byte) 127, (byte) 1)); } public void testJoin() { assertEquals("", SignedBytes.join(",", EMPTY)); assertEquals("1", SignedBytes.join(",", ARRAY1)); assertEquals("1,2", SignedBytes.join(",", (byte) 1, (byte) 2)); assertEquals("123", SignedBytes.join("", (byte) 1, (byte) 2, (byte) 3)); assertEquals("-128,-1", SignedBytes.join(",", (byte) -128, (byte) -1)); } public void testLexicographicalComparator() { List<byte[]> ordered = Arrays.asList( new byte[] {}, new byte[] {LEAST}, new byte[] {LEAST, LEAST}, new byte[] {LEAST, (byte) 1}, new byte[] {(byte) 1}, new byte[] {(byte) 1, LEAST}, new byte[] {GREATEST, GREATEST - (byte) 1}, new byte[] {GREATEST, GREATEST}, new byte[] {GREATEST, GREATEST, GREATEST}); Comparator<byte[]> comparator = SignedBytes.lexicographicalComparator(); Helpers.testComparator(comparator, ordered); } }
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.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.TestListGenerator; import junit.framework.TestCase; import java.util.List; /** * Test suite covering {@link Bytes#asList(byte[])}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class ByteArrayAsListTest extends TestCase { private static List<Byte> asList(Byte[] values) { byte[] temp = new byte[values.length]; for (int i = 0; i < values.length; i++) { temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize). } return Bytes.asList(temp); } // Test generators. To let the GWT test suite generator access them, they need to be // public named classes with a public default constructor. public static final class BytesAsListGenerator extends TestByteListGenerator { @Override protected List<Byte> create(Byte[] elements) { return asList(elements); } } public static final class BytesAsListHeadSubListGenerator extends TestByteListGenerator { @Override protected List<Byte> create(Byte[] elements) { Byte[] suffix = {Byte.MIN_VALUE, Byte.MAX_VALUE}; Byte[] all = concat(elements, suffix); return asList(all).subList(0, elements.length); } } public static final class BytesAsListTailSubListGenerator extends TestByteListGenerator { @Override protected List<Byte> create(Byte[] elements) { Byte[] prefix = {(byte) 86, (byte) 99}; Byte[] all = concat(prefix, elements); return asList(all).subList(2, elements.length + 2); } } public static final class BytesAsListMiddleSubListGenerator extends TestByteListGenerator { @Override protected List<Byte> create(Byte[] elements) { Byte[] prefix = {Byte.MIN_VALUE, Byte.MAX_VALUE}; Byte[] suffix = {(byte) 86, (byte) 99}; Byte[] all = concat(concat(prefix, elements), suffix); return asList(all).subList(2, elements.length + 2); } } private static Byte[] concat(Byte[] left, Byte[] right) { Byte[] result = new Byte[left.length + right.length]; System.arraycopy(left, 0, result, 0, left.length); System.arraycopy(right, 0, result, left.length, right.length); return result; } public static abstract class TestByteListGenerator implements TestListGenerator<Byte> { @Override public SampleElements<Byte> samples() { return new SampleBytes(); } @Override public List<Byte> create(Object... elements) { Byte[] array = new Byte[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (Byte) e; } return create(array); } /** * Creates a new collection containing the given elements; implement this * method instead of {@link #create(Object...)}. */ protected abstract List<Byte> create(Byte[] elements); @Override public Byte[] createArray(int length) { return new Byte[length]; } /** Returns the original element list, unchanged. */ @Override public List<Byte> order(List<Byte> insertionOrder) { return insertionOrder; } } public static class SampleBytes extends SampleElements<Byte> { public SampleBytes() { super((byte) 0, (byte) 1, (byte) 2, (byte) 3, (byte) 4); } } }
Java
/* * Copyright (C) 2011 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except * in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing permissions and * limitations under the License. */ package com.google.common.primitives; import static java.math.BigInteger.ONE; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import junit.framework.TestCase; import java.math.BigInteger; import java.util.Arrays; import java.util.Comparator; import java.util.List; /** * Tests for UnsignedLongs * * @author Brian Milch * @author Louis Wasserman */ @GwtCompatible(emulated = true) public class UnsignedLongsTest extends TestCase { private static final long LEAST = 0L; private static final long GREATEST = 0xffffffffffffffffL; public void testCompare() { // max value assertTrue(UnsignedLongs.compare(0, 0xffffffffffffffffL) < 0); assertTrue(UnsignedLongs.compare(0xffffffffffffffffL, 0) > 0); // both with high bit set assertTrue(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0xffffffffffffffffL) < 0); assertTrue(UnsignedLongs.compare(0xffffffffffffffffL, 0xff1a618b7f65ea12L) > 0); // one with high bit set assertTrue(UnsignedLongs.compare(0x5a4316b8c153ac4dL, 0xff1a618b7f65ea12L) < 0); assertTrue(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0x5a4316b8c153ac4dL) > 0); // neither with high bit set assertTrue(UnsignedLongs.compare(0x5a4316b8c153ac4dL, 0x6cf78a4b139a4e2aL) < 0); assertTrue(UnsignedLongs.compare(0x6cf78a4b139a4e2aL, 0x5a4316b8c153ac4dL) > 0); // same value assertTrue(UnsignedLongs.compare(0xff1a618b7f65ea12L, 0xff1a618b7f65ea12L) == 0); } public void testMax_noArgs() { try { UnsignedLongs.max(); fail(); } catch (IllegalArgumentException expected) { } } public void testMax() { assertEquals(LEAST, UnsignedLongs.max(LEAST)); assertEquals(GREATEST, UnsignedLongs.max(GREATEST)); assertEquals(0xff1a618b7f65ea12L, UnsignedLongs.max( 0x5a4316b8c153ac4dL, 8L, 100L, 0L, 0x6cf78a4b139a4e2aL, 0xff1a618b7f65ea12L)); } public void testMin_noArgs() { try { UnsignedLongs.min(); fail(); } catch (IllegalArgumentException expected) { } } public void testMin() { assertEquals(LEAST, UnsignedLongs.min(LEAST)); assertEquals(GREATEST, UnsignedLongs.min(GREATEST)); assertEquals(0L, UnsignedLongs.min( 0x5a4316b8c153ac4dL, 8L, 100L, 0L, 0x6cf78a4b139a4e2aL, 0xff1a618b7f65ea12L)); } public void testLexicographicalComparator() { List<long[]> ordered = Arrays.asList( new long[] {}, new long[] {LEAST}, new long[] {LEAST, LEAST}, new long[] {LEAST, (long) 1}, new long[] {(long) 1}, new long[] {(long) 1, LEAST}, new long[] {GREATEST, GREATEST - (long) 1}, new long[] {GREATEST, GREATEST}, new long[] {GREATEST, GREATEST, GREATEST}); Comparator<long[]> comparator = UnsignedLongs.lexicographicalComparator(); Helpers.testComparator(comparator, ordered); } public void testDivide() { assertEquals(2, UnsignedLongs.divide(14, 5)); assertEquals(0, UnsignedLongs.divide(0, 50)); assertEquals(1, UnsignedLongs.divide(0xfffffffffffffffeL, 0xfffffffffffffffdL)); assertEquals(0, UnsignedLongs.divide(0xfffffffffffffffdL, 0xfffffffffffffffeL)); assertEquals(281479271743488L, UnsignedLongs.divide(0xfffffffffffffffeL, 65535)); assertEquals(0x7fffffffffffffffL, UnsignedLongs.divide(0xfffffffffffffffeL, 2)); assertEquals(3689348814741910322L, UnsignedLongs.divide(0xfffffffffffffffeL, 5)); } public void testRemainder() { assertEquals(4, UnsignedLongs.remainder(14, 5)); assertEquals(0, UnsignedLongs.remainder(0, 50)); assertEquals(1, UnsignedLongs.remainder(0xfffffffffffffffeL, 0xfffffffffffffffdL)); assertEquals(0xfffffffffffffffdL, UnsignedLongs.remainder(0xfffffffffffffffdL, 0xfffffffffffffffeL)); assertEquals(65534L, UnsignedLongs.remainder(0xfffffffffffffffeL, 65535)); assertEquals(0, UnsignedLongs.remainder(0xfffffffffffffffeL, 2)); assertEquals(4, UnsignedLongs.remainder(0xfffffffffffffffeL, 5)); } public void testParseLong() { assertEquals(0xffffffffffffffffL, UnsignedLongs.parseUnsignedLong("18446744073709551615")); assertEquals(0x7fffffffffffffffL, UnsignedLongs.parseUnsignedLong("9223372036854775807")); assertEquals(0xff1a618b7f65ea12L, UnsignedLongs.parseUnsignedLong("18382112080831834642")); assertEquals(0x5a4316b8c153ac4dL, UnsignedLongs.parseUnsignedLong("6504067269626408013")); assertEquals(0x6cf78a4b139a4e2aL, UnsignedLongs.parseUnsignedLong("7851896530399809066")); try { // One more than maximum value UnsignedLongs.parseUnsignedLong("18446744073709551616"); fail(); } catch (NumberFormatException expected) { } } public void testDecodeLong() { assertEquals(0xffffffffffffffffL, UnsignedLongs.decode("0xffffffffffffffff")); assertEquals(01234567, UnsignedLongs.decode("01234567")); // octal assertEquals(0x1234567890abcdefL, UnsignedLongs.decode("#1234567890abcdef")); assertEquals(987654321012345678L, UnsignedLongs.decode("987654321012345678")); assertEquals(0x135791357913579L, UnsignedLongs.decode("0x135791357913579")); assertEquals(0x135791357913579L, UnsignedLongs.decode("0X135791357913579")); assertEquals(0L, UnsignedLongs.decode("0")); } public void testDecodeLongFails() { try { // One more than maximum value UnsignedLongs.decode("0xfffffffffffffffff"); fail(); } catch (NumberFormatException expected) { } try { UnsignedLongs.decode("-5"); fail(); } catch (NumberFormatException expected) { } try { UnsignedLongs.decode("-0x5"); fail(); } catch (NumberFormatException expected) { } try { UnsignedLongs.decode("-05"); fail(); } catch (NumberFormatException expected) { } } public void testParseLongWithRadix() { assertEquals(0xffffffffffffffffL, UnsignedLongs.parseUnsignedLong("ffffffffffffffff", 16)); assertEquals(0x1234567890abcdefL, UnsignedLongs.parseUnsignedLong("1234567890abcdef", 16)); BigInteger max = BigInteger.ZERO.setBit(64).subtract(ONE); // loops through all legal radix values. for (int radix = Character.MIN_RADIX; radix <= Character.MAX_RADIX; radix++) { // tests can successfully parse a number string with this radix. String maxAsString = max.toString(radix); assertEquals(max.longValue(), UnsignedLongs.parseUnsignedLong(maxAsString, radix)); try { // tests that we get exception whre an overflow would occur. BigInteger overflow = max.add(ONE); String overflowAsString = overflow.toString(radix); UnsignedLongs.parseUnsignedLong(overflowAsString, radix); fail(); } catch (NumberFormatException expected) { } } try { UnsignedLongs.parseUnsignedLong("1234567890abcdef1", 16); fail(); } catch (NumberFormatException expected) { } } public void testParseLongThrowsExceptionForInvalidRadix() { // Valid radix values are Character.MIN_RADIX to Character.MAX_RADIX, inclusive. try { UnsignedLongs.parseUnsignedLong("0", Character.MIN_RADIX - 1); fail(); } catch (NumberFormatException expected) { } try { UnsignedLongs.parseUnsignedLong("0", Character.MAX_RADIX + 1); fail(); } catch (NumberFormatException expected) { } // The radix is used as an array index, so try a negative value. try { UnsignedLongs.parseUnsignedLong("0", -1); fail(); } catch (NumberFormatException expected) { } } public void testToString() { String[] tests = { "ffffffffffffffff", "7fffffffffffffff", "ff1a618b7f65ea12", "5a4316b8c153ac4d", "6cf78a4b139a4e2a" }; int[] bases = { 2, 5, 7, 8, 10, 16 }; for (int base : bases) { for (String x : tests) { BigInteger xValue = new BigInteger(x, 16); long xLong = xValue.longValue(); // signed assertEquals(xValue.toString(base), UnsignedLongs.toString(xLong, base)); } } } public void testJoin() { assertEquals("", UnsignedLongs.join(",")); assertEquals("1", UnsignedLongs.join(",", 1)); assertEquals("1,2", UnsignedLongs.join(",", 1, 2)); assertEquals("18446744073709551615,9223372036854775808", UnsignedLongs.join(",", -1, Long.MIN_VALUE)); assertEquals("123", UnsignedLongs.join("", 1, 2, 3)); assertEquals("184467440737095516159223372036854775808", UnsignedLongs.join("", -1, Long.MIN_VALUE)); } }
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 java.lang.Long.MAX_VALUE; import static java.lang.Long.MIN_VALUE; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Random; /** * Unit test for {@link Longs}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) @SuppressWarnings("cast") // redundant casts are intentional and harmless public class LongsTest extends TestCase { private static final long[] EMPTY = {}; private static final long[] ARRAY1 = {(long) 1}; private static final long[] ARRAY234 = {(long) 2, (long) 3, (long) 4}; private static final long[] VALUES = { MIN_VALUE, (long) -1, (long) 0, (long) 1, MAX_VALUE }; public void testCompare() { for (long x : VALUES) { for (long y : VALUES) { // note: spec requires only that the sign is the same assertEquals(x + ", " + y, Long.valueOf(x).compareTo(y), Longs.compare(x, y)); } } } public void testContains() { assertFalse(Longs.contains(EMPTY, (long) 1)); assertFalse(Longs.contains(ARRAY1, (long) 2)); assertFalse(Longs.contains(ARRAY234, (long) 1)); assertTrue(Longs.contains(new long[] {(long) -1}, (long) -1)); assertTrue(Longs.contains(ARRAY234, (long) 2)); assertTrue(Longs.contains(ARRAY234, (long) 3)); assertTrue(Longs.contains(ARRAY234, (long) 4)); } public void testIndexOf() { assertEquals(-1, Longs.indexOf(EMPTY, (long) 1)); assertEquals(-1, Longs.indexOf(ARRAY1, (long) 2)); assertEquals(-1, Longs.indexOf(ARRAY234, (long) 1)); assertEquals(0, Longs.indexOf( new long[] {(long) -1}, (long) -1)); assertEquals(0, Longs.indexOf(ARRAY234, (long) 2)); assertEquals(1, Longs.indexOf(ARRAY234, (long) 3)); assertEquals(2, Longs.indexOf(ARRAY234, (long) 4)); assertEquals(1, Longs.indexOf( new long[] { (long) 2, (long) 3, (long) 2, (long) 3 }, (long) 3)); } public void testIndexOf_arrayTarget() { assertEquals(0, Longs.indexOf(EMPTY, EMPTY)); assertEquals(0, Longs.indexOf(ARRAY234, EMPTY)); assertEquals(-1, Longs.indexOf(EMPTY, ARRAY234)); assertEquals(-1, Longs.indexOf(ARRAY234, ARRAY1)); assertEquals(-1, Longs.indexOf(ARRAY1, ARRAY234)); assertEquals(0, Longs.indexOf(ARRAY1, ARRAY1)); assertEquals(0, Longs.indexOf(ARRAY234, ARRAY234)); assertEquals(0, Longs.indexOf( ARRAY234, new long[] { (long) 2, (long) 3 })); assertEquals(1, Longs.indexOf( ARRAY234, new long[] { (long) 3, (long) 4 })); assertEquals(1, Longs.indexOf(ARRAY234, new long[] { (long) 3 })); assertEquals(2, Longs.indexOf(ARRAY234, new long[] { (long) 4 })); assertEquals(1, Longs.indexOf(new long[] { (long) 2, (long) 3, (long) 3, (long) 3, (long) 3 }, new long[] { (long) 3 } )); assertEquals(2, Longs.indexOf( new long[] { (long) 2, (long) 3, (long) 2, (long) 3, (long) 4, (long) 2, (long) 3}, new long[] { (long) 2, (long) 3, (long) 4} )); assertEquals(1, Longs.indexOf( new long[] { (long) 2, (long) 2, (long) 3, (long) 4, (long) 2, (long) 3, (long) 4}, new long[] { (long) 2, (long) 3, (long) 4} )); assertEquals(-1, Longs.indexOf( new long[] { (long) 4, (long) 3, (long) 2}, new long[] { (long) 2, (long) 3, (long) 4} )); } public void testLastIndexOf() { assertEquals(-1, Longs.lastIndexOf(EMPTY, (long) 1)); assertEquals(-1, Longs.lastIndexOf(ARRAY1, (long) 2)); assertEquals(-1, Longs.lastIndexOf(ARRAY234, (long) 1)); assertEquals(0, Longs.lastIndexOf( new long[] {(long) -1}, (long) -1)); assertEquals(0, Longs.lastIndexOf(ARRAY234, (long) 2)); assertEquals(1, Longs.lastIndexOf(ARRAY234, (long) 3)); assertEquals(2, Longs.lastIndexOf(ARRAY234, (long) 4)); assertEquals(3, Longs.lastIndexOf( new long[] { (long) 2, (long) 3, (long) 2, (long) 3 }, (long) 3)); } public void testMax_noArgs() { try { Longs.max(); fail(); } catch (IllegalArgumentException expected) { } } public void testMax() { assertEquals(MIN_VALUE, Longs.max(MIN_VALUE)); assertEquals(MAX_VALUE, Longs.max(MAX_VALUE)); assertEquals((long) 9, Longs.max( (long) 8, (long) 6, (long) 7, (long) 5, (long) 3, (long) 0, (long) 9)); } public void testMin_noArgs() { try { Longs.min(); fail(); } catch (IllegalArgumentException expected) { } } public void testMin() { assertEquals(MIN_VALUE, Longs.min(MIN_VALUE)); assertEquals(MAX_VALUE, Longs.min(MAX_VALUE)); assertEquals((long) 0, Longs.min( (long) 8, (long) 6, (long) 7, (long) 5, (long) 3, (long) 0, (long) 9)); } public void testConcat() { assertTrue(Arrays.equals(EMPTY, Longs.concat())); assertTrue(Arrays.equals(EMPTY, Longs.concat(EMPTY))); assertTrue(Arrays.equals(EMPTY, Longs.concat(EMPTY, EMPTY, EMPTY))); assertTrue(Arrays.equals(ARRAY1, Longs.concat(ARRAY1))); assertNotSame(ARRAY1, Longs.concat(ARRAY1)); assertTrue(Arrays.equals(ARRAY1, Longs.concat(EMPTY, ARRAY1, EMPTY))); assertTrue(Arrays.equals( new long[] {(long) 1, (long) 1, (long) 1}, Longs.concat(ARRAY1, ARRAY1, ARRAY1))); assertTrue(Arrays.equals( new long[] {(long) 1, (long) 2, (long) 3, (long) 4}, Longs.concat(ARRAY1, ARRAY234))); } private static void assertByteArrayEquals(byte[] expected, byte[] actual) { assertTrue( "Expected: " + Arrays.toString(expected) + ", but got: " + Arrays.toString(actual), Arrays.equals(expected, actual)); } public void testToByteArray() { assertByteArrayEquals( new byte[] {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19}, Longs.toByteArray(0x1213141516171819L)); assertByteArrayEquals( new byte[] { (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC, (byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88}, Longs.toByteArray(0xFFEEDDCCBBAA9988L)); } public void testFromByteArray() { assertEquals(0x1213141516171819L, Longs.fromByteArray( new byte[] {0x12, 0x13, 0x14, 0x15, 0x16, 0x17, 0x18, 0x19, 0x33})); assertEquals(0xFFEEDDCCBBAA9988L, Longs.fromByteArray( new byte[] { (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC, (byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88})); try { Longs.fromByteArray(new byte[Longs.BYTES - 1]); fail(); } catch (IllegalArgumentException expected) { } } public void testFromBytes() { assertEquals(0x1213141516171819L, Longs.fromBytes( (byte) 0x12, (byte) 0x13, (byte) 0x14, (byte) 0x15, (byte) 0x16, (byte) 0x17, (byte) 0x18, (byte) 0x19)); assertEquals(0xFFEEDDCCBBAA9988L, Longs.fromBytes( (byte) 0xFF, (byte) 0xEE, (byte) 0xDD, (byte) 0xCC, (byte) 0xBB, (byte) 0xAA, (byte) 0x99, (byte) 0x88)); } public void testByteArrayRoundTrips() { Random r = new Random(5); byte[] b = new byte[Longs.BYTES]; // total overkill, but, it takes 0.1 sec so why not... for (int i = 0; i < 10000; i++) { long num = r.nextLong(); assertEquals(num, Longs.fromByteArray(Longs.toByteArray(num))); r.nextBytes(b); long value = Longs.fromByteArray(b); assertTrue("" + value, Arrays.equals(b, Longs.toByteArray(value))); } } public void testEnsureCapacity() { assertSame(EMPTY, Longs.ensureCapacity(EMPTY, 0, 1)); assertSame(ARRAY1, Longs.ensureCapacity(ARRAY1, 0, 1)); assertSame(ARRAY1, Longs.ensureCapacity(ARRAY1, 1, 1)); assertTrue(Arrays.equals( new long[] {(long) 1, (long) 0, (long) 0}, Longs.ensureCapacity(ARRAY1, 2, 1))); } public void testEnsureCapacity_fail() { try { Longs.ensureCapacity(ARRAY1, -1, 1); fail(); } catch (IllegalArgumentException expected) { } try { // notice that this should even fail when no growth was needed Longs.ensureCapacity(ARRAY1, 1, -1); fail(); } catch (IllegalArgumentException expected) { } } public void testJoin() { assertEquals("", Longs.join(",", EMPTY)); assertEquals("1", Longs.join(",", ARRAY1)); assertEquals("1,2", Longs.join(",", (long) 1, (long) 2)); assertEquals("123", Longs.join("", (long) 1, (long) 2, (long) 3)); } public void testLexicographicalComparator() { List<long[]> ordered = Arrays.asList( new long[] {}, new long[] {MIN_VALUE}, new long[] {MIN_VALUE, MIN_VALUE}, new long[] {MIN_VALUE, (long) 1}, new long[] {(long) 1}, new long[] {(long) 1, MIN_VALUE}, new long[] {MAX_VALUE, MAX_VALUE - (long) 1}, new long[] {MAX_VALUE, MAX_VALUE}, new long[] {MAX_VALUE, MAX_VALUE, MAX_VALUE}); Comparator<long[]> comparator = Longs.lexicographicalComparator(); Helpers.testComparator(comparator, ordered); } public void testToArray() { // need explicit type parameter to avoid javac warning!? List<Long> none = Arrays.<Long>asList(); assertTrue(Arrays.equals(EMPTY, Longs.toArray(none))); List<Long> one = Arrays.asList((long) 1); assertTrue(Arrays.equals(ARRAY1, Longs.toArray(one))); long[] array = {(long) 0, (long) 1, 0x0FF1C1AL}; List<Long> three = Arrays.asList((long) 0, (long) 1, 0x0FF1C1AL); assertTrue(Arrays.equals(array, Longs.toArray(three))); assertTrue(Arrays.equals(array, Longs.toArray(Longs.asList(array)))); } public void testToArray_threadSafe() { for (int delta : new int[] { +1, 0, -1 }) { for (int i = 0; i < VALUES.length; i++) { List<Long> list = Longs.asList(VALUES).subList(0, i); Collection<Long> misleadingSize = Helpers.misleadingSizeCollection(delta); misleadingSize.addAll(list); long[] arr = Longs.toArray(misleadingSize); assertEquals(i, arr.length); for (int j = 0; j < i; j++) { assertEquals(VALUES[j], arr[j]); } } } } public void testToArray_withNull() { List<Long> list = Arrays.asList((long) 0, (long) 1, null); try { Longs.toArray(list); fail(); } catch (NullPointerException expected) { } } public void testToArray_withConversion() { long[] array = {(long) 0, (long) 1, (long) 2}; List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2); List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2); List<Integer> ints = Arrays.asList(0, 1, 2); List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2); List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2); List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2); assertTrue(Arrays.equals(array, Longs.toArray(bytes))); assertTrue(Arrays.equals(array, Longs.toArray(shorts))); assertTrue(Arrays.equals(array, Longs.toArray(ints))); assertTrue(Arrays.equals(array, Longs.toArray(floats))); assertTrue(Arrays.equals(array, Longs.toArray(longs))); assertTrue(Arrays.equals(array, Longs.toArray(doubles))); } public void testAsList_isAView() { long[] array = {(long) 0, (long) 1}; List<Long> list = Longs.asList(array); list.set(0, (long) 2); assertTrue(Arrays.equals(new long[] {(long) 2, (long) 1}, array)); array[1] = (long) 3; assertEquals(Arrays.asList((long) 2, (long) 3), list); } public void testAsList_toArray_roundTrip() { long[] array = { (long) 0, (long) 1, (long) 2 }; List<Long> list = Longs.asList(array); long[] newArray = Longs.toArray(list); // Make sure it returned a copy list.set(0, (long) 4); assertTrue(Arrays.equals( new long[] { (long) 0, (long) 1, (long) 2 }, newArray)); newArray[1] = (long) 5; assertEquals((long) 1, (long) list.get(1)); } // This test stems from a real bug found by andrewk public void testAsList_subList_toArray_roundTrip() { long[] array = { (long) 0, (long) 1, (long) 2, (long) 3 }; List<Long> list = Longs.asList(array); assertTrue(Arrays.equals(new long[] { (long) 1, (long) 2 }, Longs.toArray(list.subList(1, 3)))); assertTrue(Arrays.equals(new long[] {}, Longs.toArray(list.subList(2, 2)))); } public void testAsListEmpty() { assertSame(Collections.emptyList(), Longs.asList(EMPTY)); } /** * Applies {@link Longs#tryParse(String)} to the given string and asserts that * the result is as expected. */ private static void tryParseAndAssertEquals(Long expected, String value) { assertEquals(expected, Longs.tryParse(value)); } }
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.checkNotNull; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.SampleElements; import com.google.common.collect.testing.TestListGenerator; import junit.framework.TestCase; import java.util.List; /** * Test suite covering {@link Longs#asList(long[])}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) public class LongArrayAsListTest extends TestCase { private static List<Long> asList(Long[] values) { long[] temp = new long[values.length]; for (int i = 0; i < values.length; i++) { temp[i] = checkNotNull(values[i]); // checkNotNull for GWT (do not optimize). } return Longs.asList(temp); } // Test generators. To let the GWT test suite generator access them, they need to be // public named classes with a public default constructor. public static final class LongsAsListGenerator extends TestLongListGenerator { @Override protected List<Long> create(Long[] elements) { return asList(elements); } } public static final class LongsAsListHeadSubListGenerator extends TestLongListGenerator { @Override protected List<Long> create(Long[] elements) { Long[] suffix = {Long.MIN_VALUE, Long.MAX_VALUE}; Long[] all = concat(elements, suffix); return asList(all).subList(0, elements.length); } } public static final class LongsAsListTailSubListGenerator extends TestLongListGenerator { @Override protected List<Long> create(Long[] elements) { Long[] prefix = {(long) 86, (long) 99}; Long[] all = concat(prefix, elements); return asList(all).subList(2, elements.length + 2); } } public static final class LongsAsListMiddleSubListGenerator extends TestLongListGenerator { @Override protected List<Long> create(Long[] elements) { Long[] prefix = {Long.MIN_VALUE, Long.MAX_VALUE}; Long[] suffix = {(long) 86, (long) 99}; Long[] all = concat(concat(prefix, elements), suffix); return asList(all).subList(2, elements.length + 2); } } private static Long[] concat(Long[] left, Long[] right) { Long[] result = new Long[left.length + right.length]; System.arraycopy(left, 0, result, 0, left.length); System.arraycopy(right, 0, result, left.length, right.length); return result; } public static abstract class TestLongListGenerator implements TestListGenerator<Long> { @Override public SampleElements<Long> samples() { return new SampleLongs(); } @Override public List<Long> create(Object... elements) { Long[] array = new Long[elements.length]; int i = 0; for (Object e : elements) { array[i++] = (Long) e; } return create(array); } /** * Creates a new collection containing the given elements; implement this * method instead of {@link #create(Object...)}. */ protected abstract List<Long> create(Long[] elements); @Override public Long[] createArray(int length) { return new Long[length]; } /** Returns the original element list, unchanged. */ @Override public List<Long> order(List<Long> insertionOrder) { return insertionOrder; } } public static class SampleLongs extends SampleElements<Long> { public SampleLongs() { super((long) 0, (long) 1, (long) 2, (long) 3, (long) 4); } } }
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 com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Unit test for {@link Shorts}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) @SuppressWarnings("cast") // redundant casts are intentional and harmless public class ShortsTest extends TestCase { private static final short[] EMPTY = {}; private static final short[] ARRAY1 = {(short) 1}; private static final short[] ARRAY234 = {(short) 2, (short) 3, (short) 4}; private static final short LEAST = Short.MIN_VALUE; private static final short GREATEST = Short.MAX_VALUE; private static final short[] VALUES = { LEAST, (short) -1, (short) 0, (short) 1, GREATEST }; public void testHashCode() { for (short value : VALUES) { assertEquals(((Short) value).hashCode(), Shorts.hashCode(value)); } } public void testCheckedCast() { for (short value : VALUES) { assertEquals(value, Shorts.checkedCast((long) value)); } assertCastFails(GREATEST + 1L); assertCastFails(LEAST - 1L); assertCastFails(Long.MAX_VALUE); assertCastFails(Long.MIN_VALUE); } public void testSaturatedCast() { for (short value : VALUES) { assertEquals(value, Shorts.saturatedCast((long) value)); } assertEquals(GREATEST, Shorts.saturatedCast(GREATEST + 1L)); assertEquals(LEAST, Shorts.saturatedCast(LEAST - 1L)); assertEquals(GREATEST, Shorts.saturatedCast(Long.MAX_VALUE)); assertEquals(LEAST, Shorts.saturatedCast(Long.MIN_VALUE)); } private static void assertCastFails(long value) { try { Shorts.checkedCast(value); fail("Cast to short should have failed: " + value); } catch (IllegalArgumentException ex) { assertTrue(value + " not found in exception text: " + ex.getMessage(), ex.getMessage().contains(String.valueOf(value))); } } public void testCompare() { for (short x : VALUES) { for (short y : VALUES) { // Only compare the sign of the result of compareTo(). int expected = Short.valueOf(x).compareTo(y); int actual = Shorts.compare(x, y); if (expected == 0) { assertEquals(x + ", " + y, expected, actual); } else if (expected < 0) { assertTrue(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")", actual < 0); } else { assertTrue(x + ", " + y + " (expected: " + expected + ", actual" + actual + ")", actual > 0); } } } } public void testContains() { assertFalse(Shorts.contains(EMPTY, (short) 1)); assertFalse(Shorts.contains(ARRAY1, (short) 2)); assertFalse(Shorts.contains(ARRAY234, (short) 1)); assertTrue(Shorts.contains(new short[] {(short) -1}, (short) -1)); assertTrue(Shorts.contains(ARRAY234, (short) 2)); assertTrue(Shorts.contains(ARRAY234, (short) 3)); assertTrue(Shorts.contains(ARRAY234, (short) 4)); } public void testIndexOf() { assertEquals(-1, Shorts.indexOf(EMPTY, (short) 1)); assertEquals(-1, Shorts.indexOf(ARRAY1, (short) 2)); assertEquals(-1, Shorts.indexOf(ARRAY234, (short) 1)); assertEquals(0, Shorts.indexOf( new short[] {(short) -1}, (short) -1)); assertEquals(0, Shorts.indexOf(ARRAY234, (short) 2)); assertEquals(1, Shorts.indexOf(ARRAY234, (short) 3)); assertEquals(2, Shorts.indexOf(ARRAY234, (short) 4)); assertEquals(1, Shorts.indexOf( new short[] { (short) 2, (short) 3, (short) 2, (short) 3 }, (short) 3)); } public void testIndexOf_arrayTarget() { assertEquals(0, Shorts.indexOf(EMPTY, EMPTY)); assertEquals(0, Shorts.indexOf(ARRAY234, EMPTY)); assertEquals(-1, Shorts.indexOf(EMPTY, ARRAY234)); assertEquals(-1, Shorts.indexOf(ARRAY234, ARRAY1)); assertEquals(-1, Shorts.indexOf(ARRAY1, ARRAY234)); assertEquals(0, Shorts.indexOf(ARRAY1, ARRAY1)); assertEquals(0, Shorts.indexOf(ARRAY234, ARRAY234)); assertEquals(0, Shorts.indexOf( ARRAY234, new short[] { (short) 2, (short) 3 })); assertEquals(1, Shorts.indexOf( ARRAY234, new short[] { (short) 3, (short) 4 })); assertEquals(1, Shorts.indexOf(ARRAY234, new short[] { (short) 3 })); assertEquals(2, Shorts.indexOf(ARRAY234, new short[] { (short) 4 })); assertEquals(1, Shorts.indexOf(new short[] { (short) 2, (short) 3, (short) 3, (short) 3, (short) 3 }, new short[] { (short) 3 } )); assertEquals(2, Shorts.indexOf( new short[] { (short) 2, (short) 3, (short) 2, (short) 3, (short) 4, (short) 2, (short) 3}, new short[] { (short) 2, (short) 3, (short) 4} )); assertEquals(1, Shorts.indexOf( new short[] { (short) 2, (short) 2, (short) 3, (short) 4, (short) 2, (short) 3, (short) 4}, new short[] { (short) 2, (short) 3, (short) 4} )); assertEquals(-1, Shorts.indexOf( new short[] { (short) 4, (short) 3, (short) 2}, new short[] { (short) 2, (short) 3, (short) 4} )); } public void testLastIndexOf() { assertEquals(-1, Shorts.lastIndexOf(EMPTY, (short) 1)); assertEquals(-1, Shorts.lastIndexOf(ARRAY1, (short) 2)); assertEquals(-1, Shorts.lastIndexOf(ARRAY234, (short) 1)); assertEquals(0, Shorts.lastIndexOf( new short[] {(short) -1}, (short) -1)); assertEquals(0, Shorts.lastIndexOf(ARRAY234, (short) 2)); assertEquals(1, Shorts.lastIndexOf(ARRAY234, (short) 3)); assertEquals(2, Shorts.lastIndexOf(ARRAY234, (short) 4)); assertEquals(3, Shorts.lastIndexOf( new short[] { (short) 2, (short) 3, (short) 2, (short) 3 }, (short) 3)); } public void testMax_noArgs() { try { Shorts.max(); fail(); } catch (IllegalArgumentException expected) { } } public void testMax() { assertEquals(LEAST, Shorts.max(LEAST)); assertEquals(GREATEST, Shorts.max(GREATEST)); assertEquals((short) 9, Shorts.max( (short) 8, (short) 6, (short) 7, (short) 5, (short) 3, (short) 0, (short) 9)); } public void testMin_noArgs() { try { Shorts.min(); fail(); } catch (IllegalArgumentException expected) { } } public void testMin() { assertEquals(LEAST, Shorts.min(LEAST)); assertEquals(GREATEST, Shorts.min(GREATEST)); assertEquals((short) 0, Shorts.min( (short) 8, (short) 6, (short) 7, (short) 5, (short) 3, (short) 0, (short) 9)); } public void testConcat() { assertTrue(Arrays.equals(EMPTY, Shorts.concat())); assertTrue(Arrays.equals(EMPTY, Shorts.concat(EMPTY))); assertTrue(Arrays.equals(EMPTY, Shorts.concat(EMPTY, EMPTY, EMPTY))); assertTrue(Arrays.equals(ARRAY1, Shorts.concat(ARRAY1))); assertNotSame(ARRAY1, Shorts.concat(ARRAY1)); assertTrue(Arrays.equals(ARRAY1, Shorts.concat(EMPTY, ARRAY1, EMPTY))); assertTrue(Arrays.equals( new short[] {(short) 1, (short) 1, (short) 1}, Shorts.concat(ARRAY1, ARRAY1, ARRAY1))); assertTrue(Arrays.equals( new short[] {(short) 1, (short) 2, (short) 3, (short) 4}, Shorts.concat(ARRAY1, ARRAY234))); } public void testEnsureCapacity() { assertSame(EMPTY, Shorts.ensureCapacity(EMPTY, 0, 1)); assertSame(ARRAY1, Shorts.ensureCapacity(ARRAY1, 0, 1)); assertSame(ARRAY1, Shorts.ensureCapacity(ARRAY1, 1, 1)); assertTrue(Arrays.equals( new short[] {(short) 1, (short) 0, (short) 0}, Shorts.ensureCapacity(ARRAY1, 2, 1))); } public void testEnsureCapacity_fail() { try { Shorts.ensureCapacity(ARRAY1, -1, 1); fail(); } catch (IllegalArgumentException expected) { } try { // notice that this should even fail when no growth was needed Shorts.ensureCapacity(ARRAY1, 1, -1); fail(); } catch (IllegalArgumentException expected) { } } public void testJoin() { assertEquals("", Shorts.join(",", EMPTY)); assertEquals("1", Shorts.join(",", ARRAY1)); assertEquals("1,2", Shorts.join(",", (short) 1, (short) 2)); assertEquals("123", Shorts.join("", (short) 1, (short) 2, (short) 3)); } public void testLexicographicalComparator() { List<short[]> ordered = Arrays.asList( new short[] {}, new short[] {LEAST}, new short[] {LEAST, LEAST}, new short[] {LEAST, (short) 1}, new short[] {(short) 1}, new short[] {(short) 1, LEAST}, new short[] {GREATEST, GREATEST - (short) 1}, new short[] {GREATEST, GREATEST}, new short[] {GREATEST, GREATEST, GREATEST}); Comparator<short[]> comparator = Shorts.lexicographicalComparator(); Helpers.testComparator(comparator, ordered); } public void testToArray() { // need explicit type parameter to avoid javac warning!? List<Short> none = Arrays.<Short>asList(); assertTrue(Arrays.equals(EMPTY, Shorts.toArray(none))); List<Short> one = Arrays.asList((short) 1); assertTrue(Arrays.equals(ARRAY1, Shorts.toArray(one))); short[] array = {(short) 0, (short) 1, (short) 3}; List<Short> three = Arrays.asList((short) 0, (short) 1, (short) 3); assertTrue(Arrays.equals(array, Shorts.toArray(three))); assertTrue(Arrays.equals(array, Shorts.toArray(Shorts.asList(array)))); } public void testToArray_threadSafe() { for (int delta : new int[] { +1, 0, -1 }) { for (int i = 0; i < VALUES.length; i++) { List<Short> list = Shorts.asList(VALUES).subList(0, i); Collection<Short> misleadingSize = Helpers.misleadingSizeCollection(delta); misleadingSize.addAll(list); short[] arr = Shorts.toArray(misleadingSize); assertEquals(i, arr.length); for (int j = 0; j < i; j++) { assertEquals(VALUES[j], arr[j]); } } } } public void testToArray_withNull() { List<Short> list = Arrays.asList((short) 0, (short) 1, null); try { Shorts.toArray(list); fail(); } catch (NullPointerException expected) { } } public void testToArray_withConversion() { short[] array = {(short) 0, (short) 1, (short) 2}; List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2); List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2); List<Integer> ints = Arrays.asList(0, 1, 2); List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2); List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2); List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2); assertTrue(Arrays.equals(array, Shorts.toArray(bytes))); assertTrue(Arrays.equals(array, Shorts.toArray(shorts))); assertTrue(Arrays.equals(array, Shorts.toArray(ints))); assertTrue(Arrays.equals(array, Shorts.toArray(floats))); assertTrue(Arrays.equals(array, Shorts.toArray(longs))); assertTrue(Arrays.equals(array, Shorts.toArray(doubles))); } public void testAsList_isAView() { short[] array = {(short) 0, (short) 1}; List<Short> list = Shorts.asList(array); list.set(0, (short) 2); assertTrue(Arrays.equals(new short[] {(short) 2, (short) 1}, array)); array[1] = (short) 3; assertEquals(Arrays.asList((short) 2, (short) 3), list); } public void testAsList_toArray_roundTrip() { short[] array = { (short) 0, (short) 1, (short) 2 }; List<Short> list = Shorts.asList(array); short[] newArray = Shorts.toArray(list); // Make sure it returned a copy list.set(0, (short) 4); assertTrue(Arrays.equals( new short[] { (short) 0, (short) 1, (short) 2 }, newArray)); newArray[1] = (short) 5; assertEquals((short) 1, (short) list.get(1)); } // This test stems from a real bug found by andrewk public void testAsList_subList_toArray_roundTrip() { short[] array = { (short) 0, (short) 1, (short) 2, (short) 3 }; List<Short> list = Shorts.asList(array); assertTrue(Arrays.equals(new short[] { (short) 1, (short) 2 }, Shorts.toArray(list.subList(1, 3)))); assertTrue(Arrays.equals(new short[] {}, Shorts.toArray(list.subList(2, 2)))); } public void testAsListEmpty() { assertSame(Collections.emptyList(), Shorts.asList(EMPTY)); } }
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 java.lang.Float.NaN; import static org.truth0.Truth.ASSERT; import com.google.common.annotations.GwtCompatible; import com.google.common.collect.testing.Helpers; import junit.framework.TestCase; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; /** * Unit test for {@link Floats}. * * @author Kevin Bourrillion */ @GwtCompatible(emulated = true) @SuppressWarnings("cast") // redundant casts are intentional and harmless public class FloatsTest extends TestCase { private static final float[] EMPTY = {}; private static final float[] ARRAY1 = {(float) 1}; private static final float[] ARRAY234 = {(float) 2, (float) 3, (float) 4}; private static final float LEAST = Float.NEGATIVE_INFINITY; private static final float GREATEST = Float.POSITIVE_INFINITY; private static final float[] NUMBERS = new float[] { LEAST, -Float.MAX_VALUE, -1f, -0f, 0f, 1f, Float.MAX_VALUE, GREATEST, Float.MIN_NORMAL, -Float.MIN_NORMAL, Float.MIN_VALUE, -Float.MIN_VALUE, Integer.MIN_VALUE, Integer.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE }; private static final float[] VALUES = Floats.concat(NUMBERS, new float[] {NaN}); public void testHashCode() { for (float value : VALUES) { assertEquals(((Float) value).hashCode(), Floats.hashCode(value)); } } public void testIsFinite() { for (float value : NUMBERS) { assertEquals(!(Float.isInfinite(value) || Float.isNaN(value)), Floats.isFinite(value)); } } public void testCompare() { for (float x : VALUES) { for (float y : VALUES) { // note: spec requires only that the sign is the same assertEquals(x + ", " + y, Float.valueOf(x).compareTo(y), Floats.compare(x, y)); } } } public void testContains() { assertFalse(Floats.contains(EMPTY, (float) 1)); assertFalse(Floats.contains(ARRAY1, (float) 2)); assertFalse(Floats.contains(ARRAY234, (float) 1)); assertTrue(Floats.contains(new float[] {(float) -1}, (float) -1)); assertTrue(Floats.contains(ARRAY234, (float) 2)); assertTrue(Floats.contains(ARRAY234, (float) 3)); assertTrue(Floats.contains(ARRAY234, (float) 4)); for (float value : NUMBERS) { assertTrue("" + value, Floats.contains(new float[] {5f, value}, value)); } assertFalse(Floats.contains(new float[] {5f, NaN}, NaN)); } public void testIndexOf() { assertEquals(-1, Floats.indexOf(EMPTY, (float) 1)); assertEquals(-1, Floats.indexOf(ARRAY1, (float) 2)); assertEquals(-1, Floats.indexOf(ARRAY234, (float) 1)); assertEquals(0, Floats.indexOf( new float[] {(float) -1}, (float) -1)); assertEquals(0, Floats.indexOf(ARRAY234, (float) 2)); assertEquals(1, Floats.indexOf(ARRAY234, (float) 3)); assertEquals(2, Floats.indexOf(ARRAY234, (float) 4)); assertEquals(1, Floats.indexOf( new float[] { (float) 2, (float) 3, (float) 2, (float) 3 }, (float) 3)); for (float value : NUMBERS) { assertEquals("" + value, 1, Floats.indexOf(new float[] {5f, value}, value)); } assertEquals(-1, Floats.indexOf(new float[] {5f, NaN}, NaN)); } public void testIndexOf_arrayTarget() { assertEquals(0, Floats.indexOf(EMPTY, EMPTY)); assertEquals(0, Floats.indexOf(ARRAY234, EMPTY)); assertEquals(-1, Floats.indexOf(EMPTY, ARRAY234)); assertEquals(-1, Floats.indexOf(ARRAY234, ARRAY1)); assertEquals(-1, Floats.indexOf(ARRAY1, ARRAY234)); assertEquals(0, Floats.indexOf(ARRAY1, ARRAY1)); assertEquals(0, Floats.indexOf(ARRAY234, ARRAY234)); assertEquals(0, Floats.indexOf( ARRAY234, new float[] { (float) 2, (float) 3 })); assertEquals(1, Floats.indexOf( ARRAY234, new float[] { (float) 3, (float) 4 })); assertEquals(1, Floats.indexOf(ARRAY234, new float[] { (float) 3 })); assertEquals(2, Floats.indexOf(ARRAY234, new float[] { (float) 4 })); assertEquals(1, Floats.indexOf(new float[] { (float) 2, (float) 3, (float) 3, (float) 3, (float) 3 }, new float[] { (float) 3 } )); assertEquals(2, Floats.indexOf( new float[] { (float) 2, (float) 3, (float) 2, (float) 3, (float) 4, (float) 2, (float) 3}, new float[] { (float) 2, (float) 3, (float) 4} )); assertEquals(1, Floats.indexOf( new float[] { (float) 2, (float) 2, (float) 3, (float) 4, (float) 2, (float) 3, (float) 4}, new float[] { (float) 2, (float) 3, (float) 4} )); assertEquals(-1, Floats.indexOf( new float[] { (float) 4, (float) 3, (float) 2}, new float[] { (float) 2, (float) 3, (float) 4} )); for (float value : NUMBERS) { assertEquals("" + value, 1, Floats.indexOf( new float[] {5f, value, value, 5f}, new float[] {value, value})); } assertEquals(-1, Floats.indexOf( new float[] {5f, NaN, NaN, 5f}, new float[] {NaN, NaN})); } public void testLastIndexOf() { assertEquals(-1, Floats.lastIndexOf(EMPTY, (float) 1)); assertEquals(-1, Floats.lastIndexOf(ARRAY1, (float) 2)); assertEquals(-1, Floats.lastIndexOf(ARRAY234, (float) 1)); assertEquals(0, Floats.lastIndexOf( new float[] {(float) -1}, (float) -1)); assertEquals(0, Floats.lastIndexOf(ARRAY234, (float) 2)); assertEquals(1, Floats.lastIndexOf(ARRAY234, (float) 3)); assertEquals(2, Floats.lastIndexOf(ARRAY234, (float) 4)); assertEquals(3, Floats.lastIndexOf( new float[] { (float) 2, (float) 3, (float) 2, (float) 3 }, (float) 3)); for (float value : NUMBERS) { assertEquals("" + value, 0, Floats.lastIndexOf(new float[] {value, 5f}, value)); } assertEquals(-1, Floats.lastIndexOf(new float[] {NaN, 5f}, NaN)); } public void testMax_noArgs() { try { Floats.max(); fail(); } catch (IllegalArgumentException expected) { } } public void testMax() { assertEquals(GREATEST, Floats.max(GREATEST)); assertEquals(LEAST, Floats.max(LEAST)); assertEquals((float) 9, Floats.max( (float) 8, (float) 6, (float) 7, (float) 5, (float) 3, (float) 0, (float) 9)); assertEquals(0f, Floats.max(-0f, 0f)); assertEquals(0f, Floats.max(0f, -0f)); assertEquals(GREATEST, Floats.max(NUMBERS)); assertTrue(Float.isNaN(Floats.max(VALUES))); } public void testMin_noArgs() { try { Floats.min(); fail(); } catch (IllegalArgumentException expected) { } } public void testMin() { assertEquals(LEAST, Floats.min(LEAST)); assertEquals(GREATEST, Floats.min(GREATEST)); assertEquals((float) 0, Floats.min( (float) 8, (float) 6, (float) 7, (float) 5, (float) 3, (float) 0, (float) 9)); assertEquals(-0f, Floats.min(-0f, 0f)); assertEquals(-0f, Floats.min(0f, -0f)); assertEquals(LEAST, Floats.min(NUMBERS)); assertTrue(Float.isNaN(Floats.min(VALUES))); } public void testConcat() { assertTrue(Arrays.equals(EMPTY, Floats.concat())); assertTrue(Arrays.equals(EMPTY, Floats.concat(EMPTY))); assertTrue(Arrays.equals(EMPTY, Floats.concat(EMPTY, EMPTY, EMPTY))); assertTrue(Arrays.equals(ARRAY1, Floats.concat(ARRAY1))); assertNotSame(ARRAY1, Floats.concat(ARRAY1)); assertTrue(Arrays.equals(ARRAY1, Floats.concat(EMPTY, ARRAY1, EMPTY))); assertTrue(Arrays.equals( new float[] {(float) 1, (float) 1, (float) 1}, Floats.concat(ARRAY1, ARRAY1, ARRAY1))); assertTrue(Arrays.equals( new float[] {(float) 1, (float) 2, (float) 3, (float) 4}, Floats.concat(ARRAY1, ARRAY234))); } public void testEnsureCapacity() { assertSame(EMPTY, Floats.ensureCapacity(EMPTY, 0, 1)); assertSame(ARRAY1, Floats.ensureCapacity(ARRAY1, 0, 1)); assertSame(ARRAY1, Floats.ensureCapacity(ARRAY1, 1, 1)); assertTrue(Arrays.equals( new float[] {(float) 1, (float) 0, (float) 0}, Floats.ensureCapacity(ARRAY1, 2, 1))); } public void testEnsureCapacity_fail() { try { Floats.ensureCapacity(ARRAY1, -1, 1); fail(); } catch (IllegalArgumentException expected) { } try { // notice that this should even fail when no growth was needed Floats.ensureCapacity(ARRAY1, 1, -1); fail(); } catch (IllegalArgumentException expected) { } } public void testLexicographicalComparator() { List<float[]> ordered = Arrays.asList( new float[] {}, new float[] {LEAST}, new float[] {LEAST, LEAST}, new float[] {LEAST, (float) 1}, new float[] {(float) 1}, new float[] {(float) 1, LEAST}, new float[] {GREATEST, Float.MAX_VALUE}, new float[] {GREATEST, GREATEST}, new float[] {GREATEST, GREATEST, GREATEST}); Comparator<float[]> comparator = Floats.lexicographicalComparator(); Helpers.testComparator(comparator, ordered); } public void testToArray() { // need explicit type parameter to avoid javac warning!? List<Float> none = Arrays.<Float>asList(); assertTrue(Arrays.equals(EMPTY, Floats.toArray(none))); List<Float> one = Arrays.asList((float) 1); assertTrue(Arrays.equals(ARRAY1, Floats.toArray(one))); float[] array = {(float) 0, (float) 1, (float) 3}; List<Float> three = Arrays.asList((float) 0, (float) 1, (float) 3); assertTrue(Arrays.equals(array, Floats.toArray(three))); assertTrue(Arrays.equals(array, Floats.toArray(Floats.asList(array)))); } public void testToArray_threadSafe() { for (int delta : new int[] { +1, 0, -1 }) { for (int i = 0; i < VALUES.length; i++) { List<Float> list = Floats.asList(VALUES).subList(0, i); Collection<Float> misleadingSize = Helpers.misleadingSizeCollection(delta); misleadingSize.addAll(list); float[] arr = Floats.toArray(misleadingSize); assertEquals(i, arr.length); for (int j = 0; j < i; j++) { assertEquals(VALUES[j], arr[j]); } } } } public void testToArray_withNull() { List<Float> list = Arrays.asList((float) 0, (float) 1, null); try { Floats.toArray(list); fail(); } catch (NullPointerException expected) { } } public void testToArray_withConversion() { float[] array = {(float) 0, (float) 1, (float) 2}; List<Byte> bytes = Arrays.asList((byte) 0, (byte) 1, (byte) 2); List<Short> shorts = Arrays.asList((short) 0, (short) 1, (short) 2); List<Integer> ints = Arrays.asList(0, 1, 2); List<Float> floats = Arrays.asList((float) 0, (float) 1, (float) 2); List<Long> longs = Arrays.asList((long) 0, (long) 1, (long) 2); List<Double> doubles = Arrays.asList((double) 0, (double) 1, (double) 2); assertTrue(Arrays.equals(array, Floats.toArray(bytes))); assertTrue(Arrays.equals(array, Floats.toArray(shorts))); assertTrue(Arrays.equals(array, Floats.toArray(ints))); assertTrue(Arrays.equals(array, Floats.toArray(floats))); assertTrue(Arrays.equals(array, Floats.toArray(longs))); assertTrue(Arrays.equals(array, Floats.toArray(doubles))); } public void testAsList_isAView() { float[] array = {(float) 0, (float) 1}; List<Float> list = Floats.asList(array); list.set(0, (float) 2); assertTrue(Arrays.equals(new float[] {(float) 2, (float) 1}, array)); array[1] = (float) 3; ASSERT.that(list).has().exactly((float) 2, (float) 3).inOrder(); } public void testAsList_toArray_roundTrip() { float[] array = { (float) 0, (float) 1, (float) 2 }; List<Float> list = Floats.asList(array); float[] newArray = Floats.toArray(list); // Make sure it returned a copy list.set(0, (float) 4); assertTrue(Arrays.equals( new float[] { (float) 0, (float) 1, (float) 2 }, newArray)); newArray[1] = (float) 5; assertEquals((float) 1, (float) list.get(1)); } // This test stems from a real bug found by andrewk public void testAsList_subList_toArray_roundTrip() { float[] array = { (float) 0, (float) 1, (float) 2, (float) 3 }; List<Float> list = Floats.asList(array); assertTrue(Arrays.equals(new float[] { (float) 1, (float) 2 }, Floats.toArray(list.subList(1, 3)))); assertTrue(Arrays.equals(new float[] {}, Floats.toArray(list.subList(2, 2)))); } public void testAsListEmpty() { assertSame(Collections.emptyList(), Floats.asList(EMPTY)); } /** * A reference implementation for {@code tryParse} that just catches the exception from * {@link Float#valueOf}. */ private static Float referenceTryParse(String input) { if (input.trim().length() < input.length()) { return null; } try { return Float.valueOf(input); } catch (NumberFormatException e) { return null; } } private static final String[] BAD_TRY_PARSE_INPUTS = { "", "+-", "+-0", " 5", "32 ", " 55 ", "infinity", "POSITIVE_INFINITY", "0x9A", "0x9A.bE-5", ".", ".e5", "NaNd", "InfinityF" }; }
Java