Skip to content

Commit 476bc7b

Browse files
committed
Create AsFloat64 functions
1 parent 09782c0 commit 476bc7b

File tree

1 file changed

+58
-6
lines changed

1 file changed

+58
-6
lines changed

x/bsonx/bsoncore/value.go

Lines changed: 58 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -188,15 +188,67 @@ func (v Value) AsInt64OK() (int64, bool) {
188188

189189
// AsFloat64 returns a BSON number as an float64. If the BSON type is not a numeric one, this method
190190
// will panic.
191-
//
192-
// TODO(GODRIVER-2751): Implement AsFloat64.
193-
// func (v Value) AsFloat64() float64
191+
func (v Value) AsFloat64() float64 {
192+
if !v.IsNumber() {
193+
return 0
194+
}
195+
var f64 float64
196+
switch v.Type {
197+
case TypeDouble:
198+
var ok bool
199+
f64, _, ok = ReadDouble(v.Data)
200+
if !ok {
201+
panic(NewInsufficientBytesError(v.Data, v.Data))
202+
}
203+
case TypeInt32:
204+
i32, _, ok := ReadInt32(v.Data)
205+
if !ok {
206+
panic(NewInsufficientBytesError(v.Data, v.Data))
207+
}
208+
f64 = float64(i32)
209+
case TypeInt64:
210+
i64, _, ok := ReadInt64(v.Data)
211+
if !ok {
212+
panic(NewInsufficientBytesError(v.Data, v.Data))
213+
}
214+
f64 = float64(i64)
215+
case TypeDecimal128:
216+
panic(ElementTypeError{"bsoncore.Value.AsFloat64", v.Type})
217+
}
218+
return f64
219+
}
194220

195221
// AsFloat64OK functions the same as AsFloat64 but returns a boolean instead of panicking. False
196222
// indicates an error.
197-
//
198-
// TODO(GODRIVER-2751): Implement AsFloat64OK.
199-
// func (v Value) AsFloat64OK() (float64, bool)
223+
func (v Value) AsFloat64OK() (float64, bool) {
224+
if !v.IsNumber() {
225+
return 0, false
226+
}
227+
var f64 float64
228+
switch v.Type {
229+
case TypeDouble:
230+
var ok bool
231+
f64, _, ok = ReadDouble(v.Data)
232+
if !ok {
233+
return 0, false
234+
}
235+
case TypeInt32:
236+
i32, _, ok := ReadInt32(v.Data)
237+
if !ok {
238+
return 0, false
239+
}
240+
f64 = float64(i32)
241+
case TypeInt64:
242+
i64, _, ok := ReadInt64(v.Data)
243+
if !ok {
244+
return 0, false
245+
}
246+
f64 = float64(i64)
247+
case TypeDecimal128:
248+
return 0, false
249+
}
250+
return f64, true
251+
}
200252

201253
// Equal compaes v to v2 and returns true if they are equal.
202254
func (v Value) Equal(v2 Value) bool {

0 commit comments

Comments
 (0)