inline RESULT *allocate(int *status, int flags, const btlso::IPv4Address& peerAddress, btlso::StreamSocketFactory<btlso::IPv4Address> *factory, bdlma::Pool *pool) { BSLS_ASSERT(factory); BSLS_ASSERT(pool); BSLS_ASSERT(status); btlso::StreamSocket<btlso::IPv4Address> *socket_p = 0; socket_p = factory->allocate(); if (!socket_p) { return NULL; // RETURN } int rc = socket_p->setBlockingMode(btlso::Flag::e_BLOCKING_MODE); BSLS_ASSERT(0 == rc); while (1) { int s = socket_p->connect(peerAddress); if (0 == s) break; if (btlso::SocketHandle::e_ERROR_INTERRUPTED != s) { *status = e_FAILED; // Any negative number satisfies the contract. factory->deallocate(socket_p); return NULL; // RETURN } if (flags & btlsc::Flag::k_ASYNC_INTERRUPT) { *status = 1; // Any positive number satisfies the contract. factory->deallocate(socket_p); return NULL; // RETURN } } RESULT *channel = new (*pool) RESULT(socket_p); return channel; }
int baltzo::TimeZoneUtil::convertLocalToLocalTime( LocalDatetime *result, const char *targetTimeZoneId, const bdlt::Datetime& srcTime, const char *srcTimeZoneId, DstPolicy::Enum dstPolicy) { BSLS_ASSERT(result); BSLS_ASSERT(targetTimeZoneId); BSLS_ASSERT(srcTimeZoneId); bdlt::DatetimeTz resultTz; const int rc = convertLocalToLocalTime(&resultTz, targetTimeZoneId, srcTime, srcTimeZoneId, dstPolicy); if (0 != rc) { return rc; // RETURN } result->setDatetimeTz(resultTz); result->setTimeZoneId(targetTimeZoneId); return 0; }
void RbTreeUtil::swap(RbTreeAnchor *a, RbTreeAnchor *b) { BSLS_ASSERT(a); BSLS_ASSERT(b); RbTreeAnchor tmp(a->rootNode(), a->firstNode(), a->numNodes()); a->reset(b->rootNode(), b->firstNode(), b->numNodes()); b->reset(tmp.rootNode(), tmp.firstNode(), tmp.numNodes()); // Readjust the sentinel nodes of both trees. if (0 == a->numNodes()) { a->setFirstNode(a->sentinel()); } else { a->rootNode()->setParent(a->sentinel()); } if (0 == b->numNodes()) { b->setFirstNode(b->sentinel()); } else { b->rootNode()->setParent(b->sentinel()); } }
void String::toFixedLength(char *dstString, int dstLength, const char *srcString, int srcLength, char padChar) { BSLS_ASSERT(dstString); BSLS_ASSERT( 0 <= dstLength); BSLS_ASSERT(srcString || 0 == srcLength); BSLS_ASSERT( 0 <= srcLength); if (dstLength < srcLength) { // We know 'srcLength > 0', therefore '0 != srcString'. if (dstString != srcString) { bsl::memmove(dstString, srcString, dstLength); } } else { if (srcString && dstString != srcString) { bsl::memmove(dstString, srcString, srcLength); } for (int i = srcLength; i < dstLength; ++i) { dstString[i] = padChar; } } }
static unsigned int hash(const char *data, int length) // That the memory starting at the specified 'data' of specified 'length' // bytes in length. { BSLS_ASSERT(0 <= length); BSLS_ASSERT(data || 0 == length); typedef unsigned char Ub1; typedef unsigned int Ub4; const Ub1 *k = reinterpret_cast<const Ub1 *>(data); Ub4 hash = 0; for (int i = 0; i < length; ++i) { hash += k[i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; }
void bslmt::Sluice::wait(const void *token) { GenerationDescriptor *g = static_cast<GenerationDescriptor *>(const_cast<void *>(token)); for (;;) { g->d_sema.wait(); LockGuard<Mutex> lock(&d_mutex); if (g->d_numSignaled) { const int numSignaled = --g->d_numSignaled; const int numThreads = --g->d_numThreads; BSLS_ASSERT(numThreads >= numSignaled); BSLS_ASSERT(d_pendingGeneration != g); if (0 == numThreads) { // The last thread is responsible for cleanup. BSLS_ASSERT(d_signaledGeneration != g); g->d_next = d_descriptorPool; d_descriptorPool = g; } return; // RETURN } // Spurious wakeups happen because 'timedWait' may timeout on the // semaphore, but still consume a signal. } }
const char *String::strstrCaseless(const char *string, int stringLen, const char *subString, int subStringLen) { BSLS_ASSERT(string || 0 == stringLen); BSLS_ASSERT( 0 <= stringLen); BSLS_ASSERT(subString || 0 == subStringLen); BSLS_ASSERT( 0 <= subStringLen); if (0 == subStringLen) { return string; // RETURN } if (stringLen < subStringLen) { return 0; // RETURN } BSLS_ASSERT_SAFE(string); // impossible to fail const char *end = string + stringLen - subStringLen; for (const char *p = string; p <= end; ++p) { if (areEqualCaseless(p, subStringLen, subString, subStringLen)) { return p; // RETURN } } return 0; }
int DecimalUtil::quantum(Decimal128 x) { BSLS_ASSERT(!isInf(x)); BSLS_ASSERT(!isNan(x)); return decQuadGetExponent(x.data()); }
CountingAllocator::~CountingAllocator() { BSLS_ASSERT(0 <= numBytesInUse()); BSLS_ASSERT(0 <= numBytesTotal()); BSLS_ASSERT(numBytesInUse() <= numBytesTotal()); BSLS_ASSERT(d_allocator_p); }
int TimeMetrics::percentage(int category) { bslmt::LockGuard<bslmt::Mutex> lock(&d_dataLock); int result = 0; BSLS_ASSERT(0 <= category); BSLS_ASSERT(category < (int) d_categoryTimes.size()); bsls::TimeInterval now = bdlt::CurrentTime::now(); bsls::TimeInterval delta = now - d_categoryStartTimes[d_currentCategory]; int deltaMS = static_cast<int>(delta.seconds() * 1000 + delta.nanoseconds() / k_MILLION); d_categoryTimes[d_currentCategory] += deltaMS; d_currentTotal += deltaMS; d_categoryStartTimes[d_currentCategory] = now; if (d_currentTotal) { result = static_cast<int>( d_categoryTimes[category] * 100.0 / d_currentTotal); } return result < 0 ? 0 : result > 100 ? 100 : result; }
int DecimalUtil::quantum(Decimal64 x) { BSLS_ASSERT(!isInf(x)); BSLS_ASSERT(!isNan(x)); return decDoubleGetExponent(x.data()); }
TimeMetrics::~TimeMetrics() { BSLS_ASSERT(d_categoryStartTimes.size() == d_categoryTimes.size()); BSLS_ASSERT(d_currentCategory < static_cast<int>(d_categoryStartTimes.size())); BSLS_ASSERT(0 <= d_currentCategory); }
// MANIPULATORS void *BlockList::allocate(int size) { BSLS_ASSERT(0 <= size); if (0 == size) { return 0; // RETURN } size = alignedAllocationSize(size, sizeof(Block)); Block *block = (Block *)d_allocator_p->allocate(size); BSLS_ASSERT(0 == bsls::AlignmentUtil::calculateAlignmentOffset( (void *)block, bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT)); block->d_next_p = (Block *)d_head_p; block->d_addrPrevNext = (Block **)&d_head_p; if (d_head_p) { d_head_p->d_addrPrevNext = &block->d_next_p; } d_head_p = block; BSLS_ASSERT(0 == bsls::AlignmentUtil::calculateAlignmentOffset( (void *)&block->d_memory, bsls::AlignmentUtil::BSLS_MAX_ALIGNMENT)); return (void *)&block->d_memory; }
void TimeInterval::addInterval(bsls::Types::Int64 seconds, int nanoseconds) { BSLS_ASSERT(isSumValidInt64(d_seconds, seconds)); BSLS_ASSERT(isSumValidInt64( d_seconds + seconds, (static_cast<bsls::Types::Int64>(d_nanoseconds) + nanoseconds) / k_NANOSECS_PER_SEC)); d_seconds += seconds; bsls::Types::Int64 nanosecs = static_cast<bsls::Types::Int64>(nanoseconds) + d_nanoseconds; if (nanosecs >= k_NANOSECS_PER_SEC || nanosecs <= -k_NANOSECS_PER_SEC) { d_seconds += nanosecs / k_NANOSECS_PER_SEC; d_nanoseconds = static_cast<int>(nanosecs % k_NANOSECS_PER_SEC); } else { d_nanoseconds = static_cast<int>(nanosecs); } if (d_seconds > 0 && d_nanoseconds < 0) { --d_seconds; d_nanoseconds += k_NANOSECS_PER_SEC; } else if (d_seconds < 0 && d_nanoseconds > 0) { ++d_seconds; d_nanoseconds -= k_NANOSECS_PER_SEC; } }
void TcpConnector::deallocate(btlsc::Channel *channel) { BSLS_ASSERT(channel); char *arena = (char *) channel; TcpTimedChannel *c = dynamic_cast<TcpTimedChannel*>(channel); btlso::StreamSocket<btlso::IPv4Address> *s = NULL; if (c) { s = c->socket(); } else { TcpChannel *c = dynamic_cast<TcpChannel*>(channel); BSLS_ASSERT(c); s = c->socket(); } BSLS_ASSERT(s); channel->invalidate(); d_factory_p->deallocate(s); bsl::vector<btlsc::Channel*>::iterator idx = bsl::lower_bound(d_channels.begin(), d_channels.end(), channel); BSLS_ASSERT(idx != d_channels.end() && *idx == channel); d_channels.erase(idx); d_pool.deallocate(arena); return ; }
int btlso::SocketImpUtil::write(const btlso::SocketHandle::Handle& socket, const void *buffer, int numBytes, int *errorCode) { // Implementation notes: For non blocking IO, the send operation will write // out some or all of the buffer if possible. However, since the // implementation of sockets may include internal buffers of certain sizes // and optimizations, the send function may return a "would block" error or // an smaller than expected number of bytes written even if it appears as // if the internal socket buffer has more room. This is known as the low // water mark and may be implemented even if the equivalent socket option // is not available. For the blocking IO case, the send operation may // block until all or part of the data is written. No assumption should be // made regarding the number of bytes that will be written with a single // call. int rc; BSLS_ASSERT(buffer); BSLS_ASSERT(numBytes >= 0); rc = ::send(socket, static_cast<const char *>(buffer), numBytes, 0); int errorNumber = rc >= 0 ? 0 : SocketImpUtil_Util::getErrorCode(); if (errorNumber && errorCode) { *errorCode = errorNumber; } return errorNumber ? SocketImpUtil_Util::mapErrorCode(errorNumber) : rc; }
// CREATORS ChannelPoolChannel::ChannelPoolChannel( int channelId, ChannelPool *channelPool, btlb::BlobBufferFactory *blobBufferFactory, bdlma::ConcurrentPoolAllocator *spAllocator, bslma::Allocator *basicAllocator) : d_mutex() , d_callbackInProgress(false) , d_closed(false) , d_readQueue(basicAllocator) , d_blobBufferFactory_p(blobBufferFactory, 0, &bslma::ManagedPtrUtil::noOpDeleter) , d_spAllocator_p(spAllocator) , d_channelPool_p(channelPool) , d_nextClockId(channelId + 0x00800000) , d_channelId(channelId) , d_peerAddress() , d_localAddress() , d_allocator_p(bslma::Default::allocator(basicAllocator)) { BSLS_ASSERT(0 != channelPool); BSLS_ASSERT(0 != blobBufferFactory); BSLS_ASSERT(0 != spAllocator); // Queue these addresses since the ChannelPool channel can have // disappeared when we get SESSION_DOWN. d_channelPool_p->getLocalAddress(&d_localAddress, d_channelId); d_channelPool_p->getPeerAddress(&d_peerAddress, d_channelId); }
int btlso::SocketImpUtil::writev(const btlso::SocketHandle::Handle& socket, const btls::Ovec *ovec, int size, int *errorCode) { int rc; BSLS_ASSERT(ovec); BSLS_ASSERT(size > 0); #if defined(BTLSO_PLATFORM_WIN_SOCKETS) DWORD bytesSent; rc = ::WSASend(socket, reinterpret_cast<WSABUF *>(const_cast<btls::Ovec *>(ovec)), size, &bytesSent, 0, 0, 0); if (0 == rc) { rc = bytesSent; } else { rc = 0; } #else rc = ::writev(socket, reinterpret_cast<const ::iovec *>(ovec), size); #endif int errorNumber = rc > 0 ? 0 : SocketImpUtil_Util::getErrorCode(); if (errorNumber && errorCode) { *errorCode = errorNumber; } return errorNumber ? SocketImpUtil_Util::mapErrorCode(errorNumber) : rc; }
// MANIPULATORS const void *bslmt::Sluice::enter() { LockGuard<Mutex> lock(&d_mutex); GenerationDescriptor *g = d_pendingGeneration; if (0 == g) { g = d_descriptorPool; if (g) { // The pool is not empty. Get a descriptor from the pool. d_descriptorPool = g->d_next; } else { // The pool is empty. Allocate a new descriptor. g = new (*d_allocator_p) GenerationDescriptor(d_clockType); } d_pendingGeneration = g; BSLS_ASSERT(0 == g->d_numThreads); BSLS_ASSERT(0 == g->d_numSignaled); } ++g->d_numThreads; return g; }
double PeriodDayCountUtil::yearsDiff( const bdlt::Date& beginDate, const bdlt::Date& endDate, const bsl::vector<bdlt::Date>& periodDate, double periodYearDiff, DayCountConvention::Enum convention) { BSLS_ASSERT(periodDate.size() >= 2); BSLS_ASSERT(periodDate.front() <= beginDate); BSLS_ASSERT( beginDate <= periodDate.back()); BSLS_ASSERT(periodDate.front() <= endDate); BSLS_ASSERT( endDate <= periodDate.back()); BSLS_ASSERT_SAFE(isSortedAndUnique(periodDate.begin(), periodDate.end())); double numYears; switch (convention) { case DayCountConvention::e_PERIOD_ICMA_ACTUAL_ACTUAL: { numYears = bbldc::PeriodIcmaActualActual::yearsDiff(beginDate, endDate, periodDate, periodYearDiff); } break; default: { BSLS_ASSERT_OPT(0 && "Unrecognized convention"); numYears = 0.0; } break; } return numYears; }
const char *String::strrstrCaseless(const char *string, int stringLen, const char *subString, int subStringLen) { BSLS_ASSERT(string || 0 == stringLen); BSLS_ASSERT( 0 <= stringLen); BSLS_ASSERT(subString || 0 == subStringLen); BSLS_ASSERT( 0 <= subStringLen); if (0 == subStringLen) { return string + stringLen; // RETURN } if (stringLen < subStringLen) { return 0; // RETURN } BSLS_ASSERT_SAFE(string); // impossible to fail for (int i = stringLen - subStringLen; i >= 0; --i) { const char *p = string + i; if (areEqualCaseless(p, subStringLen, subString, subStringLen)) { return p; // RETURN } } return 0; }
int baltzo::TimeZoneUtilImp::initLocalTime( bdlt::DatetimeTz *result, LocalTimeValidity::Enum *resultValidity, const bdlt::Datetime& localTime, const char *timeZoneId, DstPolicy::Enum dstPolicy, ZoneinfoCache *cache) { BSLS_ASSERT(result); BSLS_ASSERT(resultValidity); BSLS_ASSERT(timeZoneId); BSLS_ASSERT(cache); const Zoneinfo *timeZone; const int rc = lookupTimeZone(&timeZone, timeZoneId, cache); if (0 != rc) { return rc; // RETURN } Zoneinfo::TransitionConstIterator iter; resolveLocalTime(result, resultValidity, &iter, localTime, dstPolicy, *timeZone); return 0; }
bool String::areEqualCaseless(const char *lhsString, int lhsLength, const char *rhsString, int rhsLength) { BSLS_ASSERT(lhsString || 0 == lhsLength); BSLS_ASSERT( 0 <= lhsLength); BSLS_ASSERT(rhsString || 0 == rhsLength); BSLS_ASSERT( 0 <= rhsLength); if (lhsLength != rhsLength) { return false; // RETURN } int i = 0; while (i < lhsLength) { unsigned char lhs = static_cast<unsigned char>( bsl::tolower(static_cast<unsigned char>(lhsString[i]))); unsigned char rhs = static_cast<unsigned char>( bsl::tolower(static_cast<unsigned char>(rhsString[i]))); if (lhs != rhs) { return false; // RETURN } ++i; } return true; }
// STATIC HELPER FUNCTIONS static int lookupTimeZone(const baltzo::Zoneinfo **timeZone, const char *timeZoneId, baltzo::ZoneinfoCache *cache) // Load, into the specified 'timeZone', the address of the time zone // information having the specified 'timeZoneId' from the specified // 'cache'. Return 0 on success, and a non-zero value otherwise. A return // status of 'baltzo::ErrorCode::k_UNSUPPORTED_ID' indicates that // 'timeZoneId' is not recognized. { BSLS_ASSERT(timeZone); BSLS_ASSERT(timeZoneId); BSLS_ASSERT(cache); int rc = 0; *timeZone = cache->getZoneinfo(&rc, timeZoneId); BSLS_ASSERT((0 == rc && 0 != *timeZone) || (0 != rc && 0 == *timeZone)); if (0 == *timeZone) { BALL_LOG_SET_CATEGORY(LOG_CATEGORY); BALL_LOG_INFO << "No data found for time zone '" << timeZoneId << "' (rc = " << rc << ")." << BALL_LOG_END; } return rc; }
static unsigned int reverse_hash(const char *data, int length) // That the memory starting at the specified 'data' of specified 'length' // bytes in length. Do the bytes in the reverse of the order that 'hash' // would do them, so that this function, when called on a little-endian // machine, will return the same value as 'hash' called on a big-endian // machine. { BSLS_ASSERT(0 <= length); BSLS_ASSERT(data || 0 == length); typedef unsigned char Ub1; typedef unsigned int Ub4; const Ub1 *k = reinterpret_cast<const Ub1 *>(data); Ub4 hash = 0; for (int i = length; i > 0; ) { hash += k[--i]; hash += (hash << 10); hash ^= (hash >> 6); } hash += (hash << 3); hash ^= (hash >> 11); hash += (hash << 15); return hash; }
void baltzo::TimeZoneUtilImp::createLocalTimePeriod( LocalTimePeriod *result, const Zoneinfo::TransitionConstIterator& transition, const Zoneinfo& timeZone) { BSLS_ASSERT(result); BSLS_ASSERT(transition != timeZone.endTransitions()); BSLS_ASSERT_SAFE(ZoneinfoUtil::isWellFormed(timeZone)); result->setDescriptor(transition->descriptor()); // The transition times in 'timeZone' are guaranteed to be in the range // representable by 'bdlt::Datetime'. bdlt::Datetime utcStartTime(1, 1, 1, 0, 0, 0); Zoneinfo::convertFromTimeT64( &utcStartTime, transition->utcTime()); Zoneinfo::TransitionConstIterator next = transition; ++next; // 'utcEndTime' must account for the special case that the time falls // after the last transition. bdlt::Datetime nextUtcTime; Zoneinfo::convertFromTimeT64(&nextUtcTime, next->utcTime()); bdlt::Datetime utcEndTime = (next == timeZone.endTransitions()) ? bdlt::Datetime(9999, 12, 31, 23, 59, 59, 999) : nextUtcTime; result->setDescriptor(transition->descriptor()); result->setUtcStartAndEndTime(utcStartTime, utcEndTime); }
int baltzo::TimeZoneUtil::initLocalTime( LocalDatetime *result, LocalTimeValidity::Enum *resultValidity, const bdlt::Datetime& localTime, const char *timeZoneId, DstPolicy::Enum dstPolicy) { BSLS_ASSERT(result); BSLS_ASSERT(resultValidity); BSLS_ASSERT(timeZoneId); bdlt::DatetimeTz resultTz; LocalTimeValidity::Enum validityStatus; const int rc = initLocalTime(&resultTz, &validityStatus, localTime, timeZoneId, dstPolicy); if (0 != rc) { return rc; // RETURN } result->setDatetimeTz(resultTz); result->setTimeZoneId(timeZoneId); *resultValidity = validityStatus; return 0; }
// MANIPULATORS void Throttle::initialize(int maxSimultaneousActions, Int64 nanosecondsPerAction, bsls::SystemClockType::Enum clockType) { BSLS_ASSERT(0 <= maxSimultaneousActions); BSLS_ASSERT(0 <= nanosecondsPerAction); BSLS_ASSERT(maxSimultaneousActions || nanosecondsPerAction); BSLS_ASSERT(LLONG_MAX / bsl::max(maxSimultaneousActions, 1) >= nanosecondsPerAction); BSLS_ASSERT(bsls::SystemClockType::e_MONOTONIC == clockType || bsls::SystemClockType::e_REALTIME == clockType); AtomicOps::setInt64(&d_prevLeakTime, -k_TEN_YEARS_NANOSECONDS); if (0 == maxSimultaneousActions) { d_nanosecondsPerAction = k_ALLOW_NONE; } else if (0 == nanosecondsPerAction) { d_nanosecondsPerAction = k_ALLOW_ALL; } else { d_nanosecondsPerAction = nanosecondsPerAction; } // If 'd_nanosecondsPerAction' is set to 'allow all' or 'allow none', then // it doesn't matter what 'd_nanosecondsPerTotalReset' is. d_nanosecondsPerTotalReset = maxSimultaneousActions * nanosecondsPerAction; d_maxSimultaneousActions = 0 == nanosecondsPerAction ? INT_MAX : maxSimultaneousActions; d_clockType = clockType; }
void *BufferImpUtil::allocateFromBufferRaw(int *cursor, char *buffer, int size, bsls::Alignment::Strategy strategy) { BSLS_ASSERT(cursor); BSLS_ASSERT(buffer); BSLS_ASSERT(0 < size); BSLS_ASSERT(0 <= *cursor); void *result = 0; switch (strategy) { case bsls::Alignment::BSLS_MAXIMUM: { result = BufferImpUtil::allocateMaximallyAlignedFromBufferRaw(cursor, buffer, size); } break; case bsls::Alignment::BSLS_NATURAL: { result = BufferImpUtil::allocateNaturallyAlignedFromBufferRaw(cursor, buffer, size); } break; case bsls::Alignment::BSLS_BYTEALIGNED: { result = BufferImpUtil::allocateOneByteAlignedFromBufferRaw(cursor, buffer, size); } break; default: { BSLS_ASSERT_OPT(0 && "Invalid alignment 'strategy' value."); } break; } return result; }
StackTraceTestAllocator::StackTraceTestAllocator( int numRecordedFrames, bslma::Allocator *basicAllocator) : d_magic(k_STACK_TRACE_TEST_ALLOCATOR_MAGIC) , d_numBlocksInUse(0) , d_blocks(0) , d_mutex() , d_name("<unnamed>") , d_failureHandler(bsl::allocator_arg_t(), bsl::allocator<FailureHandler>(basicAllocator ? basicAllocator : &bslma::MallocFreeAllocator::singleton())) , d_maxRecordedFrames(numRecordedFrames + k_IGNORE_FRAMES) , d_traceBufferLength(getTraceBufferLength(numRecordedFrames)) , d_ostream(&bsl::cerr) , d_demangleFlag(true) , d_allocator_p(basicAllocator ? basicAllocator : &bslma::MallocFreeAllocator::singleton()) { BSLS_ASSERT_OPT(numRecordedFrames >= 2); BSLS_ASSERT(d_maxRecordedFrames >= numRecordedFrames); BSLS_ASSERT(d_traceBufferLength >= d_maxRecordedFrames); // This must be assigned in a statement in the body of the c'tor rather // than in the initializer list to work around a microsoft bug with // function pointers. d_failureHandler = &failAbort; }