Пример #1
0
void MessageFilterDialog::addFilter()
{
  uint32_t type;
  uint64_t types = 0;

  // iterate over the message types
  for (QListBoxItem* currentLBT = m_messageTypes->firstItem();
       currentLBT;
       currentLBT = currentLBT->next())
  {
    // if the item isn't selected, add in its type flag, and enable updates
    if (currentLBT->isSelected())
    {
      // get the message type of the selected item
      type = ((MessageFilterListBoxText*)currentLBT)->data();

      // add its flag to the types 
      types |= (uint64_t(1) << type);
    }
  } 

  // create a message filter object
  MessageFilter newFilter(m_name->text(), types, m_pattern->text());

  // if this isn't a valid filter, don't create it
  if (!newFilter.valid())
    return;

  // add the new filter
  m_currentFilterNum = m_filters->addFilter(newFilter);
  
  // if it is a valid filter, make the new filter the current selection
  if (m_currentFilterNum != 0xFF)
  {
    // retrieve the current item
    m_currentFilter = m_filters->filter(m_currentFilterNum);

    // iterate over the existing filters
    for (QListBoxItem* currentLBT = m_existingFilters->firstItem();
	 currentLBT;
	 currentLBT = currentLBT->next())
    {
      // find the current filter
      if (((MessageFilterListBoxText*)currentLBT)->data() == m_currentFilterNum)
      {
	// make the current filter the selected filter
	m_existingFilters->setSelected(currentLBT, true);
	break;
      }
    }
  }
  else // clear the current filter
  {
    // clear the current filter
    m_currentFilter = 0;
    clearFilter();
  }
  
  // setup the current dialog state
  checkState();
}
Пример #2
0
bool Wikidiff2::printMovedLineDiff(StringDiff & linediff, int opIndex, int opLine, int maxMovedLines)
{
	// helper fn creates 64-bit lookup key from opIndex and opLine
	auto makeKey = [](int index, int line) {
		return uint64_t(index) << 32 | line;
	};

	auto makeAnchorName = [](int index, int line, bool lhs) {
		char ch[2048];
		snprintf(ch, sizeof(ch), "movedpara_%d_%d_%s", index, line, lhs? "lhs": "rhs");
		return String(ch);
	};

	// check whether this paragraph immediately follows the other.
	// if so, they will be matched up next to each other and displayed as a change, not a move.
	auto isNext = [] (int opIndex, int opLine, int otherIndex, int otherLine) {
		if(otherIndex==opIndex && otherLine==opLine+1)
			return true;
		if(otherIndex==opIndex+1 && otherLine==0)
			return true;
		return false;
	};

#ifdef DEBUG_MOVED_LINES
	auto debugPrintf = [this](const char *fmt, ...) {
		char ch[2048];
		va_list ap;
		va_start(ap, fmt);
		vsnprintf(ch, sizeof(ch), fmt, ap);
		va_end(ap);

		result += "<tr><td /><td class=\"diff-context\" colspan=3>";
		result += ch;
		result += "</td></tr>";
	};
#else
	auto debugPrintf = [](...) { };
#endif

	if(!allowPrintMovedLineDiff(linediff, maxMovedLines)) {
		debugPrintf("printMovedLineDiff: diff too large (maxMovedLines=%ld), not detecting moved lines", maxMovedLines);
		return false;
	}

	debugPrintf("printMovedLineDiff (...), %d, %d\n", opIndex, opLine);

	bool printLeft = linediff[opIndex].op == DiffOp<String>::del ? true : false;
	bool printRight = !printLeft;

	// check whether this op actually refers to the diff map entry
	auto cmpDiffMapEntries = [&](int otherIndex, int otherLine) -> bool {
		uint64_t otherKey = makeKey(otherIndex, otherLine);
		auto it = diffMap.find(otherKey);
		if (it != diffMap.end()) {
			auto other = it->second;
			bool cmp = (printLeft ?
				other->opIndexFrom == opIndex && other->opLineFrom == opLine :
				other->opIndexTo == opIndex && other->opLineTo == opLine);
			if(!cmp) {
				debugPrintf("printMovedLineDiff(..., %d, %d): not printing diff again. op=%s", opIndex, opLine,
					linediff[opIndex].op == DiffOp<String>::add ? "add": linediff[opIndex].op == DiffOp<String>::del ? "del": "???");
				return false;
			}
		}
		return true;
	};

	// look for corresponding moved line for the opposite case in moved-line-map
	// if moved line exists:
	//     print diff to the moved line, omitting the left/right side for added/deleted line
	uint64_t key = makeKey(opIndex, opLine);
	auto it = diffMap.find(key);
	if (it != diffMap.end()) {
		auto best = it->second;
		int otherIndex = linediff[opIndex].op == DiffOp<String>::add ? best->opIndexFrom : best->opIndexTo;
		int otherLine = linediff[opIndex].op == DiffOp<String>::add ? best->opLineFrom : best->opLineTo;

		if(!cmpDiffMapEntries(otherIndex, otherLine))
			return false;

		if(isNext(otherIndex, otherLine, opIndex, opLine)) {
			debugPrintf("this one was already shown as a change, not displaying again...");
			return true;
		} else {
			// XXXX todo: we already have the diff, don't have to do it again, just have to print it
			printWordDiff(*linediff[best->opIndexFrom].from[best->opLineFrom], *linediff[best->opIndexTo].to[best->opLineTo],
				printLeft, printRight, makeAnchorName(opIndex, opLine, printLeft), makeAnchorName(otherIndex, otherLine, !printLeft));
		}

		if(printLeft)
			best->lhsDisplayed = true;
		else
			best->rhsDisplayed = true;

		debugPrintf("found in diffmap. copy: %d, del: %d, add: %d, change: %d, similarity: %.4f\n"
					"from: (%d,%d) to: (%d,%d)\n",
			best->ds.opCharCount[DiffOp<Word>::copy], best->ds.opCharCount[DiffOp<Word>::del], best->ds.opCharCount[DiffOp<Word>::add], best->ds.opCharCount[DiffOp<Word>::change], best->ds.charSimilarity,
			best->opIndexFrom, best->opLineFrom, best->opIndexTo, best->opLineTo);

		return true;
	}

	debugPrintf("nothing found in moved-line-map");

	// else:
	//     try to find a corresponding moved line in deleted/added lines
	int otherOp = (linediff[opIndex].op == DiffOp<String>::add ? DiffOp<String>::del : DiffOp<String>::add);
	std::shared_ptr<DiffMapEntry> found = nullptr;
	for (int i = 0; i < linediff.size(); ++i) {
		if (linediff[i].op == otherOp) {
			auto& lines = (linediff[opIndex].op == DiffOp<String>::add ? linediff[i].from : linediff[i].to);
			for (int k = 0; k < lines.size(); ++k) {
				WordVector words1, words2;
				std::shared_ptr<DiffMapEntry> tmp;
				TextUtil::explodeWords(*lines[k], words1);
				if (otherOp == DiffOp<String>::del) {
					TextUtil::explodeWords(*linediff[opIndex].to[opLine], words2);
					tmp = std::make_shared<DiffMapEntry>(words1, words2, i, k, opIndex, opLine);
				} else {
					TextUtil::explodeWords(*linediff[opIndex].from[opLine], words2);
					tmp = std::make_shared<DiffMapEntry>(words1, words2, opIndex, opLine, i, k);
				}
				if (!found || tmp->ds.charSimilarity > found->ds.charSimilarity) {
					found= tmp;
				}
			}
		}
	}

	if(found)
		debugPrintf("candidate found with similarity %.2f", found->ds.charSimilarity);

	// if candidate exists:
	//     add candidate to moved-line-map twice, for add/del case
	//     print diff to the moved line, omitting the left/right side for added/deleted line
	if (found && found->ds.charSimilarity > movedLineThreshold()) {
		// if we displayed a diff to the found block before, don't display this one as moved.
		int otherIndex = linediff[opIndex].op == DiffOp<String>::add ? found->opIndexFrom : found->opIndexTo;
		int otherLine = linediff[opIndex].op == DiffOp<String>::add ? found->opLineFrom : found->opLineTo;

		if(!cmpDiffMapEntries(otherIndex, otherLine))
			return false;

		if(printLeft)
			found->lhsDisplayed = true;
		else
			found->rhsDisplayed = true;

		diffMap[key] = found;
		diffMap[makeKey(otherIndex, otherLine)] = found;
		debugPrintf("inserting (%d,%d) + (%d,%d)", opIndex, opLine, otherIndex, otherLine);

		if(isNext(opIndex, opLine, otherIndex, otherLine)) {
			debugPrintf("This one immediately follows, displaying as change...");
			printWordDiff(*linediff[found->opIndexFrom].from[found->opLineFrom], *linediff[found->opIndexTo].to[found->opLineTo]);
			found->lhsDisplayed = true;
		}
		else {
			// XXXX todo: we already have the diff, don't have to do it again, just have to print it
			printWordDiff(*linediff[found->opIndexFrom].from[found->opLineFrom], *linediff[found->opIndexTo].to[found->opLineTo],
				printLeft, printRight, makeAnchorName(opIndex, opLine, printLeft), makeAnchorName(otherIndex, otherLine, !printLeft));
		}

		debugPrintf("copy: %d, del: %d, add: %d, change: %d, similarity: %.4f\n"
					"from: (%d,%d) to: (%d,%d)\n",
			found->ds.opCharCount[DiffOp<Word>::copy], found->ds.opCharCount[DiffOp<Word>::del], found->ds.opCharCount[DiffOp<Word>::add], found->ds.opCharCount[DiffOp<Word>::change], found->ds.charSimilarity,
			found->opIndexFrom, found->opLineFrom, found->opIndexTo, found->opLineTo);

		return true;
	}

	return false;
}
Пример #3
0
bool
WaveReader::LoadAllChunks(nsAutoPtr<dom::HTMLMediaElement::MetadataTags> &aTags)
{
  MOZ_ASSERT(OnTaskQueue());

  // Chunks are always word (two byte) aligned.
  MOZ_ASSERT(mResource.Tell() % 2 == 0,
             "LoadAllChunks called with unaligned resource");

  bool loadFormatChunk = false;
  bool findDataOffset = false;

  for (;;) {
    static const unsigned int CHUNK_HEADER_SIZE = 8;
    char chunkHeader[CHUNK_HEADER_SIZE];
    const char* p = chunkHeader;

    if (!ReadAll(chunkHeader, sizeof(chunkHeader))) {
      return false;
    }

    static_assert(sizeof(uint32_t) * 2 <= CHUNK_HEADER_SIZE,
                  "Reads would overflow chunkHeader buffer.");

    uint32_t magic = ReadUint32BE(&p);
    uint32_t chunkSize = ReadUint32LE(&p);
    int64_t chunkStart = GetPosition();

    switch (magic) {
      case FRMT_CHUNK_MAGIC:
        loadFormatChunk = LoadFormatChunk(chunkSize);
        if (!loadFormatChunk) {
          return false;
        }
        break;

      case LIST_CHUNK_MAGIC:
        if (!aTags) {
          LoadListChunk(chunkSize, aTags);
        }
        break;

      case DATA_CHUNK_MAGIC:
        findDataOffset = FindDataOffset(chunkSize);
        return loadFormatChunk && findDataOffset;

      default:
        break;
    }

    // RIFF chunks are two-byte aligned, so round up if necessary.
    chunkSize += chunkSize % 2;

    // Move forward to next chunk
    CheckedInt64 forward = CheckedInt64(chunkStart) + chunkSize - GetPosition();

    if (!forward.isValid() || forward.value() < 0) {
      return false;
    }

    static const int64_t MAX_CHUNK_SIZE = 1 << 16;
    static_assert(uint64_t(MAX_CHUNK_SIZE) < UINT_MAX / sizeof(char),
                  "MAX_CHUNK_SIZE too large for enumerator.");
    auto chunk = MakeUnique<char[]>(MAX_CHUNK_SIZE);
    while (forward.value() > 0) {
      int64_t size = std::min(forward.value(), MAX_CHUNK_SIZE);
      if (!ReadAll(chunk.get(), size)) {
        return false;
      }
      forward -= size;
    }
  }

  return false;
}
Пример #4
0
 basic_variant(unsigned int v):base(uint64_t(v)) {}
Пример #5
0
 basic_variant(unsigned char v):base(uint64_t(v)) {}
Пример #6
0
Variant::~Variant() {
    if (IS_REFCOUNTED_TYPE(m_type)) {
        tvDecRefHelper(m_type, uint64_t(m_data.pref));
    }
}
Пример #7
0
AkPacket ConvertAudioFFmpeg::convert(const AkAudioPacket &packet,
                                     const AkCaps &oCaps)
{
    AkAudioCaps oAudioCaps(oCaps);

    int64_t iSampleLayout = channelLayouts->value(packet.caps().layout(), 0);

    AVSampleFormat iSampleFormat =
            av_get_sample_fmt(AkAudioCaps::sampleFormatToString(packet.caps().format())
                              .toStdString().c_str());

    int iSampleRate = packet.caps().rate();
    int iNChannels = packet.caps().channels();
    int iNSamples = packet.caps().samples();

    int64_t oSampleLayout = channelLayouts->value(oAudioCaps.layout(),
                                                  AV_CH_LAYOUT_STEREO);

    AVSampleFormat oSampleFormat =
            av_get_sample_fmt(AkAudioCaps::sampleFormatToString(oAudioCaps.format())
                              .toStdString().c_str());

    int oSampleRate = oAudioCaps.rate();
    int oNChannels = oAudioCaps.channels();

    this->m_resampleContext =
            swr_alloc_set_opts(this->m_resampleContext,
                               oSampleLayout,
                               oSampleFormat,
                               oSampleRate,
                               iSampleLayout,
                               iSampleFormat,
                               iSampleRate,
                               0,
                               NULL);

    if (!this->m_resampleContext)
        return AkPacket();

    // Create input audio frame.
    static AVFrame iFrame;
    memset(&iFrame, 0, sizeof(AVFrame));
    iFrame.format = iSampleFormat;
    iFrame.channels = iNChannels;
    iFrame.channel_layout = uint64_t(iSampleLayout);
    iFrame.sample_rate = iSampleRate;
    iFrame.nb_samples = iNSamples;
    iFrame.pts = iFrame.pkt_pts = packet.pts();

    if (avcodec_fill_audio_frame(&iFrame,
                                 iFrame.channels,
                                 iSampleFormat,
                                 reinterpret_cast<const uint8_t *>(packet.buffer().constData()),
                                 packet.buffer().size(),
                                 1) < 0) {
        return AkPacket();
    }

    // Fill output audio frame.
    AVFrame oFrame;
    memset(&oFrame, 0, sizeof(AVFrame));
    oFrame.format = oSampleFormat;
    oFrame.channels = oNChannels;
    oFrame.channel_layout = uint64_t(oSampleLayout);
    oFrame.sample_rate = oSampleRate;
    oFrame.nb_samples = int(swr_get_delay(this->m_resampleContext, oSampleRate))
                        + iFrame.nb_samples
                        * oSampleRate
                        / iSampleRate
                        + 3;
    oFrame.pts = oFrame.pkt_pts = iFrame.pts * oSampleRate / iSampleRate;

    // Calculate the size of the audio buffer.
    int frameSize = av_samples_get_buffer_size(oFrame.linesize,
                                               oFrame.channels,
                                               oFrame.nb_samples,
                                               oSampleFormat,
                                               1);

    QByteArray oBuffer(frameSize, Qt::Uninitialized);

    if (avcodec_fill_audio_frame(&oFrame,
                                 oFrame.channels,
                                 oSampleFormat,
                                 reinterpret_cast<const uint8_t *>(oBuffer.constData()),
                                 oBuffer.size(),
                                 1) < 0) {
        return AkPacket();
    }

    // convert to destination format
    if (swr_convert_frame(this->m_resampleContext,
                          &oFrame,
                          &iFrame) < 0)
        return AkPacket();

    frameSize = av_samples_get_buffer_size(oFrame.linesize,
                                           oFrame.channels,
                                           oFrame.nb_samples,
                                           oSampleFormat,
                                           1);

    oBuffer.resize(frameSize);

    AkAudioPacket oAudioPacket;
    oAudioPacket.caps() = oAudioCaps;
    oAudioPacket.caps().samples() = oFrame.nb_samples;
    oAudioPacket.buffer() = oBuffer;
    oAudioPacket.pts() = oFrame.pts;
    oAudioPacket.timeBase() = AkFrac(1, oAudioCaps.rate());
    oAudioPacket.index() = packet.index();
    oAudioPacket.id() = packet.id();

    return oAudioPacket.toPacket();
}
Пример #8
0
void to_variant( const uint32_t& var,  variant& vo )  { vo = uint64_t(var); }
Пример #9
0
 void to_variant( unsigned long long int s, variant& v ) { v = variant( uint64_t(s)); }
Пример #10
0
bool AudioStreamGibberish::mix(int32_t *p_buffer, int p_frames) {

	if (!active)
		return false;

	zeromem(p_buffer,p_frames*sizeof(int32_t));

	if (!paused && active_voices==0) {

		active_voices=1;
		playback[0].idx=randomize();
		playback[0].fp_pos=0;
		playback[0].scale=Math::random(1,1+pitch_random_scale);
	}

	for(int i=0;i<active_voices;i++) {

		RID s = _samples[playback[i].idx]->get_rid();

		uint64_t fp_pos=playback[i].fp_pos;
		const void *data = AudioServer::get_singleton()->sample_get_data_ptr(s);
		bool is16 = AudioServer::get_singleton()->sample_get_format(s)==AudioServer::SAMPLE_FORMAT_PCM16;
		int skip = AudioServer::get_singleton()->sample_is_stereo(s) ? 1: 0;
		uint64_t max = AudioServer::get_singleton()->sample_get_length(s) * uint64_t(FP_LEN);
		int mrate = AudioServer::get_singleton()->sample_get_mix_rate(s) * pitch_scale * playback[i].scale;
		uint64_t increment = uint64_t(mrate) * uint64_t(FP_LEN) / get_mix_rate();


		float vol_begin = _get_vol_at_pos(fp_pos>>FP_BITS,max>>FP_BITS,xfade_time*mrate);
		float vol_end = _get_vol_at_pos((fp_pos+p_frames*increment)>>FP_BITS,max>>FP_BITS,xfade_time*mrate);

		int32_t vol = CLAMP(int32_t(vol_begin * 65535),0,65535);
		int32_t vol_to = CLAMP(int32_t(vol_end * 65535),0,65535);
		int32_t vol_inc = (vol_to-vol)/p_frames;

		bool done=false;

		if (is16) {

			const int16_t *smp = (int16_t*)data;
			for(int i=0;i<p_frames;i++) {

				if (fp_pos >= max) {
					done=true;
					break;
				}

				int idx = (fp_pos>>FP_BITS)<<skip;
				p_buffer[i]+=int32_t(smp[idx])*vol;
				vol+=vol_inc;

				fp_pos+=increment;
			}
		} else {

			const int8_t *smp = (int8_t*)data;
			for(int i=0;i<p_frames;i++) {

				if (fp_pos >= max) {
					done=true;
					break;
				}

				int idx = (fp_pos>>FP_BITS)<<skip;
				p_buffer[i]+=(int32_t(smp[idx])<<8)*vol;
				vol+=vol_inc;
				fp_pos+=increment;
			}

		}

		playback[i].fp_pos=fp_pos;
		if (!paused && active_voices==1 && (vol_end < vol_begin || done)) {
			//xfade to something else i gues
			active_voices=2;
			playback[1].idx=randomize();
			playback[1].fp_pos=0;
			playback[1].scale=Math::random(1,1+pitch_random_scale);
		}

		if (done) {

			if (i==0 && active_voices==2) {
				playback[0]=playback[1];
				i--;
			}
			active_voices--;

		}
	}
Пример #11
0
//-----------------------------------------------------------------------------
void StyleDialog::updatePic()
{
	static mglGraph gr(0,128,30);
	static bool f = true;
	mglData x(3), y(3), a(32,2);
	x.Fill(-1,1);	a.Fill(-1,1);
	if(!f)	gr.Clf();
	if(f)
	{
		gr.SubPlot(1,1,0,"");
		gr.SetMarkSize(15);
		gr.SetArrowSize(20);
		f = false;
	}
	result = "";
	int i,j;
	QString col="wbgrcmylenuqphkWBGRCMYLENUQPH", mrk=".+x*sdv^<>o.*+xsdv^<>o", dsh="|;=ji: ", arw="AVIKTSDO", s;
	QString msk="-+=;oOsS~<>jdD*^", dir="/\\I";
	switch(tab->currentIndex())
	{
	case 0:	// line style
		i = a2->currentIndex();		if(i>0)	result += arw[i-1];
		j = a1->currentIndex();		if(j>0)
		{
			if(i==0)	result += '_';
			result += arw[j-1];
		}
		i = dash->currentIndex();
		if(i>0 && i<8)	result += dsh[i-1];
		else if(i==8)	// manual
		{
			int d=0;
			for(int i=0;i<16;i++)	if(dash_bit[i]->isChecked())	d += 1<<i;
			result += "{d"+QString::number(d,16)+"}";
		}
		i = mark->currentIndex();	if(i>0)	result += mrk[i-1];
		if(i>11)	result += '#';
		i = cline->currentIndex();
		if(i>0)
		{
			j = nline->value();
			if(j!=5)	result += "{"+col[i-1]+char('0'+j)+"}";
			else		result += col[i-1];
		}
		i = width->value();		if(i>1)	result += char('0'+i);
		gr.Plot(x,y,result.toStdString().c_str());
		break;
	case 1: // color sceheme
	case 3: // manual mask
		for(j=0;j<7;j++)
		{
			i = cc[j]->currentIndex();
			if(i<1)	break;
			QCharRef c = col[i-1];
			i = nn[j]->value();
			if(i!=5)	result += "{"+c+char('0'+i)+"}";
			else		result += c;
		}
		if(swire->isChecked())	result += '#';
		i = ctext->currentIndex();
		if(i==1)	result += 't';
		if(i==2)	result += 'T';
		i = mask->currentIndex();
		if(i>0 && i<17)
		{
			result += msk[i-1];
			i = angle->currentIndex();
			if(i>0)	result += dir[i-1];
			i = msize->value();
			if(i>1)	result += char('0'+i);
		}
		else if(i==17)
		{
			uint64_t t=0;
			for(int j=0;j<64;j++)	if(mask_bit[j]->isChecked())	t += uint64_t(1)<<j;
			result += "{s"+QString::number(t,16)+"}";
			// TODO get hex-mask
			i = angle->currentIndex();
			if(i>0)	result += dir[i-1];
			i = msize->value();
			if(i>1)	result += char('0'+i);
		}
		
		
		i = axial->currentIndex();
		if(i>0)	result = result+':'+char('x'+i-1);
		gr.Surf(a,result.toStdString().c_str());
		break;
	case 2: // text style
		if(font_sch->isChecked())	for(j=0;j<7;j++)
		{
			i = cc[j]->currentIndex();
			if(i<1)	break;
			QCharRef c = col[i-1];
			i = nn[j]->value();
			if(i!=5)	result += "{"+c+char('0'+i)+"}";
			else		result += c;
		}
		else
		{
			i = cfont->currentIndex();
			if(i>1)	result += col[i-1];
		}
		result += ':';
		if(bold->isChecked())	result += 'b';
		if(ital->isChecked())	result += 'i';
		if(wire->isChecked())	result += 'w';
		if(uline->isChecked())	result += 'u';
		if(oline->isChecked())	result += 'o';
		if(rbL->isChecked())	result += 'L';
		if(rbC->isChecked())	result += 'C';
		if(rbR->isChecked())	result += 'R';
		gr.Puts(mglPoint(0,-0.5),"Font test",result.toStdString().c_str(),-10);
		break;
	}
	result = "'" + result + "'";
	res->setText(result);
	QPixmap p;
	convertFromGraph(p, &gr, &grBuf);
	pic->setPixmap(p);
}
Пример #12
0
NS_IMETHODIMP
nsIndexedToHTML::OnIndexAvailable(nsIRequest *aRequest,
                                  nsISupports *aCtxt,
                                  nsIDirIndex *aIndex) {
    nsresult rv;
    if (!aIndex)
        return NS_ERROR_NULL_POINTER;

    nsCString pushBuffer;
    pushBuffer.AppendLiteral("<tr");

    // We don't know the file's character set yet, so retrieve the raw bytes
    // which will be decoded by the HTML parser.
    nsXPIDLCString loc;
    aIndex->GetLocation(getter_Copies(loc));

    // Adjust the length in case unescaping shortened the string.
    loc.Truncate(nsUnescapeCount(loc.BeginWriting()));
    if (loc.First() == char16_t('.'))
        pushBuffer.AppendLiteral(" class=\"hidden-object\"");

    pushBuffer.AppendLiteral(">\n <td sortable-data=\"");

    // The sort key is the name of the item, prepended by either 0, 1 or 2
    // in order to group items.
    uint32_t type;
    aIndex->GetType(&type);
    switch (type) {
        case nsIDirIndex::TYPE_SYMLINK:
            pushBuffer.Append('0');
            break;
        case nsIDirIndex::TYPE_DIRECTORY:
            pushBuffer.Append('1');
            break;
        default:
            pushBuffer.Append('2');
            break;
    }
    nsAdoptingCString escaped(nsEscapeHTML(loc));
    pushBuffer.Append(escaped);

    pushBuffer.AppendLiteral("\"><table class=\"ellipsis\"><tbody><tr><td><a class=\"");
    switch (type) {
        case nsIDirIndex::TYPE_DIRECTORY:
            pushBuffer.AppendLiteral("dir");
            break;
        case nsIDirIndex::TYPE_SYMLINK:
            pushBuffer.AppendLiteral("symlink");
            break;
        default:
            pushBuffer.AppendLiteral("file");
            break;
    }

    pushBuffer.AppendLiteral("\" href=\"");

    // need to escape links
    nsAutoCString locEscaped;

    // Adding trailing slash helps to recognize whether the URL points to a file
    // or a directory (bug #214405).
    if ((type == nsIDirIndex::TYPE_DIRECTORY) && (loc.Last() != '/')) {
        loc.Append('/');
    }

    // now minimally re-escape the location...
    uint32_t escFlags;
    // for some protocols, we expect the location to be absolute.
    // if so, and if the location indeed appears to be a valid URI, then go
    // ahead and treat it like one.
    if (mExpectAbsLoc &&
        NS_SUCCEEDED(net_ExtractURLScheme(loc, nullptr, nullptr, nullptr))) {
        // escape as absolute 
        escFlags = esc_Forced | esc_AlwaysCopy | esc_Minimal;
    }
    else {
        // escape as relative
        // esc_Directory is needed because directories have a trailing slash.
        // Without it, the trailing '/' will be escaped, and links from within
        // that directory will be incorrect
        escFlags = esc_Forced | esc_AlwaysCopy | esc_FileBaseName | esc_Colon | esc_Directory;
    }
    NS_EscapeURL(loc.get(), loc.Length(), escFlags, locEscaped);
    // esc_Directory does not escape the semicolons, so if a filename
    // contains semicolons we need to manually escape them.
    // This replacement should be removed in bug #473280
    locEscaped.ReplaceSubstring(";", "%3b");
    nsAdoptingCString htmlEscapedURL(nsEscapeHTML(locEscaped.get()));
    pushBuffer.Append(htmlEscapedURL);

    pushBuffer.AppendLiteral("\">");

    if (type == nsIDirIndex::TYPE_FILE || type == nsIDirIndex::TYPE_UNKNOWN) {
        pushBuffer.AppendLiteral("<img src=\"moz-icon://");
        int32_t lastDot = locEscaped.RFindChar('.');
        if (lastDot != kNotFound) {
            locEscaped.Cut(0, lastDot);
            nsAdoptingCString htmlFileExt(nsEscapeHTML(locEscaped.get()));
            pushBuffer.Append(htmlFileExt);
        } else {
            pushBuffer.AppendLiteral("unknown");
        }
        pushBuffer.AppendLiteral("?size=16\" alt=\"");

        nsXPIDLString altText;
        rv = mBundle->GetStringFromName(MOZ_UTF16("DirFileLabel"),
                                        getter_Copies(altText));
        if (NS_FAILED(rv)) return rv;
        AppendNonAsciiToNCR(altText, pushBuffer);
        pushBuffer.AppendLiteral("\">");
    }

    pushBuffer.Append(escaped);
    pushBuffer.AppendLiteral("</a></td></tr></tbody></table></td>\n <td");

    if (type == nsIDirIndex::TYPE_DIRECTORY || type == nsIDirIndex::TYPE_SYMLINK) {
        pushBuffer.Append('>');
    } else {
        int64_t size;
        aIndex->GetSize(&size);

        if (uint64_t(size) != UINT64_MAX) {
            pushBuffer.AppendLiteral(" sortable-data=\"");
            pushBuffer.AppendInt(size);
            pushBuffer.AppendLiteral("\">");
            nsAutoCString sizeString;
            FormatSizeString(size, sizeString);
            pushBuffer.Append(sizeString);
        } else {
            pushBuffer.Append('>');
        }
    }
    pushBuffer.AppendLiteral("</td>\n <td");

    PRTime t;
    aIndex->GetLastModified(&t);

    if (t == -1) {
        pushBuffer.AppendLiteral("></td>\n <td>");
    } else {
        pushBuffer.AppendLiteral(" sortable-data=\"");
        pushBuffer.AppendInt(static_cast<int64_t>(t));
        pushBuffer.AppendLiteral("\">");
        nsAutoString formatted;
        mDateTime->FormatPRTime(nullptr,
                                kDateFormatShort,
                                kTimeFormatNone,
                                t,
                                formatted);
        AppendNonAsciiToNCR(formatted, pushBuffer);
        pushBuffer.AppendLiteral("</td>\n <td>");
        mDateTime->FormatPRTime(nullptr,
                                kDateFormatNone,
                                kTimeFormatSeconds,
                                t,
                                formatted);
        // use NCR to show date in any doc charset
        AppendNonAsciiToNCR(formatted, pushBuffer);
    }

    pushBuffer.AppendLiteral("</td>\n</tr>");

    return SendToListener(aRequest, aCtxt, pushBuffer);
}
Пример #13
0
///
/// @brief Configure the ARR0 of the CCS instruction for mrs05, data object as input
/// @param[in] i_target a fapi2::Target<fapi2::TARGET_TYPE_DIMM>
/// @param[in] i_data an mrs05_data object, filled in
/// @param[in,out] io_inst the instruction to fixup
/// @param[in] i_rank the rank in question
/// @return FAPI2_RC_SUCCESS iff OK
///
fapi2::ReturnCode mrs05(const fapi2::Target<fapi2::TARGET_TYPE_DIMM>& i_target,
                        const mrs05_data& i_data,
                        ccs::instruction_t<fapi2::TARGET_TYPE_MCBIST>& io_inst,
                        const uint64_t i_rank)
{
    constexpr uint64_t CA_PARITY_LATENCY_LENGTH = 3;
    constexpr uint64_t CA_PARITY_LATENCY_START = 7;
    constexpr uint64_t RTT_PARK_LENGTH = 3;
    constexpr uint64_t RTT_PARK_START = 7;

    constexpr uint64_t CA_PARITY_COUNT = 9;
    //                                                             0                4      5      6         8
    constexpr uint8_t ca_parity_latency_map[CA_PARITY_COUNT] = { 0b000, 0, 0, 0, 0b001, 0b010, 0b011, 0, 0b100 };

    fapi2::buffer<uint8_t> l_ca_parity_latency_buffer;

    fapi2::buffer<uint8_t> l_rtt_park_buffer = i_data.iv_rtt_park[mss::index(i_rank)];

    //check here to make sure the rank indexes correctly into the attribute array
    FAPI_ASSERT( (mss::index(i_rank) < MAX_RANK_PER_DIMM),
                 fapi2::MSS_BAD_MR_PARAMETER()
                 .set_MR_NUMBER(5)
                 .set_PARAMETER(RANK)
                 .set_PARAMETER_VALUE(i_rank)
                 .set_DIMM_IN_ERROR(i_target),
                 "Bad value for RTT park: %d (%s)", i_rank, mss::c_str(i_target));

    FAPI_ASSERT( (i_data.iv_ca_parity_latency < CA_PARITY_COUNT),
                 fapi2::MSS_BAD_MR_PARAMETER()
                 .set_MR_NUMBER(5)
                 .set_PARAMETER(CA_PARITY_LATENCY)
                 .set_PARAMETER_VALUE(i_data.iv_ca_parity_latency)
                 .set_DIMM_IN_ERROR(i_target),
                 "Bad value for CA parity latency: %d (%s)", i_data.iv_ca_parity_latency, mss::c_str(i_target));

    l_ca_parity_latency_buffer = ca_parity_latency_map[i_data.iv_ca_parity_latency];

    FAPI_INF("%s MR5 rank %d attributes: CAPL: 0x%x(0x%x), CRC_EC: 0x%x, CA_PES: 0x%x, ODT_IB: 0x%x "
             "RTT_PARK: 0x%x, CAP: 0x%x, DM: 0x%x, WDBI: 0x%x, RDBI: 0x%x",
             mss::c_str(i_target), i_rank, i_data.iv_ca_parity_latency, uint8_t(l_ca_parity_latency_buffer),
             i_data.iv_crc_error_clear, i_data.iv_ca_parity_error_status, i_data.iv_odt_input_buffer,
             uint8_t(l_rtt_park_buffer), i_data.iv_ca_parity,
             i_data.iv_data_mask, i_data.iv_write_dbi, i_data.iv_read_dbi);

    mss::swizzle<A0, CA_PARITY_LATENCY_LENGTH, CA_PARITY_LATENCY_START>(l_ca_parity_latency_buffer, io_inst.arr0);
    io_inst.arr0.writeBit<A3>(i_data.iv_crc_error_clear);
    io_inst.arr0.writeBit<A4>(i_data.iv_ca_parity_error_status);
    io_inst.arr0.writeBit<A5>(i_data.iv_odt_input_buffer);
    mss::swizzle<A6, RTT_PARK_LENGTH, RTT_PARK_START>(l_rtt_park_buffer, io_inst.arr0);
    io_inst.arr0.writeBit<A9>(i_data.iv_ca_parity);
    io_inst.arr0.writeBit<A10>(i_data.iv_data_mask);
    io_inst.arr0.writeBit<A11>(i_data.iv_write_dbi);
    io_inst.arr0.writeBit<A12>(i_data.iv_read_dbi);

    FAPI_INF("%s MR5: 0x%016llx", mss::c_str(i_target), uint64_t(io_inst.arr0));

    return fapi2::FAPI2_RC_SUCCESS;

fapi_try_exit:
    return fapi2::current_err;
}
Пример #14
0
void MessageFilterDialog::checkState()
{
  bool update = false;
  bool add = false;

  // the state check varies depending on if their is a current filter or not
  if (m_currentFilter)
  {
    uint32_t type;
    uint64_t types = 0;
    
    // buttons should only be enabled for valid message filter content
    if (!m_name->text().isEmpty() &&
	!m_pattern->text().isEmpty() &&
	QRegExp(m_pattern->text()).isValid())
    {
      // iterate over all the message types
      for (QListBoxItem* currentLBT = m_messageTypes->firstItem();
	   currentLBT;
	   currentLBT = currentLBT->next())
      {
	// is the current item selected
	if (currentLBT->isSelected())
	{
	  // get the items message type
	  type = ((MessageFilterListBoxText*)currentLBT)->data();

	  // add the message type into the message types
	  types |= (uint64_t(1) << type);

	  // found a selected item, fields are valid for update
	  update = true;
	}
      }

      // only enable add if the filter is different from its predecessor
      if ((m_name->text() != m_currentFilter->name()) || 
	  (m_pattern->text() != m_currentFilter->regexp().pattern()) ||
	  (types != m_currentFilter->types()))
	add = true;

    }
  }
  else
  {
    // buttons should only be enabled for valid message filter content
    if (!m_name->text().isEmpty() &&
	!m_pattern->text().isEmpty())
    {
      // iterate over all the message types
      for (QListBoxItem* currentLBT = m_messageTypes->firstItem();
	   currentLBT;
	   currentLBT = currentLBT->next())
      {
	// if the item isn't selected, try the next item
	if (!currentLBT->isSelected())
	  continue;
	
	// found a selected item, fields are valid for add
	add = true;
	break;
      }
    }
  }

  // set the button states according to the results from above
  m_add->setEnabled(add);
  m_update->setEnabled(update);

  // only enable delete if editing an existing filter
  m_delete->setEnabled(m_currentFilter != 0);
}
Пример #15
0
  bool core::queryBlocks(const std::list<crypto::hash>& knownBlockIds, uint64_t timestamp,
      uint64_t& resStartHeight, uint64_t& resCurrentHeight, uint64_t& resFullOffset, std::list<BlockFullInfo>& entries) {

    LockedBlockchainStorage lbs(m_blockchain_storage);

    uint64_t currentHeight = lbs->get_current_blockchain_height();
    uint64_t startOffset = 0;

    if (!lbs->find_blockchain_supplement(knownBlockIds, startOffset)) {
      return false;
    }

    uint64_t startFullOffset = 0;

    if (!lbs->getLowerBound(timestamp, startOffset, startFullOffset))
      startFullOffset = startOffset;

    resFullOffset = startFullOffset;

    if (startOffset != startFullOffset) {
      std::list<crypto::hash> blockIds;
      if (!lbs->getBlockIds(startOffset, std::min(uint64_t(BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT), startFullOffset - startOffset), blockIds)) {
        return false;
      }

      for (const auto& id : blockIds) {
        entries.push_back(BlockFullInfo());
        entries.back().block_id = id;
      }
    }

    auto blocksLeft = std::min(BLOCKS_IDS_SYNCHRONIZING_DEFAULT_COUNT - entries.size(), size_t(BLOCKS_SYNCHRONIZING_DEFAULT_COUNT));

    if (blocksLeft) {
      std::list<Block> blocks;
      lbs->get_blocks(startFullOffset, blocksLeft, blocks);

      for (auto& b : blocks) {
        BlockFullInfo item;

        item.block_id = get_block_hash(b);

        if (b.timestamp >= timestamp) {
          // query transactions
          std::list<Transaction> txs;
          std::list<crypto::hash> missedTxs;
          lbs->get_transactions(b.txHashes, txs, missedTxs);

          // fill data
          block_complete_entry& completeEntry = item;
          completeEntry.block = block_to_blob(b);
          for (auto& tx : txs) {
            completeEntry.txs.push_back(tx_to_blob(tx));
          }
        }

        entries.push_back(std::move(item));
      }
    }

    resCurrentHeight = currentHeight;
    resStartHeight = startOffset;

    return true;
  }
// nsIStreamListener implementation
NS_IMETHODIMP
nsFTPDirListingConv::OnDataAvailable(nsIRequest* request, nsISupports *ctxt,
                                  nsIInputStream *inStr, uint32_t sourceOffset, uint32_t count) {
    NS_ASSERTION(request, "FTP dir listing stream converter needs a request");
    
    nsresult rv;

    nsCOMPtr<nsIChannel> channel = do_QueryInterface(request, &rv);
    NS_ENSURE_SUCCESS(rv, rv);
    
    uint32_t read, streamLen;

    uint64_t streamLen64;
    rv = inStr->Available(&streamLen64);
    NS_ENSURE_SUCCESS(rv, rv);
    streamLen = (uint32_t)NS_MIN(streamLen64, uint64_t(PR_UINT32_MAX - 1));

    nsAutoArrayPtr<char> buffer(new char[streamLen + 1]);
    NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY);

    rv = inStr->Read(buffer, streamLen, &read);
    NS_ENSURE_SUCCESS(rv, rv);

    // the dir listings are ascii text, null terminate this sucker.
    buffer[streamLen] = '\0';

    PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("nsFTPDirListingConv::OnData(request = %x, ctxt = %x, inStr = %x, sourceOffset = %d, count = %d)\n", request, ctxt, inStr, sourceOffset, count));

    if (!mBuffer.IsEmpty()) {
        // we have data left over from a previous OnDataAvailable() call.
        // combine the buffers so we don't lose any data.
        mBuffer.Append(buffer);

        buffer = new char[mBuffer.Length()+1];
        NS_ENSURE_TRUE(buffer, NS_ERROR_OUT_OF_MEMORY);

        strncpy(buffer, mBuffer.get(), mBuffer.Length()+1);
        mBuffer.Truncate();
    }

#ifndef DEBUG_dougt
    PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() received the following %d bytes...\n\n%s\n\n", streamLen, buffer.get()) );
#else
    printf("::OnData() received the following %d bytes...\n\n%s\n\n", streamLen, buffer);
#endif // DEBUG_dougt

    nsCAutoString indexFormat;
    if (!mSentHeading) {
        // build up the 300: line
        nsCOMPtr<nsIURI> uri;
        rv = channel->GetURI(getter_AddRefs(uri));
        NS_ENSURE_SUCCESS(rv, rv);

        rv = GetHeaders(indexFormat, uri);
        NS_ENSURE_SUCCESS(rv, rv);

        mSentHeading = true;
    }

    char *line = buffer;
    line = DigestBufferLines(line, indexFormat);

#ifndef DEBUG_dougt
    PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() sending the following %d bytes...\n\n%s\n\n", 
        indexFormat.Length(), indexFormat.get()) );
#else
    char *unescData = ToNewCString(indexFormat);
    NS_ENSURE_TRUE(unescData, NS_ERROR_OUT_OF_MEMORY);
    
    nsUnescape(unescData);
    printf("::OnData() sending the following %d bytes...\n\n%s\n\n", indexFormat.Length(), unescData);
    nsMemory::Free(unescData);
#endif // DEBUG_dougt

    // if there's any data left over, buffer it.
    if (line && *line) {
        mBuffer.Append(line);
        PR_LOG(gFTPDirListConvLog, PR_LOG_DEBUG, ("::OnData() buffering the following %d bytes...\n\n%s\n\n",
            PL_strlen(line), line) );
    }

    // send the converted data out.
    nsCOMPtr<nsIInputStream> inputData;

    rv = NS_NewCStringInputStream(getter_AddRefs(inputData), indexFormat);
    NS_ENSURE_SUCCESS(rv, rv);

    rv = mFinalListener->OnDataAvailable(request, ctxt, inputData, 0, indexFormat.Length());

    return rv;
}
Пример #17
0
  }
  size = 0;
  TEST(Platform::GetFileSizeByFullPath(TEST_FILE_NAME, size), ());
  TEST_EQUAL(size, 6, ());

  FileWriter::DeleteFileX(TEST_FILE_NAME);

  {
    FileWriter testFile(pl.WritablePathForFile(TEST_FILE_NAME));
    testFile.Write("HOHOHO", 6);
  }
  size = 0;
  TEST(pl.GetFileSizeByName(TEST_FILE_NAME, size), ());
  TEST_EQUAL(size, 6, ());

  FileWriter::DeleteFileX(pl.WritablePathForFile(TEST_FILE_NAME));
}

UNIT_TEST(CpuCores)
{
  int const coresNum = GetPlatform().CpuCores();
  TEST_GREATER(coresNum, 0, ());
  TEST_LESS_OR_EQUAL(coresNum, 128, ());
}

UNIT_TEST(GetWritableStorageStatus)
{
  TEST_EQUAL(Platform::STORAGE_OK, GetPlatform().GetWritableStorageStatus(100000), ());
  TEST_EQUAL(Platform::NOT_ENOUGH_SPACE, GetPlatform().GetWritableStorageStatus(uint64_t(-1)), ());
}
Пример #18
0
bool DataHDDIORaw::read( const Box_i32& dim, void* dst )
{
    static bool errorReported = false;
    if( sizeof(std::streamoff) < sizeof(int64_t) && !errorReported )
    {
        LOG_ERROR << "sizeof(std::streamoff) < sizeof(int64_t): reading from large files is probably broken!" << std::endl;
        errorReported = true;
    }

    assert( isSourceSizeValid() );

    if( !dim.valid( ))
    {
        LOG_ERROR << "Input dimensions are invalid" << std::endl;
        return false;
    }

    const Vec3_ui32 srcDim = getSourceDims();
    const Vec3_ui32 dstDim = dim.getDim();

    // get actual coordinates
    Box_i32 bb( Vec3_ui32(0), srcDim );
    bb = bb.intersect( dim );

    const byte bytes = getBytesNum();
    if( bb != dim ) // our area is smaller than requested => clean initial data
        memset( dst, 0, dim.getAreaSize()*bytes );

    if( !bb.valid( ))
        return true;

    const Vec3_ui32 bbDim = bb.getDim();

    char* dstByte = reinterpret_cast<char*>( dst );

    // shift of the destination
    const uint64_t dstShift = ( uint64_t(dstDim.h)*dstDim.w*( bb.s.d-dim.s.d ) +
                                                   dstDim.w*( bb.s.h-dim.s.h ) +
                                                            ( bb.s.w-dim.s.w )  ) * uint64_t(bytes);
    dstByte += dstShift;

    // shift of the source
    const int64_t srcZ = int64_t(srcDim.h) * srcDim.w * bb.s.d * uint64_t(bytes);
    const int64_t srcY =                     srcDim.w * bb.s.h * uint64_t(bytes);
    const int64_t srcX =                                bb.s.w * uint64_t(bytes);

    // amout of data we are going to use
    const int64_t sliceSize = srcDim.h * srcDim.w * bbDim.d * bytes;

    if( srcZ != _oldZ || static_cast<int64_t>(bbDim.d) != _oldD )
    {
//        LOG_INFO << "  New depth to read from a raw file: " << srcZ << std::endl;

        const std::string& fName = getDataFileName();
        if( static_cast<int64_t>(util::fileSize( fName )) < srcZ+sliceSize )
        {
            LOG_ERROR << "File: " << fName.c_str() << " is too smll to read " << sliceSize 
                      << " bytes within the offset: " << srcZ << std::endl;
            return false;
        }

        util::InFile inFile;
        if( !inFile.open( fName, std::ios::binary, true ))
            return false;

        _tmp.resize( sliceSize );

        if( !inFile.read( srcZ, sliceSize, &_tmp[0] ))
            return false;

        _oldZ = srcZ;
        _oldD = static_cast<int64_t>(bbDim.d);
    }

    _copyData( dstByte, &_tmp[srcY+srcX], bbDim, dstDim, srcDim, bytes );

    return true;
}
Пример #19
0
namespace utils {

namespace {
const uint64_t skDefaultBlockSize = 64 * uint64_t(1) << 20;  // 64 MB
}  // anonymous namespace

const uint64_t FileIO::skDefaultReadSize = uint64_t(1)<<30;  // 1 GB

FileIO::Pointer FileIO::Open(
        const std::string& path_str,
        const std::string& open_mode,
        std::error_code * error
    )
{
    if (error)
        error->clear();

#if _WIN32
    std::wstring wide_path = bytes_to_wide(path_str);
    auto path = boost::filesystem::path(wide_path);
#else
    auto path = boost::filesystem::path(path_str);
#endif

    return Open(path, open_mode, error);
}

FileIO::Pointer FileIO::Open(
        boost::filesystem::path path,
        const std::string& open_mode,
        std::error_code * error
    )
{
    if (error)
        error->clear();

#if _WIN32
    std::wstring wide_open_mode = bytes_to_wide(open_mode);
    FILE* file_handle = _wfopen(
            path.wstring().c_str(),
            wide_open_mode.c_str()
        );
#else
    FILE* file_handle = fopen(
        path.string().c_str(),
        open_mode.c_str());
#endif

    if (file_handle != nullptr)
    {
        boost::system::error_code bec;
        uint64_t size_hint = boost::filesystem::file_size(path, bec);
        if (bec || size_hint == 0)
            size_hint = skDefaultBlockSize;

        return FileIO::Pointer(new FileIO(
                file_handle,
                size_hint
        ));
    }
    else
    {
        if ( error != nullptr )
            *error = std::error_code(errno, std::system_category());
        return FileIO::Pointer();
    }
}

FileIO::FileIO(
        FILE* file_handle,
        uint64_t size_hint
    ) :
    file_handle_(file_handle),
    size_hint_(size_hint)
{
    assert( size_hint_ != std::numeric_limits<uint64_t>::max() );
}

FileIO::~FileIO()
{
    fclose(file_handle_);
}

uint64_t FileIO::Read(
        void* buffer,
        uint64_t buffer_size,
        std::error_code * error
    )
{
    if (error)
        error->clear();

    uint64_t bytes_read = fread(buffer, 1, buffer_size, file_handle_);

    // Detect errors if requested
    if ( error != nullptr && bytes_read != buffer_size )
    {
        if ( feof(file_handle_) )
        {
            *error = make_error_code(file_io_error::EndOfFile);
        }
        else if ( ferror(file_handle_) )
        {
            *error = make_error_code(file_io_error::StreamError);
        }
        else
        {
            assert( ! "Unknown error in FileIO::Read" );
            *error = make_error_code(file_io_error::UnknownError);
        }
    }

    return bytes_read;
}

std::string FileIO::ReadString(
        uint64_t desired_bytes,
        std::error_code * error
    )
{
    if (error)
        error->clear();

    // Initialize
    std::string buffer;
    uint64_t total_bytes_read = 0;
    std::error_code read_error;

    try {
        // Calculate initial read size
        uint64_t read_size = std::min(desired_bytes, size_hint_ + 1);

        // Loop until we've read all desired or encounter an error
        while ( ! read_error && total_bytes_read < desired_bytes )
        {
            // Resize buffer
            buffer.resize(buffer.size() + read_size);

            // Calculate buffer position
            char* buffer_pos = &(&buffer.front())[total_bytes_read];

            // Read file
            uint64_t bytes_read = Read(buffer_pos, read_size, &read_error);
            total_bytes_read += bytes_read;

            // Ensure reads are complete or error
            assert( bytes_read == read_size || read_error );

            // Calculate next read size
            read_size = std::min(desired_bytes - total_bytes_read, skDefaultBlockSize);
        }
    }
    catch (const std::bad_alloc& a)
    {
        // std::bad_alloc can be thrown by std::string::resize if insufficient
        // memory
        read_error = make_error_code(file_io_error::NotEnoughMemory);
    }
    catch (const std::length_error&)
    {
        // std::length_error can be thrown by std::string::resize if arguments
        // is larger than string max size
        read_error = make_error_code(file_io_error::BufferTooLarge);
    }

    // Shrink buffer to actual bytes read
    buffer.resize(total_bytes_read);

    // Set return status
    if ( error != nullptr )
        *error = read_error;

    // Return read bytes
    return buffer;
}

std::string FileIO::ReadLine(
        std::error_code * error
    )
{
    if (error)
        error->clear();

    uint64_t bytes_consumed = 0;
    std::string lineData;

    // Read characters until we encounter an error, a newline, or we have read
    // too many bytes.
    int inputChar = fgetc(file_handle_);
    while ( inputChar != EOF && inputChar != '\n'
        && bytes_consumed < skDefaultReadSize )
    {
        lineData.push_back(static_cast<char>(inputChar));
        inputChar = fgetc(file_handle_);
        ++bytes_consumed;
    }

    // Set error condition
    if ( error != nullptr )
    {
        if ( inputChar == EOF )
        {   // Read error
            if ( feof(file_handle_) )
            {
                *error = make_error_code(file_io_error::EndOfFile);
            }
            else if ( ferror(file_handle_) )
            {
                *error = make_error_code(file_io_error::StreamError);
            }
            else
            {
                assert( ! "Unknown error in FileIO::Read" );
                *error = make_error_code(file_io_error::UnknownError);
            }
        }
        else if ( bytes_consumed >= skDefaultReadSize )
        {   // Reached our limit
            *error = make_error_code(file_io_error::LineTooLong);
        }
        else
        {   // No error
            assert( inputChar == '\n' );
        }
    }

    return lineData;
}

uint64_t FileIO::Write(
        const void* buffer,
        uint64_t buffer_size,
        std::error_code * error
    )
{
    if (error)
        error->clear();

    uint64_t bytes_written = fwrite(buffer, 1, buffer_size, file_handle_);

    // Detect errors if requested
    if ( error != nullptr && bytes_written != buffer_size )
    {
        if ( ferror(file_handle_) )
        {
            *error = make_error_code(file_io_error::StreamError);
        }
        else
        {
            assert( ! "Unknown error in FileIO::Write" );
            *error = make_error_code(file_io_error::UnknownError);
        }
    }

    return bytes_written;
}

uint64_t FileIO::WriteString(
        const std::string& buffer,
        std::error_code * error
    )
{
    return Write(buffer.data(), buffer.size(), error);
}

void FileIO::Seek(
        const SeekAnchor anchor,
        const uint64_t offset,
        std::error_code * error
    )
{
    if (error)
        error->clear();

    const int origin = [&anchor](){
        switch(anchor)
        {
            case SeekAnchor::Current:
                return SEEK_CUR;
                break;
            case SeekAnchor::Beginning:
                return SEEK_SET;
                break;
            case SeekAnchor::End:
                return SEEK_END;
                break;
            default:
                assert(!"Invalid anchor");
                return SEEK_CUR;
        }}();

#if defined(_WIN32)
#  if defined(_MSC_VER)
    const int res = _fseeki64(file_handle_, offset, origin);
#  else
    const int res = fseeko64(file_handle_, offset, origin);
#  endif
#else
    const int res = fseeko(file_handle_, offset, origin);
#endif

    if ( error != nullptr && res != 0 )
    {
        if ( ferror(file_handle_) )
        {
            *error = make_error_code(file_io_error::StreamError);
        }
        else
        {
            assert( ! "Unknown error in FileIO::Seek" );
            *error = make_error_code(file_io_error::UnknownError);
        }
    }
}

uint64_t FileIO::Tell()
{
#if defined(_WIN32)
#  if defined(_MSC_VER)
    uint64_t position = _ftelli64(file_handle_);
#  else
    uint64_t position = ftello64(file_handle_);
#  endif
#else
    uint64_t position = ftello(file_handle_);
#endif

    return position;
}

void FileIO::Flush()
{
    fflush(file_handle_);
}

}  // namespace utils
Пример #20
0
int main( int argc, char** argv )
{
   try {
      int window = 64;
      fc::time_point_sec origin   = fc::time_point::now();
      fc::microseconds   interval = fc::seconds( 60*5 );
      std::cout << "origin: "<< std::string(fc::time_point(origin)) <<" \n";
      std::cout << "interval: "<< interval.count() <<" us \n";
      std::cout << "initial difficulty: "<< std::string(fc::uint128(-1)) <<" \n";
      std::cout << "window: "<< window <<" \n";
      bts::blockchain::time_keeper tk;
      tk.configure( origin, interval, window );


      uint64_t base_diff = 1000000;

      uint32_t block_num = 0;
      
      for( uint32_t i = 0; i < 1; ++i )
      {
         tk.push_init( block_num, 
                  fc::time_point(origin) + fc::microseconds(interval.count() * i),
                  base_diff );
         ++block_num;
      }
      tk.init_stats();

      fc::time_point sim_time = tk.next_time();
      auto next_diff = tk.next_difficulty();
      if( next_diff < 5*60*1000000 ) next_diff = 5*60*1000000;

      int64_t maxerr = 0;
      int64_t minerr = 0;

      // randomly find blocks +/- 2 hours from expected time... 
      //   at the expected difficulty... this should result in
      //   an average difficulty that is about the same.
      for( uint64_t i = 0; true || i < 10000000; ++i )
      {

         tk.push( block_num, sim_time, next_diff  );
         next_diff = tk.next_difficulty();
    //     if( next_diff < 60*1000000 ) next_diff = 60*1000000;
         if( next_diff <= 0 ) next_diff = 1;
         ++block_num;

   //      if( block_num % 100 == 0 )
         {
      //     std::cerr<<" "<<(tk.current_time() - origin).count()/1000000<<", ";
       //    std::cerr<<" "<<(sim_time - origin).count()/1000000<<"\n";
           
           std::cout<< "block_num: "<<std::setw(10)<<block_num;
           std::cout<<"  cur_time:  "<<std::setw(11)<<std::string(tk.current_time());
           std::cout<<"  next_time: "<<std::setw(11)<<std::string(tk.next_time());
           std::cout<<"  delta_time: "<<std::right<<std::setw(14)<<(tk.next_time()-tk.current_time()-interval).count()/1000000<<" sec";
           std::cout<<"  cur_diff:  "<<std::right<<std::setw(14)<<tk.current_difficulty();
           std::cout<<"  next_diff: "<<std::right<<std::setw(14)<<next_diff;
           std::cout<<"  delta: "<<std::right<<std::setw(14)<<int64_t(next_diff-tk.current_difficulty());
           std::cout<<"  sim_time: "<<std::right<<std::setw(14)<<std::string(sim_time)<<" ";
           std::cout<<"  sim-cur:  "<<std::right<<std::setw(14)<<(sim_time-tk.current_time()).count()/1000000<<" ";
           std::cout<<"  timeerr:  "<<std::right<<std::setw(14)<<tk.current_time_error()<<"  ";
           std::cout<<"\n";
           if( tk.current_time_error() < minerr ) 
           {
             minerr = tk.current_time_error();
             ilog( "               MIN: ${m}", ("m",minerr) );
           }
           if( tk.current_time_error() > maxerr )
           {
             maxerr = tk.current_time_error();
             ilog( "MAX: ${m}", ("m",maxerr) );
           }
         }
         if( block_num == 10000 )
         {  
            std::cout<<"\n.... skip 4 hours ... \n";
            sim_time += fc::seconds(4*60*60); // off by 1 hour...
         }
         
         uint64_t a = rand();
         uint64_t b = rand();
         auto sample_1 = uint64_t(a*rand()) % next_diff;
         auto sample_2 = uint64_t(b*rand()) % next_diff;
         sim_time += fc::microseconds( sample_1 + sample_2 );
      }




      std::cout << "current_time:          "<< std::string( tk.current_time() ) <<"\n";
      std::cout << "next_time:             "<< std::string( tk.next_time() ) <<"\n";
      std::cout << "current_difficulty:    "<< tk.current_difficulty()  <<"\n";
      std::cout << "next_difficulty:       "<< tk.next_difficulty()  <<"\n";
      
      std::string line;
      std::getline( std::cin, line );
      while( std::cin )
      {
         std::stringstream ss(line);

          std::string time_str;
          uint64_t pow;
         ss >> time_str >> pow;

         tk.push( block_num, fc::time_point::from_iso_string(time_str), pow  );
         ++block_num;

         std::cout << "current_time:          "<< std::string( tk.current_time() ) <<"\n";
         std::cout << "next_time:             "<< std::string( tk.next_time() ) <<"\n";
         std::cout << "current_difficulty:    "<<  tk.current_difficulty()  <<"\n";
         std::cout << "next_difficulty:       "<<  tk.next_difficulty()  <<"\n";
         std::getline( std::cin, line );
      }


      return 0;
   } catch ( const fc::exception& e )
   {
     std::cout << e.to_detail_string() <<"\n";
   }
   return -1;
}
Пример #21
0
 static inline uint64_t _dataValue(level_index_type h, int idx) {
   return (uint64_t(h) << shiftAmount()) + idx;
 }
Пример #22
0
 value_type retrieve_value(uint64_t idx, uint64_t pos, uint64_t & l) const
 {
     assert(m_high_bits.bits()[pos] == 1);
     l = broadword::lsb(m_high_bits.bits().get_word(pos + 1));
     return ((uint64_t(1) << l) | m_low_bits.get_bits(pos - idx, l)) - 1;
 }
Пример #23
0
 basic_variant(unsigned long long v):base(uint64_t(v)) {}
nsresult nsTextAddress::ImportAddresses(bool *pAbort, const char16_t *pName,
                                        nsIFile *pSrc, nsIAddrDatabase *pDb,
                                        nsIImportFieldMap *fieldMap,
                                        nsString &errors, uint32_t *pProgress) {
  // Open the source file for reading, read each line and process it!
  m_database = pDb;
  m_fieldMap = fieldMap;

  nsCOMPtr<nsIInputStream> inputStream;
  nsresult rv = NS_NewLocalFileInputStream(getter_AddRefs(inputStream), pSrc);
  if (NS_FAILED(rv)) {
    IMPORT_LOG0("*** Error opening address file for reading\n");
    return rv;
  }

  // Here we use this to work out the size of the file, so we can update
  // an integer as we go through the file which will update a progress
  // bar if required by the caller.
  uint64_t bytesLeft = 0;
  rv = inputStream->Available(&bytesLeft);
  if (NS_FAILED(rv)) {
    IMPORT_LOG0("*** Error checking address file for size\n");
    inputStream->Close();
    return rv;
  }

  uint64_t totalBytes = bytesLeft;
  bool skipRecord = false;

  rv = m_fieldMap->GetSkipFirstRecord(&skipRecord);
  if (NS_FAILED(rv)) {
    IMPORT_LOG0(
        "*** Error checking to see if we should skip the first record\n");
    return rv;
  }

  nsCOMPtr<nsIUnicharLineInputStream> lineStream;
  rv = GetUnicharLineStreamForFile(pSrc, inputStream,
                                   getter_AddRefs(lineStream));
  if (NS_FAILED(rv)) {
    IMPORT_LOG0("*** Error opening converter stream for importer\n");
    return rv;
  }

  bool more = true;
  nsAutoString line;

  // Skip the first record if the user has requested it.
  if (skipRecord) rv = ReadRecord(lineStream, line, &more);

  while (!(*pAbort) && more && NS_SUCCEEDED(rv)) {
    // Read the line in
    rv = ReadRecord(lineStream, line, &more);
    if (NS_SUCCEEDED(rv)) {
      // Now process it to add it to the database
      rv = ProcessLine(line, errors);

      if (NS_FAILED(rv)) {
        IMPORT_LOG0("*** Error processing text record.\n");
      }
    }
    if (NS_SUCCEEDED(rv) && pProgress) {
      // This won't be totally accurate, but its the best we can do
      // considering that lineStream won't give us how many bytes
      // are actually left.
      bytesLeft -= line.Length();
      *pProgress = std::min(totalBytes - bytesLeft, uint64_t(PR_UINT32_MAX));
    }
  }

  inputStream->Close();

  if (NS_FAILED(rv)) {
    IMPORT_LOG0(
        "*** Error reading the address book - probably incorrect ending\n");
    return NS_ERROR_FAILURE;
  }

  return pDb->Commit(nsAddrDBCommitType::kLargeCommit);
}
Пример #25
0
uint64_t LZMA2Codec::doMaxUncompressedLength() const {
  // From lzma/base.h: "Stream is roughly 8 EiB (2^63 bytes)"
  return uint64_t(1) << 63;
}
Пример #26
0
void
jack_assistant::position (bool songmode, midipulse tick)
{

#ifdef SEQ64_JACK_SUPPORT

    long current_tick = 0;
    if (songmode)                               /* master in song mode */
    {
        if (! is_null_midipulse(tick))
            current_tick = tick * 10;
    }

    int ticks_per_beat = m_ppqn * 10;
    int beats_per_minute = parent().get_beats_per_minute();
    uint64_t tick_rate = (uint64_t(m_jack_frame_rate) * current_tick * 60.0);
    long tpb_bpm = ticks_per_beat * beats_per_minute * 4.0 / m_beat_width;
    uint64_t jack_frame = tick_rate / tpb_bpm;
    jack_transport_locate(m_jack_client, jack_frame);

#ifdef SEQ64_STAZED_JACK_SUPPORT

#if 0

    /*
     * The call to jack_BBT_position() is not necessary to change JACK
     * position!  Must set these here since they are set in timebase.
     */

    jack_position_t pos;
    double jack_tick = current_tick * m_bw / 4.0;
    pos.ticks_per_beat = m_ppqn * 10;
    pos.beats_per_minute = m_master_bus.get_bpm();
    jack_BBT_position(pos, jack_tick);

    /*
     * Calculate JACK frame to put into pos.frame; it is what matters for
     * position change.  Very similar to the uncommented code above.
     */

    uint64_t tick_rate = ((uint64_t)pos.frame_rate * current_tick * 60.0);
    long tpb_bpm = pos.ticks_per_beat * pos.beats_per_minute *
        4.0 / pos.beat_type;

    pos.frame = tick_rate / tpb_bpm;

    /*
     * ticks * 10 = jack ticks;
     * jack ticks / ticks per beat = num beats;
     * num beats / beats per minute = num minutes
     * num minutes * 60 = num seconds
     * num secords * frame_rate  = frame
     */

    jack_transport_reposition(m_jack_client, &pos);

#endif  // 0

    if (parent().is_running())
        parent().set_reposition(false);

#endif  // SEQ64_STAZED_JACK_SUPPORT

Tutorial code from jack_assistant::position():

#ifdef SAMPLE_AUDIO_CODE    // disabled, shown only for reference & learning
        jack_transport_state_t ts = jack_transport_query(jack->client(), NULL);
        if (ts == JackTransportRolling)
        {
            jack_default_audio_sample_t * in;
            jack_default_audio_sample_t * out;
            if (client_state == Init)
                client_state = Run;

            in = jack_port_get_buffer(input_port, nframes);
            out = jack_port_get_buffer(output_port, nframes);
            memcpy(out, in, sizeof (jack_default_audio_sample_t) * nframes);
        }
        else if (ts == JackTransportStopped)
        {
            if (client_state == Run)
                client_state = Exit;
        }
#endif

}
Пример #27
0
bool
WaveReader::LoadListChunk(uint32_t aChunkSize,
                          nsAutoPtr<dom::HTMLMediaElement::MetadataTags> &aTags)
{
  MOZ_ASSERT(OnTaskQueue());

  // List chunks are always word (two byte) aligned.
  MOZ_ASSERT(mResource.Tell() % 2 == 0,
             "LoadListChunk called with unaligned resource");

  static const unsigned int MAX_CHUNK_SIZE = 1 << 16;
  static_assert(uint64_t(MAX_CHUNK_SIZE) < UINT_MAX / sizeof(char),
                "MAX_CHUNK_SIZE too large for enumerator.");

  if (aChunkSize > MAX_CHUNK_SIZE || aChunkSize < 4) {
    return false;
  }

  auto chunk = MakeUnique<char[]>(aChunkSize);
  if (!ReadAll(chunk.get(), aChunkSize)) {
    return false;
  }

  static const uint32_t INFO_LIST_MAGIC = 0x494e464f;
  const char* p = chunk.get();
  if (ReadUint32BE(&p) != INFO_LIST_MAGIC) {
    return false;
  }

  const waveIdToName ID_TO_NAME[] = {
    { 0x49415254, NS_LITERAL_CSTRING("artist") },   // IART
    { 0x49434d54, NS_LITERAL_CSTRING("comments") }, // ICMT
    { 0x49474e52, NS_LITERAL_CSTRING("genre") },    // IGNR
    { 0x494e414d, NS_LITERAL_CSTRING("name") },     // INAM
  };

  const char* const end = chunk.get() + aChunkSize;

  aTags = new dom::HTMLMediaElement::MetadataTags;

  while (p + 8 < end) {
    uint32_t id = ReadUint32BE(&p);
    // Uppercase tag id, inspired by GStreamer's Wave parser.
    id &= 0xDFDFDFDF;

    uint32_t length = ReadUint32LE(&p);

    // Subchunk shall not exceed parent chunk.
    if (uint32_t(end - p) < length) {
      break;
    }

    // Wrap the string, adjusting length to account for optional
    // null termination in the chunk.
    nsCString val(p, length);
    if (length > 0 && val[length - 1] == '\0') {
      val.SetLength(length - 1);
    }

    // Chunks in List::INFO are always word (two byte) aligned. So round up if
    // necessary.
    length += length % 2;
    p += length;

    if (!IsUTF8(val)) {
      continue;
    }

    for (size_t i = 0; i < mozilla::ArrayLength(ID_TO_NAME); ++i) {
      if (id == ID_TO_NAME[i].id) {
        aTags->Put(ID_TO_NAME[i].name, val);
        break;
      }
    }
  }

  return true;
}
Пример #28
0
static uint64_t BytesToTime(int64_t offset, uint64_t length, uint64_t durationUs) {
  double perc = double(offset) / double(length);
  if (perc > 1.0)
    perc = 1.0;
  return uint64_t(double(durationUs) * perc);
}
Пример #29
0
uint128_t make_uint128( const char* string )
{
    MD5 md5( (unsigned char*)string );
    uint8_t* data = md5.raw_digest();

    const uint128_t 
        value( (uint64_t( data[7] )<<0) | (uint64_t( data[6] )<<8) |
               (uint64_t( data[5] )<<16) | (uint64_t( data[4] )<<24) |
               (uint64_t( data[3] )<<32) | (uint64_t( data[2] )<<40) |
               (uint64_t( data[1] )<<48) | (uint64_t( data[0] )<<56),
               (uint64_t( data[15] )<<0) | (uint64_t( data[14] )<<8) |
               (uint64_t( data[13] )<<16) | (uint64_t( data[12] )<<24) |
               (uint64_t( data[11] )<<32) | (uint64_t( data[10] )<<40) |
               (uint64_t( data[9] )<<48) | (uint64_t( data[8] )<<56) );
    delete [] data;
    return value;
}
Пример #30
0
 static void Profile(FoldingSetNodeID &ID, const AttributeWithIndex *Attr,
                     unsigned NumAttrs) {
     for (unsigned i = 0; i != NumAttrs; ++i)
         ID.AddInteger(uint64_t(Attr[i].Attrs) << 32 | unsigned(Attr[i].Index));
 }