2 * Copyright (c) 2015 Cisco Systems, Inc. and others. All rights reserved.
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
8 package org.opendaylight.yangtools.yang.data.impl.codec;
10 import com.google.common.base.Optional;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.ImmutableRangeSet;
13 import com.google.common.collect.Range;
14 import com.google.common.collect.RangeSet;
15 import com.google.common.collect.TreeRangeSet;
16 import java.util.Collection;
17 import java.util.Objects;
18 import org.opendaylight.yangtools.yang.data.api.codec.StringCodec;
19 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
20 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
22 class StringStringCodec extends TypeDefinitionAwareCodec<String, StringTypeDefinition> implements
25 private final RangeSet<Integer> lengths;
27 StringStringCodec(final StringTypeDefinition typeDef) {
28 super(Optional.of(typeDef), String.class);
30 final Collection<LengthConstraint> constraints = typeDef.getLengthConstraints();
31 if (!constraints.isEmpty()) {
32 final RangeSet<Integer> tmp = TreeRangeSet.create();
33 for (LengthConstraint c : constraints) {
34 tmp.add(Range.closed(c.getMin().intValue(), c.getMax().intValue()));
37 lengths = ImmutableRangeSet.copyOf(tmp);
43 static TypeDefinitionAwareCodec<?, StringTypeDefinition> from(final StringTypeDefinition normalizedType) {
44 if (normalizedType.getPatternConstraints().isEmpty()) {
45 return new StringStringCodec(normalizedType);
48 return new StringPatternCheckingCodec(normalizedType);
52 public final String deserialize(final String stringRepresentation) {
53 if (stringRepresentation == null) {
54 // FIXME: These seems buggy, but someone may be using this behaviour
57 validate(stringRepresentation);
58 return stringRepresentation;
62 public final String serialize(final String data) {
63 return Objects.toString(data, "");
66 void validate(final String s) {
67 if (lengths != null) {
68 Preconditions.checkArgument(lengths.contains(s.length()), "String '%s' does not match allowed lengths %s",