lib: adds String::to_f
authorAlexis Laferrière <alexis.laf@xymus.net>
Wed, 14 Mar 2012 15:07:12 +0000 (11:07 -0400)
committerAlexis Laferrière <alexis.laf@xymus.net>
Thu, 12 Apr 2012 19:38:17 +0000 (15:38 -0400)
Signed-off-by: Alexis Laferrière <alexis.laf@xymus.net>

lib/standard/string.nit
lib/standard/string_nit.c [new file with mode: 0644]
lib/standard/string_nit.h
tests/sav/test_string_to_f.sav [new file with mode: 0644]
tests/test_string_to_f.nit [new file with mode: 0644]

index 6089102..966e7a4 100644 (file)
@@ -264,6 +264,8 @@ class String
                return h
 
        end
+
+       fun to_f : Float is extern import String::to_cstring
 end
 
 # Strings are arrays of characters.
diff --git a/lib/standard/string_nit.c b/lib/standard/string_nit.c
new file mode 100644 (file)
index 0000000..d29de0c
--- /dev/null
@@ -0,0 +1,39 @@
+/* This file is part of NIT ( http://www.nitlanguage.org ).
+ *
+ * Copyright 2012 Alexis Laferrière <alexis.laf@xymus.net>
+ *
+ * This file is free software, which comes along with NIT.  This software is
+ * distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
+ * without  even  the implied warranty of  MERCHANTABILITY or  FITNESS FOR A
+ * PARTICULAR PURPOSE.  You can modify it is you want,  provided this header
+ * is kept unaltered, and a notification of the changes is added.
+ * You  are  allowed  to  redistribute it and sell it, alone or is a part of
+ * another product.
+ */
+
+#include "string_nit.h"
+
+/*
+C implementation of string::String::to_f
+
+Imported methods signatures:
+       char * String_to_cstring( String recv ) for string::String::to_cstring
+*/
+float String_to_f___impl( String recv )
+{
+    float value;
+    char *str;
+    int read;
+
+    str = String_to_cstring( recv );
+
+    read = sscanf( str, "%f", &value );
+
+    if ( read <= 0 )
+    {
+        fprintf( stderr, "Failed to convert string \"\" to float." );
+        abort();
+    }
+
+    return value;
+}
index d451800..97e656f 100644 (file)
@@ -17,5 +17,6 @@
 
 #define kernel_Sys_Sys_native_argc_0(self) (glob_argc)
 #define kernel_Sys_Sys_native_argv_1(self, p0) (glob_argv[(p0)])
+float String_to_f___impl( String recv );
 
 #endif
diff --git a/tests/sav/test_string_to_f.sav b/tests/sav/test_string_to_f.sav
new file mode 100644 (file)
index 0000000..9c80447
--- /dev/null
@@ -0,0 +1,3 @@
+0.123450
+1234.0
+0.989898
diff --git a/tests/test_string_to_f.nit b/tests/test_string_to_f.nit
new file mode 100644 (file)
index 0000000..61941fc
--- /dev/null
@@ -0,0 +1,4 @@
+print "0.12345".to_f
+print "1234".to_f
+print "0.989898".to_f
+