Expose getStrings() option on JsonReader.Options (#1180)

* Expose getStrings() option on JsonReader.Options

Resolves #1173

* Fix clone

Co-authored-by: Jake Wharton <github@jakewharton.com>

* Add mutation check

* Use set and make it unmodifiable

* Back to list

* strings()

* No clone()

Co-authored-by: Jake Wharton <github@jakewharton.com>
This commit is contained in:
Zac Sweers
2020-07-30 23:10:41 -04:00
committed by GitHub
parent cd31e5ce52
commit aa18c6857c
2 changed files with 22 additions and 0 deletions

View File

@@ -27,6 +27,8 @@ import okio.Buffer;
import okio.BufferedSource; import okio.BufferedSource;
import okio.ByteString; import okio.ByteString;
import static java.util.Collections.unmodifiableList;
/** /**
* Reads a JSON (<a href="http://www.ietf.org/rfc/rfc7159.txt">RFC 7159</a>) * Reads a JSON (<a href="http://www.ietf.org/rfc/rfc7159.txt">RFC 7159</a>)
* encoded value as a stream of tokens. This stream includes both literal * encoded value as a stream of tokens. This stream includes both literal
@@ -528,6 +530,11 @@ public abstract class JsonReader implements Closeable {
this.doubleQuoteSuffix = doubleQuoteSuffix; this.doubleQuoteSuffix = doubleQuoteSuffix;
} }
/** Returns a copy of this {@link Options Option's} strings. */
public List<String> strings() {
return unmodifiableList(Arrays.asList(strings));
}
@CheckReturnValue public static Options of(String... strings) { @CheckReturnValue public static Options of(String... strings) {
try { try {
ByteString[] result = new ByteString[strings.length]; ByteString[] result = new ByteString[strings.length];

View File

@@ -20,6 +20,7 @@ import java.io.IOException;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.List; import java.util.List;
import java.util.Set;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; import org.junit.runners.Parameterized;
@@ -1157,6 +1158,20 @@ public final class JsonReaderTest {
reader.endObject(); reader.endObject();
} }
@Test public void optionsStrings() {
String[] options = new String[] { "a", "b", "c" };
JsonReader.Options abc = JsonReader.Options.of("a", "b", "c");
List<String> strings = abc.strings();
assertThat(options).containsExactlyElementsOf(strings);
try {
// Confirm it's unmodifiable and we can't mutate the original underlying array
strings.add("d");
fail();
} catch (UnsupportedOperationException expected) {
}
}
/** Peek a value, then read it, recursively. */ /** Peek a value, then read it, recursively. */
private void readValue(JsonReader reader, boolean peekJsonFirst) throws IOException { private void readValue(JsonReader reader, boolean peekJsonFirst) throws IOException {
JsonReader.Token token = reader.peek(); JsonReader.Token token = reader.peek();