2 * Copyright (c) 2014 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.codec.xml;
10 import com.google.common.annotations.VisibleForTesting;
11 import com.google.common.base.Preconditions;
12 import com.google.common.collect.BiMap;
13 import com.google.common.collect.HashBiMap;
15 import java.util.Map.Entry;
16 import javax.xml.XMLConstants;
17 import javax.xml.namespace.NamespaceContext;
20 // 32 characters, carefully chosen
21 private static final String LOOKUP = "abcdefghiknoprstABCDEFGHIKNOPRST";
22 private static final int MASK = 0x1f;
23 private static final int SHIFT = 5;
25 private int counter = 0;
27 // BiMap to make values lookup faster
28 private final BiMap<URI, String> prefixes = HashBiMap.create();
29 private final NamespaceContext context;
35 RandomPrefix(final NamespaceContext context) {
36 this.context = Preconditions.checkNotNull(context);
39 Iterable<Entry<URI, String>> getPrefixes() {
40 return prefixes.entrySet();
43 String encodePrefix(final URI namespace) {
44 String prefix = prefixes.get(namespace);
50 prefix = encode(counter);
52 } while (alreadyUsedPrefix(prefix));
54 prefixes.put(namespace, prefix);
58 private boolean alreadyUsedPrefix(final String prefix) {
59 if (context == null) {
63 final String str = context.getNamespaceURI(prefix);
64 return !XMLConstants.NULL_NS_URI.equals(str);
68 static int decode(final String str) {
70 for (char c : str.toCharArray()) {
71 int idx = LOOKUP.indexOf(c);
72 Preconditions.checkArgument(idx != -1, "Invalid string %s", str);
73 ret = (ret << SHIFT) + idx;
80 static String encode(int num) {
81 final StringBuilder sb = new StringBuilder();
84 sb.append(LOOKUP.charAt(num & MASK));
88 return sb.reverse().toString();