private static String extractCharsetComment()

in freemarker-docgen-core/src/main/java/org/freemarker/docgen/core/CJSONInterpreter.java [1495:1571]


    private static String extractCharsetComment(byte[] b) {
        char c;
        String s;
        int p = 0;
        int ln = b.length;

        // Skip BOM, if present:
        if (p + 2 < ln
                && toChar(b[p]) == 0xEF
                && toChar(b[p + 1]) == 0xBB
                && toChar(b[p + 2]) == 0xBF) {
            p += 3;
        }
        
        // Skip WS
        while (p < ln && Character.isWhitespace(toChar(b[p]))) {
            p++;
        }

        // Do we start with "//"? 
        if (!(p + 1 < ln && toChar(b[p]) == '/' && toChar(b[p + 1]) == '/')) {
            return null; // No.
        }
        p += 2;
        
        p = extractCharsetComment_skipNonNLWS(b, p);
        int bp = p;
        while (p < ln) {
            c = toChar(b[p]);
            if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))) {
                break;
            }
            p++;
        }
        if (p - bp != ENCODING_COMMENT_1.length()
                && p - bp != ENCODING_COMMENT_2.length()) {
            return null;
        }
        try {
            s = new String(b, bp, p - bp, "ISO-8859-1").toLowerCase();
        } catch (UnsupportedEncodingException e) {
            throw new BugException("ISO-8859-1 decoding failed.", e);
        }
        if (!s.equals(ENCODING_COMMENT_1) && !s.equals(ENCODING_COMMENT_2)) {
            return null;
        }
        p = extractCharsetComment_skipNonNLWS(b, p);
        if (p == ln) {
            return null;
        }
        c = toChar(b[p]);
        if (c != ':') {
            return null;
        }
        p++;
        p = extractCharsetComment_skipNonNLWS(b, p);
        if (p == ln) {
            return null;
        }
        bp = p;
        while (p < ln) {
            c = toChar(b[p]);
            if (c == 0xA || c == 0xD) {
                break;
            }
            p++;
        }
        try {
            s = new String(b, bp, p - bp, "ISO-8859-1").trim();
            if (s.length() == 0) {
                return null;
            }
        } catch (UnsupportedEncodingException e) {
            throw new BugException("ISO-8859-1 decoding failed.", e);
        }
        return s;
    }