From 18d6fa71c92042bb2c8101c538b1b426180955a6 Mon Sep 17 00:00:00 2001 From: Matthew Nibecker Date: Mon, 23 Dec 2024 10:25:09 -0800 Subject: [PATCH] vam: Add floor func --- runtime/vam/expr/function/function.go | 2 ++ runtime/vam/expr/function/math.go | 36 +++++++++++++++++++++++++ runtime/ztests/expr/function/floor.yaml | 19 +++++++++++++ 3 files changed, 57 insertions(+) create mode 100644 runtime/ztests/expr/function/floor.yaml diff --git a/runtime/vam/expr/function/function.go b/runtime/vam/expr/function/function.go index df5d53c7e7..7c02232563 100644 --- a/runtime/vam/expr/function/function.go +++ b/runtime/vam/expr/function/function.go @@ -36,6 +36,8 @@ func New(zctx *super.Context, name string, narg int) (expr.Function, field.Path, f = &Error{zctx} case "fields": f = NewFields(zctx) + case "floor": + f = &Floor{zctx} case "grep": argmax = 2 f = &Grep{zctx: zctx} diff --git a/runtime/vam/expr/function/math.go b/runtime/vam/expr/function/math.go index a33b3d94ff..54046c6ad1 100644 --- a/runtime/vam/expr/function/math.go +++ b/runtime/vam/expr/function/math.go @@ -96,3 +96,39 @@ func (c *Ceil) ceil(vec vector.Any) vector.Any { panic(vec) } } + +// https://github.com/brimdata/super/blob/main/docs/language/functions.md#floor +type Floor struct { + zctx *super.Context +} + +func (f *Floor) Call(args ...vector.Any) vector.Any { + vec := vector.Under(args[0]) + switch id := vec.Type().ID(); { + case super.IsFloat(id): + return f.floor(vec) + case super.IsUnsigned(id) || super.IsSigned(id): + return vec + } + return vector.NewWrappedError(f.zctx, "floor: not a number", vec) +} + +func (f *Floor) floor(vec vector.Any) vector.Any { + switch vec := vec.(type) { + case *vector.Const: + val := super.NewFloat(vec.Type(), math.Floor(vec.Value().Float())) + return vector.NewConst(val, vec.Len(), vec.Nulls) + case *vector.View: + return vector.NewView(f.floor(vec.Any), vec.Index) + case *vector.Dict: + return vector.NewDict(f.floor(vec.Any), vec.Index, vec.Counts, vec.Nulls) + case *vector.Float: + var floats []float64 + for _, v := range vec.Values { + floats = append(floats, math.Floor(v)) + } + return vector.NewFloat(vec.Type(), floats, vec.Nulls) + default: + panic(vec) + } +} diff --git a/runtime/ztests/expr/function/floor.yaml b/runtime/ztests/expr/function/floor.yaml new file mode 100644 index 0000000000..0c2a7365be --- /dev/null +++ b/runtime/ztests/expr/function/floor.yaml @@ -0,0 +1,19 @@ +zed: floor(this) + +vector: true + +input: | + 1.5 + 1.7 + -1.5 + 1(uint8) + 1.5(float32) + "foo" + +output: | + 1. + 1. + -2. + 1(uint8) + 1.(float32) + error({message:"floor: not a number",on:"foo"})