• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

C++ size_t函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C++中size_t函数的典型用法代码示例。如果您正苦于以下问题:C++ size_t函数的具体用法?C++ size_t怎么用?C++ size_t使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了size_t函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的C++代码示例。

示例1: createFileFromTemplate

/*!
    \internal

    Generates a unique file path and returns a native handle to the open file.
    \a path is used as a template when generating unique paths, \a pos
    identifies the position of the first character that will be replaced in the
    template and \a length the number of characters that may be substituted.

    Returns an open handle to the newly created file if successful, an invalid
    handle otherwise. In both cases, the string in \a path will be changed and
    contain the generated path name.
*/
static bool createFileFromTemplate(NativeFileHandle &file,
                                   QFileSystemEntry::NativePath &path, size_t pos, size_t length,
                                   QSystemError &error)
{
    Q_ASSERT(length != 0);
    Q_ASSERT(pos < size_t(path.length()));
    Q_ASSERT(length <= size_t(path.length()) - pos);

    Char *const placeholderStart = (Char *)path.data() + pos;
    Char *const placeholderEnd = placeholderStart + length;

    // Initialize placeholder with random chars + PID.
    {
        Char *rIter = placeholderEnd;

#if defined(QT_BUILD_CORE_LIB)
        quint64 pid = quint64(QCoreApplication::applicationPid());
        do {
            *--rIter = Latin1Char((pid % 10) + '0');
            pid /= 10;
        } while (rIter != placeholderStart && pid != 0);
#endif

        while (rIter != placeholderStart) {
            char ch = char((qrand() & 0xffff) % (26 + 26));
            if (ch < 26)
                *--rIter = Latin1Char(ch + 'A');
            else
                *--rIter = Latin1Char(ch - 26 + 'a');
        }
    }

    for (;;) {
        // Atomically create file and obtain handle
#if defined(Q_OS_WIN)
        file = CreateFile((const wchar_t *)path.constData(),
                          GENERIC_READ | GENERIC_WRITE,
                          FILE_SHARE_READ | FILE_SHARE_WRITE, NULL, CREATE_NEW,
                          FILE_ATTRIBUTE_NORMAL, NULL);

        if (file != INVALID_HANDLE_VALUE)
            return true;

        DWORD err = GetLastError();
        if (err == ERROR_ACCESS_DENIED) {
            DWORD attributes = GetFileAttributes((const wchar_t *)path.constData());
            if (attributes == INVALID_FILE_ATTRIBUTES) {
                // Potential write error (read-only parent directory, etc.).
                error = QSystemError(err, QSystemError::NativeError);
                return false;
            } // else file already exists as a directory.
        } else if (err != ERROR_FILE_EXISTS) {
            error = QSystemError(err, QSystemError::NativeError);
            return false;
        }
#else // POSIX
        file = QT_OPEN(path.constData(),
                       QT_OPEN_CREAT | O_EXCL | QT_OPEN_RDWR | QT_OPEN_LARGEFILE,
                       0600);

        if (file != -1)
            return true;

        int err = errno;
        if (err != EEXIST) {
            error = QSystemError(err, QSystemError::NativeError);
            return false;
        }
#endif

        /* tricky little algorwwithm for backward compatibility */
        for (Char *iter = placeholderStart;;) {
            // Character progression: [0-9] => 'a' ... 'z' => 'A' .. 'Z'
            // String progression: "ZZaiC" => "aabiC"
            switch (char(*iter)) {
            case 'Z':
                // Rollover, advance next character
                *iter = Latin1Char('a');
                if (++iter == placeholderEnd) {
                    // Out of alternatives. Return file exists error, previously set.
                    error = QSystemError(err, QSystemError::NativeError);
                    return false;
                }

                continue;

            case '0':
            case '1':
//.........这里部分代码省略.........
开发者ID:xjohncz,项目名称:qt5,代码行数:101,代码来源:qtemporaryfile.cpp


示例2: size_t

void Fixup<Bios>(Bios& p)
{
	p.size = size_t(p.encodedSize+1) * 64*KiB;
}
开发者ID:righnatios,项目名称:0ad,代码行数:4,代码来源:smbios.cpp


示例3: asynclog_delete

/** Adds an asynchronous request to the event log. */
void asynclog_delete(proxy_t* proxy,
                     const AccessPoint& ap,
                     folly::StringPiece key,
                     folly::StringPiece poolName) {
  dynamic json = {};
  const auto& host = ap.getHost();
  const auto& port = proxy->router().opts().asynclog_port_override == 0
    ? ap.getPort()
    : proxy->router().opts().asynclog_port_override;

  if (proxy->router().opts().use_asynclog_version2) {
    json = dynamic::object;
    json["f"] = proxy->router().opts().flavor_name;
    json["h"] = folly::sformat("[{}]:{}", host, port);
    json["p"] = poolName.str();
    json["k"] = key.str();
  } else {
    /* ["host", port, escaped_command] */
    json.push_back(host);
    json.push_back(port);
    json.push_back(folly::sformat("delete {}\r\n", key));
  }

  auto fd = asynclog_open(proxy);
  if (!fd) {
    MC_LOG_FAILURE(proxy->router().opts(),
                   memcache::failure::Category::kSystemError,
                   "asynclog_open() failed (key {}, pool {})",
                   key, poolName);
    return;
  }

  // ["AS1.0", 1289416829.836, "C", ["10.0.0.1", 11302, "delete foo\r\n"]]
  // OR ["AS2.0", 1289416829.836, "C", {"f":"flavor","h":"[10.0.0.1]:11302",
  //                                    "p":"pool_name","k":"foo\r\n"}]
  dynamic jsonOut = {};
  if (proxy->router().opts().use_asynclog_version2) {
    jsonOut.push_back(ASYNCLOG_MAGIC2);
  } else {
    jsonOut.push_back(ASYNCLOG_MAGIC);
  }

  struct timeval timestamp;
  CHECK(gettimeofday(&timestamp, nullptr) == 0);

  auto timestamp_ms =
    facebook::memcache::to<std::chrono::milliseconds>(timestamp).count();

  jsonOut.push_back(1e-3 * timestamp_ms);
  jsonOut.push_back(std::string("C"));

  jsonOut.push_back(json);

  auto jstr = folly::toJson(jsonOut) + "\n";

  ssize_t size = folly::writeFull(fd->fd(), jstr.data(), jstr.size());
  if (size == -1 || size_t(size) < jstr.size()) {
    MC_LOG_FAILURE(proxy->router().opts(),
                   memcache::failure::Category::kSystemError,
                   "Error fully writing asynclog request (key {}, pool {})",
                   key, poolName);
  }
}
开发者ID:cicerocomp,项目名称:mcrouter,代码行数:64,代码来源:async.cpp


示例4: feature_group

ndsize_t BaseTagHDF5::featureCount() const {
    boost::optional<H5Group> g = feature_group(false);
    return g ? g->objectCount() : size_t(0);
}
开发者ID:G-Node,项目名称:nix,代码行数:4,代码来源:BaseTagHDF5.cpp


示例5: very_busy

 bool very_busy() const { return jobs_in_queue() > size_t(4 * m_size); }
开发者ID:AtomicFiction,项目名称:oiio,代码行数:1,代码来源:thread.cpp


示例6: db

int WorldSocket::handle_input_missing_data(void)
{
    char buf [4096];

    ACE_Data_Block db(sizeof(buf),
                      ACE_Message_Block::MB_DATA,
                      buf,
                      0,
                      0,
                      ACE_Message_Block::DONT_DELETE,
                      0);

    ACE_Message_Block message_block(&db,
                                    ACE_Message_Block::DONT_DELETE,
                                    0);

    const size_t recv_size = message_block.space();

    const ssize_t n = peer().recv(message_block.wr_ptr(),
                                  recv_size);

    if (n <= 0)
        return (int)n;

    message_block.wr_ptr(n);

    while (message_block.length() > 0)
    {
        if (m_Header.space() > 0)
        {
            // need to receive the header
            const size_t to_header = (message_block.length() > m_Header.space() ? m_Header.space() : message_block.length());
            m_Header.copy(message_block.rd_ptr(), to_header);
            message_block.rd_ptr(to_header);

            if (m_Header.space() > 0)
            {
                // Couldn't receive the whole header this time.
                MANGOS_ASSERT(message_block.length() == 0);
                errno = EWOULDBLOCK;
                return -1;
            }

            // We just received nice new header
            if (handle_input_header() == -1)
            {
                MANGOS_ASSERT((errno != EWOULDBLOCK) && (errno != EAGAIN));
                return -1;
            }
        }

        // Its possible on some error situations that this happens
        // for example on closing when epoll receives more chunked data and stuff
        // hope this is not hack ,as proper m_RecvWPct is asserted around
        if (!m_RecvWPct)
        {
            sLog.outError("Forcing close on input m_RecvWPct = NULL");
            errno = EINVAL;
            return -1;
        }

        // We have full read header, now check the data payload
        if (m_RecvPct.space() > 0)
        {
            // need more data in the payload
            const size_t to_data = (message_block.length() > m_RecvPct.space() ? m_RecvPct.space() : message_block.length());
            m_RecvPct.copy(message_block.rd_ptr(), to_data);
            message_block.rd_ptr(to_data);

            if (m_RecvPct.space() > 0)
            {
                // Couldn't receive the whole data this time.
                MANGOS_ASSERT(message_block.length() == 0);
                errno = EWOULDBLOCK;
                return -1;
            }
        }

        // just received fresh new payload
        if (handle_input_payload() == -1)
        {
            MANGOS_ASSERT((errno != EWOULDBLOCK) && (errno != EAGAIN));
            return -1;
        }
    }

    return size_t(n) == recv_size ? 1 : 2;
}
开发者ID:249CAAFE40,项目名称:mangos-tbc,代码行数:88,代码来源:WorldSocket.cpp


示例7: recv_to_file

template<typename samp_type> void recv_to_file(
    uhd::usrp::multi_usrp::sptr usrp,
    const std::string &cpu_format,
    const std::string &wire_format,
    const std::string &channel,
    const std::string &file,
    size_t samps_per_buff,
    unsigned long long num_requested_samples,
    double time_requested = 0.0,
    bool bw_summary = false,
    bool stats = false,
    bool null = false,
    bool enable_size_map = false,
    bool continue_on_bad_packet = false
){
    unsigned long long num_total_samps = 0;
    //create a receive streamer
    uhd::stream_args_t stream_args(cpu_format,wire_format);
    std::vector<size_t> channel_nums;
    channel_nums.push_back(boost::lexical_cast<size_t>(channel));
    stream_args.channels = channel_nums;
    uhd::rx_streamer::sptr rx_stream = usrp->get_rx_stream(stream_args);

    uhd::rx_metadata_t md;
    std::vector<samp_type> buff(samps_per_buff);
    std::ofstream outfile;
    if (not null)
        outfile.open(file.c_str(), std::ofstream::binary);
    bool overflow_message = true;

    //setup streaming
    uhd::stream_cmd_t stream_cmd((num_requested_samples == 0)?
        uhd::stream_cmd_t::STREAM_MODE_START_CONTINUOUS:
        uhd::stream_cmd_t::STREAM_MODE_NUM_SAMPS_AND_DONE
    );
    stream_cmd.num_samps = size_t(num_requested_samples);
    stream_cmd.stream_now = true;
    stream_cmd.time_spec = uhd::time_spec_t();
    rx_stream->issue_stream_cmd(stream_cmd);

    boost::system_time start = boost::get_system_time();
    unsigned long long ticks_requested = (long)(time_requested * (double)boost::posix_time::time_duration::ticks_per_second());
    boost::posix_time::time_duration ticks_diff;
    boost::system_time last_update = start;
    unsigned long long last_update_samps = 0;

    typedef std::map<size_t,size_t> SizeMap;
    SizeMap mapSizes;

    while(not stop_signal_called and (num_requested_samples != num_total_samps or num_requested_samples == 0)) {
        boost::system_time now = boost::get_system_time();

        size_t num_rx_samps = rx_stream->recv(&buff.front(), buff.size(), md, 3.0, enable_size_map);

        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_TIMEOUT) {
            std::cout << boost::format("Timeout while streaming") << std::endl;
            break;
        }
        if (md.error_code == uhd::rx_metadata_t::ERROR_CODE_OVERFLOW){
            if (overflow_message) {
                overflow_message = false;
                std::cerr << boost::format(
                    "Got an overflow indication. Please consider the following:\n"
                    "  Your write medium must sustain a rate of %fMB/s.\n"
                    "  Dropped samples will not be written to the file.\n"
                    "  Please modify this example for your purposes.\n"
                    "  This message will not appear again.\n"
                ) % (usrp->get_rx_rate()*sizeof(samp_type)/1e6);
            }
            continue;
        }
        if (md.error_code != uhd::rx_metadata_t::ERROR_CODE_NONE){
            std::string error = str(boost::format("Receiver error: %s") % md.strerror());
            if (continue_on_bad_packet){
                std::cerr << error << std::endl;
                continue;
            }
            else
                throw std::runtime_error(error);
        }

        if (enable_size_map) {
            SizeMap::iterator it = mapSizes.find(num_rx_samps);
            if (it == mapSizes.end())
                mapSizes[num_rx_samps] = 0;
            mapSizes[num_rx_samps] += 1;
        }

        num_total_samps += num_rx_samps;

        if (outfile.is_open())
            outfile.write((const char*)&buff.front(), num_rx_samps*sizeof(samp_type));

        if (bw_summary) {
            last_update_samps += num_rx_samps;
            boost::posix_time::time_duration update_diff = now - last_update;
            if (update_diff.ticks() > boost::posix_time::time_duration::ticks_per_second()) {
                double t = (double)update_diff.ticks() / (double)boost::posix_time::time_duration::ticks_per_second();
                double r = (double)last_update_samps / t;
                std::cout << boost::format("\t%f Msps") % (r/1e6) << std::endl;
//.........这里部分代码省略.........
开发者ID:excursionator,项目名称:uhd,代码行数:101,代码来源:rx_samples_to_file.cpp


示例8: GetSessionDbLocaleIndex

/// Only _static_ data send in this packet !!!
void WorldSession::HandleCreatureQueryOpcode( WorldPacket & recv_data )
{
    uint32 entry;
    recv_data >> entry;
    uint64 guid;
    recv_data >> guid;

    CreatureInfo const *ci = ObjectMgr::GetCreatureTemplate(entry);
    if (ci)
    {
        std::string Name, SubName;
        Name = ci->Name;
        SubName = ci->SubName;

        int loc_idx = GetSessionDbLocaleIndex();
        if (loc_idx >= 0)
        {
            CreatureLocale const *cl = sObjectMgr.GetCreatureLocale(entry);
            if (cl)
            {
                if (cl->Name.size() > size_t(loc_idx) && !cl->Name[loc_idx].empty())
                    Name = cl->Name[loc_idx];
                if (cl->SubName.size() > size_t(loc_idx) && !cl->SubName[loc_idx].empty())
                    SubName = cl->SubName[loc_idx];
            }
        }
        DETAIL_LOG("WORLD: CMSG_CREATURE_QUERY '%s' - Entry: %u.", ci->Name, entry);
                                                            // guess size
        WorldPacket data( SMSG_CREATURE_QUERY_RESPONSE, 100 );
        data << uint32(entry);                              // creature entry
        data << Name;
        data << uint8(0) << uint8(0) << uint8(0);           // name2, name3, name4, always empty
        data << SubName;
        data << ci->IconName;                               // "Directions" for guard, string for Icons 2.3.0
        data << uint32(ci->type_flags);                     // flags
        data << uint32(ci->type);                           // CreatureType.dbc
        data << uint32(ci->family);                         // CreatureFamily.dbc
        data << uint32(ci->rank);                           // Creature Rank (elite, boss, etc)
        data << uint32(ci->KillCredit[0]);                  // new in 3.1, kill credit
        data << uint32(ci->KillCredit[1]);                  // new in 3.1, kill credit

        for(int i = 0; i < MAX_CREATURE_MODEL; ++i)
            data << uint32(ci->ModelId[i]);

        data << float(ci->unk16);                           // health modifier
        data << float(ci->unk17);                           // power modifier
        data << uint8(ci->RacialLeader);
        for(uint32 i = 0; i < 6; ++i)
            data << uint32(ci->questItems[i]);              // itemId[6], quest drop
        data << uint32(ci->movementId);                     // CreatureMovementInfo.dbc
        SendPacket( &data );
        DEBUG_LOG( "WORLD: Sent SMSG_CREATURE_QUERY_RESPONSE" );
    }
    else
    {
        DEBUG_LOG("WORLD: CMSG_CREATURE_QUERY - NO CREATURE INFO! (GUID: %u, ENTRY: %u)",
            GUID_LOPART(guid), entry);
        WorldPacket data( SMSG_CREATURE_QUERY_RESPONSE, 4 );
        data << uint32(entry | 0x80000000);
        SendPacket( &data );
        DEBUG_LOG( "WORLD: Sent SMSG_CREATURE_QUERY_RESPONSE" );
    }
}
开发者ID:Aldrealia,项目名称:mangos,代码行数:64,代码来源:QueryHandler.cpp


示例9: DETAIL_LOG

void WorldSession::HandleNpcTextQueryOpcode( WorldPacket & recv_data )
{
    uint32 textID;
    uint64 guid;

    recv_data >> textID;
    DETAIL_LOG("WORLD: CMSG_NPC_TEXT_QUERY ID '%u'", textID);

    recv_data >> guid;
    _player->SetTargetGUID(guid);

    GossipText const* pGossip = sObjectMgr.GetGossipText(textID);

    WorldPacket data( SMSG_NPC_TEXT_UPDATE, 100 );          // guess size
    data << textID;

    if (!pGossip)
    {
        for(uint32 i = 0; i < 8; ++i)
        {
            data << float(0);
            data << "Greetings $N";
            data << "Greetings $N";
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
            data << uint32(0);
        }
    }
    else
    {
        std::string Text_0[8], Text_1[8];
        for (int i = 0; i < 8; ++i)
        {
            Text_0[i]=pGossip->Options[i].Text_0;
            Text_1[i]=pGossip->Options[i].Text_1;
        }

        int loc_idx = GetSessionDbLocaleIndex();
        if (loc_idx >= 0)
        {
            NpcTextLocale const *nl = sObjectMgr.GetNpcTextLocale(textID);
            if (nl)
            {
                for (int i = 0; i < 8; ++i)
                {
                    if (nl->Text_0[i].size() > size_t(loc_idx) && !nl->Text_0[i][loc_idx].empty())
                        Text_0[i]=nl->Text_0[i][loc_idx];
                    if (nl->Text_1[i].size() > size_t(loc_idx) && !nl->Text_1[i][loc_idx].empty())
                        Text_1[i]=nl->Text_1[i][loc_idx];
                }
            }
        }

        for (int i = 0; i < 8; ++i)
        {
            data << pGossip->Options[i].Probability;

            if ( Text_0[i].empty() )
                data << Text_1[i];
            else
                data << Text_0[i];

            if ( Text_1[i].empty() )
                data << Text_0[i];
            else
                data << Text_1[i];

            data << pGossip->Options[i].Language;

            for(int j = 0; j < 3; ++j)
            {
                data << pGossip->Options[i].Emotes[j]._Delay;
                data << pGossip->Options[i].Emotes[j]._Emote;
            }
        }
    }

    SendPacket( &data );

    DEBUG_LOG( "WORLD: Sent SMSG_NPC_TEXT_UPDATE" );
}
开发者ID:Aldrealia,项目名称:mangos,代码行数:85,代码来源:QueryHandler.cpp


示例10: BOOST_AUTO_TEST_CASE


//.........这里部分代码省略.........
                auto_stmt->Execute();

                BOOST_CHECK(auto_stmt->HasMoreResults());
                BOOST_CHECK(auto_stmt->HasRows());
                unique_ptr<IResultSet> rs(auto_stmt->GetResultSet());
                BOOST_CHECK(rs.get() != NULL);

                while (rs->Next()) {
                    BOOST_CHECK(rs->GetVariant(1).GetInt4() > 0);
                    BOOST_CHECK(rs->GetVariant(2).GetString().size() > 0);
                    BOOST_CHECK(rs->GetVariant(3).GetString().size() > 0);
                    ++num;
                }

                BOOST_CHECK(num > 0);

                DumpResults(auto_stmt.get());
            }
        }

        // Test ICallableStatement
        // With parameters.
        {
            {
                unique_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_server_info")
                    );

                // Set parameter to NULL ...
                auto_stmt->SetParam( CVariant(eDB_Int), "@attribute_id" );
                auto_stmt->Execute();

                if (GetArgs().GetServerType() == CDBConnParams::eSybaseSQLServer) {
                    BOOST_CHECK_EQUAL( size_t(30), GetNumOfRecords(auto_stmt) );
                } else {
                    BOOST_CHECK_EQUAL( size_t(29), GetNumOfRecords(auto_stmt) );
                }

                // Set parameter to 1 ...
                auto_stmt->SetParam( CVariant( Int4(1) ), "@attribute_id" );
                auto_stmt->Execute();

                BOOST_CHECK_EQUAL( size_t(1), GetNumOfRecords(auto_stmt) );
            }

            // NULL value with CVariant ...
            {
                unique_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_statistics")
                    );

                auto_stmt->SetParam(CVariant((const char*) NULL), "@table_name");
                auto_stmt->Execute();
                DumpResults(auto_stmt.get());
            }

            // Doesn't work for some reason ...
            if (false) {
                // Execute it first time ...
                unique_ptr<ICallableStatement> auto_stmt(
                    GetConnection().GetCallableStatement("sp_statistics")
                    );

                auto_stmt->SetParam(CVariant(GetTableName()), "@table_name");
                auto_stmt->Execute();
开发者ID:svn2github,项目名称:ncbi_tk,代码行数:66,代码来源:dbapi_unit_test_proc.cpp


示例11: operator

 std::size_t operator()(const cast_key_t& k) const
 {
     return (size_t(k.first) << 32) | size_t(k.second);
 }
开发者ID:kaabimg,项目名称:ev_library,代码行数:4,代码来源:value.cpp


示例12: ResetAll

 void ResetAll() {
     assert(result_ != EOF);
     width_ = 0;
     prec_ = size_t(-1);
     flags_ = 0;
 }
开发者ID:semenovf,项目名称:jq,代码行数:6,代码来源:safeformat.hpp


示例13: FormatWithCurrentFlags

 void FormatWithCurrentFlags(const LOKI_SAFEFORMAT_UNSIGNED_LONG i) {
     // look at the format character
     Char formatChar = *format_;
     bool isSigned = formatChar == _T('d') || formatChar == _T('i');
     if (formatChar == _T('p')) {
         formatChar = _T('x'); // pointers go to hex
         SetAlternateForm(); // printed with '0x' in front
         isSigned = true; // that's what gcc does
     }
     if (!JQ_STRCHR(_T("cdiuoxX"), formatChar)) {
         result_ = -1;
         return;
     }
     Char buf[
         sizeof(LOKI_SAFEFORMAT_UNSIGNED_LONG) * 3 // digits
         + 1 // sign or ' '
         + 2 // 0x or 0X
         + 1]; // terminating zero
     const Char *const bufEnd = buf + (sizeof(buf) / sizeof(Char));
     Char * bufLast = buf + (sizeof(buf) / sizeof(Char) - 1);
     Char signChar = 0;
     unsigned int base = 10;
     
     if (formatChar == _T('c')) {
         // Format only one character
         // The 'fill with zeros' flag is ignored
         ResetFillZeros();
         *bufLast = static_cast<char_type>(i);
     } else {
         // TODO: inefficient code, refactor
         const bool negative = isSigned && static_cast<LOKI_SAFEFORMAT_SIGNED_LONG>(i) < 0;
         if (formatChar == _T('o')) base = 8;
         else if (formatChar == _T('x') || formatChar == _T('X')) base = 16;
         bufLast = isSigned
             ? RenderWithoutSign(static_cast<LOKI_SAFEFORMAT_SIGNED_LONG>(i), bufLast, base,
                 formatChar == _T('X'))
             : RenderWithoutSign(i, bufLast, base, 
                 formatChar == _T('X'));
         // Add the sign
         if (isSigned) {
             negative ? signChar = _T('-')
             : ShowSignAlways() ? signChar = _T('+')
             : Blank() ? signChar = _T(' ')
             : 0;
         }
     }
     // precision 
     size_t 
         countDigits = bufEnd - bufLast,
         countZeros = prec_ != size_t(-1) && countDigits < prec_ && 
                 formatChar != _T('c')
             ? prec_ - countDigits 
             : 0,
         countBase = base != 10 && AlternateForm() && i != 0
             ? (base == 16 ? 2 : countZeros > 0 ? 0 : 1)
             : 0,
         countSign = (signChar != 0),
         totalPrintable = countDigits + countZeros + countBase + countSign;
     size_t countPadLeft = 0, countPadRight = 0;
     if (width_ > totalPrintable) {
         if (LeftJustify()) {
             countPadRight = width_ - totalPrintable;
             countPadLeft = 0;
         } else {
             countPadLeft = width_ - totalPrintable;
             countPadRight = 0;
         }
     }
     if (FillZeros() && prec_ == size_t(-1)) {
         // pad with zeros and no precision - transfer padding to precision
         countZeros = countPadLeft;
         countPadLeft = 0;
     }
     // ok, all computed, ready to print to device
     Fill(' ', countPadLeft);
     if (signChar != 0) Write(&signChar, &signChar + 1);
     if (countBase > 0) Fill(_T('0'), 1);
     if (countBase == 2) Fill(formatChar, 1);
     Fill(_T('0'), countZeros);
     Write(bufLast, bufEnd);
     Fill(_T(' '), countPadRight);
     // done, advance
     Next();
 }
开发者ID:semenovf,项目名称:jq,代码行数:84,代码来源:safeformat.hpp


示例14: TestEmptyQueue

void TestEmptyQueue() {
    const tbb::concurrent_queue<T> queue;
    ASSERT( queue.size()==0, NULL );
    ASSERT( queue.capacity()>0, NULL );
    ASSERT( size_t(queue.capacity())>=size_t(-1)/(sizeof(void*)+sizeof(T)), NULL );
}
开发者ID:Zer0code,项目名称:LoLUpdater,代码行数:6,代码来源:test_concurrent_queue_v2.cpp


示例15: to_string

		// return a copy of the 20 bytes representing the sha1-hash as a std::string.
		// It's still a binary string with 20 binary characters.
		std::string to_string() const
		{
			return std::string(reinterpret_cast<char const*>(&m_number[0])
				, size_t(size));
		}
开发者ID:Athorcis,项目名称:libtorrent,代码行数:7,代码来源:sha1_hash.hpp


示例16: push_best_triangle


//.........这里部分代码省略.........
			}
		}


		// the push_best_triangle() function is never called if there are no triangles to begin with,
		// and if there are some, the code above should always return a best triangle
		assert(has_best_triangle);


		// get the best triangle
		triangle_data &best_tri = tri_data[best_triangle];

		// push the best triangle's vertices to the top of the LRU cache, potentially expanding
		// the cache by up to 3 vertices
		// the loop is reversed to preserver order of the vertices inside the LRU cache; that is, triangle vertex index #0 shall
		// be the first in the LRU cache, index #1 the second etc.
		// TODO: reverse/nonreverse return different optimization results; test if this has an impact in cache efficiency
		{
			for (int i = 2; i >= 0; --i)
			{
				vertex_index_t idx = best_tri.indices[i];
				typename lru_cache_t::iterator cache_iter = std::find(lru_cache.begin(), lru_cache.end(), idx);
				if (cache_iter != lru_cache.end())
				{
					lru_cache.push_front(idx);
					lru_cache.erase(cache_iter);
				}
				else
				{
					lru_cache.push_front(idx);
				}
			}
		}

		// push the best triangle into the optimized triangle list, and disable it, meaning
		// it will not be considered a candidate for best triangle anymore
		optimized_tris.push_back(best_tri);
		best_tri.disabled = true;

		// remove the best triangle from the tri_indices_using vectors of its vertices
		for (int i = 0; i < 3; ++i)
		{
			vertex_data &vtx = vtx_data[best_tri.indices[i]];
			typename tri_indices_using_t::iterator iter = vtx.tri_indices_using.find(best_triangle);
			if (iter != vtx.tri_indices_using.end())
				vtx.tri_indices_using.erase(iter);
		}

		// now find a new best triangle
		{
			std::set < triangle_index_t > triangles_in_cache;

			// fill the triangles_in_cache vector by visiting each vertex in the LRU cache,
			// retrieving the indices of the triangles using these vertices, and storing them
			// in triangles_in_cache
			// the result is a set of indices of those triangles which are referred to by LRU cache
			// vertices; only these triangles are candidates for the new best triangle
			int pos = 0;
			for (typename lru_cache_t::iterator cache_iter = lru_cache.begin(); cache_iter != lru_cache.end(); ++cache_iter, ++pos)
			{
				vertex_data &vtx = vtx_data[*cache_iter];
				vtx.position = (pos < int(max_cache_size)) ? pos : -1;
				vtx.score = find_vertex_score(vtx);
				triangles_in_cache.insert(vtx.tri_indices_using.begin(), vtx.tri_indices_using.end());
			}

			numeric_type_t highest_score = 0;
			has_best_triangle = false;

			// amongst the candidate triangles, find the one with the highest score - this one
			// will become the new best triangle
			for (typename std::set < triangle_index_t > ::iterator tri_iter = triangles_in_cache.begin(); tri_iter != triangles_in_cache.end(); ++tri_iter)
			{
				triangle_data &tri_in_cache = tri_data[*tri_iter];
				if (tri_in_cache.disabled)
					continue; // if this triangle was a best triangle before, skip it

				// update the triangle's score
				tri_in_cache.score =
					vtx_data[tri_in_cache.indices[0]].score +
					vtx_data[tri_in_cache.indices[1]].score +
					vtx_data[tri_in_cache.indices[2]].score;

				// is this triangle's score higher than the highest score seen so far?
				// if so, it becomes the new candidate for the best triangle
				if (tri_in_cache.score > highest_score)
				{
					highest_score = tri_in_cache.score;
					best_triangle = *tri_iter;
					has_best_triangle = true;
				}
			}
		}

		// finally, prune the LRU cache if necessary
		while (lru_cache.size() > size_t(max_cache_size))
		{
			lru_cache.pop_back();
		}
	}
开发者ID:dv1,项目名称:vcache_optimizer,代码行数:101,代码来源:vcache_optimizer.hpp


示例17: word_wrap_text

std::string word_wrap_text(const std::string& unwrapped_text, int font_size,
	int max_width, int max_height, int max_lines, bool partial_line)
{
	VALIDATE(max_width > 0, _("The maximum text width is less than 1."));

	utf8::iterator ch(unwrapped_text);
	std::string current_word;
	std::string current_line;
	size_t line_width = 0;
	size_t current_height = 0;
	bool line_break = false;
	bool first = true;
	bool start_of_line = true;
	std::string wrapped_text;
	std::string format_string;
	SDL_Color color;
	int font_sz = font_size;
	int style = TTF_STYLE_NORMAL;
	utf8::iterator end = utf8::iterator::end(unwrapped_text);

	while(1) {
		if(start_of_line) {
			line_width = 0;
			format_string.clear();
			while(ch != end && *ch < static_cast<ucs4::char_t>(0x100)
					&& is_format_char(*ch) && !ch.next_is_end()) {

				format_string.append(ch.substr().first, ch.substr().second);
				++ch;
			}
			// We need to parse the special format characters
			// to give the proper font_size and style to line_size()
			font_sz = font_size;
			style = TTF_STYLE_NORMAL;
			parse_markup(format_string.begin(),format_string.end(),&font_sz,&color,&style);
			current_line.clear();
			start_of_line = false;
		}

		// If there is no current word, get one
		if(current_word.empty() && ch == end) {
			break;
		} else if(current_word.empty()) {
			if(*ch == ' ' || *ch == '\n') {
				current_word = *ch;
				++ch;
			} else {
				ucs4::char_t previous = 0;
				for(;ch != utf8::iterator::end(unwrapped_text) &&
						*ch != ' ' && *ch != '\n'; ++ch) {

					if(!current_word.empty() &&
							break_before(*ch) &&
							!no_break_after(previous))
						break;

					if(!current_word.empty() &&
							break_after(previous) &&
							!no_break_before(*ch))
						break;

					current_word.append(ch.substr().first, ch.substr().second);

					previous = *ch;
				}
			}
		}

		if(current_word == "\n") {
			line_break = true;
			current_word.clear();
			start_of_line = true;
		} else {

			const size_t word_width = line_size(current_word, preferences::font_scaled(font_sz), style).w;

			line_width += word_width;

			if(static_cast<long>(line_width) > max_width) {
				if (!partial_line && static_cast<long>(word_width) > max_width) {
					cut_word(current_line,
						current_word, font_sz, style, max_width);
				}
				if(current_word == " ")
					current_word = "";
				line_break = true;
			} else {
				current_line += current_word;
				current_word = "";
			}
		}

		if(line_break || (current_word.empty() && ch == end)) {
			SDL_Rect size = line_size(current_line, preferences::font_scaled(font_sz), style);
			if(max_height > 0 && current_height + size.h >= size_t(max_height)) {
				return wrapped_text;
			}

			if(!first) {
				wrapped_text += '\n';
//.........这里部分代码省略.........
开发者ID:Heark,项目名称:wesnoth,代码行数:101,代码来源:marked-up_text.cpp


示例18: smart_malloc

void* smart_malloc(size_t nbytes) {
  auto& mm = MM();
  auto const size = mm.debugAddExtra(std::max(nbytes, size_t(1)));
  return mm.debugPostAllocate(mm.smartMalloc(size), 0, 0);
}
开发者ID:BionicClick,项目名称:hhvm,代码行数:5,代码来源:memory-manager.cpp


示例19: max_size

 size_t max_size() const {return size_t(~0) / sizeof(T);}
开发者ID:RCambier,项目名称:EmbeddedAndVerification,代码行数:1,代码来源:thread.cpp


示例20: switch

void wxMenu::GtkAppend(wxMenuItem* mitem, int pos)
{
    GtkWidget *menuItem;
    switch (mitem->GetKind())
    {
        case wxITEM_SEPARATOR:
            menuItem = gtk_separator_menu_item_new();
            break;
        case wxITEM_CHECK:
            menuItem = gtk_check_menu_item_new_with_label("");
            break;
        case wxITEM_RADIO:
            {
                // See if we need to create a new radio group for this item or
                // add it to an existing one.
                wxMenuItem* radioGroupItem = NULL;

                const size_t numItems = GetMenuItemCount();
                const size_t n = pos == -1 ? numItems - 1 : size_t(pos);

                if (n != 0)
                {
                    wxMenuItem* const itemPrev = FindItemByPosition(n - 1);
                    if ( itemPrev->GetKind() == wxITEM_RADIO )
                    {
                        // Appending an item after an existing radio item puts
                        // it into the same radio group.
                        radioGroupItem = itemPrev;
                    }
                }

                if (radioGroupItem == NULL && n != numItems - 1)
                {
                    wxMenuItem* const itemNext = FindItemByPosition(n + 1);
                    if ( itemNext->GetKind() == wxITEM_RADIO )
                    {
                        // Inserting an item before an existing radio item
                        // also puts it into the existing radio group.
                        radioGroupItem = itemNext;
                    }
                }

                GSList* group = NULL;
                if ( radioGroupItem )
                {
                    group = gtk_radio_menu_item_get_group(
                              GTK_RADIO_MENU_ITEM(radioGroupItem->GetMenuItem())
                            );
                }

                menuItem = gtk_radio_menu_item_new_with_label(group, "");
            }
            break;
        default:
            wxFAIL_MSG("unexpected menu item kind");
            // fall through
        case wxITEM_NORMAL:
            const wxBitmap& bitmap = mitem->GetBitmap();
            const char* stockid;
            if (bitmap.IsOk())
            {
                // always use pixbuf, because pixmap mask does not
                // work with disabled images in some themes
                GtkWidget* image = gtk_image_new_from_pixbuf(bitmap.GetPixbuf());
                menuItem = gtk_image_menu_item_new_with_label("");
                gtk_widget_show(image);
                gtk_image_menu_item_set_image(GTK_IMAGE_MENU_ITEM(menuItem), image);
            }
            else if ((stockid = wxGetStockGtkID(mitem->GetId())) != NULL)
                // use stock bitmap for this item if available on the assumption
                // that it never hurts to follow GTK+ conventions more closely
                menuItem = gtk_image_menu_item_new_from_stock(stockid, NULL);
            else
                menuItem = gtk_menu_item_new_with_label("");
            break;
    }
    mitem->SetMenuItem(menuItem);

    gtk_menu_shell_insert(GTK_MENU_SHELL(m_menu), menuItem, pos);

    gtk_widget_show( menuItem );

    if ( !mitem->IsSeparator() )
    {
        mitem->SetGtkLabel();
        g_signal_connect (menuItem, "select",
                          G_CALLBACK(menuitem_select), mitem);
        g_signal_connect (menuItem, "deselect",
    

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C++ size_type函数代码示例发布时间:2022-05-30
下一篇:
C++ size_policy函数代码示例发布时间:2022-05-30
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap