#  Copyright (c) 2019 JD Williams
#
#  This file is part of Firefly, a Python SOA framework built by JD Williams. Firefly 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 3 of the License, or (at your option) any later version.
#
#  Firefly 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 Lesser General Public
#  License along with this program.  If not, see <http://www.gnu.org/licenses/>.
#
#  You should have received a copy of the GNU General Public License along with Firefly. If not, see
#  <http://www.gnu.org/licenses/>.

"""A clone of the default copy.deepcopy that doesn't handle cyclic
structures or complex types except for dicts and lists. This is
because gyp copies so large structure that small copy overhead ends up
taking seconds in a project the size of Chromium."""

class Error(Exception):
  pass

__all__ = ["Error", "deepcopy"]

def deepcopy(x):
  """Deep copy operation on gyp objects such as strings, ints, dicts
  and lists. More than twice as fast as copy.deepcopy but much less
  generic."""

  try:
    return _deepcopy_dispatch[type(x)](x)
  except KeyError:
    raise Error('Unsupported type %s for deepcopy. Use copy.deepcopy ' +
                'or expand simple_copy support.' % type(x))

_deepcopy_dispatch = d = {}

def _deepcopy_atomic(x):
  return x

for x in (type(None), int, long, float,
          bool, str, unicode, type):
  d[x] = _deepcopy_atomic

def _deepcopy_list(x):
  return [deepcopy(a) for a in x]
d[list] = _deepcopy_list

def _deepcopy_dict(x):
  y = {}
  for key, value in x.iteritems():
    y[deepcopy(key)] = deepcopy(value)
  return y
d[dict] = _deepcopy_dict

del d
