本文整理汇总了C++中size_t函数的典型用法代码示例。如果您正苦于以下问题:C++ size_t函数的具体用法?C++ size_t怎么用?C++ size_t使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了size_t函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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':
//.........这里部分代码省略.........
示例2: size_t
void Fixup<Bios>(Bios& p)
{
p.size = size_t(p.encodedSize+1) * 64*KiB;
}
示例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(×tamp, 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);
}
}
示例4: feature_group
ndsize_t BaseTagHDF5::featureCount() const {
boost::optional<H5Group> g = feature_group(false);
return g ? g->objectCount() : size_t(0);
}
示例5: very_busy
bool very_busy() const { return jobs_in_queue() > size_t(4 * m_size); }
示例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;
}
示例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;
//.........这里部分代码省略.........
示例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" );
}
}
示例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" );
}
示例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();
示例11: operator
std::size_t operator()(const cast_key_t& k) const
{
return (size_t(k.first) << 32) | size_t(k.second);
}
示例12: ResetAll
void ResetAll() {
assert(result_ != EOF);
width_ = 0;
prec_ = size_t(-1);
flags_ = 0;
}
示例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();
}
示例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 );
}
示例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));
}