计算字符串被UTF8编码后的字节数 via guava

@see Utf8#encodedLength(CharSequence)
492441
public static int utf8EncodedLength(@Nullable CharSequence sequence) {
		if (StringUtils.isEmpty(sequence)) {
			return 0;
		}
		return Utf8.encodedLength(sequence);
	}
394301
public void writeUtf8(CharSequence string) {
    for (int i = 0, len = string.length(); i < len; i++) {
      char ch = string.charAt(i);
      if (ch < 0x80) { // 7-bit ASCII character
        writeByte(ch);
        // This could be an ASCII run, or possibly entirely ASCII
        while (i < len - 1) {
          ch = string.charAt(i + 1);
          if (ch >= 0x80) break;
          i++;
          writeByte(ch); // another 7-bit ASCII character
        }
      } else if (ch < 0x800) { // 11-bit character
        writeByte(0xc0 | (ch >> 6));
        writeByte(0x80 | (ch & 0x3f));
      } else if (ch < 0xd800 || ch > 0xdfff) { // 16-bit character
        writeByte(0xe0 | (ch >> 12));
        writeByte(0x80 | ((ch >> 6) & 0x3f));
        writeByte(0x80 | (ch & 0x3f));
      } else { // Possibly a 21-bit character
        if (!Character.isHighSurrogate(ch)) { // Malformed or not UTF-8
          writeByte('?');
          continue;
        }
        if (i == len - 1) { // Truncated or not UTF-8
          writeByte('?');
          break;
        }
        char low = string.charAt(++i);
        if (!Character.isLowSurrogate(low)) { // Malformed or not UTF-8
          writeByte('?');
          writeByte(Character.isHighSurrogate(low) ? '?' : low);
          continue;
        }
        // Write the 21-bit character using 4 bytes
        // See http://www.unicode.org/versions/Unicode7.0.0/ch03.pdf#G2630
        int codePoint = Character.toCodePoint(ch, low);
        writeByte(0xf0 | (codePoint >> 18));
        writeByte(0x80 | ((codePoint >> 12) & 0x3f));
        writeByte(0x80 | ((codePoint >> 6) & 0x3f));
        writeByte(0x80 | (codePoint & 0x3f));
      }
    }
  }
905589
static int getLength(int lenByte, InputStream in) throws IOException {
        int value, tmp;

        tmp = lenByte;
        if ((tmp & 0x080) == 0x00) { // short form, 1 byte datum
            value = tmp;
        } else {                     // long form or indefinite
            tmp &= 0x07f;

            /*
             * NOTE:  tmp == 0 indicates indefinite length encoded data.
             * tmp > 4 indicates more than 4Gb of data.
             */
            if (tmp == 0)
                return -1;
            if (tmp < 0 || tmp > 4)
                throw new IOException("DerInputStream.getLength(): lengthTag="
                    + tmp + ", "
                    + ((tmp < 0) ? "incorrect DER encoding." : "too big."));

            for (value = 0; tmp > 0; tmp --) {
                value <<= 8;
                value += 0x0ff & in.read();
            }
            if (value < 0) {
                throw new IOException("DerInputStream.getLength(): "
                        + "Invalid length bytes");
            }
        }
        return value;
    }
857430
private static final String encode(String s) {
    try {
      return URLEncoder.encode(s, UTF_8);
    } catch (UnsupportedEncodingException e) {
      throw new Error("JVM unable to handle UTF-8");
    }
  }
1306440
static byte[] encode(int count) {
        // 计算需要填充的位数
        int amountToPad = BLOCK_SIZE - (count % BLOCK_SIZE);
        if (amountToPad == 0) {
            amountToPad = BLOCK_SIZE;
        }
        // 获得补位所用的字符
        char padChr = chr(amountToPad);
        String tmp = new String();
        for (int index = 0; index < amountToPad; index++) {
            tmp += padChr;
        }
        return tmp.getBytes(CHARSET);
    }
1324745
private function decodeString()
    {
        if ("0" === $this->getChar() && ":" != $this->getChar($this->offset + 1)) {
            throw new RuntimeException("Illegal zero-padding in string entity length declaration at offset $this->offset");
        }

        $offsetOfColon = strpos($this->source, ":", $this->offset);
        if (false === $offsetOfColon) {
            throw new RuntimeException("Unterminated string entity at offset $this->offset");
        }

        $contentLength = (int) substr($this->source, $this->offset, $offsetOfColon);
        if (($contentLength + $offsetOfColon + 1) > $this->sourceLength) {
            throw new RuntimeException("Unexpected end of string entity at offset $this->offset");
        }

        $value = substr($this->source, $offsetOfColon + 1, $contentLength);
        $this->offset = $offsetOfColon + $contentLength + 1;

        return $value;
    }
883608
function lengthInUtf8Bytes(str) {
		const m = encodeURIComponent(str).match(/%[89ABab]/g);
		return str.length + (m ? m.length : 0);
	}
146579
public static int utf8Bytes(final CharSequence seq) {
        if (seq instanceof AsciiString) {
            return seq.length();
        }
        int seqLength = seq.length();
        int i = 0;
        // ASCII fast path
        while (i < seqLength && seq.charAt(i) < 0x80) {
            ++i;
        }
        // !ASCII is packed in a separate method to let the ASCII case be smaller
        return i < seqLength ? i + utf8Bytes(seq, i, seqLength) : i;
    }
1309423
function _getUTF8Length(content) {
    var result = encodeURI(content).toString().replace(/\%[0-9a-fA-F]{2}/g, 'a');
    return result.length + (result.length != content ? 3 : 0);
  }
1027605
@Override
    public String decode( String encodedText ) {
        if (encodedText == null) return null;
        if (encodedText.length() < 7) {
            // Not big enough to have an encoded sequence
            return encodedText;
        }
        StringBuilder sb = new StringBuilder();
        char[] digits = new char[4];
        CharacterIterator iter = new StringCharacterIterator(encodedText);
        for (char c = iter.first(); c != CharacterIterator.DONE; c = iter.next()) {
            if (c == '_') {
                // Read the next character, if there is one ...
                char next = iter.next();
                if (next == CharacterIterator.DONE) {
                    sb.append(c);
                    break;
                }
                // If the next character is not 'x', then these are just regular characters ...
                if (next != 'x') {
                    sb.append(c).append(next);
                    continue;
                }
                // Read the next 4 characters (digits) and another '_' character ...
                digits[0] = iter.next();
                if (digits[0] == CharacterIterator.DONE) {
                    sb.append(c).append(next);
                    break;
                }
                digits[1] = iter.next();
                if (digits[1] == CharacterIterator.DONE) {
                    sb.append(c).append(next).append(digits, 0, 1);
                    break;
                }
                digits[2] = iter.next();
                if (digits[2] == CharacterIterator.DONE) {
                    sb.append(c).append(next).append(digits, 0, 2);
                    break;
                }
                digits[3] = iter.next();
                if (digits[3] == CharacterIterator.DONE) {
                    sb.append(c).append(next).append(digits, 0, 3);
                    break;
                }
                char underscore = iter.next();
                if (underscore != '_') { // includes DONE
                    sb.append(c).append(next).append(digits, 0, 4);
                    if (underscore == CharacterIterator.DONE) break;
                    sb.append(underscore);
                    continue;
                }
                // We've read all 4 digits, including the trailing '_'
                // Now parse into the resulting character
                try {
                    sb.appendCodePoint(Integer.parseInt(new String(digits), 16));
                } catch (NumberFormatException e) {
                    // code was not hexadecimal, so just write out the characters as is ...
                    sb.append(c).append(next).append(digits).append(underscore);
                }
            } else {
                // Just append other characters ...
                sb.append(c);
            }
        }
        return sb.toString();
    }
303525
public String readUTF8EncodedString(int stringLength) {
        if (stringLength > 0 && this.bufferPosition + stringLength <= this.bufferData.length) {
            this.bufferPosition += stringLength;
            try {
                return new String(this.bufferData, this.bufferPosition - stringLength, stringLength, CHARSET_UTF8);
            } catch (UnsupportedEncodingException e) {
                throw new IllegalStateException(e);
            }
        }
        LOGGER.warning("invalid string length: " + stringLength);
        return null;
    }
272990
def utf8_char_length_in_bytes(first_byte)
      if first_byte.hex < 'C0'.hex
        1
      elsif first_byte.hex < 'DF'.hex
        2
      elsif first_byte.hex < 'EF'.hex
        3
      else
        4
      end
    end
761653
public static function length($string, $charset = 'UTF-8')
    {
        $charset = self::lower($charset);

        if ($charset == 'utf-8' || $charset == 'utf8') {
            return strlen(utf8_decode($string));
        }

        if (Horde_Util::extensionExists('mbstring')) {
            $ret = @mb_strlen($string, self::_mbstringCharset($charset));
            if (!empty($ret)) {
                return $ret;
            }
        }
        if (Horde_Util::extensionExists('intl')) {
            return grapheme_strlen(
                self::convertCharset($string, $charset, 'UTF-8')
            );
        }

        return strlen($string);
    }
1285140
public int getLength() {
    // Alias, number of patterns
    int length = 4 + 4;

    if (this.identifierPatterns != null) {
      for (String identifier : this.identifierPatterns) {
        try {
          length += (4 + identifier.getBytes("UTF-16BE").length);
        } catch (UnsupportedEncodingException e) {
          log.error("Unable to encode to UTF-16BE.");
        }
      }
    }
    return length;
  }
631395
function _rsapem_encodeLength(length) {
    if (length >= parseInt("80", 16)) {
        var realLength = _rsapem_padWithZero(length.toString(16));
        var lengthOfLength = (realLength.length / 2);
        return (parseInt("80", 16) + lengthOfLength).toString(16) + realLength;
    } else {
        return _rsapem_padWithZero(length.toString(16));
    }
}
281079
public static String encodeString(final String string) {
		String encodedString = null;

		try {
			encodedString = encodeString(string, "UTF-8");
		} catch (UnsupportedEncodingException uue) {
			// Should never happen, java has to support "UTF-8".
		}

		return encodedString;
	}
1331515
public static String decodeString(String encoded,int offset,int length,String charset)
    {
        if (charset==null)
            charset=StringUtil.__ISO_8859_1;
        byte[] bytes=null;
        int n=0;
        
        for (int i=0;i<length;i++)
        {
            char c = encoded.charAt(offset+i);
            if (c<0||c>0xff)
                throw new IllegalArgumentException("Not encoded");
            
            if (c=='+')
            {
                if (bytes==null)
                {
                    bytes=new byte[length*2];
                    encoded.getBytes(offset, offset+i, bytes, 0);
                    n=i;
                }
                bytes[n++] = (byte) ' ';
            }
            else if (c=='%' && (i+2)<length)
            {
                byte b;
                char cn = encoded.charAt(offset+i+1);
                if (cn>='a' && cn<='z')
                    b=(byte)(10+cn-'a');
                else if (cn>='A' && cn<='Z')
                    b=(byte)(10+cn-'A');
                else
                    b=(byte)(cn-'0');
                cn = encoded.charAt(offset+i+2);
                if (cn>='a' && cn<='z')
                    b=(byte)(b*16+10+cn-'a');
                else if (cn>='A' && cn<='Z')
                    b=(byte)(b*16+10+cn-'A');
                else
                    b=(byte)(b*16+cn-'0');

                if (bytes==null)
                {
                    bytes=new byte[length*2];
                    encoded.getBytes(offset, offset+i, bytes, 0);
                    n=i;
                }
                i+=2;
                bytes[n++]=b;
            }
            else if (n>0)
                bytes[n++] = (byte) c;
        }

        if (bytes==null)
        {
            if (offset==0 && encoded.length()==length)
                return encoded;
            return encoded.substring(offset,offset+length);
        }
        
        try
        {
            return new String(bytes,0,n,charset);
        }
        catch (UnsupportedEncodingException e)
        {
            return new String(bytes,0,n);
        }
        
    }