• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1#!/usr/bin/env python
2# Copyright (c) 2012 The Chromium Authors. All rights reserved.
3# Use of this source code is governed by a BSD-style license that can be
4# found in the LICENSE file.
5
6try:
7  import hashlib
8  _new_md5 = hashlib.md5
9except ImportError:
10  import md5
11  _new_md5 = md5.new
12
13
14"""64-bit fingerprint support for strings.
15
16Usage:
17    from extern import FP
18    print 'Fingerprint is %ld' % FP.FingerPrint('Hello world!')
19"""
20
21
22def _UnsignedFingerPrintImpl(str, encoding='utf-8'):
23  """Generate a 64-bit fingerprint by taking the first half of the md5
24  of the string.
25  """
26  hex128 = _new_md5(str).hexdigest()
27  int64 = long(hex128[:16], 16)
28  return int64
29
30
31def UnsignedFingerPrint(str, encoding='utf-8'):
32  """Generate a 64-bit fingerprint.
33
34  The default implementation uses _UnsignedFingerPrintImpl, which
35  takes the first half of the md5 of the string, but the
36  implementation may be switched using SetUnsignedFingerPrintImpl.
37  """
38  return _UnsignedFingerPrintImpl(str, encoding)
39
40
41def FingerPrint(str, encoding='utf-8'):
42  fp = UnsignedFingerPrint(str, encoding=encoding)
43  # interpret fingerprint as signed longs
44  if fp & 0x8000000000000000L:
45    fp = - ((~fp & 0xFFFFFFFFFFFFFFFFL) + 1)
46  return fp
47
48
49def UseUnsignedFingerPrintFromModule(module_name):
50  """Imports module_name and replaces UnsignedFingerPrint in the
51  current module with the function of the same name from the imported
52  module.
53
54  Returns the function object previously known as
55  grit.extern.FP.UnsignedFingerPrint.
56  """
57  hash_module = __import__(module_name, fromlist=[module_name])
58  return SetUnsignedFingerPrint(hash_module.UnsignedFingerPrint)
59
60
61def SetUnsignedFingerPrint(function_object):
62  """Sets grit.extern.FP.UnsignedFingerPrint to point to
63  function_object.
64
65  Returns the function object previously known as
66  grit.extern.FP.UnsignedFingerPrint.
67  """
68  global UnsignedFingerPrint
69  original_function_object = UnsignedFingerPrint
70  UnsignedFingerPrint = function_object
71  return original_function_object
72