Skip to content
Browse files

NSData serialization and deserialization of object ids.

  • Loading branch information...
1 parent 16a04dd commit a7df85619990be3f5a947be31d143b3deb17638c Tim Burks committed Dec 8, 2010
Showing with 35 additions and 1 deletion.
  1. +6 −0 objc/NuBSON.h
  2. +20 −0 objc/NuBSON.m
  3. +9 −1 test/test_bson.nu
View
6 objc/NuBSON.h
@@ -71,10 +71,16 @@ limitations under the License.
/*! Create a new and unique object ID. */
+ (NuBSONObjectID *) objectID;
+/*! Create an object ID from a 12-byte data representation */
++ (NuBSONObjectID *) objectIDWithData:(NSData *) data;
/*! Create an object ID from a hex string. */
- (id) initWithString:(NSString *) s;
/*! Get the hex string value of an object ID. */
- (NSString *) stringValue;
+/*! Create an object ID from an NSData representation. */
+- (id) initWithData:(NSData *) data;
+/*! Get the NSData representation of an object ID. */
+- (NSData *) dataRepresentation;
/*! Compare two object ID values. */
- (NSComparisonResult)compare:(NuBSONObjectID *) other;
/*! Test for equality with another object ID. */
View
20 objc/NuBSON.m
@@ -129,6 +129,11 @@ + (NuBSONObjectID *) objectID
return [[[NuBSONObjectID alloc] initWithObjectIDPointer:&oid] autorelease];
}
++ (NuBSONObjectID *) objectIDWithData:(NSData *) data
+{
+ return [[[NuBSONObjectID alloc] initWithData:data] autorelease];
+}
+
- (id) initWithString:(NSString *) s
{
if (self = [super init]) {
@@ -147,6 +152,21 @@ - (id) initWithObjectIDPointer:(const bson_oid_t *) objectIDPointer
- (const bson_oid_t *) objectIDPointer {return &oid;}
+- (id) initWithData:(NSData *) data
+{
+ if (self = [super init]) {
+ if ([data length] == 12) {
+ memcpy(oid.bytes, [data bytes], 12);
+ }
+ }
+ return self;
+}
+
+- (NSData *) dataRepresentation
+{
+ return [[[NSData alloc] initWithBytes:oid.bytes length:12] autorelease];
+}
+
- (NSString *) description
{
char buffer[25]; /* str must be at least 24 hex chars + null byte */
View
10 test/test_bson.nu
@@ -42,4 +42,12 @@
;; expand this one since (z f:) is a bson object
(assert_equal ((y f:) a:) ((z f:) a:))
(assert_equal (y g:) (z g:))
- (assert_equal (y h:) (z h:))))
+ (assert_equal (y h:) (z h:)))
+
+ (- testOIDs is
+ (10 times:
+ (do (i)
+ (set id ((NuBSONObjectID objectID)))
+ (set id2 ((NuBSONObjectID alloc)
+ initWithData:(id dataRepresentation)))
+ (assert_equal id id2)))))

0 comments on commit a7df856

Please sign in to comment.
Something went wrong with that request. Please try again.