Beispiel #1
0
ImageData* ImageData::create(DOMUint8ClampedArray* data,
                             unsigned width,
                             ExceptionState& exceptionState) {
  unsigned lengthInPixels = 0;
  if (!validateConstructorArguments(data, width, lengthInPixels,
                                    exceptionState)) {
    DCHECK(exceptionState.hadException());
    return nullptr;
  }
  DCHECK_GT(lengthInPixels, 0u);
  DCHECK_GT(width, 0u);
  unsigned height = lengthInPixels / width;
  return new ImageData(IntSize(width, height), data);
}
Beispiel #2
0
void NodeSet::traversalSort() const {
  HeapHashSet<Member<Node>> nodes;
  bool containsAttributeNodes = false;

  unsigned nodeCount = m_nodes.size();
  DCHECK_GT(nodeCount, 1u);
  for (unsigned i = 0; i < nodeCount; ++i) {
    Node* node = m_nodes[i].get();
    nodes.add(node);
    if (node->isAttributeNode())
      containsAttributeNodes = true;
  }

  HeapVector<Member<Node>> sortedNodes;
  sortedNodes.reserveInitialCapacity(nodeCount);

  for (Node& n : NodeTraversal::startsAt(*findRootNode(m_nodes.first()))) {
    if (nodes.contains(&n))
      sortedNodes.append(&n);

    if (!containsAttributeNodes || !n.isElementNode())
      continue;

    Element* element = toElement(&n);
    AttributeCollection attributes = element->attributes();
    for (auto& attribute : attributes) {
      Attr* attr = element->attrIfExists(attribute.name());
      if (attr && nodes.contains(attr))
        sortedNodes.append(attr);
    }
  }

  DCHECK_EQ(sortedNodes.size(), nodeCount);
  const_cast<HeapVector<Member<Node>>&>(m_nodes).swap(sortedNodes);
}
SplitTextNodeContainingElementCommand::SplitTextNodeContainingElementCommand(
    Text* text,
    int offset)
    : CompositeEditCommand(text->document()), m_text(text), m_offset(offset) {
  DCHECK(m_text);
  DCHECK_GT(m_text->length(), 0u);
}
Beispiel #4
0
size_t HTTPTransaction::sendBodyNow(std::unique_ptr<folly::IOBuf> body,
                                    size_t bodyLen, bool sendEom) {
  static const std::string noneStr = "None";
  DCHECK(body);
  DCHECK_GT(bodyLen, 0);
  size_t nbytes = 0;
  if (useFlowControl_) {
    CHECK(sendWindow_.reserve(bodyLen));
  }
  VLOG(4) << *this << " Sending " << bodyLen << " bytes of body. eom="
          << ((sendEom) ? "yes" : "no") << " send_window is "
          << ( useFlowControl_ ?
               folly::to<std::string>(sendWindow_.getSize(), " / ",
                                      sendWindow_.getCapacity()) : noneStr);
  if (sendEom) {
    CHECK(HTTPTransactionEgressSM::transit(
            egressState_, HTTPTransactionEgressSM::Event::eomFlushed));
  } else if (ingressErrorSeen_ && isExpectingWindowUpdate()) {
    // I don't know how we got here but we're in trouble.  We need a window
    // update to continue but we've already seen an ingress error.
    HTTPException ex(HTTPException::Direction::INGRESS_AND_EGRESS,
                     folly::to<std::string>("window blocked with ingress error,"
                                            " streamID=", id_));
    ex.setProxygenError(kErrorEOF);
    ex.setCodecStatusCode(ErrorCode::FLOW_CONTROL_ERROR);
    onError(ex);
    return 0;
  }
  updateReadTimeout();
  nbytes = transport_.sendBody(this, std::move(body), sendEom);
  if (egressLimitBytesPerMs_ > 0) {
    numLimitedBytesEgressed_ += nbytes;
  }
  return nbytes;
}
 /**
  * @brief Constructor for merging sorted runs to generate a sorted relation.
  *
  * @param input_relation The relation to merge sorted blocks.
  * @param output_relation The output relation.
  * @param output_destination_index The index of the InsertDestination in the
  *        QueryContext to store the sorted blocks in.
  * @param run_relation The temporary relation used to store intermediate runs
  *                     of blocks.
  * @param run_block_destination_index The index of the InsertDestination in
  *        the QueryContext to store the intermediate blocks in the merging
  *        process.
  * @param sort_config_index The index of the Sort configuration in
  *        QueryContext.
  * @param merge_factor Merge factor of this operator.
  * @param top_k Only return the first \c top_k results. Return all results if
  *              \c top_k is 0.
  * @param input_relation_is_stored Boolean to indicate is input relation is
  *                                 stored or streamed.
  **/
 SortMergeRunOperator(const CatalogRelation &input_relation,
                      const CatalogRelation &output_relation,
                      const QueryContext::insert_destination_id output_destination_index,
                      const CatalogRelation &run_relation,
                      const QueryContext::insert_destination_id run_block_destination_index,
                      const QueryContext::sort_config_id sort_config_index,
                      const std::size_t merge_factor,
                      const std::size_t top_k,
                      const bool input_relation_is_stored)
     : input_relation_(input_relation),
       output_relation_(output_relation),
       output_destination_index_(output_destination_index),
       sort_config_index_(sort_config_index),
       merge_factor_(merge_factor),
       top_k_(top_k),
       merge_tree_(merge_factor_),
       input_relation_block_ids_(input_relation_is_stored
                                     ? input_relation.getBlocksSnapshot()
                                     : std::vector<block_id>()),
       num_input_workorders_generated_(0),
       run_relation_(run_relation),
       run_block_destination_index_(run_block_destination_index),
       input_relation_is_stored_(input_relation_is_stored),
       input_stream_done_(input_relation_is_stored),
       started_(false) {
   DCHECK_GT(merge_factor_, 1u);
 }
Beispiel #6
0
bool PathService::Override(int key, const FilePath& path)
{
    PathData* path_data = GetPathData();
    DCHECK(path_data);
    DCHECK_GT(key, base::DIR_CURRENT) << "invalid path key";

    FilePath file_path = path;

    // Make sure the directory exists. We need to do this before we translate
    // this to the absolute path because on POSIX, AbsolutePath fails if called
    // on a non-existant path.
    if(!base::PathExists(file_path) && !base::CreateDirectory(file_path))
    {
        return false;
    }

    // We need to have an absolute path, as extensions and plugins don't like
    // relative paths, and will glady crash the browser in CHECK()s if they get a
    // relative path.
    if(!base::AbsolutePath(&file_path))
    {
        return false;
    }

    base::AutoLock scoped_lock(path_data->lock);

    // Clear the cache now. Some of its entries could have depended
    // on the value we are overriding, and are now out of sync with reality.
    path_data->cache.clear();

    path_data->cache[key] = file_path;
    path_data->overrides[key] = file_path;

    return true;
}
Beispiel #7
0
void PathService::RegisterProvider(ProviderFunc func, int key_start,
                                   int key_end)
{
    PathData* path_data = GetPathData();
    DCHECK(path_data);
    DCHECK_GT(key_end, key_start);

    base::AutoLock scoped_lock(path_data->lock);

    Provider* p;

#ifndef NDEBUG
    p = path_data->providers;
    while(p)
    {
        DCHECK(key_start >= p->key_end || key_end <= p->key_start) <<
            "path provider collision";
        p = p->next;
    }
#endif

    p = new Provider;
    p->is_static = false;
    p->func = func;
    p->next = path_data->providers;
#ifndef NDEBUG
    p->key_start = key_start;
    p->key_end = key_end;
#endif
    path_data->providers = p;
}
/*
 * Copy "len" bytes from "src" to "op", one byte at a time.  Used for
 * handling COPY operations where the input and output regions may
 * overlap.  For example, suppose:
 *    src    == "ab"
 *    op     == src + 2
 *    len    == 20
 * After IncrementalCopy(src, op, len), the result will have
 * eleven copies of "ab"
 *    ababababababababababab
 * Note that this does not match the semantics of either memcpy()
 * or memmove().
 */
static inline void IncrementalCopy(const char *src, char *op, int len)
{
	DCHECK_GT(len, 0);
	do {
		*op++ = *src++;
	} while (--len > 0);
}
BytesWriteHandler::BytesWriteHandler(size_t grow)
    : grow_(grow),
      datasize_(grow),
      offset_(0) {
  DCHECK_GT(grow, 0U);
  data_ = malloc(grow);
  DCHECK(data_ != NULL);
}
ImageBuffer::~ImageBuffer()
{
    if (m_gpuMemoryUsage) {
        DCHECK_GT(s_globalAcceleratedImageBufferCount, 0u);
        s_globalAcceleratedImageBufferCount--;
    }
    ImageBuffer::s_globalGPUMemoryUsage -= m_gpuMemoryUsage;
}
Beispiel #11
0
void NotificationResourcesLoader::didFinishRequest() {
  DCHECK_GT(m_pendingRequestCount, 0);
  m_pendingRequestCount--;
  if (!m_pendingRequestCount) {
    stop();
    (*m_completionCallback)(this);
    // The |this| pointer may have been deleted now.
  }
}
 inline std::size_t reduceEstimatedCardinality(
     const std::size_t original_estimate) const {
   if (original_estimate < kEstimateReductionFactor) {
     return original_estimate;
   } else {
     DCHECK_GT(kEstimateReductionFactor, 0u);
     return original_estimate / kEstimateReductionFactor;
   }
 }
 /**
  * @brief Add a mapping between a block and the NUMA node on which the block
  *        is placed.
  *
  * @param block The block_id of the block for which the NUMA node mapping is
  *              added.
  * @param numa_node The numa node id on which the block is placed.
  **/
 void addBlockToNUMANodeMap(const block_id block, const int numa_node) {
   // Make sure that the block doesn't have a mapping already.
   // A block will be mapped to only one NUMA node.
   // A NUMA node will be associated with a block only once.
   DCHECK(block_to_numa_node_map_.find(block) == block_to_numa_node_map_.end());
   DCHECK_GT(numa_num_configured_nodes(), numa_node)
       << "NUMA node above the valid value.";
   block_to_numa_node_map_[block] = numa_node;
 }
Beispiel #14
0
CachedMetadata::CachedMetadata(const char* data, size_t size) {
  // We need to define a local variable to use the constant in DCHECK.
  constexpr auto kDataStart = CachedMetadata::kDataStart;
  // Serialized metadata should have non-empty data.
  DCHECK_GT(size, kDataStart);
  DCHECK(data);

  m_serializedData.reserveInitialCapacity(size);
  m_serializedData.append(data, size);
}
Beispiel #15
0
IIRProcessor::IIRProcessor(float sampleRate,
                           size_t numberOfChannels,
                           const Vector<double>& feedforwardCoef,
                           const Vector<double>& feedbackCoef)
    : AudioDSPKernelProcessor(sampleRate, numberOfChannels) {
  unsigned feedbackLength = feedbackCoef.size();
  unsigned feedforwardLength = feedforwardCoef.size();
  DCHECK_GT(feedbackLength, 0u);
  DCHECK_GT(feedforwardLength, 0u);

  m_feedforward.allocate(feedforwardLength);
  m_feedback.allocate(feedbackLength);
  m_feedforward.copyToRange(feedforwardCoef.data(), 0, feedforwardLength);
  m_feedback.copyToRange(feedbackCoef.data(), 0, feedbackLength);

  // Need to scale the feedback and feedforward coefficients appropriately.
  // (It's up to the caller to ensure feedbackCoef[0] is not 0.)
  DCHECK_NE(feedbackCoef[0], 0);

  if (feedbackCoef[0] != 1) {
    // The provided filter is:
    //
    //   a[0]*y(n) + a[1]*y(n-1) + ... = b[0]*x(n) + b[1]*x(n-1) + ...
    //
    // We want the leading coefficient of y(n) to be 1:
    //
    //   y(n) + a[1]/a[0]*y(n-1) + ... = b[0]/a[0]*x(n) + b[1]/a[0]*x(n-1) + ...
    //
    // Thus, the feedback and feedforward coefficients need to be scaled by
    // 1/a[0].
    float scale = feedbackCoef[0];
    for (unsigned k = 1; k < feedbackLength; ++k)
      m_feedback[k] /= scale;

    for (unsigned k = 0; k < feedforwardLength; ++k)
      m_feedforward[k] /= scale;

    // The IIRFilter checks to make sure this coefficient is 1, so make it so.
    m_feedback[0] = 1;
  }

  m_responseKernel = WTF::makeUnique<IIRDSPKernel>(this);
}
Beispiel #16
0
    FieldTrial::FieldTrial(const std::string& name,
        const Probability total_probability,
        const std::string& default_group_name,
        const int year,
        const int month,
        const int day_of_month)
        : name_(name),
        divisor_(total_probability),
        default_group_name_(default_group_name),
        random_(static_cast<Probability>(divisor_*RandDouble())),
        accumulated_group_probability_(0),
        next_group_number_(kDefaultGroupNumber+1),
        group_(kNotFinalized),
        enable_field_trial_(true)
    {
        DCHECK_GT(total_probability, 0);
        DCHECK(!name_.empty());
        DCHECK(!default_group_name_.empty());
        FieldTrialList::Register(this);

        DCHECK_GT(year, 1970);
        DCHECK_GT(month, 0);
        DCHECK_LT(month, 13);
        DCHECK_GT(day_of_month, 0);
        DCHECK_LT(day_of_month, 32);

        Time::Exploded exploded;
        exploded.year = year;
        exploded.month = month;
        exploded.day_of_week = 0; // Should be unused.
        exploded.day_of_month = day_of_month;
        exploded.hour = 0;
        exploded.minute = 0;
        exploded.second = 0;
        exploded.millisecond = 0;

        Time expiration_time = Time::FromLocalExploded(exploded);
        if(GetBuildTime() > expiration_time)
        {
            Disable();
        }
    }
Beispiel #17
0
ImageData* ImageData::create(DOMUint8ClampedArray* data,
                             unsigned width,
                             unsigned height,
                             ExceptionState& exceptionState) {
  unsigned lengthInPixels = 0;
  if (!validateConstructorArguments(data, width, lengthInPixels,
                                    exceptionState)) {
    DCHECK(exceptionState.hadException());
    return nullptr;
  }
  DCHECK_GT(lengthInPixels, 0u);
  DCHECK_GT(width, 0u);
  if (height != lengthInPixels / width) {
    exceptionState.throwDOMException(
        IndexSizeError,
        "The input data byte length is not equal to (4 * width * height).");
    return nullptr;
  }
  return new ImageData(IntSize(width, height), data);
}
Beispiel #18
0
ProcessReturnCode Subprocess::poll() {
  returnCode_.enforce(ProcessReturnCode::RUNNING);
  DCHECK_GT(pid_, 0);
  int status;
  pid_t found = ::waitpid(pid_, &status, WNOHANG);
  checkUnixError(found, "waitpid");
  if (found != 0) {
    returnCode_ = ProcessReturnCode(status);
    pid_ = -1;
  }
  return returnCode_;
}
std::unique_ptr<IOBuf> ZlibStreamDecompressor::decompress(const IOBuf* in) {
  auto out = IOBuf::create(decompressor_buffer_growth_);
  auto appender = folly::io::Appender(out.get(), decompressor_buffer_growth_);

  const IOBuf* crtBuf = in;
  size_t offset = 0;
  while (true) {
    // Advance to the next IOBuf if necessary
    DCHECK_GE(crtBuf->length(), offset);
    if (crtBuf->length() == offset) {
      crtBuf = crtBuf->next();
      offset = 0;
      if (crtBuf == in) {
        // We hit the end of the IOBuf chain, and are done.
        break;
      }
    }

    if (status_ == Z_STREAM_END) {
      // we convert this into a stream error
      status_ = Z_STREAM_ERROR;
      // we should probably bump up a counter here
      LOG(ERROR) << "error uncompressing buffer: reached end of zlib data "
                    "before the end of the buffer";
      return nullptr;
    }

    // Ensure there is space in the output IOBuf
    appender.ensure(decompressor_buffer_minsize_);
    DCHECK_GT(appender.length(), 0);

    const size_t origAvailIn = crtBuf->length() - offset;
    zlibStream_.next_in = const_cast<uint8_t*>(crtBuf->data() + offset);
    zlibStream_.avail_in = origAvailIn;
    zlibStream_.next_out = appender.writableData();
    zlibStream_.avail_out = appender.length();
    status_ = inflate(&zlibStream_, Z_PARTIAL_FLUSH);
    if (status_ != Z_OK && status_ != Z_STREAM_END) {
      LOG(INFO) << "error uncompressing buffer: r=" << status_;
      return nullptr;
    }

    // Adjust the input offset ahead
    auto inConsumed = origAvailIn - zlibStream_.avail_in;
    offset += inConsumed;
    // Move output buffer ahead
    auto outMove = appender.length() - zlibStream_.avail_out;
    appender.append(outMove);
  }

  return out;
}
Beispiel #20
0
ProcessReturnCode Subprocess::wait() {
  returnCode_.enforce(ProcessReturnCode::RUNNING);
  DCHECK_GT(pid_, 0);
  int status;
  pid_t found;
  do {
    found = ::waitpid(pid_, &status, 0);
  } while (found == -1 && errno == EINTR);
  checkUnixError(found, "waitpid");
  DCHECK_EQ(found, pid_);
  returnCode_ = ProcessReturnCode(status);
  return returnCode_;
}
void RadioButtonGroup::updateRequiredButton(MemberKeyValue& it,
                                            bool isRequired) {
  if (it.value == isRequired)
    return;

  it.value = isRequired;
  if (isRequired) {
    m_requiredCount++;
  } else {
    DCHECK_GT(m_requiredCount, 0u);
    m_requiredCount--;
  }
}
Beispiel #22
0
// helper method for case where needles.size() <= 16
size_t qfind_first_byte_of_needles16(const StringPieceLite haystack,
                                     const StringPieceLite needles) {
  DCHECK_GT(haystack.size(), 0u);
  DCHECK_GT(needles.size(), 0u);
  DCHECK_LE(needles.size(), 16u);
  if ((needles.size() <= 2 && haystack.size() >= 256) ||
      // must bail if we can't even SSE-load a single segment of haystack
      (haystack.size() < 16 &&
       page_for(haystack.end() - 1) != page_for(haystack.data() + 15)) ||
      // can't load needles into SSE register if it could cross page boundary
      page_for(needles.end() - 1) != page_for(needles.data() + 15)) {
    return detail::qfind_first_byte_of_nosse(haystack, needles);
  }

  auto arr2 = _mm_loadu_si128(
      reinterpret_cast<const __m128i*>(needles.data()));
  // do an unaligned load for first block of haystack
  auto arr1 = _mm_loadu_si128(
      reinterpret_cast<const __m128i*>(haystack.data()));
  auto index =
      _mm_cmpestri(arr2, int(needles.size()), arr1, int(haystack.size()), 0);
  if (index < 16) {
    return index;
  }

  // Now, we can do aligned loads hereafter...
  size_t i = nextAlignedIndex(haystack.data());
  for (; i < haystack.size(); i+= 16) {
    arr1 =
        _mm_load_si128(reinterpret_cast<const __m128i*>(haystack.data() + i));
    index = _mm_cmpestri(
        arr2, int(needles.size()), arr1, int(haystack.size() - i), 0);
    if (index < 16) {
      return i + index;
    }
  }
  return std::string::npos;
}
Beispiel #23
0
ProcessReturnCode Subprocess::poll() {
  returnCode_.enforce(ProcessReturnCode::RUNNING);
  DCHECK_GT(pid_, 0);
  int status;
  pid_t found = ::waitpid(pid_, &status, WNOHANG);
  checkUnixError(found, "waitpid");
  if (found != 0) {
    // Though the child process had quit, this call does not close the pipes
    // since its descendants may still be using them.
    returnCode_ = ProcessReturnCode(status);
    pid_ = -1;
  }
  return returnCode_;
}
Beispiel #24
0
static CString encodeComplexWindowsLatin1(const CharType* characters,
                                          size_t length,
                                          UnencodableHandling handling) {
  size_t targetLength = length;
  Vector<char> result(targetLength);
  char* bytes = result.data();

  size_t resultLength = 0;
  for (size_t i = 0; i < length;) {
    UChar32 c;
    // If CharType is LChar the U16_NEXT call reads a byte and increments;
    // since the convention is that LChar is already latin1 this is safe.
    U16_NEXT(characters, i, length, c);
    // If input was a surrogate pair (non-BMP character) then we overestimated
    // the length.
    if (c > 0xffff)
      --targetLength;
    unsigned char b = static_cast<unsigned char>(c);
    // Do an efficient check to detect characters other than 00-7F and A0-FF.
    if (b != c || (c & 0xE0) == 0x80) {
      // Look for a way to encode this with Windows Latin-1.
      for (b = 0x80; b < 0xA0; ++b) {
        if (table[b] == c)
          goto gotByte;
      }
      // No way to encode this character with Windows Latin-1.
      UnencodableReplacementArray replacement;
      int replacementLength =
          TextCodec::getUnencodableReplacement(c, handling, replacement);
      DCHECK_GT(replacementLength, 0);
      // Only one char was initially reserved per input character, so grow if
      // necessary. Note that the case of surrogate pairs and
      // QuestionMarksForUnencodables the result length may be shorter than
      // the input length.
      targetLength += replacementLength - 1;
      if (targetLength > result.size()) {
        result.grow(targetLength);
        bytes = result.data();
      }
      memcpy(bytes + resultLength, replacement, replacementLength);
      resultLength += replacementLength;
      continue;
    }
  gotByte:
    bytes[resultLength++] = b;
  }

  return CString(bytes, resultLength);
}
Beispiel #25
0
ProcessReturnCode Subprocess::wait() {
  returnCode_.enforce(ProcessReturnCode::RUNNING);
  DCHECK_GT(pid_, 0);
  int status;
  pid_t found;
  do {
    found = ::waitpid(pid_, &status, 0);
  } while (found == -1 && errno == EINTR);
  checkUnixError(found, "waitpid");
  // Though the child process had quit, this call does not close the pipes
  // since its descendants may still be using them.
  DCHECK_EQ(found, pid_);
  returnCode_ = ProcessReturnCode(status);
  pid_ = -1;
  return returnCode_;
}
void CanvasRenderingContext2D::validateStateStack() const {
#if DCHECK_IS_ON()
  if (SkCanvas* skCanvas = canvas()->existingDrawingCanvas()) {
    // The canvas should always have an initial save frame, to support
    // resetting the top level matrix and clip.
    DCHECK_GT(skCanvas->getSaveCount(), 1);

    if (m_contextLostMode == NotLostContext) {
      DCHECK_EQ(static_cast<size_t>(skCanvas->getSaveCount()),
                m_stateStack.size() + 1);
    }
  }
#endif
  CHECK(m_stateStack.first()
            .get());  // Temporary for investigating crbug.com/648510
}
Beispiel #27
0
string ToZeroPaddedString(std::uint64_t val, int pad_width) {
  DCHECK_GT(pad_width, 0);
  const std::size_t str_len = pad_width + 1;
  char *str = new char[str_len]();

  int bytes = snprintf(str,
                       str_len,
                       "%0*" PRIu64,
                       pad_width,
                       val);
  DCHECK_EQ(pad_width, bytes);

  string result(str, pad_width);
  delete[] str;

  return result;
}
Beispiel #28
0
    uint64 RandGenerator(uint64 range)
    {
        DCHECK_GT(range, 0u);

        // We must discard random results above this number, as they would
        // make the random generator non-uniform (consider e.g. if
        // MAX_UINT64 was 7 and |range| was 5, then a result of 1 would be twice
        // as likely as a result of 3 or 4).
        uint64 max_acceptable_value =
            (std::numeric_limits<uint64>::max() / range) * range - 1;

        uint64 value;
        do
        {
            value = base::RandUint64();
        } while(value >= max_acceptable_value);

        return value % range;
    }
Beispiel #29
0
size_t scanHaystackBlock(const StringPieceLite haystack,
                         const StringPieceLite needles,
                         uint64_t blockStartIdx) {
  DCHECK_GT(needles.size(), 16u); // should handled by *needles16() method
  DCHECK(blockStartIdx + 16 <= haystack.size() ||
         (page_for(haystack.data() + blockStartIdx) ==
          page_for(haystack.data() + blockStartIdx + 15)));

  __m128i arr1;
  if (HAYSTACK_ALIGNED) {
    arr1 = _mm_load_si128(
        reinterpret_cast<const __m128i*>(haystack.data() + blockStartIdx));
  } else {
    arr1 = _mm_loadu_si128(
        reinterpret_cast<const __m128i*>(haystack.data() + blockStartIdx));
  }

  // This load is safe because needles.size() >= 16
  auto arr2 = _mm_loadu_si128(
      reinterpret_cast<const __m128i*>(needles.data()));
  size_t b =
      _mm_cmpestri(arr2, 16, arr1, int(haystack.size() - blockStartIdx), 0);

  size_t j = nextAlignedIndex(needles.data());
  for (; j < needles.size(); j += 16) {
    arr2 = _mm_load_si128(
        reinterpret_cast<const __m128i*>(needles.data() + j));

    auto index = _mm_cmpestri(
        arr2,
        int(needles.size() - j),
        arr1,
        int(haystack.size() - blockStartIdx),
        0);
    b = std::min<size_t>(index, b);
  }

  if (b < 16) {
    return blockStartIdx + b;
  }
  return std::string::npos;
}
Beispiel #30
0
bool IOBufEqual::operator()(const IOBuf& a, const IOBuf& b) const {
  io::Cursor ca(&a);
  io::Cursor cb(&b);
  for (;;) {
    auto ba = ca.peekBytes();
    auto bb = cb.peekBytes();
    if (ba.empty() && bb.empty()) {
      return true;
    } else if (ba.empty() || bb.empty()) {
      return false;
    }
    size_t n = std::min(ba.size(), bb.size());
    DCHECK_GT(n, 0u);
    if (memcmp(ba.data(), bb.data(), n)) {
      return false;
    }
    ca.skip(n);
    cb.skip(n);
  }
}