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 static com.google.common.base.Preconditions.checkArgument;
11 import static java.util.Objects.requireNonNull;
13 import com.google.common.annotations.Beta;
14 import com.google.common.collect.ImmutableRangeSet;
15 import com.google.common.collect.Range;
16 import com.google.common.collect.RangeSet;
17 import com.google.common.collect.TreeRangeSet;
18 import java.util.Collection;
19 import java.util.Optional;
20 import org.opendaylight.yangtools.yang.data.api.codec.StringCodec;
21 import org.opendaylight.yangtools.yang.model.api.type.LengthConstraint;
22 import org.opendaylight.yangtools.yang.model.api.type.StringTypeDefinition;
25 * Do not use this class outside of yangtools, its presence does not fall into the API stability contract.
28 public class StringStringCodec extends TypeDefinitionAwareCodec<String, StringTypeDefinition>
29 implements StringCodec<String> {
31 private final RangeSet<Integer> lengths;
33 StringStringCodec(final StringTypeDefinition typeDef) {
34 super(Optional.of(typeDef), String.class);
36 final Collection<LengthConstraint> constraints = typeDef.getLengthConstraints();
37 if (!constraints.isEmpty()) {
38 final RangeSet<Integer> tmp = TreeRangeSet.create();
39 for (LengthConstraint c : constraints) {
40 tmp.add(Range.closed(c.getMin().intValue(), c.getMax().intValue()));
43 lengths = ImmutableRangeSet.copyOf(tmp);
49 public static StringStringCodec from(final StringTypeDefinition normalizedType) {
50 if (normalizedType.getPatternConstraints().isEmpty()) {
51 return new StringStringCodec(normalizedType);
54 return new StringPatternCheckingCodec(normalizedType);
58 public final String deserialize(final String stringRepresentation) {
59 validate(requireNonNull(stringRepresentation));
60 return stringRepresentation;
64 public final String serialize(final String data) {
65 return requireNonNull(data);
68 void validate(final String str) {
69 if (lengths != null) {
70 checkArgument(lengths.contains(str.length()), "String '%s' does not match allowed lengths %s", lengths);