Add yang-xpath-api
[yangtools.git] / yang / yang-xpath-api / src / main / java / org / opendaylight / yangtools / yang / xpath / api / YangBooleanConstantExpr.java
1 /*
2  * Copyright (c) 2018 Pantheon Technologies, s.r.o.  All rights reserved.
3  *
4  * This program and the accompanying materials are made available under the
5  * terms of the Eclipse Public License v1.0 which accompanies this distribution,
6  * and is available at http://www.eclipse.org/legal/epl-v10.html
7  */
8 package org.opendaylight.yangtools.yang.xpath.api;
9
10 import static java.util.Objects.requireNonNull;
11
12 import com.google.common.annotations.Beta;
13 import java.util.Optional;
14 import org.eclipse.jdt.annotation.Nullable;
15 import org.opendaylight.yangtools.yang.common.QName;
16
17 /**
18  * Expressions which evaluate to a logical {@code true} or {@code false}. These expressions are equivalent to the result
19  * returned by {@code true()} and {@code false()} functions defined in XPath 1.0.
20  *
21  * <p>
22  * They also map these functions' names to the constant pool under their {@link YangFunctionCallExpr#getName()}
23  * identity. All users should use these constants in favor of their equivalent function calls.
24  *
25  * @author Robert Varga
26  */
27 @Beta
28 public enum YangBooleanConstantExpr implements YangConstantExpr<Boolean> {
29     /**
30      * A constant {@code false} expression.
31      */
32     FALSE(Boolean.FALSE, YangFunction.FALSE),
33     /**
34      * A constant {@code true} expression.
35      */
36     TRUE(Boolean.TRUE, YangFunction.TRUE);
37
38     private final YangFunctionCallExpr function;
39     private final Boolean value;
40
41     @SuppressWarnings("null")
42     YangBooleanConstantExpr(final @Nullable Boolean value, final YangFunction function) {
43         this.value = requireNonNull(value);
44         this.function = YangFunctionCallExpr.of(function.getIdentifier());
45     }
46
47     @Override
48     public QName getIdentifier() {
49         return function.getName();
50     }
51
52     @Override
53     public Boolean getValue() {
54         return value;
55     }
56
57     /**
58      * Convert this constant into the equivalent function. This function is provided for bridging purposes only.
59      *
60      * @return Equivalent function invocation.
61      */
62     public YangFunctionCallExpr asFunction() {
63         return function;
64     }
65
66     public static YangBooleanConstantExpr of(final boolean bool) {
67         return bool ? TRUE : FALSE;
68     }
69
70     public static Optional<YangFunctionCallExpr> forFunctionName(final String functionName) {
71         switch (functionName) {
72             case "false":
73                 return Optional.of(FALSE.function);
74             case "true":
75                 return Optional.of(TRUE.function);
76             default:
77                 return Optional.empty();
78         }
79     }
80 }