/*
 * libsal/skiplists/random.c
 * Random number support for skip lists
 * 
 * See libsal/license.h for licensing details.
 */

#include <libsal/skiplists/internal.h>
#include <libsal/license.h>
#include <libsal/proto.h>
#include <libsal/defines.h>
#include <libsal/types.h>

#include <stdlib.h>

static int iRandomsLeft;
static int iRandomBits;

int sal_skiplist_GetRandomLevel(void)
{
  int level = 0;
  int b;
  
  do
  {
    b = iRandomBits&3;
    if (!b) 
      level++;
    
    iRandomBits >>= 2;
    
    if (--iRandomsLeft == 0)
      sal_skiplist_SetRandomLevel();
    
  } while (!b);
  
  return (level>SAL_SKIPLIST_MAXLEVEL ? SAL_SKIPLIST_MAXLEVEL : level);
}

void sal_skiplist_SetRandomLevel(void)
{
  iRandomBits  = rand();
  iRandomsLeft = PRECISION_INT/2;
}
