def clone(src, **kwargs):
    """Clones object with optionally overridden fields"""
    obj = object.__new__(type(src))
    obj.__dict__.update(src.__dict__)
    obj.__dict__.update(kwargs)
    return obj def ensure_context(ctx, func, right=True):
    if isinstance(func, ContexAware):  # pragma: no cover
        assert right, 'Context-aware function must be attached to right side'
        assert ctx, 'Context needed'
        func.check(ctx)
        return partial(func, ctx)
    return func def merge_dicts(*dicts, **kwargs):
    """Merges dicts and kwargs into one dict"""
    result = {}
    for d in dicts:
        result.update(d)
    result.update(kwargs)
    return result PY2 = sys.version_info[0] == 2
COROUTINE = sys.version_info[:2] >= (3, 4)
ASYNC_AWAIT = sys.version_info[:2] >= (3, 5)
def bstr(data, encoding='latin1'):
def ustr(data, encoding='latin1'):
def str_map(data, encoding='latin1'):
def str_coerce(stype, data, encoding='latin1'):
    def iscoroutinefunction(fun):
    def reraise(tp, value, tb=None): class Invalid(ValueError):
    def __init__(self, errors, clean):
        self.errors = errors
        self.clean = clean
        ValueError.__init__(self, repr(self.errors)) class RequiredExcepion(ValueError):
    def __init__(self, message=None):
        ValueError.__init__(self, message or 'Required item') class RangeException(ValueError):
    def __init__(self, value, min=None, max=None):
        self.value = value
        self.min = min
        self.max = max

        if min is not None:
            ValueError.__init__(self, '{0} is less then {1}'.format(value, min))
        else:
            ValueError.__init__(self, '{0} is greater then {1}'.format(value, max)) class RegexException(ValueError):
    def __init__(self, value, regex):
        self.value = value
        self.regex = regex
        ValueError.__init__(self, 'Mismatch "{0}" for "{1}"'.format(value, regex.pattern)) class LengthException(ValueError):
    def __init__(self, value, exact=None, min=None, max=None):
        self.value = value
        self.exact = exact
        self.min = min
        self.max = max

        size = len(value or '')
        if exact is not None:
            ValueError.__init__(self, 'Length of {0} does not equal {1}'.format(size, exact))
        elif min is not None:
            ValueError.__init__(self, 'Length of {0} is less then {1}'.format(size, min))
        else:
            ValueError.__init__(self, 'Length of {0} is greater then {1}'.format(size, max)) class EnumException(ValueError):
    def __init__(self, value, enum):
        self.value = value
        self.enum = enum
        ValueError.__init__(self, '{0} not in {1}'.format(repr(value), enum))
import re
from datetime import datetime
from .utils import clone, ensure_context, merge_dicts
from .compat import utype, btype, stype, ustr, str_map, str_coerce, bstr, PY2
from .errors import (Invalid, RequiredExcepion, RangeException, RegexException,
                     LengthException, EnumException)
    def to_dict(self, data, multi=False):
        """Returns map data as a dict."""
        return data


class ListItemGetter(ItemGetter):
    '''Get items from dict with lists as values

    Can be used as root getter for result of parsing HTTP query string.
    '''
    def get(self, data, field):
        if field.multi:
            return data.get(field.src)
        else:
            d = data.get(field.src)
            if d:
                return d[0]
            else:
                return None

    def to_dict(self, data, multi=False):
        if multi:
            return data
        else:
            return dict((k, v[0]) if v else None
                        for k, v in data.items())


item_getter = ItemGetter()
list_item_getter = ListItemGetter()


class Adjustable(object):
    def adjust(self):  # pragma: no cover
        pass


class Pipeable(object):
    """Pipeable mixin

    Adds ``|`` operation to class.
    """
    def __or__(self, other):
        return Pipe([self, ensure_context(self, other)], self)

    def __ror__(self, other):
        return get_item(other) | self


class Pipe(Pipeable, Adjustable):
    """Pipe validator

    Pass data through function list
    """
    def __init__(self, pipe, ctx=None):
        self.pipe = pipe
        self.ctx = None

    def __call__(self, data):
        for it in self.pipe:
            data = it(data)
        return data

    def __or__(self, other):
        return Pipe(self.pipe + [ensure_context(self.ctx, other)], self.ctx)

    def adjust(self, item_getter):
        if self.pipe:
            self.pipe[0] = adjust_getter(self.pipe[0], item_getter)
        return self


class Map(Pipeable, Adjustable):
    '''Dict checker

    :param items: Dict with fields. Key is a destination key,
                  value is an alias, any callable or covador.schema.item.

    If source dict does not contain a key, key value is considered None.

    item can have src or dest param to be able to specify source or
    destination key, by default it equals to field key.
    ::

        Map({'foo': int})({'foo': '10'}) -> {'foo': 10}

        Map({'foo': opt(int)})({}) -> None

        m = Map({'raw': item('bytes', src='data'),
                 'data': item('str', dest='decoded')})
        m({'data': b'data'}) -> {'raw': b'data', 'decoded': u'data'}
    '''
    def __init__(self, items, getter=None):
        if isinstance(items, Map):  # pragma: no cover
            items = items.items

        self.items = {}
        for k, it in items.items():
            it = get_item(it)
            if not it.src:
                it.src = k
            if not it.dest:
                it.dest = k
            self.items[it.dest] = it

        self.getter = getter or item_getter

    def __call__(self, data):
        errors = []
        result = {}
        get = self.getter.get

        for k, it in self.items.items():
            raw_data = get(data, it)
            try:
                result[k] = it(raw_data)
            except Exception as e:
                errors.append((it.src, e))

        if errors:

            raise Invalid(errors, result)