예제 #1
0
void CudaVector<T>::Resize(size_t newSize)
{
	Reserve(newSize);
	size = newSize;
}
예제 #2
0
void String::Compact()
{
    if (capacity_)
        Reserve(length_ + 1);
}
예제 #3
0
파일: AStar.hpp 프로젝트: CnZoom/XcSoarPull
 /**
  * Default constructor
  *
  * @param is_min Whether this algorithm will search for min or max distance
  */
 AStar(unsigned reserve_default = DEFAULT_QUEUE_SIZE)
 {
   Reserve(reserve_default);
 }
예제 #4
0
파일: InsDel.c 프로젝트: mike2718/WinVi
void InsertChar(INT Char) {
	INT space = CharSize(Char);

	if (IsViewOnly()) return;
	SetUnsafe();
	if (Mode != ReplaceMode || (HexEditMode ? CharAt(&CurrPos) == C_EOF
											: CharFlags(CharAt(&CurrPos)) & 1))
		Reserve(&CurrPos, space, 0);
	else {
		INT oldspace = CharSize(CharAt(&CurrPos));

		if (space != oldspace) {
			Reserve(&CurrPos, -oldspace, 0);
			Reserve(&CurrPos, space, 0);
		} else {
			EnterDeleteForUndo(&CurrPos, oldspace, 0);
			EnterInsertForUndo(&CurrPos, space);
		}
		ByteAt(&CurrPos);
	}
	++InsertCount;
	if (!SuppressMap) switch (CharSet) {
		case CS_EBCDIC:
			if ((unsigned)Char >= 0x100) Char = 0x1a;
			else Char = MapAnsiToEbcdic[Char];
			break;

		case CS_OEM:
			Char = UnicodeToOemChar(Char);
			break;
	}
	assert(CurrPos.p->PageBuf);
	if (space > 1) {
		POSITION Pos = CurrPos;

		UnsafePage(&CurrPos);
		if (Char == C_CRLF) {
			if (UtfEncoding == 16) {
				assert((Pos.i & 1) == 0 && Pos.i + 1 < Pos.p->Fill);
				if (UtfLsbFirst) {
					Pos.p->PageBuf[Pos.i]	= '\r';
					Pos.p->PageBuf[Pos.i+1]	= '\0';
					Advance(&Pos, 2);
					Pos.p->PageBuf[Pos.i]	= '\n';
					Pos.p->PageBuf[Pos.i+1]	= '\0';
				} else {
					Pos.p->PageBuf[Pos.i]	= '\0';
					Pos.p->PageBuf[Pos.i+1]	= '\r';
					Advance(&Pos, 2);
					Pos.p->PageBuf[Pos.i]	= '\0';
					Pos.p->PageBuf[Pos.i+1]	= '\n';
				}
				assert(Pos.i + 1 < Pos.p->Fill);
			} else {
				Pos.p->PageBuf[Pos.i] = '\r';
				Advance(&Pos, 1);
				Pos.p->PageBuf[Pos.i] = '\n';
			}
		} else if (UtfEncoding == 16) {
			assert(Pos.i + 1 < Pos.p->Fill);
			if (UtfLsbFirst) {
				Pos.p->PageBuf[Pos.i]	= Char;
				Pos.p->PageBuf[Pos.i+1]	= Char >> 8;
			} else {
예제 #5
0
HawkOctets::HawkOctets(UInt32 iSize) : m_pBase(0),m_pHigh(0),m_iCap(0)
{
    Reserve(iSize);
}
예제 #6
0
파일: FlatQueue.hpp 프로젝트: denghe/69net
 void FlatQueue<T>::Emplace( PTS&& ...ps )
 {
     new ( buf + tail++ ) T( std::forward<PTS>( ps )... );
     if( tail == maxSize ) tail = 0;
     if( tail == head ) Reserve( maxSize + 1, true );
 }
예제 #7
0
void String::ReserveMore(size_t more_length)
{
    Reserve(GetLength() + more_length);
}
예제 #8
0
int TRI_AppendDoubleStringBuffer (TRI_string_buffer_t * self, double attr) {
  int res;

  // IEEE754 NaN values have an interesting property that we can exploit...
  // if the architecture does not use IEEE754 values then this shouldn't do
  // any harm either
  if (attr != attr) {
    return TRI_AppendStringStringBuffer(self, "NaN");
  }

  if (attr == HUGE_VAL) {
    return TRI_AppendStringStringBuffer(self, "inf");
  }
  if (attr == -HUGE_VAL) {
    return TRI_AppendStringStringBuffer(self, "-inf");
  }

  res = Reserve(self, 1);

  if (res != TRI_ERROR_NO_ERROR) {
    return res;
  }

  if (attr < 0.0) {
    AppendChar(self, '-');
    attr = -attr;
  }
  else if (attr == 0.0) {
    AppendChar(self, '0');
    return TRI_ERROR_NO_ERROR;
  }

  if (((double)((uint32_t) attr)) == attr) {
    return TRI_AppendUInt32StringBuffer(self, (uint32_t) attr);
  }
  else if (attr < (double) 429496U) {
    uint32_t smll;

    smll = (uint32_t)(attr * 10000.0);

    if (((double) smll) == attr * 10000.0) {
      uint32_t ep;

      TRI_AppendUInt32StringBuffer(self, smll / 10000);

      ep = smll % 10000;

      if (ep != 0) {
        size_t pos;
        char a1;
        char a2;
        char a3;
        char a4;

        pos = 0;

        res = Reserve(self, 6);

        if (res != TRI_ERROR_NO_ERROR) {
          return res;
        }

        AppendChar(self, '.');

        if ((ep / 1000L) % 10 != 0)  pos = 1;
        a1 = (char) ((ep / 1000L) % 10 + '0');

        if ((ep / 100L) % 10 != 0)  pos = 2;
        a2 = (char) ((ep / 100L) % 10 + '0');

        if ((ep / 10L) % 10 != 0)  pos = 3;
        a3 = (char) ((ep / 10L) % 10 + '0');

        if (ep % 10 != 0)  pos = 4;
        a4 = (char) (ep % 10 + '0');

        AppendChar(self, a1);
        if (pos > 1) { AppendChar(self, a2); }
        if (pos > 2) { AppendChar(self, a3); }
        if (pos > 3) { AppendChar(self, a4); }

      }

      return TRI_ERROR_NO_ERROR;
    }
  }

  // we do not habe a small integral number nor small decimal number with only a few decimal digits

  // there at most 16 significant digits, first find out if we have an integer value
  if (10000000000000000.0 < attr) {
    size_t n;

    n = 0;

    while (10000000000000000.0 < attr) {
      attr /= 10.0;
      ++n;
    }

    res = TRI_AppendUInt64StringBuffer(self, (uint64_t) attr);

    if (res != TRI_ERROR_NO_ERROR) {
      return res;
    }

    res = Reserve(self, n);

    if (res != TRI_ERROR_NO_ERROR) {
      return res;
    }

    for (;  0 < n;  --n) {
      AppendChar(self, '0');
    }

    return TRI_ERROR_NO_ERROR;
  }


  // very small, i. e. less than 1
  else if (attr < 1.0) {
    size_t n;

    n = 0;

    while (attr < 1.0) {
      attr *= 10.0;
      ++n;

      // should not happen, so it must be almost 0
      if (n > 400) {
        return TRI_AppendUInt32StringBuffer(self, 0);
      }
    }

    res = Reserve(self, n + 2);

    if (res != TRI_ERROR_NO_ERROR) {
      return res;
    }

    AppendChar(self, '0');
    AppendChar(self, '.');

    for (--n;  0 < n;  --n) {
      AppendChar(self, '0');
    }

    attr = 10000000000000000.0 * attr;

    return TRI_AppendUInt64StringBuffer(self, (uint64_t) attr);
  }


  // somewhere in between
  else {
    uint64_t m;
    double d;
    size_t n;

    m = (uint64_t) attr;
    d = attr - m;
    n = 0;

    TRI_AppendUInt64StringBuffer(self, m);

    while (d < 1.0) {
      d *= 10.0;
      ++n;

      // should not happen, so it must be almost 0
      if (n > 400) {
        return TRI_ERROR_NO_ERROR;
      }
    }

    res = Reserve(self, n + 1);

    if (res != TRI_ERROR_NO_ERROR) {
      return res;
    }

    AppendChar(self, '.');

    for (--n;  0 < n;  --n) {
      AppendChar(self, '0');
    }

    d = 10000000000000000.0 * d;

    return TRI_AppendUInt64StringBuffer(self, (uint64_t) d);
  }
}
예제 #9
0
int TRI_ReserveStringBuffer (TRI_string_buffer_t* self, const size_t length) {
  return Reserve(self, length);
}
예제 #10
0
 /**
  * Default constructor
  *
  * @param is_min Whether this algorithm will search for min or max distance
  */
 AStar(unsigned reserve_default = ASTAR_QUEUE_SIZE)
 {
   Reserve(reserve_default);
 }
예제 #11
0
 /**
  * Constructor
  *
  * @param n Node to start
  * @param is_min Whether this algorithm will search for min or max distance
  */
 AStar(const Node &node, unsigned reserve_default = ASTAR_QUEUE_SIZE)
 {
   Reserve(reserve_default);
   Push(node, node, AStarPriorityValue(0));
 }
예제 #12
0
//=============================================================================
//	eTape::ParseTZX
//-----------------------------------------------------------------------------
bool eTape::ParseTZX(const void* data, size_t data_size)
{
	byte* ptr = (byte*)data;
	CloseTape();
	dword size, pause, i, j, n, t, t0;
	byte pl, last, *end;
	byte* p;
	dword loop_n = 0, loop_p = 0;
	char nm[512];
	while(ptr < (const byte*)data + data_size)
	{
		switch(*ptr++)
		{
		case 0x10: // normal block
			AllocInfocell();
			size = Word(ptr + 2);
			pause = Word(ptr);
			ptr += 4;
			Desc(ptr, size, tapeinfo[tape_infosize].desc);
			tape_infosize++;
			MakeBlock(ptr, size, 2168, 667, 735, 855, 1710, (*ptr < 4) ? 8064
					: 3220, pause);
			ptr += size;
			break;
		case 0x11: // turbo block
			AllocInfocell();
			size = 0xFFFFFF & Dword(ptr + 0x0F);
			Desc(ptr + 0x12, size, tapeinfo[tape_infosize].desc);
			tape_infosize++;
			MakeBlock(ptr + 0x12, size, Word(ptr), Word(ptr + 2),
					Word(ptr + 4), Word(ptr + 6), Word(ptr + 8),
					Word(ptr + 10), Word(ptr + 13), ptr[12]);
			// todo: test used bits - ptr+12
			ptr += size + 0x12;
			break;
		case 0x12: // pure tone
			CreateAppendableBlock();
			pl = FindPulse(Word(ptr));
			n = Word(ptr + 2);
			Reserve(n);
			for(i = 0; i < n; i++)
				tape_image[tape_imagesize++] = pl;
			ptr += 4;
			break;
		case 0x13: // sequence of pulses of different lengths
			CreateAppendableBlock();
			n = *ptr++;
			Reserve(n);
			for(i = 0; i < n; i++, ptr += 2)
				tape_image[tape_imagesize++] = FindPulse(Word(ptr));
			break;
		case 0x14: // pure data block
			CreateAppendableBlock();
			size = 0xFFFFFF & Dword(ptr + 7);
			MakeBlock(ptr + 0x0A, size, 0, 0, 0, Word(ptr),
					Word(ptr + 2), -1, Word(ptr + 5), ptr[4]);
			ptr += size + 0x0A;
			break;
		case 0x15: // direct recording
			size = 0xFFFFFF & Dword(ptr + 5);
			t0 = Word(ptr);
			pause = Word(ptr + 2);
			last = ptr[4];
			NamedCell("direct recording");
			ptr += 8;
			pl = 0;
			n = 0;
			for(i = 0; i < size; i++) // count number of pulses
				for(j = 0x80; j; j >>= 1)
					if((ptr[i] ^ pl) & j)
						n++, pl ^= -1;
			t = 0;
			pl = 0;
			Reserve(n + 2);
			for(i = 1; i < size; i++, ptr++) // find pulses
				for(j = 0x80; j; j >>= 1)
				{
					t += t0;
					if((*ptr ^ pl) & j)
					{
						tape_image[tape_imagesize++] = FindPulse(t);
						pl ^= -1;
						t = 0;
					}
				}
			// find pulses - last byte
			for(j = 0x80; j != (byte)(0x80 >> last); j >>= 1)
			{
				t += t0;
				if((*ptr ^ pl) & j)
				{
					tape_image[tape_imagesize++] = FindPulse(t);
					pl ^= -1;
					t = 0;
				}
			}
			ptr++;
			tape_image[tape_imagesize++] = FindPulse(t); // last pulse ???
			if(pause)
				tape_image[tape_imagesize++] = FindPulse(pause * 3500);
			break;
		case 0x20: // pause (silence) or 'stop the tape' command
			pause = Word(ptr);
			sprintf(nm, pause ? "pause %d ms" : "stop the tape", pause);
			NamedCell(nm);
			Reserve(2);
			ptr += 2;
			if(!pause)
			{ // at least 1ms pulse as specified in TZX 1.13
				tape_image[tape_imagesize++] = FindPulse(3500);
				pause = -1;
			}
			else
				pause *= 3500;
			tape_image[tape_imagesize++] = FindPulse(pause);
			break;
		case 0x21: // group start
			n = *ptr++;
			NamedCell(ptr, n);
			ptr += n;
			appendable = 1;
			break;
		case 0x22: // group end
			break;
		case 0x23: // jump to block
			NamedCell("* jump");
			ptr += 2;
			break;
		case 0x24: // loop start
			loop_n = Word(ptr);
			loop_p = tape_imagesize;
			ptr += 2;
			break;
		case 0x25: // loop end
			if(!loop_n)
				break;
			size = tape_imagesize - loop_p;
			Reserve((loop_n - 1) * size);
			for(i = 1; i < loop_n; i++)
				memcpy(tape_image + loop_p + i * size, tape_image + loop_p,
						size);
			tape_imagesize += (loop_n - 1) * size;
			loop_n = 0;
			break;
		case 0x26: // call
			NamedCell("* call");
			ptr += 2 + 2 * Word(ptr);
			break;
		case 0x27: // ret
			NamedCell("* return");
			break;
		case 0x28: // select block
			sprintf(nm, "* choice: ");
			n = ptr[2];
			p = ptr + 3;
			for(i = 0; i < n; i++)
			{
				if(i)
					strcat(nm, " / ");
				char *q = nm + strlen(nm);
				size = *(p + 2);
				memcpy(q, p + 3, size);
				q[size] = 0;
				p += size + 3;
			}
			NamedCell(nm);
			ptr += 2 + Word(ptr);
			break;
		case 0x2A: // stop if 48k
			NamedCell("* stop if 48K");
			ptr += 4 + Dword(ptr);
			break;
		case 0x30: // text description
			n = *ptr++;
			NamedCell(ptr, n);
			ptr += n;
			appendable = 1;
			break;
		case 0x31: // message block
			NamedCell("- MESSAGE BLOCK ");
			end = ptr + 2 + ptr[1];
			pl = *end;
			*end = 0;
			for(p = ptr + 2; p < end; p++)
				if(*p == 0x0D)
					*p = 0;
			for(p = ptr + 2; p < end; p += strlen((char*)p) + 1)
				NamedCell(p);
			*end = pl;
			ptr = end;
			NamedCell("-");
			break;
		case 0x32: // archive info
			NamedCell("- ARCHIVE INFO ");
			p = ptr + 3;
			for(i = 0; i < ptr[2]; i++)
			{
				const char *info;
				switch(*p++)
				{
				case 0:
					info = "Title";
					break;
				case 1:
					info = "Publisher";
					break;
				case 2:
					info = "Author";
					break;
				case 3:
					info = "Year";
					break;
				case 4:
					info = "Language";
					break;
				case 5:
					info = "Type";
					break;
				case 6:
					info = "Price";
					break;
				case 7:
					info = "Protection";
					break;
				case 8:
					info = "Origin";
					break;
				case 0xFF:
					info = "Comment";
					break;
				default:
					info = "info";
					break;
				}
				dword size = *p + 1;
				char tmp = p[size];
				p[size] = 0;
				sprintf(nm, "%s: %s", info, p + 1);
				p[size] = tmp;
				p += size;
				NamedCell(nm);
			}
			NamedCell("-");
			ptr += 2 + Word(ptr);
			break;
		case 0x33: // hardware type
			ParseHardware(ptr);
			ptr += 1 + 3 * *ptr;
			break;
		case 0x34: // emulation info
			NamedCell("* emulation info");
			ptr += 8;
			break;
		case 0x35: // custom info
			if(!memcmp(ptr, "POKEs           ", 16))
			{
				NamedCell("- POKEs block ");
				NamedCell(ptr + 0x15, ptr[0x14]);
				p = ptr + 0x15 + ptr[0x14];
				n = *p++;
				for(i = 0; i < n; i++)
				{
					NamedCell(p + 1, *p);
					p += *p + 1;
					t = *p++;
					strcpy(nm, "POKE ");
					for(j = 0; j < t; j++)
					{
						sprintf(nm + strlen(nm), "%d,", Word(p + 1));
						sprintf(nm + strlen(nm), *p & 0x10 ? "nn" : "%d",
								*(byte*)(p + 3));
						if(!(*p & 0x08))
							sprintf(nm + strlen(nm), "(page %d)", *p & 7);
						strcat(nm, "; ");
						p += 5;
					}
					NamedCell(nm);
				}
				nm[0] = '-';
				nm[1] = 0;
				nm[2] = 0;
				nm[3] = 0;
			}
			else
				sprintf(nm, "* custom info: %s", ptr), nm[15 + 16] = 0;
			NamedCell(nm);
			ptr += 0x14 + Dword(ptr + 0x10);
			break;
		case 0x40: // snapshot
			NamedCell("* snapshot");
			ptr += 4 + (0xFFFFFF & Dword(ptr + 1));
			break;
		case 0x5A: // 'Z'
			ptr += 9;
			break;
		default:
			ptr += data_size;
		}
	}
	for(i = 0; i < tape_infosize; i++)
	{
		if(tapeinfo[i].desc[0] == '*' && tapeinfo[i].desc[1] == ' ')
			strcat(tapeinfo[i].desc, " [UNSUPPORTED]");
		if(*tapeinfo[i].desc == '-')
			while(strlen(tapeinfo[i].desc) < sizeof(tapeinfo[i].desc) - 1)
				strcat(tapeinfo[i].desc, "-");
	}
	if(tape_imagesize && tape_pulse[tape_image[tape_imagesize - 1]] < 350000)
		Reserve(1), tape_image[tape_imagesize++] = FindPulse(350000); // small pause [rqd for 3ddeathchase]
	FindTapeSizes();
	return (ptr == (const byte*)data + data_size);
}
예제 #13
0
파일: List.hpp 프로젝트: denghe/69net
 T& List<T>::Emplace( PTS&& ...ps )
 {
     if( size == maxSize ) Reserve( size + 1 );
     return *new ( buf + size++ ) T( std::forward<PTS>( ps )... );
 }
예제 #14
0
파일: db_vmint.c 프로젝트: bihai/pico-basic
/* Execute - execute the main code */
int Execute(System *sys, ObjHeap *heap, VMHANDLE main)
{
    size_t stackSize;
    Interpreter *i;
    VMVALUE tmp, tmp2, ind;
    VMHANDLE obj, htmp;
    int8_t tmpb;

    /* allocate the interpreter state */
    if (!(i = (Interpreter *)AllocateFreeSpace(sys, sizeof(Interpreter))))
        return VMFALSE;

    /* make sure there is space left for the stack */
    if ((stackSize = (sys->freeTop - sys->freeNext) / sizeof(VMVALUE)) <= 0)
        return VMFALSE;
        
    /* setup the heap before/after compact functions */
    heap->beforeCompact = NULL;
    heap->afterCompact = AfterCompact;
    heap->compactCookie = i;
    
    /* initialize the interpreter state */
    i->sys = sys;
    i->heap = heap;
    i->stack = (VMVALUE *)((uint8_t *)i + sizeof(Interpreter));
    i->stackTop = i->stack + stackSize;
    
    /* setup to execute the main function */
    i->code = main;
    ObjAddRef(i->code);
    i->cbase = i->pc = GetCodePtr(main);
    i->sp = i->fp = i->stackTop;
    i->hsp = i->hfp = (VMHANDLE *)i->stack - 1;

    if (setjmp(i->sys->errorTarget)) {
        while (i->hsp > (VMHANDLE *)i->stack)
            ObjRelease(i->heap, PopH(i));
        ObjRelease(i->heap, i->code);
        return VMFALSE;
    }

    for (;;) {
#if 0
        ShowStack(i);
        DecodeInstruction(0, 0, i->pc);
#endif
        switch (VMCODEBYTE(i->pc++)) {
        case OP_HALT:
            return VMTRUE;
        case OP_BRT:
            get_VMVALUE(tmp, VMCODEBYTE(i->pc++));
            if (Pop(i))
                i->pc += tmp;
            break;
        case OP_BRTSC:
            get_VMVALUE(tmp, VMCODEBYTE(i->pc++));
            if (*i->sp)
                i->pc += tmp;
            else
                Drop(i, 1);
            break;
        case OP_BRF:
            get_VMVALUE(tmp, VMCODEBYTE(i->pc++));
            if (!Pop(i))
                i->pc += tmp;
            break;
        case OP_BRFSC:
            get_VMVALUE(tmp, VMCODEBYTE(i->pc++));
            if (!*i->sp)
                i->pc += tmp;
            else
                Drop(i, 1);
            break;
        case OP_BR:
            get_VMVALUE(tmp, VMCODEBYTE(i->pc++));
            i->pc += tmp;
            break;
        case OP_NOT:
            *i->sp = (*i->sp ? VMFALSE : VMTRUE);
            break;
        case OP_NEG:
            *i->sp = -*i->sp;
            break;
        case OP_ADD:
            tmp = Pop(i);
            *i->sp += tmp;
            break;
        case OP_SUB:
            tmp = Pop(i);
            *i->sp -= tmp;
            break;
        case OP_MUL:
            tmp = Pop(i);
            *i->sp *= tmp;
            break;
        case OP_DIV:
            tmp = Pop(i);
            *i->sp = (tmp == 0 ? 0 : *i->sp / tmp);
            break;
        case OP_REM:
            tmp = Pop(i);
            *i->sp = (tmp == 0 ? 0 : *i->sp % tmp);
            break;
        case OP_CAT:
            StringCat(i);
            break;
        case OP_BNOT:
            *i->sp = ~*i->sp;
            break;
        case OP_BAND:
            tmp = Pop(i);
            *i->sp &= tmp;
            break;
        case OP_BOR:
            tmp = Pop(i);
            *i->sp |= tmp;
            break;
        case OP_BXOR:
            tmp = Pop(i);
            *i->sp ^= tmp;
            break;
        case OP_SHL:
            tmp = Pop(i);
            *i->sp <<= tmp;
            break;
        case OP_SHR:
            tmp = Pop(i);
            *i->sp >>= tmp;
            break;
        case OP_LT:
            tmp = Pop(i);
            *i->sp = (*i->sp < tmp ? VMTRUE : VMFALSE);
            break;
        case OP_LE:
            tmp = Pop(i);
            *i->sp = (*i->sp <= tmp ? VMTRUE : VMFALSE);
            break;
        case OP_EQ:
            tmp = Pop(i);
            *i->sp = (*i->sp == tmp ? VMTRUE : VMFALSE);
            break;
        case OP_NE:
            tmp = Pop(i);
            *i->sp = (*i->sp != tmp ? VMTRUE : VMFALSE);
            break;
        case OP_GE:
            tmp = Pop(i);
            *i->sp = (*i->sp >= tmp ? VMTRUE : VMFALSE);
            break;
        case OP_GT:
            tmp = Pop(i);
            *i->sp = (*i->sp > tmp ? VMTRUE : VMFALSE);
            break;
        case OP_LIT:
            get_VMVALUE(tmp, VMCODEBYTE(i->pc++));
            CPush(i, tmp);
            break;
        case OP_GREF:
            get_VMVALUE(tmp, VMCODEBYTE(i->pc++));
            obj = (VMHANDLE)tmp;
            CPush(i, GetSymbolPtr(obj)->v.iValue);
            break;
        case OP_GSET:
            get_VMVALUE(tmp, VMCODEBYTE(i->pc++));
            obj = (VMHANDLE)tmp;
            GetSymbolPtr(obj)->v.iValue = Pop(i);
            break;
        case OP_LREF:
            tmpb = (int8_t)VMCODEBYTE(i->pc++);
            CPush(i, i->fp[(int)tmpb]);
            break;
        case OP_LSET:
            tmpb = (int8_t)VMCODEBYTE(i->pc++);
            i->fp[(int)tmpb] = Pop(i);
            break;
        case OP_VREF:
            ind = *i->sp;
            obj = *i->hsp;
            if (ind < 0 || ind >= GetHeapObjSize(obj))
                Abort(i->sys, str_subscript_err, ind);
            *i->sp = GetIntegerVectorBase(obj)[ind];
            DropH(i, 1);
            break;
        case OP_VSET:
            tmp2 = Pop(i);
            ind = Pop(i);
            obj = *i->hsp;
            if (ind < 0 || ind >= GetHeapObjSize(obj))
                Abort(i->sys, str_subscript_err, ind);
            GetIntegerVectorBase(obj)[ind] = tmp2;
            DropH(i, 1);
            break;
       case OP_LITH:
            get_VMVALUE(tmp, VMCODEBYTE(i->pc++));
            CPushH(i, (VMHANDLE)tmp);
            ObjAddRef(*i->hsp);
            break;
        case OP_GREFH:
            get_VMVALUE(tmp, VMCODEBYTE(i->pc++));
            CPushH(i, GetSymbolPtr((VMHANDLE)tmp)->v.hValue);
            ObjAddRef(*i->hsp);
            break;
        case OP_GSETH:
            get_VMVALUE(tmp, VMCODEBYTE(i->pc++));
            ObjRelease(i->heap, GetSymbolPtr((VMHANDLE)tmp)->v.hValue);
            GetSymbolPtr((VMHANDLE)tmp)->v.hValue = PopH(i);
            break;
        case OP_LREFH:
            tmpb = (int8_t)VMCODEBYTE(i->pc++);
            CPushH(i, i->hfp[(int)tmpb]);
            ObjAddRef(*i->hsp);
            break;
        case OP_LSETH:
            tmpb = (int8_t)VMCODEBYTE(i->pc++);
            ObjRelease(i->heap, i->hfp[(int)tmpb]);
            i->hfp[(int)tmpb] = PopH(i);
            break;
        case OP_VREFH:
            ind = Pop(i);
            obj = *i->hsp;
            if (ind < 0 || ind >= GetHeapObjSize(obj))
                Abort(i->sys, str_subscript_err, ind);
            *i->hsp = GetStringVectorBase(obj)[ind];
            ObjAddRef(*i->hsp);
            break;
        case OP_VSETH:
            htmp = PopH(i);
            ind = Pop(i);
            obj = *i->hsp;
            if (ind < 0 || ind >= GetHeapObjSize(obj))
                Abort(i->sys, str_subscript_err, ind);
            ObjRelease(i->heap, GetStringVectorBase(obj)[ind]);
            GetStringVectorBase(obj)[ind] = htmp;
            DropH(i, 1);
            break;
        case OP_RESERVE:
            tmp = VMCODEBYTE(i->pc++);
            tmp2 = VMCODEBYTE(i->pc++);
            Reserve(i, tmp);
            ReserveH(i, tmp2);
            break;
         case OP_CALL:
            StartCode(i);
            break;
        case OP_RETURN:
            tmp = *i->sp;
            PopFrame(i);
            Push(i, tmp);
            break;
        case OP_RETURNH:
            htmp = *i->hsp;
            PopFrame(i);
            PushH(i, htmp);
            break;
        case OP_RETURNV:
            PopFrame(i);
            break;
        case OP_DROP:
            Drop(i, 1);
            break;
        case OP_DROPH:
            ObjRelease(i->heap, *i->hsp);
            DropH(i, 1);
            break;
        default:
            Abort(i->sys, str_opcode_err, VMCODEBYTE(i->pc - 1));
            break;
        }
    }
}
예제 #15
0
 namespace internal
 {
         const std::function<rapidjsonValue_ptr(const IReader* obj,Allocator& allocator)>vectorConverter
         = [](const IReader* obj,Allocator& allocator)
         {
             const auto value = static_cast<const ReaderVector*>(obj);
             auto valueResult = rapidjsonValue_ptr(new rapidjsonValue(rapidjson::Type::kArrayType));
             valueResult->Reserve((rapidjson::SizeType)value->size(), allocator);
             for (auto it = value->begin(), end = value->end(); it != end; ++it)
             {
                 auto element = *it;
                 auto elementResult = convert(element, allocator);
                 valueResult->PushBack(*elementResult, allocator);
             }
             return valueResult;
         };
     
     
     const std::function<rapidjsonValue_ptr(const IReader* obj,Allocator& allocator)>mapConverter
     = [](const IReader* obj,Allocator& allocator)
     {
         const auto value = static_cast<const ReaderMap*>(obj);
         auto valueResult = rapidjsonValue_ptr(new rapidjsonValue(rapidjson::Type::kObjectType));
         //valueResult->Reserve((rapidjson::SizeType)value->size(), allocator);
         for (auto it = value->begin(), end = value->end(); it != end; ++it)
         {
             auto element = it->second;
             auto elementResult = convert(element, allocator);
             valueResult->AddMember(it->first.c_str(), *elementResult, allocator);
         }
         return valueResult;
     };
     
     const std::function<rapidjsonValue_ptr(const IReader* obj,Allocator& allocator)> stringConverter
     = [](const IReader* obj,Allocator& allocator)
     {
         const auto value = static_cast<const ReaderString*>(obj);
         auto valueResult = rapidjsonValue_ptr(new rapidjsonValue());
         valueResult->SetString(value->getValue().data(), static_cast<rapidjson::SizeType>(value->getValue().length()), allocator);
         return valueResult;
     };
     
 
     const std::array<std::function<rapidjsonValue_ptr(const IReader* obj,Allocator& allocator)>,(int)InternalType::STRING64+1> typeConverter =
     {
         [](const IReader* /*obj*/,Allocator& /*allocator*/)
         {
             auto value = rapidjsonValue_ptr(new rapidjsonValue());
             value->SetNull();
             return value;
         },
         //ints
         [](const IReader* obj,Allocator& /*allocator*/)
         {
             const auto value = static_cast<const ReaderInt8*>(obj);
             return rapidjsonValue_ptr(new rapidjsonValue(value->getValue()));
         }
         ,
         [](const IReader* obj,Allocator& /*allocator*/)
         {
             const auto value = static_cast<const ReaderInt16*>(obj);
             return rapidjsonValue_ptr(new rapidjsonValue(value->getValue()));
         }
         ,
         [](const IReader* obj,Allocator& /*allocator*/)
         {
             const auto value = static_cast<const ReaderInt32*>(obj);
             return rapidjsonValue_ptr(new rapidjsonValue(value->getValue()));
         }
         ,
         [](const IReader* obj,Allocator& /*allocator*/)
         {
             const auto value = static_cast<const ReaderInt64*>(obj);
             return rapidjsonValue_ptr(new rapidjsonValue(value->getValue()));
         },
         //uints
         [](const IReader* obj,Allocator& /*allocator*/)
         {
             const auto value = static_cast<const ReaderUInt8*>(obj);
             return rapidjsonValue_ptr(new rapidjsonValue(value->getValue()));
         }
         ,
         [](const IReader* obj,Allocator& /*allocator*/)
         {
             const auto value = static_cast<const ReaderUInt16*>(obj);
             return rapidjsonValue_ptr(new rapidjsonValue(value->getValue()));
         }
         ,
         [](const IReader* obj,Allocator& /*allocator*/)
         {
             const auto value = static_cast<const ReaderUInt32*>(obj);
             return rapidjsonValue_ptr(new rapidjsonValue(value->getValue()));
         }
         ,
         [](const IReader* obj,Allocator& /*allocator*/)
         {
             const auto value = static_cast<const ReaderUInt64*>(obj);
             return rapidjsonValue_ptr(new rapidjsonValue(value->getValue()));
         },
         //float
         [](const IReader* obj,Allocator& /*allocator*/)
         {
             const auto value = static_cast<const ReaderFloat*>(obj);
             return rapidjsonValue_ptr(new rapidjsonValue(value->getValue()));
         },
         //double
         [](const IReader* obj,Allocator& /*allocator*/)
         {
             const auto value = static_cast<const ReaderDouble*>(obj);
             return rapidjsonValue_ptr(new rapidjsonValue(value->getValue()));
         },
         //bool
         [](const IReader* obj,Allocator& /*allocator*/)
         {
             const auto value = static_cast<const ReaderBool*>(obj);
             return rapidjsonValue_ptr(new rapidjsonValue(value->getValue()));
         },
         //vector
         vectorConverter,
         vectorConverter,
         vectorConverter,
         vectorConverter,
         //map
         mapConverter,
         mapConverter,
         mapConverter,
         mapConverter,
         //string
         stringConverter,
         stringConverter,
         stringConverter,
         stringConverter
     };
 }
예제 #16
0
파일: OldPool.cpp 프로젝트: denghe/69net
 void OldPool::Reserve( int capacity )
 {
     while( items.Size() < capacity ) Reserve();
 }
예제 #17
0
파일: FlatQueue.hpp 프로젝트: denghe/69net
 void FlatQueue<T>::Push( VT&& v )
 {
     new ( buf + tail++ ) T( std::forward<VT>( v ) );
     if( tail == maxSize ) tail = 0;
     if( tail == head ) Reserve( maxSize + 1, true );
 }
예제 #18
0
파일: OldPool.cpp 프로젝트: denghe/69net
 void* OldPool::Alloc()
 {
     if( items.Size() == 0 ) Reserve();
     return items.TopPop();
 }
예제 #19
0
// TODO: UTF-16対応
bool CTuningSpaceList::LoadFromFile(LPCTSTR pszFileName)
{
	static const LONGLONG MAX_FILE_SIZE=8LL*1024*1024;

	HANDLE hFile;
	LARGE_INTEGER FileSize;
	DWORD Read;
	char *pszFile,*p;

	hFile=::CreateFile(pszFileName,GENERIC_READ,FILE_SHARE_READ,NULL,
					   OPEN_EXISTING,FILE_ATTRIBUTE_NORMAL,NULL);
	if (hFile==INVALID_HANDLE_VALUE)
		return false;
	if (!::GetFileSizeEx(hFile,&FileSize)
			|| FileSize.QuadPart<1
			|| FileSize.QuadPart>MAX_FILE_SIZE) {
		::CloseHandle(hFile);
		return false;
	}
	pszFile=new char[FileSize.LowPart+1];
	if (!::ReadFile(hFile,pszFile,FileSize.LowPart,&Read,NULL) || Read!=FileSize.LowPart) {
		delete [] pszFile;
		::CloseHandle(hFile);
		return false;
	}
	pszFile[FileSize.LowPart]='\0';
	::CloseHandle(hFile);

	m_AllChannelList.Clear();
	p=pszFile;

	do {
		TCHAR szName[MAX_CHANNEL_NAME];
		int Space,Channel,ControlKey,ServiceType,ServiceID,NetworkID,TransportStreamID;
		bool fEnabled;

		while (*p=='\r' || *p=='\n' || *p==' ' || *p=='\t')
			p++;
		if (*p=='#' || *p==';') {	// コメント
			p++;
			if (*p=='#') {
				p++;
				if (::strnicmp(p,"space(",6)==0) {
					// チューニング空間名 #space(インデックス,名前)
					p+=6;
					SkipSpaces(&p);
					if (IsDigit(*p)) {
						Space=ParseDigits(&p);
						SkipSpaces(&p);
						if (Space>=0 && Space<10 && *p==',') {
							int i;

							p++;
							SkipSpaces(&p);
							for (i=0;p[i]!=')' && p[i]!='\0' && p[i]!='\r' && p[i]!='\n';i++);
							if (p[i]==')' && p[i+1]==')')
								i++;
							if (i>0) {
#ifdef UNICODE
								szName[::MultiByteToWideChar(CP_ACP,0,p,i,szName,lengthof(szName)-1)]='\0';
#else
								::lstrcpyn(szName,p,min(i+1,lengthof(szName)));
#endif
								if ((int)m_TuningSpaceList.size()<=Space) {
									Reserve(Space+1);
									m_TuningSpaceList[Space]->SetName(szName);
								}
								p+=i;
								if (*p=='\0')
									break;
								p++;
							}
						}
					}
				}
			}
			goto Next;
		}
		if (*p=='\0')
			break;

		// チャンネル名
		char cName[MAX_CHANNEL_NAME*2];
		int NameLength=0;
		bool fTruncate=false;
		bool fQuote=false;
		if (*p=='"') {
			fQuote=true;
			p++;
		}
		while (*p!='\0') {
			if (fQuote) {
				if (*p=='"') {
					p++;
					if (*p!='"') {
						SkipSpaces(&p);
						break;
					}
				}
			} else {
				if (*p==',')
					break;
			}
			if (::IsDBCSLeadByteEx(CP_ACP,*p)) {
				if (*(p+1)=='\0') {
					p++;
					break;
				}
				if (NameLength<lengthof(cName)-2) {
					cName[NameLength++]=*p;
					cName[NameLength++]=*(p+1);
				} else {
					fTruncate=true;
				}
				p+=2;
			} else {
				if (!fTruncate && NameLength<lengthof(cName)-1) {
					cName[NameLength++]=*p;
				}
				p++;
			}
		}
		if (*p!=',')
			goto Next;
		p++;
		SkipSpaces(&p);
		cName[NameLength]='\0';
#ifdef UNICODE
		::MultiByteToWideChar(CP_ACP,0,cName,-1,szName,MAX_CHANNEL_NAME);
#else
		::lstrcpynA(szName,cName,MAX_CHANNEL_NAME);
#endif

		// チューニング空間
		if (!IsDigit(*p))
			goto Next;
		Space=ParseDigits(&p);
		SkipSpaces(&p);
		if (*p!=',')
			goto Next;
		p++;
		SkipSpaces(&p);

		// チャンネル
		if (!IsDigit(*p))
			goto Next;
		Channel=ParseDigits(&p);
		SkipSpaces(&p);

		ControlKey=0;
		ServiceType=0;
		ServiceID=0;
		NetworkID=0;
		TransportStreamID=0;
		fEnabled=true;

		if (*p==',') {
			p++;
			// リモコン番号(オプション)
			ControlKey=ParseDigits(&p);
			SkipSpaces(&p);
			if (*p==',') {
				// サービスタイプ(オプション)
				p++;
				ServiceType=ParseDigits(&p);
				SkipSpaces(&p);
				if (*p==',') {
					// サービスID(オプション)
					p++;
					ServiceID=ParseDigits(&p);
					SkipSpaces(&p);
					if (*p==',') {
						// ネットワークID(オプション)
						p++;
						NetworkID=ParseDigits(&p);
						SkipSpaces(&p);
						if (*p==',') {
							// トランスポートストリームID(オプション)
							p++;
							TransportStreamID=ParseDigits(&p);
							SkipSpaces(&p);
							if (*p==',') {
								// 有効状態(オプション)
								p++;
								SkipSpaces(&p);
								if (IsDigit(*p)) {
									int Value=ParseDigits(&p);
									fEnabled=(Value&1)!=0;
								}
							}
						}
					}
				}
			}
		}
		{
			CChannelInfo ChInfo(Space,Channel,ControlKey,szName);
			if (ServiceID!=0)
				ChInfo.SetServiceID(ServiceID);
			if (NetworkID!=0)
				ChInfo.SetNetworkID(NetworkID);
			if (TransportStreamID!=0)
				ChInfo.SetTransportStreamID(TransportStreamID);
			if (ServiceType!=0)
				ChInfo.SetServiceType(ServiceType);
			if (!fEnabled)
				ChInfo.Enable(false);
			m_AllChannelList.AddChannel(ChInfo);
		}

	Next:
		while (*p!='\r' && *p!='\n' && *p!='\0')
			p++;
	} while (*p!='\0');

	delete [] pszFile;

	return MakeTuningSpaceList(&m_AllChannelList);
}
예제 #20
0
HBTInt OctTree_t::Build(const Snapshot_t &snapshot, HBTInt num_part)
/* build tree for a snapshot (or SnapshotView); automatically resize memory if necessary.
  * if num_part>0 is given, then only use the first num_part particles in the snapshot*/
{
	HBTInt NumNids,numnodes;
	HBTInt sub,subid,i,j,nodeid;
	double center[3], lenhalf;
	double xmin[3], xmax[3],Center[3], Len,Lenhalf;

	if(!num_part) num_part=snapshot.size();
	if(num_part>MaxNumberOfParticles)
	{
	  Clear();
	  Reserve(num_part);
	}
	
	NumberOfParticles=num_part;
	Snapshot=&snapshot;
	
	/* find enclosing rectangle */
  for(j = 0; j < 3; j++)
    xmin[j] = xmax[j] = Snapshot->GetComovingPosition(0)[j];

  for(i = 1; i < NumberOfParticles; i++)
    for(j = 0; j < 3; j++)
      {
	if(Snapshot->GetComovingPosition(i)[j] > xmax[j])
	  xmax[j] = Snapshot->GetComovingPosition(i)[j];
	else if(Snapshot->GetComovingPosition(i)[j] < xmin[j])
	  xmin[j] = Snapshot->GetComovingPosition(i)[j];
      }

  /* determine maxmimum extension */
  for(j = 1, Len = xmax[0] - xmin[0]; j < 3; j++)
    if((xmax[j] - xmin[j]) > Len)
      Len = xmax[j] - xmin[j];

  for(j = 0; j < 3; j++)
    Center[j] = 0.5 * (xmax[j] + xmin[j]);
  
  Lenhalf=0.5*Len;
MaxNodeId=MaxNumberOfCells+NumberOfParticles;

Nodes= Cells-NumberOfParticles;	/* select first node */


nodeid = NumberOfParticles;	/* id used to distinguish whether it's internal node or particle*/
NumNids=NumberOfParticles+1;	
	/* create an empty  root node  */
  for(i = 0; i < 8; i++)
Cells->sons[i] = -1;

  for(i = 0; i < NumberOfParticles; i++)	/* insert all  particles */
	{
	  nodeid = NumberOfParticles ;	/* select index of first node in tree */
	    lenhalf = Lenhalf;
	  for(j = 0; j < 3; j++)
	    center[j] = Center[j];

	  while(1)
		{
			  //len = lenhalf;
			//fprintf(logfile,"%f\n",len);
			  lenhalf *= 0.5;//halflen for the to-be-found subnode
			  sub = 0;
	      if(Snapshot->GetComovingPosition(i)[0] > center[0])
		{
		  center[0] += lenhalf;//subcenter
		  sub += 1;//sub index
		}
	      else
		{
		  center[0] -= lenhalf;
		}
	      if(Snapshot->GetComovingPosition(i)[1] > center[1])
		{
		  center[1] += lenhalf;
		  sub += 2;
		}
	      else
		{
		  center[1] -= lenhalf;
		}
	      if(Snapshot->GetComovingPosition(i)[2] > center[2])
		{
		  center[2] += lenhalf;
		  sub += 4;
		}
	      else
		{
		  center[2] -= lenhalf;
		}
		
		subid=Nodes[nodeid].sons[sub];
		if(subid<0)//an empty node, insert particle as leaf
			{
			Nodes[nodeid].sons[sub]=i;
			break;//finished for this particle, begin to insert a new particle
			}
		else if(subid<NumberOfParticles)//a particle node, upgrade the node to internal
			{
			Nodes[nodeid].sons[sub]=NumNids;//create a new node;
			nodeid=NumNids;//take over the new nodeid
			NumNids++;
			if(NumNids >= MaxNodeId)
			{
			  stringstream msg;
			  msg<<"maximum number "<<MaxNumberOfCells<<" of tree-nodes reached for particle "<<i;
			  throw OctTreeExceeded_t(msg.str());
			}
			for(sub=0;sub<8;sub++)//initialize new node
				Nodes[nodeid].sons[sub]=-1;
			/*insert that subid into this new node*/
			//what if the two particles are too near? 
			//unnecessary to divide too fine, just get rid of one by random insertion. 
			 if(lenhalf < HBTConfig.TreeNodeResolutionHalf)
				{
				/* seems like we're dealing with particles   
				* at identical locations. randomize 
				* sub index (well below gravitational softening scale).
				* to introduce some ambiguity so that we don't get jammed!*/
				sub = (HBTInt) (8.0 * drand48());
				if(sub >= 8)
				sub = 7;
				//~ fprintf(logfile,"len=%g Len=%g sub=%d  i=%d (%g|%g|%g)\n",
					//~ lenhalf*2, Len, sub, i, Snapshot->GetComovingPosition(i][0], Snapshot->GetComovingPosition(i][1], Snapshot->GetComovingPosition(i][2]);
				}
			 else
				{
				sub=0;
				if(Snapshot->GetComovingPosition(subid)[0] > center[0])
					sub += 1;
				if(Snapshot->GetComovingPosition(subid)[1] > center[1])
					sub += 2;
				if(Snapshot->GetComovingPosition(subid)[2] > center[2])
					sub += 4;
				}	
			Nodes[nodeid].sons[sub]=subid;//the disturbing particle inserted
			}
		else nodeid=subid;//an internal node,take over it;
		}
	}
	
	numnodes=NumNids-NumberOfParticles;
	//~ FilledFraction=(HBTReal)numnodes/MaxNumberOfCells;
	//~ #pragma omp critical
	//~ if(FilledFraction>MaxNodeFilledFraction) MaxNodeFilledFraction=FilledFraction;
	//~ fprintf(logfile,"used %d nodes out of allocated %d. (filled fraction %g)\n",
	 //~ numnodes, MaxNumberOfCells, (double)numnodes / MaxNumberOfCells);	
	/* finished inserting, now update for walk*/
	UpdateInternalNodes(NumberOfParticles , -1, Len);/*insert sibling and next infomation*/
	
	return numnodes; 
}
예제 #21
0
DynamicQueue<TX>::~DynamicQueue() {
   // Destructor
   Reserve(0);                                   // De-allocate buffer
}
예제 #22
0
// This function gets executed in each thread
void *startFunction(void *socketnumber)
{
	int s = *(int *)socketnumber;	
	char message[1000];
	
	//Send ACCEPTED to client acknowledge the client about the connection.
	strcpy(message, "ACCEPTED");
    send(s , message , strlen(message),0);

    int r;
    char query[1000];
    //Wait for client query.....
    while( (r = recv(s , query , 1000 , 0)) > 0 )
    {

    	//SEARCH for search, INSERT for insert, ISSUE for issue, RENEW for renew, RESERVE for reserve, EXIT for exit. 
    	if (query[0] == '1')
    	{
            //If writer is greater than 0 then donot allow any readers to enter.
            while(writers>0);
            readers++;
    		send(s, "1", strlen("1"),0);
    		//Receive Book Name in 
    		r = recv(s,query,1000,0);
            query[r] = '\0';
    		if (r==0 || r==-1)
    		{
    			break;
    		}
    		Search(query, message, myLibrary,nbooks);
            send(s,message,strlen(message),0);
            readers--;
    	}
    	else if (query[0] == '2')
    	{
            writers++;
            int thisWriter = turns++;
            //Wait for all the earliar readers to finish
            while(readers>0 || turn != thisWriter);//Do Nothing
    		send(s, "1", strlen("1"),0);
    		r = recv(s,query,1000,0);
            query[r] = '\0';
    		if (r==0 || r==-1)
    		{
    			break;
    		}
    		myLibrary = Insert(query,myLibrary,nbooks);
            send(s,"1",strlen("1"),0);
            writers--;
            turn++;
    	}
    	else if (query[0] == '3')
    	{
    		send(s, "1", strlen("1"),0);
    		r = recv(s,query,1000,0);
    		if (r==0 || r==-1)
    		{
    			break;
    		}
    		int result = Issue(atoi(query),message,myLibrary,nbooks);            
            send(s,message,strlen(message),0);
    	}
    	else if (query[0] == '4')
    	{
    		send(s, "1", strlen("1"),0);
    		r = recv(s,query,1000,0);
    		if (r==0 || r==-1)
    		{
    			break;
    		}
    		int result = Renew(atoi(query),message,myLibrary,nbooks);
            send(s,message,strlen(message),0);
    	}
    	else if (query[0] == '5')
    	{
    		send(s, "1", strlen("1"),0);
    		r = recv(s,query,1000,0);
    		if (r==0 || r==-1)
    		{
    			break;
    		}
    		int result = Reserve(atoi(query),message,myLibrary,nbooks);
            send(s,message,strlen(message),0);
    	}
    	else if (query[0] == '6')
    	{
            writers++;
            int thisWriter = turns++;
            send(s, "1", strlen("1"),0);
            int result = Exit(myLibrary,nbooks);
        }
        else if (query[0] == '7')
        {
            break;
        }
    }
     
    if(r == 0)
    {
        printf("Client %d disconnected\n",s );
    }
    else if(r == -1)
    {
        printf("Receive Failed from clien %d",s);
    }
    printf("Client %d disconnected\n",s );
    return(0);
}
예제 #23
0
HawkOctets& HawkOctets::Resize(UInt32 iSize)
{
    Reserve(iSize);
    m_pHigh = (Char*)m_pBase+iSize;
    return *this;
}
예제 #24
0
BOOL CFileTextLines::Load(const CString& sFilePath, int lengthHint /* = 0*/)
{
	m_LineEndings = EOL_AUTOLINE;
	m_UnicodeType = CFileTextLines::AUTOTYPE;
	RemoveAll();
	m_endings.clear();
	if(lengthHint != 0)
	{
		Reserve(lengthHint);
	}

	if (PathIsDirectory(sFilePath))
	{
		m_sErrorString.Format(IDS_ERR_FILE_NOTAFILE, (LPCTSTR)sFilePath);
		return FALSE;
	}

	if (!PathFileExists(sFilePath))
	{
		//file does not exist, so just return SUCCESS
		return TRUE;
	}

	CAutoFile hFile = CreateFile(sFilePath, GENERIC_READ, FILE_SHARE_READ, NULL, OPEN_EXISTING, NULL, NULL);
	if (!hFile)
	{
		SetErrorString();
		return FALSE;
	}

	LARGE_INTEGER fsize;
	if (!GetFileSizeEx(hFile, &fsize))
	{
		SetErrorString();
		return false;
	}
	if (fsize.HighPart)
	{
		// file is way too big for us
		m_sErrorString.LoadString(IDS_ERR_FILE_TOOBIG);
		return FALSE;
	}

	// If new[] was done for type T delete[] must be called on a pointer of type T*,
	// otherwise the behavior is undefined.
	// +1 is to address possible truncation when integer division is done
	wchar_t* pFileBuf = new wchar_t[fsize.LowPart/sizeof(wchar_t) + 1];
	DWORD dwReadBytes = 0;
	if (!ReadFile(hFile, pFileBuf, fsize.LowPart, &dwReadBytes, NULL))
	{
		delete [] pFileBuf;
		SetErrorString();
		return FALSE;
	}
	if (m_UnicodeType == CFileTextLines::AUTOTYPE)
	{
		m_UnicodeType = this->CheckUnicodeType(pFileBuf, dwReadBytes);
	}
	if (m_LineEndings == EOL_AUTOLINE)
	{
		m_LineEndings = CheckLineEndings(pFileBuf, min(10000, dwReadBytes));
	}
	hFile.CloseHandle();

	if (m_UnicodeType == CFileTextLines::BINARY)
	{
		m_sErrorString.Format(IDS_ERR_FILE_BINARY, (LPCTSTR)sFilePath);
		delete [] pFileBuf;
		return FALSE;
	}

	// we may have to convert the file content
	if ((m_UnicodeType == UTF8)||(m_UnicodeType == UTF8BOM))
	{
		int ret = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pFileBuf, dwReadBytes, NULL, 0);
		wchar_t * pWideBuf = new wchar_t[ret];
		int ret2 = MultiByteToWideChar(CP_UTF8, 0, (LPCSTR)pFileBuf, dwReadBytes, pWideBuf, ret);
		if (ret2 == ret)
		{
			delete [] pFileBuf;
			pFileBuf = pWideBuf;
			dwReadBytes = ret2;
		} else
			delete [] pWideBuf;
	}
	else if (m_UnicodeType == ASCII)
	{
		int ret = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPCSTR)pFileBuf, dwReadBytes, NULL, 0);
		wchar_t * pWideBuf = new wchar_t[ret];
		int ret2 = MultiByteToWideChar(CP_ACP, MB_PRECOMPOSED, (LPCSTR)pFileBuf, dwReadBytes, pWideBuf, ret);
		if (ret2 == ret)
		{
			delete [] pFileBuf;
			pFileBuf = pWideBuf;
			dwReadBytes = ret2;
		}
		else
			delete [] pWideBuf;
	}
	// fill in the lines into the array
	wchar_t * pTextBuf = pFileBuf;
	wchar_t * pLineStart = pFileBuf;
	if (m_UnicodeType == UNICODE_LE)
	{
		// UTF16 have two bytes per char
		dwReadBytes/=2;
	}
	if ((m_UnicodeType == UTF8BOM)||(m_UnicodeType == UNICODE_LE))
	{
		// ignore the BOM
		++pTextBuf;
		++pLineStart;
		--dwReadBytes;
	}

	for (DWORD i = 0; i<dwReadBytes; ++i)
	{
		if (*pTextBuf == '\r')
		{
			if ((i + 1) < dwReadBytes)
			{
				if (*(pTextBuf+1) == '\n')
				{
					// crlf line ending
					CString line(pLineStart, (int)(pTextBuf-pLineStart));
					Add(line, EOL_CRLF);
					pLineStart = pTextBuf+2;
					++pTextBuf;
					++i;
				}
				else
				{
					// cr line ending
					CString line(pLineStart, (int)(pTextBuf-pLineStart));
					Add(line, EOL_CR);
					pLineStart =pTextBuf+1;
				}
			}
		}
		else if (*pTextBuf == '\n')
		{
			// lf line ending
			CString line(pLineStart, (int)(pTextBuf-pLineStart));
			Add(line, EOL_LF);
			pLineStart =pTextBuf+1;
		}
		++pTextBuf;
	}
	if (pLineStart < pTextBuf)
	{
		CString line(pLineStart, (int)(pTextBuf-pLineStart));
		Add(line, EOL_NOENDING);
		m_bReturnAtEnd = false;
	}
	else
		m_bReturnAtEnd = true;

	delete [] pFileBuf;

	return TRUE;
}
예제 #25
0
 //! Constructor, create object with n bytes pre-allocated.
 explicit BufferBuilder(size_t n) {
     Reserve(n);
 }
예제 #26
0
	void HttpProtocol::WriteBuffer( const char* buf,INT32 len )
	{
		Reserve(m_nLenUsed + len);
		memcpy(&m_pBuf[m_nLenUsed],buf,len);
		m_nLenUsed += len;
	}
예제 #27
0
COutStream::COutStream() : no_flush(false), length_to_write(0)
{
	Reserve(kDefaultBufferSize); // start with 8kb
}
예제 #28
0
파일: String.cpp 프로젝트: joewan/turso3d
void String::Compact()
{
    if (Capacity())
        Reserve(Length() + 1);
}