ext/calc/calc.c in calc-nik-0.0.4 vs ext/calc/calc.c in calc-nik-0.0.5
- old
+ new
@@ -1,19 +1,117 @@
#include <ruby.h>
-/* our new native method; it just returns
- * the string "bonjour!" */
-static VALUE calc_bonjour(VALUE self) {
- return rb_str_new2("bonjour!");
+int is_palindrome(char*);
+void copy_string(char*, char*);
+void reverse_string(char*);
+int string_length(char*);
+int compare_string(char*, char*);
+
+static VALUE palindrom(VALUE self, VALUE string_raw)
+{
+ char *string = StringValuePtr(string_raw);
+ int result;
+
+ result = is_palindrome(string);
+
+ if ( result == 1 )
+ return Qtrue;
+ else
+ return Qfalse;
}
+
+int is_palindrome(char *string)
+{
+ int check, length;
+ char *reverse;
+
+ length = string_length(string);
+ reverse = (char*)malloc(length+1);
+
+ copy_string(reverse, string);
+ reverse_string(reverse);
+
+ check = compare_string(string, reverse);
+
+ free(reverse);
+
+ if ( check == 0 )
+ return 1;
+ else
+ return 0;
+}
+
+int string_length(char *string)
+{
+ int length = 0;
+
+ while(*string)
+ {
+ length++;
+ string++;
+ }
+
+ return length;
+}
+
+void copy_string(char *target, char *source)
+{
+ while(*source)
+ {
+ *target = *source;
+ source++;
+ target++;
+ }
+ *target = '\0';
+}
+
+void reverse_string(char *string)
+{
+ int length, c;
+ char *begin, *end, temp;
+
+ length = string_length(string);
+
+ begin = string;
+ end = string;
+
+ for ( c = 0 ; c < ( length - 1 ) ; c++ )
+ end++;
+
+ for ( c = 0 ; c < length/2 ; c++ )
+ {
+ temp = *end;
+ *end = *begin;
+ *begin = temp;
+
+ begin++;
+ end--;
+ }
+}
+
+int compare_string(char *first, char *second)
+{
+ while(*first==*second)
+ {
+ if ( *first == '\0' || *second == '\0' )
+ break;
+
+ first++;
+ second++;
+ }
+ if( *first == '\0' && *second == '\0' )
+ return 0;
+ else
+ return -1;
+}
/* ruby calls this to load the extension */
void Init_calc(void) {
/* assume we haven't yet defined Hola */
VALUE klass = rb_define_class("Calc_c",
rb_cObject);
- /* the hola_bonjour function can be called
- * from ruby as "Hola.bonjour" */
+ /* the palindrom function can be called
+ * from ruby as "Calc_c.palindrom?" */
rb_define_singleton_method(klass,
- "bonjour", calc_bonjour, 0);
+ "palindrom?", palindrom, 1);
}
\ No newline at end of file