code: @Override
    public int write(OutputStreamWithBuffer os, char []cbuf, int off, int len)
      throws IOException
    {
      byte []buffer = os.buffer();
      int length = os.offset();
      int capacity = buffer.length;
      int tail = off + len;
      int head = off;
  
      while (off < tail) {
        while (capacity - length <= 4) {
          buffer = os.nextBuffer(length);
          length = os.offset();
        }
        
        char ch = cbuf[off++];
  
        if (ch < 0x80) {
          buffer[length++] = (byte) ch;
        }
        else if (ch < 0x800) {
          buffer[length++] = (byte) (0xc0 + (ch >> 6));
          buffer[length++] = (byte) (0x80 + (ch & 0x3f));
        }
        else if (ch < 0xd800 || 0xdfff < ch) {
          // server/0815
          buffer[length++] = (byte) (0xe0 + (ch >> 12));
          buffer[length++] = (byte) (0x80 + ((ch >> 6) & 0x3f));
          buffer[length++] = (byte) (0x80 + (ch & 0x3f));
        }
        else if (off == tail) {
          off--;
          break;
        }
        else {
          char ch2 = cbuf[off++];
          
          int v = 0x10000 + (ch & 0x3ff) * 0x400 + (ch2 & 0x3ff);
            
          buffer[length++] = (byte) (0xf0 + (v >> 18));
          buffer[length++] = (byte) (0x80 + ((v >> 12) & 0x3f));
          buffer[length++] = (byte) (0x80 + ((v >> 6) & 0x3f));
          buffer[length++] = (byte) (0x80 + (v & 0x3f));
        }
      }
  
      os.offset(length);
      
      return off - head;
    }
docs: Writes into a character buffer using the correct encoding.
  
  @param cbuf character array with the data to write.
  @param off starting offset into the character array.
  @param len the number of characters to write.