aboutsummaryrefslogtreecommitdiffstats
path: root/indexinglanguage/src/main/java/com/yahoo/vespa/indexinglanguage/expressions/ToBoolExpression.java
blob: 18ac6bb1013d8165d2cab6bb4ad2cc6ad9483f74 (plain) (blame)
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
// Copyright Yahoo. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.vespa.indexinglanguage.expressions;

import com.yahoo.document.DataType;
import com.yahoo.document.datatypes.BoolFieldValue;
import com.yahoo.document.datatypes.FieldValue;
import com.yahoo.document.datatypes.NumericFieldValue;
import com.yahoo.document.datatypes.StringFieldValue;

/**
 * @author bratseth
 */
public final class ToBoolExpression extends Expression {

    public ToBoolExpression() {
        super(UnresolvedDataType.INSTANCE);
    }

    @Override
    protected void doExecute(ExecutionContext context) {
        context.setValue(new BoolFieldValue(toBooleanValue(context.getValue())));
    }

    private boolean toBooleanValue(FieldValue value) {
        if (value instanceof NumericFieldValue)
            return ((NumericFieldValue)value).getNumber().intValue() != 0;
        if (value instanceof StringFieldValue)
            return ! ((StringFieldValue)value).getString().isEmpty();
        return false;
    }

    @Override
    protected void doVerify(VerificationContext context) {
        context.setValueType(createdOutputType());
    }

    @Override
    public DataType createdOutputType() {
        return DataType.BOOL;
    }

    @Override
    public String toString() {
        return "to_bool";
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof ToBoolExpression;
    }

    @Override
    public int hashCode() {
        return getClass().hashCode();
    }

}