├── .gitignore ├── README.md ├── src └── org │ └── gradiant │ └── cuckooFilter │ ├── ByteUtil.java │ ├── ByteArrayTable.java │ └── CuckooFilter.java └── LICENSE_APACHEv2 /.gitignore: -------------------------------------------------------------------------------- 1 | /bin 2 | .classpath 3 | .project 4 | /.settings 5 | 6 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | java-cuckoo-filter 2 | ================== 3 | 4 | Open Java implementation of Cuckoo Filters, Apache License v2 5 | 6 | **© GRADIANT (http://www.gradiant.org)** 7 | 8 | This is an implementation of Cuckoo Filters, as defined in "Cuckoo Filter: Better than Bloom" (http://www.cs.cmu.edu/~binfan/papers/login_cuckoofilter.pdf) paper. A cuckoo filter is similar to bloom filters in functionality: is a data structure that can be used to test whether an element (item) is part of a set. 9 | 10 | Developed for Java v6. 11 | 12 | _Use with caution!_ This software has not been thoroughly tested, also its performance is far from optimal at this stage. 13 | 14 | -------------------------------------------------------------------------------- /src/org/gradiant/cuckooFilter/ByteUtil.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright Gradiant (http://www.gradiant.org) 2014 3 | * 4 | * APACHE LICENSE v2.0 5 | * 6 | * Author: Dr. Luis Rodero-Merino (lrodero@gradiant.org) 7 | */ 8 | package org.gradiant.cuckooFilter; 9 | 10 | public class ByteUtil { 11 | 12 | public final static boolean isZero(byte[] array) { 13 | if(array == null) 14 | throw new IllegalArgumentException("Cannot check if a null array is full of zeros"); 15 | for(byte b: array) 16 | if(b != 0) 17 | return false; 18 | return true; 19 | } 20 | 21 | /** 22 | * Shift byte array a certain number of positions to left (where the minus significant bit is at the right end), and fill 23 | * with 0's as the array is moved. Up to 7 bits (positions) can be shifted. 24 | * @param array 25 | * @param positions 26 | * @return 27 | */ 28 | public final static byte[] shiftLeftAndFill(byte[] array, int positions) { 29 | if(array == null) 30 | throw new IllegalArgumentException("Cannot shift a null byte array"); 31 | if(positions < 0) 32 | throw new IllegalArgumentException("Cannot shift a negative number of positions"); 33 | if(positions >= 8) 34 | throw new IllegalArgumentException("Weird error, should not be asking for shifting more than 7 positions, but " + positions + " are asked for"); 35 | byte[] result = new byte[array.length]; 36 | byte mask = (byte) (((byte)0xff) << (8-positions)); 37 | for(int i = array.length-1; i >=0; i--) { // Traversing array from left to right 38 | result[i] = (byte)(array[i] << positions); 39 | if(i==0) { 40 | break; 41 | } 42 | // 'Retrieving' bits from following byte at the right, so they are not lost 43 | byte fromFoll = (byte)(array[i-1] & mask); 44 | fromFoll = (byte) ((fromFoll&0xff) >>> (8-positions)); // The 0xff mask is to prevent the '>>>' operator to make appear some 1's... 45 | result[i] = (byte) (result[i] | fromFoll); 46 | } 47 | return result; 48 | } 49 | 50 | /** 51 | * Shift byte array a certain number of positions to right (where the minus significant bit is at the right end), and fill 52 | * with 0's as the array is moved. Up to 7 bits (positions) can be shifted. 53 | * @param array 54 | * @param positions 55 | * @return 56 | */ 57 | public final static byte[] shitfRightAndFill(byte[] array, int positions) { 58 | if(array == null) 59 | throw new IllegalArgumentException("Cannot shift a null byte array"); 60 | if(positions < 0) 61 | throw new IllegalArgumentException("Cannot shift a negative number of positions"); 62 | if(positions >= 8) 63 | throw new IllegalArgumentException("Weird error, should not be asking for shifting more than 7 positions, but " + positions + " are asked for"); 64 | byte[] result = new byte[array.length]; 65 | byte mask = (byte)((0x01 << positions)-1); 66 | for(int i = 0; i <= array.length - 1; i++) { // Traversing array from right to left 67 | result[i] = (byte)((array[i]&0xff) >>> positions); 68 | if(i < array.length - 1) // Getting bits from following byte at the left 69 | result[i] = (byte)(result[i] | (byte) (((byte)(array[i+1] & mask)) << (8-positions))); 70 | } 71 | return result; 72 | } 73 | 74 | public final static void insertZeroIn(byte[] array, int bitPos) { 75 | if(array == null) 76 | throw new IllegalArgumentException("Cannot insert zeros in a null array"); 77 | if(bitPos < 0) 78 | throw new IllegalArgumentException("Cannot insert zero in a negative position (byte array index)"); 79 | if(bitPos >= array.length * 8) 80 | throw new IllegalArgumentException("Cannot insert zero in position (index) " + bitPos + ", byte array length is " + array.length*8 + " in bits"); 81 | int bytePos = bitPos / 8; 82 | int posInByte = bitPos % 8; 83 | byte mask = (byte) ~(byte)(0x01 << posInByte); 84 | array[bytePos] = (byte)(array[bytePos] & mask); 85 | } 86 | 87 | public final static String readableByteArray(byte[] array) { 88 | if(array == null) 89 | return "[NULL]"; 90 | String result = "["; 91 | for(int i = array.length-1; i >=0; i--) { 92 | result += readableByte(array[i]); 93 | if(i > 0) 94 | result += ("|"); 95 | } 96 | result += "]"; 97 | return result; 98 | } 99 | 100 | public final static String readableByteArrayI(int val) { // Most significative first (at the left size) 101 | String result = "["; 102 | int mask = 0xff; 103 | for(int i = 0; i < 4; i++) { 104 | long masked = (val & (mask << ((3 - i))*8)); 105 | masked = (masked >>> ((3-i))*8); 106 | result += readableByte((byte)(masked&0xff)); 107 | if(i < 3) 108 | result += "|"; 109 | } 110 | result += "]"; 111 | return result; 112 | } 113 | 114 | public final static String readableByteArrayL(long val) { // Most significative first (at the left size) 115 | String result = "["; 116 | long mask = 0xffL; 117 | for(int i = 0; i < 8; i++) { 118 | long masked = (val & (mask << ((7 - i))*8)); 119 | masked = (masked >>> ((7-i))*8); 120 | result += readableByte((byte)masked); 121 | if(i < 7) 122 | result += "|"; 123 | } 124 | result += "]"; 125 | return result; 126 | } 127 | 128 | public final static String readableByte(byte b) { 129 | String a = Integer.toBinaryString(256 + (int) b); 130 | return (a.substring(a.length() - 8)); 131 | } 132 | } 133 | -------------------------------------------------------------------------------- /src/org/gradiant/cuckooFilter/ByteArrayTable.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright Gradiant (http://www.gradiant.org) 2014 3 | * 4 | * APACHE LICENSE v2.0 5 | * 6 | * Author: Dr. Luis Rodero-Merino (lrodero@gradiant.org) 7 | */ 8 | package org.gradiant.cuckooFilter; 9 | 10 | import java.util.Arrays; 11 | /** 12 | * Table to store data in a byte array. A ByteBuffer could be used if we were sure that data items size will be 13 | * an integer number of bytes. 14 | * 15 | * @author Luis Rodero-Merino 16 | * 17 | */ 18 | public class ByteArrayTable { 19 | 20 | private int bitsPerBucket; 21 | private int buckets; 22 | protected byte[] table = null; 23 | 24 | public int size() { 25 | return buckets; 26 | } 27 | 28 | public ByteArrayTable(int buckets, int bitsPerBucket) { 29 | 30 | if(buckets <= 0) 31 | throw new IllegalArgumentException("Cannot create a table with a non-positive number of buckets"); 32 | if(bitsPerBucket <= 0) 33 | throw new IllegalArgumentException("Cannot create a table with a non-positive number of bits per bucket"); 34 | 35 | this.bitsPerBucket = bitsPerBucket; 36 | this.buckets = buckets; 37 | int tableSize = (int) Math.ceil(bitsPerBucket * buckets / 8.0D); 38 | table = new byte[tableSize]; 39 | 40 | } 41 | 42 | public boolean isItemInPos(byte[] item, int itemPos) { 43 | 44 | if(item.length != bytesPerBucket()) 45 | throw new IllegalArgumentException("A data item must be an array of size " + bytesPerBucket() + " in bytes, to store the " + bitsPerBucket + " bits per bucket"); 46 | if(itemPos >= buckets) 47 | throw new IllegalArgumentException("Cannot get item from position " + itemPos + ", valid range is [0," + (buckets-1) + "]"); 48 | if(itemPos < 0) 49 | throw new IllegalArgumentException("Cannot get item from a negative position " + itemPos + ", valid range is [0," + (buckets-1) + "]"); 50 | 51 | byte[] data = get(itemPos); 52 | 53 | for(int i = 0; i < data.length; i++) 54 | if(data[i] != item[i]) 55 | return false; 56 | 57 | return true; 58 | } 59 | 60 | public byte[] get(int itemPos) { 61 | 62 | if(itemPos >= buckets) 63 | throw new IllegalArgumentException("Cannot get item from position " + itemPos + ", valid range is [0," + (buckets-1) + "]"); 64 | if(itemPos < 0) 65 | throw new IllegalArgumentException("Cannot get item from a negative position " + itemPos + ", valid range is [0," + (buckets-1) + "]"); 66 | 67 | // Locating affected bytes in table 68 | int firstByteInd = itemPos * bitsPerBucket / 8; 69 | int lastByteInd = ((itemPos + 1) * bitsPerBucket - 1) / 8; 70 | 71 | byte[] item = new byte[lastByteInd-firstByteInd+1]; 72 | System.arraycopy(table, firstByteInd, item, 0, item.length); 73 | 74 | // Shifting to the left to align the item array with the bytes in the table, new positions are also filled with 0's. 75 | int firstBitInFirstByteInd = itemPos * bitsPerBucket % 8; 76 | item = ByteUtil.shitfRightAndFill(item, firstBitInFirstByteInd); 77 | 78 | // Removing leading byte if needed 79 | if(item.length == (bytesPerBucket()+1)) 80 | item = Arrays.copyOfRange(item, 0, item.length-1); 81 | 82 | // Just a small check... 83 | if(item.length != bytesPerBucket()) 84 | throw new InternalError("Created an item with a number of bytes " + item.length + " that differes from the size of buckets " + bytesPerBucket()); 85 | 86 | // Removing leading bits that come from following item in table 87 | if(bitsPerBucket % 8 != 0) { 88 | byte mask = (byte)((0x01 << (bitsPerBucket % 8))-1); 89 | item[item.length-1] &= mask; 90 | } 91 | 92 | return item; 93 | } 94 | 95 | public void insert(byte[] item, int itemPos) { 96 | 97 | if(item.length != bytesPerBucket()) 98 | throw new IllegalArgumentException("A data item must be an array of size " + bytesPerBucket() + " in bytes, to store the " + bitsPerBucket + " bits per bucket"); 99 | if(itemPos >= buckets) 100 | throw new IllegalArgumentException("Cannot insert item at position " + itemPos + ", valid range is [0," + (buckets-1) + "]"); 101 | if(itemPos < 0) 102 | throw new IllegalArgumentException("Cannot insert item at a negative position " + itemPos + ", valid range is [0," + (buckets-1) + "]"); 103 | 104 | // Locating affected bytes in table 105 | int firstByteInd = itemPos * bitsPerBucket / 8; 106 | int lastByteInd = ((itemPos + 1) * bitsPerBucket - 1) / 8; 107 | 108 | // We'll create a copy of the item array that will be combined with AND operation with the corresponding bytes in the table 109 | byte[] itemCp = new byte[lastByteInd-firstByteInd+1]; 110 | System.arraycopy(item, 0, itemCp, 0, item.length); 111 | 112 | // Just one small check, the amount of affected bytes must be equal to the item size or be one byte greater (should never happen otherwise but anyway) 113 | if(item.length != itemCp.length && (item.length != (itemCp.length - 1))) 114 | throw new InternalError("Affected bytes are in positions [" + firstByteInd + "," + lastByteInd + "], " + (itemCp.length+1) + " bytes affected in total, but item is " + item.length + " bytes large"); 115 | 116 | // Not all bits in the data item must be added to the table, only those that account for a bucket. The rest (which are the most significant ones, i.e. the ones at the left size), 117 | // will be all replaced by 0's (it will be handy later on). 118 | int lastByteMaskSize = item.length * 8 - bitsPerBucket; // E.g. we need three 0's in the mask 119 | byte lastByteMask = (byte)((0xff >> (lastByteMaskSize))); // Building the mask 00011111 120 | itemCp[item.length-1] = (byte)(itemCp[item.length-1] & lastByteMask); // Applying the mask in the last byte _coming from the original data item_ 121 | if(itemCp.length > item.length) // If an extra byte had to be created, filling it with 0's as well 122 | itemCp[itemCp.length-1] = (byte)0x00; 123 | 124 | // Now shifting to the left to align the item array with the bytes in the table, new positions are also filled with 0's. 125 | int firstBitInFirstByteInd = itemPos * bitsPerBucket % 8; 126 | itemCp = ByteUtil.shiftLeftAndFill(itemCp, firstBitInFirstByteInd); 127 | 128 | // Setting to 0's all bits in table that are going to be replaced (i.e. the bits of the corresponding bucket) 129 | delete(itemPos); 130 | 131 | // Finally, combining the affected bytes in the table with the item array 132 | for(int i = 0; i < itemCp.length; i++) 133 | itemCp[i] = (byte)(itemCp[i] | table[i+firstByteInd]); 134 | 135 | System.arraycopy(itemCp, 0, table, firstByteInd, itemCp.length); 136 | 137 | } 138 | 139 | public void delete(int itemPos) { 140 | 141 | if(itemPos >= buckets) 142 | throw new IllegalArgumentException("Cannot delete item in position " + itemPos + ", valid range is [0," + (buckets-1) + "]"); 143 | if(itemPos < 0) 144 | throw new IllegalArgumentException("Cannot delete item in a negative position " + itemPos + ", valid range is [0," + (buckets-1) + "]"); 145 | 146 | for(int i = itemPos*bitsPerBucket; i < (itemPos+1)*bitsPerBucket; i++) 147 | ByteUtil.insertZeroIn(table, i); 148 | } 149 | 150 | private int bytesPerBucket() { 151 | return (int) Math.ceil(bitsPerBucket / 8.0D); 152 | } 153 | 154 | } 155 | -------------------------------------------------------------------------------- /LICENSE_APACHEv2: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | 203 | -------------------------------------------------------------------------------- /src/org/gradiant/cuckooFilter/CuckooFilter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright Gradiant (http://www.gradiant.org) 2014 3 | * 4 | * APACHE LICENSE v2.0 5 | * 6 | * Author: Dr. Luis Rodero-Merino (lrodero@gradiant.org) 7 | */ 8 | package org.gradiant.cuckooFilter; 9 | 10 | import java.security.MessageDigest; 11 | import java.security.NoSuchAlgorithmException; 12 | import java.util.Arrays; 13 | import java.util.HashSet; 14 | import java.util.Iterator; 15 | import java.util.Random; 16 | import java.util.Set; 17 | 18 | /** 19 | * Cuckoo filter implementation. A cuckoo filter is a data structure for membership control, akin to bloom filters. But unlike bloom filters, deletions are allowed. 20 | * 21 | * False positives are possible, false negatives are not (as long as there is not collision... if two objects have the same fingerprint and are assigned the same positions then 22 | * conflicts can arise). 23 | * @author lrodero 24 | * 25 | */ 26 | public class CuckooFilter { 27 | 28 | private static final int MAX_TRIES_WHEN_ADDING = 500; 29 | 30 | private MessageDigest sha1 = null; 31 | private int fingerprintSize = 0; 32 | private byte fingerprintLastByteMask = (byte)0xff; 33 | private ByteArrayTable table = null; 34 | private ItemInfo lastVictim = null; 35 | 36 | /** 37 | * 38 | * @param fingerprintSize Number of bits for each fingerprint (value that represents an item) 39 | * @param maxItems Max amount of items we expect in the filter. In fact the underlying array size will be greater than this. 40 | */ 41 | public CuckooFilter(int fingerprintSize, int maxItems) { 42 | 43 | if(fingerprintSize <= 0) 44 | throw new IllegalArgumentException("Fingerprint size must be a positive number, received " + fingerprintSize); 45 | if(fingerprintSize > 16 * 8) 46 | throw new IllegalArgumentException("Fingerprint size cannot be greater than " + 16 * 8 +" , received " + fingerprintSize); 47 | 48 | this.fingerprintSize = fingerprintSize; 49 | if(fingerprintSize % 8 != 0) { // Must add some leading 0's in the most significant byte of the mask 50 | int zeros = 8 - (fingerprintSize % 8); 51 | fingerprintLastByteMask = (byte)((0x01 << zeros) - 1); 52 | } 53 | 54 | try { 55 | sha1 = MessageDigest.getInstance("SHA1"); 56 | } catch (NoSuchAlgorithmException e) { 57 | throw new InternalError("All Java implementations should carry an implementation of SHA1, however it cannot be found!"); 58 | } 59 | 60 | // Table size must be a power of 2 and greater than the max number of items 61 | int tableSize = 1; 62 | while(tableSize < maxItems) 63 | tableSize <<= 1; 64 | // If there is not enough 'space to spare', we increase the table size 65 | if(maxItems*1.0D/tableSize > 0.96) 66 | tableSize <<= 1; 67 | 68 | table = new ByteArrayTable(tableSize, fingerprintSize); 69 | } 70 | 71 | /** 72 | * It will return {@code true} if the signature of the given object is found in the filter. But remember that false positives are possible! 73 | * @param o 74 | * @return 75 | */ 76 | public boolean contains(Object o) { 77 | ItemInfo info = itemInfoObj(o); 78 | 79 | if(lastVictim != null) 80 | if(Arrays.equals(info.fingerprint, lastVictim.fingerprint)) 81 | return true; 82 | 83 | if(Arrays.equals(info.fingerprint, table.get(info.index))) 84 | return true; 85 | if(Arrays.equals(info.fingerprint, table.get(info.index2))) 86 | return true; 87 | 88 | return false; 89 | } 90 | 91 | public boolean isFull() { 92 | return lastVictim != null; 93 | } 94 | 95 | /** 96 | * It will return {@code true} if the given object {@code o} has been included, so future calls to {@link #contains(o)} will return {@code true}. 97 | * This method returns {@code false} if the filter is too full. 98 | * @param o 99 | * @return 100 | */ 101 | public boolean add(Object o) { 102 | if(o == null) 103 | throw new IllegalArgumentException("Cannot add a null object"); 104 | return addItem(itemInfoObj(o)); 105 | } 106 | 107 | private boolean addItem(ItemInfo info) { 108 | 109 | // Is already there? If so, we return true 110 | if(Arrays.equals(info.fingerprint, table.get(info.index))) 111 | return true; 112 | if(Arrays.equals(info.fingerprint, table.get(info.index2))) 113 | return true; 114 | 115 | if(lastVictim != null) // Table is already too full 116 | return false; 117 | 118 | if(ByteUtil.isZero(table.get(info.index))) { 119 | table.insert(info.fingerprint, info.index); 120 | return true; 121 | } 122 | 123 | int destination = info.index2; 124 | byte[] fingerprint = info.fingerprint; 125 | int tries = 0; 126 | while(++tries <= MAX_TRIES_WHEN_ADDING) { 127 | byte[] oldFingerprint = table.get(destination); 128 | table.insert(fingerprint, destination); 129 | if(ByteUtil.isZero(oldFingerprint)) 130 | return true; 131 | fingerprint = oldFingerprint; 132 | destination = altIndex(fingerprint, destination); 133 | } 134 | 135 | lastVictim = new ItemInfo(); 136 | lastVictim.fingerprint = fingerprint; 137 | lastVictim.index = destination; 138 | lastVictim.index2 = altIndex(fingerprint, destination); 139 | 140 | return true; 141 | } 142 | 143 | /** 144 | * It will return {@code true} if the element signature was found, {@code false} otherwise. In any case 145 | * the signature will be removed if found. 146 | * @param o 147 | * @return 148 | */ 149 | public boolean delete(Object o) { 150 | 151 | if(o == null) 152 | throw new IllegalArgumentException("Cannot remove a null object"); 153 | 154 | ItemInfo info = itemInfoObj(o); 155 | 156 | 157 | if(ByteUtil.isZero(table.get(info.index)) && ByteUtil.isZero(table.get(info.index2))) 158 | return false; 159 | 160 | boolean deleted = false; 161 | if(Arrays.equals(info.fingerprint, table.get(info.index))) { 162 | table.delete(info.index); 163 | deleted = true; 164 | } else if(Arrays.equals(info.fingerprint, table.get(info.index2))) { 165 | table.delete(info.index2); 166 | deleted = true; 167 | } 168 | 169 | if(deleted) // There is room again for the victim (if there is any), let's try to insert it 170 | if(lastVictim != null) { 171 | ItemInfo infoVic = new ItemInfo(); 172 | infoVic.fingerprint = Arrays.copyOf(lastVictim.fingerprint, lastVictim.fingerprint.length); 173 | infoVic.index = lastVictim.index; 174 | infoVic.index2 = lastVictim.index2; 175 | lastVictim = null; 176 | addItem(infoVic); 177 | } 178 | 179 | return deleted; 180 | 181 | } 182 | 183 | private class ItemInfo { 184 | int index = -1; 185 | int index2 = -1; 186 | byte[] fingerprint = null; 187 | @Override 188 | public String toString() { 189 | return "i1: " + index + ", i2: " + index2 + ", fingerprint: " + ByteUtil.readableByteArray(fingerprint); 190 | } 191 | } 192 | 193 | protected ItemInfo itemInfoObj(Object o) { 194 | int h = o.hashCode(); 195 | byte[] b = new byte[4]; 196 | for(int i=0; i < b.length; i++) { 197 | b[i] = (byte)(h & 0xff); 198 | h >>= 8; 199 | } 200 | return itemInfo(b); 201 | } 202 | 203 | protected ItemInfo itemInfo(byte[] item) { 204 | ItemInfo info = new ItemInfo(); 205 | byte[] hash = sha1.digest(item); 206 | 207 | // First index 208 | long val = 0; 209 | for(int i=0; i < 4; i++) { 210 | val |= (hash[i] & 0xff); // The '& 0xff' op is because the hash[i] byte is transformed to int by java keeping the sign!, this way we get rid of leading 1's if present 211 | if(i<3) 212 | val <<= 8; 213 | } 214 | val &= 0x00000000ffffffffL; 215 | info.index = (int) (val % (long)table.size()); 216 | 217 | // Fingerprint 218 | info.fingerprint = new byte[fingerprintSizeInBytes()]; 219 | for(int i=0; i < info.fingerprint.length; i++) 220 | info.fingerprint[i] = hash[i+4]; 221 | info.fingerprint[info.fingerprint.length-1] &= fingerprintLastByteMask; 222 | if(ByteUtil.isZero(info.fingerprint)) // Avoiding fingerprints with all zeros (they would be confused with 'no fingerprint' in the table) 223 | info.fingerprint[0] = 1; 224 | 225 | // Second index 226 | info.index2 = altIndex(info.fingerprint, info.index); 227 | 228 | // Just a small check 229 | if(altIndex(info.fingerprint, info.index2) != info.index) 230 | throw new InternalError("Generated wrong indexes!"); 231 | 232 | return info; 233 | } 234 | 235 | private int altIndex(byte[] fingerprint, int index) { 236 | byte[] hash = sha1.digest(fingerprint); 237 | long val = 0; 238 | for(int i=0; i < 4; i++) { 239 | long mask = 0xffL; 240 | mask <<= (i*8); 241 | byte b = (byte)((mask & (long)index) >> (i*8)); 242 | val |= (((hash[i] ^ b)&0xff) << (i*8)); 243 | } 244 | val &= 0x00000000ffffffffL; 245 | return (int) (val % (long)table.size()); 246 | } 247 | 248 | private int fingerprintSizeInBytes() { 249 | return (int)Math.ceil(fingerprintSize/8.0D); 250 | } 251 | 252 | public static void main(String[] args) throws NoSuchAlgorithmException { 253 | for(int i=0; i < 10000; i++) 254 | if(!testFilter()) 255 | break; 256 | } 257 | 258 | private static boolean testFilter() { 259 | CuckooFilter filter = new CuckooFilter(16, 1000); 260 | System.out.println("\n==============================="); 261 | System.out.println("Table size: " + filter.table.size()); 262 | 263 | System.out.println("RANDOM INSERTIONS"); 264 | Random random = new Random(); 265 | Set bag = new HashSet(); 266 | for(int i = 0; i < 1000; i++) { 267 | Integer o = new Integer(i); 268 | boolean insert = random.nextBoolean(); 269 | if(insert) { 270 | if(filter.add(o)) 271 | bag.add(o); 272 | else { 273 | System.out.println("ERROR COULD NOT ADD " + o); 274 | return false; 275 | } 276 | } 277 | } 278 | if(filter.isFull()) 279 | System.out.println("FILTER IS FULL"); 280 | else 281 | System.out.println("FILTER IS NOT FULL"); 282 | 283 | System.out.println("CHECKING CONTENTS AFTER RANDOM INSERTIONS (BAG SIZE IS " + bag.size() + ")"); 284 | for(Integer i: bag) 285 | if(!filter.contains(i)) { 286 | System.out.println("ERROR!"); 287 | return false; 288 | } 289 | 290 | byte[] tableCpBfDel = Arrays.copyOf(filter.table.table, filter.table.table.length); 291 | 292 | System.out.println("RANDOM DELETIONS"); 293 | Iterator iter = bag.iterator(); 294 | while(iter.hasNext()) { 295 | Integer i = iter.next(); 296 | boolean remove = random.nextBoolean(); 297 | if(remove) { 298 | filter.delete(i); 299 | iter.remove(); 300 | } 301 | } 302 | 303 | System.out.println("CHECKING CONTENTS AFTER RANDOM DELETIONS (BAG SIZE IS " + bag.size() + ")"); 304 | for(Integer i: bag) 305 | if(!filter.contains(i)) { 306 | System.out.println("ERROR, FILTER DOES NOT CONTAIN " + i); 307 | ItemInfo info = filter.itemInfoObj(i); 308 | System.out.println(info); 309 | System.out.println("filter["+info.index+"]:"+ByteUtil.readableByteArray(filter.table.get(info.index)) + "; filter["+info.index2+"]:"+ByteUtil.readableByteArray(filter.table.get(info.index2))); 310 | System.out.println("filterBfDe["+info.index+"]:"+ByteUtil.readableByteArray(new byte[]{tableCpBfDel[info.index]}) + "; filterBfDe["+info.index2+"]:"+ByteUtil.readableByteArray(new byte[]{tableCpBfDel[info.index2]})); 311 | return false; 312 | } 313 | 314 | System.out.println("EVERYTHING FINE!"); 315 | return true; 316 | } 317 | 318 | } 319 | --------------------------------------------------------------------------------