\begin{code}
{-# LANGUAGE StrictData #-}
module Tox.Core.PingArray where
\end{code}

\chapter{Ping array}

Ping array is an array used in toxcore to store data for pings.  It enables the
storage of arbitrary data that can then be retrieved later by passing the 8
byte ping id that was returned when the data was stored.  It also frees data
from pings that are older than a ping expiring delay set when initializing the
array.

Ping arrays are initialized with a size and a timeout parameter.  The size
parameter denotes the maximum number of entries in the array and the timeout
denotes the number of seconds to keep an entry in the array.  Timeout and size
must be bigger than 0.

Adding an entry to the ping array will make it return an 8 byte number that can
be used as the ping number of a ping packet.  This number is generated by first
generating a random 8 byte number (toxcore uses the cryptographic secure random
number generator), dividing then multiplying it by the total size of the array
and then adding the index of the element that was added.  This generates a
random looking number that will return the index of the element that was added
to the array.  This number is also stored along with the added data and the
current time (to check for timeouts).  Data is added to the array in a cyclical
manner (0, 1, 2, 3... (array size - 1), 0, 1, ...).  If the array is full, the
oldest element is overwritten.

To get data from the ping array, the ping number is passed to the function to
get the data from the array.  The modulo of the ping number with the total size
of the array will return the index at which the data is.  If there is no data
stored at this index, the function returns an error.  The ping number is then
checked against the ping number stored for this element, if it is not equal the
function returns an error.  If the array element has timed out, the function
returns an error.  If all the checks succeed the function returns the exact
data that was stored and it is removed from the array.

Ping array is used in many places in toxcore to efficiently keep track of sent
packets.