Fix BaseDecimalType scales
[yangtools.git] / model / yang-model-ri / src / main / java / org / opendaylight / yangtools / yang / model / ri / type / AbstractConstraint.java
1 /*
2  * Copyright (c) 2021 PANTHEON.tech, s.r.o. and others.  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.model.ri.type;
9
10 import static com.google.common.base.Verify.verify;
11 import static java.util.Objects.requireNonNull;
12
13 import com.google.common.collect.ImmutableRangeSet;
14 import com.google.common.collect.Range;
15 import com.google.common.collect.RangeSet;
16 import java.util.Optional;
17 import org.eclipse.jdt.annotation.NonNull;
18 import org.opendaylight.yangtools.yang.model.api.ConstraintMetaDefinition;
19
20 /**
21  * Abstract base class for {@link ResolvedLengthConstraint} and {@link ResolvedRangeConstraint}.
22  *
23  * @param <T> type of constraint
24  */
25 abstract class AbstractConstraint<T extends Number & Comparable<T>> implements ConstraintMetaDefinition {
26     private final ConstraintMetaDefinition meta;
27     private final Object ranges;
28
29     AbstractConstraint(final ConstraintMetaDefinition meta, final RangeSet<T> ranges) {
30         this.meta = requireNonNull(meta);
31
32         final var tmp = ranges.asRanges();
33         if (tmp.size() == 1) {
34             this.ranges = tmp.iterator().next();
35         } else {
36             this.ranges = ImmutableRangeSet.copyOf(ranges);
37         }
38     }
39
40     @Override
41     public final Optional<String> getDescription() {
42         return meta.getDescription();
43     }
44
45     @Override
46     public final Optional<String> getErrorAppTag() {
47         return meta.getErrorAppTag();
48     }
49
50     @Override
51     public final Optional<String> getErrorMessage() {
52         return meta.getErrorMessage();
53     }
54
55     @Override
56     public final Optional<String> getReference() {
57         return meta.getReference();
58     }
59
60     @SuppressWarnings("unchecked")
61     final @NonNull ImmutableRangeSet<T> ranges() {
62         if (ranges instanceof ImmutableRangeSet) {
63             return (ImmutableRangeSet<T>) ranges;
64         }
65         verify(ranges instanceof Range, "Unexpected range object %s", ranges);
66         return ImmutableRangeSet.of((Range<T>) ranges);
67     }
68 }