/* ,file-id archive://[lord]/396/vu/./reserv.c/1998-05-18
*/
/*	Copyright (C) 1997 Tom Lord
 * 
 * This program is provided to you under the terms of the Liberty Software
 * License.  You are NOT permitted to redistribute, modify, or use it
 * except in very specific ways described by that license.
 *
 * This software comes with NO WARRANTY.
 * 
 * You should have received a copy of the Liberty Software License
 * along with this software; see the file =LICENSE.  If not, write to
 * the Tom Lord, 1810 Francisco St. #2, Berkeley CA, 94703, USA.  
 */



#include <errno.h>
#include "reserv.h"



static int * reserved  = 0;
static int * rflags = 0;

int
reserv (int * errn, int flags)
{
  int n_reserved;
  int x;
  int a;

  n_reserved = asize (reserved);
  for (x = 0; (x < n_reserved) && (reserved[x] >= 0); ++x)
    {
      if (rflags[reserved[x]] == flags)
	{
	  a = reserved[x];
	  reserved[x] = reserved[n_reserved - 1];
	  reserved[n_reserved - 1] = -1;
	  --n_reserved;
	  return a;
	}
    }

  a = open ("/dev/null", flags, 0);
  if (a >= 0)
    *((int *)aref (&rflags, a, sizeof (int))) = flags;
  else
    *errn = errno;

  return a;
}

void
unreserv (int fd)
{
  *((int *)aref (&reserved, asize (reserved), sizeof (int))) = fd;
}

