MediaTypeSet extends AbstractSet<MediaType> { @VisibleForTesting @SuppressWarnings("checkstyle:FallThrough") static void addRanges(List<MediaType> ranges, CharSequence header) { final int length = header.length(); int state = ST_SKIP_LEADING_WHITESPACES; int firstCharIdx = 0; int lastCharIdx = -1; for (int i = 0; i < length; i++) { final char ch = header.charAt(i); switch (state) { case ST_SKIP_LEADING_WHITESPACES: if (!Character.isWhitespace(ch)) { state = ST_READ_QDTEXT; firstCharIdx = i; lastCharIdx = -1; } else { break; } case ST_READ_QDTEXT: if (Character.isWhitespace(ch)) { break; } switch (ch) { case '"': state = ST_READ_QUOTED_STRING; break; case ',': addRange(ranges, header, firstCharIdx, lastCharIdx); state = ST_SKIP_LEADING_WHITESPACES; break; default: lastCharIdx = i; } break; case ST_READ_QUOTED_STRING: switch (ch) { case '\\': state = ST_READ_QUOTED_STRING_ESCAPED; break; case '"': state = ST_READ_QDTEXT; lastCharIdx = i; break; } break; case ST_READ_QUOTED_STRING_ESCAPED: state = ST_READ_QUOTED_STRING; break; } } if (state == ST_READ_QDTEXT) { addRange(ranges, header, firstCharIdx, lastCharIdx); } } private  MediaTypeSet(Iterable<MediaType> mediaTypes); static MediaTypeSet of(MediaType... mediaTypes); static MediaTypeSet of(Iterable<MediaType> mediaTypes); @Override boolean contains(Object o); @Override Iterator<MediaType> iterator(); @Override int size(); @Nullable MediaType matchHeaders(Iterable<? extends CharSequence> acceptHeaders); @Nullable MediaType matchHeaders(CharSequence... acceptHeaders); @Nullable MediaType match(MediaType range); @Nullable MediaType match(MediaType first, MediaType... rest); @Nullable MediaType match(Iterable<MediaType> ranges);  }
@Test void testAddRanges() { final List<MediaType> ranges = new ArrayList<>(); MediaTypeSet.addRanges(ranges, "text/plain"); assertThat(ranges).containsExactly(MediaType.parse("text/plain")); ranges.clear(); MediaTypeSet.addRanges(ranges, "text/plain,text/html"); assertThat(ranges).containsExactly(MediaType.parse("text/plain"), MediaType.parse("text/html")); ranges.clear(); MediaTypeSet.addRanges(ranges, " text/plain "); assertThat(ranges).containsExactly(MediaType.parse("text/plain")); ranges.clear(); MediaTypeSet.addRanges(ranges, " text/plain , text/html "); assertThat(ranges).containsExactly(MediaType.parse("text/plain"), MediaType.parse("text/html")); ranges.clear(); MediaTypeSet.addRanges(ranges, "text/plain; foo=\"b\\\"a,r\", text/html; bar=\"b\\a\\z\""); assertThat(ranges).containsExactly(MediaType.parse("text/plain; foo=\"b\\\"a,r\""), MediaType.parse("text/html; bar=baz")); ranges.clear(); MediaTypeSet.addRanges(ranges, ",,,"); assertThat(ranges).isEmpty(); MediaTypeSet.addRanges(ranges, " , , , "); assertThat(ranges).isEmpty(); }