Skip to content

Commit af2e271

Browse files
committed
GODRIVER-2119 implement methods required to use as a map key
1 parent 83fefd1 commit af2e271

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

bson/primitive/objectid.go

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,20 @@ func (id ObjectID) MarshalJSON() ([]byte, error) {
9999
return json.Marshal(id.Hex())
100100
}
101101

102+
// MarshalText returns the ObjectID as text
103+
// Implementing this allows us to use the ObjectID as a map key
104+
// when marshalling json.
105+
func (id ObjectID) MarshalText() ([]byte, error) {
106+
return []byte(id.Hex()), nil
107+
}
108+
109+
// UnmarshalText converts a text ObjectID into a byte string
110+
// Implementing this allows us to use the ObjectID as a map key
111+
// when marshalling json.
112+
func (id ObjectID) UnmarshalText(b []byte) error {
113+
return id.UnmarshalJSON(b)
114+
}
115+
102116
// UnmarshalJSON populates the byte slice with the ObjectID. If the byte slice is 24 bytes long, it
103117
// will be populated with the hex representation of the ObjectID. If the byte slice is twelve bytes
104118
// long, it will be populated with the BSON representation of the ObjectID. This method also accepts empty strings and

bson/primitive/objectid_test.go

Lines changed: 31 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -172,6 +172,37 @@ func TestCounterOverflow(t *testing.T) {
172172
require.Equal(t, uint32(0), objectIDCounter)
173173
}
174174

175+
func TestObjectID_MarshalJSONMap(t *testing.T) {
176+
type mapOID struct {
177+
Map map[ObjectID]string
178+
}
179+
180+
oid := NewObjectID()
181+
expectedJson := []byte(fmt.Sprintf(`{"Map":{%q:"foo"}}`, oid.Hex()))
182+
data := mapOID{
183+
Map: map[ObjectID]string{oid: "foo"},
184+
}
185+
186+
out, err := json.Marshal(&data)
187+
require.NoError(t, err)
188+
require.Equal(t, expectedJson, out)
189+
}
190+
191+
func TestObjectID_UnmarshalJSONMap(t *testing.T) {
192+
type mapOID struct {
193+
Map map[ObjectID]string
194+
}
195+
oid := NewObjectID()
196+
mapOIDJson := []byte(fmt.Sprintf(`{"Map":{%q:"foo"}}`, oid.Hex()))
197+
expectedData := mapOID{
198+
Map: map[ObjectID]string{oid: "foo"},
199+
}
200+
201+
data := mapOID{}
202+
err := json.Unmarshal(mapOIDJson, &data)
203+
require.NoError(t, err)
204+
require.Equal(t, expectedData, data)
205+
}
175206
func TestObjectID_UnmarshalJSON(t *testing.T) {
176207
oid := NewObjectID()
177208

0 commit comments

Comments
 (0)