view src/name/blackcap/exifwasher/Whitelist.kt @ 5:dc1f4359659d

Got it compiling.
author David Barts <n5jrn@me.com>
date Thu, 09 Apr 2020 18:20:34 -0700
parents 19c381c536ec
children aafc9c127c7b
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 + 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)
            }
        }
    }
}