| 1 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 2 | // Copyright (c) 2018 Saxonica Limited. |
| 3 | // This Source Code Form is subject to the terms of the Mozilla Public License, v. 2.0. |
| 4 | // If a copy of the MPL was not distributed with this file, You can obtain one at http://mozilla.org/MPL/2.0/. |
| 5 | // This Source Code Form is "Incompatible With Secondary Licenses", as defined by the Mozilla Public License, v. 2.0. |
| 6 | //////////////////////////////////////////////////////////////////////////////////////////////////////////////////// |
| 7 | |
| 8 | package net.sf.saxon.serialize; |
| 9 | |
| 10 | /** |
| 11 | * A simple class for testing membership of a fixed set of case-insensitive ASCII strings. |
| 12 | * The class must be initialised with enough space for all the strings, |
| 13 | * it will go into an infinite loop if it fills. The string matching is case-blind, |
| 14 | * using an algorithm that works only for ASCII. |
| 15 | * <p>The class implements part of the java.util.Set interface; it could be replaced with |
| 16 | * an implementation of java.util.Set together with a class that implemented a customized |
| 17 | * equals() method.</p> |
| 18 | */ |
| 19 | |
| 20 | public class HTMLTagHashSet { |
| 21 | |
| 22 | String[] strings; |
| 23 | int size; |
| 24 | |
| 25 | public HTMLTagHashSet(int size) { |
| 26 | strings = new String[size]; |
| 27 | this.size = size; |
| 28 | } |
| 29 | |
| 30 | public void add(String s) { |
| 31 | int hash = (hashCode(s) & 0x7fffffff) % size; |
| 32 | while (true) { |
| 33 | if (strings[hash] == null) { |
| 34 | strings[hash] = s; |
| 35 | return; |
| 36 | } |
| 37 | if (strings[hash].equalsIgnoreCase(s)) { |
| 38 | return; |
| 39 | } |
| 40 | hash = (hash + 1) % size; |
| 41 | } |
| 42 | } |
| 43 | |
| 44 | public boolean contains(/*@NotNull*/ String s) { |
| 45 | int hash = (hashCode(s) & 0x7fffffff) % size; |
| 46 | while (true) { |
| 47 | if (strings[hash] == null) { |
| 48 | return false; |
| 49 | } |
| 50 | if (strings[hash].equalsIgnoreCase(s)) { |
| 51 | return true; |
| 52 | } |
| 53 | hash = (hash + 1) % size; |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | private int hashCode(String s) { |
| 58 | // get a hashcode that doesn't depend on the case of characters. |
| 59 | // This relies on the fact that char & 0xDF is case-blind in ASCII |
| 60 | int hash = 0; |
| 61 | int limit = s.length(); |
| 62 | if (limit > 24) limit = 24; |
| 63 | for (int i = 0; i < limit; i++) { |
| 64 | hash = (hash << 1) + (s.charAt(i) & 0xdf); |
| 65 | } |
| 66 | return hash; |
| 67 | } |
| 68 | } |