Class: Kmp::String

Inherits:
Object
  • Object
show all
Defined in:
lib/kmp/string.rb,
ext/kmp/kmp_string.c

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(rb_string) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'ext/kmp/kmp_string.c', line 23

static VALUE initialize(VALUE self, VALUE rb_string)
{
    struct Str * str;

    Check_Type(rb_string, T_STRING);
    Data_Get_Struct(self, struct Str, str);

    str->ptr = calloc(RSTRING_LEN(rb_string) + 1 , sizeof(char));
    memcpy(str->ptr, StringValuePtr(rb_string), RSTRING_LEN(rb_string));

    rb_iv_set(self, "@str", rb_string);
    rb_iv_set(self, "@length", INT2NUM(RSTRING_LEN(rb_string)));

    return self;
}

Instance Attribute Details

#lengthObject (readonly)

#strObject (readonly)

Instance Method Details

#inspectObject



3
4
5
# File 'lib/kmp/string.rb', line 3

def inspect
  str
end

#match(rb_str) ⇒ Object



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'ext/kmp/kmp_string.c', line 57

static VALUE match(VALUE self, VALUE rb_str)
{
    VALUE positions = rb_ary_new();
    struct Str * obj;
    char * str;
    char * ptrn;
    int * prefix;
    int n,m,q;

    Data_Get_Struct(self, struct Str, obj);
    str = calloc(strlen(obj->ptr) + 1, sizeof(char));
    strcpy(str, obj->ptr);

    ptrn = (char *) calloc(RSTRING_LEN(rb_str) + 1, sizeof(char));
    memcpy(ptrn, StringValuePtr(rb_str), RSTRING_LEN(rb_str));

    prefix = compute_prefix(ptrn);

    n = strlen(str);
    m = strlen(ptrn);

    q = -1;
    for(int i=0; i<n; i++)
    {
        while( q>-1 && ptrn[q+1]!=str[i] ) q = prefix[q];
        if( ptrn[q+1]==str[i] ) q = q+1;
        if( q==m-1 )
        {
            rb_ary_push(positions, INT2NUM(i-m+1));
            q = prefix[q];
        }
    }
    free(prefix);
    free(ptrn);
    free(str);

    return positions;
}