public String encode()

in geronimo-mail_2.1_impl/geronimo-mail_2.1_provider/src/main/java/org/apache/geronimo/mail/store/imap/connection/IMAPCommand.java [291:362]


    public String encode(String original) {

        // buffer for encoding sections of data
        byte[] buffer = new byte[4];
        int bufferCount = 0;

        StringBuffer result = new StringBuffer();

        // state flag for the type of section we're in.
        boolean encoding = false;

        for (int i = 0; i < original.length(); i++) {
            char ch = original.charAt(i);

            // processing an encoded section?
            if (encoding) {
                // is this a printable character?
                if (ch > 31 && ch < 127) {
                    // encode anything in the buffer
                    encode(buffer, bufferCount, result);
                    // add the section terminator char
                    result.append('-');
                    encoding = false;
                    // we now fall through to the printable character section.
                }
                // still an unprintable
                else {
                    // add this char to the working buffer?
                    buffer[++bufferCount] = (byte)(ch >> 8);
                    buffer[++bufferCount] = (byte)(ch & 0xff);
                    // if we have enough to encode something, do it now.
                    if (bufferCount >= 3) {
                        bufferCount = encode(buffer, bufferCount, result);
                    }
                    // go back to the top of the loop.
                    continue;
                }
            }
            // is this the special printable?
            if (ch == '&') {
                // this is the special null escape sequence
                result.append('&');
                result.append('-');
            }
            // is this a printable character?
            else if (ch > 31 && ch < 127) {
                // just add to the result
                result.append(ch);
            }
            else {
                // write the escape character
                result.append('&');

                // non-printable ASCII character, we need to switch modes
                // both bytes of this character need to be encoded.  Each
                // encoded digit will basically be a "character-and-a-half".
                buffer[0] = (byte)(ch >> 8);
                buffer[1] = (byte)(ch & 0xff);
                bufferCount = 2;
                encoding = true;
            }
        }
        // were we in a non-printable section at the end?
        if (encoding) {
            // take care of any remaining characters
            encode(buffer, bufferCount, result);
            // add the section terminator char
            result.append('-');
        }
        // convert the encoded string.
        return result.toString();
    }