Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse files

[enhance] v0.4.x compatibility

  • Loading branch information...
commit 654d7bedb5665ce8e358b0f4aeb46467290801f1 1 parent 3eef881
@marcello3d authored
Showing with 35 additions and 2 deletions.
  1. +1 −0  .travis.yml
  2. +34 −2 lib/objectid.js
View
1  .travis.yml
@@ -1,3 +1,4 @@
language: node_js
node_js:
+ - 0.4
- 0.6
View
36 lib/objectid.js
@@ -36,7 +36,7 @@ function ObjectId(bytes) {
} else if (typeof bytes == 'string') {
if (bytes.length != 24) throw new Error("String-based ObjectId must be 24 bytes")
if (!/^[0-9a-f]{24}$/i.test(bytes)) throw new Error("String-based ObjectId must in hex-format:" + bytes)
- this.bytes = new Buffer(bytes, 'hex')
+ this.bytes = fromHex(bytes)
} else if (typeof bytes !== 'undefined') {
throw new Error("Unrecognized type: "+bytes)
} else {
@@ -59,5 +59,37 @@ function ObjectId(bytes) {
}
}
ObjectId.prototype.toString = function() {
- return this.bytes.toString('hex')
+ return toHex(this.bytes)
}
+
+var toHex = function(buffer) {
+ return buffer.toString('hex')
+}
+
+var fromHex = function(string) {
+ return new Buffer(string, 'hex')
+}
+
+// This is how we support 0.4.x. Pretty grody, huh?
+try {
+ if (toHex(new Buffer([0x90])) !='90') throw '0.4.x'
+} catch (e) {
+ toHex = function(buffer) {
+ var s = ''
+ for (var i=0; i<buffer.length; i++) {
+ s += buffer[i] > 16 ? buffer[i].toString(16) : '0' + buffer[i].toString(16)
+ }
+ return s
+ }
+}
+try {
+ if (fromHex('90')[0] != 0x90) throw '0.4.x'
+} catch (e) {
+ fromHex = function(string) {
+ var buffer = new Buffer(string.length/2)
+ for (var i=0; i<string.length; i+=2) {
+ buffer[i/2] = parseInt(string.substring(i,i+2),16)
+ }
+ return buffer
+ }
+}
Please sign in to comment.
Something went wrong with that request. Please try again.