public void encode(String value,ByteBuffer buffer) throws BufferOverflowException {
  if (value == null) {
    buffer.put((byte)(0x80));
    return;
  }
  int charCount=value.length();
  if (charCount == 0) {
    buffer.put((byte)(1 | 0x80));
    return;
  }
  int position=buffer.position();
  boolean ascii=true;
  if (charCount > 1) {
    for (int i=0; i < charCount; i++) {
      int c=value.charAt(i);
      if (c > 127) {
        ascii=false;
        break;
      }
      buffer.put((byte)c);
    }
  }
 else {
    ascii=false;
  }
  if (ascii) {
    position=buffer.position();
    buffer.put(position - 1,(byte)(buffer.get(position - 1) | 0x80));
  }
 else {
    buffer.position(position);
    writeLength(charCount + 1,buffer);
    int charIndex=0;
    for (; charIndex < charCount; charIndex++) {
      int c=value.charAt(charIndex);
      if (c > 127)       break;
      buffer.put((byte)c);
    }
    writeUTF8String(value,charCount,charIndex,buffer);
  }
}

public void encode ( String value , ByteBuffer buffer ) throws BufferOverflowException { if ( value == null ) { buffer . put ( ( byte ) ( 0x80 ) ) ; return ; } int charCount = value . length ( ) ; if ( charCount == 0 ) { buffer . put ( ( byte ) ( 1 | 0x80 ) ) ; return ; } int position = buffer . position ( ) ; boolean ascii = true ; if ( charCount > 1 ) { for ( int i = 0 ; i < charCount ; i ++ ) { int c = value . charAt ( i ) ; if ( c > 127 ) { ascii = false ; break ; } buffer . put ( ( byte ) c ) ; } } else { ascii = false ; } if ( ascii ) { position = buffer . position ( ) ; buffer . put ( position - 1 , ( byte ) ( buffer . get ( position - 1 ) | 0x80 ) ) ; } else { buffer . position ( position ) ; writeLength ( charCount + 1 , buffer ) ; int charIndex = 0 ; for ( ; charIndex < charCount ; charIndex ++ ) { int c = value . charAt ( charIndex ) ; if ( c > 127 ) break ; buffer . put ( ( byte ) c ) ; } writeUTF8String ( value , charCount , charIndex , buffer ) ; } }
encode the string to the buffer , null and empty string is allowable . the input byte buffer is writable and it write from its current position . if the input buffer capacity is not enough , the bufferoverflowexception will be thrown .
