BUG-6316: Fix Bit and EnumPair's position/value types
[yangtools.git] / yang / yang-model-util / src / main / java / org / opendaylight / yangtools / yang / model / util / type / BitsTypeBuilder.java
1 /*
2  * Copyright (c) 2015 Pantheon Technologies 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.util.type;
9
10 import com.google.common.collect.ImmutableMap;
11 import com.google.common.collect.ImmutableMap.Builder;
12 import java.util.HashMap;
13 import java.util.Map;
14 import javax.annotation.Nonnull;
15 import org.opendaylight.yangtools.yang.model.api.SchemaPath;
16 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition;
17 import org.opendaylight.yangtools.yang.model.api.type.BitsTypeDefinition.Bit;
18
19 public final class BitsTypeBuilder extends TypeBuilder<BitsTypeDefinition> {
20     private final Builder<String, Bit> builder = ImmutableMap.builder();
21
22     BitsTypeBuilder(final SchemaPath path) {
23         super(null, path);
24     }
25
26     public BitsTypeBuilder addBit(@Nonnull final Bit item) {
27         builder.put(item.getName(), item);
28         return this;
29     }
30
31     @Override
32     public BitsTypeDefinition build() {
33         final Map<String, Bit> map = builder.build();
34         final Map<Long, Bit> positionMap = new HashMap<>();
35
36         for (Bit b : map.values()) {
37             final Bit conflict = positionMap.put(b.getPosition(), b);
38             if (conflict != null) {
39                 throw new InvalidBitDefinitionException(b, "Bit %s conflicts on position with bit ", conflict);
40             }
41         }
42
43         return new BaseBitsType(getPath(), getUnknownSchemaNodes(), positionMap.values());
44     }
45 }