aboutsummaryrefslogtreecommitdiff
path: root/chapter/6/resources/code/counters/python/state-based-increment-and-decrement-counter-incorrect.py
blob: 6f0cbdeb404edd5c5b8a21662bfcebd2309d98ab (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
class CvRDT:
    pass

class Counter(CvRDT):

    def __init__(self, counts = None):  # constructor function
        if counts is None:
            self._counts = [0] * length(self.replicas())
        else:
            self._counts = counts

    def value(self):                    # query function
        return sum(self._counts)

    def counts(self):                   # query function
        return list(self._counts)       # return a clone

    def increment(self):                # update function
        self._counts[self.replicaId()] += 1

    def decrement(self):                # update function
        self._counts[self.replicaId()] -= 1

    def compare(self, other):           # comparison function
        return all(v1 <= v2 for (v1, v2) in
                   zip(self.counts(),
                       other.counts()))

    def merge(self, other):             # merge function
        return Counter(map(max, zip(self.counts(),
                                    other.counts())))