Shuyi Chen | d7955ce | 2013-05-22 14:51:55 -0700 | [diff] [blame] | 1 | // Copyright (c) 1999-2004 Brian Wellington (bwelling@xbill.org) |
| 2 | |
| 3 | package org.xbill.DNS; |
| 4 | |
| 5 | /** |
| 6 | * DNS Name Compression object. |
| 7 | * @see Message |
| 8 | * @see Name |
| 9 | * |
| 10 | * @author Brian Wellington |
| 11 | */ |
| 12 | |
| 13 | public class Compression { |
| 14 | |
| 15 | private static class Entry { |
| 16 | Name name; |
| 17 | int pos; |
| 18 | Entry next; |
| 19 | } |
| 20 | |
| 21 | private static final int TABLE_SIZE = 17; |
| 22 | private static final int MAX_POINTER = 0x3FFF; |
| 23 | private Entry [] table; |
| 24 | private boolean verbose = Options.check("verbosecompression"); |
| 25 | |
| 26 | /** |
| 27 | * Creates a new Compression object. |
| 28 | */ |
| 29 | public |
| 30 | Compression() { |
| 31 | table = new Entry[TABLE_SIZE]; |
| 32 | } |
| 33 | |
| 34 | /** |
| 35 | * Adds a compression entry mapping a name to a position in a message. |
| 36 | * @param pos The position at which the name is added. |
| 37 | * @param name The name being added to the message. |
| 38 | */ |
| 39 | public void |
| 40 | add(int pos, Name name) { |
| 41 | if (pos > MAX_POINTER) |
| 42 | return; |
| 43 | int row = (name.hashCode() & 0x7FFFFFFF) % TABLE_SIZE; |
| 44 | Entry entry = new Entry(); |
| 45 | entry.name = name; |
| 46 | entry.pos = pos; |
| 47 | entry.next = table[row]; |
| 48 | table[row] = entry; |
| 49 | if (verbose) |
| 50 | System.err.println("Adding " + name + " at " + pos); |
| 51 | } |
| 52 | |
| 53 | /** |
| 54 | * Retrieves the position of the given name, if it has been previously |
| 55 | * included in the message. |
| 56 | * @param name The name to find in the compression table. |
| 57 | * @return The position of the name, or -1 if not found. |
| 58 | */ |
| 59 | public int |
| 60 | get(Name name) { |
| 61 | int row = (name.hashCode() & 0x7FFFFFFF) % TABLE_SIZE; |
| 62 | int pos = -1; |
| 63 | for (Entry entry = table[row]; entry != null; entry = entry.next) { |
| 64 | if (entry.name.equals(name)) |
| 65 | pos = entry.pos; |
| 66 | } |
| 67 | if (verbose) |
| 68 | System.err.println("Looking for " + name + ", found " + pos); |
| 69 | return pos; |
| 70 | } |
| 71 | |
| 72 | } |