Migrate schema/data tree-related methods
[yangtools.git] / yang / yang-parser-rfc7950 / src / main / java / org / opendaylight / yangtools / yang / parser / rfc7950 / stmt / AbstractModelStatement.java
1 /*
2  * Copyright (c) 2020 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.parser.rfc7950.stmt;
9
10 import com.google.common.collect.ImmutableList;
11 import org.eclipse.jdt.annotation.NonNull;
12 import org.opendaylight.yangtools.yang.model.api.meta.ModelStatement;
13
14 abstract class AbstractModelStatement<A> implements ModelStatement<A> {
15
16     /**
17      * Utility method for squashing singleton lists into single objects. This is a CPU/mem trade-off, which we are
18      * usually willing to make: for the cost of an instanceof check we can save one object and re-create it when needed.
19      * The inverse operation is #unmaskSubstatements(Object)}.
20      *
21      * @param list list to mask
22      * @return Masked list
23      * @throws NullPointerException if list is null
24      */
25     protected static final @NonNull Object maskList(final ImmutableList<?> list) {
26         // Note: ImmutableList guarantees non-null content
27         return list.size() == 1 ? list.get(0) : list;
28     }
29
30     /**
31      * Utility method for recovering singleton lists squashed by {@link #maskList(ImmutableList)}.
32      *
33      * @param masked list to unmask
34      * @return Unmasked list
35      * @throws NullPointerException if any argument is null
36      * @throws ClassCastException if masked object does not match expected class
37      */
38     @SuppressWarnings("unchecked")
39     protected static final <T> @NonNull ImmutableList<T> unmaskList(final @NonNull Object masked,
40             final @NonNull Class<T> type) {
41         return masked instanceof ImmutableList ? (ImmutableList<T>) masked
42                 // Yes, this is ugly code, which could use an explicit verify, that would just change the what sort
43                 // of exception we throw. ClassCastException is as good as VerifyException.
44                 : ImmutableList.of(type.cast(masked));
45     }
46 }