1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
package Torello.Java;

class ChompCallableBraces
{
    static String run(String callableAsStr)
    {
        callableAsStr = callableAsStr.trim();

        if (callableAsStr.charAt(0) != '{') throw new CallableBodyException(
            "Passed callable does not begin with a squiggly-brace '{', but rather a: '" + 
            callableAsStr.charAt(0) + "'\n" + callableAsStr
        );

        if (callableAsStr.charAt(callableAsStr.length() - 1) != '}') throw new CallableBodyException(
            "Passed callable does not end with a squiggly-brace '}', but rather a: '" + 
            callableAsStr.charAt(0) + "'\n"+ callableAsStr
        );


        // This Version does a single "String.substring(...)", meaning it is more efficient
        // because it is not doing any extra String copies at all.
        //
        // NOTE: There is an auto-pre-increment (and pre-decrement), in both of the while loops.
        //       Therefore, sPos starts at 'zero' - even though the open-curly-brace is the 
        //       character at position 0, and the closed-curly-brace is at position length-1.

        int     sPos    = 0;
        int     ePos    = callableAsStr.length() - 1;
        int     first   = 1;    // The character after the '{' (open-curly-brace)
        char    tempCh  = 0;    // temp-var


        // If the callable-braces are on their own line, skip that first line.
        // If they are **NOTE** on their own first line, the first character returned will be
        // the first character of source-code.

        while ((sPos < ePos) && Character.isWhitespace(tempCh = callableAsStr.charAt(++sPos)))

            if (tempCh == '\n')
            {
                first = sPos + 1;
                break;
            }


        // Check for the "bizarre case" that the method body just doesn't contain any code.
        // This means that *EVERY CHARACTER* that was checked was white-space.  Return a single
        // space character, and be done with it.

        if (sPos == ePos) return " ";


        // When this loop terminates, 'ePos' will be pointing to the first non-white-space
        // character at the tail end of the source-code / String (callableAsStr is a String of
        // source-code used in the JavaDoc package)

        while ((ePos > sPos) && Character.isWhitespace(callableAsStr.charAt(--ePos)));


        // Starts at the 'first-white-space' character in the first line of code, and ends at the
        // last non-white-space character in source-code String 'callableAsStr'

        return callableAsStr.substring(first, ePos + 1);
    }    
}