/*
** 2001 September 15
**
** The author disclaims copyright to this source code.  In place of
** a legal notice, here is a blessing:
**
**    May you do good and not evil.
**    May you find forgiveness for yourself and forgive others.
**    May you share freely, never taking more than you give.
**
*************************************************************************
** This file contains code to implement a pseudo-random number
** generator (PRNG) for SQLite.
**
** Random numbers are used by some of the database backends in order
** to generate random integer keys for tables or random filenames.
**
** $Id: random.c,v 1.7 2001/09/23 19:46:52 drh Exp $
*/
#include "sqliteInt.h"
#include "os.h"

/*
** Get a single 8-bit random value from the RC4 PRNG.
*/
int sqliteRandomByte(sqlite *db){
  int t;

  /* Initialize the state of the random number generator once,
  ** the first time this routine is called.  The seed value does
  ** not need to contain a lot of randomness since we are not
  ** trying to do secure encryption or anything like that...
  **
  ** Nothing in this file or anywhere else in SQLite does any kind of
  ** encryption.  The RC4 algorithm is being used as a PRNG (pseudo-random
  ** number generator) not as an encryption device.
  */
  if( !db->prng.isInit ){
    int i;
    char k[256];
    db->prng.j = 0;
    db->prng.i = 0;
    sqliteOsRandomSeed(k);
    for(i=0; i<256; i++){
      db->prng.s[i] = i;
    }
    for(i=0; i<256; i++){
      int t;
      db->prng.j = (db->prng.j + db->prng.s[i] + k[i]) & 0xff;
      t = db->prng.s[db->prng.j];
      db->prng.s[db->prng.j] = db->prng.s[i];
      db->prng.s[i] = t;
    }
    db->prng.isInit = 1;
  }

  /* Generate and return single random byte
  */
  db->prng.i = (db->prng.i + 1) & 0xff;
  db->prng.j = (db->prng.j + db->prng.s[db->prng.i]) & 0xff;
  t = db->prng.s[db->prng.i];
  db->prng.s[db->prng.i] = db->prng.s[db->prng.j];
  db->prng.s[db->prng.j] = t;
  t = db->prng.s[db->prng.i] + db->prng.s[db->prng.j];
  return db->prng.s[t & 0xff];
}

/*
** Return a random 32-bit integer.  The integer is generated by making
** 4 calls to sqliteRandomByte().
*/
int sqliteRandomInteger(sqlite *db){
  int r;
  int i;
  r = sqliteRandomByte(db);
  for(i=1; i<4; i++){
    r = (r<<8) + sqliteRandomByte(db);
  }
  return r;
}
