aboutsummaryrefslogtreecommitdiff
path: root/xmpp-vala/src/util.vala
diff options
context:
space:
mode:
authorhrxi <hrrrxi@gmail.com>2019-09-01 18:18:25 +0200
committerfiaxh <fiaxh@users.noreply.github.com>2019-09-10 19:36:11 +0200
commitd5d305193ce527f1cc3022c406de35d9a85d4ccb (patch)
treed12efc741319a7d71c13f7bf6c2c7579d25fdabe /xmpp-vala/src/util.vala
parent9950742bf1903291c271619aea101b0e2f81d19c (diff)
downloaddino-d5d305193ce527f1cc3022c406de35d9a85d4ccb.tar.gz
dino-d5d305193ce527f1cc3022c406de35d9a85d4ccb.zip
Fix some warnings
Instances of `RegexError` are just asserted as `assert_not_reached` as they cannot really fail except for allocation failure if the given regex is valid.
Diffstat (limited to 'xmpp-vala/src/util.vala')
-rw-r--r--xmpp-vala/src/util.vala50
1 files changed, 50 insertions, 0 deletions
diff --git a/xmpp-vala/src/util.vala b/xmpp-vala/src/util.vala
new file mode 100644
index 00000000..34a05b7a
--- /dev/null
+++ b/xmpp-vala/src/util.vala
@@ -0,0 +1,50 @@
+namespace Xmpp.Util {
+
+// Parse a number from a hexadecimal representation.
+//
+// Skips any whitespace at the start of the string, parses as many valid
+// characters as hexadecimal digits as possible (possibly zero) and returns
+// them as an integer value.
+//
+// ```
+// // 0x0
+// print("0x%lx\n", from_hex(""));
+//
+// // 0x123abc
+// print("0x%lx\n", from_hex("123abc"));
+//
+// // 0x0
+// print("0x%lx\n", from_hex("0x123abc"));
+//
+// // 0xa
+// print("0x%lx\n", from_hex("A quick brown fox jumps over the lazy dog."));
+//
+// // 0xfeed
+// print("0x%lx\n", from_hex(" FEED ME "));
+// ```
+
+public long from_hex(string numeral) {
+ long result = 0;
+ bool skipping_whitespace = true;
+ foreach (uint8 byte in numeral.data) {
+ char c = (char)byte;
+ if (skipping_whitespace && c.isspace()) {
+ continue;
+ }
+ skipping_whitespace = false;
+ int digit;
+ if ('0' <= c && c <= '9') {
+ digit = c - '0';
+ } else if ('A' <= c && c <= 'F') {
+ digit = c - 'A' + 10;
+ } else if ('a' <= c && c <= 'f') {
+ digit = c - 'a' + 10;
+ } else {
+ break;
+ }
+ result = (result << 4) | digit;
+ }
+ return result;
+}
+
+}