Re: [Vala] string.to_long vs long.parse





----- Original Message -----
From: Andy Lees <andrewl oz gmail com>
Sent: Thursday, 11 February 2016, 4:58
Subject: [Vala] string.to_long vs long.parse

I note that string.to_long is deprecated, but that the replacement
long.parse has reduced functionality.  Using to_long, I can have
hexadecimal, octal and binary number strings accepted, whilst long.parse
doesn't allow for this.

This does seem rather a backward step.  Was there some reason for not
accepting different standardised number representations?


I think the binding should be changed from using atol() to strtol()
For a good write up on strtol() see:
https://blog.mozilla.org/nnethercote/2009/03/13/atol-considered-harmful/

As a first attempt apply:
diff --git a/vapi/glib-2.0.vapi b/vapi/glib-2.0.vapi
index b240b6b..96703ac 100644
--- a/vapi/glib-2.0.vapi
+++ b/vapi/glib-2.0.vapi
@@ -259,8 +259,8 @@ public struct long {
[CCode (cname = "GLONG_FROM_LE")]
public static long from_little_endian (long val);

-       [CCode (cname = "atol", cheader_filename = "stdlib.h")]
-       public static long parse (string str);
+       [CCode (cname = "strtol", cheader_filename = "stdlib.h")]
+       public static long parse (string str, [CCode (pos = 3)] int base = 0, [CCode (pos = 2)] char? endptr 
= null);
}


This will now allow you to use both hex and octal representations as
well, e.g. long.parse( "0x1a" ); 

You can also specify the number base, e.g. long.parse( "1a", 16 )


There are two problems with this binding though.

Firstly, I don't know how to correctly bind the endptr, but a default of null
is fine for the current behaviour of long.parse in Vala.

Secondly, this binding changes the current behaviour of long.parse, if the
current behaviour should be kept then the default base needs to be 10.

So currently long.parse( "0x1a" ) gives 0 as the result, that is the
zero before the x. The new binding will give 26 in base 10.

By using the current behaviour in the new binding you would always have
to add a parameter for the base, e.g. long.parse( "0x1a", 0 ). I think
using 0 as the default base is the more convenient binding if it was
new, but it does break backwards compatibility.

I hope that gets the discussion started,

Al


[Date Prev][Date Next]   [Thread Prev][Thread Next]   [Thread Index] [Date Index] [Author Index]