public static @NotNull Pair.NonNull<Charset, byte[]> chooseMostlyHarmlessCharset(@NotNull Charset existing, @NotNull Charset specified, @NotNull String text) {
    try {
      if (specified.equals(existing)) {
        return Pair.createNonNull(specified, text.getBytes(existing));
      }

      byte[] out = isSupported(specified, text);
      if (out != null) {
        // if explicitly specified encoding is safe, return it
        return Pair.createNonNull(specified, out);
      }
      out = isSupported(existing, text);
      if (out != null) {
        // otherwise, stick to the old encoding if it's ok
        return Pair.createNonNull(existing, out);
      }
      return Pair.createNonNull(specified, text.getBytes(specified)); //if both are bad, there is no difference
    }
    catch (RuntimeException e) {
      Charset defaultCharset = Charset.defaultCharset();
      return Pair.createNonNull(defaultCharset, text.getBytes(defaultCharset)); //if both are bad and there is no hope, use the default charset
    }
  }
public static @NotNull Pair.NonNull<Charset, byte[]> chooseMostlyHarmlessCharset(@NotNull Charset existing, @NotNull Charset specified, @NotNull String text)