class String

Public Instance Methods

densify() click to toggle source
static VALUE densify(VALUE self) {
    // Convert ruby string into c string and length
    int length = RSTRING_LEN(self);
    char *string = RSTRING_PTR(self);
    
    // set up string to accept characters from ruby string
    char minified[length+1];
    int minified_index = 0; // since the overall length of the original string > length of the minified string
    
    int is_in_quotes = 0;
    int is_in_spaces = 0;
    
    for (int i = 0; i < length; i++) {
        char curr_char = string[i];
        
        // current char is a quote
        if (curr_char == '"' || curr_char == '\'') {
            is_in_quotes = (is_in_quotes == 0)?1:0;
        }
        
        // if in quotes, add the character automatically
        if (is_in_quotes == 1) {
            minified[minified_index] = curr_char;
            minified_index++;
            continue;
        }
        
        switch (curr_char) {
            case '\n':
                // ignore newlines
                break;
            case '\t': // treat tabs like spaces
            case ' ':
                // If this is the first space, add the space
                if (is_in_spaces == 0) {
                    minified[minified_index] = ' ';
                    minified_index++;
                }
                
                // indicate that we are in a series of spaces
                is_in_spaces = 1;
                break;
            default: // this is every other character
                is_in_spaces = 0;
                minified[minified_index] = curr_char;
                minified_index++;
                break;
        }
    }

    // no need to null terminate
    return rb_str_new(minified, minified_index);
}