@CheckForNull
  public Charset detect(byte[] buf) {
    // Try UTF-8 first since we are very confident in it if it's a yes.
    // Fail if we see nulls to not have FPs if the text is ASCII encoded in UTF-16.
    Result utf8Result = validator.isUTF8(buf, true);
    if (utf8Result.valid() == Validation.YES) {
      return utf8Result.charset();
    } else if (utf8Result.valid() == Validation.MAYBE) {
      return detectAscii(buf);
    }

    // try UTF16 with both endiness. Fail if we see nulls to not have FPs if it's UTF-32.
    Result utf16 = validator.isUTF16(buf, true);
    if (utf16.valid() == Validation.YES && validator.isValidUTF16(buf, UTF_16LE.equals(utf16.charset()))) {
      return utf16.charset();
    }

    // at this point we know it can't be UTF-8
    Charset c = userConfiguration;
    if (!UTF_8.equals(c) && (!isUtf16(c) || utf16.valid() == Validation.MAYBE) && validator.tryDecode(buf, c)) {
      return c;
    }

    Result windows1252 = validator.isValidWindows1252(buf);
    if (windows1252.valid() == Validation.MAYBE) {
      return windows1252.charset();
    }

    return null;
  }
@Test
  public void tryUTF8First() {
    when(validation.isUTF8(any(byte[].class), anyBoolean())).thenReturn(Result.newValid(StandardCharsets.UTF_8));
    assertThat(charsets.detect(new byte[1])).isEqualTo(StandardCharsets.UTF_8);
  }