Grove.Counter.PNCounter (Grove v0.1.1)

View Source

A positive-negative counter (PN-Counter) CRDT.

Supports both increment and decrement operations by maintaining two G-Counters: one for increments (P) and one for decrements (N). The value is P - N.

Delta-State Support

This CRDT supports delta-state replication for efficient synchronization:

  • delta/1 - Returns accumulated changes since last reset
  • reset_delta/1 - Clears the delta buffer after synchronization

Example

iex> counter = Grove.Counter.PNCounter.new(:node_a)
iex> counter = Grove.Counter.PNCounter.increment(counter, 10)
iex> counter = Grove.Counter.PNCounter.decrement(counter, 3)
iex> Grove.Counter.PNCounter.value(counter)
7

Summary

Functions

Decrements the counter by 1.

Decrements the counter by the given amount.

Returns the accumulated delta since the last reset.

Increments the counter by 1.

Increments the counter by the given amount.

Merges two PN-Counters.

Returns the total negative count.

Creates a new PN-Counter for the given actor.

Returns the total positive count.

Resets the delta buffer after synchronization.

Returns the current value of the counter (positive - negative).

Types

actor()

@type actor() :: term()

t()

@type t() :: %Grove.Counter.PNCounter{
  actor: actor(),
  negative: Grove.Counter.GCounter.t(),
  positive: Grove.Counter.GCounter.t()
}

Functions

decrement(counter)

@spec decrement(t()) :: t()

Decrements the counter by 1.

decrement(counter, amount)

@spec decrement(t(), non_neg_integer()) :: t()

Decrements the counter by the given amount.

delta(pn_counter)

@spec delta(t()) :: t()

Returns the accumulated delta since the last reset.

The delta contains only the changes made locally to both the positive and negative counters.

increment(counter)

@spec increment(t()) :: t()

Increments the counter by 1.

increment(counter, amount)

@spec increment(t(), non_neg_integer()) :: t()

Increments the counter by the given amount.

merge(counter1, counter2)

@spec merge(t(), t()) :: t()

Merges two PN-Counters.

negative_value(pn_counter)

@spec negative_value(t()) :: non_neg_integer()

Returns the total negative count.

new(actor)

@spec new(actor()) :: t()

Creates a new PN-Counter for the given actor.

positive_value(pn_counter)

@spec positive_value(t()) :: non_neg_integer()

Returns the total positive count.

reset_delta(counter)

@spec reset_delta(t()) :: t()

Resets the delta buffer after synchronization.

Call this after sending the delta to other replicas.

value(pn_counter)

@spec value(t()) :: integer()

Returns the current value of the counter (positive - negative).