Kuang-che Wu | fcbcc50 | 2020-06-01 11:48:20 +0800 | [diff] [blame] | 1 | # -*- coding: utf-8 -*- |
| 2 | # Copyright 2020 The Chromium OS 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 | """Cache mechanism to speed up heavy operations.""" |
| 6 | import functools |
| 7 | |
| 8 | |
| 9 | class Cache: |
| 10 | """A simple cache decorator with enable/disable control. |
| 11 | |
| 12 | Sample usage: |
| 13 | @Cache |
| 14 | def foo(x): |
| 15 | return ... |
| 16 | |
| 17 | @Cache.default_disabled |
| 18 | def bar(x): |
| 19 | return ... |
| 20 | |
| 21 | foo.disable_cache() |
| 22 | bar.enable_cache() |
| 23 | """ |
| 24 | |
| 25 | def __init__(self, func, enable=True): |
| 26 | self.wrapped = func |
| 27 | self.enabled = enable |
| 28 | self.data = {} |
| 29 | functools.update_wrapper(self, func) |
| 30 | |
| 31 | @staticmethod |
| 32 | def default_disabled(func): |
| 33 | return Cache(func, enable=False) |
| 34 | |
| 35 | def __call__(self, *args): |
| 36 | if not self.enabled: |
| 37 | return self.wrapped(*args) |
| 38 | |
| 39 | result = self.data.get(args) |
| 40 | if result is None: |
| 41 | result = self.wrapped(*args) |
| 42 | self.data[args] = result |
| 43 | return result |
| 44 | |
| 45 | def enable_cache(self): |
| 46 | self.enabled = True |
| 47 | |
| 48 | def disable_cache(self): |
| 49 | self.enabled = False |
| 50 | self.data = {} |