candu / node-int64-native

A simple uint64_t wrapper for node.js.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

missing constructor with decimal string argument

jkryl opened this issue · comments

Currently it's possible to create int64 object by supplying a string of hexadecimal representation of a number. But how to construct int64 based on its decimal representation? I haven't found any easy way to do that (assuming that the input number is too big so it doesn't fit to int32 and cannot be converted to JS number as an intermediate step).

The constructor for int64 should be enhanced to recognize number prefixes, which denote number's base (hexadecimal = 0x, decimal without prefix). I have a simple patch which does it:

@@ -99,18 +108,30 @@
 Int64::Int64(const Local<String>& s) {
   String::Utf8Value utf8(s);
   mValue = 0ull;
-  for (int i = 0; i < utf8.length(); i++) {
-    mValue <<= 4;
-    char c = (*utf8)[i];
-    if (c >= '0' && c <= '9') {
-      mValue += (c - '0');
-    } else if (c >= 'a' && c <= 'f') {
-      mValue += 10 + (c - 'a');
-    } else if (c >= 'A' && c <= 'F') {
-      mValue += 10 + (c - 'A');
-    } else {
-      ThrowException(Exception::TypeError(String::New("Invalid string")));
+  if (utf8.length() > 2 && (*utf8)[0] == '0' && (*utf8)[1] == 'x') {
+    for (int i = 2; i < utf8.length(); i++) {
+      mValue <<= 4;
+      char c = (*utf8)[i];
+      if (c >= '0' && c <= '9') {
+        mValue += (c - '0');
+      } else if (c >= 'a' && c <= 'f') {
+        mValue += 10 + (c - 'a');
+      } else if (c >= 'A' && c <= 'F') {
+        mValue += 10 + (c - 'A');
+      } else {
+        ThrowException(Exception::TypeError(String::New("Invalid string")));
+      }
     }
+  } else {
+    for (int i = 0; i < utf8.length(); i++) {
+      mValue *= 10;
+      char c = (*utf8)[i];
+      if (c >= '0' && c <= '9') {
+        mValue += (c - '0');
+      } else {
+        ThrowException(Exception::TypeError(String::New("Invalid string")));
+      }
+    }
   }
 }

Unfortunately it constitutes a backward incompatible change and it would require major version number bump. I can submit a pull request if people are ok with the fix.

Thanks for the feature request!

Just published version 0.3.1, which provides support for constructing Int64 instances via either decimal or hex numeric strings - the implementation is in this commit:

c7b847c

Added a few tests for this as well. Let me know if you run into any issues.

That was blazing fast response. Many thanks for implementing the feature!