Class: SuffixArray

Inherits:
Object
  • Object
show all
Defined in:
ext/gdiff/suffix_array.c

Instance Method Summary collapse

Constructor Details

#new(source, [raw_array], [start]) ⇒ SuffixArray

Given a string (anything like a string really) this will generate a suffix array for the string so that you can work with it. The source cannot be an empty string since this is a useless operation.

Two optional parameters allow you to restore a suffix array without running the construction process again. You basically give it the String from SuffixArray.raw_array and the start from SuffixArray.suffix_start and it will skip most calculations. This feature is really experimental and is CPU dependent since the integers in the raw_array are native.



134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
# File 'ext/gdiff/suffix_array.c', line 134

static VALUE SuffixArray_initialize(int argc, VALUE *argv, VALUE self)
{
    SuffixArray *sa = NULL;
    size_t i = 0;
    Data_Get_Struct(self, SuffixArray, sa);
    assert(sa != NULL);
    VALUE source;
    VALUE array;
    VALUE start;
    
    // sort out the arguments and such
    rb_scan_args(argc, argv, "12", &source, &array, &start);

    // get the string value of the source given to us, keep it around for later
    VALUE sa_source_str = StringValue(source);
    rb_iv_set(self, "@source", sa_source_str);
    
    // setup temporary variables for the source and length pointers
    unsigned char *sa_source = (unsigned char *) RSTRING(sa_source_str)->ptr;
    size_t sa_source_len = RSTRING(sa_source_str)->len;
    
    // error check the whole thing
    if(sa_source_len == 0) {
        // we can't have this, so return a nil
        rb_raise(cSAError, ERR_NO_ZERO_LENGTH_INPUT);
    }
    
    if(!NIL_P(array) && NIL_P(start)) {
        rb_raise(cSAError, ERR_START_IF_ARRAY);
    } else if (!NIL_P(array) && !NIL_P(start)) {
        // looks like both parameters were given so check out the lengths
        if(RSTRING(array)->len / sizeof(int) != sa_source_len) {
            rb_raise(cSAError, ERR_MISMATCH_LENGTH);
        }
    }
        
    // allocate memory for the index integers
    sa->suffix_index = malloc(sizeof(int) * (sa_source_len + 1));
    
    if(NIL_P(array)) {
        // create the suffix array from the source
        int st = bsarray(sa_source, sa->suffix_index, sa_source_len-1);

        // set the suffix_start in our object
        rb_iv_set(self, "@suffix_start", INT2NUM(st));
    } else {
        // convert the given array and start to the internal structures needed
        // the return value is ignored since I can't seem find any consistent definition for
        // it's value that will tell me if this failed.
        memcpy(sa->suffix_index, RSTRING(array)->ptr, sa_source_len * sizeof(int));
        rb_iv_set(self, "@suffix_start", start);
    }
    
    unsigned char c = sa_source[sa->suffix_index[0]];  // start off with the first char in the sarray list
    sa->starts[c] = 0;
    for(i = 0; i < sa_source_len; i++) {
        // skip characters until we see a new one
        if(sa_source[sa->suffix_index[i]] != c) {
            sa->ends[c] = i-1; // it's -1 since this is a new character, so the end was actually behind this point
            c = sa_source[sa->suffix_index[i]];
            sa->starts[c] = i;
        }
    }
    // set the last valid character to get the tail of the sa, the loop will miss it
    c = sa_source[sa->suffix_index[sa_source_len-1]];
    sa->ends[c] = sa_source_len-1;
    
    return INT2FIX(sa_source_len);
}

Instance Method Details

#all_starts(character) ⇒ Array

Returns an array containing all the indexes into the source that start with the given character. This is a very fast operation since the SuffixArray already knows where each character starts and ends in the suffix array structure internally. All it does is copy the range of the suffix array for that region.

Returns:

  • (Array)


454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
# File 'ext/gdiff/suffix_array.c', line 454

static VALUE SuffixArray_all_starts(VALUE self, VALUE character)
{
    SuffixArray *sa = NULL;
    Data_Get_Struct(self, SuffixArray, sa);
    
    VALUE result = rb_ary_new();
    VALUE char_str = StringValue(character);
    
    // must be at least one length
    if(RSTRING(char_str)->len > 0) {
        size_t ch = (size_t)RSTRING(char_str)->ptr[0];

        // go through all the suffix array indices as indicated by sa->starts and sa->ends
        size_t start = 0;
    
        for(start = sa->starts[ch]; start <= sa->ends[ch]; start++) {
            rb_ary_push(result, INT2FIX(sa->suffix_index[start]));
        }
    }
    
    return result;
}

#arrayArray

Returns a copy of the internal suffix array as an Array of Fixnum objects. This array is a copy so you’re free to mangle it however you wish.

A suffix array is the sequence of indices into the source that mark each suffix as if they were sorted.

Returns:

  • (Array)


365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
# File 'ext/gdiff/suffix_array.c', line 365

static VALUE SuffixArray_array(VALUE self) 
{
    SuffixArray *sa = NULL;
    Data_Get_Struct(self, SuffixArray, sa);

    VALUE sa_source = SuffixArray_source(self);
    
    if(sa == NULL || sa->suffix_index == NULL || RSTRING(sa_source)->len == 0) {
        rb_raise(cSAError, ERR_NOT_INITIALIZED);
    }
    
    // get the length of the suffix index
    size_t source_len = RSTRING(sa_source)->len;
    size_t i = 0;
    
    VALUE result = rb_ary_new();
    
    for(i = 0; i < source_len; i++) {
        rb_ary_push(result, INT2FIX(sa->suffix_index[i]));
    }
    
    return result;
}

#longest_match(target, from_index) ⇒ Array

Takes a target string and an index inside that string, and then tries to find the longest match from that point in the source string for this SuffixArray object.

It returns an array of [start, length] of where in the source a length string from the target would match.

Refer to the unit test for examples of usage.

Returns:

  • (Array)


218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
# File 'ext/gdiff/suffix_array.c', line 218

static VALUE SuffixArray_longest_match(VALUE self, VALUE target, VALUE from_index) 
{
    SuffixArray *sa = NULL;
    Data_Get_Struct(self, SuffixArray, sa);

    VALUE sa_source = SuffixArray_source(self);
    
    if(sa == NULL || sa->suffix_index == NULL || RSTRING(sa_source)->len == 0) {
        rb_raise(cSAError, ERR_NOT_INITIALIZED);
    }
    
    // get the from and for_length arguments as unsigned ints
    size_t from = NUM2UINT(from_index);

    
    // get better pointers for the source (should already be in String form)
    unsigned char *source_ptr = (unsigned char *) RSTRING(sa_source)->ptr;
    size_t source_len = RSTRING(sa_source)->len;

    // get the target as a string
    VALUE target_str = StringValue(target);
    
    // better pointers again, we also need target_len as an in/out parameter
    unsigned char *target_ptr = (unsigned char *) RSTRING(target_str)->ptr;
    size_t target_len = RSTRING(target_str)->len;

    // check the input for validity, returning nil like in array operations
    if(from > target_len) {
        return Qnil;
    }
    
    // adjust for the from and for_length settings to be within the target len
    target_ptr += from;
    target_len -= from;
    
    size_t start = find_longest_match(source_ptr, source_len, target_ptr, &target_len, 
                                      sa->starts, sa->ends, sa->suffix_index);
    
    // create the 2 value return array
    VALUE result = rb_ary_new();
    
    rb_ary_push(result, INT2FIX(start));
    rb_ary_push(result, INT2FIX(target_len));
    
    return result;
}

#longest_nonmatch(target, from_index, min_match) ⇒ Array

Mostly the inverse of longest_match, except that it first tries to find a non-matching region, then a matching region. The target and from_index are the same as in longest_match. The min_match argument is the smallest matching region that you’ll accept as significant enough to end the non-matching search. Giving non_match=0 will stop at the first matching region.

It works by first searching the suffix array for a non-matching region. When it hits a character that is in the source (according to the suffix array) it tries to find a matching region. If it can find a matching region that is longer than min_match then it stops and returns, otherwise it adds this match to the length of the non-matching region and continues.

The return value is an Array of [non_match_length, match_start, match_length].

Returns:

  • (Array)


284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
# File 'ext/gdiff/suffix_array.c', line 284

static VALUE SuffixArray_longest_nonmatch(VALUE self, VALUE target, VALUE from_index, VALUE min_match) 
{
    SuffixArray *sa = NULL;
    Data_Get_Struct(self, SuffixArray, sa);

    VALUE sa_source = SuffixArray_source(self);
    
    if(sa == NULL || sa->suffix_index == NULL || RSTRING(sa_source)->len == 0) {
        rb_raise(cSAError, ERR_NOT_INITIALIZED);
    }
    
    // get the from and for_length arguments as unsigned ints
    size_t from = NUM2UINT(from_index);
    size_t min = NUM2INT(min_match);
    
    // get better pointers for the source (should already be in String form)
    unsigned char *source_ptr = (unsigned char *) RSTRING(sa_source)->ptr;
    size_t source_len = RSTRING(sa_source)->len;

    // get the target as a string
    VALUE target_str = StringValue(target);
    
    // better pointers again, we also need target_len as an in/out parameter
    unsigned char *target_ptr = (unsigned char *) RSTRING(target_str)->ptr;
    size_t target_len = RSTRING(target_str)->len;

    // check the input for validity, returning nil like in array operations
    if(from > target_len) {
        return Qnil;
    }
    
    
    // adjust for the from and for_length settings to be within the target len
    unsigned char *scan = target_ptr + from;
    unsigned char *end = target_ptr + target_len;
    size_t match_len = 0;
    size_t match_start = 0;
    while(scan < end) {
        if(*scan != source_ptr[sa->suffix_index[sa->starts[*scan]]]) {
            scan ++;
        } else {
            // search remaining stuff for a possible match, which return as a result as well
            match_len = end - scan;
            match_start = find_longest_match(source_ptr, source_len, scan, &match_len, 
                                              sa->starts, sa->ends, sa->suffix_index);
            
            if(match_len == 0) {
                // match not found, which really shouldn't happen
                break;
            } else if(match_len > min) {
                // the match is possibly long enough, drop out
                break;
            } else {
                // the number of possibly matching characters is much too small, so we continue by skipping them
                scan += match_len;
                // reset the match_len and match_start to 0 to signal that a match hasn't been found yet
                match_len = match_start = 0;
            }
        } 
    }

    VALUE result = rb_ary_new();
    
    size_t nonmatch_len = (scan - (target_ptr + from));
    rb_ary_push(result, INT2FIX(nonmatch_len));
    rb_ary_push(result, INT2FIX(match_start));
    rb_ary_push(result, INT2FIX(match_len));

    return result;
}

#raw_arrayString

Returns the “raw” internal suffix array which is an array of C int types used internally as the suffix array. The purpose of this function is to allow you to store the suffix_array and then very quickly restore it later without having to rebuild the suffix array.

The returned String should be treated as an opaque structure. It is just a copy of the int[] used internally. This means that it is dependent on your CPU. If you want something you can use that is cross platform then use the SuffixArray.array function instead.

Returns:

  • (String)


404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
# File 'ext/gdiff/suffix_array.c', line 404

static VALUE SuffixArray_raw_array(VALUE self) 
{
    SuffixArray *sa = NULL;
    Data_Get_Struct(self, SuffixArray, sa);

    VALUE sa_source = SuffixArray_source(self);
    
    if(sa == NULL || sa->suffix_index == NULL || RSTRING(sa_source)->len == 0) {
        rb_raise(cSAError, ERR_NOT_INITIALIZED);
    }
    
    // build a string that copies this stuff
    VALUE result = rb_str_new((const char *)sa->suffix_index, RSTRING(sa_source)->len * sizeof(int));

    return result;
}

#sourceString

Returns the source that this suffix array was constructed with.

Returns:

  • (String)


98
99
100
101
# File 'ext/gdiff/suffix_array.c', line 98

static VALUE SuffixArray_source(VALUE self)
{
    return rb_iv_get(self, "@source");
}

#startFixnum

Tells you which index in the suffix array is the longest suffix (also known as the start of the source string). If you want to get the beginning of the source string in a round about way you would do this:

source = “abracadabra” sa = SuffixArray.new source first = source[sa.array]]

Remember that the start is the index into the suffix array where the source starts, not an index into the source string (that would just be 0).

Returns:

  • (Fixnum)


436
437
438
439
# File 'ext/gdiff/suffix_array.c', line 436

static VALUE SuffixArray_suffix_start(VALUE self)
{
    return rb_iv_get(self, "@suffix_start");
}