forked from pingcap/tidb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
eval_bit_ops.go
81 lines (75 loc) · 2.34 KB
/
eval_bit_ops.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
// Copyright 2016 PingCAP, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// See the License for the specific language governing permissions and
// limitations under the License.
package xeval
import (
"github.com/juju/errors"
"github.com/pingcap/tidb/sessionctx/variable"
"github.com/pingcap/tidb/util/types"
"github.com/pingcap/tipb/go-tipb"
)
func (e *Evaluator) evalBitOps(expr *tipb.Expr) (types.Datum, error) {
var result types.Datum
if expr.GetTp() == tipb.ExprType_BitNeg {
if len(expr.Children) != 1 {
err := ErrInvalid.Gen("BitNeg(~) need 1 operand but got %d", len(expr.Children))
return result, err
}
operand, err := e.Eval(expr.Children[0])
if err != nil {
return types.Datum{}, errors.Trace(err)
}
a, err := types.CoerceArithmetic(e.StatementCtx, operand)
if err != nil {
return result, errors.Trace(err)
}
return types.ComputeBitNeg(e.StatementCtx, a)
}
left, right, err := e.evalTwoChildren(expr)
if err != nil {
return result, errors.Trace(err)
}
return ComputeBit(e.StatementCtx, expr.GetTp(), left, right)
}
// ComputeBit computes the bitwise operation on two datums.
func ComputeBit(sc *variable.StatementContext, op tipb.ExprType, left, right types.Datum) (types.Datum, error) {
var result types.Datum
a, err := types.CoerceArithmetic(sc, left)
if err != nil {
return result, errors.Trace(err)
}
b, err := types.CoerceArithmetic(sc, right)
if err != nil {
return result, errors.Trace(err)
}
a, b, err = types.CoerceDatum(sc, a, b)
if err != nil {
return result, errors.Trace(err)
}
if a.IsNull() || b.IsNull() {
return result, nil
}
switch op {
case tipb.ExprType_BitAnd:
return types.ComputeBitAnd(sc, a, b)
case tipb.ExprType_BitOr:
return types.ComputeBitOr(sc, a, b)
case tipb.ExprType_BitXor:
return types.ComputeBitXor(sc, a, b)
case tipb.ExprType_LeftShift:
return types.ComputeLeftShift(sc, a, b)
case tipb.ExprType_RighShift:
return types.ComputeRightShift(sc, a, b)
default:
return result, errors.Errorf("Unknown binop type: %v", op)
}
}