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