public static String encode()

in src/main/java/com/twitter/joauth/UrlCodec.java [53:108]


  public static String encode(String s) {
    if (s == null) {
      return null;
    }

    StringBuilder sb = null;
    int j = 0;

    // scan through to see where we have to start % encoding, if at all
    int startingIndex = 0;
    while (j < s.length()) {
      if (!isUnreserved(s.charAt(j))) {
        startingIndex = j;
        break;
      } else {
        j++;
      }
    }

    // scan through to see where we have to end % encoding, if at all
    int endingIndex = startingIndex;
    while (j < s.length()) {
      if (!isUnreserved(s.charAt(j))) {
        j += Character.charCount(s.codePointAt(j));
        endingIndex = j;
      } else {
        j++;
      }
    }

    if (startingIndex < endingIndex) {
      // allocate a string builder with padding for % encoding
      sb = new StringBuilder(s.length() + 40);
      // append prefix (no encoding required)
      sb.append(s, 0, startingIndex);

      byte[] byteArray = s.substring(startingIndex, endingIndex).getBytes(UTF_8_CHARSET);
      for (int i = 0; i < byteArray.length; i++) {
        byte bite = byteArray[i];
        if (isUnreserved(bite)) {
          sb.append((char)bite);
        } else {
          // turn the Byte into an int into the hex string, but be sure to mask out the unneeded bits
          // to avoid nastiness with converting to a negative int
          sb.append('%');
          sb.append(HEX_DIGITS[(bite >> 4) & 0x0F]);
          sb.append(HEX_DIGITS[bite & 0x0F]);
        }
      }

      // append postfix (no encoding required)
      sb.append(s, endingIndex, s.length());
    }

    return (sb == null) ? s : sb.toString();
  }