[GODRIVER-801] Add ObjectID methods to convert from and to `[]byte` Created: 01/Feb/19  Updated: 27/Oct/23  Resolved: 01/Feb/19

Status: Closed
Project: Go Driver
Component/s: BSON
Affects Version/s: None
Fix Version/s: None

Type: New Feature Priority: Trivial - P5
Reporter: Alexander Assignee: Kristofer Brandow (Inactive)
Resolution: Works as Designed Votes: 0
Labels: None
Remaining Estimate: Not Specified
Time Spent: Not Specified
Original Estimate: Not Specified


 Description   

By analog with `Hex() string` and `ObjectIDFromHex(s string) (ObjectID, error)` methods it will be handy to have methods like `Bytes() []byte` and `ObjectIDFromBytes(b []bytes) (ObjectID, error)`.



 Comments   
Comment by Kristofer Brandow (Inactive) [ 01/Feb/19 ]

No problem! Glad I could help.

Comment by Alexander [ 01/Feb/19 ]

Yes, you're right. Thanks for explain.

Comment by Kristofer Brandow (Inactive) [ 01/Feb/19 ]

If we did that, we'd need to return an error so the amount of code would be the same:

buf, err := oid.Bytes()
if err != nil {
    return err
}

if len(buf) < 12 {
   return errors.New("Not enough bytes in buf")
}
copy(oid[:], buf)

Comment by Alexander [ 01/Feb/19 ]

Ok, I agree. But what you think about checking buf length like it done in ObjectIDFromHex?

if len(b) != 12 {
   return NilObjectID, ErrInvalidHex
}

Comment by Kristofer Brandow (Inactive) [ 01/Feb/19 ]

Hi turboezh,

Since an ObjectID is [12]byte converting to a slice of bytes is supported by the language:

var oid primitive.ObjectID
var buf []byte
buf = oid[:]

 

 

Conversely, converting a slice of bytes to an ObjectID is similar:

 

var oid primitive.ObjectID
var buf []byte
copy(oid[:], buf)

 

Since these are single line solutions using built in language constructs, we shouldn't need helpers.

Let me know if this helps.

--Kris

Generated at Thu Feb 08 08:35:00 UTC 2024 using Jira 9.7.1#970001-sha1:2222b88b221c4928ef0de3161136cc90c8356a66.