/* Release 3.10 */
/*-------------------------------------------------------------------------*
*                                                                          *
*  NEW.CPP - new implementations.                		           *
*                                                                          *
*  COPYRIGHT (C) 1989..1992 Clarion Software Corporation.                  *
*  All Rights Reserved                                                     *
*                                                                          *
*--------------------------------------------------------------------------*/

#include <clib.h>
#include <p_std.h>

#pragma module(init_prio=>22)

_STATIC void (*new_handler)(void);

#pragma save, call(reg_return=>(ax,bx))
void* operator new(unsigned size) {

  void *b;

  b=p_alloc(size);
  if((b == NULL) && (new_handler) && (size))
    new_handler();
  return b;
}
#pragma restore

void* operator new(unsigned, void *place) {

  return place;
}

void operator delete(void *p) {

  p_free(p);
}

void (* set_new_handler(void(*nh)()))() {

  void (* ret)();

  ret=new_handler;
  new_handler=nh;
  return ret;
}

extern "C" void * _vec_new( char * obj_ptr, unsigned n, unsigned siz, ctor_t ctor, unsigned vbnum) {

  unsigned *h;

  if (! obj_ptr) {
    h=(unsigned *)p_alloc(n * siz + sizeof(unsigned));
    if(h == NULL) {
      if(new_handler)
        new_handler();
      return NULL;
    }
    *h=n;
    obj_ptr= (char *)(h + 1);
  }

  if (ctor)
    _call_ctors(ctor, (char *) obj_ptr, vbnum, n, siz);

  return obj_ptr;
}

extern "C" void _vec_delete( char * obj_ptr, unsigned siz, dtor_t dtor, unsigned _free, unsigned vbnum, unsigned static_num)
  {
  unsigned n;
  unsigned *tmp;

  if (obj_ptr)
    {
    tmp = (unsigned *)obj_ptr-1;
    if(dtor)
      {
      if(_free)
        n=*tmp;
      else
        n=static_num;
      obj_ptr+=n*siz;
      _call_dtors(dtor,obj_ptr,vbnum,n,siz);
      }
    if(_free)
      p_free(tmp);
    }
  }
