Added source code to zxing.org
[zxing.git] / zxingorg / src / com / google / zxing / web / IPTrie.java
1 /*\r
2  * Copyright 2008 Google Inc.\r
3  *\r
4  * Licensed under the Apache License, Version 2.0 (the "License");\r
5  * you may not use this file except in compliance with the License.\r
6  * You may obtain a copy of the License at\r
7  *\r
8  *      http://www.apache.org/licenses/LICENSE-2.0\r
9  *\r
10  * Unless required by applicable law or agreed to in writing, software\r
11  * distributed under the License is distributed on an "AS IS" BASIS,\r
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r
13  * See the License for the specific language governing permissions and\r
14  * limitations under the License.\r
15  */\r
16 \r
17 package com.google.zxing.web;\r
18 \r
19 import java.net.InetAddress;\r
20 import java.util.Arrays;\r
21 \r
22 /**\r
23  * @author Sean Owen\r
24  */\r
25 final class IPTrie {\r
26 \r
27         private final IPTrieNode root;\r
28 \r
29         IPTrie() {\r
30                 root = new IPTrieNode(false);\r
31         }\r
32 \r
33         int incrementAndGet(InetAddress ipAddress) {\r
34                 byte[] octets = ipAddress.getAddress();\r
35                 synchronized (root) {\r
36                         IPTrieNode current = root;\r
37                         int max = octets.length - 1;\r
38                         for (int offset = 0; offset < max; offset++) {\r
39                                 int index = 0xFF & octets[offset];\r
40                                 IPTrieNode child = current.children[index];\r
41                                 if (child == null) {\r
42                                         child = new IPTrieNode(offset == max - 1);\r
43                                         current.children[index] = child;\r
44                                 }\r
45                                 current = child;\r
46                         }\r
47                         int index = 0xFF & octets[max];\r
48                         current.values[index]++;\r
49                         return current.values[index];\r
50                 }\r
51         }\r
52 \r
53         void clear() {\r
54                 synchronized (root) {\r
55                         Arrays.fill(root.children, null);\r
56                 }\r
57         }\r
58 \r
59         private static final class IPTrieNode {\r
60                 final IPTrieNode[] children;\r
61                 final int[] values;\r
62                 private IPTrieNode(boolean terminal) {\r
63                         if (terminal) {\r
64                                 children = null;\r
65                                 values = new int[256];\r
66                         } else {\r
67                                 children = new IPTrieNode[256];\r
68                                 values = null;\r
69                         }\r
70                 }\r
71         }\r
72 \r
73 }