view src/name/blackcap/exifwasher/Whitelist.kt @ 38:d794ef80f9b0

Remove more deadwood.
author David Barts <n5jrn@me.com>
date Fri, 01 May 2020 11:52:46 -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)
            }
        }
    }
}