Commit 1eb5044f authored by Rico Tzschichholz's avatar Rico Tzschichholz

glib-2.0: Add optional 'unparsed' parameter to *.try_parse ()

This reintroduces a dropped feature of string.to_*() while returning the
maybe available unparsed part of the string.

https://bugzilla.gnome.org/show_bug.cgi?id=774124
parent 78a92305
......@@ -45,6 +45,11 @@ void test_double () {
string s = d.to_string ();
assert (s == "42");
unowned string unparsed;
double.try_parse ("3.45mm", out d, out unparsed);
assert (d == 3.45);
assert (unparsed == "mm");
// ensure that MIN and MAX are valid values
d = double.MIN;
assert (d == double.MIN);
......
......@@ -70,6 +70,20 @@ void test_int () {
string s = i.to_string ();
assert (s == "42");
unowned string unparsed;
int64 i64;
int64.try_parse ("-4711inch", out i64, out unparsed);
assert (i64 == -4711);
assert (unparsed == "inch");
int64.try_parse ("-31415km", out i64);
assert (i64 == -31415);
uint64 ui64;
uint64.try_parse ("4711yards", out ui64, out unparsed);
assert (ui64 == 4711);
assert (unparsed == "yards");
uint64.try_parse ("31415yards", out ui64);
assert (ui64 == 31415);
// ensure that MIN and MAX are valid values
i = int.MIN;
assert (i == int.MIN);
......
......@@ -689,12 +689,14 @@ public struct int64 {
}
[Version (since = "2.12")]
public static bool try_parse (string str, out int64 result = null) {
public static bool try_parse (string str, out int64 result = null, out unowned string unparsed = null) {
char* endptr;
result = ascii_strtoll (str, out endptr, 0);
if (endptr == (char*) str + str.length) {
unparsed = "";
return true;
} else {
unparsed = (string) endptr;
return false;
}
}
......@@ -745,12 +747,14 @@ public struct uint64 {
public static uint64 parse (string str) {
return ascii_strtoull (str, null, 0);
}
public static bool try_parse (string str, out uint64 result = null) {
public static bool try_parse (string str, out uint64 result = null, out unowned string unparsed = null) {
char* endptr;
result = ascii_strtoull (str, out endptr, 0);
if (endptr == (char*) str + str.length) {
unparsed = "";
return true;
} else {
unparsed = (string) endptr;
return false;
}
}
......@@ -885,12 +889,14 @@ public struct double {
public static double parse (string str) {
return ascii_strtod (str, null);
}
public static bool try_parse (string str, out double result = null) {
public static bool try_parse (string str, out double result = null, out unowned string unparsed = null) {
char* endptr;
result = ascii_strtod (str, out endptr);
if (endptr == (char*) str + str.length) {
unparsed = "";
return true;
} else {
unparsed = (string) endptr;
return false;
}
}
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment