code: static String encode(Encoder encoder, String str) {
          if (str == null) {
              // consistent with String.valueOf(...) use "null" for null.
              str = "null";
          }
  
          // quick pass--see if we need to actually encode anything, if not
          // return the value unchanged.
          final int n = str.length();
          int j = encoder.firstEncodedOffset(str, 0, n);
  
          if (j == n) {
              return str;
          }
  
          // otherwise, we need to encode.  We use a buffer to avoid
          // excessive memory allocation for these calls.  Note: this means that
          // an encoder implementation must NEVER call this method internally.
          return new Buffer().encode(encoder, str, j);
      }
docs: Core encoding loop shared by public methods.  It first uses the
  encoder to scan the input for characters that need encoding.  If
  no characters require encoding, the input string is returned.
  Otherwise a buffer is used to encode the remainder
  of the input.
  
  @param encoder the encoder to use
  @param str the string to encode
  @return the input string encoded with the provided encoder.