view src/name/blackcap/exifwasher/Whitelist.kt @ 31:3b0546fa0d74

Add documentation in alternative formats to HTML.
author David Barts <davidb@stashtea.com>
date Sat, 18 Apr 2020 09:08:23 -0700
parents aafc9c127c7b
children
line wrap: on
line source

/*
 * An exif key whitelist. Supports both prefixes and entire strings.
 */
package name.blackcap.exifwasher

import java.util.regex.Pattern
import kotlin.collections.mutableSetOf
import kotlin.collections.mutableListOf

class Whitelist: Cloneable {
    private val entire = mutableSetOf<String>()
    private val prefixes = mutableListOf<String>()

    fun addEntire(s: String) = entire.add(s)

    fun addPrefix(s: String) = prefixes.add(s)

    private fun autoOp(s: String, pfx: (String) -> Boolean, ent: (String) -> Boolean): Boolean {
        return if (s.endsWith('*')) { pfx(s.dropLast(1)) } else { ent(s) }
    }

    fun add(s: String) = autoOp(s, ::addPrefix, ::addEntire)

    fun removeEntire(s: String) = entire.remove(s)

    fun removePrefix(s: String) = prefixes.remove(s)

    fun remove(s: String) = autoOp(s, ::removePrefix, ::removeEntire)

    fun contains(s: String) = entire.contains(s) || prefixes.find { s.startsWith(it) } != null

    fun toList(): List<String> = prefixes.map { it + "*" } + entire

    override fun toString(): String = toList().joinToString(",")

    override public fun clone() = Whitelist().also { new ->
        entire.forEach { new.addEntire(it) }
        prefixes.forEach { new.addPrefix(it) }
    }

    companion object {
        private val SPLITTER = Pattern.compile(",\\s*")
        fun parse(raw: String) = Whitelist().also {
            for (s in raw.split(SPLITTER)) {
                it.add(s)
            }
        }
    }
}