MAJOR=7
MINOR=5
DEVNAME=loop5
DEVTYPE=disk
DISKSEQ=10
      MAJOR=7
MINOR=0
DEVNAME=loop0
DEVTYPE=disk
DISKSEQ=5
 ?÷     # Copyright (C) 2008-2011 Canonical Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA

"""Persistent maps from tuple_of_strings->string using CHK stores.

Overview and current status:

The CHKMap class implements a dict from tuple_of_strings->string by using a trie
with internal nodes of 8-bit fan out; The key tuples are mapped to strings by
joining them by \x00, and \x00 padding shorter keys out to the length of the
longest key. Leaf nodes are packed as densely as possible, and internal nodes
are all an additional 8-bits wide leading to a sparse upper tree.

Updates to a CHKMap are done preferentially via the apply_delta method, to
allow optimisation of the update operation; but individual map/unmap calls are
possible and supported. Individual changes via map/unmap are buffered in memory
until the _save method is called to force serialisation of the tree.
apply_delta records its changes immediately by performing an implicit _save.

TODO:
-----

Densely packed upper nodes.

"""

import heapq
import threading
from typing import Callable

from .. import (
    errors,
    lru_cache,
    osutils,
    registry,
    trace,
    )
from .static_tuple import StaticTuple, expect_static_tuple

# approx 4MB
# If each line is 50 bytes, and you have 255 internal pages, with 255-way fan
# out, it takes 3.1MB to cache the layer.
_PAGE_CACHE_SIZE = 4 * 1024 * 1024
# Per thread caches for 2 reasons:
# - in the server we may be serving very different content, so we get less
#   cache thrashing.
# - we avoid locking on every cache lookup.
_thread_caches = threading.local()
# The page cache.
_thread_caches.page_cache = None


def _get_cache():
    """Get the per-thread page cache.

    We need a function to do this because in a new thread the _thread_caches
    threading.local object does not have the cache initialized yet.
    """
    page_cache = getattr(_thread_caches, 'page_cache', None)
    if page_cache is None:
        # We are caching bytes so len(value) is perfectly accurate
        page_cache = lru_cache.LRUSizeCache(_PAGE_CACHE_SIZE)
        _thread_caches.page_cache = page_cache
    return page_cache


def clear_cache():
    _get_cache().clear()


# If a ChildNode falls below this many bytes, we check for a remap
_INTERESTING_NEW_SIZE = 50
# If a ChildNode shrinks by more than this amount, we check for a remap
_INTERESTING_SHRINKAGE_LIMIT = 20


def _search_key_plain(key):
    """Map the key tuple into a search string that just uses the key bytes."""
    return b'\x00'.join(key)


search_key_registry = registry.Registry[bytes, Callable[[bytes], bytes]]()
search_key_registry.register(b'plain', _search_key_plain)


class CHKMap:
    """A persistent map from string to string backed by a CHK store."""

    __slots__ = ('_store', '_root_node', '_search_key_func')

    def __init__(self, store, root_key, search_key_func=None):
        """Create a CHKMap object.

        :param store: The store the CHKMap is stored in.
        :param root_key: The root key of the map. None to create an empty
            CHKMap.
        :param search_key_func: A function mapping a key => bytes. These bytes
            are then used by the internal nodes to split up leaf nodes into
            multiple pages.
        """
        self._store = store
        if search_key_func is None:
   