Skip to content

Instantly share code, notes, and snippets.

@nathankrishnan
nathankrishnan / maliciousDomainSetExample.swift
Last active April 9, 2017 18:07
Using a set to store malicious domains
var badDomains: Set<String> = ["badguys.com", "drevil.me", "virus.io"]
let websiteToLoad = NSURL(string: "http://virus.io")
if let validDomain = websiteToLoad?.host {
if badDomains.contains(validDomain) {
print("This website is known to be malicious!")
} else {
print("This website doesn't exist in our dossier. Let's proceed.")
}
}
print(MemoryLayout<Bool>.size)
// A Bool is represented with 1 byte
print(MemoryLayout<Int>.size)
// An Int is represented with 8 bytes
public class BloomFilter<T> {
private var array: [Bool]
private var hashFunctions: [(T) -> Int]
public init(size: Int = 1024, hashFunctions: [(T) -> Int]) {
self.array = [Bool](repeating: false, count: size)
self.hashFunctions = hashFunctions
}
private func computeHashes(_ value: T) -> [Int]
private func computeHashes(_ value: T) -> [Int] {
return hashFunctions.map() { hashFunction in abs(hashFunction(value) % array.count) }
}
private func computeHashes(_ value: T) -> [Int] {
return hashFunctions.map({
(hashFunction: (T) -> Int) -> Int in
return abs(hashFunction(value)) % array.count
})
}
private func computeHashes(_ value: T) -> [Int] {
var results: [Int] = []
for hashFunction in hashFunctions {
let value = abs(hashFunction(value)) % array.count
results.append(value)
}
return results
}
public func insert(_ element: T) {
for hashValuePosition in computeHashes(element) {
array[hashValuePosition] = true
}
}
public func query(_ value: T) -> Bool {
let hashValuePositions = computeHashes(value)
let valuesAtIndices = hashValuePositions.map() { hashValuePosition in array[hashValuePosition] }
let exists = valuesAtIndices.reduce(true, { $0 && $1 })
return exists
}
public func isEmpty() -> Bool {
return array.reduce(true) { prev, next in prev && !next }
}
let badDomains = BloomFilter<String>(size: 1024, hashFunctions: [djb2, sdbm])
badDomains.insert("badguys.com")
badDomains.insert("drevil.me")
badDomains.insert("virus.io")
let websiteToLoad = NSURL(string: "http://virus.io")
if let validDomain = websiteToLoad?.host {
if badDomains.query(validDomain) {
print("The website is most likely bad!")
} else {