/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * license agreements; and to You under the Apache License, version 2.0:
 *
 *   https://www.apache.org/licenses/LICENSE-2.0
 *
 * This file is part of the Apache Pekko project, which was derived from Akka.
 */

/*
 * Copyright (C) 2009-2022 Lightbend Inc. <https://www.lightbend.com>
 */

package org.apache.pekko.http.impl.util

import org.apache.pekko.annotation.InternalApi

/**
 * INTERNAL API
 *
 * A unsynchronized registry to keep track of singleton instances similar to what
 * java.lang.Enum provides. `registry` should therefore only be used inside of singleton constructors.
 */
@InternalApi
private[http] trait ObjectRegistry[K, V <: AnyRef] {
  private[this] var _registry = Map.empty[K, V]

  protected final def register(key: K, obj: V): obj.type = {
    require(!_registry.contains(key), s"ObjectRegistry for ${getClass.getSimpleName} already contains value for $key")
    _registry = _registry.updated(key, obj)
    obj
  }
  def getForKey(key: K): Option[V] = _registry.get(key)

  def getForKeyCaseInsensitive(key: String)(implicit conv: String <:< K): Option[V] =
    getForKey(conv(key.toRootLowerCase))
}
