proxygen
folly Namespace Reference

—— Concurrent Priority Queue Implementation —— More...

Namespaces

 array_detail
 
 bititerator_detail
 
 bser
 
 chrono
 
 cold_detail
 
 compression
 
 conv_bench_detail
 
 coro
 
 detail
 
 dptr_detail
 
 dynamicconverter_detail
 
 exception_tracer
 
 exception_wrapper_detail
 
 expected_detail
 
 experimental
 
 f14
 
 fbstring_detail
 
 fibers
 
 fileutil_detail
 
 for_each_detail
 
 format_value
 
 fs
 
 futures
 
 gen
 
 hash
 
 invoke_detail
 
 io
 
 json
 
 jsonschema
 
 literals
 
 logging
 
 moveonly_
 
 netops
 
 observer
 
 observer_detail
 
 padded
 
 parking_lot_detail
 
 poly
 
 portability
 
 pushmi
 
 python
 
 recordio_helpers
 
 replaceable_detail
 
 settings
 
 small_vector_policy
 
 ssl
 
 symbolizer
 
 sync_tests
 
 test
 
 threadlocal_detail
 
 traits_detail
 
 traits_detail_IsEqualityComparable
 
 traits_detail_IsLessThanComparable
 
 traits_detail_IsNothrowSwappable
 
 try_detail
 
 uri_detail
 
 utility_detail
 

Classes

struct  AccessModeStrict
 
struct  AccessSpreader
 
class  AlignedSysAllocator
 
class  allocator_delete
 
struct  AllocatorHasDefaultObjectConstruct
 
struct  AllocatorHasDefaultObjectConstruct< std::allocator< Value >, T, Args... >
 
struct  AllocatorHasDefaultObjectDestroy
 
struct  AllocatorHasDefaultObjectDestroy< std::allocator< Value >, T >
 
struct  AllocatorHasTrivialDeallocate
 
struct  AllocatorHasTrivialDeallocate< Arena< Alloc > >
 
struct  AllocatorHasTrivialDeallocate< CxxAllocatorAdaptor< T, Alloc > >
 
struct  AllocatorHasTrivialDeallocate< ParanoidArenaAlloc< ParentAlloc > >
 
struct  AllocatorHasTrivialDeallocate< SysArena >
 
struct  AllocatorHasTrivialDeallocate< ThreadCachedArena >
 
class  AlpnClient
 
class  AlpnServer
 
struct  apply_result
 
struct  ApplyInvoke
 
class  Arena
 
struct  ArenaAllocatorTraits
 
struct  ArenaAllocatorTraits< SysAllocator< void > >
 
struct  AsciiCaseInsensitive
 
struct  AsciiCaseSensitive
 
class  AsyncFileWriter
 
class  AsyncIO
 
class  AsyncIOOp
 
class  AsyncIOQueue
 
class  AsyncPipeReader
 
class  AsyncPipeWriter
 
class  AsyncReader
 
class  AsyncServerSocket
 
class  AsyncSignalHandler
 
class  AsyncSocket
 
class  AsyncSocketBase
 
class  AsyncSocketException
 
class  AsyncSSLSocket
 
class  AsyncSSLSocketWriteTest
 
class  AsyncTimeout
 
class  AsyncTransport
 
class  AsyncTransportCertificate
 
class  AsyncTransportWrapper
 
class  AsyncUDPServerSocket
 
class  AsyncUDPSocket
 
class  AsyncWriter
 
class  atomic_shared_ptr
 
class  AtomicBitSet
 
class  AtomicCoreCachedSharedPtr
 
class  AtomicFetchResetTest
 
class  AtomicFetchSetTest
 
class  AtomicHashArray
 
struct  AtomicHashArrayLinearProbeFcn
 
struct  AtomicHashArrayQuadraticProbeFcn
 
class  AtomicHashMap
 
struct  AtomicHashMapFullError
 
class  AtomicIntrusiveLinkedList
 
struct  AtomicIntrusiveLinkedListHook
 
class  AtomicLinkedList
 
class  AtomicStruct
 
struct  AtomicUnorderedInsertMap
 
class  AttachDetachClient
 
class  AutoTimer
 
struct  B
 
class  BadExpectedAccess
 
class  BadFormatArg
 
struct  BadPolyAccess
 
struct  BadPolyCast
 
class  BaseFormatter
 
class  basic_fbstring
 
class  basic_once_flag
 
class  BasicDynamicTokenBucket
 
class  BasicFixedString
 A class for holding up to N characters of type Char that is amenable to constexpr string manipulation. It is guaranteed to not perform any dynamic allocation. More...
 
class  BasicTokenBucket
 
class  Baton
 
struct  BenchmarkSuspender
 
class  BitIterator
 
struct  Bits
 
class  BlockingQueue
 
struct  BlockingQueueAddResult
 
class  BlockingWriteClient
 
class  BlockingWriteServer
 
struct  Bools
 
class  BrokenPromise
 
class  BucketedTimeSeries
 
class  CachelinePadded
 
struct  CacheLocality
 
class  CalledProcessError
 
class  Codel
 
struct  compare_equal_to
 
struct  compare_greater
 
struct  compare_greater_equal
 
struct  compare_less
 
struct  compare_less_equal
 
struct  compare_not_equal_to
 
class  ConcurrentHashMap
 
class  ConcurrentSkipList
 
struct  Conjunction
 
struct  Conjunction< T >
 
struct  Conjunction< T, TList... >
 
class  ConnectClient
 
class  ConnectTimeoutCallback
 
struct  constexpr_equal_to
 
struct  constexpr_greater
 
struct  constexpr_greater_equal
 
struct  constexpr_less
 
struct  constexpr_less_equal
 
struct  constexpr_not_equal_to
 
class  ContainsExpected
 
class  ConversionError
 
struct  ConversionErrorBase
 
struct  CopyCount
 
class  CoreCachedSharedPtr
 
class  CoreCachedWeakPtr
 
class  CoreRawAllocator
 
class  CpuId
 
class  CPUThreadPoolExecutor
 
struct  custom_stop_watch
 
class  CustomLogFormatter
 
class  CxxAllocatorAdaptor
 
class  CxxHugePageAllocator
 
class  Data
 
class  DecoratedAsyncTransportWrapper
 
class  DefaultAlign
 
class  DefaultKeepAliveExecutor
 
struct  DefaultWeightFn
 
class  DelayedDestruction
 
class  DelayedDestructionBase
 
class  DestructorCheck
 
class  DiscriminatedPtr
 
struct  Disjunction
 
struct  Disjunction< T >
 
struct  Disjunction< T, TList... >
 
class  DrivableExecutor
 
struct  drop_unit
 
struct  drop_unit< Unit >
 
class  dummy_fbstring_core
 
struct  dynamic
 
class  DynamicBoundedQueue
 
struct  DynamicConstructor
 
struct  DynamicConstructor< C, typename std::enable_if< !std::is_same< C, dynamic >::value &&!dynamicconverter_detail::is_map< C >::value &&!std::is_constructible< StringPiece, const C & >::value &&dynamicconverter_detail::is_range< C >::value >::type >
 
struct  DynamicConstructor< C, typename std::enable_if< !std::is_same< C, dynamic >::value &&dynamicconverter_detail::is_map< C >::value >::type >
 
struct  DynamicConstructor< C, typename std::enable_if< std::is_same< C, dynamic >::value >::type >
 
struct  DynamicConstructor< std::pair< A, B >, void >
 
struct  DynamicConstructor< std::vector< bool >, void >
 
struct  DynamicConverter
 
struct  DynamicConverter< A >
 
struct  DynamicConverter< B >
 
struct  DynamicConverter< bool >
 
struct  DynamicConverter< C, typename std::enable_if< dynamicconverter_detail::is_container< C >::value &&!dynamicconverter_detail::is_associative< C >::value >::type >
 
struct  DynamicConverter< C, typename std::enable_if< dynamicconverter_detail::is_container< C >::value &&dynamicconverter_detail::is_associative< C >::value >::type >
 
struct  DynamicConverter< folly::fbstring >
 
struct  DynamicConverter< std::pair< F, S > >
 
struct  DynamicConverter< std::string >
 
struct  DynamicConverter< T, typename std::enable_if< std::is_enum< T >::value >::type >
 
struct  DynamicConverter< T, typename std::enable_if< std::is_floating_point< T >::value >::type >
 
struct  DynamicConverter< T, typename std::enable_if< std::is_integral< T >::value &&!std::is_same< T, bool >::value >::type >
 
struct  DynamicConverter< Token >
 
class  DynamicParser
 
struct  DynamicParserLogicError
 
struct  DynamicParserParseError
 
struct  emplace_args
 
class  EmptyReadCallback
 
struct  enable_if<(n<=0)>::type >
 
class  enable_shared_from_this
 
class  Endian
 
struct  EvbAndContext
 
class  EventBase
 
class  EventBaseAborter
 
class  EventBaseLocal
 
class  EventBaseManager
 
class  EventBaseObserver
 
class  EventBaseThread
 
class  EventCount
 
class  EventHandler
 
class  EventUtil
 
class  EvictingCacheMap
 
class  exception_wrapper
 
class  ExecutionObserver
 
class  Executor
 
class  Expected
 
struct  ExpectingDeleter
 
class  ExpectWriteErrorCallback
 
class  F14FastMap
 
class  F14FastSet
 
class  F14NodeMap
 
class  F14NodeSet
 
struct  F14TableStats
 
class  F14ValueMap
 
class  F14ValueSet
 
class  F14VectorMap
 
class  F14VectorSet
 
class  FakeAllPowerfulAssertingMutex
 
class  FakeAllPowerfulAssertingMutexInternal
 
class  FakeMutex
 
struct  FallbackGetcpu
 
class  fbstring_core
 
class  fbvector
 
class  FcCustomExample
 
class  FcSimpleExample
 
class  FiberIOExecutor
 An IOExecutor that executes funcs under mapped fiber context. More...
 
class  File
 
class  FileHandlerFactory
 
class  FileWriterFactory
 
class  Fingerprint
 
class  FixedAlign
 
class  FlatCombining
 
struct  FormatArg
 
class  FormatKeyNotFoundException
 
class  Formatter
 
class  FormatValue
 
class  FormatValue< bool >
 
class  FormatValue< detail::DefaultValueWrapper< dynamic, V > >
 
class  FormatValue< double >
 
class  FormatValue< dynamic >
 
class  FormatValue< float >
 
class  FormatValue< FormattableButNoToString >
 
class  FormatValue< KeyValue >
 
class  FormatValue< NoncopyableInt >
 
class  FormatValue< T, typename std::enable_if< std::is_integral< T >::value &&!std::is_same< T, bool >::value >::type >
 
class  FormatValue< ToStringFailure >
 
class  Function
 
class  FunctionRef
 A reference wrapper for callable objects. More...
 
class  FunctionRef< ReturnType(Args...)>
 
class  FunctionScheduler
 
class  Future
 
class  FutureAlreadyContinued
 
class  FutureAlreadyRetrieved
 
class  FutureCancellation
 
class  FutureDAG
 
class  FutureDAGFunctor
 
class  FutureException
 
class  FutureExecutor
 
class  FutureInvalid
 
class  FutureNoExecutor
 
class  FutureNoTimekeeper
 
class  FutureNotReady
 
class  FuturePredicateDoesNotObtain
 
class  FutureSplitter
 
class  FutureSplitterInvalid
 
class  FutureTimeout
 
struct  Getcpu
 
class  GlogStyleFormatter
 
struct  GoogleLogger
 
class  GroupVarint
 
class  HandshakeCallback
 
class  HandshakeErrorCallback
 
class  HandshakeTimeoutCallback
 
struct  Hash
 
struct  hasher
 
struct  hasher< bool >
 
struct  hasher< char >
 
struct  hasher< double >
 
struct  hasher< float >
 
struct  hasher< folly::Range< T * >, std::enable_if_t< std::is_integral< T >::value, void > >
 
struct  hasher< signed char >
 
struct  hasher< signed int >
 
struct  hasher< signed long >
 
struct  hasher< signed long long >
 
struct  hasher< signed short >
 
struct  hasher< std::pair< T1, T2 > >
 
struct  hasher< std::string >
 
struct  hasher< std::tuple< Ts... > >
 
struct  hasher< T, std::enable_if_t< std::is_enum< T >::value > >
 
struct  hasher< unsigned char >
 
struct  hasher< unsigned int >
 
struct  hasher< unsigned long >
 
struct  hasher< unsigned long long >
 
struct  hasher< unsigned short >
 
struct  HashingThreadId
 
class  hazptr_array
 
struct  hazptr_default_domain_helper
 
struct  hazptr_default_domain_helper< std::atomic >
 
class  hazptr_deleter
 
class  hazptr_deleter< T, std::default_delete< T > >
 
class  hazptr_domain
 
class  hazptr_holder
 
class  hazptr_local
 
class  hazptr_obj
 
class  hazptr_obj_base
 
class  hazptr_obj_base_linked
 
class  hazptr_obj_linked
 
class  hazptr_obj_list
 
class  hazptr_priv
 
class  hazptr_rec
 
class  hazptr_root
 
class  hazptr_tc
 
class  hazptr_tc_entry
 
class  HazptrLockFreeLIFO
 
class  HazptrSWMRSet
 
class  HazptrWideCAS
 
struct  HeterogeneousAccessEqualTo
 
struct  HeterogeneousAccessEqualTo< T, std::enable_if_t< detail::TransparentlyConvertibleToRange< T >::value > >
 
struct  HeterogeneousAccessHash
 
struct  HeterogeneousAccessHash< T, std::enable_if_t< detail::TransparentlyConvertibleToRange< T >::value > >
 
class  HHWheelTimer
 
class  Histogram
 
struct  HugePageSize
 
struct  Identity
 
struct  Ignore
 
class  ImmediateFileWriter
 
struct  in_place_index_tag
 
struct  in_place_tag
 
struct  in_place_type_tag
 
class  Indestructible
 
struct  IndexedMemPool
 
struct  IndexedMemPoolTraits
 
class  Init
 
struct  initlist_construct_t
 
class  InitThreadFactory
 
class  InlineExecutor
 
struct  integer_sequence
 
class  InvalidAddressFamilyException
 
struct  invoke_result
 
class  IOBuf
 
struct  IOBufCompare
 
struct  IOBufEqualTo
 
struct  IOBufGreater
 
struct  IOBufGreaterEqual
 
struct  IOBufHash
 
struct  IOBufLess
 
struct  IOBufLessEqual
 
struct  IOBufNotEqualTo
 
class  IOBufQueue
 
class  IOExecutor
 
class  IOObjectCache
 
class  IOThreadPoolExecutor
 
class  IPAddressFormatException
 
class  IPAddressV4
 
class  IPAddressV6
 
struct  is_applicable
 
struct  is_applicable_r
 
struct  is_invocable
 
struct  is_invocable_r
 
struct  is_nothrow_applicable
 
struct  is_nothrow_applicable_r
 
struct  is_nothrow_invocable
 
struct  is_nothrow_invocable_r
 
struct  is_replaceable
 
struct  is_replaceable< Replaceable< T > >
 
struct  IsAvalanchingHasher
 
struct  IsAvalanchingHasher< Hash, K >
 
struct  IsAvalanchingHasher< hasher< bool >, K >
 
struct  IsAvalanchingHasher< hasher< std::string >, K >
 
struct  IsAvalanchingHasher< hasher< std::tuple< T > >, K >
 
struct  IsAvalanchingHasher< hasher< std::tuple< T1, T2, Ts... > >, K >
 
struct  IsAvalanchingHasher< hasher< T, std::enable_if_t< std::is_enum< T >::value > >, K >
 
struct  IsAvalanchingHasher< std::hash< std::basic_string< Args... > >, K >
 
struct  IsAvalanchingHasher< transparent< H >, K >
 
struct  IsConvertible
 
struct  isFuture
 
struct  isFuture< Future< T > >
 
struct  isFutureOrSemiFuture
 
struct  isFutureOrSemiFuture< Future< T > >
 
struct  isFutureOrSemiFuture< SemiFuture< T > >
 
struct  IsRelocatable
 
struct  IsRelocatable< Data< f, pad > >
 
struct  IsRelocatable< std::basic_string< T1, T2, T3 > >
 
struct  IsRelocatable< std::deque< T1, T2 > >
 
struct  IsRelocatable< std::function< T1 > >
 
struct  IsRelocatable< std::pair< T, U > >
 
struct  IsRelocatable< std::shared_ptr< T1 > >
 
struct  IsRelocatable< std::unique_ptr< T1, T2 > >
 
struct  IsRelocatable< std::vector< T1, T2 > >
 
struct  IsRelocatable< T1 >
 
struct  isSemiFuture
 
struct  isSemiFuture< SemiFuture< T > >
 
struct  IsSomeString
 
struct  IsSomeString< fbstring >
 
struct  IsSomeString< std::string >
 
struct  isTry
 
struct  isTry< Try< T > >
 
struct  IsZeroInitializable
 
class  JemallocHugePageAllocator
 
class  JemallocNodumpAllocator
 
class  json_patch
 
class  json_pointer
 
class  KeepAliveTestExecutor
 
class  LeakySingleton
 
class  LegacyStatsClock
 
struct  LifoSemImpl
 
class  LifoSemMPMCQueue
 
struct  lift_unit
 
struct  lift_unit< void >
 
struct  like
 
struct  Line
 
class  LockedPtr
 
class  LockedPtrBase
 
class  LockedPtrBase< SynchronizedType, std::mutex, LockPolicy >
 
class  LockFreeRingBuffer
 
struct  LockPolicyExclusive
 
struct  LockPolicyFromExclusiveToShared
 
struct  LockPolicyFromExclusiveToUpgrade
 
struct  LockPolicyFromUpgradeToExclusive
 
struct  LockPolicyFromUpgradeToShared
 
struct  LockPolicyShared
 
struct  LockPolicyTryExclusive
 
struct  LockPolicyTryShared
 
struct  LockPolicyTryUpgrade
 
struct  LockPolicyUpgrade
 
struct  LockTraits
 
struct  LockTraitsBase
 
class  LogCategory
 
class  LogCategoryConfig
 
class  LogConfig
 
class  LogConfigParseError
 
class  LogFormatter
 
class  Logger
 
class  LoggerDB
 
class  LogHandler
 
class  LogHandlerConfig
 
class  LogHandlerFactory
 
class  LogMessage
 
class  LogName
 
class  LogStream
 
class  LogStreamBuffer
 
class  LogStreamProcessor
 
class  LogStreamVoidify
 
class  LogStreamVoidify< true >
 
class  LogWriter
 
class  MacAddress
 
class  ManualExecutor
 
struct  max_align_t
 
class  MemoryIdlerTimeout
 
class  MemoryMapping
 
class  MicroLockBase
 
class  MicroLockCore
 
struct  MicroSpinLock
 
class  MockAsyncSSLSocket
 
class  MoveTester
 
class  MoveWrapper
 
class  MPMCPipeline
 
class  MPMCPipelineStage
 
class  MPMCQueue
 
class  MPMCQueue< T, Atom, true >
 
class  MultiLevelTimeSeries
 
struct  MutableAtom
 
struct  MutableData
 
class  NamedThreadFactory
 
struct  Negation
 
class  NestedCommandLineApp
 
struct  NestedCommandLineParseResult
 
struct  NetworkSocket
 
struct  NoConstructor
 
struct  NoDefault
 
struct  NoDestructor
 
class  NonDefaultConstructibleMutex
 
struct  None
 
class  NoopReadCallback
 
struct  NoSelfAssign
 
class  NotificationQueue
 
class  Optional
 
class  OptionalEmptyException
 
class  PackedSyncPtr
 
class  ParkingLot
 
class  PasswordCollector
 
class  PasswordInFile
 
struct  PicoSpinLock
 
struct  Poly
 
struct  PolyExtends
 
struct  presorted_t
 
class  PriorityLifoSemMPMCQueue
 
class  PriorityMPMCQueue
 
class  PriorityThreadFactory
 
class  ProcessReturnCode
 
struct  ProducerConsumerQueue
 
class  ProgramExit
 
class  Promise
 
class  PromiseAlreadySatisfied
 
class  PromiseException
 
class  PromiseInvalid
 
class  propagate_const
 
struct  QuantileEstimates
 
class  QueuedImmediateExecutor
 
class  QueueFullException
 
class  Random
 
class  Range
 
class  rcu_domain
 
class  rcu_obj_base
 
class  rcu_reader_domain
 
class  rcu_token
 
class  ReadCallback
 
class  ReadCallbackBase
 
class  ReadCallbackTerminator
 
class  ReadEOFCallback
 
class  ReadErrorCallback
 
class  ReadMostlyMainPtr
 
class  ReadMostlyMainPtrDeleter
 
class  ReadMostlySharedPtr
 
class  ReadMostlyWeakPtr
 
class  RecordIOReader
 
class  RecordIOWriter
 
class  RelaxedConcurrentPriorityQueue
 
struct  remove_cvref
 
class  RenegotiatingServer
 
class  Replaceable
 
class  Req
 
class  RequestContext
 
class  RequestContextScopeGuard
 
class  RequestData
 
class  RequestEventBase
 
class  RequestToken
 
class  rvalue_reference_wrapper
 
class  RWSpinLock
 
class  SaturatingSemaphore
 
struct  ScaleInfo
 
class  ScheduledExecutor
 
class  ScopedBoundPort
 
class  ScopedEventBaseThread
 
class  ScopedUnlocker
 
class  SemiFuture
 
class  SendMsgDataCallback
 
class  SendMsgFlagsCallback
 
class  SendMsgParamsCallbackBase
 
class  SequencedExecutor
 
class  SerialExecutor
 Executor that guarantees serial non-concurrent execution of added tasks. More...
 
struct  ShallowCopyRequestContextScopeGuard
 
class  SharedMutexImpl
 
struct  SharedMutexToken
 
class  SharedPromise
 
struct  ShutdownSemError
 The exception thrown when wait()ing on an isShutdown() LifoSem. More...
 
class  ShutdownSocketSet
 
class  SimpleAllocator
 
class  SimpleQuantileEstimator
 
class  Singleton
 
class  SingletonThreadLocal
 
class  SingletonVault
 
class  SlidingWindowQuantileEstimator
 
class  small_vector
 
class  SNIClient
 
class  SNIServer
 
class  SocketAddress
 
class  SocketAddressTestHelper
 
class  SocketPair
 
class  SomeClass
 
class  sorted_vector_map
 
class  sorted_vector_set
 
class  SparseByteSet
 
class  SpinLock
 
struct  SpinLockArray
 
class  SpinLockGuardImpl
 
class  SSLAcceptCloseRunner
 
class  SSLAcceptDestroyRunner
 
class  SSLAcceptErrorRunner
 
class  SSLAcceptEvbRunner
 
class  SSLAcceptRunner
 
class  SSLClient
 
class  SSLContext
 
class  SSLContextTest
 
class  SSLException
 
class  SSLHandshakeBase
 
class  SSLHandshakeClient
 
class  SSLHandshakeClientDoVerify
 
class  SSLHandshakeClientNoVerify
 
class  SSLHandshakeServer
 
class  SSLHandshakeServerDoVerify
 
class  SSLHandshakeServerNoVerify
 
class  SSLHandshakeServerParseClientHello
 
class  SSLOptionsTest
 
class  SSLServerAcceptCallback
 
class  SSLServerAcceptCallbackBase
 
class  SSLServerAcceptCallbackDelay
 
class  SSLServerAsyncCacheAcceptCallback
 
class  SSLSessionTest
 
struct  StampedPtr
 
class  StandardLogHandler
 
class  StandardLogHandlerFactory
 
struct  static_function_deleter
 
class  StreamHandlerFactory
 
struct  StrictConjunction
 
struct  StrictDisjunction
 
class  StringKeyedMap
 
class  StringKeyedSetBase
 
struct  StringKeyedUnorderedMap
 
class  Subprocess
 
class  SubprocessError
 
class  SubprocessSpawnError
 
struct  Synchronized
 
class  SynchronizedBase
 
class  SynchronizedBase< Subclass, detail::MutexLevel::SHARED >
 
class  SynchronizedBase< Subclass, detail::MutexLevel::UNIQUE >
 
class  SynchronizedBase< Subclass, detail::MutexLevel::UPGRADE >
 
class  SynchronizedLockTest
 
class  SynchronizedPtr
 
struct  SynchronizedPtrLockedElement
 
class  SynchronizedTest
 
class  SynchronizedTimedTest
 
class  SynchronizedTimedWithConstTest
 
class  SysAllocator
 
class  SysArena
 
struct  SysBufferDeleter
 
class  TDigest
 
class  Tearable
 
struct  TemplateRange
 
struct  TemplateSeq
 
struct  TemplateTupleRange
 
class  TestExecutor
 
class  TestHandlerFactory
 
class  TestLogHandler
 
class  TestLogHandlerFactory
 
class  TestLogWriter
 
class  TestSSLAsyncCacheServer
 
class  TestSSLServer
 
class  ThreadCachedArena
 
class  ThreadCachedInt
 
class  ThreadedExecutor
 
class  ThreadedRepeatingFunctionRunner
 
class  ThreadFactory
 
class  ThreadLocal
 
class  ThreadLocalPRNG
 
class  ThreadLocalPtr
 
class  ThreadPoolExecutor
 
class  ThreadPoolListHook
 
class  ThreadWheelTimekeeper
 
struct  ThrowingBadness
 
class  TimedDrivableExecutor
 
class  Timekeeper
 
class  TimeoutManager
 
class  TimeoutQueue
 
class  TimePoint
 
class  TimeseriesHistogram
 
class  TLRefCount
 
struct  TokenBucketTest
 
struct  transparent
 
struct  TransparentStringEqualTo
 
struct  TransparentStringHash
 
class  Try
 
class  Try< void >
 
class  TryException
 
struct  TupleHasher
 
struct  TupleHasher< 0, Ts... >
 
class  TypedIOBuf
 
struct  TypeError
 
struct  Unaligned
 
struct  Unaligned< T, typename std::enable_if< std::is_pod< T >::value >::type >
 
struct  UnalignedNoASan
 
class  UnboundedBlockingQueue
 
class  UnboundedQueue
 
class  UndelayedDestruction
 
class  Unexpected
 
struct  Unit
 
struct  unsorted_t
 
class  Uri
 
class  UsingUninitializedTry
 
class  UTF8Range
 
class  VirtualEventBase
 
class  VirtualExecutor
 
class  WaitOptions
 
struct  WithConstructor
 
struct  WithDestructor
 
class  WriteCallbackBase
 
class  WriteChainAsyncTransportWrapper
 
class  WriteErrorCallback
 
class  XlogCategoryInfo
 
class  XlogFileScopeInfo
 
class  XlogLevelInfo
 
class  ZeroCopyTest
 
class  ZeroCopyTestAsyncSocket
 
class  ZeroCopyTestServer
 

Typedefs

template<class KeyT , class ValueT , class HashFcn = std::hash<KeyT>, class EqualFcn = std::equal_to<KeyT>, class Allocator = std::allocator<char>>
using QuadraticProbingAtomicHashMap = AtomicHashMap< KeyT, ValueT, HashFcn, EqualFcn, Allocator, AtomicHashArrayQuadraticProbeFcn >
 
template<typename Key , typename Value , typename Hash = std::hash<Key>, typename KeyEqual = std::equal_to<Key>, bool SkipKeyValueDeletion = (boost::has_trivial_destructor<Key>::value && boost::has_trivial_destructor<Value>::value), template< typename > class Atom = std::atomic, typename Allocator = folly::detail::MMapAlloc>
using AtomicUnorderedInsertMap64 = AtomicUnorderedInsertMap< Key, Value, Hash, KeyEqual, SkipKeyValueDeletion, Atom, uint64_t, Allocator >
 
typedef function< detail::TimeIterPair(unsigned int)> BenchmarkFun
 
typedef FallbackGetcpu< HashingThreadIdFallbackGetcpuType
 
template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = 7, typename WeightFn = DefaultWeightFn<T>, template< typename > class Atom = std::atomic>
using DSPSCQueue = DynamicBoundedQueue< T, true, true, MayBlock, LgSegmentSize, LgAlign, WeightFn, Atom >
 Aliases. More...
 
template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = 7, typename WeightFn = DefaultWeightFn<T>, template< typename > class Atom = std::atomic>
using DMPSCQueue = DynamicBoundedQueue< T, false, true, MayBlock, LgSegmentSize, LgAlign, WeightFn, Atom >
 
template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = 7, typename WeightFn = DefaultWeightFn<T>, template< typename > class Atom = std::atomic>
using DSPMCQueue = DynamicBoundedQueue< T, true, false, MayBlock, LgSegmentSize, LgAlign, WeightFn, Atom >
 
template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = 7, typename WeightFn = DefaultWeightFn<T>, template< typename > class Atom = std::atomic>
using DMPMCQueue = DynamicBoundedQueue< T, false, false, MayBlock, LgSegmentSize, LgAlign, WeightFn, Atom >
 
template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = constexpr_log2(hardware_destructive_interference_size), template< typename > class Atom = std::atomic>
using USPSCQueue = UnboundedQueue< T, true, true, MayBlock, LgSegmentSize, LgAlign, Atom >
 
template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = constexpr_log2(hardware_destructive_interference_size), template< typename > class Atom = std::atomic>
using UMPSCQueue = UnboundedQueue< T, false, true, MayBlock, LgSegmentSize, LgAlign, Atom >
 
template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = constexpr_log2(hardware_destructive_interference_size), template< typename > class Atom = std::atomic>
using USPMCQueue = UnboundedQueue< T, true, false, MayBlock, LgSegmentSize, LgAlign, Atom >
 
template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = constexpr_log2(hardware_destructive_interference_size), template< typename > class Atom = std::atomic>
using UMPMCQueue = UnboundedQueue< T, false, false, MayBlock, LgSegmentSize, LgAlign, Atom >
 
template<typename Container , bool implicit_unpack = true>
using emplace_iterator = detail::emplace_iterator_impl< detail::Emplace, Container, implicit_unpack >
 
template<typename Container , bool implicit_unpack = true>
using hint_emplace_iterator = detail::emplace_iterator_impl< detail::EmplaceHint, Container, implicit_unpack >
 
template<typename Container , bool implicit_unpack = true>
using front_emplace_iterator = detail::emplace_iterator_impl< detail::EmplaceFront, Container, implicit_unpack >
 
template<typename Container , bool implicit_unpack = true>
using back_emplace_iterator = detail::emplace_iterator_impl< detail::EmplaceBack, Container, implicit_unpack >
 
template<class... Ts>
using PolyMembers = detail::TypeList< Ts... >
 
using Func = Function< void()>
 
using SyncVecThreadPoolExecutors = folly::Synchronized< std::vector< ThreadPoolExecutor * >>
 
template<class Expected >
using ExpectedValueType = typename std::remove_reference< Expected >::type::value_type
 
template<class Expected >
using ExpectedErrorType = typename std::remove_reference< Expected >::type::error_type
 
using unexpected_t = expected_detail::UnexpectedTag(&)(expected_detail::UnexpectedTag)
 
typedef std::vector< HugePageSizeHugePageSizeVec
 
using DefaultRefCount = TLRefCount
 
using StringKeyedSet = StringKeyedSetBase<>
 
template<class Hash = f14::DefaultHasher<std::string>, class Eq = f14::DefaultKeyEqual<std::string>, class Alloc = f14::DefaultAlloc<std::string>>
using BasicStringKeyedUnorderedSet = F14NodeSet< std::string, Hash, Eq, Alloc >
 
using StringKeyedUnorderedSet = BasicStringKeyedUnorderedSet<>
 
typedef basic_fbstring< char > fbstring
 
template<std::size_t N>
using FixedString = BasicFixedString< char, N >
 
template<typename Tuple >
using index_sequence_for_tuple = make_index_sequence< std::tuple_size< Tuple >::value >
 
template<typename F , typename Tuple >
using apply_result_t = invoke_result_t< ApplyInvoke, F, Tuple >
 
template<typename F , typename... Args>
using invoke_result_t = typename invoke_result< F, Args... >::type
 
using Duration = std::chrono::milliseconds
 
template<typename F , typename T , typename ItT >
using MaybeTryArg = typename std::conditional< is_invocable< F, T &&, Try< ItT > && >::value, Try< ItT >, ItT >::type
 
typedef std::unique_ptr< int > A
 
template<class T >
using EnableIfFuture = typename std::enable_if< isFuture< T >::value >::type
 
template<class T >
using EnableUnlessFuture = typename std::enable_if<!isFuture< T >::value >::type
 
template<typename T >
using IndexedMemPoolTraitsLazyRecycle = IndexedMemPoolTraits< T, false, false >
 
template<typename T >
using IndexedMemPoolTraitsEagerRecycle = IndexedMemPoolTraits< T, true, true >
 
using IntrusiveListHook = boost::intrusive::list_member_hook< boost::intrusive::link_mode< boost::intrusive::auto_unlink >>
 
template<typename T , IntrusiveListHook T::* PtrToMember>
using IntrusiveList = boost::intrusive::list< T, boost::intrusive::member_hook< T, IntrusiveListHook, PtrToMember >, boost::intrusive::constant_time_size< false >>
 
using SafeIntrusiveListHook = boost::intrusive::list_member_hook< boost::intrusive::link_mode< boost::intrusive::safe_link >>
 
template<typename T , SafeIntrusiveListHook T::* PtrToMember>
using CountedIntrusiveList = boost::intrusive::list< T, boost::intrusive::member_hook< T, SafeIntrusiveListHook, PtrToMember >, boost::intrusive::constant_time_size< true >>
 
using Cob = Func
 
typedef Range< const char * > StringPiece
 
typedef std::shared_ptr< SSLContextSSLContextPtr
 
typedef std::pair< IPAddressV4, uint8_tCIDRNetworkV4
 
typedef std::array< uint8_t, 4 > ByteArray4
 
typedef std::pair< IPAddressV6, uint8_tCIDRNetworkV6
 
typedef std::array< uint8_t, 16 > ByteArray16
 
template<typename T , typename Alloc >
using ArenaAllocator = CxxAllocatorAdaptor< T, Arena< Alloc >>
 
template<typename T >
using SysArenaAllocator = ArenaAllocator< T, SysAllocator< void >>
 
template<typename T >
using ThreadCachedArenaAllocator = CxxAllocatorAdaptor< T, ThreadCachedArena >
 
using SysBufferUniquePtr = std::unique_ptr< void, SysBufferDeleter >
 
typedef MicroLockBase MicroLock
 
template<class Node , class Tfx = detail::MetaIdentity, class Access = detail::PolyAccess>
using PolySelf = decltype(Access::template self_< Node, Tfx >())
 
using PolyDecay = detail::MetaQuote< std::decay_t >
 
using libevent_fd_t = int
 
using EventSetCallback = void(*)(libevent_fd_t, short, void *)
 
typedef Range< char * > MutableStringPiece
 
typedef Range< const unsigned char * > ByteRange
 
typedef Range< unsigned char * > MutableByteRange
 
typedef SharedMutexImpl< true > SharedMutexReadPriority
 
typedef SharedMutexImpl< false > SharedMutexWritePriority
 
typedef SharedMutexWritePriority SharedMutex
 
typedef SharedMutexImpl< false, void, std::atomic, false, false > SharedMutexSuppressTSAN
 
typedef SpinLockGuardImpl< SpinLockSpinLockGuard
 
using monotonic_clock = std::chrono::steady_clock
 
template<typename Duration = folly::chrono::coarse_steady_clock::duration>
using coarse_stop_watch = custom_stop_watch< folly::chrono::coarse_steady_clock, Duration >
 
template<typename Duration = std::chrono::steady_clock::duration>
using stop_watch = custom_stop_watch< std::chrono::steady_clock, Duration >
 
using atomic_uint_fast_wait_t = std::atomic< std::uint32_t >
 
using once_flag = basic_once_flag< SharedMutex >
 
using DistributedMutex = detail::distributed_mutex::DistributedMutex<>
 
template<template< typename > class Atom>
using aligned_hazptr_holder = typename std::aligned_storage< sizeof(hazptr_holder< Atom >), alignof(hazptr_holder< Atom >)>::type
 
typedef LifoSemImpl LifoSem
 
typedef std::lock_guard< MicroSpinLockMSLGuard
 
using rcu_reader = rcu_reader_domain< RcuTag >
 
template<class Mutex >
using MutexLevelValue = detail::MutexLevelValueImpl< true, LockTraits< Mutex >::is_shared, LockTraits< Mutex >::is_upgrade >
 
using SynchronizedTestTypes = testing::Types< folly::SharedMutexReadPriority, folly::SharedMutexWritePriority, std::mutex, std::recursive_mutex, boost::mutex, boost::recursive_mutex, boost::shared_mutex, folly::SpinLock >
 
using SynchronizedTimedTestTypes = testing::Types< folly::SharedMutexReadPriority, folly::SharedMutexWritePriority >
 
using SynchronizedTimedWithConstTestTypes = testing::Types< folly::SharedMutexReadPriority, folly::SharedMutexWritePriority >
 
using CountPair = std::pair< int, int >
 
template<typename LockPolicy >
using LPtr = LockedPtr< Synchronized< int >, LockPolicy >
 
using TokenBucket = BasicTokenBucket<>
 
using DynamicTokenBucket = BasicDynamicTokenBucket<>
 
template<bool B>
using bool_constant = std::integral_constant< bool, B >
 
template<std::size_t I>
using index_constant = std::integral_constant< std::size_t, I >
 
template<typename T >
using _t = typename T::type
 
template<typename T >
using remove_cvref_t = typename remove_cvref< T >::type
 
template<typename Src , typename Dst >
using like_t = typename detail::like_< Src >::template apply< remove_cvref_t< Dst >>
 
template<class T , class... Ts>
using type_t = typename traits_detail::type_t_< T, Ts... >::type
 
template<class... Ts>
using void_t = type_t< void, Ts... >
 
template<class T >
using is_trivially_copyable = std::is_trivially_copyable< T >
 
template<class... >
using Ignored = Ignore
 
template<typename T , typename... Ts>
using IsOneOf = StrictDisjunction< std::is_same< T, Ts >... >
 
template<typename T >
using lift_unit_t = typename lift_unit< T >::type
 
template<typename T >
using drop_unit_t = typename drop_unit< T >::type
 
using UTF8StringPiece = UTF8Range< const char * >
 
template<std::size_t... Ints>
using index_sequence = integer_sequence< std::size_t, Ints... >
 
template<typename T , std::size_t Size>
using make_integer_sequence = typename utility_detail::make_seq< Size >::template apply< integer_sequence< T >, integer_sequence< T, 0 >>
 
template<std::size_t Size>
using make_index_sequence = make_integer_sequence< std::size_t, Size >
 
template<class... T>
using index_sequence_for = make_index_sequence< sizeof...(T)>
 
using in_place_t = in_place_tag(&)(in_place_tag)
 
template<class T >
using in_place_type_t = in_place_type_tag< T >(&)(in_place_type_tag< T >)
 
template<std::size_t I>
using in_place_index_t = in_place_index_tag< I >(&)(in_place_index_tag< I >)
 
using MoveOnly = moveonly_::MoveOnly
 

Enumerations

enum  CompressionCounterKey {
  CompressionCounterKey::BYTES_BEFORE_COMPRESSION = 0, CompressionCounterKey::BYTES_AFTER_COMPRESSION = 1, CompressionCounterKey::BYTES_BEFORE_DECOMPRESSION = 2, CompressionCounterKey::BYTES_AFTER_DECOMPRESSION = 3,
  CompressionCounterKey::COMPRESSIONS = 4, CompressionCounterKey::DECOMPRESSIONS = 5, CompressionCounterKey::COMPRESSION_MILLISECONDS = 6, CompressionCounterKey::DECOMPRESSION_MILLISECONDS = 7
}
 
enum  CompressionCounterType { CompressionCounterType::AVG = 0, CompressionCounterType::SUM = 1 }
 
enum  ConversionCode : unsigned char {
  ConversionCode::SUCCESS, ConversionCode::EMPTY_INPUT_STRING, ConversionCode::NO_DIGITS, ConversionCode::BOOL_OVERFLOW,
  ConversionCode::BOOL_INVALID_VALUE, ConversionCode::NON_DIGIT_CHAR, ConversionCode::INVALID_LEADING_CHAR, ConversionCode::POSITIVE_OVERFLOW,
  ConversionCode::NEGATIVE_OVERFLOW, ConversionCode::STRING_TO_FLOAT_ERROR, ConversionCode::NON_WHITESPACE_AFTER_END, ConversionCode::ARITH_POSITIVE_OVERFLOW,
  ConversionCode::ARITH_NEGATIVE_OVERFLOW, ConversionCode::ARITH_LOSS_OF_PRECISION, ConversionCode::NUM_ERROR_CODES
}
 
enum  TLPDestructionMode { TLPDestructionMode::THIS_THREAD, TLPDestructionMode::ALL_THREADS }
 
enum  QueueBehaviorIfFull { QueueBehaviorIfFull::THROW, QueueBehaviorIfFull::BLOCK }
 
enum  GoogleLoggerStyle { GoogleLoggerStyle::SECONDS, GoogleLoggerStyle::PRETTY }
 
enum  ProgramOptionsStyle { ProgramOptionsStyle::GFLAGS, ProgramOptionsStyle::GNU }
 
enum  AcquireMallocatedString
 
enum  WriteFlags : uint32_t {
  WriteFlags::NONE = 0x00, WriteFlags::CORK = 0x01, WriteFlags::EOR = 0x02, WriteFlags::WRITE_SHUTDOWN = 0x04,
  WriteFlags::WRITE_MSG_ZEROCOPY = 0x08
}
 
enum  SSLError {
  SSLError::CLIENT_RENEGOTIATION, SSLError::INVALID_RENEGOTIATION, SSLError::EARLY_WRITE, SSLError::SSL_ERROR,
  SSLError::NETWORK_ERROR, SSLError::EOF_ERROR
}
 
enum  StateEnum { STATE_WAITING, STATE_SUCCEEDED, STATE_FAILED }
 
enum  IPAddressFormatError { IPAddressFormatError::INVALID_IP, IPAddressFormatError::UNSUPPORTED_ADDR_FAMILY }
 
enum  CIDRNetworkError {
  CIDRNetworkError::INVALID_DEFAULT_CIDR, CIDRNetworkError::INVALID_IP_SLASH_CIDR, CIDRNetworkError::INVALID_IP, CIDRNetworkError::INVALID_CIDR,
  CIDRNetworkError::CIDR_MISMATCH
}
 
enum  ordering : int { ordering::lt = -1, ordering::eq = 0, ordering::gt = 1 }
 
enum  LogLevel : uint32_t {
  LogLevel::UNINITIALIZED = 0, LogLevel::NONE = 1, LogLevel::MIN_LEVEL = 1, LogLevel::DBG = 1000,
  LogLevel::DBG0 = 1999, LogLevel::DBG1 = 1998, LogLevel::DBG2 = 1997, LogLevel::DBG3 = 1996,
  LogLevel::DBG4 = 1995, LogLevel::DBG5 = 1994, LogLevel::DBG6 = 1993, LogLevel::DBG7 = 1992,
  LogLevel::DBG8 = 1991, LogLevel::DBG9 = 1990, LogLevel::INFO = 2000, LogLevel::INFO0 = 2999,
  LogLevel::INFO1 = 2998, LogLevel::INFO2 = 2997, LogLevel::INFO3 = 2996, LogLevel::INFO4 = 2995,
  LogLevel::INFO5 = 2994, LogLevel::INFO6 = 2993, LogLevel::INFO7 = 2992, LogLevel::INFO8 = 2991,
  LogLevel::INFO9 = 2990, LogLevel::WARN = 3000, LogLevel::WARNING = 3000, LogLevel::ERR = 4000,
  LogLevel::CRITICAL = 5000, LogLevel::DFATAL = 0x7ffffffe, LogLevel::FATAL = 0x7fffffff, LogLevel::MAX_LEVEL = 0x7fffffff
}
 
enum  UriEscapeMode : unsigned char { UriEscapeMode::ALL = 0, UriEscapeMode::QUERY = 1, UriEscapeMode::PATH = 2 }
 
enum  PrettyType {
  PRETTY_TIME, PRETTY_TIME_HMS, PRETTY_BYTES_METRIC, PRETTY_BYTES_BINARY,
  PRETTY_BYTES = PRETTY_BYTES_BINARY, PRETTY_BYTES_BINARY_IEC, PRETTY_BYTES_IEC = PRETTY_BYTES_BINARY_IEC, PRETTY_UNITS_METRIC,
  PRETTY_UNITS_BINARY, PRETTY_UNITS_BINARY_IEC, PRETTY_SI, PRETTY_NUM_TYPES
}
 
enum  AMBFlags { AMBFlags::NORMAL, AMBFlags::EXPEDITED }
 
enum  UnparkControl { UnparkControl::RetainContinue, UnparkControl::RemoveContinue, UnparkControl::RetainBreak, UnparkControl::RemoveBreak }
 
enum  ParkResult { ParkResult::Skip, ParkResult::Unpark, ParkResult::Timeout }
 
enum  annotate_rwlock_level : long { annotate_rwlock_level::rdlock = 0, annotate_rwlock_level::wrlock = 1 }
 
enum  E { E::E1, E::E2 }
 
enum  DecodeVarintError { DecodeVarintError::TooManyBytes = 0, DecodeVarintError::TooFewBytes = 1 }
 

Functions

vector< detail::BenchmarkRegistration > & benchmarks ()
 
 BENCHMARK (fbFollyGlobalBenchmarkBaseline)
 
size_t getGlobalBenchmarkBaselineIndex ()
 
static double estimateTime (double *begin, double *end)
 
static double runBenchmarkGetNSPerIteration (const BenchmarkFun &fun, const double globalBaseline)
 
static string humanReadable (double n, unsigned int decimals, const ScaleInfo *scales)
 
static string readableTime (double n, unsigned int decimals)
 
static string metricReadable (double n, unsigned int decimals)
 
static void printBenchmarkResultsAsJson (const vector< detail::BenchmarkResult > &data)
 
static void printBenchmarkResultsAsVerboseJson (const vector< detail::BenchmarkResult > &data)
 
static void printBenchmarkResults (const vector< detail::BenchmarkResult > &data)
 
void benchmarkResultsToDynamic (const vector< detail::BenchmarkResult > &data, dynamic &out)
 
void benchmarkResultsFromDynamic (const dynamic &d, vector< detail::BenchmarkResult > &results)
 
static pair< StringPiece, StringPieceresultKey (const detail::BenchmarkResult &result)
 
void printResultComparison (const vector< detail::BenchmarkResult > &base, const vector< detail::BenchmarkResult > &test)
 
void checkRunMode ()
 
void runBenchmarks ()
 
bool runBenchmarksOnFlag ()
 
template<typename Lambda >
std::enable_if< boost::function_types::function_arity< decltype(&Lambda::operator())>::value==2 >::type addBenchmark (const char *file, const char *name, Lambda &&lambda)
 
template<typename Lambda >
std::enable_if< boost::function_types::function_arity< decltype(&Lambda::operator())>::value==1 >::type addBenchmark (const char *file, const char *name, Lambda &&lambda)
 
template<typename T >
auto doNotOptimizeAway (const T &datum) -> typename std::enable_if< !detail::DoNotOptimizeAwayNeedsIndirect< T >::value >::type
 
template<typename T >
auto makeUnpredictable (T &datum) -> typename std::enable_if< !detail::DoNotOptimizeAwayNeedsIndirect< T >::value >::type
 
template<typename Tgt >
std::enable_if< detail::is_duration< Tgt >::value, Expected< Tgt, ConversionCode > >::type tryTo (const struct timespec &ts)
 
template<typename Tgt >
std::enable_if< detail::is_duration< Tgt >::value, Expected< Tgt, ConversionCode > >::type tryTo (const struct timeval &tv)
 
template<typename Tgt , typename Src >
std::enable_if< detail::is_time_point< Tgt >::value &&detail::is_posix_time_type< Src >::value, Expected< Tgt, ConversionCode > >::type tryTo (const Src &value)
 
template<typename Tgt , typename Rep , typename Period >
std::enable_if< std::is_same< Tgt, struct timespec >::value, Expected< Tgt, ConversionCode > >::type tryTo (const std::chrono::duration< Rep, Period > &duration)
 
template<typename Tgt , typename Rep , typename Period >
std::enable_if< std::is_same< Tgt, struct timeval >::value, Expected< Tgt, ConversionCode > >::type tryTo (const std::chrono::duration< Rep, Period > &duration)
 
template<typename Tgt , typename Clock , typename Duration >
std::enable_if< detail::is_posix_time_type< Tgt >::value, Expected< Tgt, ConversionCode > >::type tryTo (const std::chrono::time_point< Clock, Duration > &timePoint)
 
template<typename Tgt , typename Src >
std::enable_if< detail::is_chrono_conversion< Tgt, Src >::value, Tgt >::type to (const Src &value)
 
FOLLY_ATTR_WEAK folly::Function< void(double)> makeCompressionCounterHandler (folly::io::CodecType, folly::StringPiece, folly::Optional< int >, CompressionCounterKey, CompressionCounterType)
 
static CacheLocality getSystemLocalityInfo ()
 Returns the best real CacheLocality information available. More...
 
template<>
const CacheLocalityCacheLocality::system< std::atomic > ()
 
static size_t parseLeadingNumber (const std::string &line)
 
template<typename T , size_t Stripes>
CxxAllocatorAdaptor< T, typename CoreRawAllocator< Stripes >::Allocator > getCoreAllocator (size_t stripe)
 
template<typename T >
constexpr T constexpr_max (T a)
 
template<typename T , typename... Ts>
constexpr T constexpr_max (T a, T b, Ts...ts)
 
template<typename T >
constexpr T constexpr_min (T a)
 
template<typename T , typename... Ts>
constexpr T constexpr_min (T a, T b, Ts...ts)
 
template<typename T , typename Less >
constexpr T const & constexpr_clamp (T const &v, T const &lo, T const &hi, Less less)
 
template<typename T >
constexpr T const & constexpr_clamp (T const &v, T const &lo, T const &hi)
 
template<typename T >
constexpr auto constexpr_abs (T t) -> decltype(detail::constexpr_abs_helper< T >::go(t))
 
template<typename T >
constexpr T constexpr_log2 (T t)
 
template<typename T >
constexpr T constexpr_log2_ceil (T t)
 
template<typename T >
constexpr T constexpr_ceil (T t, T round)
 
template<typename T >
constexpr T constexpr_pow (T base, std::size_t exp)
 
template<typename T >
constexpr std::size_t constexpr_find_last_set (T const t)
 
template<typename T >
constexpr std::size_t constexpr_find_first_set (T t)
 
template<typename T >
constexpr T constexpr_add_overflow_clamped (T a, T b)
 
template<typename T >
constexpr T constexpr_sub_overflow_clamped (T a, T b)
 
template<typename Dst , typename Src >
constexpr std::enable_if< std::is_integral< Src >::value, Dst >::type constexpr_clamp_cast (Src src)
 
template<typename Dst , typename Src >
constexpr std::enable_if< std::is_floating_point< Src >::value, Dst >::type constexpr_clamp_cast (Src src)
 
template<typename C >
constexpr auto size (C const &c) -> decltype(c.size())
 
template<typename T , std::size_t N>
constexpr std::size_t size (T const (&)[N]) noexcept
 
template<typename C >
constexpr auto empty (C const &c) -> decltype(c.empty())
 
template<typename T , std::size_t N>
constexpr bool empty (T const (&)[N]) noexcept
 
template<typename E >
constexpr bool empty (std::initializer_list< E > il) noexcept
 
template<typename C >
constexpr auto data (C &c) -> decltype(c.data())
 
template<typename C >
constexpr auto data (C const &c) -> decltype(c.data())
 
template<typename T , std::size_t N>
constexpr Tdata (T(&a)[N]) noexcept
 
template<typename E >
constexpr E const * data (std::initializer_list< E > il) noexcept
 
template<typename D = void, typename... TList>
constexpr array_detail::return_type< D, TList... > make_array (TList &&...t)
 
template<std::size_t Size, typename MakeItem >
constexpr auto make_array_with (MakeItem const &make)
 
template<class BaseIter >
BitIterator< BaseIter > findFirstSet (BitIterator< BaseIter >, BitIterator< BaseIter >)
 
template<class BaseIter >
BitIterator< BaseIter > makeBitIterator (const BaseIter &iter)
 
template<class Range >
detail::RangeEnumerator< Rangeenumerate (Range &&r)
 
template<typename Sequence , typename Func >
FOLLY_CPP14_CONSTEXPR Func for_each (Sequence &&sequence, Func func)
 
template<typename Sequence , typename Index >
decltype(auto) FOLLY_CPP14_CONSTEXPR fetch (Sequence &&sequence, Index &&index)
 
template<typename Range , typename Func >
FOLLY_CPP14_CONSTEXPR Func for_each (Range &&range, Func func)
 
template<typename... Args>
emplace_args< Args... > make_emplace_args (Args &&...args) noexcept(noexcept(emplace_args< Args... >(std::forward< Args >(args)...)))
 
template<size_t I, typename... Args>
decltype(auto) get_emplace_arg (emplace_args< Args... > &&args) noexcept
 
template<size_t I, typename... Args>
decltype(auto) get_emplace_arg (emplace_args< Args... > &args) noexcept
 
template<size_t I, typename... Args>
decltype(auto) get_emplace_arg (const emplace_args< Args... > &args) noexcept
 
template<size_t I, typename Args >
decltype(auto) get_emplace_arg (Args &&args) noexcept
 
template<size_t I, typename Args >
decltype(auto) get_emplace_arg (Args &args) noexcept
 
template<size_t I, typename Args >
decltype(auto) get_emplace_arg (const Args &args) noexcept
 
template<bool implicit_unpack = true, typename Container >
emplace_iterator< Container, implicit_unpack > emplacer (Container &c, typename Container::iterator i)
 
template<bool implicit_unpack = true, typename Container >
hint_emplace_iterator< Container, implicit_unpack > hint_emplacer (Container &c, typename Container::iterator i)
 
template<bool implicit_unpack = true, typename Container >
front_emplace_iterator< Container, implicit_unpack > front_emplacer (Container &c)
 
template<bool implicit_unpack = true, typename Container >
back_emplace_iterator< Container, implicit_unpack > back_emplacer (Container &c)
 
template<class InputIt1 , class InputIt2 , class OutputIt , class Compare >
OutputIt merge (InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first, Compare comp)
 
template<class InputIt1 , class InputIt2 , class OutputIt >
OutputIt merge (InputIt1 first1, InputIt1 last1, InputIt2 first2, InputIt2 last2, OutputIt d_first)
 
ConversionError makeConversionError (ConversionCode code, StringPiece input)
 
template<class Tgt , class Src >
std::enable_if< std::is_same< Tgt, typename std::decay< Src >::type >::value, Expected< Tgt, ConversionCode > >::type tryTo (Src &&value)
 
template<class Tgt , class Src >
std::enable_if< std::is_same< Tgt, typename std::decay< Src >::type >::value, Tgt >::type to (Src &&value)
 
template<class Tgt , class Src >
std::enable_if< std::is_arithmetic< Src >::value &&!std::is_same< Tgt, Src >::value &&std::is_same< Tgt, bool >::value, Expected< Tgt, ConversionCode > >::type tryTo (const Src &value)
 
template<class Tgt , class Src >
std::enable_if< std::is_arithmetic< Src >::value &&!std::is_same< Tgt, Src >::value &&std::is_same< Tgt, bool >::value, Tgt >::type to (const Src &value)
 
uint32_t digits10 (uint64_t v)
 
uint32_t uint64ToBufferUnsafe (uint64_t v, char *const buffer)
 
template<class Tgt >
void toAppend (char value, Tgt *result)
 
template<class T >
constexpr std::enable_if< std::is_same< T, char >::value, size_t >::type estimateSpaceNeeded (T)
 
template<size_t N>
constexpr size_t estimateSpaceNeeded (const char(&)[N])
 
template<class Tgt , class Src >
std::enable_if< std::is_convertible< Src, const char * >::value &&IsSomeString< Tgt >::value >::type toAppend (Src value, Tgt *result)
 
template<class Src >
std::enable_if< std::is_convertible< Src, const char * >::value, size_t >::type estimateSpaceNeeded (Src value)
 
template<class Src >
std::enable_if< IsSomeString< Src >::value, size_t >::type estimateSpaceNeeded (Src const &value)
 
template<class Src >
std::enable_if< std::is_convertible< Src, folly::StringPiece >::value &&!IsSomeString< Src >::value &&!std::is_convertible< Src, const char * >::value, size_t >::type estimateSpaceNeeded (Src value)
 
template<>
size_t estimateSpaceNeeded (std::nullptr_t)
 
template<class Src >
std::enable_if< std::is_pointer< Src >::value &&IsSomeString< std::remove_pointer< Src > >::value, size_t >::type estimateSpaceNeeded (Src value)
 
template<class Tgt , class Src >
std::enable_if< IsSomeString< Src >::value &&IsSomeString< Tgt >::value >::type toAppend (const Src &value, Tgt *result)
 
template<class Tgt >
std::enable_if< IsSomeString< Tgt >::value >::type toAppend (StringPiece value, Tgt *result)
 
template<class Tgt >
std::enable_if< IsSomeString< Tgt >::value >::type toAppend (const fbstring &value, Tgt *result)
 
template<class Tgt , class Src >
size_t::type estimateSpaceNeeded (Src value)
 
template<class Delimiter , class... Ts>
void reserveInTargetDelim (const Delimiter &d, const Ts &...vs)
 
template<class T , class Tgt >
std::enable_if< IsSomeString< typename std::remove_pointer< Tgt >::type >::value >::type toAppendStrImpl (const T &v, Tgt result)
 
folly::std enable_if::typetoAppendDelimStrImpl const Delimiter, const Tv, Tgtresult sizeof (Ts) >
 
folly::std enable_if::typetoAppendDelimStrImpl const Delimiter, const Tv, Tgtresult bool Tgt::type to (const char *b, const char *e)
 
template<typename Tgt >
FOLLY_NODISCARD std::enable_if< std::is_arithmetic< Tgt >::value, Expected< StringPiece, ConversionCode > >::type parseTo (StringPiece src, Tgt &out)
 
template<typename Tgt , typename Src >
std::enable_if< detail::IsArithToArith< Tgt, Src >::value, Expected< Tgt, ConversionCode > >::type tryTo (const Src &value) noexcept
 
template<typename Tgt , typename Src >
std::enable_if< detail::IsArithToArith< Tgt, Src >::value, Tgt >::type to (const Src &value)
 
template<class T >
FOLLY_NODISCARD std::enable_if< std::is_enum< T >::value, Expected< StringPiece, ConversionCode > >::type parseTo (StringPiece in, T &out) noexcept
 
FOLLY_NODISCARD Expected< StringPiece, ConversionCodeparseTo (StringPiece in, StringPiece &out) noexcept
 
FOLLY_NODISCARD Expected< StringPiece, ConversionCodeparseTo (StringPiece in, std::string &out)
 
FOLLY_NODISCARD Expected< StringPiece, ConversionCodeparseTo (StringPiece in, fbstring &out)
 
template<class Tgt >
std::enable_if< !std::is_same< StringPiece, Tgt >::value, Expected< Tgt, detail::ParseToError< Tgt > > >::type tryTo (StringPiece src)
 
template<class Tgt , class Src >
std::enable_if< IsSomeString< Src >::value &&!std::is_same< StringPiece, Tgt >::value, Tgt >::type to (Src const &src)
 
template<class Tgt >
std::enable_if<!std::is_same< StringPiece, Tgt >::value, Tgt >::type to (StringPiece src)
 
template<class Tgt >
Expected< Tgt, detail::ParseToError< Tgt > > tryTo (StringPiece *src)
 
template<class Tgt >
Tgt to (StringPiece *src)
 
template<class Tgt , class Src >
std::enable_if< std::is_enum< Src >::value &&!std::is_same< Src, Tgt >::value &&!std::is_convertible< Tgt, StringPiece >::value, Expected< Tgt, ConversionCode > >::type tryTo (const Src &value)
 
template<class Tgt , class Src >
std::enable_if< !std::is_convertible< Src, StringPiece >::value &&std::is_enum< Tgt >::value &&!std::is_same< Src, Tgt >::value, Expected< Tgt, ConversionCode > >::type tryTo (const Src &value)
 
template<class Tgt , class Src >
std::enable_if< std::is_enum< Src >::value &&!std::is_same< Src, Tgt >::value &&!std::is_convertible< Tgt, StringPiece >::value, Tgt >::type to (const Src &value)
 
template<class Tgt , class Src >
std::enable_if< !std::is_convertible< Src, StringPiece >::value &&std::is_enum< Tgt >::value &&!std::is_same< Src, Tgt >::value, Tgt >::type to (const Src &value)
 
fbstring demangle (const char *name)
 
size_t demangle (const char *name, char *out, size_t outSize)
 
size_t strlcpy (char *dest, const char *const src, size_t size)
 
fbstring demangle (const std::type_info &type)
 
size_t demangle (const std::type_info &type, char *buf, size_t bufSize)
 
template<class T , class I >
detail::AddCvrefOf< T, I > & poly_cast (detail::PolyRoot< I > &)
 
template<class T , class I >
detail::AddCvrefOf< T, I > const & poly_cast (detail::PolyRoot< I > const &)
 
template<typename Visitor , typename... Args>
decltype(auto) apply_visitor (Visitor &&visitor, const DiscriminatedPtr< Args... > &variant)
 
template<typename Visitor , typename... Args>
decltype(auto) apply_visitor (Visitor &&visitor, DiscriminatedPtr< Args... > &variant)
 
template<typename Visitor , typename... Args>
decltype(auto) apply_visitor (Visitor &&visitor, DiscriminatedPtr< Args... > &&variant)
 
std::ostream & operator<< (std::ostream &out, dynamic const &d)
 
template<typename T >
T convertTo (const dynamic &)
 
template<typename T >
dynamic toDynamic (const T &)
 
std::system_error makeSystemErrorExplicit (int err, const char *msg)
 
template<class... Args>
std::system_error makeSystemErrorExplicit (int err, Args &&...args)
 
std::system_error makeSystemError (const char *msg)
 
template<class... Args>
std::system_error makeSystemError (Args &&...args)
 
void throwSystemErrorExplicit (int err, const char *msg)
 
template<class... Args>
void throwSystemErrorExplicit (int err, Args &&...args)
 
template<class... Args>
void throwSystemError (Args &&...args)
 
template<class... Args>
void checkPosixError (int err, Args &&...args)
 
template<class... Args>
void checkKernelError (ssize_t ret, Args &&...args)
 
template<class... Args>
void checkUnixError (ssize_t ret, Args &&...args)
 
template<class... Args>
void checkUnixErrorExplicit (ssize_t ret, int savedErrno, Args &&...args)
 
template<class... Args>
void checkFopenError (FILE *fp, Args &&...args)
 
template<class... Args>
void checkFopenErrorExplicit (FILE *fp, int savedErrno, Args &&...args)
 
fbstring exceptionStr (const std::exception &e)
 
template<typename E >
auto exceptionStr (const E &e) -> typename std::enable_if<!std::is_base_of< std::exception, E >::value, fbstring >::type
 
fbstring exceptionStr (exception_wrapper const &ew)
 
template<class Ex , typename... As>
exception_wrapper make_exception_wrapper (As &&...as)
 
template<class Ch >
std::basic_ostream< Ch > & operator<< (std::basic_ostream< Ch > &sout, exception_wrapper const &ew)
 
void swap (exception_wrapper &a, exception_wrapper &b) noexcept
 
template<typename... Exceptions, typename F >
exception_wrapper try_and_catch (F &&fn)
 
template<typename ExecutorT >
Executor::KeepAlive< ExecutorT > getKeepAliveToken (ExecutorT *executor)
 
template<typename ExecutorT >
Executor::KeepAlive< ExecutorT > getKeepAliveToken (ExecutorT &executor)
 
template<class F >
auto async (F &&fn)
 
std::shared_ptr< ExecutorgetCPUExecutor ()
 
void setCPUExecutor (std::weak_ptr< Executor > executor)
 
std::shared_ptr< IOExecutorgetIOExecutor ()
 
void setIOExecutor (std::weak_ptr< IOExecutor > executor)
 
EventBasegetEventBase ()
 
bool isSequencedExecutor (folly::Executor &executor)
 
void testExecutor (folly::Executor &executor)
 
void testExecutor (folly::SequencedExecutor &executor)
 
 TEST (SequencedExecutor, CPUThreadPoolExecutor)
 
 TEST (SequencedExecutor, SerialCPUThreadPoolExecutor)
 
 TEST (SequencedExecutor, EventBase)
 
template<typename F >
static auto with_unique_lock (std::mutex &m, F &&f) -> decltype(f())
 
SyncVecThreadPoolExecutorsgetSyncVecThreadPoolExecutors ()
 
 DEFINE_int64 (threadtimeout_ms, 60000,"Idle time before ThreadPoolExecutor threads are joined")
 
template<class Error >
constexpr Unexpected< typename std::decay< Error >::typemakeUnexpected (Error &&)
 
template<class Error , class Value >
constexpr Expected< typename std::decay< Value >::type, Error > makeExpected (Value &&)
 
expected_detail::UnexpectedTag unexpected (expected_detail::UnexpectedTag={})
 
template<class Error , bool FB_CONCATENATE = false, typename std::enable_if< (FB_CONCATENATE(FB_CONCATENATE(Folly, Requires), __LINE__)||static_cast< bool >(IsEqualityComparable< Error >::value)), int >::type = 0>
bool operator== (const Unexpected< Error > &lhs, const Unexpected< Error > &rhs)
 
template<class Error , bool FB_CONCATENATE = false, typename std::enable_if< (FB_CONCATENATE(FB_CONCATENATE(Folly, Requires), __LINE__)||static_cast< bool >(IsEqualityComparable< Error >::value)), int >::type = 0>
bool operator!= (const Unexpected< Error > &lhs, const Unexpected< Error > &rhs)
 
template<class Value , class Error >
std::enable_if< IsEqualityComparable< Value >::value, bool >::type operator== (const Expected< Value, Error > &lhs, const Expected< Value, Error > &rhs)
 
template<class Value , class Error , bool FB_CONCATENATE = false, typename std::enable_if< (FB_CONCATENATE(FB_CONCATENATE(Folly, Requires), __LINE__)||static_cast< bool >(IsEqualityComparable< Value >::value)), int >::type = 0>
bool operator!= (const Expected< Value, Error > &lhs, const Expected< Value, Error > &rhs)
 
template<class Value , class Error >
std::enable_if< IsLessThanComparable< Value >::value, bool >::type operator< (const Expected< Value, Error > &lhs, const Expected< Value, Error > &rhs)
 
template<class Value , class Error , bool FB_CONCATENATE = false, typename std::enable_if< (FB_CONCATENATE(FB_CONCATENATE(Folly, Requires), __LINE__)||static_cast< bool >(IsLessThanComparable< Value >::value)), int >::type = 0>
bool operator<= (const Expected< Value, Error > &lhs, const Expected< Value, Error > &rhs)
 
template<class Value , class Error , bool FB_CONCATENATE = false, typename std::enable_if< (FB_CONCATENATE(FB_CONCATENATE(Folly, Requires), __LINE__)||static_cast< bool >(IsLessThanComparable< Value >::value)), int >::type = 0>
bool operator> (const Expected< Value, Error > &lhs, const Expected< Value, Error > &rhs)
 
template<class Value , class Error , bool FB_CONCATENATE = false, typename std::enable_if< (FB_CONCATENATE(FB_CONCATENATE(Folly, Requires), __LINE__)||static_cast< bool >(IsLessThanComparable< Value >::value)), int >::type = 0>
bool operator>= (const Expected< Value, Error > &lhs, const Expected< Value, Error > &rhs)
 
template<class Value , class Error >
void swap (Expected< Value, Error > &lhs, Expected< Value, Error > &rhs) noexcept(expected_detail::StrictAllOf< IsNothrowSwappable, Value, Error >::value)
 
template<class Value , class Error >
const Value * get_pointer (const Expected< Value, Error > &ex) noexcept
 
template<class Value , class Error >
Value * get_pointer (Expected< Value, Error > &ex) noexcept
 
template<class Value , class Error >
bool operator== (const Expected< Value, Error > &, const Value &other)=delete
 
template<class Value , class Error >
bool operator!= (const Expected< Value, Error > &, const Value &other)=delete
 
template<class Value , class Error >
bool operator< (const Expected< Value, Error > &, const Value &other)=delete
 
template<class Value , class Error >
bool operator<= (const Expected< Value, Error > &, const Value &other)=delete
 
template<class Value , class Error >
bool operator>= (const Expected< Value, Error > &, const Value &other)=delete
 
template<class Value , class Error >
bool operator> (const Expected< Value, Error > &, const Value &other)=delete
 
template<class Value , class Error >
bool operator== (const Value &other, const Expected< Value, Error > &)=delete
 
template<class Value , class Error >
bool operator!= (const Value &other, const Expected< Value, Error > &)=delete
 
template<class Value , class Error >
bool operator< (const Value &other, const Expected< Value, Error > &)=delete
 
template<class Value , class Error >
bool operator<= (const Value &other, const Expected< Value, Error > &)=delete
 
template<class Value , class Error >
bool operator>= (const Value &other, const Expected< Value, Error > &)=delete
 
template<class Value , class Error >
bool operator> (const Value &other, const Expected< Value, Error > &)=delete
 
template<class Logger = GoogleLogger<GoogleLoggerStyle::PRETTY>, class Clock = std::chrono::high_resolution_clock>
auto makeAutoTimer (std::string &&msg="", const std::chrono::duration< double > &minTimeToLog=std::chrono::duration< double >::zero(), Logger &&logger=Logger())
 
std::ostream & operator<< (std::ostream &os, const AsyncIOOp &op)
 
std::ostream & operator<< (std::ostream &os, AsyncIOOp::State state)
 
const HugePageSizeVecgetHugePageSizes ()
 
const HugePageSizegetHugePageSize (size_t size)
 
const HugePageSizegetHugePageSizeForDevice (dev_t device)
 
bool operator< (const HugePageSize &a, const HugePageSize &b)
 
bool operator== (const HugePageSize &a, const HugePageSize &b)
 
JemallocNodumpAllocatorglobalJemallocNodumpAllocator ()
 
po::options_description getGFlags (ProgramOptionsStyle style)
 
NestedCommandLineParseResult parseNestedCommandLine (int argc, const char *const argv[], const po::options_description &desc)
 
NestedCommandLineParseResult parseNestedCommandLine (const std::vector< std::string > &cmdline, const po::options_description &desc)
 
NestedCommandLineParseResult parseNestedCommandLine (int argc, const char *const argv[], const boost::program_options::options_description &desc)
 
NestedCommandLineParseResult parseNestedCommandLine (const std::vector< std::string > &cmdline, const boost::program_options::options_description &desc)
 
template<typename T , typename RefCount >
bool operator== (const ReadMostlyMainPtr< T, RefCount > &ptr, std::nullptr_t)
 
template<typename T , typename RefCount >
bool operator== (std::nullptr_t, const ReadMostlyMainPtr< T, RefCount > &ptr)
 
template<typename T , typename RefCount >
bool operator== (const ReadMostlySharedPtr< T, RefCount > &ptr, std::nullptr_t)
 
template<typename T , typename RefCount >
bool operator== (std::nullptr_t, const ReadMostlySharedPtr< T, RefCount > &ptr)
 
template<typename T , typename RefCount >
bool operator!= (const ReadMostlyMainPtr< T, RefCount > &ptr, std::nullptr_t)
 
template<typename T , typename RefCount >
bool operator!= (std::nullptr_t, const ReadMostlyMainPtr< T, RefCount > &ptr)
 
template<typename T , typename RefCount >
bool operator!= (const ReadMostlySharedPtr< T, RefCount > &ptr, std::nullptr_t)
 
template<typename T , typename RefCount >
bool operator!= (std::nullptr_t, const ReadMostlySharedPtr< T, RefCount > &ptr)
 
template<class Instructions >
uint64_t select64 (uint64_t x, uint64_t k)
 
template<>
FOLLY_ALWAYS_INLINE uint64_t select64< compression::instructions::Haswell > (uint64_t x, uint64_t k)
 
template<typename T >
StampedPtr< TmakeStampedPtr (T *ptr, uint16_t stamp)
 
template<class Alloc >
StringPiece stringPieceDup (StringPiece piece, const Alloc &alloc)
 
template<class Alloc >
void stringPieceDel (StringPiece piece, const Alloc &alloc)
 
 TEST (LockFreeRingBuffer, writeReadSequentially)
 
 TEST (LockFreeRingBuffer, writeReadSequentiallyBackward)
 
 TEST (LockFreeRingBuffer, readsCanBlock)
 
template<typename T , template< typename > class Atom>
uint64_t value (const typename LockFreeRingBuffer< T, Atom >::Cursor &rbcursor)
 
template<template< typename > class Atom>
void runReader (LockFreeRingBuffer< int, Atom > &rb, std::atomic< int32_t > &writes)
 
template<template< typename > class Atom>
void runWritesNeverFail (int capacity, int writes, int writers)
 
 TEST (LockFreeRingBuffer, writesNeverFail)
 
 TEST (LockFreeRingBuffer, readerCanDetectSkips)
 
 TEST (LockFreeRingBuffer, currentTailRange)
 
 TEST (LockFreeRingBuffer, cursorFromWrites)
 
 TEST (LockFreeRingBuffer, moveBackwardsCanFail)
 
template<typename Counter >
void shutdown (Counter &)
 
void shutdown (TLRefCount &c)
 
template<typename Counter , size_t threadCount>
void benchmark (size_t n)
 
 BENCHMARK (TLRefCountOneThread, n)
 
 BENCHMARK (TLRefCountFourThreads, n)
 
template<typename RefCount >
void basicTest ()
 
template<typename RefCount >
void stressTest (size_t itersCount)
 
 TEST (TLRefCount, Basic)
 
 TEST (TLRefCount, Stress)
 
template<std::size_t start = 0, std::size_t n = std::numeric_limits<std::size_t>::max(), class T , class Seq = typename TemplateTupleRange<T, start, n>::type>
auto tupleRange (T &&v) -> decltype(detail::TupleSelect< Seq >::select(std::forward< T >(v)))
 
template<class T , class U >
auto tuplePrepend (T &&car, U &&cdr) -> decltype(std::tuple_cat(std::make_tuple(std::forward< T >(car)), std::forward< U >(cdr)))
 
template<typename E , class T , class A , class S >
basic_fbstring< E, T, A, Soperator+ (const basic_fbstring< E, T, A, S > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
basic_fbstring< E, T, A, Soperator+ (basic_fbstring< E, T, A, S > &&lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
basic_fbstring< E, T, A, Soperator+ (const basic_fbstring< E, T, A, S > &lhs, basic_fbstring< E, T, A, S > &&rhs)
 
template<typename E , class T , class A , class S >
basic_fbstring< E, T, A, Soperator+ (basic_fbstring< E, T, A, S > &&lhs, basic_fbstring< E, T, A, S > &&rhs)
 
template<typename E , class T , class A , class S >
basic_fbstring< E, T, A, Soperator+ (const E *lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
basic_fbstring< E, T, A, Soperator+ (const E *lhs, basic_fbstring< E, T, A, S > &&rhs)
 
template<typename E , class T , class A , class S >
basic_fbstring< E, T, A, Soperator+ (E lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
basic_fbstring< E, T, A, Soperator+ (E lhs, basic_fbstring< E, T, A, S > &&rhs)
 
template<typename E , class T , class A , class S >
basic_fbstring< E, T, A, Soperator+ (const basic_fbstring< E, T, A, S > &lhs, const E *rhs)
 
template<typename E , class T , class A , class S >
basic_fbstring< E, T, A, Soperator+ (basic_fbstring< E, T, A, S > &&lhs, const E *rhs)
 
template<typename E , class T , class A , class S >
basic_fbstring< E, T, A, Soperator+ (const basic_fbstring< E, T, A, S > &lhs, E rhs)
 
template<typename E , class T , class A , class S >
basic_fbstring< E, T, A, Soperator+ (basic_fbstring< E, T, A, S > &&lhs, E rhs)
 
template<typename E , class T , class A , class S >
bool operator== (const basic_fbstring< E, T, A, S > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
bool operator== (const typename basic_fbstring< E, T, A, S >::value_type *lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
bool operator== (const basic_fbstring< E, T, A, S > &lhs, const typename basic_fbstring< E, T, A, S >::value_type *rhs)
 
template<typename E , class T , class A , class S >
bool operator!= (const basic_fbstring< E, T, A, S > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
bool operator!= (const typename basic_fbstring< E, T, A, S >::value_type *lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
bool operator!= (const basic_fbstring< E, T, A, S > &lhs, const typename basic_fbstring< E, T, A, S >::value_type *rhs)
 
template<typename E , class T , class A , class S >
bool operator< (const basic_fbstring< E, T, A, S > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
bool operator< (const basic_fbstring< E, T, A, S > &lhs, const typename basic_fbstring< E, T, A, S >::value_type *rhs)
 
template<typename E , class T , class A , class S >
bool operator< (const typename basic_fbstring< E, T, A, S >::value_type *lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
bool operator> (const basic_fbstring< E, T, A, S > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
bool operator> (const basic_fbstring< E, T, A, S > &lhs, const typename basic_fbstring< E, T, A, S >::value_type *rhs)
 
template<typename E , class T , class A , class S >
bool operator> (const typename basic_fbstring< E, T, A, S >::value_type *lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
bool operator<= (const basic_fbstring< E, T, A, S > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
bool operator<= (const basic_fbstring< E, T, A, S > &lhs, const typename basic_fbstring< E, T, A, S >::value_type *rhs)
 
template<typename E , class T , class A , class S >
bool operator<= (const typename basic_fbstring< E, T, A, S >::value_type *lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
bool operator>= (const basic_fbstring< E, T, A, S > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
bool operator>= (const basic_fbstring< E, T, A, S > &lhs, const typename basic_fbstring< E, T, A, S >::value_type *rhs)
 
template<typename E , class T , class A , class S >
bool operator>= (const typename basic_fbstring< E, T, A, S >::value_type *lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
void swap (basic_fbstring< E, T, A, S > &lhs, basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S >
std::basic_istream< typename basic_fbstring< E, T, A, S >::value_type, typename basic_fbstring< E, T, A, S >::traits_type > & operator>> (std::basic_istream< typename basic_fbstring< E, T, A, S >::value_type, typename basic_fbstring< E, T, A, S >::traits_type > &is, basic_fbstring< E, T, A, S > &str)
 
template<typename E , class T , class A , class S >
std::basic_ostream< typename basic_fbstring< E, T, A, S >::value_type, typename basic_fbstring< E, T, A, S >::traits_type > & operator<< (std::basic_ostream< typename basic_fbstring< E, T, A, S >::value_type, typename basic_fbstring< E, T, A, S >::traits_type > &os, const basic_fbstring< E, T, A, S > &str)
 
template<typename E , class T , class A , class S , class A2 >
bool operator== (const basic_fbstring< E, T, A, S > &lhs, const std::basic_string< E, T, A2 > &rhs)
 
template<typename E , class T , class A , class S , class A2 >
bool operator== (const std::basic_string< E, T, A2 > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S , class A2 >
bool operator!= (const basic_fbstring< E, T, A, S > &lhs, const std::basic_string< E, T, A2 > &rhs)
 
template<typename E , class T , class A , class S , class A2 >
bool operator!= (const std::basic_string< E, T, A2 > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S , class A2 >
bool operator< (const basic_fbstring< E, T, A, S > &lhs, const std::basic_string< E, T, A2 > &rhs)
 
template<typename E , class T , class A , class S , class A2 >
bool operator> (const basic_fbstring< E, T, A, S > &lhs, const std::basic_string< E, T, A2 > &rhs)
 
template<typename E , class T , class A , class S , class A2 >
bool operator< (const std::basic_string< E, T, A2 > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S , class A2 >
bool operator> (const std::basic_string< E, T, A2 > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S , class A2 >
bool operator<= (const basic_fbstring< E, T, A, S > &lhs, const std::basic_string< E, T, A2 > &rhs)
 
template<typename E , class T , class A , class S , class A2 >
bool operator>= (const basic_fbstring< E, T, A, S > &lhs, const std::basic_string< E, T, A2 > &rhs)
 
template<typename E , class T , class A , class S , class A2 >
bool operator<= (const std::basic_string< E, T, A2 > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<typename E , class T , class A , class S , class A2 >
bool operator>= (const std::basic_string< E, T, A2 > &lhs, const basic_fbstring< E, T, A, S > &rhs)
 
template<class T , class R , class A , class S >
 FOLLY_ASSUME_RELOCATABLE (basic_fbstring< T, R, A, S >)
 
template<class T , class A >
void swap (fbvector< T, A > &lhs, fbvector< T, A > &rhs) noexcept
 
template<class T , class A >
void compactResize (fbvector< T, A > *v, size_t sz)
 
template<class T , class A >
Trelinquish (fbvector< T, A > &v)
 
template<class T , class A >
void attach (fbvector< T, A > &v, T *data, size_t sz, size_t cap)
 
void swap (File &a, File &b) noexcept
 
int openNoInt (const char *name, int flags, mode_t mode)
 
static int filterCloseReturn (int r)
 
int closeNoInt (int fd)
 
int closeNoInt (NetworkSocket fd)
 
int fsyncNoInt (int fd)
 
int dupNoInt (int fd)
 
int dup2NoInt (int oldfd, int newfd)
 
int fdatasyncNoInt (int fd)
 
int ftruncateNoInt (int fd, off_t len)
 
int truncateNoInt (const char *path, off_t len)
 
int flockNoInt (int fd, int operation)
 
int shutdownNoInt (NetworkSocket fd, int how)
 
ssize_t readNoInt (int fd, void *buf, size_t count)
 
ssize_t preadNoInt (int fd, void *buf, size_t count, off_t offset)
 
ssize_t readvNoInt (int fd, const iovec *iov, int count)
 
ssize_t writeNoInt (int fd, const void *buf, size_t count)
 
ssize_t pwriteNoInt (int fd, const void *buf, size_t count, off_t offset)
 
ssize_t writevNoInt (int fd, const iovec *iov, int count)
 
ssize_t readFull (int fd, void *buf, size_t count)
 
ssize_t preadFull (int fd, void *buf, size_t count, off_t offset)
 
ssize_t writeFull (int fd, const void *buf, size_t count)
 
ssize_t pwriteFull (int fd, const void *buf, size_t count, off_t offset)
 
ssize_t readvFull (int fd, iovec *iov, int count)
 
ssize_t preadvFull (int fd, iovec *iov, int count, off_t offset)
 
ssize_t writevFull (int fd, iovec *iov, int count)
 
ssize_t pwritevFull (int fd, iovec *iov, int count, off_t offset)
 
int writeFileAtomicNoThrow (StringPiece filename, iovec *iov, int count, mode_t permissions)
 
void writeFileAtomic (StringPiece filename, iovec *iov, int count, mode_t permissions)
 
void writeFileAtomic (StringPiece filename, ByteRange data, mode_t permissions)
 
void writeFileAtomic (StringPiece filename, StringPiece data, mode_t permissions)
 
int shutdownNoInt (int fd, int how)
 
template<class Container >
bool readFile (int fd, Container &out, size_t num_bytes=std::numeric_limits< size_t >::max())
 
template<class Container >
bool readFile (const char *file_name, Container &out, size_t num_bytes=std::numeric_limits< size_t >::max())
 
template<class Container >
bool writeFile (const Container &data, const char *filename, int flags=O_WRONLY|O_CREAT|O_TRUNC, mode_t mode=0666)
 
uint64_t fingerprint64 (StringPiece str)
 
void fingerprint96 (StringPiece str, uint64_t *msb, uint32_t *lsb)
 
void fingerprint128 (StringPiece str, uint64_t *msb, uint64_t *lsb)
 
std::uint32_t hsieh_hash32_buf (const void *buf, std::size_t len)
 
template<class C , std::size_t N>
std::basic_ostream< C > & operator<< (std::basic_ostream< C > &os, const BasicFixedString< C, N > &string)
 
template<class Char , std::size_t A, std::size_t B>
constexpr bool operator== (const BasicFixedString< Char, A > &a, const BasicFixedString< Char, B > &b) noexcept
 
template<class Char , std::size_t A, std::size_t B>
constexpr bool operator!= (const BasicFixedString< Char, A > &a, const BasicFixedString< Char, B > &b)
 
template<class Char , std::size_t A, std::size_t B>
constexpr bool operator< (const BasicFixedString< Char, A > &a, const BasicFixedString< Char, B > &b) noexcept
 
template<class Char , std::size_t A, std::size_t B>
constexpr bool operator> (const BasicFixedString< Char, A > &a, const BasicFixedString< Char, B > &b) noexcept
 
template<class Char , std::size_t A, std::size_t B>
constexpr bool operator<= (const BasicFixedString< Char, A > &a, const BasicFixedString< Char, B > &b) noexcept
 
template<class Char , std::size_t A, std::size_t B>
constexpr bool operator>= (const BasicFixedString< Char, A > &a, const BasicFixedString< Char, B > &b) noexcept
 
template<class Char , std::size_t N, std::size_t M>
constexpr BasicFixedString< Char, N+Moperator+ (const BasicFixedString< Char, N > &a, const BasicFixedString< Char, M > &b) noexcept
 
template<class Char , std::size_t N>
constexpr BasicFixedString< Char, N-1u > makeFixedString (const Char(&a)[N]) noexcept
 
template<class Char , std::size_t N>
FOLLY_CPP14_CONSTEXPR void swap (BasicFixedString< Char, N > &a, BasicFixedString< Char, N > &b) noexcept
 
template<class Derived , bool containerMode, class... Args>
void writeTo (FILE *fp, const BaseFormatter< Derived, containerMode, Args... > &formatter)
 
template<class... Args>
Formatter< false, Args... > format (StringPiece fmt, Args &&...args)
 
template<class C >
Formatter< true, Cvformat (StringPiece fmt, C &&container)
 
template<bool containerMode, class... Args>
std::ostream & operator<< (std::ostream &out, const Formatter< containerMode, Args... > &formatter)
 
template<class... Args>
std::string sformat (StringPiece fmt, Args &&...args)
 
template<class Container >
Formatter< true, Container > vformat (StringPiece fmt, Container &&container)
 
template<class Container >
std::string svformat (StringPiece fmt, Container &&container)
 
template<class Container , class Value >
detail::DefaultValueWrapper< Container, Value > defaulted (const Container &c, const Value &v)
 
template<class Str , class... Args>
std::enable_if< IsSomeString< Str >::value >::type format (Str *out, StringPiece fmt, Args &&...args)
 
template<class Str , class Container >
std::enable_if< IsSomeString< Str >::value >::type vformat (Str *out, StringPiece fmt, Container &&container)
 
template<class... Args>
Formatter< false, Args... > formatChecked (StringPiece fmt, Args &&...args)
 
template<class... Args>
std::string sformatChecked (StringPiece fmt, Args &&...args)
 
template<class Container >
Formatter< true, Container > vformatChecked (StringPiece fmt, Container &&container)
 
template<class Container >
std::string svformatChecked (StringPiece fmt, Container &&container)
 
template<class Str , class... Args>
std::enable_if< IsSomeString< Str >::value >::type formatChecked (Str *out, StringPiece fmt, Args &&...args)
 
template<class Str , class Container >
std::enable_if< IsSomeString< Str >::value >::type vformatChecked (Str *out, StringPiece fmt, Container &&container)
 
template<typename ReturnType , typename... Args>
Function< ReturnType(Args...) const > constCastFunction (Function< ReturnType(Args...)> &&) noexcept
 
template<typename FunctionType >
void swap (Function< FunctionType > &lhs, Function< FunctionType > &rhs) noexcept
 
template<typename FunctionType >
bool operator== (const Function< FunctionType > &fn, std::nullptr_t)
 
template<typename FunctionType >
bool operator== (std::nullptr_t, const Function< FunctionType > &fn)
 
template<typename FunctionType >
bool operator!= (const Function< FunctionType > &fn, std::nullptr_t)
 
template<typename FunctionType >
bool operator!= (std::nullptr_t, const Function< FunctionType > &fn)
 
template<typename ReturnType , typename... Args>
Function< ReturnType(Args...) const > constCastFunction (Function< ReturnType(Args...) const > &&that) noexcept
 
template<typename F , typename Tuple >
decltype(auto) constexpr apply (F &&func, Tuple &&tuple)
 
template<typename Tuple >
auto forward_tuple (Tuple &&tuple) noexcept-> decltype(detail::apply_tuple::adl::forward_tuple(std::declval< Tuple >(), std::declval< index_sequence_for_tuple< std::remove_reference_t< Tuple >>>()))
 
template<class F >
auto uncurry (F &&f) -> detail::apply_tuple::Uncurry< typename std::decay< F >::type >
 
template<class T , class Tuple >
constexpr T make_from_tuple (Tuple &&t)
 
template<typename F , typename... Args>
constexpr auto invoke (F &&f, Args &&...args) noexcept(noexcept(static_cast< F && >(f)(static_cast< Args && >(args)...))) -> decltype(static_cast< F && >(f)(static_cast< Args && >(args)...))
 
template<typename M , typename C , typename... Args>
constexpr auto invoke (M(C::*d), Args &&...args) -> decltype(std::mem_fn(d)(static_cast< Args && >(args)...))
 
template<typename F , typename... Args>
auto partial (F &&f, Args &&...args) -> detail::partial::Partial< typename std::decay< F >::type, std::tuple< typename std::decay< Args >::type... >>
 
template<class T >
SemiFuture< typename std::decay< T >::typemakeSemiFuture (T &&t)
 
template<class F >
std::enable_if< isFutureOrSemiFuture< invoke_result_t< F > >::value, SemiFuture< typename invoke_result_t< F >::value_type > >::type makeSemiFutureWith (F &&func)
 
template<class F >
std::enable_if< !(isFutureOrSemiFuture< invoke_result_t< F >>::value), SemiFuture< lift_unit_t< invoke_result_t< F > > > >::type makeSemiFutureWith (F &&func)
 
template<class T >
SemiFuture< TmakeSemiFuture (std::exception_ptr const &e)
 
template<class T >
SemiFuture< TmakeSemiFuture (exception_wrapper ew)
 Make a failed SemiFuture from an exception_wrapper. More...
 
template<class T , class E >
std::enable_if< std::is_base_of< std::exception, E >::value, SemiFuture< T > >::type makeSemiFuture (E const &e)
 
template<class T >
SemiFuture< TmakeSemiFuture (Try< T > t)
 
SemiFuture< UnitmakeSemiFuture ()
 
template<class Func >
auto via (Executor *x, Func &&func) -> Future< typename isFutureOrSemiFuture< decltype(std::declval< Func >()())>::Inner >
 
template<class Func >
auto via (Executor::KeepAlive<> x, Func &&func) -> Future< typename isFutureOrSemiFuture< decltype(std::declval< Func >()())>::Inner >
 
template<class T >
Future< typename std::decay< T >::typemakeFuture (T &&t)
 
Future< UnitmakeFuture ()
 
template<class F >
std::enable_if< isFuture< invoke_result_t< F > >::value, invoke_result_t< F > >::type makeFutureWith (F &&func)
 
template<class F >
std::enable_if< !(isFuture< invoke_result_t< F >>::value), Future< lift_unit_t< invoke_result_t< F > > > >::type makeFutureWith (F &&func)
 
template<class T >
Future< TmakeFuture (std::exception_ptr const &e)
 
template<class T >
Future< TmakeFuture (exception_wrapper ew)
 
template<class T , class E >
std::enable_if< std::is_base_of< std::exception, E >::value, Future< T > >::type makeFuture (E const &e)
 
template<class T >
Future< TmakeFuture (Try< T > t)
 
Future< Unitvia (Executor *executor, int8_t priority)
 
Future< Unitvia (Executor::KeepAlive<> executor, int8_t priority)
 
template<typename... Fs>
SemiFuture< std::tuple< Try< typename remove_cvref_t< Fs >::value_type >... > > collectAllSemiFuture (Fs &&...fs)
 
template<typename... Fs>
Future< std::tuple< Try< typename remove_cvref_t< Fs >::value_type >... > > collectAll (Fs &&...fs)
 
template<class InputIterator >
SemiFuture< std::vector< Try< typename std::iterator_traits< InputIterator >::value_type::value_type > > > collectAllSemiFuture (InputIterator first, InputIterator last)
 
template<class InputIterator >
Future< std::vector< Try< typename std::iterator_traits< InputIterator >::value_type::value_type > > > collectAll (InputIterator first, InputIterator last)
 
template<class InputIterator >
Future< std::vector< typename std::iterator_traits< InputIterator >::value_type::value_type > > collect (InputIterator first, InputIterator last)
 
template<typename... Fs>
Future< std::tuple< typename remove_cvref_t< Fs >::value_type... > > collect (Fs &&...fs)
 
template<class InputIterator >
Future< std::pair< size_t, Try< typename std::iterator_traits< InputIterator >::value_type::value_type > > > collectAny (InputIterator first, InputIterator last)
 
template<class InputIterator >
SemiFuture< std::pair< size_t, typename std::iterator_traits< InputIterator >::value_type::value_type > > collectAnyWithoutException (InputIterator first, InputIterator last)
 
template<class InputIterator >
SemiFuture< std::vector< std::pair< size_t, Try< typename std::iterator_traits< InputIterator >::value_type::value_type > > > > collectN (InputIterator first, InputIterator last, size_t n)
 
template<class It , class T , class F >
Future< Treduce (It first, It last, T &&initial, F &&func)
 
template<class Collection , class F , class ItT , class Result >
std::vector< Future< Result > > window (Collection input, F func, size_t n)
 
template<class F >
auto window (size_t times, F func, size_t n) -> std::vector< invoke_result_t< F, size_t >>
 
template<class Collection , class F , class ItT , class Result >
std::vector< Future< Result > > window (Executor *executor, Collection input, F func, size_t n)
 
template<class Collection , class F , class ItT , class Result >
std::vector< Future< Result > > window (Executor::KeepAlive<> executor, Collection input, F func, size_t n)
 
template<class It , class T , class F >
Future< TunorderedReduce (It first, It last, T initial, F func)
 
template<class F >
Future< Unitwhen (bool p, F &&thunk)
 
template<class P , class F >
Future< UnitwhileDo (P &&predicate, F &&thunk)
 
template<class F >
Future< Unittimes (const int n, F &&thunk)
 
template<class T >
std::pair< Promise< T >, SemiFuture< T > > makePromiseContract ()
 
template<class T >
std::pair< Promise< T >, Future< T > > makePromiseContract (Executor *e)
 
template<class T >
FutureSplitter< TsplitFuture (Future< T > &&future)
 
template<class F >
std::enable_if< !(isFutureOrSemiFuture< invoke_result_t< F >>::value), SemiFuture< typename lift_unit< invoke_result_t< F > >::type > >::type makeSemiFutureWith (F &&func)
 
template<class F >
std::enable_if< !(isFuture< invoke_result_t< F >>::value), Future< typename lift_unit< invoke_result_t< F > >::type > >::type makeFutureWith (F &&func)
 
template<class Collection >
auto collectAllSemiFuture (Collection &&c) -> decltype(collectAllSemiFuture(c.begin(), c.end()))
 Sugar for the most common case. More...
 
template<class Collection >
auto collectAll (Collection &&c) -> decltype(collectAll(c.begin(), c.end()))
 
template<class Collection >
auto collect (Collection &&c) -> decltype(collect(c.begin(), c.end()))
 Sugar for the most common case. More...
 
template<class Collection >
auto collectAny (Collection &&c) -> decltype(collectAny(c.begin(), c.end()))
 Sugar for the most common case. More...
 
template<class Collection >
auto collectAnyWithoutException (Collection &&c) -> decltype(collectAnyWithoutException(c.begin(), c.end()))
 Sugar for the most common case. More...
 
template<class Collection >
auto collectN (Collection &&c, size_t n) -> decltype(collectN(c.begin(), c.end(), n))
 Sugar for the most common case. More...
 
template<class Collection , class T , class F >
auto reduce (Collection &&c, T &&initial, F &&func) -> decltype(reduce(c.begin(), c.end(), std::forward< T >(initial), std::forward< F >(func)))
 Sugar for the most common case. More...
 
template<class Collection , class T , class F >
auto unorderedReduce (Collection &&c, T &&initial, F &&func) -> decltype(unorderedReduce(c.begin(), c.end(), std::forward< T >(initial), std::forward< F >(func)))
 Sugar for the most common case. More...
 
template<class T >
Future< TsomeFuture ()
 
template<class Ret , class... Params>
std::enable_if< isFuture< Ret >::value, Ret >::type aFunction (Params...)
 
template<class Ret , class... Params>
std::enable_if<!isFuture< Ret >::value, Ret >::type aFunction (Params...)
 
template<class Ret , class... Params>
std::function< Ret(Params...)> aStdFunction (typename std::enable_if<!isFuture< Ret >::value, bool >::type=false)
 
template<class Ret , class... Params>
std::function< Ret(Params...)> aStdFunction (typename std::enable_if< isFuture< Ret >::value, bool >::type=true)
 
uint32_t crc32c (const uint8_t *data, size_t nbytes, uint32_t startingChecksum)
 
uint32_t crc32 (const uint8_t *data, size_t nbytes, uint32_t startingChecksum)
 
uint32_t crc32_type (const uint8_t *data, size_t nbytes, uint32_t startingChecksum)
 
uint32_t crc32_combine (uint32_t crc1, uint32_t crc2, size_t crc2len)
 
uint32_t crc32c_combine (uint32_t crc1, uint32_t crc2, size_t crc2len)
 
static constexpr uint32_t gf_multiply_sw_1 (size_t i, uint32_t p, uint32_t a, uint32_t b, uint32_t m)
 
static constexpr uint32_t gf_multiply_sw (uint32_t a, uint32_t b, uint32_t m)
 
static constexpr uint32_t gf_square_sw (uint32_t a, uint32_t m)
 
static uint32_t gf_multiply_crc32c_hw (uint64_t, uint64_t, uint32_t)
 
static uint32_t gf_multiply_crc32_hw (uint64_t, uint64_t, uint32_t)
 
template<typename F >
static uint32_t crc32_append_zeroes (F mult, uint32_t crc, size_t len, uint32_t polynomial, std::array< uint32_t, 62 > const &powers_array)
 
void init (int *argc, char ***argv, bool removeFlags)
 
int setCloseOnExec (int fd, int value)
 
std::ostream & operator<< (std::ostream &os, const AsyncSocket::StateEnum &state)
 
WriteFlags operator| (WriteFlags a, WriteFlags b)
 
WriteFlagsoperator|= (WriteFlags &a, WriteFlags b)
 
WriteFlags operator& (WriteFlags a, WriteFlags b)
 
WriteFlagsoperator&= (WriteFlags &a, WriteFlags b)
 
WriteFlags operator~ (WriteFlags a)
 
WriteFlags unSet (WriteFlags a, WriteFlags b)
 
bool isSet (WriteFlags a, WriteFlags b)
 
bool operator== (const DelayedDestructionBase::DestructorGuard &left, const DelayedDestructionBase::DestructorGuard &right)
 
bool operator!= (const DelayedDestructionBase::DestructorGuard &left, const DelayedDestructionBase::DestructorGuard &right)
 
bool operator== (const DelayedDestructionBase::DestructorGuard &left, std::nullptr_t)
 
bool operator== (std::nullptr_t, const DelayedDestructionBase::DestructorGuard &right)
 
bool operator!= (const DelayedDestructionBase::DestructorGuard &left, std::nullptr_t)
 
bool operator!= (std::nullptr_t, const DelayedDestructionBase::DestructorGuard &right)
 
template<typename LeftAliasType , typename RightAliasType >
bool operator== (const DelayedDestructionBase::IntrusivePtr< LeftAliasType > &left, const DelayedDestructionBase::IntrusivePtr< RightAliasType > &right)
 
template<typename LeftAliasType , typename RightAliasType >
bool operator!= (const DelayedDestructionBase::IntrusivePtr< LeftAliasType > &left, const DelayedDestructionBase::IntrusivePtr< RightAliasType > &right)
 
template<typename LeftAliasType >
bool operator== (const DelayedDestructionBase::IntrusivePtr< LeftAliasType > &left, std::nullptr_t)
 
template<typename RightAliasType >
bool operator== (std::nullptr_t, const DelayedDestructionBase::IntrusivePtr< RightAliasType > &right)
 
template<typename LeftAliasType >
bool operator!= (const DelayedDestructionBase::IntrusivePtr< LeftAliasType > &left, std::nullptr_t)
 
template<typename RightAliasType >
bool operator!= (std::nullptr_t, const DelayedDestructionBase::IntrusivePtr< RightAliasType > &right)
 
static std::chrono::milliseconds getTimeDelta (std::chrono::steady_clock::time_point *prev)
 
std::atomic< EventBaseManager * > globalManager (nullptr)
 
auto event_ref_flags (struct event *ev) -> decltype(std::ref(ev->ev_flags))
 
auto event_ref_flags (struct event const *ev) -> decltype(std::cref(ev->ev_flags))
 
static void run (EventBaseManager *ebm, EventBase *eb, folly::Baton<> *stop, const StringPiece &name)
 
std::ostream & operator<< (std::ostream &os, const PasswordCollector &collector)
 
 TEST (AsyncSocketException, SimpleTest)
 
 TEST (AsyncSocketException, SSLExceptionType)
 
 TEST (AsyncSocketTest, getSockOpt)
 
 TEST (AsyncSocketTest, REUSEPORT)
 
 TEST (AsyncSocketTest, v4v6samePort)
 
 TEST (AsyncSocketTest, duplicateBind)
 
 TEST (AsyncSocketTest, tosReflect)
 
void getfds (int fds[2])
 
void getctx (std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
 
void sslsocketpair (EventBase *eventBase, AsyncSSLSocket::UniquePtr *clientSock, AsyncSSLSocket::UniquePtr *serverSock)
 
bool clientProtoFilterPickPony (unsigned char **client, unsigned int *client_len, const unsigned char *, unsigned int)
 
bool clientProtoFilterPickNone (unsigned char **, unsigned int *, const unsigned char *, unsigned int)
 
std::string getFileAsBuf (const char *fileName)
 
 TEST (AsyncSSLSocketTest, ConnectWriteReadClose)
 
 TEST (AsyncSSLSocketTest, ReadAfterClose)
 
 TEST (AsyncSSLSocketTest, Renegotiate)
 
 TEST (AsyncSSLSocketTest, HandshakeError)
 
 TEST (AsyncSSLSocketTest, ReadError)
 
 TEST (AsyncSSLSocketTest, WriteError)
 
 TEST (AsyncSSLSocketTest, SocketWithDelay)
 
 TEST (AsyncSSLSocketTest, SNITestMatch)
 
 TEST (AsyncSSLSocketTest, SNITestNotMatch)
 
 TEST (AsyncSSLSocketTest, SNITestChangeServerName)
 
 TEST (AsyncSSLSocketTest, SNITestClientHelloNoHostname)
 
 TEST (AsyncSSLSocketTest, SSLClientTest)
 
 TEST (AsyncSSLSocketTest, SSLClientTestReuse)
 
 TEST (AsyncSSLSocketTest, SSLClientTimeoutTest)
 
 TEST (AsyncSSLSocketTest, SSLParseClientHelloSuccess)
 
 TEST (AsyncSSLSocketTest, GetClientCertificate)
 
 TEST (AsyncSSLSocketTest, SSLParseClientHelloOnePacket)
 
 TEST (AsyncSSLSocketTest, SSLParseClientHelloTwoPackets)
 
 TEST (AsyncSSLSocketTest, SSLParseClientHelloMultiplePackets)
 
 TEST (AsyncSSLSocketTest, SSLHandshakeValidationSuccess)
 
 TEST (AsyncSSLSocketTest, SSLHandshakeValidationFailure)
 
 TEST (AsyncSSLSocketTest, OverrideSSLCtxDisableVerify)
 
 TEST (AsyncSSLSocketTest, OverrideSSLCtxEnableVerify)
 
 TEST (AsyncSSLSocketTest, SSLHandshakeValidationOverride)
 
 TEST (AsyncSSLSocketTest, SSLHandshakeValidationSkip)
 
 TEST (AsyncSSLSocketTest, ClientCertHandshakeSuccess)
 
 TEST (AsyncSSLSocketTest, NoClientCertHandshakeError)
 
 TEST (AsyncSSLSocketTest, LoadCertFromMemory)
 
 TEST (AsyncSSLSocketTest, MinWriteSizeTest)
 
 TEST (AsyncSSLSocketTest, UnencryptedTest)
 
 TEST (AsyncSSLSocketTest, ConnectUnencryptedTest)
 
 TEST (AsyncSSLSocketTest, SSLAcceptRunnerBasic)
 
 TEST (AsyncSSLSocketTest, SSLAcceptRunnerAcceptError)
 
 TEST (AsyncSSLSocketTest, SSLAcceptRunnerAcceptClose)
 
 TEST (AsyncSSLSocketTest, SSLAcceptRunnerAcceptDestroy)
 
 TEST (AsyncSSLSocketTest, ConnResetErrorString)
 
 TEST (AsyncSSLSocketTest, ConnEOFErrorString)
 
 TEST (AsyncSSLSocketTest, ConnOpenSSLErrorString)
 
 TEST (AsyncSSLSocketTest, TestSSLCipherCodeToNameMap)
 
 TEST (AsyncSSLSocketTest2, AttachDetachSSLContext)
 
 TEST (AsyncSSLSocketTest2, TestTLS12DefaultClient)
 
 TEST (AsyncSSLSocketTest2, TestTLS12BadClient)
 
 TEST_F (AsyncSSLSocketWriteTest, write_coalescing1)
 
 TEST_F (AsyncSSLSocketWriteTest, write_coalescing2)
 
 TEST_F (AsyncSSLSocketWriteTest, write_coalescing3)
 
 TEST_F (AsyncSSLSocketWriteTest, write_coalescing4)
 
 TEST_F (AsyncSSLSocketWriteTest, write_coalescing5)
 
 TEST_F (AsyncSSLSocketWriteTest, write_coalescing6)
 
 TEST_F (AsyncSSLSocketWriteTest, write_with_eor1)
 
 TEST_F (AsyncSSLSocketWriteTest, write_with_eor2)
 
 TEST_F (AsyncSSLSocketWriteTest, write_with_eor3)
 
 TEST (AsyncTimeout, make)
 
 TEST (AsyncTimeout, schedule)
 
 TEST (AsyncTimeout, schedule_immediate)
 
 TEST (AsyncTimeout, cancel_make)
 
 TEST (AsyncTimeout, cancel_schedule)
 
 TEST (AsyncTransportTest, getSocketFromSocket)
 
 TEST (AsyncTransportTest, getSocketFromWrappedTransport)
 
void setupSSLLocks ()
 
 TEST (SSLContextInitializationTest, SSLContextInitializeThenSetLocksAndInit)
 
 TEST (SSLContextInitializationTest, SSLContextSetLocksAndInitialize)
 
 TEST (SSLContextInitializationTest, SSLContextLocks)
 
 TEST (SSLContextInitializationTest, SSLContextLocksSetAfterInitIgnored)
 
 TEST_F (SSLContextTest, TestSetCipherString)
 
 TEST_F (SSLContextTest, TestSetCipherList)
 
 TEST_F (SSLContextTest, TestLoadCertKey)
 
 TEST_F (SSLOptionsTest, TestSetCommonCipherList)
 
 TEST_F (SSLSessionTest, BasicTest)
 
 TEST_F (SSLSessionTest, SerializeDeserializeTest)
 
 TEST_F (SSLSessionTest, GetSessionID)
 
static int getLinuxVersion (StringPiece release)
 
static nanoseconds getSchedTimeWaiting (pid_t tid)
 
std::ostream & operator<< (std::ostream &os, const TimePoint &timePoint)
 
bool checkTimeout (const TimePoint &start, const TimePoint &end, nanoseconds expected, bool allowSmaller, nanoseconds tolerance)
 
bool checkTimeout (const TimePoint &start, const TimePoint &end, std::chrono::nanoseconds expected, bool allowSmaller, std::chrono::nanoseconds tolerance=std::chrono::milliseconds(5))
 
 TEST (WriteFlagsTest, isSet)
 
 TEST (WriteFlagsTest, unionOperator)
 
 TEST (WriteFlagsTest, intersectionOperator)
 
 TEST (WriteFlagsTest, exclusionOperator)
 
 TEST (WriteFlagsTest, unsetOperator)
 
 TEST (WriteFlagsTest, compoundAssignmentUnionOperator)
 
 TEST (WriteFlagsTest, compoundAssignmentIntersectionOperator)
 
std::shared_ptr< ShutdownSocketSettryGetShutdownSocketSet ()
 
ReadMostlySharedPtr< ShutdownSocketSettryGetShutdownSocketSetFast ()
 
size_t hash_value (const IPAddress &addr)
 
ostream & operator<< (ostream &os, const IPAddress &addr)
 
void toAppend (IPAddress addr, string *result)
 
void toAppend (IPAddress addr, fbstring *result)
 
bool operator== (const IPAddress &addr1, const IPAddress &addr2)
 
bool operator< (const IPAddress &addr1, const IPAddress &addr2)
 
size_t hash_value (const IPAddressV4 &addr)
 
ostream & operator<< (ostream &os, const IPAddressV4 &addr)
 
void toAppend (IPAddressV4 addr, string *result)
 
void toAppend (IPAddressV4 addr, fbstring *result)
 
bool operator== (const IPAddressV4 &addr1, const IPAddressV4 &addr2)
 
bool operator< (const IPAddressV4 &addr1, const IPAddressV4 &addr2)
 
bool operator!= (const IPAddressV4 &a, const IPAddressV4 &b)
 
bool operator> (const IPAddressV4 &a, const IPAddressV4 &b)
 
bool operator<= (const IPAddressV4 &a, const IPAddressV4 &b)
 
bool operator>= (const IPAddressV4 &a, const IPAddressV4 &b)
 
size_t hash_value (const IPAddressV6 &addr)
 
ostream & operator<< (ostream &os, const IPAddressV6 &addr)
 
void toAppend (IPAddressV6 addr, string *result)
 
void toAppend (IPAddressV6 addr, fbstring *result)
 
static uint16_t unpack (uint8_t lobyte, uint8_t hibyte)
 
static void unpackInto (const unsigned char *src, uint16_t *dest, size_t count)
 
dynamic parseJson (StringPiece range)
 
dynamic parseJson (StringPiece range, json::serialization_opts const &opts)
 
std::string toJson (dynamic const &dyn)
 
std::string toPrettyJson (dynamic const &dyn)
 
void PrintTo (const dynamic &dyn, std::ostream *os)
 
FOLLY_ALWAYS_INLINE void assume (bool cond)
 
FOLLY_ALWAYS_INLINE void assume_unreachable ()
 
template<typename T >
constexpr unsigned int findFirstSet (T const v)
 
template<typename T >
constexpr unsigned int findLastSet (T const v)
 
template<typename T >
constexpr unsigned int popcount (T const v)
 
template<class T >
constexpr T nextPowTwo (T const v)
 
template<class T >
constexpr T prevPowTwo (T const v)
 
template<class T >
constexpr bool isPowTwo (T const v)
 
template<class T >
FOLLY_PACK_POP T loadUnaligned (const void *p)
 
template<class T >
T partialLoadUnaligned (const void *p, size_t l)
 
template<class T >
void storeUnaligned (void *p, T value)
 
template<typename T >
T bitReverse (T n)
 
template<typename Ex >
FOLLY_NOINLINE FOLLY_COLD void throw_exception (Ex &&ex)
 
template<typename Ex >
FOLLY_NOINLINE FOLLY_COLD void terminate_with (Ex &&ex) noexcept
 
template<typename Ex , typename... Args>
FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN void throw_exception (Args &&...args)
 
template<typename Ex , typename... Args>
FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN void terminate_with (Args &&...args) noexcept
 
template<typename F , typename... A>
FOLLY_NOINLINE FOLLY_COLD void invoke_noreturn_cold (F &&f, A &&...a)
 
template<typename T >
FOLLY_NODISCARD Tlaunder (T *in) noexcept
 
void launder (void *)=delete
 
void launder (void const *)=delete
 
void launder (void volatile *)=delete
 
void launder (void const volatile *)=delete
 
template<typename T , typename... Args>
void launder (T(*)(Args...))=delete
 
template<typename T >
constexpr ordering to_ordering (T c)
 
template<typename Pointer >
constexpr Pointer & get_underlying (propagate_const< Pointer > &obj)
 
template<typename Pointer >
constexpr Pointer const & get_underlying (propagate_const< Pointer > const &obj)
 
template<typename Pointer >
FOLLY_CPP14_CONSTEXPR void swap (propagate_const< Pointer > &a, propagate_const< Pointer > &b) noexcept(noexcept(a.swap(b)))
 
template<typename Pointer >
constexpr bool operator== (propagate_const< Pointer > const &a, std::nullptr_t)
 
template<typename Pointer >
constexpr bool operator== (std::nullptr_t, propagate_const< Pointer > const &a)
 
template<typename Pointer >
constexpr bool operator!= (propagate_const< Pointer > const &a, std::nullptr_t)
 
template<typename Pointer >
constexpr bool operator!= (std::nullptr_t, propagate_const< Pointer > const &a)
 
template<typename Pointer >
constexpr bool operator== (propagate_const< Pointer > const &a, propagate_const< Pointer > const &b)
 
template<typename Pointer >
constexpr bool operator!= (propagate_const< Pointer > const &a, propagate_const< Pointer > const &b)
 
template<typename Pointer >
constexpr bool operator< (propagate_const< Pointer > const &a, propagate_const< Pointer > const &b)
 
template<typename Pointer >
constexpr bool operator<= (propagate_const< Pointer > const &a, propagate_const< Pointer > const &b)
 
template<typename Pointer >
constexpr bool operator> (propagate_const< Pointer > const &a, propagate_const< Pointer > const &b)
 
template<typename Pointer >
constexpr bool operator>= (propagate_const< Pointer > const &a, propagate_const< Pointer > const &b)
 
template<typename Pointer , typename Other >
constexpr auto operator== (propagate_const< Pointer > const &a, Other const &b) -> decltype(get_underlying(a)==b, false)
 
template<typename Pointer , typename Other >
constexpr auto operator!= (propagate_const< Pointer > const &a, Other const &b) -> decltype(get_underlying(a)!=b, false)
 
template<typename Pointer , typename Other >
constexpr auto operator< (propagate_const< Pointer > const &a, Other const &b) -> decltype(get_underlying(a)< b, false)
 
template<typename Pointer , typename Other >
constexpr auto operator<= (propagate_const< Pointer > const &a, Other const &b) -> decltype(get_underlying(a)<=b, false)
 
template<typename Pointer , typename Other >
constexpr auto operator> (propagate_const< Pointer > const &a, Other const &b) -> decltype(get_underlying(a) > b, false)
 
template<typename Pointer , typename Other >
constexpr auto operator>= (propagate_const< Pointer > const &a, Other const &b) -> decltype(get_underlying(a) >=b, false)
 
template<typename Other , typename Pointer >
constexpr auto operator== (Other const &a, propagate_const< Pointer > const &b) -> decltype(a==get_underlying(b), false)
 
template<typename Other , typename Pointer >
constexpr auto operator!= (Other const &a, propagate_const< Pointer > const &b) -> decltype(a!=get_underlying(b), false)
 
template<typename Other , typename Pointer >
constexpr auto operator< (Other const &a, propagate_const< Pointer > const &b) -> decltype(a< get_underlying(b), false)
 
template<typename Other , typename Pointer >
constexpr auto operator<= (Other const &a, propagate_const< Pointer > const &b) -> decltype(a<=get_underlying(b), false)
 
template<typename Other , typename Pointer >
constexpr auto operator> (Other const &a, propagate_const< Pointer > const &b) -> decltype(a > get_underlying(b), false)
 
template<typename Other , typename Pointer >
constexpr auto operator>= (Other const &a, propagate_const< Pointer > const &b) -> decltype(a >=get_underlying(b), false)
 
template<typename T >
rvalue_reference_wrapper< Trref (T &&value) noexcept
 
template<typename T >
rvalue_reference_wrapper< Trref (T &) noexcept=delete
 
int uncaught_exceptions () noexcept
 
template<class Func >
auto lazy (Func &&fun)
 
void initLogging (StringPiece configString)
 
void initLoggingOrDie (StringPiece configString)
 
const char * getBaseLoggingConfig ()
 
LogConfig parseLogConfig (StringPiece value)
 
LogConfig parseLogConfigJson (StringPiece value)
 
LogConfig parseLogConfigDynamic (const dynamic &value)
 
dynamic logConfigToDynamic (const LogConfig &config)
 
dynamic logConfigToDynamic (const LogHandlerConfig &config)
 
dynamic logConfigToDynamic (const LogCategoryConfig &config)
 
FOLLY_ATTR_WEAK void initializeLoggerDB (LoggerDB &db)
 
LogLevel stringToLogLevel (StringPiece name)
 
string logLevelToString (LogLevel level)
 
std::ostream & operator<< (std::ostream &os, LogLevel level)
 
constexpr LogLevel operator+ (LogLevel level, uint32_t value)
 
LogLeveloperator+= (LogLevel &level, uint32_t value)
 
constexpr LogLevel operator- (LogLevel level, uint32_t value)
 
LogLeveloperator-= (LogLevel &level, uint32_t value)
 
constexpr bool isLogLevelFatal (LogLevel level)
 
void logDisabledHelper (std::true_type) noexcept
 
void logDisabledHelper (std::false_type) noexcept
 
std::string loggingFormatPrintf (const char *format,...) noexcept
 
std::string loggingFormatPrintf (FOLLY_PRINTF_FORMAT const char *format,...) noexcept FOLLY_PRINTF_FORMAT_ATTR(1
 
std::ostream & operator<< (std::ostream &os, const LogConfig &config)
 
std::ostream & operator<< (std::ostream &os, const LogCategoryConfig &config)
 
std::ostream & operator<< (std::ostream &os, const LogHandlerConfig &config)
 
void PrintTo (const std::shared_ptr< LogHandler > &handler, std::ostream *os)
 
StringPiece getXlogCategoryNameForFile (StringPiece filename)
 
constexpr bool xlogIsDirSeparator (char c)
 
constexpr const char * xlogStripFilename (const char *filename, const char *prefixes)
 
std::ostream & operator<< (std::ostream &os, MacAddress address)
 
template<class Tgt >
std::enable_if< IsSomeString< Tgt >::value >::type toAppend (MacAddress address, Tgt *result)
 
template<typename Map , typename Key >
Map::mapped_type get_default (const Map &map, const Key &key)
 
template<class Map , typename Key = typename Map::key_type, typename Value = typename Map::mapped_type, typename std::enable_if<!is_invocable< Value >::value >::type * = nullptr>
Map::mapped_type get_default (const Map &map, const Key &key, Value &&dflt)
 
template<class Map , typename Key = typename Map::key_type, typename Func , typename = typename std::enable_if< is_invocable_r<typename Map::mapped_type, Func>::value>::type>
Map::mapped_type get_default (const Map &map, const Key &key, Func &&dflt)
 
template<class E = std::out_of_range, class Map , typename Key = typename Map::key_type>
const Map::mapped_type & get_or_throw (const Map &map, const Key &key, const std::string &exceptionStrPrefix=std::string())
 
template<class E = std::out_of_range, class Map , typename Key = typename Map::key_type>
Map::mapped_type & get_or_throw (Map &map, const Key &key, const std::string &exceptionStrPrefix=std::string())
 
template<class Map , typename Key = typename Map::key_type>
folly::Optional< typename Map::mapped_type > get_optional (const Map &map, const Key &key)
 
template<class Map , typename Key = typename Map::key_type>
const Map::mapped_type & get_ref_default (const Map &map, const Key &key, const typename Map::mapped_type &dflt)
 
template<class Map , typename Key = typename Map::key_type>
const Map::mapped_type & get_ref_default (const Map &map, const Key &key, typename Map::mapped_type &&dflt)=delete
 
template<class Map , typename Key = typename Map::key_type>
const Map::mapped_type & get_ref_default (const Map &map, const Key &key, const typename Map::mapped_type &&dflt)=delete
 
template<class Map , typename Key = typename Map::key_type, typename Func , typename = typename std::enable_if< is_invocable_r<const typename Map::mapped_type&, Func>::value>::type, typename = typename std::enable_if< std::is_reference<invoke_result_t<Func>>::value>::type>
const Map::mapped_type & get_ref_default (const Map &map, const Key &key, Func &&dflt)
 
template<class Map , typename Key = typename Map::key_type>
const Map::mapped_type * get_ptr (const Map &map, const Key &key)
 
template<class Map , typename Key = typename Map::key_type>
Map::mapped_type * get_ptr (Map &map, const Key &key)
 
template<class Map , class Key1 , class Key2 , class... Keys>
auto get_optional (const Map &map, const Key1 &key1, const Key2 &key2, const Keys &...keys) -> folly::Optional< typename detail::NestedMapType< Map, 2+sizeof...(Keys)>::type >
 
template<class Map , class Key1 , class Key2 , class... Keys>
auto get_ptr (const Map &map, const Key1 &key1, const Key2 &key2, const Keys &...keys) -> typename detail::NestedMapType< Map, 2+sizeof...(Keys)>::type const *
 
template<class Map , class Key1 , class Key2 , class... Keys>
auto get_ptr (Map &map, const Key1 &key1, const Key2 &key2, const Keys &...keys) -> typename detail::NestedMapType< Map, 2+sizeof...(Keys)>::type *
 
template<class Map , class Key1 , class Key2 , class... KeysDefault, typename = typename std::enable_if<sizeof...(KeysDefault) != 0>::type>
auto get_default (const Map &map, const Key1 &key1, const Key2 &key2, const KeysDefault &...keysDefault) -> typename detail::NestedMapType< Map, 1+sizeof...(KeysDefault)>::type
 
template<class Map , class Key1 , class Key2 , class... KeysDefault, typename = typename std::enable_if<sizeof...(KeysDefault) != 0>::type, typename = typename std::enable_if<std::is_lvalue_reference< typename detail::DefaultType<KeysDefault...>::type>::value>::type>
auto get_ref_default (const Map &map, const Key1 &key1, const Key2 &key2, KeysDefault &&...keysDefault) -> typename detail::NestedMapType< Map, 1+sizeof...(KeysDefault)>::typeconst &
 
template<typename N , typename D >
constexpr detail::IdivResultType< N, DdivFloor (N num, D denom)
 
template<typename N , typename D >
constexpr detail::IdivResultType< N, DdivCeil (N num, D denom)
 
template<typename N , typename D >
constexpr detail::IdivResultType< N, DdivTrunc (N num, D denom)
 
template<typename N , typename D >
constexpr detail::IdivResultType< N, DdivRoundAway (N num, D denom)
 
template<typename T >
void mallctlRead (const char *cmd, T *out)
 
template<typename T >
void mallctlWrite (const char *cmd, T in)
 
template<typename T >
void mallctlReadWrite (const char *cmd, T *out, T in)
 
void mallctlCall (const char *cmd)
 
bool usingJEMalloc () noexcept
 
size_t goodMallocSize (size_t minSize) noexcept
 
void * checkedMalloc (size_t size)
 
void * checkedCalloc (size_t n, size_t size)
 
void * checkedRealloc (void *ptr, size_t size)
 
void * smartRealloc (void *p, const size_t currentSize, const size_t currentCapacity, const size_t newCapacity)
 
void resizeWithoutInitialization (std::string &s, std::size_t n)
 
template<typename T , typename = typename std::enable_if< std::is_trivially_destructible<T>::value && !std::is_same<T, bool>::value>::type>
void resizeWithoutInitialization (std::vector< T > &v, std::size_t n)
 
void * allocateBytes (size_t n)
 
void deallocateBytes (void *p, size_t n)
 
void * aligned_malloc (size_t size, size_t align)
 
void aligned_free (void *aligned_ptr)
 
template<typename Alloc , size_t kAlign = alignof(typename std::allocator_traits<Alloc>::value_type)>
std::allocator_traits< Alloc >::pointer allocateOverAligned (Alloc const &alloc, size_t n)
 
template<typename Alloc , size_t kAlign = alignof(typename std::allocator_traits<Alloc>::value_type)>
void deallocateOverAligned (Alloc const &alloc, typename std::allocator_traits< Alloc >::pointer ptr, size_t n)
 
template<typename Alloc , size_t kAlign = alignof(typename std::allocator_traits<Alloc>::value_type)>
size_t allocationBytesForOverAligned (size_t n)
 
template<typename T , typename... Args>
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique (Args &&...args)
 
template<typename T >
std::enable_if< std::is_array< T >::value, std::unique_ptr< T > >::type make_unique (const size_t n)
 
template<typename T , typename... Args>
std::enable_if< std::extent< T >::value!=0, std::unique_ptr< T > >::type make_unique (Args &&...)=delete
 
template<typename T , typename D >
std::shared_ptr< Tto_shared_ptr (std::unique_ptr< T, D > &&ptr)
 
template<typename T >
std::weak_ptr< Tto_weak_ptr (const std::shared_ptr< T > &ptr)
 
template<typename T , typename Alloc , typename... Args>
std::unique_ptr< T, allocator_delete< Alloc > > allocate_unique (Alloc const &alloc, Args &&...args)
 
SysBufferUniquePtr allocate_sys_buffer (std::size_t size)
 
template<class T , class T0 = typename std::remove_reference<T>::type>
MoveWrapper< T0 > makeMoveWrapper (T &&t)
 
template<class CharT , class Traits >
std::basic_ostream< CharT, Traits > & operator<< (std::basic_ostream< CharT, Traits > &os, const NetworkSocket &addr)
 
template<class T >
const Tget_pointer (const Optional< T > &opt)
 
template<class T >
Tget_pointer (Optional< T > &opt)
 
template<class T >
void swap (Optional< T > &a, Optional< T > &b) noexcept(noexcept(a.swap(b)))
 
template<class T >
constexpr Optional< _t< std::decay< T > > > make_optional (T &&v)
 
template<class T , class... Args>
constexpr folly::Optional< Tmake_optional (Args &&...args)
 
template<class T , class U , class... Args>
constexpr folly::Optional< Tmake_optional (std::initializer_list< U > il, Args &&...args)
 
template<class U , class V >
constexpr bool operator== (const Optional< U > &a, const V &b)
 
template<class U , class V >
constexpr bool operator!= (const Optional< U > &a, const V &b)
 
template<class U , class V >
constexpr bool operator== (const U &a, const Optional< V > &b)
 
template<class U , class V >
constexpr bool operator!= (const U &a, const Optional< V > &b)
 
template<class U , class V >
FOLLY_CPP14_CONSTEXPR bool operator== (const Optional< U > &a, const Optional< V > &b)
 
template<class U , class V >
constexpr bool operator!= (const Optional< U > &a, const Optional< V > &b)
 
template<class U , class V >
FOLLY_CPP14_CONSTEXPR bool operator< (const Optional< U > &a, const Optional< V > &b)
 
template<class U , class V >
constexpr bool operator> (const Optional< U > &a, const Optional< V > &b)
 
template<class U , class V >
constexpr bool operator<= (const Optional< U > &a, const Optional< V > &b)
 
template<class U , class V >
constexpr bool operator>= (const Optional< U > &a, const Optional< V > &b)
 
template<class V >
bool operator< (const Optional< V > &, const V &other)=delete
 
template<class V >
bool operator<= (const Optional< V > &, const V &other)=delete
 
template<class V >
bool operator>= (const Optional< V > &, const V &other)=delete
 
template<class V >
bool operator> (const Optional< V > &, const V &other)=delete
 
template<class V >
bool operator< (const V &other, const Optional< V > &)=delete
 
template<class V >
bool operator<= (const V &other, const Optional< V > &)=delete
 
template<class V >
bool operator>= (const V &other, const Optional< V > &)=delete
 
template<class V >
bool operator> (const V &other, const Optional< V > &)=delete
 
template<class V >
constexpr bool operator== (const Optional< V > &a, None) noexcept
 
template<class V >
constexpr bool operator== (None, const Optional< V > &a) noexcept
 
template<class V >
constexpr bool operator< (const Optional< V > &, None) noexcept
 
template<class V >
constexpr bool operator< (None, const Optional< V > &a) noexcept
 
template<class V >
constexpr bool operator> (const Optional< V > &a, None) noexcept
 
template<class V >
constexpr bool operator> (None, const Optional< V > &) noexcept
 
template<class V >
constexpr bool operator<= (None, const Optional< V > &) noexcept
 
template<class V >
constexpr bool operator<= (const Optional< V > &a, None) noexcept
 
template<class V >
constexpr bool operator>= (const Optional< V > &, None) noexcept
 
template<class V >
constexpr bool operator>= (None, const Optional< V > &a) noexcept
 
template<typename... Cases>
decltype(auto) overload (Cases &&...cases)
 
template<typename Variant , typename... Cases>
decltype(auto) variant_match (Variant &&variant, Cases &&...cases)
 
template<typename T >
std::ostream & operator<< (std::ostream &os, const PackedSyncPtr< T > &ptr)
 
template<class I1 , class I2 , std::enable_if_t< detail::Comparable< I1, I2 >::value, int > = 0>
bool operator== (Poly< I1 > const &_this, Poly< I2 > const &that)
 
template<class I1 , class I2 , std::enable_if_t< detail::Comparable< I1, I2 >::value, int > = 0>
bool operator!= (Poly< I1 > const &_this, Poly< I2 > const &that)
 
template<class I1 , class I2 , std::enable_if_t< detail::Orderable< I1, I2 >::value, int > = 0>
bool operator< (Poly< I1 > const &_this, Poly< I2 > const &that)
 
template<class I1 , class I2 , std::enable_if_t< detail::Orderable< I1, I2 >::value, int > = 0>
bool operator> (Poly< I1 > const &_this, Poly< I2 > const &that)
 
template<class I1 , class I2 , std::enable_if_t< detail::Orderable< I1, I2 >::value, int > = 0>
bool operator<= (Poly< I1 > const &_this, Poly< I2 > const &that)
 
template<class I1 , class I2 , std::enable_if_t< detail::Orderable< I1, I2 >::value, int > = 0>
bool operator>= (Poly< I1 > const &_this, Poly< I2 > const &that)
 
template<std::size_t N, typename This , typename... As>
auto poly_call (This &&_this, As &&...as) -> decltype(detail::PolyAccess::call< N >(static_cast< This && >(_this), static_cast< As && >(as)...))
 
template<std::size_t N, class I , class Tail , typename... As>
decltype(auto) poly_call (detail::PolyNode< I, Tail > &&_this, As &&...as)
 
template<std::size_t N, class I , class Tail , typename... As>
decltype(auto) poly_call (detail::PolyNode< I, Tail > &_this, As &&...as)
 
template<std::size_t N, class I , class Tail , typename... As>
decltype(auto) poly_call (detail::PolyNode< I, Tail > const &_this, As &&...as)
 
template<std::size_t N, class I , class Poly , typename... As, std::enable_if_t< detail::IsPoly< Poly >::value, int > = 0>
auto poly_call (Poly &&_this, As &&...as) -> decltype(poly_call< N, I >(static_cast< Poly && >(_this).get(), static_cast< As && >(as)...))
 
template<class T , class I >
detail::AddCvrefOf< T, I > && poly_cast (detail::PolyRoot< I > &&that)
 
template<class T , class Poly , std::enable_if_t< detail::IsPoly< Poly >::value, int > = 0>
constexpr auto poly_cast (Poly &&that) -> decltype(poly_cast< T >(std::declval< Poly >().get()))
 
template<class I >
std::type_info const & poly_type (detail::PolyRoot< I > const &that) noexcept
 
template<class Poly , std::enable_if_t< detail::IsPoly< Poly >::value, int > = 0>
constexpr auto poly_type (Poly const &that) noexcept-> decltype(poly_type(that.get()))
 
template<class I >
bool poly_empty (detail::PolyRoot< I > const &that) noexcept
 
template<class I >
constexpr bool poly_empty (detail::PolyRoot< I && > const &) noexcept
 
template<class I >
constexpr bool poly_empty (detail::PolyRoot< I & > const &) noexcept
 
template<class I >
constexpr bool poly_empty (Poly< I && > const &) noexcept
 
template<class I >
constexpr bool poly_empty (Poly< I & > const &) noexcept
 
template<class I , std::enable_if_t< detail::Not< std::is_reference< I >>::value, int > = 0>
constexpr Poly< I > && poly_move (detail::PolyRoot< I > &that) noexcept
 
template<class I , std::enable_if_t< detail::Not< std::is_const< I >>::value, int > = 0>
Poly< I && > poly_move (detail::PolyRoot< I & > const &that) noexcept
 
template<class I >
Poly< I const & > poly_move (detail::PolyRoot< I const & > const &that) noexcept
 
template<class Poly , std::enable_if_t< detail::IsPoly< Poly >::value, int > = 0>
constexpr auto poly_move (Poly &that) noexcept-> decltype(poly_move(that.get()))
 
template<class I >
void swap (Poly< I > &left, Poly< I > &right) noexcept
 
void asm_volatile_memory ()
 
void asm_volatile_pause ()
 
std::uint64_t asm_rdtsc ()
 
template<typename Char >
constexpr size_t constexpr_strlen (const Char *s)
 
template<>
constexpr size_t constexpr_strlen (const char *s)
 
template<typename Char >
constexpr int constexpr_strcmp (const Char *s1, const Char *s2)
 
template<>
constexpr int constexpr_strcmp (const char *s1, const char *s2)
 
libevent_fd_t getLibeventFd (int fd)
 
int libeventFdToFd (libevent_fd_t fd)
 
void folly_event_set (event *e, int fd, short s, EventSetCallback f, void *arg)
 
uint32_t randomNumberSeed ()
 
template<class Iter , class Comp = std::equal_to<typename Range<Iter>::value_type>>
size_t qfind (const Range< Iter > &haystack, const Range< Iter > &needle, Comp eq=Comp())
 
template<class Iter >
size_t qfind (const Range< Iter > &haystack, const typename Range< Iter >::value_type &needle)
 
template<class Iter >
size_t rfind (const Range< Iter > &haystack, const typename Range< Iter >::value_type &needle)
 
template<class Iter >
size_t qfind_first_of (const Range< Iter > &haystack, const Range< Iter > &needle)
 
template<class Iter >
void swap (Range< Iter > &lhs, Range< Iter > &rhs)
 
template<class Iter >
constexpr Range< Iter > range (Iter first, Iter last)
 
template<class Collection >
constexpr auto range (Collection &v) -> Range< decltype(v.data())>
 
template<class Collection >
constexpr auto range (Collection const &v) -> Range< decltype(v.data())>
 
template<class Collection >
constexpr auto crange (Collection const &v) -> Range< decltype(v.data())>
 
template<class T , size_t n>
constexpr Range< T * > range (T(&array)[n])
 
template<class T , size_t n>
constexpr Range< T const * > range (T const (&array)[n])
 
template<class T , size_t n>
constexpr Range< T const * > crange (T const (&array)[n])
 
template<class T , size_t n>
constexpr Range< T * > range (std::array< T, n > &array)
 
template<class T , size_t n>
constexpr Range< T const * > range (std::array< T, n > const &array)
 
template<class T , size_t n>
constexpr Range< T const * > crange (std::array< T, n > const &array)
 
template<class C >
std::basic_ostream< C > & operator<< (std::basic_ostream< C > &os, Range< C const * > piece)
 
template<class C >
std::basic_ostream< C > & operator<< (std::basic_ostream< C > &os, Range< C * > piece)
 
template<class Iter >
bool operator== (const Range< Iter > &lhs, const Range< Iter > &rhs)
 
template<class Iter >
bool operator!= (const Range< Iter > &lhs, const Range< Iter > &rhs)
 
template<class Iter >
bool operator< (const Range< Iter > &lhs, const Range< Iter > &rhs)
 
template<class Iter >
bool operator<= (const Range< Iter > &lhs, const Range< Iter > &rhs)
 
template<class Iter >
bool operator> (const Range< Iter > &lhs, const Range< Iter > &rhs)
 
template<class Iter >
bool operator>= (const Range< Iter > &lhs, const Range< Iter > &rhs)
 
template<class T , class U >
_t< std::enable_if< detail::ComparableAsStringPiece< T, U >::value, bool > > operator== (const T &lhs, const U &rhs)
 
template<class T , class U >
_t< std::enable_if< detail::ComparableAsStringPiece< T, U >::value, bool > > operator!= (const T &lhs, const U &rhs)
 
template<class T , class U >
_t< std::enable_if< detail::ComparableAsStringPiece< T, U >::value, bool > > operator< (const T &lhs, const U &rhs)
 
template<class T , class U >
_t< std::enable_if< detail::ComparableAsStringPiece< T, U >::value, bool > > operator> (const T &lhs, const U &rhs)
 
template<class T , class U >
_t< std::enable_if< detail::ComparableAsStringPiece< T, U >::value, bool > > operator<= (const T &lhs, const U &rhs)
 
template<class T , class U >
_t< std::enable_if< detail::ComparableAsStringPiece< T, U >::value, bool > > operator>= (const T &lhs, const U &rhs)
 
template<class Iter , class Comp >
size_t qfind_first_of (const Range< Iter > &haystack, const Range< Iter > &needles, Comp eq)
 
template<>
size_t qfind (const Range< const char * > &haystack, const char &needle)
 
template<>
size_t rfind (const Range< const char * > &haystack, const char &needle)
 
template<>
size_t qfind (const Range< const unsigned char * > &haystack, const unsigned char &needle)
 
template<>
size_t rfind (const Range< const unsigned char * > &haystack, const unsigned char &needle)
 
template<>
size_t qfind_first_of (const Range< const char * > &haystack, const Range< const char * > &needles)
 
template<>
size_t qfind_first_of (const Range< const unsigned char * > &haystack, const Range< const unsigned char * > &needles)
 
template<class T >
constexpr Replaceable< std::decay_t< T > > make_replaceable (T &&t)
 
template<class T , class... Args>
constexpr Replaceable< Tmake_replaceable (Args &&...args)
 
template<class T , class U , class... Args>
constexpr Replaceable< Tmake_replaceable (std::initializer_list< U > il, Args &&...args)
 
template<typename F >
FOLLY_NODISCARD detail::ScopeGuardImplDecay< F, true > makeGuard (F &&f) noexcept(noexcept(detail::ScopeGuardImplDecay< F, true >(static_cast< F && >(f))))
 
template<class T , std::size_t MaxInline, class A , class B , class C >
void swap (small_vector< T, MaxInline, A, B, C > &a, small_vector< T, MaxInline, A, B, C > &b)
 
size_t hash_value (const SocketAddress &address)
 
std::ostream & operator<< (std::ostream &os, const SocketAddress &addr)
 
template<class T , class C , class A , class G >
void swap (sorted_vector_set< T, C, A, G > &a, sorted_vector_set< T, C, A, G > &b)
 
template<class K , class V , class C , class A , class G >
void swap (sorted_vector_map< K, V, C, A, G > &a, sorted_vector_map< K, V, C, A, G > &b)
 
static double k_to_q (double k, double d)
 
static double clamp (double v, double lo, double hi)
 
template<class String >
void cEscape (StringPiece str, String &out)
 
template<class String >
void cUnescape (StringPiece str, String &out, bool strict)
 
template<class String >
void uriEscape (StringPiece str, String &out, UriEscapeMode mode)
 
template<class String >
void uriUnescape (StringPiece str, String &out, UriEscapeMode mode)
 
template<class Delim , class String , class OutputType >
void split (const Delim &delimiter, const String &input, std::vector< OutputType > &out, bool ignoreEmpty)
 
template<class Delim , class String , class OutputType >
void split (const Delim &delimiter, const String &input, fbvector< OutputType > &out, bool ignoreEmpty)
 
template<class OutputValueType , class Delim , class String , class OutputIterator >
void splitTo (const Delim &delimiter, const String &input, OutputIterator out, bool ignoreEmpty)
 
template<bool exact, class Delim , class... OutputTypes>
bool::type split (const Delim &delimiter, StringPiece input, OutputTypes &...outputs)
 
template<class Delim , class Iterator , class String >
void join (const Delim &delimiter, Iterator begin, Iterator end, String &output)
 
template<class OutputString >
void backslashify (folly::StringPiece input, OutputString &output, bool hex_style)
 
template<class String1 , class String2 >
void humanify (const String1 &input, String2 &output)
 
template<class InputString , class OutputString >
bool hexlify (const InputString &input, OutputString &output, bool append_output)
 
template<class InputString , class OutputString >
bool unhexlify (const InputString &input, OutputString &output)
 
template<class OutIt >
void hexDump (const void *ptr, size_t size, OutIt out)
 
static bool is_oddspace (char c)
 
StringPiece ltrimWhitespace (StringPiece sp)
 
StringPiece rtrimWhitespace (StringPiece sp)
 
std::string stringPrintf (const char *format,...)
 
std::string stringVPrintf (const char *format, va_list ap)
 
std::stringstringAppendf (std::string *output, const char *format,...)
 
std::stringstringVAppendf (std::string *output, const char *format, va_list ap)
 
void stringPrintf (std::string *output, const char *format,...)
 
void stringVPrintf (std::string *output, const char *format, va_list ap)
 
std::string prettyPrint (double val, PrettyType type, bool addSpace)
 
double prettyToDouble (folly::StringPiece *const prettyString, const PrettyType type)
 
double prettyToDouble (folly::StringPiece prettyString, const PrettyType type)
 
std::string hexDump (const void *ptr, size_t size)
 
fbstring errnoStr (int err)
 
void toLowerAscii (char *str, size_t length)
 
std::string stripLeftMargin (std::string s)
 
std::string toStdString (const folly::fbstring &s)
 
const std::stringtoStdString (const std::string &s)
 
std::string && toStdString (std::string &&s)
 
template<class String >
String cEscape (StringPiece str)
 
template<class String >
String cUnescape (StringPiece str, bool strict=true)
 
template<class String >
String uriEscape (StringPiece str, UriEscapeMode mode=UriEscapeMode::ALL)
 
template<class String >
String uriUnescape (StringPiece str, UriEscapeMode mode=UriEscapeMode::ALL)
 
std::string stringPrintf (FOLLY_PRINTF_FORMAT const char *format,...) FOLLY_PRINTF_FORMAT_ATTR(1
 
std::string void stringPrintf (std::string *out, FOLLY_PRINTF_FORMAT const char *fmt,...) FOLLY_PRINTF_FORMAT_ATTR(2
 
std::string void std::stringstringAppendf (std::string *output, FOLLY_PRINTF_FORMAT const char *format,...) FOLLY_PRINTF_FORMAT_ATTR(2
 
template<class OutputString = std::string>
OutputString backslashify (StringPiece input, bool hex_style=false)
 
template<class String >
String humanify (const String &input)
 
template<class OutputString = std::string>
OutputString hexlify (ByteRange input)
 
template<class OutputString = std::string>
OutputString hexlify (StringPiece input)
 
template<class OutputString = std::string>
OutputString unhexlify (StringPiece input)
 
template<class Delim , class Container , class String >
void join (const Delim &delimiter, const Container &container, String &output)
 
template<class Delim , class Value , class String >
void join (const Delim &delimiter, const std::initializer_list< Value > &values, String &output)
 
template<class Delim , class Container >
std::string join (const Delim &delimiter, const Container &container)
 
template<class Delim , class Value >
std::string join (const Delim &delimiter, const std::initializer_list< Value > &values)
 
template<class Delim , class Iterator , typename std::enable_if< std::is_base_of< std::forward_iterator_tag, typename std::iterator_traits< Iterator >::iterator_category >::value >::type * = nullptr>
std::string join (const Delim &delimiter, Iterator begin, Iterator end)
 
StringPiece trimWhitespace (StringPiece sp)
 
StringPiece skipWhitespace (StringPiece sp)
 
void toLowerAscii (MutableStringPiece str)
 
void toLowerAscii (std::string &str)
 
static std::string toSubprocessSpawnErrorMessage (char const *executable, int errCode, int errnoValue)
 
void asymmetricHeavyBarrier (AMBFlags flags)
 
FOLLY_ALWAYS_INLINE void asymmetricLightBarrier ()
 
template<typename Integer >
void atomic_wait (const std::atomic< Integer > *atomic, Integer expected)
 
template<typename Integer , typename Clock , typename Duration >
std::cv_status atomic_wait_until (const std::atomic< Integer > *atomic, Integer expected, const std::chrono::time_point< Clock, Duration > &deadline)
 
template<typename Integer >
void atomic_notify_one (const std::atomic< Integer > *atomic)
 
template<typename Integer >
void atomic_notify_all (const std::atomic< Integer > *atomic)
 
template<typename Atomic >
bool atomic_fetch_set (Atomic &atomic, std::size_t bit, std::memory_order mo)
 
template<typename Atomic >
bool atomic_fetch_reset (Atomic &atomic, std::size_t bit, std::memory_order mo)
 
template<typename Mutex , template< typename > class Atom, typename F , typename... Args>
FOLLY_ALWAYS_INLINE void call_once (basic_once_flag< Mutex, Atom > &flag, F &&f, Args &&...args)
 
template<template< typename > class Atom = std::atomic>
hazptr_tc< Atom > & hazptr_tc_tls ()
 
template<template< typename > class Atom = std::atomic>
hazptr_priv< Atom > & hazptr_priv_tls ()
 
template<template< typename > class Atom = std::atomic>
hazptr_domain< Atom > & default_hazptr_domain ()
 
template<template< typename > class Atom = std::atomic>
void hazptr_domain_push_retired (hazptr_obj_list< Atom > &l, bool check=true, hazptr_domain< Atom > &domain=default_hazptr_domain< Atom >()) noexcept
 
template<template< typename > class Atom = std::atomic, typename T , typename D = std::default_delete<T>>
void hazptr_retire (T *obj, D reclaim={})
 
template<template< typename > class Atom = std::atomic>
void hazptr_cleanup (hazptr_domain< Atom > &domain=default_hazptr_domain< Atom >()) noexcept
 
template<template< typename > class Atom = std::atomic>
void swap (hazptr_holder< Atom > &, hazptr_holder< Atom > &) noexcept
 
template<template< typename > class Atom>
FOLLY_ALWAYS_INLINE hazptr_domain< Atom > & default_hazptr_domain ()
 
template<template< typename > class Atom, typename T , typename D >
FOLLY_ALWAYS_INLINE void hazptr_retire (T *obj, D reclaim)
 
template<template< typename > class Atom>
FOLLY_ALWAYS_INLINE void swap (hazptr_holder< Atom > &lhs, hazptr_holder< Atom > &rhs) noexcept
 
FOLLY_STATIC_CTOR_PRIORITY_MAX folly::Indestructible< rcu_domain< RcuTag > * > rcu_default_domain_ (folly::detail::createGlobal< rcu_domain< RcuTag >, RcuTag >())
 
rcu_domain< RcuTag > * rcu_default_domain ()
 
template<typename Tag = RcuTag>
void swap (rcu_reader_domain< Tag > &a, rcu_reader_domain< Tag > &b) noexcept
 
template<typename Tag = RcuTag>
void synchronize_rcu (rcu_domain< Tag > *domain=rcu_default_domain()) noexcept
 
template<typename Tag = RcuTag>
void rcu_barrier (rcu_domain< Tag > *domain=rcu_default_domain()) noexcept
 
template<typename T , typename D = std::default_delete<T>, typename Tag = RcuTag>
void rcu_retire (T *p, D d={}, rcu_domain< Tag > *domain=rcu_default_domain())
 
static FOLLY_ALWAYS_INLINE void annotate_rwlock_create (void const volatile *const addr, char const *const f, int const l)
 
static FOLLY_ALWAYS_INLINE void annotate_rwlock_create_static (void const volatile *const addr, char const *const f, int const l)
 
static FOLLY_ALWAYS_INLINE void annotate_rwlock_destroy (void const volatile *const addr, char const *const f, int const l)
 
static FOLLY_ALWAYS_INLINE void annotate_rwlock_acquired (void const volatile *const addr, annotate_rwlock_level const w, char const *const f, int const l)
 
static FOLLY_ALWAYS_INLINE void annotate_rwlock_try_acquired (void const volatile *const addr, annotate_rwlock_level const w, bool const result, char const *const f, int const l)
 
static FOLLY_ALWAYS_INLINE void annotate_rwlock_released (void const volatile *const addr, annotate_rwlock_level const w, char const *const f, int const l)
 
static FOLLY_ALWAYS_INLINE void annotate_benign_race_sized (void const volatile *const addr, long const size, char const *const desc, char const *const f, int const l)
 
 TEST (AtomicWait, Basic)
 
 TEST (AtomicWait, BasicNonStandardWidths)
 
 TEST (AtomicWait, AtomicWaitUntilTimeout)
 
 TEST (AtomicWait, AtomicWaitUntilTimeoutNonStandardWidths)
 
 TEST (AtomicWait, AtomicWaitUntilNotified)
 
 TEST (AtomicWait, AtomicWaitUntilNotifiedNonStandardWidths)
 
 TEST (AtomicWait, AtomicWaitAliasing)
 
 TEST (AtomicWait, AtomicWaitAliasingNonStandardWidths)
 
 TEST_F (AtomicFetchSetTest, Basic)
 
 TEST_F (AtomicFetchResetTest, Basic)
 
 TEST_F (AtomicFetchSetTest, EnsureFetchOrUsed)
 
 TEST_F (AtomicFetchResetTest, EnsureFetchAndUsed)
 
 TEST_F (AtomicFetchSetTest, FetchSetDefault)
 
 TEST_F (AtomicFetchSetTest, FetchResetDefault)
 
 TEST_F (AtomicFetchSetTest, FetchSetX86)
 
 TEST_F (AtomicFetchResetTest, FetchResetX86)
 
 TEST (DistributedMutex, InternalDetailTestOne)
 
 TEST (DistributedMutex, Basic)
 
 TEST (DistributedMutex, BasicTryLock)
 
 TEST (DistributedMutex, TestSingleElementContentionChain)
 
 TEST (DistributedMutex, TestTwoElementContentionChain)
 
 TEST (DistributedMutex, TestTwoContentionChains)
 
 TEST (DistributedMutex, StressTwoThreads)
 
 TEST (DistributedMutex, StressThreeThreads)
 
 TEST (DistributedMutex, StressFourThreads)
 
 TEST (DistributedMutex, StressFiveThreads)
 
 TEST (DistributedMutex, StressSixThreads)
 
 TEST (DistributedMutex, StressSevenThreads)
 
 TEST (DistributedMutex, StressEightThreads)
 
 TEST (DistributedMutex, StressSixteenThreads)
 
 TEST (DistributedMutex, StressThirtyTwoThreads)
 
 TEST (DistributedMutex, StressSixtyFourThreads)
 
 TEST (DistributedMutex, StressHundredThreads)
 
 TEST (DistributedMutex, StressHardwareConcurrencyThreads)
 
 TEST (DistributedMutex, StressTryLock)
 
 TEST (DistributedMutex, DeterministicStressTwoThreads)
 
 TEST (DistributedMutex, DeterministicStressFourThreads)
 
 TEST (DistributedMutex, DeterministicStressEightThreads)
 
 TEST (DistributedMutex, DeterministicStressSixteenThreads)
 
 TEST (DistributedMutex, DeterministicStressThirtyTwoThreads)
 
 TEST (DistributedMutex, TimedLockTimeout)
 
 TEST (DistributedMutex, TimedLockAcquireAfterUnlock)
 
 TEST (DistributedMutex, TimedLockAcquireAfterLock)
 
 TEST (DistributedMutex, TimedLockAcquireAfterContentionChain)
 
 TEST (DistributedMutex, StressTryLockWithConcurrentLocksTwoThreads)
 
 TEST (DistributedMutex, StressTryLockWithConcurrentLocksFourThreads)
 
 TEST (DistributedMutex, StressTryLockWithConcurrentLocksEightThreads)
 
 TEST (DistributedMutex, StressTryLockWithConcurrentLocksSixteenThreads)
 
 TEST (DistributedMutex, StressTryLockWithConcurrentLocksThirtyTwoThreads)
 
 TEST (DistributedMutex, StressTryLockWithConcurrentLocksSixtyFourThreads)
 
 TEST (DistributedMutex, DeterministicTryLockWithLocksTwoThreads)
 
 TEST (DistributedMutex, DeterministicTryLockWithFourThreads)
 
 TEST (DistributedMutex, DeterministicTryLockWithLocksEightThreads)
 
 TEST (DistributedMutex, DeterministicTryLockWithLocksSixteenThreads)
 
 TEST (DistributedMutex, DeterministicTryLockWithLocksThirtyTwoThreads)
 
 TEST (DistributedMutex, DeterministicTryLockWithLocksSixtyFourThreads)
 
 TEST (DistributedMutex, StressTryLockWithTwoThreads)
 
 TEST (DistributedMutex, StressTryLockFourThreads)
 
 TEST (DistributedMutex, StressTryLockEightThreads)
 
 TEST (DistributedMutex, StressTryLockSixteenThreads)
 
 TEST (DistributedMutex, StressTryLockThirtyTwoThreads)
 
 TEST (DistributedMutex, StressTryLockSixtyFourThreads)
 
 TEST (DistributedMutex, DeterministicTryLockTwoThreads)
 
 TEST (DistributedMutex, DeterministicTryLockFourThreads)
 
 TEST (DistributedMutex, DeterministicTryLockEightThreads)
 
 TEST (DistributedMutex, DeterministicTryLockSixteenThreads)
 
 TEST (DistributedMutex, DeterministicTryLockThirtyTwoThreads)
 
 TEST (DistributedMutex, DeterministicTryLockSixtyFourThreads)
 
template<typename D , typename M , typename... Args>
auto wlock (Synchronized< D, M > &synchronized, Args &&...args)
 
template<typename Data , typename Mutex , typename... Args>
auto rlock (const Synchronized< Data, Mutex > &synchronized, Args &&...args)
 
template<typename D , typename M , typename... Args>
auto ulock (Synchronized< D, M > &synchronized, Args &&...args)
 
template<typename D , typename M , typename... Args>
auto lock (Synchronized< D, M > &synchronized, Args &&...args)
 
template<typename D , typename M , typename... Args>
auto lock (const Synchronized< D, M > &synchronized, Args &&...args)
 
template<typename Func , typename... SynchronizedLockers>
decltype(auto) synchronized (Func &&func, SynchronizedLockers &&...lockers)
 
template<typename LockableOne , typename LockableTwo , typename... Lockables>
void lock (LockableOne &one, LockableTwo &two, Lockables &...lockables)
 
template<class Sync1 , class Sync2 >
std::tuple< detail::LockedPtrType< Sync1 >, detail::LockedPtrType< Sync2 > > acquireLocked (Sync1 &l1, Sync2 &l2)
 
template<class Sync1 , class Sync2 >
std::pair< detail::LockedPtrType< Sync1 >, detail::LockedPtrType< Sync2 > > acquireLockedPair (Sync1 &l1, Sync2 &l2)
 
template<class T , class M >
void swap (Synchronized< T, M > &lhs, Synchronized< T, M > &rhs)
 
void swap (MemoryMapping &a, MemoryMapping &b) noexcept
 
void alignedForwardMemcpy (void *dst, const void *src, size_t size)
 
void mmapFileCopy (const char *src, const char *dest, mode_t mode)
 
std::string shellQuote (StringPiece argument)
 
template<typename... Arguments>
std::vector< std::stringshellify (StringPiece format, Arguments &&...arguments)
 
 TEST (MemoryMapping, Basic)
 
 TEST (MemoryMapping, Move)
 
 TEST (MemoryMapping, DoublyMapped)
 
 TEST (MemoryMapping, Simple)
 
 TEST (MemoryMapping, LargeFile)
 
 TEST (MemoryMapping, ZeroLength)
 
 TEST (MemoryMapping, Advise)
 
uint64_t getCurrentThreadID ()
 
uint64_t getOSThreadID ()
 
bool canSetCurrentThreadName ()
 
bool canSetOtherThreadName ()
 
Optional< std::stringgetThreadName (std::thread::id id)
 
Optional< std::stringgetCurrentThreadName ()
 
bool setThreadName (std::thread::id tid, StringPiece name)
 
bool setThreadName (pthread_t pid, StringPiece name)
 
bool setThreadName (StringPiece name)
 
template<>
CacheLocality const & CacheLocality::system< test::DeterministicAtomic > ()
 
 TEST (ExecutorTest, KeepAliveBasic)
 
 TEST (ExecutorTest, KeepAliveMove)
 
 TEST (ExecutorTest, KeepAliveConvert)
 
 TEST (ExecutorTest, KeepAliveCopy)
 
std::ostream & operator<< (std::ostream &os, E e)
 
template<class V , class E >
std::ostream & operator<< (std::ostream &os, const Expected< V, E > &e)
 
 TEST (Expected, NoDefault)
 
 TEST (Expected, String)
 
 TEST (Expected, Ambiguous)
 
 TEST (Expected, Const)
 
 TEST (Expected, Simple)
 
bool operator== (const MoveTester &o1, const MoveTester &o2)
 
 TEST (Expected, value_or_rvalue_arg)
 
 TEST (Expected, value_or_noncopyable)
 
 TEST (Expected, value_move)
 
 TEST (Expected, dereference_move)
 
 TEST (Expected, EmptyConstruct)
 
 TEST (Expected, Unique)
 
 TEST (Expected, Shared)
 
 TEST (Expected, Order)
 
 TEST (Expected, SwapMethod)
 
 TEST (Expected, StdSwapFunction)
 
 TEST (Expected, FollySwapFunction)
 
 TEST (Expected, Comparisons)
 
 TEST (Expected, Conversions)
 
 TEST (Expected, Pointee)
 
 TEST (Expected, MakeOptional)
 
 TEST (Expected, SelfAssignment)
 
 TEST (Expected, AssignmentContained)
 
 TEST (Expected, Exceptions)
 
 TEST (Expected, NoThrowDefaultConstructible)
 
 TEST (Expected, NoThrowMoveConstructible)
 
 TEST (Expected, NoThrowMoveAssignable)
 
 TEST (Expected, NoSelfAssign)
 
 TEST (Expected, TriviallyDestructible)
 
 TEST (Expected, TriviallyCopyable)
 
 TEST (Expected, Then)
 
 TEST (Expected, ThenOrThrow)
 
 BENCHMARK (SmallFunctionFunctionPointerInvoke, iters)
 
 BENCHMARK (SmallFunctionStdFunctionInvoke, iters)
 
 BENCHMARK (SmallFunctionStdFunctionWithReferenceWrapperInvoke, iters)
 
 BENCHMARK (SmallFunctionFollyFunctionInvoke, iters)
 
 BENCHMARK (SmallFunctionFollyFunctionRefInvoke, iters)
 
 BENCHMARK_DRAW_LINE ()
 
 BENCHMARK (SmallFunctionFunctionPointerCreateInvoke, iters)
 
 BENCHMARK (SmallFunctionStdFunctionCreateInvoke, iters)
 
 BENCHMARK (SmallFunctionStdFunctionReferenceWrapperCreateInvoke, iters)
 
 BENCHMARK (SmallFunctionFollyFunctionCreateInvoke, iters)
 
 BENCHMARK (SmallFunctionFollyFunctionRefCreateInvoke, iters)
 
 BENCHMARK (BigFunctionStdFunctionInvoke, iters)
 
 BENCHMARK (BigFunctionStdFunctionReferenceWrapperInvoke, iters)
 
 BENCHMARK (BigFunctionFollyFunctionInvoke, iters)
 
 BENCHMARK (BigFunctionFollyFunctionRefInvoke, iters)
 
 BENCHMARK (BigFunctionStdFunctionCreateInvoke, iters)
 
 BENCHMARK (BigFunctionStdFunctionReferenceWrapperCreateInvoke, iters)
 
 BENCHMARK (BigFunctionFollyFunctionCreateInvoke, iters)
 
 BENCHMARK (BigFunctionFollyFunctionRefCreateInvoke, iters)
 
bool compareJson (StringPiece json1, StringPiece json2)
 
bool compareDynamicWithTolerance (const dynamic &obj1, const dynamic &obj2, double tolerance)
 
bool compareJsonWithTolerance (StringPiece json1, StringPiece json2, double tolerance)
 
 TEST (Lazy, Simple)
 
 TEST (Lazy, Global)
 
 TEST (Lazy, Map)
 
 TEST (Lazy, NonLambda)
 
 TEST (Lazy, Consty)
 
 TEST (makeMoveWrapper, Empty)
 
 TEST (makeMoveWrapper, NonEmpty)
 
 TEST (makeMoveWrapper, rvalue)
 
 TEST (makeMoveWrapper, lvalue)
 
 TEST (makeMoveWrapper, lvalue_copyable)
 
 TEST (Optional, NoDefault)
 
 TEST (Optional, Emplace)
 
 TEST (Optional, EmplaceInitializerList)
 
 TEST (Optional, Reset)
 
 TEST (Optional, String)
 
 TEST (Optional, Const)
 
 TEST (Optional, Simple)
 
 TEST (Optional, value_or_rvalue_arg)
 
 TEST (Optional, value_or_noncopyable)
 
 TEST (Optional, value_move)
 
 TEST (Optional, dereference_move)
 
 TEST (Optional, EmptyConstruct)
 
 TEST (Optional, InPlaceConstruct)
 
 TEST (Optional, InPlaceNestedConstruct)
 
 TEST (Optional, Unique)
 
 TEST (Optional, Shared)
 
 TEST (Optional, Order)
 
 TEST (Optional, Swap)
 
 TEST (Optional, Comparisons)
 
 TEST (Optional, HeterogeneousComparisons)
 
 TEST (Optional, NoneComparisons)
 
 TEST (Optional, Conversions)
 
 TEST (Optional, Pointee)
 
 TEST (Optional, MakeOptional)
 
 TEST (Optional, InitializerListConstruct)
 
 TEST (Optional, TestDisambiguationMakeOptionalVariants)
 
 TEST (Optional, SelfAssignment)
 
 TEST (Optional, AssignmentContained)
 
 TEST (Optional, Exceptions)
 
 TEST (Optional, NoThrowDefaultConstructible)
 
 TEST (Optional, TriviallyDestructible)
 
 TEST (Optional, Hash)
 
 TEST (Optional, ConstMember)
 
 TEST (Optional, NoneMatchesNullopt)
 
bool operator== (MutableStringPiece mp, StringPiece sp)
 
bool operator== (StringPiece sp, MutableStringPiece mp)
 
 TYPED_TEST_CASE (SynchronizedTest, SynchronizedTestTypes)
 
 TYPED_TEST (SynchronizedTest, Basic)
 
 TYPED_TEST (SynchronizedTest, WithLock)
 
 TYPED_TEST (SynchronizedTest, Unlock)
 
 TYPED_TEST (SynchronizedTest, Deprecated)
 
 TYPED_TEST (SynchronizedTest, Concurrency)
 
 TYPED_TEST (SynchronizedTest, AcquireLocked)
 
 TYPED_TEST (SynchronizedTest, AcquireLockedWithConst)
 
 TYPED_TEST (SynchronizedTest, DualLocking)
 
 TYPED_TEST (SynchronizedTest, DualLockingWithConst)
 
 TYPED_TEST (SynchronizedTest, ConstCopy)
 
 TYPED_TEST (SynchronizedTest, InPlaceConstruction)
 
 TYPED_TEST (SynchronizedTest, Exchange)
 
 TYPED_TEST_CASE (SynchronizedTimedTest, SynchronizedTimedTestTypes)
 
 TYPED_TEST (SynchronizedTimedTest, Timed)
 
 TYPED_TEST (SynchronizedTimedTest, TimedSynchronized)
 
 TYPED_TEST_CASE (SynchronizedTimedWithConstTest, SynchronizedTimedWithConstTestTypes)
 
 TYPED_TEST (SynchronizedTimedWithConstTest, TimedShared)
 
 TYPED_TEST (SynchronizedTimedWithConstTest, TimedSynchronizeWithConst)
 
 TEST_F (SynchronizedLockTest, TestCopyConstructibleValues)
 
 TEST_F (SynchronizedLockTest, UpgradableLocking)
 
 TEST_F (SynchronizedLockTest, UpgradableLockingWithULock)
 
 TEST_F (SynchronizedLockTest, TestPieceWiseConstruct)
 
 TEST_F (SynchronizedLockTest, TestTryLock)
 
 TEST_F (SynchronizedLockTest, TestTryWLock)
 
 TEST_F (SynchronizedLockTest, TestTryRLock)
 
 TEST_F (SynchronizedLockTest, TestTryULock)
 
 TEST_F (SynchronizedLockTest, TestLockedPtrCompatibilityExclusive)
 
 TEST_F (SynchronizedLockTest, TestLockedPtrCompatibilityShared)
 
 TEST_F (SynchronizedLockTest, TestLockedPtrCompatibilityUpgrade)
 
 TEST_F (SynchronizedLockTest, TestConvertTryLockToLock)
 
 TEST (FollyLockTest, TestVariadicLockWithSynchronized)
 
 TEST (FollyLockTest, TestVariadicLockWithArbitraryLockables)
 
 TEST (FollyLockTest, TestVariadicLockSmartAndPoliteAlgorithm)
 
 TEST (SynchronizedAlgorithmTest, Basic)
 
 TEST (SynchronizedAlgorithmTest, BasicNonShareableMutex)
 
 TEST (Synchronized, SynchronizedFunctionNonConst)
 
 TEST (Synchronized, SynchronizedFunctionConst)
 
 TEST (Synchronized, SynchronizedFunctionManyObjects)
 
void PrintTo (StringPiece sp,::std::ostream *os)
 
template<>
 FOLLY_ASSUME_RELOCATABLE (T2)
 
vector< detail::BenchmarkResultresultsFromFile (const std::string &filename)
 
void compareBenchmarkResults (const std::string &base, const std::string &test)
 
template<typename T >
constexpr bool is_negative (T x)
 
template<typename T >
constexpr bool is_non_positive (T x)
 
template<typename T >
constexpr bool is_positive (T x)
 
template<typename T >
constexpr bool is_non_negative (T x)
 
template<typename RHS , RHS rhs, typename LHS >
bool less_than (LHS const lhs)
 
template<typename RHS , RHS rhs, typename LHS >
bool greater_than (LHS const lhs)
 
template<typename F >
std::enable_if< !std::is_same< invoke_result_t< F >, void >::value, Try< invoke_result_t< F > > >::type makeTryWith (F &&f)
 
template<typename F >
std::enable_if< std::is_same< invoke_result_t< F >, void >::value, Try< void > >::type makeTryWith (F &&f)
 
template<typename T , typename... Args>
TtryEmplace (Try< T > &t, Args &&...args) noexcept
 
void tryEmplace (Try< void > &t) noexcept
 
template<typename T , typename Func >
TtryEmplaceWith (Try< T > &t, Func &&func) noexcept
 
template<typename Func >
bool tryEmplaceWith (Try< void > &t, Func &&func) noexcept
 
template<typename Tuple >
auto unwrapTryTuple (Tuple &&instance)
 
std::string codePointToUtf8 (char32_t cp)
 
char32_t utf8ToCodePoint (const unsigned char *&p, const unsigned char *const e, bool skipOnError)
 
template<typename T >
constexpr std::decay< T >::type copy (T &&value) noexcept(noexcept(typename std::decay< T >::type(std::forward< T >(value))))
 
template<class T >
constexpr T const & as_const (T &t) noexcept
 
template<class T >
void as_const (T const &&)=delete
 
template<typename Src , typename Dst >
constexpr like_t< Src, Dst > && forward_like (Dst &&dst) noexcept
 
template<class T , class U = T>
T exchange (T &obj, U &&new_value)
 
in_place_tag in_place (in_place_tag={})
 
template<class T >
in_place_type_tag< Tin_place_type (in_place_type_tag< T >={})
 
template<std::size_t I>
in_place_index_tag< I > in_place_index (in_place_index_tag< I >={})
 
template<typename T >
constexpr auto to_signed (T const &t) -> typename std::make_signed< T >::type
 
template<typename T >
constexpr auto to_unsigned (T const &t) -> typename std::make_unsigned< T >::type
 
size_t encodeVarint (uint64_t val, uint8_t *buf)
 
int encodeVarintSize (uint64_t val)
 
template<class T >
uint64_t decodeVarint (Range< T * > &data)
 
template<class T >
Expected< uint64_t, DecodeVarintErrortryDecodeVarint (Range< T * > &data)
 
uint64_t encodeZigZag (int64_t val)
 
int64_t decodeZigZag (uint64_t val)
 
template<>
folly::dynamic toDynamic (const wangle::SSLSessionCacheData &data)
 
template<>
wangle::SSLSessionCacheData convertTo (const dynamic &d)
 

Variables

template<class Tgt , class Src >
std::enable_if< std::is_integral< Src >::value &&IsSomeString< Tgt >::value &&sizeof(Src)< 4 >::typetoAppend(Src value, Tgt *result){typedef typename std::conditional< std::is_signed< Src >::value, int64_t, uint64_t >::type Intermediate;toAppend< Tgt >static_cast< Intermediate >value), result);}template< class Src >typename std::enable_if< std::is_integral< Src >::value &&sizeof(Src)< 4 &&!std::is_same< Src, char >::value, size_t >::typeestimateSpaceNeeded(Src value){typedef typename std::conditional< std::is_signed< Src >::value, int64_t, uint64_t >::type Intermediate;return estimateSpaceNeeded(static_cast< Intermediate >value));}template< class Tgt, class Src >typename std::enable_if< std::is_enum< Src >::value &&IsSomeString< Tgt >::value >::typetoAppend(Src value, Tgt *result){toAppend(static_cast< typename std::underlying_type< Src >::type >value), result);}template< class Src >typename std::enable_if< std::is_enum< Src >::value, size_t >::typeestimateSpaceNeeded(Src value){return estimateSpaceNeeded(static_cast< typename std::underlying_type< Src >::type >value));}namespace detail{constexpr int kConvMaxDecimalInShortestLow=-6;constexpr int kConvMaxDecimalInShortestHigh=21;}template< class Tgt, class Src >typename std::enable_if< std::is_floating_point< Src >::value &&IsSomeString< Tgt >::value >::typetoAppend(Src value, Tgt *result, double_conversion::DoubleToStringConverter::DtoaMode mode, unsigned int numDigits){using namespace double_conversion;DoubleToStringConverter conv(DoubleToStringConverter::NO_FLAGS,"Infinity","NaN", 'E', detail::kConvMaxDecimalInShortestLow, detail::kConvMaxDecimalInShortestHigh, 6, 1);char buffer[256];StringBuilder builder(buffer, sizeof(buffer));switch(mode){case DoubleToStringConverter::SHORTEST:conv.ToShortest(value,&builder);break;case DoubleToStringConverter::SHORTEST_SINGLE:conv.ToShortestSingle(static_cast< float >value),&builder);break;case DoubleToStringConverter::FIXED:conv.ToFixed(value, int(numDigits),&builder);break;default:CHECK(mode==DoubleToStringConverter::PRECISION);conv.ToPrecision(value, int(numDigits),&builder);break;}const size_t length=size_t(builder.position());builder.Finalize();result->append(buffer, length);}template< class Tgt, class Src >typename std::enable_if< std::is_floating_point< Src >::value &&IsSomeString< Tgt >::value >::typetoAppend(Src value, Tgt *result){toAppend(value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);}template< class Src >typename std::enable_if< std::is_floating_point< Src >::value, size_t >::typeestimateSpaceNeeded(Src value){constexpr int kMaxMantissaSpace=double_conversion::DoubleToStringConverter::kBase10MaximalLength+1;constexpr int kMaxExponentSpace=2+3;static const int kMaxPositiveSpace=std::max({kMaxMantissaSpace+kMaxExponentSpace, kMaxMantissaSpace-detail::kConvMaxDecimalInShortestLow, detail::kConvMaxDecimalInShortestHigh,});return size_t(kMaxPositiveSpace+(value< 0?1:0));}template< class Src >struct HasLengthEstimator:std::false_type{};template< class Src >constexpr typename std::enable_if< !std::is_fundamental< Src >::value &&!IsSomeString< Src >::value &&!std::is_convertible< Src, const char * >::value &&!std::is_convertible< Src, StringPiece >::value &&!std::is_enum< Src >::value &&!HasLengthEstimator< Src >::value, size_t >::typeestimateSpaceNeeded(const Src &){return sizeof(Src)+1;}namespace detail{template< class Tgt >typename std::enable_if< IsSomeString< Tgt >::value, size_t >::typeestimateSpaceToReserve(size_t sofar, Tgt *){return sofar;}template< class T, class...Ts >size_t estimateSpaceToReserve(size_t sofar, const T &v, const Ts &...vs){return estimateSpaceToReserve(sofar+estimateSpaceNeeded(v), vs...);}template< class...Ts >void reserveInTarget(const Ts &...vs){getLastElement(vs...) -> reserve (estimateSpaceToReserve(0, vs...))
 
static const ScaleInfo kTimeSuffixes []
 
static const ScaleInfo kMetricSuffixes []
 
constexpr auto loop_break = for_each_detail::LoopControl::BREAK
 
constexpr auto loop_continue = for_each_detail::LoopControl::CONTINUE
 
folly::std Delimiter
 
folly::std T
 
static constexpr uint32_t crc32c_m = 0x82f63b78
 
static constexpr uint32_t crc32_m = 0xedb88320
 
static constexpr std::array< uint32_t, 62 > const crc32c_powers
 
static constexpr std::array< uint32_t, 62 > const crc32_powers
 
static constexpr bool msgErrQueueSupported
 
static constexpr bool msgErrQueueSupported
 
const AsyncSocketException socketClosedLocallyEx (AsyncSocketException::END_OF_FILE,"socket closed locally")
 
const AsyncSocketException socketShutdownForWritesEx (AsyncSocketException::END_OF_FILE,"socket shutdown for writes")
 
static std::mutex libevent_mutex_
 
const char * kTestCert = "folly/io/async/test/certs/tests-cert.pem"
 
const char * kTestKey = "folly/io/async/test/certs/tests-key.pem"
 
const char * kTestCA = "folly/io/async/test/certs/ca-cert.pem"
 
const char * kClientTestCert = "folly/io/async/test/certs/client_cert.pem"
 
const char * kClientTestKey = "folly/io/async/test/certs/client_key.pem"
 
const char * kClientTestCA = "folly/io/async/test/certs/client_ca_cert.pem"
 
static Singleton< ShutdownSocketSet, PrivateTag > singleton
 
constexpr std::size_t max_align_v = detail::max_align_v_::value
 
constexpr std::size_t hardware_destructive_interference_size
 
constexpr std::size_t hardware_constructive_interference_size = 64
 
FOLLY_PACK_PUSH struct folly::Unaligned< T, typename std::enable_if< std::is_pod< T >::value >::typeFOLLY_PACK_ATTR
 
constexpr LogLevel kDefaultLogLevel = LogLevel::INFO
 
constexpr auto kIntegerDivisionGivesRemainder = true
 
static const size_t jemallocMinInPlaceExpandable = 4096
 
constexpr None none {None::_secret::_token}
 
template<class Sig >
constexpr detail::Sig< Sig > const sig = {}
 
constexpr size_t kIovMax = UIO_MAXIOV
 
constexpr bool kHasUnalignedAccess = false
 
constexpr bool kIsArchArm = 0 == 1
 
constexpr bool kIsArchAmd64 = 0 == 1
 
constexpr bool kIsArchAArch64 = 0 == 1
 
constexpr bool kIsArchPPC64 = 0 == 1
 
constexpr bool kIsSanitizeAddress = false
 
constexpr bool kIsSanitizeThread = false
 
constexpr bool kIsSanitize = false
 
constexpr auto kIsDebug = true
 
constexpr auto kIsLittleEndian = __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
 
constexpr auto kIsBigEndian = !kIsLittleEndian
 
constexpr auto kIsObjC = false
 
constexpr auto kIsMobile = false
 
constexpr auto kIsLinux = false
 
constexpr auto kIsWindows = false
 
constexpr auto kIsGlibcxx = false
 
constexpr auto kIsLibcpp = false
 
constexpr auto kIsLibstdcpp = false
 
constexpr auto kMscVer = 0
 
constexpr auto kMicrosoftAbiVer = 0
 
constexpr auto kCpplibVer = 0
 
hazptr_domain< std::atomic > default_domain
 
folly::Indestructible< rcu_domain< RcuTag > * > rcu_default_domain_
 
static constexpr size_t kMaxThreadNameLength = 16
 
auto globalCount = folly::lazy([] { return 0; })
 
auto const foo
 
static FakeAllPowerfulAssertingMutexInternal globalAllPowerfulAssertingMutex
 
constexpr Unit unit {}
 
constexpr initlist_construct_t initlist_construct {}
 
constexpr presorted_t presorted {}
 
constexpr unsorted_t unsorted {}
 
constexpr size_t kMaxVarintLength32 = 5
 
constexpr size_t kMaxVarintLength64 = 10
 

Detailed Description

—— Concurrent Priority Queue Implementation ——

Conversions between std::chrono types and POSIX time types.

These conversions will fail with a ConversionError if an overflow would occur performing the conversion. (e.g., if the input value cannot fit in the destination type). However they allow loss of precision (e.g., converting nanoseconds to a struct timeval which only has microsecond granularity, or a struct timespec to std::chrono::minutes).

Compression / decompression over IOBufs

Helper functions for compression codecs.

include or backport:

  • std::size
  • std::empty
  • std::data

BitIterator Wrapper around an iterator over an integral type that iterates over its underlying bits in MSb to LSb order

findFirstSet(BitIterator begin, BitIterator end) return a BitIterator pointing to the first 1 bit in [begin, end), or end if all bits in [begin, end) are 0

Author
Tudor Bosman (tudor.nosp@m.b@fb.nosp@m..com)

Similar to Python's enumerate(), folly::enumerate() can be used to iterate a range with a for-range loop, and it also allows to retrieve the count of iterations so far.

For example:

for (auto&& it : folly::enumerate(vec)) { // *it is a reference to the current element. Const if vec is const. // it->member can be used as well. // it.index contains the iteration count. }

If the iteration variable is const, the reference is too.

for (const auto&& it : folly::enumerate(vec)) { // *it is always a const reference. }

Author
Giuseppe Ottaviano ott@f.nosp@m.b.co.nosp@m.m

F14NodeMap, F14ValueMap, and F14VectorMap

F14FastMap conditionally inherits from F14ValueMap or F14VectorMap

See F14.md

Author
Nathan Bronson ngbro.nosp@m.nson.nosp@m.@fb.c.nosp@m.om
Xiao Shi xshi@.nosp@m.fb.c.nosp@m.om

F14NodeSet, F14ValueSet, and F14VectorSet

F14FastSet conditionally inherits from F14ValueSet or F14VectorSet

See F14.md

Author
Nathan Bronson ngbro.nosp@m.nson.nosp@m.@fb.c.nosp@m.om
Xiao Shi xshi@.nosp@m.fb.c.nosp@m.om

Converts anything to anything, with an emphasis on performance and safety.

Author
Andrei Alexandrescu (andre.nosp@m.i.al.nosp@m.exand.nosp@m.resc.nosp@m.u@fb..nosp@m.com)

Helper functions and templates for FileUtil.cpp. Declared here so they can be unittested.

Discriminated pointer: Type-safe pointer to one of several types.

Similar to boost::variant, but has no space overhead over a raw pointer, as it relies on the fact that (on x86_64) there are 16 unused bits in a pointer.

Author
Tudor Bosman (tudor.nosp@m.b@fb.nosp@m..com)

This is a runtime dynamically typed value. It holds types from a specific predetermined set of types (ints, bools, arrays, etc). In particular, it can be used as a convenient in-memory representation for complete json objects.

In general you can try to use these objects as if they were the type they represent (although in some cases with a slightly less complete interface than the raw type), and it'll just throw a TypeError if it is used in an illegal way.

Some examples:

dynamic twelve = 12; dynamic str = "string"; dynamic map = dynamic::object; map[str] = twelve; map[str + "another_str"] = dynamic::array("array", "of", 4, "elements"); map.insert("null_element", nullptr); ++map[str]; assert(map[str] == 13);

// Building a complex object with a sub array inline: dynamic d = dynamic::object ("key", "value") ("key2", dynamic::array("a", "array")) ;

Also see folly/json.h for the serialization and deserialization functions for JSON.

Additional documentation is in folly/docs/Dynamic.md.

Author
Jordan DeLong delon.nosp@m.g.j@.nosp@m.fb.co.nosp@m.m

convertTo returns a well-typed representation of the input dynamic.

Example:

dynamic d = dynamic::array( dynamic::array(1, 2, 3), dynamic::array(4, 5)); // a vector of vector of int auto vvi = convertTo<fbvector<fbvector<int>>>(d);

See docs/DynamicConverter.md for supported types and customization

gcc-4.7 warns about use of uninitialized memory around the use of storage_ even though this is explicitly initialized at each point.

Author
Giuseppe Ottaviano ott@f.nosp@m.b.co.nosp@m.m

Shared utils for BitVectorCoding.h and EliasFanoCoding.h.

Author
Philip Pronin (phili.nosp@m.pp@f.nosp@m.b.com)

Based on the paper by Sebastiano Vigna, "Quasi-succinct indices" (arxiv:1206.4300).

Validation according to the draft v4 standard: http://json-schema.org/

If your schema is invalid, then it won't validate anything. For example, if you set "type": "invalid_type" in your schema, then it won't check for any type, as if you had left that property out. If you want to make sure your schema is valid, you can optionally validate it first according to the metaschema.

Limitations:

  • We don't support fetching schemas via HTTP.
  • We don't support remote $refs.
  • We don't support $ref via id (only by path).
  • We don't support UTF-8 for string lengths, i.e. we will count bytes for schemas that use minLength/maxLength.

— Overview — — Mound — — Design — — Template Parameters: — — Interface

Wrappers for different versions of boost::context library API reference for different versions Boost 1.51: http://www.boost.org/doc/libs/1_51_0/libs/context/doc/html/context/context/boost_fcontext.html Boost 1.52: http://www.boost.org/doc/libs/1_52_0/libs/context/doc/html/context/context/boost_fcontext.html Boost 1.56: http://www.boost.org/doc/libs/1_56_0/libs/context/doc/html/context/context/boost_fcontext.html Boost 1.61: https://github.com/boostorg/context/blob/boost-1.61.0/include/boost/context/detail/fcontext.hpp

Compute 64-, 96-, and 128-bit Rabin fingerprints, as described in Michael O. Rabin (1981) Fingerprinting by Random Polynomials Center for Research in Computing Technology, Harvard University Tech Report TR-CSE-03-01

The implementation follows the optimization described in Andrei Z. Broder (1993) Some applications of Rabin's fingerprinting method

extended for fingerprints larger than 64 bits, and modified to use 64-bit instead of 32-bit integers for computation.

The precomputed tables are in Fingerprint.cpp.

Benchmarked on 10/13/2009 on a 2.5GHz quad-core Xeon L5420,

  • Fingerprint<64>::update64() takes about 12ns
  • Fingerprint<96>::update64() takes about 30ns
  • Fingerprint<128>::update128() takes about 30ns (unsurprisingly, Fingerprint<96> and Fingerprint<128> take the same amount of time, as they both use 128-bit operations; the least significant 32 bits of Fingerprint<96> will always be 0)
Author
Tudor Bosman (tudor.nosp@m.b@fa.nosp@m.ceboo.nosp@m.k.co.nosp@m.m)

include or backport:

  • std::invoke
  • std::invoke_result
  • std::invoke_result_t
  • std::is_invocable
  • std::is_invocable_r
  • std::is_nothrow_invocable
  • std::is_nothrow_invocable_r

Generator-based Sequence Comprehensions in C++, akin to C#'s LINQ

Author
Tom Jackson tjack.nosp@m.son@.nosp@m.fb.co.nosp@m.m

This library makes it possible to write declarative comprehensions for processing sequences of values efficiently in C++. The operators should be familiar to those with experience in functional programming, and the performance will be virtually identical to the equivalent, boilerplate C++ implementations.

Generator objects may be created from either an stl-like container (anything supporting begin() and end()), from sequences of values, or from another generator (see below). To create a generator that pulls values from a vector, for example, one could write:

vector<string> names { "Jack", "Jill", "Sara", "Tom" }; auto gen = from(names);

Generators are composed by building new generators out of old ones through the use of operators. These are reminiscent of shell pipelines, and afford similar composition. Lambda functions are used liberally to describe how to handle individual values:

auto lengths = gen | mapped([](const fbstring& name) { return name.size(); });

Generators are lazy; they don't actually perform any work until they need to. As an example, the 'lengths' generator (above) won't actually invoke the provided lambda until values are needed:

auto lengthVector = lengths | as<std::vector>(); auto totalLength = lengths | sum;

'auto' is useful in here because the actual types of the generators objects are usually complicated and implementation-sensitive.

If a simpler type is desired (for returning, as an example), VirtualGen<T> may be used to wrap the generator in a polymorphic wrapper:

VirtualGen<float> powersOfE() { return seq(1) | mapped(&expf); }

To learn more about this library, including the use of infinite generators, see the examples in the comments, or the docs (coming soon).

Cursor class for fast iteration over IOBuf chains.

Cursor - Read-only access

RWPrivateCursor - Read-write access, assumes private access to IOBuf chain RWUnshareCursor - Read-write access, calls unshare on write (COW) Appender - Write access, assumes private access to IOBuf chain

Note that RW cursors write in the preallocated part of buffers (that is, between the buffer's data() and tail()), while Appenders append to the end of the buffer (between the buffer's tail() and bufferEnd()). Appenders automatically adjust the buffer pointers, so you may only use one Appender with a buffer chain; for this reason, Appenders assume private access to the buffer (you need to call unshare() yourself if necessary).

Serialize and deserialize folly::dynamic values as JSON.

Before you use this you should probably understand the basic concepts in the JSON type system:

Value : String | Bool | Null | Object | Array | Number String : UTF-8 sequence Object : (String, Value) pairs, with unique String keys Array : ordered list of Values Null : null Bool : true | false Number : (representation unspecified)

... That's about it. For more information see http://json.org or look up RFC 4627.

If your dynamic has anything illegal with regard to this type system, the serializer will throw.

Author
Jordan DeLong delon.nosp@m.g.j@.nosp@m.fb.co.nosp@m.m

Various low-level, bit-manipulation routines.

findFirstSet(x) [constexpr] find first (least significant) bit set in a value of an integral type, 1-based (like ffs()). 0 = no bits are set (x == 0)

findLastSet(x) [constexpr] find last (most significant) bit set in a value of an integral type, 1-based. 0 = no bits are set (x == 0) for x != 0, findLastSet(x) == 1 + floor(log2(x))

nextPowTwo(x) [constexpr] Finds the next power of two >= x.

isPowTwo(x) [constexpr] return true iff x is a power of two

popcount(x) return the number of 1 bits in x

Endian convert between native, big, and little endian representation Endian::big(x) big <-> native Endian::little(x) little <-> native Endian::swap(x) big <-> little

Author
Tudor Bosman (tudor.nosp@m.b@fb.nosp@m..com)

Some arithmetic functions that seem to pop up or get hand-rolled a lot. So far they are all focused on integer division.

folly implementation of std::overload like functionality

Example: struct One {}; struct Two {}; boost::variant<One, Two> value;

variant_match(value, [] (const One& one) { ... }, [] (const Two& two) { ... });

Code that aids in storing data aligned on block (possibly cache-line) boundaries, perhaps with padding.

Class Node represents one block. Given an iterator to a container of Node, class Iterator encapsulates an iterator to the underlying elements. Adaptor converts a sequence of Node into a sequence of underlying elements (not fully compatible with STL container requirements, see comments near the Node class declaration).

An instance of Replaceable<T> wraps an instance of T.

You access the inner T instance with operator* and operator-> (as if it were a smart pointer).

Replaceable<T> adds no indirection cost and performs no allocations.

Replaceable<T> has the same size and alignment as T.

You can replace the T within a Replaceable<T> using the emplace method (presuming that it is constructible and destructible without throwing exceptions). If the destructor or constructor you're using could throw an exception you should use Optional<T> instead, as it's not a logic error for that to be empty.

Frequently Asked Questions

Why does this need to be so complicated?

If a T instance contains const-qualified member variables or reference member variables we can't safely replace a T instance by destructing it manually and using placement new. This is because compilers are permitted to assume that the const or reference members of a named, referenced, or pointed-to object do not change.

For pointed-to objects in allocated storage you can use the pointer returned by placement new or use the launder function to get a pointer to the new object. Note that launder doesn't affect its argument, it's still undefined behaviour to use the original pointer. And none of this helps if the object is a local or a member variable because the destructor call will not have been laundered. In summary, this is the only way to use placement new that is both simple and safe:

 T* pT = new T(...);
 pT->~T();
 pT = ::new (pT) T(...);
 delete pT;

What are the other safe solutions to this problem?

  • Ask the designer of T to de-const and -reference the members of T.
    • Makes T harder to reason about
    • Can reduce the performance of T methods
    • They can refuse to make the change
  • Put the T on the heap and use a raw/unique/shared pointer.
    • Adds a level of indirection, costing performance.
    • Harder to reason about your code as you need to check for nullptr.
  • Put the T in an Optional.
    • Harder to reason about your code as you need to check for None.
  • Pass the problem on, making the new code also not-replaceable
    • Contagion is not really a solution

Are there downsides to this?

There is a potential performance penalty after converting T to Replaceable<T> if you have non-T-member-function code which repeatedly examines the value of a const or reference data member of T, because the compiler now has to look at the value each time whereas previously it was permitted to load it once up-front and presume that it could never change.

Usage notes

Don't store a reference to the T within a Replaceable<T> unless you can show that its lifetime does not cross an emplace call. For safety a reasonable rule is to always use operator*() to get a fresh temporary each time you need a `T&.

If you store a pointer to the T within a Replaceable<T> you must launder it after each call to emplace before using it. Again you can reasonably choose to always use operator->() to get a fresh temporary each time you need a `T*.

Thus far I haven't thought of a good reason to use Replaceable<T> or Replaceable<T> const& as a function parameter type.

Replaceable<T>& can make sense to pass to a function that conditionally replaces the T, where T has const or reference member variables.

The main use of Replaceable<T> is as a class member type or a local type in long-running functions.

It's probably time to rethink your design choices if you end up with Replaceable<Replaceable<T>>, Optional<Replaceable<T>>, Replaceable<Optional<T>>, unique_ptr<Replaceable<T>> etc. except as a result of template expansion.

Subprocess library, modeled after Python's subprocess module (http://docs.python.org/2/library/subprocess.html)

This library defines one class (Subprocess) which represents a child process. Subprocess has two constructors: one that takes a vector<string> and executes the given executable without using the shell, and one that takes a string and executes the given command using the shell. Subprocess allows you to redirect the child's standard input, standard output, and standard error to/from child descriptors in the parent, or to create communication pipes between the child and the parent.

The simplest example is a thread-safe [1] version of the system() library function: Subprocess(cmd).wait(); which executes the command using the default shell and waits for it to complete, returning the exit status.

A thread-safe [1] version of popen() (type="r", to read from the child): Subprocess proc(cmd, Subprocess::Options().pipeStdout()); // read from proc.stdoutFd() proc.wait();

A thread-safe [1] version of popen() (type="w", to write to the child): Subprocess proc(cmd, Subprocess::Options().pipeStdin()); // write to proc.stdinFd() proc.wait();

If you want to redirect both stdin and stdout to pipes, you can, but note that you're subject to a variety of deadlocks. You'll want to use nonblocking I/O, like the callback version of communicate().

The string or IOBuf-based variants of communicate() are the simplest way to communicate with a child via its standard input, standard output, and standard error. They buffer everything in memory, so they are not great for large amounts of data (or long-running processes), but they are much simpler than the callback version.

== A note on thread-safety ==

[1] "thread-safe" refers ONLY to the fact that Subprocess is very careful to fork in a way that does not cause grief in multithreaded programs.

Caveat: If your system does not have the atomic pipe2 system call, it is not safe to concurrently call Subprocess from different threads. Therefore, it is best to have a single thread be responsible for spawning subprocesses.

A particular instances of Subprocess is emphatically not thread-safe. If you need to simultaneously communicate via the pipes, and interact with the Subprocess state, your best bet is to:

  • takeOwnershipOfPipes() to separate the pipe I/O from the subprocess.
  • Only interact with the Subprocess from one thread at a time.

The current implementation of communicate() cannot be safely interrupted. To do so correctly, one would need to use EventFD, or open a dedicated pipe to be messaged from a different thread – in particular, kill() will not do, since a descendant may keep the pipes open indefinitely.

So, once you call communicate(), you must wait for it to return, and not touch the pipes from other threads. closeParentFd() is emphatically unsafe to call concurrently, and even sendSignal() is not a good idea. You can perhaps give the Subprocess's PID to a different thread before starting communicate(), and use that PID to send a signal without accessing the Subprocess object. In that case, you will need a mutex that ensures you don't wait() before you sent said signal. In a nutshell, don't do this.

In fact, signals are inherently concurrency-unsafe on Unix: if you signal a PID, while another thread is in waitpid(), the signal may fire either before or after the process is reaped. This means that your signal can, in pathological circumstances, be delivered to the wrong process (ouch!). To avoid this, you should only use non-blocking waits (i.e. poll()), and make sure to serialize your signals (i.e. kill()) with the waits – either wait & signal from the same thread, or use a mutex.

Classes related to hazard pointer domains.

Classes related to objects protected by hazard pointers.

Classes related to link counted objects and automatic retirement.

Raw node storage is preallocated in a contiguous memory segment, but we use an anonymous mmap so the physical memory used (RSS) will only reflect the maximum number of waiters that actually existed concurrently. For blocked threads the max node count is limited by the number of threads, so we can conservatively estimate that this will be < 10k. For LifoEventSem, however, we could potentially have many more.

On a 64-bit architecture each LifoSemRawNode takes 16 bytes. We make the pool 1 million entries.

This module implements a Synchronized abstraction useful in mutex-based concurrency.

The Synchronized<T, Mutex> class is the primary public API exposed by this module. See folly/docs/Synchronized.md for a more complete explanation of this class and its benefits.

Shell provides a collection of functions to use with Subprocess that make it easier to safely run processes in a unix shell.

Note: use this rarely and carefully. By default you should use Subprocess with a vector of arguments.

============================================================================

folly/test/FunctionRefBenchmark.cpp relative time/iter iters/s

SmallFunctionFunctionPointerInvoke 3.02ns 331.34M SmallFunctionStdFunctionInvoke 3.02ns 331.34M SmallFunctionStdFunctionWithReferenceWrapperInv 3.02ns 331.33M SmallFunctionFollyFunctionInvoke 3.02ns 331.30M

SmallFunctionFollyFunctionRefInvoke 3.02ns 331.34M

SmallFunctionFunctionPointerCreateInvoke 3.02ns 331.34M SmallFunctionStdFunctionCreateInvoke 3.76ns 266.24M SmallFunctionStdFunctionReferenceWrapperCreateI 4.77ns 209.52M SmallFunctionFollyFunctionCreateInvoke 3.24ns 308.40M

SmallFunctionFollyFunctionRefCreateInvoke 3.02ns 331.34M

BigFunctionStdFunctionInvoke 3.02ns 330.74M BigFunctionStdFunctionReferenceWrapperInvoke 3.02ns 330.74M BigFunctionFollyFunctionInvoke 3.02ns 331.31M

BigFunctionFollyFunctionRefInvoke 3.02ns 331.31M

BigFunctionStdFunctionCreateInvoke 43.87ns 22.79M BigFunctionStdFunctionReferenceWrapperCreateInv 4.20ns 238.22M BigFunctionFollyFunctionCreateInvoke 43.01ns 23.25M

BigFunctionFollyFunctionRefCreateInvoke 3.02ns 331.31M

Higher performance (up to 10x) atomic increment using thread caching.

Author
Spencer Ahrens (sahrens)

Improved thread local storage for non-trivial types (similar speed as pthread_getspecific but only consumes a single pthread_key_t, and 4x faster than boost::thread_specific_ptr).

Also includes an accessor interface to walk all the thread local child objects of a parent. accessAllThreads() initializes an accessor which holds a global lock that blocks all creation and destruction of ThreadLocal objects with the same Tag and can be used as an iterable container. accessAllThreads() can race with destruction of thread-local elements. We provide a strict mode which is dangerous because it requires the access lock to be held while destroying thread-local elements which could cause deadlocks. We gate this mode behind the AccessModeStrict template parameter.

Intended use is for frequent write, infrequent read data access patterns such as counters.

There are two classes here - ThreadLocal and ThreadLocalPtr. ThreadLocalPtr has semantics similar to boost::thread_specific_ptr. ThreadLocal is a thin wrapper around ThreadLocalPtr that manages allocation automatically.

Author
Spencer Ahrens (sahrens)

Simple timeout queue. Call user-specified callbacks when their timeouts expire.

This class assumes that "time" is an int64_t and doesn't care about time units (seconds, milliseconds, etc). You call runOnce() / runLoop() using the same time units that you use to specify callbacks.

Author
Tudor Bosman (tudor.nosp@m.b@fb.nosp@m..com)

Typedef Documentation

template<typename T >
using folly::_t = typedef typename T::type

Definition at line 171 of file Traits.h.

typedef std::unique_ptr<int> folly::A

Definition at line 26 of file ThenCompileTest.h.

template<template< typename > class Atom>
using folly::aligned_hazptr_holder = typedef typename std::aligned_storage< sizeof(hazptr_holder<Atom>), alignof(hazptr_holder<Atom>)>::type

Type used by hazptr_array and hazptr_local.

Definition at line 199 of file HazptrHolder.h.

template<typename F , typename Tuple >
using folly::apply_result_t = typedef invoke_result_t<ApplyInvoke, F, Tuple>

Definition at line 126 of file ApplyTuple.h.

template<typename T , typename Alloc >
using folly::ArenaAllocator = typedef CxxAllocatorAdaptor<T, Arena<Alloc>>

Definition at line 247 of file Arena.h.

using folly::atomic_uint_fast_wait_t = typedef std::atomic<std::uint32_t>

Definition at line 63 of file AtomicNotification.h.

template<typename Key , typename Value , typename Hash = std::hash<Key>, typename KeyEqual = std::equal_to<Key>, bool SkipKeyValueDeletion = (boost::has_trivial_destructor<Key>::value && boost::has_trivial_destructor<Value>::value), template< typename > class Atom = std::atomic, typename Allocator = folly::detail::MMapAlloc>
using folly::AtomicUnorderedInsertMap64 = typedef AtomicUnorderedInsertMap< Key, Value, Hash, KeyEqual, SkipKeyValueDeletion, Atom, uint64_t, Allocator>

AtomicUnorderedInsertMap64 is just a type alias that makes it easier to select a 64 bit slot index type. Use this if you need a capacity bigger than 2^30 (about a billion). This increases memory overheads, obviously.

Definition at line 493 of file AtomicUnorderedMap.h.

template<typename Container , bool implicit_unpack = true>
using folly::back_emplace_iterator = typedef detail:: emplace_iterator_impl<detail::EmplaceBack, Container, implicit_unpack>

Behaves just like std::back_insert_iterator except that it calls emplace_back() instead of insert(). Uses perfect forwarding.

Examples:
/facebook/proxygen/proxygen/folly/folly/container/Iterator.h.

Definition at line 433 of file Iterator.h.

template<class Hash = f14::DefaultHasher<std::string>, class Eq = f14::DefaultKeyEqual<std::string>, class Alloc = f14::DefaultAlloc<std::string>>
using folly::BasicStringKeyedUnorderedSet = typedef F14NodeSet<std::string, Hash, Eq, Alloc>

Definition at line 27 of file StringKeyedUnorderedSet.h.

typedef function<detail::TimeIterPair(unsigned int)> folly::BenchmarkFun

Definition at line 73 of file Benchmark.cpp.

template<bool B>
using folly::bool_constant = typedef std::integral_constant<bool, B>

Definition at line 145 of file Traits.h.

typedef std::array<uint8_t, 16> folly::ByteArray16

Specialization for IPv6 addresses

Definition at line 50 of file IPAddressV6.h.

typedef std::array<uint8_t, 4> folly::ByteArray4

Specialization for IPv4 addresses

Definition at line 46 of file IPAddressV4.h.

typedef Range<const unsigned char*> folly::ByteRange

Definition at line 1163 of file Range.h.

Pair of IPAddressV4, netmask

Definition at line 36 of file IPAddressV4.h.

Pair of IPAddressV6, netmask

Definition at line 40 of file IPAddressV6.h.

template<typename Duration = folly::chrono::coarse_steady_clock::duration>
using folly::coarse_stop_watch = typedef custom_stop_watch<folly::chrono::coarse_steady_clock, Duration>

A type alias for custom_stop_watch that uses a coarse monotonic clock as the time source. Refer to the documentation of custom_stop_watch for full documentation.

Arguments:

  • Duration: (optional) the duration to use when reporting elapsed time. Defaults to the clock's duration.

Example:

coarse_stop_watch<std::chrono::seconds> watch; do_something(); std::cout << "time elapsed: " << watch.elapsed().count() << std::endl;

Author
: Marcelo Juchem marce.nosp@m.lo@f.nosp@m.b.com

Definition at line 284 of file stop_watch.h.

using folly::Cob = typedef Func

Definition at line 54 of file EventBase.h.

template<typename T , SafeIntrusiveListHook T::* PtrToMember>
using folly::CountedIntrusiveList = typedef boost::intrusive::list< T, boost::intrusive::member_hook<T, SafeIntrusiveListHook, PtrToMember>, boost::intrusive::constant_time_size<true>>

An intrusive list with const-time size() method.

A CountedIntrusiveList always uses a safe-link hook. CountedIntrusiveList::size() is an O(1) operation. Users of this type of lists need to remove a member from a list by calling one of the methods on the list (e.g., erase(), pop_front(), etc.), rather than calling unlink on the member's list hook. Given references to a list and a member, a constant-time removal operation can be accomplished by list.erase(list.iterator_to(member)). Also, when a member is destroyed, it is NOT automatically removed from the list.

Example usage:

class Foo { // Note that the listHook member variable needs to be visible // to the code that defines the CountedIntrusiveList instantiation. // The list hook can be made public, or you can make the other class a // friend. SafeIntrusiveListHook listHook; };

using FooList = CountedIntrusiveList<Foo, &Foo::listHook> FooList;

Foo *foo = new Foo(); FooList myList; myList.push_back(*foo); myList.pop_front();

Note that each SafeIntrusiveListHook can only be part of a single list at any given time. If you need the same object to be stored in two lists at once, you need to use two different SafeIntrusiveListHook member variables.

The elements stored in the list must contain an SafeIntrusiveListHook member variable.

Definition at line 116 of file IntrusiveList.h.

using folly::CountPair = typedef std::pair<int, int>

Definition at line 161 of file SynchronizedTest.cpp.

Definition at line 34 of file ReadMostlySharedPtr.h.

Bring the default instantiation of DistributedMutex into the folly namespace without requiring any template arguments for public usage

Definition at line 187 of file DistributedMutex.h.

template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = 7, typename WeightFn = DefaultWeightFn<T>, template< typename > class Atom = std::atomic>
using folly::DMPMCQueue = typedef DynamicBoundedQueue< T, false, false, MayBlock, LgSegmentSize, LgAlign, WeightFn, Atom>

DMPMCQueue

Definition at line 737 of file DynamicBoundedQueue.h.

template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = 7, typename WeightFn = DefaultWeightFn<T>, template< typename > class Atom = std::atomic>
using folly::DMPSCQueue = typedef DynamicBoundedQueue< T, false, true, MayBlock, LgSegmentSize, LgAlign, WeightFn, Atom>

DMPSCQueue

Definition at line 701 of file DynamicBoundedQueue.h.

template<typename T >
using folly::drop_unit_t = typedef typename drop_unit<T>::type

Definition at line 67 of file Unit.h.

template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = 7, typename WeightFn = DefaultWeightFn<T>, template< typename > class Atom = std::atomic>
using folly::DSPMCQueue = typedef DynamicBoundedQueue< T, true, false, MayBlock, LgSegmentSize, LgAlign, WeightFn, Atom>

DSPMCQueue

Definition at line 719 of file DynamicBoundedQueue.h.

template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = 7, typename WeightFn = DefaultWeightFn<T>, template< typename > class Atom = std::atomic>
using folly::DSPSCQueue = typedef DynamicBoundedQueue< T, true, true, MayBlock, LgSegmentSize, LgAlign, WeightFn, Atom>

Aliases.

DSPSCQueue

Definition at line 683 of file DynamicBoundedQueue.h.

using folly::Duration = typedef std::chrono::milliseconds

folly::Duration is an alias for the best resolution we offer/work with. However, it is not intended to be used for client code - you should use a descriptive std::chrono::duration type instead. e.g. do not write this:

futures::sleep(Duration(1000))...

rather this:

futures::sleep(std::chrono::milliseconds(1000));

or this:

futures::sleep(std::chrono::seconds(1));

Definition at line 36 of file Types.h.

Definition at line 376 of file TokenBucket.h.

template<typename Container , bool implicit_unpack = true>
using folly::emplace_iterator = typedef detail::emplace_iterator_impl<detail::Emplace, Container, implicit_unpack>

Behaves just like std::insert_iterator except that it calls emplace() instead of insert(). Uses perfect forwarding.

Examples:
/facebook/proxygen/proxygen/folly/folly/container/Iterator.h.

Definition at line 409 of file Iterator.h.

template<class T >
using folly::EnableIfFuture = typedef typename std::enable_if<isFuture<T>::value>::type

Definition at line 30 of file ThenCompileTest.h.

template<class T >
using folly::EnableUnlessFuture = typedef typename std::enable_if<!isFuture<T>::value>::type

Definition at line 33 of file ThenCompileTest.h.

using folly::EventSetCallback = typedef void (*)(libevent_fd_t, short, void*)

Definition at line 48 of file Event.h.

template<class Expected >
using folly::ExpectedErrorType = typedef typename std::remove_reference<Expected>::type::error_type

Alias for an Expected type's assiciated error_type

Definition at line 96 of file Expected.h.

template<class Expected >
using folly::ExpectedValueType = typedef typename std::remove_reference<Expected>::type::value_type

Alias for an Expected type's assiciated value_type

Definition at line 89 of file Expected.h.

Definition at line 2904 of file FBString.h.

template<std::size_t N>
using folly::FixedString = typedef BasicFixedString<char, N>

Definition at line 45 of file FixedString.h.

template<typename Container , bool implicit_unpack = true>
using folly::front_emplace_iterator = typedef detail:: emplace_iterator_impl<detail::EmplaceFront, Container, implicit_unpack>

Behaves just like std::front_insert_iterator except that it calls emplace_front() instead of insert(). Uses perfect forwarding.

Examples:
/facebook/proxygen/proxygen/folly/folly/container/Iterator.h.

Definition at line 425 of file Iterator.h.

using folly::Func = typedef Function<void()>

Definition at line 27 of file Executor.h.

template<typename Container , bool implicit_unpack = true>
using folly::hint_emplace_iterator = typedef detail:: emplace_iterator_impl<detail::EmplaceHint, Container, implicit_unpack>

Behaves just like std::insert_iterator except that it calls emplace_hint() instead of insert(). Uses perfect forwarding.

Examples:
/facebook/proxygen/proxygen/folly/folly/container/Iterator.h.

Definition at line 417 of file Iterator.h.

typedef std::vector<HugePageSize> folly::HugePageSizeVec

Vector of (huge_page_size, mount_point), sorted by huge_page_size. mount_point might be empty if no hugetlbfs file system is mounted for that size.

Definition at line 59 of file HugePages.h.

template<class... >
using folly::Ignored = typedef Ignore

Definition at line 388 of file Traits.h.

template<std::size_t I>
using folly::in_place_index_t = typedef in_place_index_tag<I> (&)(in_place_index_tag<I>)

Definition at line 233 of file Utility.h.

Definition at line 229 of file Utility.h.

template<class T >
using folly::in_place_type_t = typedef in_place_type_tag<T> (&)(in_place_type_tag<T>)

Definition at line 231 of file Utility.h.

template<std::size_t I>
using folly::index_constant = typedef std::integral_constant<std::size_t, I>

Definition at line 150 of file Traits.h.

template<std::size_t... Ints>
using folly::index_sequence = typedef integer_sequence<std::size_t, Ints...>

Definition at line 191 of file Utility.h.

template<class... T>
using folly::index_sequence_for = typedef make_index_sequence<sizeof...(T)>

Definition at line 211 of file Utility.h.

template<typename Tuple >
using folly::index_sequence_for_tuple = typedef make_index_sequence<std::tuple_size<Tuple>::value>

Helper to generate an index sequence from a tuple like type

Definition at line 36 of file ApplyTuple.h.

template<typename T >
using folly::IndexedMemPoolTraitsEagerRecycle = typedef IndexedMemPoolTraits<T, true, true>

IndexedMemPool traits that implements the eager lifecycle strategy. In this strategy elements are constructed when they are allocated from the pool and destroyed when recycled.

Definition at line 100 of file IndexedMemPool.h.

template<typename T >
using folly::IndexedMemPoolTraitsLazyRecycle = typedef IndexedMemPoolTraits<T, false, false>

IndexedMemPool traits that implements the lazy lifecycle strategy. In this strategy elements are default-constructed the first time they are allocated, and destroyed when the pool itself is destroyed.

Definition at line 94 of file IndexedMemPool.h.

template<typename T , IntrusiveListHook T::* PtrToMember>
using folly::IntrusiveList = typedef boost::intrusive::list< T, boost::intrusive::member_hook<T, IntrusiveListHook, PtrToMember>, boost::intrusive::constant_time_size<false>>

An intrusive list.

An IntrusiveList always uses an auto-unlink hook. Beware that IntrusiveList::size() is an O(n) operation, since it has to walk the entire list.

Example usage:

class Foo { // Note that the listHook member variable needs to be visible // to the code that defines the IntrusiveList instantiation. // The list hook can be made public, or you can make the other class a // friend. IntrusiveListHook listHook; };

using FooList = IntrusiveList<Foo, &Foo::listHook>;

Foo *foo = new Foo(); FooList myList; myList.push_back(*foo);

Note that each IntrusiveListHook can only be part of a single list at any given time. If you need the same object to be stored in two lists at once, you need to use two different IntrusiveListHook member variables.

The elements stored in the list must contain an IntrusiveListHook member variable.

Definition at line 68 of file IntrusiveList.h.

using folly::IntrusiveListHook = typedef boost::intrusive::list_member_hook< boost::intrusive::link_mode<boost::intrusive::auto_unlink>>

An auto-unlink intrusive list hook.

Definition at line 32 of file IntrusiveList.h.

template<typename F , typename... Args>
using folly::invoke_result_t = typedef typename invoke_result<F, Args...>::type

Definition at line 142 of file Invoke.h.

template<class T >
using folly::is_trivially_copyable = typedef std::is_trivially_copyable<T>

Definition at line 313 of file Traits.h.

template<typename T , typename... Ts>
using folly::IsOneOf = typedef StrictDisjunction<std::is_same<T, Ts>...>

Definition at line 609 of file Traits.h.

using folly::libevent_fd_t = typedef int

Definition at line 37 of file Event.h.

LifoSem is a semaphore that wakes its waiters in a manner intended to maximize performance rather than fairness. It should be preferred to a mutex+condvar or POSIX sem_t solution when all of the waiters are equivalent. It is faster than a condvar or sem_t, and it has a shutdown state that might save you a lot of complexity when it comes time to shut down your work pipelines. LifoSem is larger than sem_t, but that is only because it uses padding and alignment to avoid false sharing.

LifoSem allows multi-post and multi-tryWait, and provides a shutdown state that awakens all waiters. LifoSem is faster than sem_t because it performs exact wakeups, so it often requires fewer system calls. It provides all of the functionality of sem_t except for timed waiting. It is called LifoSem because its wakeup policy is approximately LIFO, rather than the usual FIFO.

The core semaphore operations provided are:

– post() – if there is a pending waiter, wake it up, otherwise increment the value of the semaphore. If the value of the semaphore is already 2^32-1, does nothing. Compare to sem_post().

– post(n) – equivalent to n calls to post(), but much more efficient. sem_t has no equivalent to this method.

– bool tryWait() – if the semaphore's value is positive, decrements it and returns true, otherwise returns false. Compare to sem_trywait().

– uint32_t tryWait(uint32_t n) – attempts to decrement the semaphore's value by n, returning the amount by which it actually was decremented (a value from 0 to n inclusive). Not atomic. Equivalent to n calls to tryWait(). sem_t has no equivalent to this method.

wait() – waits until tryWait() can succeed. Compare to sem_wait().

– timed wait variants - will wait until timeout. Note when these timeout, the current implementation takes a lock, blocking concurrent pushes and pops. (If timed wait calls are substantial, consider re-working this code to be lock-free).

LifoSem also has the notion of a shutdown state, in which any calls that would block (or are already blocked) throw ShutdownSemError. Note the difference between a call to wait() and a call to wait() that might block. In the former case tryWait() would succeed, and no isShutdown() check is performed. In the latter case an exception is thrown. This behavior allows a LifoSem controlling work distribution to drain. If you want to immediately stop all waiting on shutdown, you can just check isShutdown() yourself (preferrably wrapped in an UNLIKELY). This fast-stop behavior is easy to add, but difficult to remove if you want the draining behavior, which is why we have chosen the former.

All LifoSem operations except valueGuess() are guaranteed to be linearizable.

Definition at line 38 of file LifoSem.h.

template<typename T >
using folly::lift_unit_t = typedef typename lift_unit<T>::type

Definition at line 56 of file Unit.h.

template<typename Src , typename Dst >
using folly::like_t = typedef typename detail::like_<Src>::template apply<remove_cvref_t<Dst>>

Definition at line 220 of file Traits.h.

template<typename LockPolicy >
using folly::LPtr = typedef LockedPtr<Synchronized<int>, LockPolicy>

Definition at line 771 of file SynchronizedTest.cpp.

template<std::size_t Size>
using folly::make_index_sequence = typedef make_integer_sequence<std::size_t, Size>

Definition at line 209 of file Utility.h.

template<typename T , std::size_t Size>
using folly::make_integer_sequence = typedef typename utility_detail::make_seq< Size>::template apply<integer_sequence<T>, integer_sequence<T, 0>>

Definition at line 204 of file Utility.h.

template<typename F , typename T , typename ItT >
using folly::MaybeTryArg = typedef typename std:: conditional<is_invocable<F, T&&, Try<ItT>&&>::value, Try<ItT>, ItT>::type

Definition at line 445 of file helpers.h.

Definition at line 233 of file MicroLock.h.

using folly::monotonic_clock = typedef std::chrono::steady_clock

Definition at line 28 of file stop_watch.h.

Definition at line 386 of file Utility.h.

typedef std::lock_guard<MicroSpinLock> folly::MSLGuard

Definition at line 160 of file MicroSpinLock.h.

typedef Range<unsigned char*> folly::MutableByteRange

Definition at line 1164 of file Range.h.

Definition at line 1162 of file Range.h.

template<class Mutex >
using folly::MutexLevelValue = typedef detail::MutexLevelValueImpl< true, LockTraits<Mutex>::is_shared, LockTraits<Mutex>::is_upgrade>

Public version of LockInterfaceDispatcher that contains the MutexLevel enum for the passed in mutex type

This is decoupled from MutexLevelValueImpl in LockTraits.h because this ensures that a heterogenous mutex with a different API can be used. For example - if a mutex does not have a lock_shared() method but the LockTraits specialization for it supports a static non member lock_shared(Mutex&) it can be used as a shared mutex and will provide rlock() and wlock() functions.

Definition at line 66 of file Synchronized.h.

Definition at line 109 of file CallOnce.h.

using folly::PolyDecay = typedef detail::MetaQuote<std::decay_t>

When used in conjunction with PolySelf, controls how to construct Poly types related to the one currently being instantiated.

See also
PolySelf

Definition at line 116 of file Poly.h.

template<class... Ts>
using folly::PolyMembers = typedef detail::TypeList<Ts...>

A list of member function bindings.

Definition at line 71 of file PolyDetail.h.

template<class Node , class Tfx = detail::MetaIdentity, class Access = detail::PolyAccess>
using folly::PolySelf = typedef decltype(Access::template self_<Node, Tfx>())

Within the definition of interface I, PolySelf<Base> is an alias for the instance of Poly that is currently being instantiated. It is one of: Poly<J>, Poly<J&&>, Poly<J&>, or Poly<J const&>; where J is either I or some interface that extends I.

It can be used within interface definitions to declare members that accept other Poly objects of the same type as *this.

The first parameter may optionally be cv- and/or reference-qualified, in which case, the qualification is applies to the type of the interface in the resulting Poly<> instance. The second template parameter controls whether or not the interface is decayed before the cv-ref qualifiers of the first argument are applied. For example, given the following:

struct Foo {
  template <class Base>
  struct Interface : Base {
    using A = PolySelf<Base>;
    using B = PolySelf<Base &>;
    using C = PolySelf<Base const &>;
    using X = PolySelf<Base, PolyDecay>;
    using Y = PolySelf<Base &, PolyDecay>;
    using Z = PolySelf<Base const &, PolyDecay>;
  };
  // ...
};
struct Bar : PolyExtends<Foo> {
  // ...
};

Then for Poly<Bar>, the typedefs are aliases for the following types:

And for Poly<Bar &>, the typedefs are aliases for the following types:

Definition at line 108 of file Poly.h.

template<class KeyT , class ValueT , class HashFcn = std::hash<KeyT>, class EqualFcn = std::equal_to<KeyT>, class Allocator = std::allocator<char>>
using folly::QuadraticProbingAtomicHashMap = typedef AtomicHashMap< KeyT, ValueT, HashFcn, EqualFcn, Allocator, AtomicHashArrayQuadraticProbeFcn>

Definition at line 497 of file AtomicHashMap.h.

using folly::rcu_reader = typedef rcu_reader_domain<RcuTag>

Definition at line 440 of file Rcu.h.

template<typename T >
using folly::remove_cvref_t = typedef typename remove_cvref<T>::type

Definition at line 183 of file Traits.h.

using folly::SafeIntrusiveListHook = typedef boost::intrusive::list_member_hook< boost::intrusive::link_mode<boost::intrusive::safe_link>>

A safe-link intrusive list hook.

Definition at line 74 of file IntrusiveList.h.

Definition at line 1511 of file SharedMutex.h.

Definition at line 1509 of file SharedMutex.h.

typedef SharedMutexImpl<false, void, std::atomic, false, false> folly::SharedMutexSuppressTSAN

Definition at line 1513 of file SharedMutex.h.

Definition at line 1510 of file SharedMutex.h.

Definition at line 79 of file SpinLock.h.

typedef std::shared_ptr<SSLContext> folly::SSLContextPtr

Definition at line 628 of file SSLContext.h.

template<typename Duration = std::chrono::steady_clock::duration>
using folly::stop_watch = typedef custom_stop_watch<std::chrono::steady_clock, Duration>

A type alias for custom_stop_watch that uses a monotonic clock as the time source. Refer to the documentation of custom_stop_watch for full documentation.

Arguments:

  • Duration: (optional) the duration to use when reporting elapsed time. Defaults to the clock's duration.

Example:

stop_watch<std::chrono::seconds> watch; do_something(); std::cout << "time elapsed: " << watch.elapsed().count() << std::endl;

Author
: Marcelo Juchem marce.nosp@m.lo@f.nosp@m.b.com

Definition at line 304 of file stop_watch.h.

Definition at line 191 of file StringKeyedSet.h.

typedef Range< const char * > folly::StringPiece

Definition at line 29 of file ScopedEventBaseThread.h.

using folly::SynchronizedTestTypes = typedef testing::Types< folly::SharedMutexReadPriority, folly::SharedMutexWritePriority, std::mutex, std::recursive_mutex, boost::mutex, boost::recursive_mutex, boost::shared_mutex, folly::SpinLock>

Definition at line 58 of file SynchronizedTest.cpp.

Definition at line 25 of file ThreadPoolExecutor.cpp.

template<typename T >
using folly::SysArenaAllocator = typedef ArenaAllocator<T, SysAllocator<void>>

Definition at line 250 of file Arena.h.

using folly::SysBufferUniquePtr = typedef std::unique_ptr<void, SysBufferDeleter>

Definition at line 639 of file Memory.h.

Definition at line 88 of file ThreadCachedArena.h.

Definition at line 375 of file TokenBucket.h.

template<class T , class... Ts>
using folly::type_t = typedef typename traits_detail::type_t_<T, Ts...>::type

Definition at line 300 of file Traits.h.

template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = constexpr_log2(hardware_destructive_interference_size), template< typename > class Atom = std::atomic>
using folly::UMPMCQueue = typedef UnboundedQueue<T, false, false, MayBlock, LgSegmentSize, LgAlign, Atom>

Definition at line 883 of file UnboundedQueue.h.

template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = constexpr_log2(hardware_destructive_interference_size), template< typename > class Atom = std::atomic>
using folly::UMPSCQueue = typedef UnboundedQueue<T, false, true, MayBlock, LgSegmentSize, LgAlign, Atom>

Definition at line 865 of file UnboundedQueue.h.

template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = constexpr_log2(hardware_destructive_interference_size), template< typename > class Atom = std::atomic>
using folly::USPMCQueue = typedef UnboundedQueue<T, true, false, MayBlock, LgSegmentSize, LgAlign, Atom>

Definition at line 874 of file UnboundedQueue.h.

template<typename T , bool MayBlock, size_t LgSegmentSize = 8, size_t LgAlign = constexpr_log2(hardware_destructive_interference_size), template< typename > class Atom = std::atomic>
using folly::USPSCQueue = typedef UnboundedQueue<T, true, true, MayBlock, LgSegmentSize, LgAlign, Atom>

Definition at line 856 of file UnboundedQueue.h.

using folly::UTF8StringPiece = typedef UTF8Range<const char*>

Definition at line 46 of file UTF8String.h.

template<class... Ts>
using folly::void_t = typedef type_t<void, Ts...>

Definition at line 302 of file Traits.h.

Enumeration Type Documentation

Defines a special acquisition method for constructing fbstring objects. AcquireMallocatedString means that the user passes a pointer to a malloc-allocated string that the fbstring object will take into custody.

Definition at line 221 of file FBString.h.

221 {};
enum folly::AMBFlags
strong
Enumerator
NORMAL 
EXPEDITED 

Definition at line 25 of file AsymmetricMemoryBarrier.h.

enum folly::annotate_rwlock_level : long
strong
Enumerator
rdlock 
wrlock 

Definition at line 23 of file SanitizeThread.h.

Wraps error from parsing IP/MASK string

Enumerator
INVALID_DEFAULT_CIDR 
INVALID_IP_SLASH_CIDR 
INVALID_IP 
INVALID_CIDR 
CIDR_MISMATCH 

Definition at line 35 of file IPAddressException.h.

Enumerator
AVG 
SUM 

Definition at line 41 of file Counters.h.

Enumerator
TooManyBytes 
TooFewBytes 

Definition at line 74 of file Varint.h.

enum folly::E
strong
Enumerator
E1 
E2 

Definition at line 35 of file ExpectedTest.cpp.

Enumerator
SECONDS 
PRETTY 

Definition at line 31 of file AutoTimer.h.

Error codes for non-throwing interface of IPAddress family of functions.

Enumerator
INVALID_IP 
UNSUPPORTED_ADDR_FAMILY 

Definition at line 30 of file IPAddressException.h.

enum folly::LogLevel : uint32_t
strong

Log level values.

Higher levels are more important than lower ones.

However, the numbers in the DBG* and INFO* level names are reversed, and can be thought of as debug verbosity levels. Increasing DBG* numbers mean increasing level of verbosity. DBG0 is the least verbose debug level, DBG1 is one level higher of verbosity, etc.

Enumerator
UNINITIALIZED 
NONE 
MIN_LEVEL 
DBG 
DBG0 
DBG1 
DBG2 
DBG3 
DBG4 
DBG5 
DBG6 
DBG7 
DBG8 
DBG9 
INFO 
INFO0 
INFO1 
INFO2 
INFO3 
INFO4 
INFO5 
INFO6 
INFO7 
INFO8 
INFO9 
WARN 
WARNING 
ERR 
CRITICAL 
DFATAL 
FATAL 
MAX_LEVEL 

Definition at line 38 of file LogLevel.h.

38  : uint32_t {
39  UNINITIALIZED = 0,
40  NONE = 1,
41  MIN_LEVEL = 1,
42 
43  // "DBG" is the lowest (aka most verbose) debug log level.
44  // This level is intended to be primarily used in log category settings.
45  // In your code it is usually better to use one of the finer-grained DBGn
46  // levels. In your log category settings you can then set the log category
47  // level to a specific DBGn level, or to to main DBG level to enable all DBGn
48  // messages.
49  //
50  // This is named "DBG" rather than "DEBUG" since some open source projects
51  // define "DEBUG" as a preprocessor macro.
52  DBG = 1000,
53 
54  // Fine-grained debug log levels.
55  DBG0 = 1999,
56  DBG1 = 1998,
57  DBG2 = 1997,
58  DBG3 = 1996,
59  DBG4 = 1995,
60  DBG5 = 1994,
61  DBG6 = 1993,
62  DBG7 = 1992,
63  DBG8 = 1991,
64  DBG9 = 1990,
65 
66  INFO = 2000,
67  // Fine-grained info log levels.
68  INFO0 = 2999,
69  INFO1 = 2998,
70  INFO2 = 2997,
71  INFO3 = 2996,
72  INFO4 = 2995,
73  INFO5 = 2994,
74  INFO6 = 2993,
75  INFO7 = 2992,
76  INFO8 = 2991,
77  INFO9 = 2990,
78 
79  WARN = 3000,
80  WARNING = 3000,
81 
82  // Unfortunately Windows headers #define ERROR, so we cannot use
83  // it as an enum value name. We only provide ERR instead.
84  ERR = 4000,
85 
86  CRITICAL = 5000,
87 
88  // DFATAL log messages crash the program on debug builds.
89  DFATAL = 0x7ffffffe,
90  // FATAL log messages always abort the program.
91  // This level is equivalent to MAX_LEVEL.
92  FATAL = 0x7fffffff,
93 
94  // The most significant bit is used by LogCategory to store a flag value,
95  // so the maximum value has that bit cleared.
96  //
97  // (We call this MAX_LEVEL instead of MAX just since MAX() is commonly
98  // defined as a preprocessor macro by some C headers.)
99  MAX_LEVEL = 0x7fffffff,
100 };
enum folly::ordering : int
strong
Enumerator
lt 
eq 
gt 

Definition at line 21 of file Ordering.h.

enum folly::ParkResult
strong
Enumerator
Skip 
Unpark 
Timeout 

Definition at line 135 of file ParkingLot.h.

135  {
136  Skip,
137  Unpark,
138  Timeout,
139 };
def Skip(lines, pos, regex)
Definition: pump.py:261

A pretty-printer for numbers that appends suffixes of units of the given type. It prints 4 sig-figs of value with the most appropriate unit.

If `addSpace' is true, we put a space between the units suffix and the value.

Current types are: PRETTY_TIME - s, ms, us, ns, etc. PRETTY_TIME_HMS - h, m, s, ms, us, ns, etc. PRETTY_BYTES_METRIC - kB, MB, GB, etc (goes up by 10^3 = 1000 each time) PRETTY_BYTES - kB, MB, GB, etc (goes up by 2^10 = 1024 each time) PRETTY_BYTES_IEC - KiB, MiB, GiB, etc PRETTY_UNITS_METRIC - k, M, G, etc (goes up by 10^3 = 1000 each time) PRETTY_UNITS_BINARY - k, M, G, etc (goes up by 2^10 = 1024 each time) PRETTY_UNITS_BINARY_IEC - Ki, Mi, Gi, etc PRETTY_SI - full SI metric prefixes from yocto to Yotta http://en.wikipedia.org/wiki/Metric_prefix

Author
Mark Rabkin mrabk.nosp@m.in@f.nosp@m.b.com
Enumerator
PRETTY_TIME 
PRETTY_TIME_HMS 
PRETTY_BYTES_METRIC 
PRETTY_BYTES_BINARY 
PRETTY_BYTES 
PRETTY_BYTES_BINARY_IEC 
PRETTY_BYTES_IEC 
PRETTY_UNITS_METRIC 
PRETTY_UNITS_BINARY 
PRETTY_UNITS_BINARY_IEC 
PRETTY_SI 
PRETTY_NUM_TYPES 

Definition at line 314 of file String.h.

Enumerator
GFLAGS 
GNU 

Definition at line 26 of file ProgramOptions.h.

Enumerator
THROW 
BLOCK 

Definition at line 32 of file BlockingQueue.h.

enum folly::SSLError
strong
Enumerator
CLIENT_RENEGOTIATION 
INVALID_RENEGOTIATION 
EARLY_WRITE 
SSL_ERROR 
NETWORK_ERROR 
EOF_ERROR 

Definition at line 22 of file SSLErrors.h.

22  {
23  CLIENT_RENEGOTIATION, // A client tried to renegotiate with this server
24  INVALID_RENEGOTIATION, // We attempted to start a renegotiation.
25  EARLY_WRITE, // Wrote before SSL connection established.
26  SSL_ERROR, // An error related to SSL
27  NETWORK_ERROR, // An error related to the network.
28  EOF_ERROR, // The peer terminated the connection correctly.
29 };
Enumerator
STATE_WAITING 
STATE_SUCCEEDED 
STATE_FAILED 

Definition at line 45 of file TestSSLServer.h.

enum folly::UnparkControl
strong
Enumerator
RetainContinue 
RemoveContinue 
RetainBreak 
RemoveBreak 

Definition at line 128 of file ParkingLot.h.

enum folly::UriEscapeMode : unsigned char
strong

URI-escape a string. Appends the result to the output string.

Alphanumeric characters and other characters marked as "unreserved" in RFC 3986 ( -_.~ ) are left unchanged. In PATH mode, the forward slash (/) is also left unchanged. In QUERY mode, spaces are replaced by '+'. All other characters are percent-encoded.

Enumerator
ALL 
QUERY 
PATH 

Definition at line 121 of file String.h.

121  : unsigned char {
122  // The values are meaningful, see generate_escape_tables.py
123  ALL = 0,
124  QUERY = 1,
125  PATH = 2
126 };
enum folly::WriteFlags : uint32_t
strong
Enumerator
NONE 
CORK 
EOR 
WRITE_SHUTDOWN 
WRITE_MSG_ZEROCOPY 

Definition at line 47 of file AsyncTransport.h.

47  : uint32_t {
48  NONE = 0x00,
49  /*
50  * Whether to delay the output until a subsequent non-corked write.
51  * (Note: may not be supported in all subclasses or on all platforms.)
52  */
53  CORK = 0x01,
54  /*
55  * for a socket that has ACK latency enabled, it will cause the kernel
56  * to fire a TCP ESTATS event when the last byte of the given write call
57  * will be acknowledged.
58  */
59  EOR = 0x02,
60  /*
61  * this indicates that only the write side of socket should be shutdown
62  */
63  WRITE_SHUTDOWN = 0x04,
64  /*
65  * use msg zerocopy if allowed
66  */
67  WRITE_MSG_ZEROCOPY = 0x08,
68 };

Function Documentation

template<class Sync1 , class Sync2 >
std::tuple<detail::LockedPtrType<Sync1>, detail::LockedPtrType<Sync2> > folly::acquireLocked ( Sync1 &  l1,
Sync2 &  l2 
)

Acquire locks for multiple Synchronized<T> objects, in a deadlock-safe manner.

The locks are acquired in order from lowest address to highest address. (Note that this is not necessarily the same algorithm used by std::lock().) For parameters that are const and support shared locks, a read lock is acquired. Otherwise an exclusive lock is acquired.

use lock() with folly::wlock(), folly::rlock() and folly::ulock() for arbitrary locking without causing a deadlock (as much as possible), with the same effects as std::lock()

Definition at line 1626 of file Synchronized.h.

References std::tr1::make_tuple(), and folly::gen::move.

Referenced by acquireLockedPair(), folly::RequestContext::setContext(), folly::RequestContext::setShallowCopyContext(), folly::sync_tests::testAcquireLocked(), and folly::sync_tests::testAcquireLockedWithConst().

1626  {
1627  if (static_cast<const void*>(&l1) < static_cast<const void*>(&l2)) {
1628  auto p1 = l1.contextualLock();
1629  auto p2 = l2.contextualLock();
1630  return std::make_tuple(std::move(p1), std::move(p2));
1631  } else {
1632  auto p2 = l2.contextualLock();
1633  auto p1 = l1.contextualLock();
1634  return std::make_tuple(std::move(p1), std::move(p2));
1635  }
1636 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
tuple make_tuple()
Definition: gtest-tuple.h:675
template<class Sync1 , class Sync2 >
std::pair<detail::LockedPtrType<Sync1>, detail::LockedPtrType<Sync2> > folly::acquireLockedPair ( Sync1 &  l1,
Sync2 &  l2 
)

A version of acquireLocked() that returns a std::pair rather than a std::tuple, which is easier to use in many places.

Definition at line 1644 of file Synchronized.h.

References acquireLocked(), and folly::gen::move.

1644  {
1645  auto lockedPtrs = acquireLocked(l1, l2);
1646  return {std::move(std::get<0>(lockedPtrs)),
1647  std::move(std::get<1>(lockedPtrs))};
1648 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::tuple< detail::LockedPtrType< Sync1 >, detail::LockedPtrType< Sync2 > > acquireLocked(Sync1 &l1, Sync2 &l2)
template<typename Lambda >
std::enable_if< boost::function_types::function_arity< decltype(&Lambda::operator())>::value == 2>::type folly::addBenchmark ( const char *  file,
const char *  name,
Lambda &&  lambda 
)

Adds a benchmark. Usually not called directly but instead through the macro BENCHMARK defined below. The lambda function involved must take exactly one parameter of type unsigned, and the benchmark uses it with counter semantics (iteration occurs inside the function).

Definition at line 172 of file Benchmark.h.

References folly::detail::addBenchmarkImpl(), folly::test::end(), now(), start, times(), folly::BenchmarkSuspender::timeSpent, and type.

Referenced by addBenchmark(), and detail::addHashBenchmark().

172  {
173  auto execute = [=](unsigned int times) {
174  BenchmarkSuspender::timeSpent = {};
175  unsigned int niter;
176 
177  // CORE MEASUREMENT STARTS
179  niter = lambda(times);
181  // CORE MEASUREMENT ENDS
182 
183  return detail::TimeIterPair(
184  (end - start) - BenchmarkSuspender::timeSpent, niter);
185  };
186 
188  file, name, std::function<detail::TimeIterPair(unsigned int)>(execute));
189 }
std::chrono::steady_clock::time_point now()
void addBenchmarkImpl(const char *file, const char *name, std::function< TimeIterPair(unsigned int)>)
const char * name
Definition: http_parser.c:437
std::pair< std::chrono::high_resolution_clock::duration, unsigned int > TimeIterPair
Definition: Benchmark.h:58
auto end(TestAdlIterable &instance)
Definition: ForeachTest.cpp:62
auto start
Future< Unit > times(const int n, F &&thunk)
Definition: Future-inl.h:2348
template<typename Lambda >
std::enable_if< boost::function_types::function_arity< decltype(&Lambda::operator())>::value == 1>::type folly::addBenchmark ( const char *  file,
const char *  name,
Lambda &&  lambda 
)

Adds a benchmark. Usually not called directly but instead through the macro BENCHMARK defined below. The lambda function involved must take zero parameters, and the benchmark calls it repeatedly (iteration occurs outside the function).

Definition at line 201 of file Benchmark.h.

References addBenchmark(), doNotOptimizeAway(), makeUnpredictable(), T, and times().

201  {
202  addBenchmark(file, name, [=](unsigned int times) {
203  unsigned int niter = 0;
204  while (times-- > 0) {
205  niter += lambda();
206  }
207  return niter;
208  });
209 }
const char * name
Definition: http_parser.c:437
std::enable_if< boost::function_types::function_arity< decltype(&Lambda::operator())>::value==1 >::type addBenchmark(const char *file, const char *name, Lambda &&lambda)
Definition: Benchmark.h:201
Future< Unit > times(const int n, F &&thunk)
Definition: Future-inl.h:2348
template<class Ret , class... Params>
std::enable_if<isFuture<Ret>::value, Ret>::type folly::aFunction ( Params...  )

Definition at line 41 of file ThenCompileTest.h.

References makeFuture(), and T.

Referenced by TEST().

41  {
42  typedef typename Ret::value_type T;
43  return makeFuture(T());
44 }
#define T(v)
Definition: http_parser.c:233
Future< typename std::decay< T >::type > makeFuture(T &&t)
Definition: Future-inl.h:1310
template<class Ret , class... Params>
std::enable_if<!isFuture<Ret>::value, Ret>::type folly::aFunction ( Params...  )

Definition at line 47 of file ThenCompileTest.h.

47  {
48  return Ret();
49 }
void* folly::aligned_malloc ( size_t  size,
size_t  align 
)
inline
void folly::alignedForwardMemcpy ( void *  dest,
const void *  src,
size_t  size 
)

A special case of memcpy() that always copies memory forwards. (libc's memcpy() is allowed to copy memory backwards, and will do so when using SSSE3 instructions).

Assumes src and dest are aligned to alignof(unsigned long).

Useful when copying from/to memory mappings after hintLinearScan(); copying backwards renders any prefetching useless (even harmful).

Definition at line 390 of file MemoryMapping.cpp.

References size().

Referenced by mmapFileCopy().

390  {
391  assert(reinterpret_cast<uintptr_t>(src) % alignof(unsigned long) == 0);
392  assert(reinterpret_cast<uintptr_t>(dst) % alignof(unsigned long) == 0);
393 
394  auto srcl = static_cast<const unsigned long*>(src);
395  auto dstl = static_cast<unsigned long*>(dst);
396 
397  while (size >= sizeof(unsigned long)) {
398  *dstl++ = *srcl++;
399  size -= sizeof(unsigned long);
400  }
401 
402  auto srcc = reinterpret_cast<const unsigned char*>(srcl);
403  auto dstc = reinterpret_cast<unsigned char*>(dstl);
404 
405  while (size != 0) {
406  *dstc++ = *srcc++;
407  --size;
408  }
409 }
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
SysBufferUniquePtr folly::allocate_sys_buffer ( std::size_t  size)
inline

Definition at line 641 of file Memory.h.

Referenced by TEST().

641  {
642  auto p = std::malloc(size);
643  if (!p) {
644  throw_exception<std::bad_alloc>();
645  }
646  return {p, {}};
647 }
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
template<typename T , typename Alloc , typename... Args>
std::unique_ptr<T, allocator_delete<Alloc> > folly::allocate_unique ( Alloc const &  alloc,
Args &&...  args 
)

allocate_unique, like std::allocate_shared but for std::unique_ptr

Definition at line 609 of file Memory.h.

References copy(), FOLLY_UNLIKELY, handler(), folly::gen::move, and T.

611  {
612  using traits = std::allocator_traits<Alloc>;
613  struct DeferCondDeallocate {
614  bool& cond;
615  Alloc& copy;
616  T* p;
617  ~DeferCondDeallocate() {
618  if (FOLLY_UNLIKELY(!cond)) {
619  traits::deallocate(copy, p, 1);
620  }
621  }
622  };
623  auto copy = alloc;
624  auto const p = traits::allocate(copy, 1);
625  {
626  bool constructed = false;
627  DeferCondDeallocate handler{constructed, copy, p};
628  traits::construct(copy, p, static_cast<Args&&>(args)...);
629  constructed = true;
630  }
631  return {p, allocator_delete<Alloc>(std::move(copy))};
632 }
#define T(v)
Definition: http_parser.c:233
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define FOLLY_UNLIKELY(x)
Definition: Likely.h:36
void handler(int, siginfo_t *, void *)
constexpr std::decay< T >::type copy(T &&value) noexcept(noexcept(typename std::decay< T >::type(std::forward< T >(value))))
Definition: Utility.h:72
void* folly::allocateBytes ( size_t  n)
inline

allocateBytes and deallocateBytes work like a checkedMalloc/free pair, but take advantage of sized deletion when available

Definition at line 43 of file Memory.h.

Referenced by TEST().

43  {
44  return ::operator new(n);
45 }
template<typename Alloc , size_t kAlign = alignof(typename std::allocator_traits<Alloc>::value_type)>
std::allocator_traits<Alloc>::pointer folly::allocateOverAligned ( Alloc const &  alloc,
size_t  n 
)

Definition at line 198 of file Memory.h.

Referenced by TEST().

200  {
201  void* raw = nullptr;
202  detail::rawOverAlignedImpl<Alloc, kAlign, true>(alloc, n, raw);
203  return std::pointer_traits<typename std::allocator_traits<Alloc>::pointer>::
204  pointer_to(
205  *static_cast<typename std::allocator_traits<Alloc>::value_type*>(
206  raw));
207 }
template<typename Alloc , size_t kAlign = alignof(typename std::allocator_traits<Alloc>::value_type)>
size_t folly::allocationBytesForOverAligned ( size_t  n)

Definition at line 223 of file Memory.h.

References testing::Args(), constexpr_min(), make_unique(), T, type, value, and value().

Referenced by TEST().

223  {
224  static_assert((kAlign & (kAlign - 1)) == 0, "Align must be a power of 2");
225 
226  using AllocTraits = std::allocator_traits<Alloc>;
227  using T = typename AllocTraits::value_type;
228 
229  constexpr size_t kBaseAlign = constexpr_min(kAlign, alignof(max_align_t));
230 
231  if (kAlign > kBaseAlign && std::is_same<Alloc, std::allocator<T>>::value) {
232  return n * sizeof(T);
233  } else {
234  size_t quanta = (n * sizeof(T) + kBaseAlign - 1) / kBaseAlign;
235  if (kAlign > kBaseAlign) {
236  quanta += kAlign / kBaseAlign;
237  }
238  return quanta * kBaseAlign;
239  }
240 }
#define T(v)
Definition: http_parser.c:233
constexpr T constexpr_min(T a)
Definition: ConstexprMath.h:79
static const char *const value
Definition: Conv.cpp:50
static FOLLY_ALWAYS_INLINE void folly::annotate_benign_race_sized ( void const volatile *const  addr,
long const  size,
char const *const  desc,
char const *const  f,
int const  l 
)
static

Definition at line 124 of file SanitizeThread.h.

References folly::detail::annotate_benign_race_sized_impl(), and kIsSanitizeThread.

Referenced by folly::SharedMutexImpl< true >::annotateLazyCreate().

129  {
130  if (kIsSanitizeThread) {
132  }
133 }
auto f
constexpr bool kIsSanitizeThread
Definition: Portability.h:124
void annotate_benign_race_sized_impl(const volatile void *addr, long size, const char *desc, const char *f, int l)
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
ThreadPoolListHook * addr
static FOLLY_ALWAYS_INLINE void folly::annotate_rwlock_acquired ( void const volatile *const  addr,
annotate_rwlock_level const  w,
char const *const  f,
int const  l 
)
static

Definition at line 93 of file SanitizeThread.h.

References folly::detail::annotate_rwlock_acquired_impl(), and kIsSanitizeThread.

Referenced by annotate_rwlock_try_acquired(), folly::detail::annotate_rwlock_try_acquired_impl(), folly::SharedMutexImpl< true >::annotateAcquired(), and folly::observer_detail::ObserverManager::scheduleRefresh().

97  {
98  if (kIsSanitizeThread) {
100  }
101 }
auto f
void annotate_rwlock_acquired_impl(void const volatile *const addr, annotate_rwlock_level const w, char const *const f, int const l)
constexpr bool kIsSanitizeThread
Definition: Portability.h:124
ThreadPoolListHook * addr
static FOLLY_ALWAYS_INLINE void folly::annotate_rwlock_create ( void const volatile *const  addr,
char const *const  f,
int const  l 
)
static

Definition at line 66 of file SanitizeThread.h.

References folly::detail::annotate_rwlock_create_impl(), and kIsSanitizeThread.

Referenced by folly::SharedMutexImpl< true >::annotateLazyCreate().

69  {
70  if (kIsSanitizeThread) {
72  }
73 }
auto f
constexpr bool kIsSanitizeThread
Definition: Portability.h:124
void annotate_rwlock_create_impl(void const volatile *const addr, char const *const f, int const l)
ThreadPoolListHook * addr
static FOLLY_ALWAYS_INLINE void folly::annotate_rwlock_create_static ( void const volatile *const  addr,
char const *const  f,
int const  l 
)
static

Definition at line 75 of file SanitizeThread.h.

References folly::detail::annotate_rwlock_create_static_impl(), and kIsSanitizeThread.

78  {
79  if (kIsSanitizeThread) {
81  }
82 }
auto f
constexpr bool kIsSanitizeThread
Definition: Portability.h:124
void annotate_rwlock_create_static_impl(void const volatile *const addr, char const *const f, int const l)
ThreadPoolListHook * addr
static FOLLY_ALWAYS_INLINE void folly::annotate_rwlock_destroy ( void const volatile *const  addr,
char const *const  f,
int const  l 
)
static

Definition at line 84 of file SanitizeThread.h.

References folly::detail::annotate_rwlock_destroy_impl(), and kIsSanitizeThread.

Referenced by folly::SharedMutexImpl< true >::annotateDestroy().

87  {
88  if (kIsSanitizeThread) {
90  }
91 }
auto f
constexpr bool kIsSanitizeThread
Definition: Portability.h:124
void annotate_rwlock_destroy_impl(void const volatile *const addr, char const *const f, int const l)
ThreadPoolListHook * addr
static FOLLY_ALWAYS_INLINE void folly::annotate_rwlock_released ( void const volatile *const  addr,
annotate_rwlock_level const  w,
char const *const  f,
int const  l 
)
static

Definition at line 114 of file SanitizeThread.h.

References folly::detail::annotate_rwlock_released_impl(), and kIsSanitizeThread.

Referenced by folly::SharedMutexImpl< true >::annotateReleased(), and folly::observer_detail::ObserverManager::scheduleRefresh().

118  {
119  if (kIsSanitizeThread) {
121  }
122 }
void annotate_rwlock_released_impl(void const volatile *const addr, annotate_rwlock_level const w, char const *const f, int const l)
auto f
constexpr bool kIsSanitizeThread
Definition: Portability.h:124
ThreadPoolListHook * addr
static FOLLY_ALWAYS_INLINE void folly::annotate_rwlock_try_acquired ( void const volatile *const  addr,
annotate_rwlock_level const  w,
bool const  result,
char const *const  f,
int const  l 
)
static

Definition at line 103 of file SanitizeThread.h.

References annotate_rwlock_acquired().

Referenced by folly::SharedMutexImpl< true >::annotateTryAcquired().

108  {
109  if (result) {
111  }
112 }
auto f
static FOLLY_ALWAYS_INLINE void annotate_rwlock_acquired(void const volatile *const addr, annotate_rwlock_level const w, char const *const f, int const l)
ThreadPoolListHook * addr
template<typename Visitor , typename... Args>
decltype(auto) folly::apply_visitor ( Visitor &&  visitor,
const DiscriminatedPtr< Args... > &  variant 
)
template<typename Visitor , typename... Args>
decltype(auto) folly::apply_visitor ( Visitor &&  visitor,
DiscriminatedPtr< Args... > &  variant 
)

Definition at line 234 of file DiscriminatedPtr.h.

References testing::Args().

236  {
237  return variant.apply(std::forward<Visitor>(visitor));
238 }
template<typename Visitor , typename... Args>
decltype(auto) folly::apply_visitor ( Visitor &&  visitor,
DiscriminatedPtr< Args... > &&  variant 
)

Definition at line 241 of file DiscriminatedPtr.h.

243  {
244  return variant.apply(std::forward<Visitor>(visitor));
245 }
template<class T >
constexpr T const& folly::as_const ( T t)
noexcept

A simple helper for getting a constant reference to an object.

Example:

std::vector<int> v{1,2,3}; // The following two lines are equivalent: auto a = const_cast<const std::vector<int>&>(v).begin(); auto b = folly::as_const(v).begin();

Like C++17's std::as_const. See http://wg21.link/p0007

Definition at line 96 of file Utility.h.

References folly::pushmi::detail::t, and T.

Referenced by folly::RequestContext::setContext(), folly::futures::detail::Core< T >::setInterruptHandler(), folly::RequestContext::setShallowCopyContext(), TEST(), and TEST_F().

96  {
97  return t;
98 }
template<class T >
void folly::as_const ( T const &&  )
delete

Referenced by copy().

std::uint64_t folly::asm_rdtsc ( )
inline

Definition at line 49 of file Asm.h.

References now(), uint32_t, and uint64_t.

Referenced by folly::detail::distributed_mutex::time().

49  {
50 #if _MSC_VER
51  return (uint64_t)__rdtsc();
52 #elif defined(__i386__) || FOLLY_X64
53  // read the timestamp counter on x86
54  auto hi = std::uint32_t{};
55  auto lo = std::uint32_t{};
56  asm volatile("rdtsc" : "=a"(lo), "=d"(hi));
57  return (((std::uint64_t)lo) + (((std::uint64_t)hi) << 32));
58 #else
59  // use steady_clock::now() as an approximation for the timestamp counter on
60  // non-x86 systems
61  return std::chrono::steady_clock::now().time_since_epoch().count();
62 #endif
63 }
std::chrono::steady_clock::time_point now()
void folly::asm_volatile_memory ( )
inline

Definition at line 29 of file Asm.h.

Referenced by asymmetricLightBarrier(), and BENCHMARK().

29  {
30 #if defined(__clang__) || defined(__GNUC__)
31  asm volatile("" : : : "memory");
32 #elif defined(_MSC_VER)
33  ::_ReadWriteBarrier();
34 #endif
35 }
FOLLY_ALWAYS_INLINE void folly::assume ( bool  cond)

Inform the compiler that the argument can be assumed true. It is undefined behavior if the argument is not actually true, so use with care.

Implemented as a function instead of a macro because __builtin_assume does not evaluate its argument at runtime, so it cannot be used with expressions that have side-effects.

Definition at line 41 of file Assume.h.

References folly::detail::assume_check(), and kIsDebug.

Referenced by assume_unreachable(), BENCHMARK(), folly::F14VectorSet< Key, Hasher, KeyEqual, Alloc >::operator=(), folly::F14VectorMap< Key, Mapped, Hasher, KeyEqual, Alloc >::operator=(), partialLoadUnaligned(), folly::compression::EliasFanoReader< Encoder, Instructions, kUnchecked, SizeType >::readLowerPart(), folly::futures::detail::Core< T >::setCallback(), folly::coro::TimedWaitAwaitable< Awaitable >::SharedState::setException(), folly::futures::detail::Core< T >::setProxy(), folly::futures::detail::Core< T >::setResult(), folly::coro::TimedWaitAwaitable< Awaitable >::SharedState::setValue(), and storeUnaligned().

41  {
42  if (kIsDebug) {
44  } else {
45 #if defined(__clang__) // Must go first because Clang also defines __GNUC__.
46  __builtin_assume(cond);
47 #elif defined(__GNUC__)
48  if (!cond) {
49  __builtin_unreachable();
50  }
51 #elif defined(_MSC_VER)
52  __assume(cond);
53 #else
54  // Do nothing.
55 #endif
56  }
57 }
constexpr auto kIsDebug
Definition: Portability.h:264
void assume_check(bool cond)
Definition: Assume.cpp:25
FOLLY_ALWAYS_INLINE void folly::assume_unreachable ( )

Definition at line 59 of file Assume.h.

References assume().

Referenced by folly::FcCustomExample< Req, Mutex, Atom >::combinedOp(), compareDynamicWithTolerance(), folly::compression::instructions::dispatch(), folly::dynamic::hash(), folly::json_pointer::parse(), poly_call(), poly_cast(), poly_empty(), poly_move(), poly_type(), fizz::OpenSSLSignature< T >::sign(), folly::ProcessReturnCode::state(), folly::ProcessReturnCode::str(), folly::exception_wrapper::SharedPtr::throw_(), folly::fibers::TimedMutex::timed_lock(), and fizz::OpenSSLSignature< T >::verify().

59  {
60  assume(false);
61  // Do a bit more to get the compiler to understand
62  // that this function really will never return.
63 #if defined(__GNUC__)
64  __builtin_unreachable();
65 #elif defined(_MSC_VER)
66  __assume(0);
67 #else
68  // Well, it's better than nothing.
69  std::abort();
70 #endif
71 }
FOLLY_ALWAYS_INLINE void assume(bool cond)
Definition: Assume.h:41
template<class Ret , class... Params>
std::function<Ret(Params...)> folly::aStdFunction ( typename std::enable_if<!isFuture< Ret >::value, bool >::type  = false)

Definition at line 52 of file ThenCompileTest.h.

Referenced by TEST().

53  {
54  return [](Params...) -> Ret { return Ret(); };
55 }
template<class Ret , class... Params>
std::function<Ret(Params...)> folly::aStdFunction ( typename std::enable_if< isFuture< Ret >::value, bool >::type  = true)

Definition at line 58 of file ThenCompileTest.h.

References makeFuture(), and T.

59  {
60  typedef typename Ret::value_type T;
61  return [](Params...) -> Future<T> { return makeFuture(T()); };
62 }
#define T(v)
Definition: http_parser.c:233
Future< typename std::decay< T >::type > makeFuture(T &&t)
Definition: Future-inl.h:1310
void folly::asymmetricHeavyBarrier ( AMBFlags  flags)

Definition at line 83 of file AsymmetricMemoryBarrier.cpp.

References checkUnixError(), EXPEDITED, kIsLinux, folly::detail::sysMembarrier(), and folly::detail::sysMembarrierAvailable().

Referenced by asymmetricLightBarrier(), folly::hazptr_domain< DeterministicAtomic >::bulk_reclaim(), folly::detail::ThreadCachedInts< folly::detail::folly::detail::Tag >::readFull(), folly::ThreadPoolExecutor::tryTimeoutThread(), folly::TLRefCount::useGlobal(), and folly::detail::ThreadCachedInts< folly::detail::folly::detail::Tag >::waitForZero().

83  {
84  if (kIsLinux) {
85  static const bool useSysMembarrier = detail::sysMembarrierAvailable();
86  // sys_membarrier currently does not support EXPEDITED
87  if (useSysMembarrier && flags != AMBFlags::EXPEDITED) {
88  auto r = detail::sysMembarrier();
89  checkUnixError(r, "membarrier");
90  } else {
91  mprotectMembarrier();
92  }
93  } else {
94  std::atomic_thread_fence(std::memory_order_seq_cst);
95  }
96 }
flags
Definition: http_parser.h:127
bool sysMembarrierAvailable()
void checkUnixError(ssize_t ret, Args &&...args)
Definition: Exception.h:101
constexpr auto kIsLinux
Definition: Portability.h:361
template<class F >
auto folly::async ( F &&  fn)

Definition at line 24 of file Async.h.

References getCPUExecutor().

Referenced by cmake_minimum_required(), and TEST().

24  {
25  return folly::via<F>(getCPUExecutor().get(), std::forward<F>(fn));
26 }
std::shared_ptr< Executor > getCPUExecutor()
template<typename Atomic >
bool folly::atomic_fetch_reset ( Atomic &  atomic,
std::size_t  bit,
std::memory_order  order = std::memory_order_seq_cst 
)

Resets a bit at the given index in the binary representation of the integer to 0. Returns the previous value of the bit, so true if the bit was changed, false otherwise

This follows the same underlying principle and implementation as fetch_set(). Using the optimized implementation when possible and falling back to std::atomic::fetch_and() when in debug mode or in an architecture where an optimization is not possible

Definition at line 253 of file AtomicUtil-inl.h.

References folly::detail::atomic_fetch_reset_default(), folly::detail::atomic_fetch_reset_x86(), and kIsArchAmd64.

253  {
254  using Integer = decltype(atomic.load());
255  static_assert(std::is_unsigned<Integer>{}, "");
256  static_assert(!std::is_const<Atomic>{}, "");
257  assert(bit < (sizeof(Integer) * 8));
258 
259  if (folly::kIsArchAmd64) {
260  // do the optimized thing on x86 builds
261  return detail::atomic_fetch_reset_x86(atomic, bit, mo);
262  } else {
263  // otherwise default to the default implementation using fetch_and()
264  return detail::atomic_fetch_reset_default(atomic, bit, mo);
265  }
266 }
bool atomic_fetch_reset_default(Atomic &atomic, std::size_t bit, std::memory_order order)
bool atomic_fetch_reset_x86(Atomic &, std::size_t, std::memory_order) noexcept
constexpr bool kIsArchAmd64
Definition: Portability.h:102
template<typename Atomic >
bool folly::atomic_fetch_set ( Atomic &  atomic,
std::size_t  bit,
std::memory_order  order = std::memory_order_seq_cst 
)

Sets a bit at the given index in the binary representation of the integer to 1. Returns the previous value of the bit, so true if the bit was not changed, false otherwise

On some architectures, using this is more efficient than the corresponding std::atomic::fetch_or() with a mask. For example to set the first (least significant) bit of an integer, you could do atomic.fetch_or(0b1)

The efficiency win is only visible in x86 (yet) and comes from the implementation using the x86 bts instruction when possible.

When something other than std::atomic is passed, the implementation assumed incompatibility with this interface and calls Atomic::fetch_or()

Definition at line 237 of file AtomicUtil-inl.h.

References folly::detail::atomic_fetch_set_default(), folly::detail::atomic_fetch_set_x86(), and kIsArchAmd64.

Referenced by folly::detail::distributed_mutex::DistributedMutex< Atomic, TimePublishing >::try_lock().

237  {
238  using Integer = decltype(atomic.load());
239  static_assert(std::is_unsigned<Integer>{}, "");
240  static_assert(!std::is_const<Atomic>{}, "");
241  assert(bit < (sizeof(Integer) * 8));
242 
243  if (folly::kIsArchAmd64) {
244  // do the optimized thing on x86 builds
245  return detail::atomic_fetch_set_x86(atomic, bit, mo);
246  } else {
247  // otherwise default to the default implementation using fetch_or()
248  return detail::atomic_fetch_set_default(atomic, bit, mo);
249  }
250 }
bool atomic_fetch_set_default(Atomic &atomic, std::size_t bit, std::memory_order order)
constexpr bool kIsArchAmd64
Definition: Portability.h:102
bool atomic_fetch_set_x86(Atomic &, std::size_t, std::memory_order) noexcept
template<typename Integer >
void folly::atomic_notify_all ( const std::atomic< Integer > *  atomic)

Definition at line 144 of file AtomicNotification-inl.h.

References folly::detail::atomic_notification::atomic_notify_all_impl().

144  {
146 }
void atomic_notify_all_impl(const Atom< Integer, Args... > *atomic)
template<typename Integer >
void folly::atomic_notify_one ( const std::atomic< Integer > *  atomic)
template<typename Integer >
void folly::atomic_wait ( const std::atomic< Integer > *  atomic,
Integer  expected 
)

The behavior of the atomic_wait() family of functions is semantically identical to futex(). Correspondingly, calling atomic_notify_one(), atomic_notify_all() is identical to futexWake() with 1 and std::numeric_limits<int>::max() respectively

The difference here compared to the futex API above is that it works with all types of atomic widths. When a 32 bit atomic integer is used, the implementation falls back to using futex() if possible, and the compatibility implementation for non-linux systems otherwise. For all other integer widths, the compatibility implementation is used

The templating of this API is changed from the standard in the following ways

  • At the time of writing, libstdc++'s implementation of std::atomic<> does not include the value_type alias. So we rely on the atomic type being a template class such that the first type is the underlying value type
  • The Atom parameter allows this API to be compatible with DeterministicSchedule testing.
  • atomic_wait_until() does not exist in the linked paper, the version here is identical to futexWaitUntil() and returns std::cv_status

Definition at line 125 of file AtomicNotification-inl.h.

References folly::detail::atomic_notification::atomic_wait_impl().

125  {
127 }
void atomic_wait_impl(const Atom< Integer, Args... > *atomic, Integer expected)
template<typename Integer , typename Clock , typename Duration >
std::cv_status folly::atomic_wait_until ( const std::atomic< Integer > *  atomic,
Integer  expected,
const std::chrono::time_point< Clock, Duration > &  deadline 
)

Definition at line 130 of file AtomicNotification-inl.h.

References folly::detail::atomic_notification::atomic_wait_until_impl().

Referenced by folly::detail::distributed_mutex::timedLock().

133  {
135  atomic, expected, deadline);
136 }
std::cv_status atomic_wait_until_impl(const Atom< Integer, Args... > *atomic, Integer expected, const std::chrono::time_point< Clock, Duration > &deadline)
template<class T , class A >
void folly::attach ( fbvector< T, A > &  v,
T data,
size_t  sz,
size_t  cap 
)

Definition at line 1751 of file FBVector.h.

References folly::fbvector< T, Allocator >::data().

Referenced by test_I_attach3().

1752  {
1753  assert(v.data() == nullptr);
1754  v.impl_.b_ = data;
1755  v.impl_.e_ = data + sz;
1756  v.impl_.z_ = data + cap;
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
template<bool implicit_unpack = true, typename Container >
back_emplace_iterator<Container, implicit_unpack> folly::back_emplacer ( Container &  c)

Convenience function to construct a folly::back_emplace_iterator, analogous to std::back_inserter().

Setting implicit_unpack to false will disable implicit unpacking of single std::pair and std::tuple arguments to the iterator's operator=. That may be desirable in case of constructors that expect a std::pair or std::tuple argument.

Examples:
/facebook/proxygen/proxygen/folly/folly/container/Iterator.h.

Definition at line 492 of file Iterator.h.

References c.

Referenced by TEST().

492  {
493  return back_emplace_iterator<Container, implicit_unpack>(c);
494 }
char c
template<class OutputString = std::string>
OutputString folly::backslashify ( StringPiece  input,
bool  hex_style = false 
)

Definition at line 219 of file String.h.

References backslashify(), humanify(), and gmock_output_test::output.

219  {
220  OutputString output;
221  backslashify(input, output, hex_style);
222  return output;
223 }
OutputString backslashify(StringPiece input, bool hex_style=false)
Definition: String.h:219
template<class OutputString >
void folly::backslashify ( folly::StringPiece  input,
OutputString &  output,
bool  hex_style = false 
)

Backslashify a string, that is, replace non-printable characters with C-style (but NOT C compliant) "\xHH" encoding. If hex_style is false, then shorthand notations like "\0" will be used instead of "\x00" for the most common backslash cases.

There are two forms, one returning the input string, and one creating output in the specified output string.

This is mainly intended for printing to a terminal, so it is not particularly optimized.

Do not use this in situations where you expect to be able to feed the string to a C or C++ compiler, as there are nuances with how C parses such strings that lead to failures. This is for display purposed only. If you want a string you can embed for use in C or C++, use cEscape instead. This function is for display purposes only.

Definition at line 507 of file String-inl.h.

References c, and folly::Range< Iter >::size().

Referenced by backslashify(), humanify(), TEST(), and uriUnescape().

510  {
511  static const char hexValues[] = "0123456789abcdef";
512  output.clear();
513  output.reserve(3 * input.size());
514  for (unsigned char c : input) {
515  // less than space or greater than '~' are considered unprintable
516  if (c < 0x20 || c > 0x7e || c == '\\') {
517  bool hex_append = false;
518  output.push_back('\\');
519  if (hex_style) {
520  hex_append = true;
521  } else {
522  if (c == '\r') {
523  output += 'r';
524  } else if (c == '\n') {
525  output += 'n';
526  } else if (c == '\t') {
527  output += 't';
528  } else if (c == '\a') {
529  output += 'a';
530  } else if (c == '\b') {
531  output += 'b';
532  } else if (c == '\0') {
533  output += '0';
534  } else if (c == '\\') {
535  output += '\\';
536  } else {
537  hex_append = true;
538  }
539  }
540  if (hex_append) {
541  output.push_back('x');
542  output.push_back(hexValues[(c >> 4) & 0xf]);
543  output.push_back(hexValues[c & 0xf]);
544  }
545  } else {
546  output += c;
547  }
548  }
549 }
constexpr size_type size() const
Definition: Range.h:431
char c
template<typename RefCount >
void folly::basicTest ( )

Definition at line 25 of file RefCountTest.cpp.

References b, count, EXPECT_EQ, EXPECT_TRUE, i, folly::Baton< MayBlock, Atom >::post(), folly::pushmi::detail::t, and folly::Baton< MayBlock, Atom >::wait().

Referenced by GenericFilterTest< Owned >::getRandomFilters(), and TEST_F().

25  {
26  constexpr size_t numIters = 100000;
27  constexpr size_t numThreads = 10;
28 
29  size_t got0 = 0;
30 
31  RefCount count;
32 
34 
35  std::vector<std::thread> ts;
36  folly::Baton<> threadBatons[numThreads];
37  for (size_t t = 0; t < numThreads; ++t) {
38  ts.emplace_back([&count, &b, &got0, t, &threadBatons] {
39  for (size_t i = 0; i < numIters; ++i) {
40  auto ret = ++count;
41 
42  EXPECT_TRUE(ret > 1);
43  if (i == 0) {
44  threadBatons[t].post();
45  }
46  }
47 
48  if (t == 0) {
49  b.post();
50  }
51 
52  for (size_t i = 0; i < numIters; ++i) {
53  auto ret = --count;
54 
55  if (ret == 0) {
56  ++got0;
57  EXPECT_EQ(numIters - 1, i);
58  }
59  }
60  });
61  }
62 
63  for (size_t t = 0; t < numThreads; ++t) {
64  threadBatons[t].wait();
65  }
66 
67  b.wait();
68 
69  count.useGlobal();
70  if (--count == 0) {
71  ++got0;
72  }
73 
74  for (auto& t : ts) {
75  t.join();
76  }
77 
78  EXPECT_EQ(1, got0);
79 
80  EXPECT_EQ(0, ++count);
81  EXPECT_EQ(0, ++count);
82 }
char b
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
FOLLY_ALWAYS_INLINE void wait(const WaitOptions &opt=wait_options()) noexcept
Definition: Baton.h:170
void post() noexcept
Definition: Baton.h:123
int * count
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
template<typename Counter , size_t threadCount>
void folly::benchmark ( size_t  n)

Definition at line 32 of file RefCountBenchmark.cpp.

References i, shutdown(), folly::pushmi::detail::t, and x.

32  {
33  Counter x;
34 
35  std::vector<std::thread> ts;
36 
37  for (size_t t = 0; t < threadCount; ++t) {
38  ts.emplace_back([&]() {
39  for (size_t i = 0; i < n; ++i) {
40  ++x;
41  }
42  for (size_t i = 0; i < n; ++i) {
43  --x;
44  }
45  });
46  }
47 
48  for (auto& t : ts) {
49  t.join();
50  }
51 
52  shutdown(x);
53 }
const int x
void shutdown(TLRefCount &c)
folly::BENCHMARK ( TLRefCountOneThread  ,
 
)

Definition at line 55 of file RefCountBenchmark.cpp.

55  {
56  benchmark<TLRefCount, 1>(n);
57 }
folly::BENCHMARK ( TLRefCountFourThreads  ,
 
)

Definition at line 59 of file RefCountBenchmark.cpp.

59  {
60  benchmark<TLRefCount, 4>(n);
61 }
folly::BENCHMARK ( fbFollyGlobalBenchmarkBaseline  )

Definition at line 84 of file Benchmark.cpp.

Referenced by BENCHMARK(), folly::test::TEST(), and TEST().

84  {
85 #ifdef _MSC_VER
86  _ReadWriteBarrier();
87 #else
88  asm volatile("");
89 #endif
90 }
folly::BENCHMARK ( SmallFunctionFunctionPointerInvoke  ,
iters   
)

Definition at line 127 of file FunctionRefBenchmark.cpp.

References f.

127  {
128  using FPtr = size_t (*)(size_t&);
129  runSmallInvokeBenchmark(iters, [](auto& f) { return FPtr{f}; });
130 }
auto f
folly::BENCHMARK ( SmallFunctionStdFunctionInvoke  ,
iters   
)

Definition at line 131 of file FunctionRefBenchmark.cpp.

References f.

131  {
132  runSmallInvokeBenchmark(
133  iters, [](auto& f) { return std::function<size_t(size_t&)>{f}; });
134 }
auto f
folly::BENCHMARK ( SmallFunctionStdFunctionWithReferenceWrapperInvoke  ,
iters   
)

Definition at line 135 of file FunctionRefBenchmark.cpp.

References f.

135  {
136  runSmallInvokeBenchmark(iters, [](auto& f) {
137  return std::function<size_t(size_t&)>{std::ref(f)};
138  });
139 }
auto f
folly::BENCHMARK ( SmallFunctionFollyFunctionInvoke  ,
iters   
)

Definition at line 140 of file FunctionRefBenchmark.cpp.

References f.

140  {
141  runSmallInvokeBenchmark(
142  iters, [](auto& f) { return folly::Function<size_t(size_t&)>{f}; });
143 }
auto f
folly::BENCHMARK ( SmallFunctionFollyFunctionRefInvoke  ,
iters   
)

Definition at line 144 of file FunctionRefBenchmark.cpp.

References BENCHMARK_DRAW_LINE(), and f.

144  {
145  runSmallInvokeBenchmark(
146  iters, [](auto& f) { return folly::FunctionRef<size_t(size_t&)>{f}; });
147 }
auto f
A reference wrapper for callable objects.
Definition: Function.h:893
folly::BENCHMARK ( SmallFunctionFunctionPointerCreateInvoke  ,
iters   
)

Definition at line 150 of file FunctionRefBenchmark.cpp.

References f.

150  {
151  using FPtr = size_t (*)(size_t&);
152  runSmallCreateAndInvokeBenchmark(iters, [](auto& f) { return FPtr{f}; });
153 }
auto f
folly::BENCHMARK ( SmallFunctionStdFunctionCreateInvoke  ,
iters   
)

Definition at line 154 of file FunctionRefBenchmark.cpp.

References f.

154  {
155  runSmallCreateAndInvokeBenchmark(
156  iters, [](auto& f) { return std::function<size_t(size_t&)>{f}; });
157 }
auto f
folly::BENCHMARK ( SmallFunctionStdFunctionReferenceWrapperCreateInvoke  ,
iters   
)

Definition at line 158 of file FunctionRefBenchmark.cpp.

References f.

158  {
159  runSmallCreateAndInvokeBenchmark(iters, [](auto& f) {
160  return std::function<size_t(size_t&)>{std::ref(f)};
161  });
162 }
auto f
folly::BENCHMARK ( SmallFunctionFollyFunctionCreateInvoke  ,
iters   
)

Definition at line 163 of file FunctionRefBenchmark.cpp.

References f.

163  {
164  runSmallCreateAndInvokeBenchmark(
165  iters, [](auto& f) { return folly::Function<size_t(size_t&)>{f}; });
166 }
auto f
folly::BENCHMARK ( SmallFunctionFollyFunctionRefCreateInvoke  ,
iters   
)

Definition at line 167 of file FunctionRefBenchmark.cpp.

References BENCHMARK_DRAW_LINE(), and f.

167  {
168  runSmallCreateAndInvokeBenchmark(
169  iters, [](auto& f) { return folly::FunctionRef<size_t(size_t&)>{f}; });
170 }
auto f
A reference wrapper for callable objects.
Definition: Function.h:893
folly::BENCHMARK ( BigFunctionStdFunctionInvoke  ,
iters   
)

Definition at line 173 of file FunctionRefBenchmark.cpp.

References f.

173  {
174  runBigAndInvokeBenchmark(
175  iters, [](auto& f) { return std::function<size_t(size_t&)>{f}; });
176 }
auto f
folly::BENCHMARK ( BigFunctionStdFunctionReferenceWrapperInvoke  ,
iters   
)

Definition at line 177 of file FunctionRefBenchmark.cpp.

References f.

177  {
178  runBigAndInvokeBenchmark(iters, [](auto& f) {
179  return std::function<size_t(size_t&)>{std::ref(f)};
180  });
181 }
auto f
folly::BENCHMARK ( BigFunctionFollyFunctionInvoke  ,
iters   
)

Definition at line 182 of file FunctionRefBenchmark.cpp.

References f.

182  {
183  runBigAndInvokeBenchmark(
184  iters, [](auto& f) { return folly::Function<size_t(size_t&)>{f}; });
185 }
auto f
folly::BENCHMARK ( BigFunctionFollyFunctionRefInvoke  ,
iters   
)

Definition at line 186 of file FunctionRefBenchmark.cpp.

References BENCHMARK_DRAW_LINE(), and f.

186  {
187  runBigAndInvokeBenchmark(
188  iters, [](auto& f) { return folly::FunctionRef<size_t(size_t&)>{f}; });
189 }
auto f
A reference wrapper for callable objects.
Definition: Function.h:893
folly::BENCHMARK ( BigFunctionStdFunctionCreateInvoke  ,
iters   
)

Definition at line 192 of file FunctionRefBenchmark.cpp.

References f.

192  {
193  runBigCreateAndInvokeBenchmark(
194  iters, [](auto& f) { return std::function<size_t(size_t&)>{f}; });
195 }
auto f
folly::BENCHMARK ( BigFunctionStdFunctionReferenceWrapperCreateInvoke  ,
iters   
)

Definition at line 196 of file FunctionRefBenchmark.cpp.

References f.

196  {
197  runBigCreateAndInvokeBenchmark(iters, [](auto& f) {
198  return std::function<size_t(size_t&)>{std::ref(f)};
199  });
200 }
auto f
folly::BENCHMARK ( BigFunctionFollyFunctionCreateInvoke  ,
iters   
)

Definition at line 201 of file FunctionRefBenchmark.cpp.

References f.

201  {
202  runBigCreateAndInvokeBenchmark(
203  iters, [](auto& f) { return folly::Function<size_t(size_t&)>{f}; });
204 }
auto f
folly::BENCHMARK ( BigFunctionFollyFunctionRefCreateInvoke  ,
iters   
)

Definition at line 205 of file FunctionRefBenchmark.cpp.

References f.

205  {
206  runBigCreateAndInvokeBenchmark(
207  iters, [](auto& f) { return folly::FunctionRef<size_t(size_t&)>{f}; });
208 }
auto f
A reference wrapper for callable objects.
Definition: Function.h:893
void folly::benchmarkResultsFromDynamic ( const dynamic d,
vector< detail::BenchmarkResult > &  results 
)

Definition at line 357 of file Benchmark.cpp.

Referenced by makeUnpredictable(), and resultsFromFile().

359  {
360  for (auto& datum : d) {
361  results.push_back(
362  {datum[0].asString(), datum[1].asString(), datum[2].asDouble()});
363  }
364 }
void folly::benchmarkResultsToDynamic ( const vector< detail::BenchmarkResult > &  data,
dynamic out 
)

Definition at line 348 of file Benchmark.cpp.

References folly::dynamic::push_back().

Referenced by makeUnpredictable(), and printBenchmarkResultsAsVerboseJson().

350  {
351  out = dynamic::array;
352  for (auto& datum : data) {
353  out.push_back(dynamic::array(datum.file, datum.name, datum.timeInNs));
354  }
355 }
vector<detail::BenchmarkRegistration>& folly::benchmarks ( )

Definition at line 75 of file Benchmark.cpp.

Referenced by getGlobalBenchmarkBaselineIndex(), and runBenchmarks().

75  {
76  static vector<detail::BenchmarkRegistration> _benchmarks;
77  return _benchmarks;
78 }
template<typename T >
T folly::bitReverse ( T  n)

Definition at line 369 of file Bits.h.

References m, folly::Endian::swap(), T, and type.

Referenced by BENCHMARK(), and TEST().

369  {
370  auto m = static_cast<typename std::make_unsigned<T>::type>(n);
371  m = ((m & 0xAAAAAAAAAAAAAAAA) >> 1) | ((m & 0x5555555555555555) << 1);
372  m = ((m & 0xCCCCCCCCCCCCCCCC) >> 2) | ((m & 0x3333333333333333) << 2);
373  m = ((m & 0xF0F0F0F0F0F0F0F0) >> 4) | ((m & 0x0F0F0F0F0F0F0F0F) << 4);
374  return static_cast<T>(Endian::swap(m));
375 }
#define T(v)
Definition: http_parser.c:233
PskType type
static map< string, int > m
void swap(SwapTrackingAlloc< T > &, SwapTrackingAlloc< T > &)
Definition: F14TestUtil.h:414
template<>
const CacheLocality& folly::CacheLocality::system< std::atomic > ( )

Definition at line 61 of file CacheLocality.cpp.

References getSystemLocalityInfo().

61  {
62  static auto* cache = new CacheLocality(getSystemLocalityInfo());
63  return *cache;
64 }
static CacheLocality getSystemLocalityInfo()
Returns the best real CacheLocality information available.

Definition at line 423 of file DeterministicSchedule.cpp.

References folly::CacheLocality::uniform().

423  {
424  static CacheLocality cache(CacheLocality::uniform(16));
425  return cache;
426 }
template<typename Mutex , template< typename > class Atom, typename F , typename... Args>
FOLLY_ALWAYS_INLINE void folly::call_once ( basic_once_flag< Mutex, Atom > &  flag,
F &&  f,
Args &&...  args 
)
bool folly::canSetCurrentThreadName ( )

This returns true if the current platform supports setting the name of the current thread.

Definition at line 71 of file ThreadName.cpp.

71  {
72 #if FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME || \
73  FOLLY_HAS_PTHREAD_SETNAME_NP_NAME || _WIN32
74  return true;
75 #else
76  return false;
77 #endif
78 }
bool folly::canSetOtherThreadName ( )

This returns true if the current platform supports setting the name of threads other than the one currently executing.

Definition at line 80 of file ThreadName.cpp.

80  {
81 #if FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME || _WIN32
82  return true;
83 #else
84  return false;
85 #endif
86 }
template<class String >
void folly::cEscape ( StringPiece  str,
String &  out 
)

C-Escape a string, making it suitable for representation as a C string literal. Appends the result to the output string.

Backslashes all occurrences of backslash and double-quote: " -> \" \ -> \

Replaces all non-printable ASCII characters with backslash-octal representation: <ASCII 254> -> \376

Note that we use backslash-octal instead of backslash-hex because the octal representation is guaranteed to consume no more than 3 characters; "\3760" represents two characters, one with value 254, and one with value 48 ('0'), whereas "\xfe0" represents only one character (with value 4064, which leads to implementation-defined behavior).

Definition at line 39 of file String-inl.h.

References folly::Range< Iter >::begin(), c, folly::detail::cEscapeTable, folly::detail::cUnescapeTable, folly::Range< Iter >::end(), folly::detail::hexTable, folly::Range< Iter >::size(), and v.

Referenced by cEscape(), and toStdString().

39  {
40  char esc[4];
41  esc[0] = '\\';
42  out.reserve(out.size() + str.size());
43  auto p = str.begin();
44  auto last = p; // last regular character
45  // We advance over runs of regular characters (printable, not double-quote or
46  // backslash) and copy them in one go; this is faster than calling push_back
47  // repeatedly.
48  while (p != str.end()) {
49  char c = *p;
50  unsigned char v = static_cast<unsigned char>(c);
51  char e = detail::cEscapeTable[v];
52  if (e == 'P') { // printable
53  ++p;
54  } else if (e == 'O') { // octal
55  out.append(&*last, size_t(p - last));
56  esc[1] = '0' + ((v >> 6) & 7);
57  esc[2] = '0' + ((v >> 3) & 7);
58  esc[3] = '0' + (v & 7);
59  out.append(esc, 4);
60  ++p;
61  last = p;
62  } else { // special 1-character escape
63  out.append(&*last, size_t(p - last));
64  esc[1] = e;
65  out.append(esc, 2);
66  ++p;
67  last = p;
68  }
69  }
70  out.append(&*last, size_t(p - last));
71 }
auto v
const std::array< char, 256 > cEscapeTable
Definition: String.cpp:116
char c
template<class String >
String folly::cEscape ( StringPiece  str)

Similar to cEscape above, but returns the escaped string.

Definition at line 80 of file String.h.

References cEscape(), and cUnescape().

80  {
81  String out;
82  cEscape(str, out);
83  return out;
84 }
String cEscape(StringPiece str)
Definition: String.h:80
void* folly::checkedCalloc ( size_t  n,
size_t  size 
)
inline

Definition at line 235 of file Malloc.h.

235  {
236  void* p = calloc(n, size);
237  if (!p) {
238  throw_exception<std::bad_alloc>();
239  }
240  return p;
241 }
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
void* folly::checkedMalloc ( size_t  size)
inline

Trivial wrappers around malloc, calloc, realloc that check for allocation failure and throw std::bad_alloc in that case.

Definition at line 227 of file Malloc.h.

Referenced by folly::IOBuf::allocExtBuffer(), folly::fbstring_core< Char >::copyMedium(), folly::fbstring_core< Char >::RefCounted::create(), folly::IOBuf::createCombined(), folly::fbvector< T, Allocator >::Impl::D_allocate(), folly::fbstring_core< Char >::initMedium(), folly::small_vector< Observer< T > *, InlineObservers >::makeSizeInternal(), folly::IOBuf::operator new(), folly::IOBuf::reserveSlow(), folly::fbstring_core< Char >::reserveSmall(), and smartRealloc().

227  {
228  void* p = malloc(size);
229  if (!p) {
230  throw_exception<std::bad_alloc>();
231  }
232  return p;
233 }
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
void* folly::checkedRealloc ( void *  ptr,
size_t  size 
)
inline

Definition at line 243 of file Malloc.h.

Referenced by smartRealloc().

243  {
244  void* p = realloc(ptr, size);
245  if (!p) {
246  throw_exception<std::bad_alloc>();
247  }
248  return p;
249 }
void * ptr
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
template<class... Args>
void folly::checkFopenError ( FILE fp,
Args &&...  args 
)

Definition at line 118 of file Exception.h.

References testing::Args(), throwSystemError(), and UNLIKELY.

Referenced by folly::File::temporary(), and folly::test::TEST().

118  {
119  if (UNLIKELY(!fp)) {
120  throwSystemError(std::forward<Args>(args)...);
121  }
122 }
void throwSystemError(Args &&...args)
Definition: Exception.h:76
#define UNLIKELY(x)
Definition: Likely.h:48
template<class... Args>
void folly::checkFopenErrorExplicit ( FILE fp,
int  savedErrno,
Args &&...  args 
)

Definition at line 125 of file Exception.h.

References throwSystemErrorExplicit(), and UNLIKELY.

Referenced by folly::test::TEST().

125  {
126  if (UNLIKELY(!fp)) {
127  throwSystemErrorExplicit(savedErrno, std::forward<Args>(args)...);
128  }
129 }
void throwSystemErrorExplicit(int err, Args &&...args)
Definition: Exception.h:70
#define UNLIKELY(x)
Definition: Likely.h:48
template<class... Args>
void folly::checkKernelError ( ssize_t  ret,
Args &&...  args 
)

Definition at line 92 of file Exception.h.

References testing::Args(), throwSystemErrorExplicit(), and UNLIKELY.

Referenced by folly::AsyncIO::initializeContext(), and folly::test::TEST().

92  {
93  if (UNLIKELY(ret < 0)) {
94  throwSystemErrorExplicit(int(-ret), std::forward<Args>(args)...);
95  }
96 }
void throwSystemErrorExplicit(int err, Args &&...args)
Definition: Exception.h:70
#define UNLIKELY(x)
Definition: Likely.h:48
template<class... Args>
void folly::checkPosixError ( int  err,
Args &&...  args 
)
void folly::checkRunMode ( )

Definition at line 448 of file Benchmark.cpp.

References kIsDebug, and kIsSanitize.

Referenced by runBenchmarks().

448  {
450  std::cerr << "WARNING: Benchmark running "
451  << (folly::kIsDebug ? "in DEBUG mode" : "with SANITIZERS")
452  << std::endl;
453  }
454 }
constexpr auto kIsDebug
Definition: Portability.h:264
constexpr bool kIsSanitize
Definition: Portability.h:130
bool folly::checkTimeout ( const TimePoint start,
const TimePoint end,
std::chrono::nanoseconds  expected,
bool  allowSmaller,
std::chrono::nanoseconds  tolerance = std::chrono::milliseconds(5) 
)
bool folly::checkTimeout ( const TimePoint start,
const TimePoint end,
nanoseconds  expected,
bool  allowSmaller,
nanoseconds  tolerance 
)

Definition at line 241 of file TimeUtil.cpp.

References folly::TimePoint::getTid(), folly::TimePoint::getTimeEnd(), folly::TimePoint::getTimeStart(), and folly::TimePoint::getTimeWaiting().

246  {
247  auto elapsedTime = end.getTimeStart() - start.getTimeEnd();
248 
249  if (!allowSmaller) {
250  // Timeouts should never fire before the time was up.
251  // Allow 1ms of wiggle room for rounding errors.
252  if (elapsedTime < (expected - milliseconds(1))) {
253  return false;
254  }
255  }
256 
257  // Check that the event fired within a reasonable time of the timout.
258  //
259  // If the system is under heavy load, our process may have had to wait for a
260  // while to be run. The time spent waiting for the processor shouldn't
261  // count against us, so exclude this time from the check.
262  nanoseconds timeExcluded;
263  if (end.getTid() != start.getTid()) {
264  // We can only correctly compute the amount of time waiting to be scheduled
265  // if both TimePoints were set in the same thread.
266  timeExcluded = nanoseconds(0);
267  } else {
268  timeExcluded = end.getTimeWaiting() - start.getTimeWaiting();
269  assert(end.getTimeWaiting() >= start.getTimeWaiting());
270  // Add a tolerance here due to precision issues on linux, see below note.
271  assert((elapsedTime + tolerance) >= timeExcluded);
272  }
273 
274  nanoseconds effectiveElapsedTime(0);
275  if (elapsedTime > timeExcluded) {
276  effectiveElapsedTime = elapsedTime - timeExcluded;
277  }
278 
279  // On x86 Linux, sleep calls generally have precision only to the nearest
280  // millisecond. The tolerance parameter lets users allow a few ms of slop.
281  auto overrun = effectiveElapsedTime - expected;
282  if (overrun > tolerance) {
283  return false;
284  }
285 
286  return true;
287 }
auto end(TestAdlIterable &instance)
Definition: ForeachTest.cpp:62
auto start
template<class... Args>
void folly::checkUnixErrorExplicit ( ssize_t  ret,
int  savedErrno,
Args &&...  args 
)

Definition at line 108 of file Exception.h.

References testing::Args(), throwSystemErrorExplicit(), and UNLIKELY.

Referenced by folly::test::TEST().

108  {
109  if (UNLIKELY(ret == -1)) {
110  throwSystemErrorExplicit(savedErrno, std::forward<Args>(args)...);
111  }
112 }
void throwSystemErrorExplicit(int err, Args &&...args)
Definition: Exception.h:70
#define UNLIKELY(x)
Definition: Likely.h:48
static double folly::clamp ( double  v,
double  lo,
double  hi 
)
static

Definition at line 70 of file TDigest.cpp.

References v.

Referenced by folly::TDigest::estimateQuantile().

70  {
71  if (v > hi) {
72  return hi;
73  } else if (v < lo) {
74  return lo;
75  }
76  return v;
77 }
auto v
bool folly::clientProtoFilterPickNone ( unsigned char **  ,
unsigned int *  ,
const unsigned char *  ,
unsigned  int 
)

Definition at line 171 of file AsyncSSLSocketTest.cpp.

175  {
176  return false;
177 }
bool folly::clientProtoFilterPickPony ( unsigned char **  client,
unsigned int *  client_len,
const unsigned char *  ,
unsigned  int 
)

Definition at line 158 of file AsyncSSLSocketTest.cpp.

162  {
163  // the protocol string in length prefixed byte string. the
164  // length byte is not included in the length
165  static unsigned char p[7] = {6, 'p', 'o', 'n', 'i', 'e', 's'};
166  *client = p;
167  *client_len = 7;
168  return true;
169 }
int folly::closeNoInt ( NetworkSocket  fd)

Definition at line 60 of file FileUtil.cpp.

References folly::netops::close(), and filterCloseReturn().

60  {
61  return filterCloseReturn(netops::close(fd));
62 }
static int filterCloseReturn(int r)
Definition: FileUtil.cpp:40
int close(NetworkSocket s)
Definition: NetOps.cpp:90
std::string folly::codePointToUtf8 ( char32_t  cp)

Definition at line 24 of file Unicode.cpp.

References string.

24  {
25  std::string result;
26 
27  // Based on description from http://en.wikipedia.org/wiki/UTF-8.
28 
29  if (cp <= 0x7f) {
30  result.resize(1);
31  result[0] = static_cast<char>(cp);
32  } else if (cp <= 0x7FF) {
33  result.resize(2);
34  result[1] = static_cast<char>(0x80 | (0x3f & cp));
35  result[0] = static_cast<char>(0xC0 | (cp >> 6));
36  } else if (cp <= 0xFFFF) {
37  result.resize(3);
38  result[2] = static_cast<char>(0x80 | (0x3f & cp));
39  result[1] = (0x80 | static_cast<char>((0x3f & (cp >> 6))));
40  result[0] = (0xE0 | static_cast<char>(cp >> 12));
41  } else if (cp <= 0x10FFFF) {
42  result.resize(4);
43  result[3] = static_cast<char>(0x80 | (0x3f & cp));
44  result[2] = static_cast<char>(0x80 | (0x3f & (cp >> 6)));
45  result[1] = static_cast<char>(0x80 | (0x3f & (cp >> 12)));
46  result[0] = static_cast<char>(0xF0 | (cp >> 18));
47  }
48 
49  return result;
50 }
const char * string
Definition: Conv.cpp:212
template<class Collection >
auto folly::collect ( Collection &&  c) -> decltype(collect(c.begin(), c.end()))

Sugar for the most common case.

Definition at line 344 of file helpers.h.

References c, collect(), and collectAny().

344  {
345  return collect(c.begin(), c.end());
346 }
static auto collect
Definition: StringTest.cpp:37
char c
template<class InputIterator >
Future< std::vector< typename std::iterator_traits< InputIterator >::value_type::value_type > > folly::collect ( InputIterator  first,
InputIterator  last 
)

Like collectAll, but will short circuit on the first exception. Thus, the type of the returned Future is std::vector<T> instead of std::vector<Try<T>>

Definition at line 1536 of file Future-inl.h.

References folly::gen::first, i, folly::InlineExecutor::instance(), folly::gen::move, folly::futures::detail::FutureBase< T >::result(), folly::pushmi::detail::t, T, and folly::pushmi::operators::transform.

Referenced by collect(), collectAll(), complexBenchmark(), folly::detail::ThreadCachedLists< Tag >::ListHead::forEach(), folly::FutureDAG::go(), folly::futures::test::TEST(), TEST(), TEST_F(), TEST_P(), and folly::TLRefCount::LocalRefCount::~LocalRefCount().

1536  {
1537  using F = typename std::iterator_traits<InputIterator>::value_type;
1538  using T = typename F::value_type;
1539 
1540  struct Context {
1541  explicit Context(size_t n) : result(n) {
1542  finalResult.reserve(n);
1543  }
1544  ~Context() {
1545  if (!threw.load(std::memory_order_relaxed)) {
1546  // map Optional<T> -> T
1548  result.begin(),
1549  result.end(),
1550  std::back_inserter(finalResult),
1551  [](Optional<T>& o) { return std::move(o.value()); });
1552  p.setValue(std::move(finalResult));
1553  }
1554  }
1555  Promise<std::vector<T>> p;
1556  std::vector<Optional<T>> result;
1557  std::vector<T> finalResult;
1558  std::atomic<bool> threw{false};
1559  };
1560 
1561  auto ctx = std::make_shared<Context>(std::distance(first, last));
1562  for (size_t i = 0; first != last; ++first, ++i) {
1563  first->setCallback_([i, ctx](Try<T>&& t) {
1564  if (t.hasException()) {
1565  if (!ctx->threw.exchange(true, std::memory_order_relaxed)) {
1566  ctx->p.setException(std::move(t.exception()));
1567  }
1568  } else if (!ctx->threw.load(std::memory_order_relaxed)) {
1569  ctx->result[i] = std::move(t.value());
1570  }
1571  });
1572  }
1573  return ctx->p.getSemiFuture().via(&InlineExecutor::instance());
1574 }
#define T(v)
Definition: http_parser.c:233
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
PUSHMI_INLINE_VAR constexpr detail::transform_fn transform
Definition: transform.h:158
constexpr detail::First first
Definition: Base-inl.h:2553
template<typename... Fs>
Future< std::tuple< typename remove_cvref_t< Fs >::value_type... > > folly::collect ( Fs &&...  fs)

Like collectAll, but will short circuit on the first exception. Thus, the type of the returned Future is std::tuple<T1, T2, ...> instead of std::tuple<Try<T1>, Try<T2>, ...>

Definition at line 1580 of file Future-inl.h.

References f, folly::futures::detail::foreach(), folly::pushmi::operators::get, i, folly::InlineExecutor::instance(), folly::gen::move, folly::pushmi::detail::t, and unwrapTryTuple().

1581  {
1582  using Result = std::tuple<typename remove_cvref_t<Fs>::value_type...>;
1583  struct Context {
1584  ~Context() {
1585  if (!threw.load(std::memory_order_relaxed)) {
1586  p.setValue(unwrapTryTuple(std::move(results)));
1587  }
1588  }
1589  Promise<Result> p;
1590  std::tuple<Try<typename remove_cvref_t<Fs>::value_type>...> results;
1591  std::atomic<bool> threw{false};
1592  };
1593 
1594  auto ctx = std::make_shared<Context>();
1596  [&](auto i, auto&& f) {
1597  f.setCallback_([i, ctx](auto&& t) {
1598  if (t.hasException()) {
1599  if (!ctx->threw.exchange(true, std::memory_order_relaxed)) {
1600  ctx->p.setException(std::move(t.exception()));
1601  }
1602  } else if (!ctx->threw.load(std::memory_order_relaxed)) {
1603  std::get<i.value>(ctx->results) = std::move(t);
1604  }
1605  });
1606  },
1607  static_cast<Fs&&>(fs)...);
1608  return ctx->p.getSemiFuture().via(&InlineExecutor::instance());
1609 }
auto f
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN void foreach(V &&v, Fs &&...fs)
Definition: Future-inl.h:1387
PUSHMI_INLINE_VAR constexpr detail::get_fn< T > get
Definition: submit.h:391
auto unwrapTryTuple(Tuple &&instance)
Definition: Try-inl.h:320
template<class Collection >
auto folly::collectAll ( Collection &&  c) -> decltype(collectAll(c.begin(), c.end()))

Definition at line 319 of file helpers.h.

References c, collect(), collectAll(), and collectAllSemiFuture().

319  {
320  return collectAll(c.begin(), c.end());
321 }
char c
auto collectAll(Collection &&c) -> decltype(collectAll(c.begin(), c.end()))
Definition: helpers.h:319
template<typename... Fs>
Future< std::tuple< Try< typename remove_cvref_t< Fs >::value_type >... > > folly::collectAll ( Fs &&...  fs)

Definition at line 1477 of file Future-inl.h.

References collectAllSemiFuture().

Referenced by collectAll(), collectAllSemiFuture(), complexBenchmark(), and TEST().

1478  {
1479  return collectAllSemiFuture(std::forward<Fs>(fs)...).toUnsafeFuture();
1480 }
SemiFuture< std::vector< Try< typename std::iterator_traits< InputIterator >::value_type::value_type > > > collectAllSemiFuture(InputIterator first, InputIterator last)
Definition: Future-inl.h:1487
template<class InputIterator >
Future< std::vector< Try< typename std::iterator_traits< InputIterator >::value_type::value_type > > > folly::collectAll ( InputIterator  first,
InputIterator  last 
)

Definition at line 1526 of file Future-inl.h.

References collectAllSemiFuture().

1526  {
1527  return collectAllSemiFuture(first, last).toUnsafeFuture();
1528 }
SemiFuture< std::vector< Try< typename std::iterator_traits< InputIterator >::value_type::value_type > > > collectAllSemiFuture(InputIterator first, InputIterator last)
Definition: Future-inl.h:1487
constexpr detail::First first
Definition: Base-inl.h:2553
template<class Collection >
auto folly::collectAllSemiFuture ( Collection &&  c) -> decltype(collectAllSemiFuture(c.begin(), c.end()))

Sugar for the most common case.

Definition at line 308 of file helpers.h.

References c, collectAll(), and collectAllSemiFuture().

309  {
310  return collectAllSemiFuture(c.begin(), c.end());
311 }
auto collectAllSemiFuture(Collection &&c) -> decltype(collectAllSemiFuture(c.begin(), c.end()))
Sugar for the most common case.
Definition: helpers.h:308
char c
template<typename... Fs>
SemiFuture< std::tuple< Try< typename remove_cvref_t< Fs >::value_type >... > > folly::collectAllSemiFuture ( Fs &&...  fs)

This version takes a varying number of Futures instead of an iterator. The return type for (Future<T1>, Future<T2>, ...) input is a Future<std::tuple<Try<T1>, Try<T2>, ...>>. The Futures are moved in, so your copies are invalid.

Definition at line 1441 of file Future-inl.h.

References f, folly::futures::detail::foreach(), folly::pushmi::operators::get, folly::futures::detail::getDeferredExecutor(), i, folly::gen::move, folly::futures::detail::stealDeferredExecutorsVariadic(), and folly::pushmi::detail::t.

Referenced by collectAll(), collectAllSemiFuture(), folly::SemiFuture< T >::delayed(), folly::Future< T >::delayed(), doubleBatchOuterDispatch(), folly::futures::map(), reduce(), TEST(), and folly::Future< T >::willEqual().

1441  {
1442  using Result = std::tuple<Try<typename remove_cvref_t<Fs>::value_type>...>;
1443  struct Context {
1444  ~Context() {
1445  p.setValue(std::move(results));
1446  }
1447  Promise<Result> p;
1448  Result results;
1449  };
1450 
1451  std::vector<folly::Executor::KeepAlive<futures::detail::DeferredExecutor>>
1452  executors;
1454 
1455  auto ctx = std::make_shared<Context>();
1457  [&](auto i, auto&& f) {
1458  f.setCallback_([i, ctx](auto&& t) {
1459  std::get<i.value>(ctx->results) = std::move(t);
1460  });
1461  },
1462  static_cast<Fs&&>(fs)...);
1463 
1464  auto future = ctx->p.getSemiFuture();
1465  if (!executors.empty()) {
1466  auto work = [](Try<typename decltype(future)::value_type>&& t) {
1467  return std::move(t).value();
1468  };
1469  future = std::move(future).defer(work);
1470  auto deferredExecutor = futures::detail::getDeferredExecutor(future);
1471  deferredExecutor->setNestedExecutors(std::move(executors));
1472  }
1473  return future;
1474 }
auto f
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
DeferredExecutor * getDeferredExecutor(SemiFuture< T > &future)
Definition: Future-inl.h:1395
FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN void foreach(V &&v, Fs &&...fs)
Definition: Future-inl.h:1387
PUSHMI_INLINE_VAR constexpr detail::get_fn< T > get
Definition: submit.h:391
void stealDeferredExecutorsVariadic(std::vector< folly::Executor::KeepAlive< DeferredExecutor >> &executors, Ts &...ts)
Definition: Future-inl.h:1411
template<class InputIterator >
SemiFuture< std::vector< Try< typename std::iterator_traits< InputIterator >::value_type::value_type > > > folly::collectAllSemiFuture ( InputIterator  first,
InputIterator  last 
)

When all the input Futures complete, the returned Future will complete. Errors do not cause early termination; this Future will always succeed after all its Futures have finished (whether successfully or with an error).

The Futures are moved in, so your copies are invalid. If you need to chain further from these Futures, use the variant with an output iterator.

This function is thread-safe for Futures running on different threads. But if you are doing anything non-trivial after, you will probably want to follow with via(executor) because it will complete in whichever thread the last Future completes in.

The return type for Future<T> input is a Future<std::vector<Try<T>>>

Definition at line 1487 of file Future-inl.h.

References folly::gen::first, folly::futures::detail::getDeferredExecutor(), i, folly::gen::move, folly::futures::detail::stealDeferredExecutors(), folly::pushmi::detail::t, and T.

1487  {
1488  using F = typename std::iterator_traits<InputIterator>::value_type;
1489  using T = typename F::value_type;
1490 
1491  struct Context {
1492  explicit Context(size_t n) : results(n) {}
1493  ~Context() {
1494  p.setValue(std::move(results));
1495  }
1496  Promise<std::vector<Try<T>>> p;
1497  std::vector<Try<T>> results;
1498  };
1499 
1500  std::vector<folly::Executor::KeepAlive<futures::detail::DeferredExecutor>>
1501  executors;
1503 
1504  auto ctx = std::make_shared<Context>(size_t(std::distance(first, last)));
1505 
1506  for (size_t i = 0; first != last; ++first, ++i) {
1507  first->setCallback_(
1508  [i, ctx](Try<T>&& t) { ctx->results[i] = std::move(t); });
1509  }
1510 
1511  auto future = ctx->p.getSemiFuture();
1512  if (!executors.empty()) {
1513  future = std::move(future).defer(
1514  [](Try<typename decltype(future)::value_type>&& t) {
1515  return std::move(t).value();
1516  });
1517  auto deferredExecutor = futures::detail::getDeferredExecutor(future);
1518  deferredExecutor->setNestedExecutors(std::move(executors));
1519  }
1520  return future;
1521 }
#define T(v)
Definition: http_parser.c:233
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
DeferredExecutor * getDeferredExecutor(SemiFuture< T > &future)
Definition: Future-inl.h:1395
void stealDeferredExecutors(std::vector< folly::Executor::KeepAlive< DeferredExecutor >> &executors, InputIterator first, InputIterator last)
Definition: Future-inl.h:1424
constexpr detail::First first
Definition: Base-inl.h:2553
template<class Collection >
auto folly::collectAny ( Collection &&  c) -> decltype(collectAny(c.begin(), c.end()))

Sugar for the most common case.

Definition at line 369 of file helpers.h.

References c, collectAny(), and collectAnyWithoutException().

369  {
370  return collectAny(c.begin(), c.end());
371 }
auto collectAny(Collection &&c) -> decltype(collectAny(c.begin(), c.end()))
Sugar for the most common case.
Definition: helpers.h:369
char c
template<class InputIterator >
Future< std::pair< size_t, Try< typename std::iterator_traits< InputIterator >::value_type::value_type > > > folly::collectAny ( InputIterator  first,
InputIterator  last 
)

The result is a pair of the index of the first Future to complete and the Try. If multiple Futures complete at the same time (or are already complete when passed in), the "winner" is chosen non-deterministically.

This function is thread-safe for Futures running on different threads.

Definition at line 1618 of file Future-inl.h.

References folly::gen::first, folly::Promise< T >::getSemiFuture(), i, folly::InlineExecutor::instance(), folly::gen::move, folly::pushmi::detail::t, and T.

Referenced by collect(), collectAny(), complexBenchmark(), and TEST().

1618  {
1619  using F = typename std::iterator_traits<InputIterator>::value_type;
1620  using T = typename F::value_type;
1621 
1622  struct Context {
1623  Promise<std::pair<size_t, Try<T>>> p;
1624  std::atomic<bool> done{false};
1625  };
1626 
1627  auto ctx = std::make_shared<Context>();
1628  for (size_t i = 0; first != last; ++first, ++i) {
1629  first->setCallback_([i, ctx](Try<T>&& t) {
1630  if (!ctx->done.exchange(true, std::memory_order_relaxed)) {
1631  ctx->p.setValue(std::make_pair(i, std::move(t)));
1632  }
1633  });
1634  }
1635  return ctx->p.getSemiFuture().via(&InlineExecutor::instance());
1636 }
#define T(v)
Definition: http_parser.c:233
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
constexpr detail::First first
Definition: Base-inl.h:2553
template<class Collection >
auto folly::collectAnyWithoutException ( Collection &&  c) -> decltype(collectAnyWithoutException(c.begin(), c.end()))

Sugar for the most common case.

Definition at line 385 of file helpers.h.

References c, collectAnyWithoutException(), and collectN().

386  {
387  return collectAnyWithoutException(c.begin(), c.end());
388 }
auto collectAnyWithoutException(Collection &&c) -> decltype(collectAnyWithoutException(c.begin(), c.end()))
Sugar for the most common case.
Definition: helpers.h:385
char c
template<class InputIterator >
SemiFuture< std::pair< size_t, typename std::iterator_traits< InputIterator >::value_type::value_type > > folly::collectAnyWithoutException ( InputIterator  first,
InputIterator  last 
)

Similar to collectAny, collectAnyWithoutException return the first Future to complete without exceptions. If none of the future complete without excpetions, the last exception will be returned as a result.

Definition at line 1644 of file Future-inl.h.

References folly::gen::first, folly::futures::detail::getDeferredExecutor(), i, folly::gen::move, folly::futures::detail::stealDeferredExecutors(), folly::pushmi::detail::t, and T.

Referenced by collectAny(), collectAnyWithoutException(), and TEST().

1644  {
1645  using F = typename std::iterator_traits<InputIterator>::value_type;
1646  using T = typename F::value_type;
1647 
1648  struct Context {
1649  Context(size_t n) : nTotal(n) {}
1650  Promise<std::pair<size_t, T>> p;
1651  std::atomic<bool> done{false};
1652  std::atomic<size_t> nFulfilled{0};
1653  size_t nTotal;
1654  };
1655 
1656  std::vector<folly::Executor::KeepAlive<futures::detail::DeferredExecutor>>
1657  executors;
1659 
1660  auto ctx = std::make_shared<Context>(size_t(std::distance(first, last)));
1661  for (size_t i = 0; first != last; ++first, ++i) {
1662  first->setCallback_([i, ctx](Try<T>&& t) {
1663  if (!t.hasException() &&
1664  !ctx->done.exchange(true, std::memory_order_relaxed)) {
1665  ctx->p.setValue(std::make_pair(i, std::move(t.value())));
1666  } else if (
1667  ctx->nFulfilled.fetch_add(1, std::memory_order_relaxed) + 1 ==
1668  ctx->nTotal) {
1669  ctx->p.setException(t.exception());
1670  }
1671  });
1672  }
1673 
1674  auto future = ctx->p.getSemiFuture();
1675  if (!executors.empty()) {
1676  future = std::move(future).defer(
1677  [](Try<typename decltype(future)::value_type>&& t) {
1678  return std::move(t).value();
1679  });
1680  auto deferredExecutor = futures::detail::getDeferredExecutor(future);
1681  deferredExecutor->setNestedExecutors(std::move(executors));
1682  }
1683  return future;
1684 }
#define T(v)
Definition: http_parser.c:233
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
DeferredExecutor * getDeferredExecutor(SemiFuture< T > &future)
Definition: Future-inl.h:1395
void stealDeferredExecutors(std::vector< folly::Executor::KeepAlive< DeferredExecutor >> &executors, InputIterator first, InputIterator last)
Definition: Future-inl.h:1424
constexpr detail::First first
Definition: Base-inl.h:2553
template<class Collection >
auto folly::collectN ( Collection &&  c,
size_t  n 
) -> decltype(collectN(c.begin(), c.end(), n))

Sugar for the most common case.

Definition at line 404 of file helpers.h.

References c, collectN(), and window().

405  {
406  return collectN(c.begin(), c.end(), n);
407 }
auto collectN(Collection &&c, size_t n) -> decltype(collectN(c.begin(), c.end(), n))
Sugar for the most common case.
Definition: helpers.h:404
char c
template<class InputIterator >
SemiFuture< std::vector< std::pair< size_t, Try< typename std::iterator_traits< InputIterator >::value_type::value_type > > > > folly::collectN ( InputIterator  first,
InputIterator  last,
size_t  n 
)

when n Futures have completed, the Future completes with a vector of the index and Try of those n Futures (the indices refer to the original order, but the result vector will be in an arbitrary order)

Not thread safe.

Definition at line 1692 of file Future-inl.h.

References c, folly::gen::first, i, min, min_, folly::gen::move, folly::futures::detail::FutureBase< T >::result(), s, folly::futures::detail::FutureBase< T >::setCallback_(), folly::pushmi::detail::t, T, v, and folly::futures::detail::FutureBase< T >::value().

Referenced by collectAnyWithoutException(), collectN(), and TEST().

1692  {
1693  using F = typename std::iterator_traits<InputIterator>::value_type;
1694  using T = typename F::value_type;
1695  using Result = std::vector<std::pair<size_t, Try<T>>>;
1696 
1697  struct Context {
1698  explicit Context(size_t numFutures, size_t min_)
1699  : v(numFutures), min(min_) {}
1700 
1701  std::vector<Optional<Try<T>>> v;
1702  size_t min;
1703  std::atomic<size_t> completed = {0}; // # input futures completed
1704  std::atomic<size_t> stored = {0}; // # output values stored
1705  Promise<Result> p;
1706  };
1707 
1708  assert(n > 0);
1709  assert(std::distance(first, last) >= 0);
1710 
1711  if (size_t(std::distance(first, last)) < n) {
1712  return SemiFuture<Result>(
1713  exception_wrapper(std::runtime_error("Not enough futures")));
1714  }
1715 
1716  // for each completed Future, increase count and add to vector, until we
1717  // have n completed futures at which point we fulfil our Promise with the
1718  // vector
1719  auto ctx = std::make_shared<Context>(size_t(std::distance(first, last)), n);
1720  for (size_t i = 0; first != last; ++first, ++i) {
1721  first->setCallback_([i, ctx](Try<T>&& t) {
1722  // relaxed because this guards control but does not guard data
1723  auto const c = 1 + ctx->completed.fetch_add(1, std::memory_order_relaxed);
1724  if (c > ctx->min) {
1725  return;
1726  }
1727  ctx->v[i] = std::move(t);
1728 
1729  // release because the stored values in all threads must be visible below
1730  // acquire because no stored value is permitted to be fetched early
1731  auto const s = 1 + ctx->stored.fetch_add(1, std::memory_order_acq_rel);
1732  if (s < ctx->min) {
1733  return;
1734  }
1735  Result result;
1736  result.reserve(ctx->completed.load());
1737  for (size_t j = 0; j < ctx->v.size(); ++j) {
1738  auto& entry = ctx->v[j];
1739  if (entry.hasValue()) {
1740  result.emplace_back(j, std::move(entry).value());
1741  }
1742  }
1743  ctx->p.setTry(Try<Result>(std::move(result)));
1744  });
1745  }
1746 
1747  return ctx->p.getSemiFuture();
1748 }
#define T(v)
Definition: http_parser.c:233
auto v
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const int min_
LogLevel min
Definition: LogLevel.cpp:30
static const char *const value
Definition: Conv.cpp:50
static set< string > s
char c
constexpr detail::First first
Definition: Base-inl.h:2553
template<class T , class A >
void folly::compactResize ( fbvector< T, A > *  v,
size_t  sz 
)

Definition at line 1715 of file FBVector.h.

1716  {
1717  v->resize(sz);
1718  v->shrink_to_fit();
void folly::compareBenchmarkResults ( const std::string base,
const std::string test 
)

Definition at line 34 of file BenchmarkCompare.cpp.

References printResultComparison(), and resultsFromFile().

Referenced by main().

34  {
36 }
vector< detail::BenchmarkResult > resultsFromFile(const std::string &filename)
void printResultComparison(const vector< detail::BenchmarkResult > &base, const vector< detail::BenchmarkResult > &test)
Definition: Benchmark.cpp:371
bool folly::compareDynamicWithTolerance ( const dynamic obj1,
const dynamic obj2,
double  tolerance 
)

Like compareJsonWithTolerance, but operates directly on the dynamics.

Definition at line 42 of file JsonTestUtil.cpp.

References folly::dynamic::asBool(), folly::dynamic::asDouble(), folly::dynamic::asInt(), folly::dynamic::asString(), assume_unreachable(), folly::dynamic::begin(), folly::dynamic::end(), folly::dynamic::get_ptr(), folly::dynamic::isInt(), folly::dynamic::isNumber(), folly::dynamic::items(), folly::dynamic::size(), STRING, and folly::dynamic::type().

Referenced by compareJsonWithTolerance().

45  {
46  if (obj1.type() != obj2.type()) {
47  if (obj1.isNumber() && obj2.isNumber()) {
48  const auto& integ = obj1.isInt() ? obj1 : obj2;
49  const auto& doubl = obj1.isInt() ? obj2 : obj1;
50  // Use to<double> to fail on precision loss for very large
51  // integers (in which case the comparison does not make sense).
52  return isClose(to<double>(integ.asInt()), doubl.asDouble(), tolerance);
53  }
54  return false;
55  }
56 
57  switch (obj1.type()) {
58  case dynamic::Type::NULLT:
59  return true;
60  case dynamic::Type::ARRAY:
61  if (obj1.size() != obj2.size()) {
62  return false;
63  }
64  for (auto i1 = obj1.begin(), i2 = obj2.begin(); i1 != obj1.end();
65  ++i1, ++i2) {
66  if (!compareDynamicWithTolerance(*i1, *i2, tolerance)) {
67  return false;
68  }
69  }
70  return true;
71  case dynamic::Type::BOOL:
72  return obj1.asBool() == obj2.asBool();
73  case dynamic::Type::DOUBLE:
74  return isClose(obj1.asDouble(), obj2.asDouble(), tolerance);
75  case dynamic::Type::INT64:
76  return obj1.asInt() == obj2.asInt();
77  case dynamic::Type::OBJECT:
78  if (obj1.size() != obj2.size()) {
79  return false;
80  }
81 
82  return std::all_of(
83  obj1.items().begin(), obj1.items().end(), [&](const auto& item) {
84  const auto& value1 = item.second;
85  const auto value2 = obj2.get_ptr(item.first);
86  return value2 &&
87  compareDynamicWithTolerance(value1, *value2, tolerance);
88  });
90  return obj1.asString() == obj2.asString();
91  }
92 
94 }
#define STRING
bool compareDynamicWithTolerance(const dynamic &obj1, const dynamic &obj2, double tolerance)
bool folly::compareJson ( StringPiece  json1,
StringPiece  json2 
)

Compares two JSON strings and returns whether they represent the same document (thus ignoring things like object ordering or multiple representations of the same number).

This is implemented by deserializing both strings into dynamic, so it is not efficient and it is meant to only be used in tests.

It will throw an exception if any of the inputs is invalid.

Definition at line 28 of file JsonTestUtil.cpp.

References parseJson().

Referenced by TEST().

28  {
29  auto obj1 = parseJson(json1);
30  auto obj2 = parseJson(json2);
31  return obj1 == obj2;
32 }
dynamic parseJson(StringPiece range)
Definition: json.cpp:900
bool folly::compareJsonWithTolerance ( StringPiece  json1,
StringPiece  json2,
double  tolerance 
)

Like compareJson, but allows for the given tolerance when comparing numbers.

Note that in the dynamic flavor of JSON 64-bit integers are a supported type. If the values to be compared are both integers, tolerance is not applied (it may not be possible to represent them as double without loss of precision).

When comparing objects exact key match is required, including if keys are doubles (again a dynamic extension).

Definition at line 96 of file JsonTestUtil.cpp.

References compareDynamicWithTolerance(), and parseJson().

Referenced by TEST().

99  {
100  auto obj1 = parseJson(json1);
101  auto obj2 = parseJson(json2);
102  return compareDynamicWithTolerance(obj1, obj2, tolerance);
103 }
dynamic parseJson(StringPiece range)
Definition: json.cpp:900
bool compareDynamicWithTolerance(const dynamic &obj1, const dynamic &obj2, double tolerance)
template<typename ReturnType , typename... Args>
Function< ReturnType(Args...) const > folly::constCastFunction ( Function< ReturnType(Args...)> &&  that)
noexcept

NOTE: See detailed note about constCastFunction at the top of the file. This is potentially dangerous and requires the equivalent of a const_cast.

Definition at line 845 of file Function.h.

References testing::Args(), and folly::gen::move.

Referenced by constCastFunction(), and TEST().

846  {
847  return Function<ReturnType(Args...) const>{std::move(that),
848  detail::function::CoerceTag{}};
849 }
A polymorphic function wrapper that is not copyable and does not require the wrapped function to be c...
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
internal::ArgsMatcher< InnerMatcher > Args(const InnerMatcher &matcher)
const
Definition: upload.py:398
template<typename ReturnType , typename... Args>
Function<ReturnType(Args...) const> folly::constCastFunction ( Function< ReturnType(Args...) const > &&  that)
noexcept

Definition at line 852 of file Function.h.

References testing::Args(), constCastFunction(), and folly::gen::move.

853  {
854  return std::move(that);
855 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<typename T >
constexpr auto folly::constexpr_abs ( T  t) -> decltype(detail::constexpr_abs_helper<T>::go(t))

Definition at line 135 of file ConstexprMath.h.

References folly::pushmi::detail::t.

Referenced by TEST_F().

136  {
137  return detail::constexpr_abs_helper<T>::go(t);
138 }
template<typename T >
constexpr T folly::constexpr_add_overflow_clamped ( T  a,
T  b 
)

Definition at line 217 of file ConstexprMath.h.

References constexpr_clamp(), constexpr_max(), constexpr_min(), M, max, min, T, and value.

Referenced by constexpr_sub_overflow_clamped(), NoOverflowAdd(), and TEST_F().

217  {
218  using L = std::numeric_limits<T>;
219  using M = std::intmax_t;
220  static_assert(
221  !std::is_integral<T>::value || sizeof(T) <= sizeof(M),
222  "Integral type too large!");
223  // clang-format off
224  return
225  // don't do anything special for non-integral types.
227  // for narrow integral types, just convert to intmax_t.
228  sizeof(T) < sizeof(M)
229  ? T(constexpr_clamp(M(a) + M(b), M(L::min()), M(L::max()))) :
230  // when a >= 0, cannot add more than `MAX - a` onto a.
231  !(a < 0) ? a + constexpr_min(b, T(L::max() - a)) :
232  // a < 0 && b >= 0, `a + b` will always be in valid range of type T.
233  !(b < 0) ? a + b :
234  // a < 0 && b < 0, keep the result >= MIN.
235  a + constexpr_max(b, T(L::min() - a));
236  // clang-format on
237 }
constexpr T const & constexpr_clamp(T const &v, T const &lo, T const &hi)
Definition: ConstexprMath.h:93
#define T(v)
Definition: http_parser.c:233
char b
LogLevel max
Definition: LogLevel.cpp:31
constexpr T constexpr_max(T a, T b, Ts...ts)
Definition: ConstexprMath.h:72
LogLevel min
Definition: LogLevel.cpp:30
char a
static const char *const value
Definition: Conv.cpp:50
**Optimized Holders **The template hazptr_array< M > provides most of the functionality *of M hazptr_holder s but with faster construction destruction *for M
Definition: Hazptr.h:104
constexpr T constexpr_min(T a, T b, Ts...ts)
Definition: ConstexprMath.h:83
template<typename T >
constexpr T folly::constexpr_ceil ( T  t,
T  round 
)

Definition at line 168 of file ConstexprMath.h.

References folly::chrono::round(), and T.

Referenced by TEST_F().

168  {
169  return round == T(0)
170  ? t
171  : ((t + (t < T(0) ? T(0) : round - T(1))) / round) * round;
172 }
#define T(v)
Definition: http_parser.c:233
constexpr To round(std::chrono::duration< Rep, Period > const &d)
Definition: Chrono.h:139
template<typename T , typename Less >
constexpr T const& folly::constexpr_clamp ( T const &  v,
T const &  lo,
T const &  hi,
Less  less 
)

Definition at line 89 of file ConstexprMath.h.

References v.

Referenced by constexpr_add_overflow_clamped(), constexpr_clamp(), constexpr_clamp_cast(), constexpr_sub_overflow_clamped(), folly::LogCategory::setLevelLocked(), and TEST_F().

89  {
90  return less(v, lo) ? lo : less(hi, v) ? hi : v;
91 }
auto v
template<typename T >
constexpr T const& folly::constexpr_clamp ( T const &  v,
T const &  lo,
T const &  hi 
)

Definition at line 93 of file ConstexprMath.h.

References constexpr_clamp().

93  {
94  return constexpr_clamp(v, lo, hi, constexpr_less<T>{});
95 }
constexpr T const & constexpr_clamp(T const &v, T const &lo, T const &hi)
Definition: ConstexprMath.h:93
template<typename Dst , typename Src >
constexpr std::enable_if<std::is_integral<Src>::value, Dst>::type folly::constexpr_clamp_cast ( Src  src)

Definition at line 303 of file ConstexprMath.h.

References constexpr_clamp(), constexpr_min(), int64_t, max, min, and value.

Referenced by constexpr_clamp_cast().

303  {
304  static_assert(
305  std::is_integral<Dst>::value && sizeof(Dst) <= sizeof(int64_t),
306  "constexpr_clamp_cast can only cast into integral type (up to 64bit)");
307 
308  using L = std::numeric_limits<Dst>;
309  // clang-format off
310  return
311  // Check if Src and Dst have same signedness.
313  ? (
314  // Src and Dst have same signedness. If sizeof(Src) <= sizeof(Dst),
315  // we can safely convert Src to Dst without any loss of accuracy.
316  sizeof(Src) <= sizeof(Dst) ? Dst(src) :
317  // If Src is larger in size, we need to clamp it to valid range in Dst.
318  Dst(constexpr_clamp(src, Src(L::min()), Src(L::max()))))
319  // Src and Dst have different signedness.
320  // Check if it's signed -> unsigend cast.
321  : std::is_signed<Src>::value && std::is_unsigned<Dst>::value
322  ? (
323  // If src < 0, the result should be 0.
324  src < 0 ? Dst(0) :
325  // Otherwise, src >= 0. If src can fit into Dst, we can safely cast it
326  // without loss of accuracy.
327  sizeof(Src) <= sizeof(Dst) ? Dst(src) :
328  // If Src is larger in size than Dst, we need to ensure the result is
329  // at most Dst MAX.
330  Dst(constexpr_min(src, Src(L::max()))))
331  // It's unsigned -> signed cast.
332  : (
333  // Since Src is unsigned, and Dst is signed, Src can fit into Dst only
334  // when sizeof(Src) < sizeof(Dst).
335  sizeof(Src) < sizeof(Dst) ? Dst(src) :
336  // If Src does not fit into Dst, we need to ensure the result is at most
337  // Dst MAX.
338  Dst(constexpr_min(src, Src(L::max()))));
339  // clang-format on
340 }
constexpr T const & constexpr_clamp(T const &v, T const &lo, T const &hi)
Definition: ConstexprMath.h:93
struct folly::detail::LastElementImpl sizeof
LogLevel max
Definition: LogLevel.cpp:31
STL namespace.
LogLevel min
Definition: LogLevel.cpp:30
static const char *const value
Definition: Conv.cpp:50
constexpr T constexpr_min(T a, T b, Ts...ts)
Definition: ConstexprMath.h:83
template<typename Dst , typename Src >
constexpr std::enable_if<std::is_floating_point<Src>::value, Dst>::type folly::constexpr_clamp_cast ( Src  src)

Definition at line 363 of file ConstexprMath.h.

References constexpr_clamp_cast(), folly::detail::constexpr_clamp_cast_helper(), int64_t, folly::detail::kClampCastLowerBoundDoubleToInt64F, folly::detail::kClampCastLowerBoundFloatToInt32F, folly::detail::kClampCastUpperBoundDoubleToInt64F, folly::detail::kClampCastUpperBoundDoubleToUInt64F, folly::detail::kClampCastUpperBoundFloatToInt32F, folly::detail::kClampCastUpperBoundFloatToUInt32F, max, min, uint64_t, and value.

363  {
364  static_assert(
365  std::is_integral<Dst>::value && sizeof(Dst) <= sizeof(int64_t),
366  "constexpr_clamp_cast can only cast into integral type (up to 64bit)");
367 
368  using L = std::numeric_limits<Dst>;
369  // clang-format off
370  return
371  // Special case: cast NaN into 0.
372  // Using a trick here to portably check for NaN: f != f only if f is NaN.
373  // see: https://stackoverflow.com/a/570694
374  (src != src) ? Dst(0) :
375  // using `sizeof(Src) > sizeof(Dst)` as a heuristic that Dst can be
376  // represented in Src without loss of accuracy.
377  // see: https://en.wikipedia.org/wiki/Floating-point_arithmetic
378  sizeof(Src) > sizeof(Dst) ?
380  src, Src(L::min()), Src(L::max()), L::min(), L::max()) :
381  // sizeof(Src) < sizeof(Dst) only happens when doing cast of
382  // 32bit float -> u/int64_t.
383  // Losslessly promote float into double, change into double -> u/int64_t.
384  sizeof(Src) < sizeof(Dst) ? (
385  src >= 0.0
386  ? constexpr_clamp_cast<Dst>(
387  constexpr_clamp_cast<std::uint64_t>(double(src)))
388  : constexpr_clamp_cast<Dst>(
389  constexpr_clamp_cast<std::int64_t>(double(src)))) :
390  // The following are for sizeof(Src) == sizeof(Dst).
391  std::is_same<Src, double>::value && std::is_same<Dst, int64_t>::value ?
393  double(src),
396  L::min(),
397  L::max()) :
398  std::is_same<Src, double>::value && std::is_same<Dst, uint64_t>::value ?
400  double(src),
401  0.0,
403  L::min(),
404  L::max()) :
405  std::is_same<Src, float>::value && std::is_same<Dst, int32_t>::value ?
407  float(src),
410  L::min(),
411  L::max()) :
413  float(src),
414  0.0f,
416  L::min(),
417  L::max());
418  // clang-format on
419 }
constexpr float kClampCastUpperBoundFloatToInt32F
auto f
constexpr double kClampCastUpperBoundDoubleToInt64F
struct folly::detail::LastElementImpl sizeof
LogLevel max
Definition: LogLevel.cpp:31
STL namespace.
constexpr std::enable_if< std::is_floating_point< Src >::value, Dst >::type constexpr_clamp_cast(Src src)
constexpr float kClampCastUpperBoundFloatToUInt32F
constexpr float kClampCastLowerBoundFloatToInt32F
LogLevel min
Definition: LogLevel.cpp:30
constexpr D constexpr_clamp_cast_helper(S src, S sl, S su, D dl, D du)
constexpr double kClampCastLowerBoundDoubleToInt64F
static const char *const value
Definition: Conv.cpp:50
constexpr double kClampCastUpperBoundDoubleToUInt64F
template<typename T >
constexpr std::size_t folly::constexpr_find_first_set ( T  t)

constexpr_find_first_set

Return the 1-based index of the least significant bit which is set. For x > 0, the exponent in the largest power of two which does not divide x.

Definition at line 208 of file ConstexprMath.h.

References folly::detail::constexpr_find_first_set_(), size(), folly::pushmi::detail::t, and T.

Referenced by TEST_F().

208  {
209  using U = std::make_unsigned_t<T>;
210  using size = std::integral_constant<std::size_t, sizeof(T) * 4>;
211  return t == T(0)
212  ? 0
213  : 1 + detail::constexpr_find_first_set_(size{}, 0, static_cast<U>(t));
214 }
#define T(v)
Definition: http_parser.c:233
constexpr std::size_t constexpr_find_first_set_(std::size_t s, std::size_t a, U const u)
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
template<typename T >
constexpr std::size_t folly::constexpr_find_last_set ( T const  t)

constexpr_find_last_set

Return the 1-based index of the most significant bit which is set. For x > 0, constexpr_find_last_set(x) == 1 + floor(log2(x)).

Definition at line 188 of file ConstexprMath.h.

References constexpr_log2(), and T.

Referenced by TEST_F().

188  {
189  using U = std::make_unsigned_t<T>;
190  return t == T(0) ? 0 : 1 + constexpr_log2(static_cast<U>(t));
191 }
#define T(v)
Definition: http_parser.c:233
constexpr T constexpr_log2(T t)
template<typename T >
constexpr T folly::constexpr_log2 ( T  t)
template<typename T >
constexpr T folly::constexpr_log2_ceil ( T  t)

Definition at line 163 of file ConstexprMath.h.

References constexpr_log2(), and folly::detail::constexpr_log2_ceil_().

Referenced by TEST_F().

163  {
165 }
constexpr T constexpr_log2(T t)
constexpr T constexpr_log2_ceil_(T l2, T t)
template<typename T >
constexpr T folly::constexpr_max ( T  a)
template<typename T , typename... Ts>
constexpr T folly::constexpr_max ( T  a,
T  b,
Ts...  ts 
)

Definition at line 72 of file ConstexprMath.h.

References constexpr_max().

72  {
73  return b < a ? constexpr_max(a, ts...) : constexpr_max(b, ts...);
74 }
char b
constexpr T constexpr_max(T a, T b, Ts...ts)
Definition: ConstexprMath.h:72
char a
template<typename T , typename... Ts>
constexpr T folly::constexpr_min ( T  a,
T  b,
Ts...  ts 
)

Definition at line 83 of file ConstexprMath.h.

References constexpr_min(), and T.

83  {
84  return b < a ? constexpr_min(b, ts...) : constexpr_min(a, ts...);
85 }
char b
char a
constexpr T constexpr_min(T a, T b, Ts...ts)
Definition: ConstexprMath.h:83
template<typename T >
constexpr T folly::constexpr_pow ( T  base,
std::size_t  exp 
)

Definition at line 175 of file ConstexprMath.h.

References folly::detail::constexpr_square_(), and T.

Referenced by folly::detail::format_table_conv_make_item< Base, Size, Upper >::make_item::operator()(), and TEST_F().

175  {
176  return exp == 0
177  ? T(1)
178  : exp == 1 ? base
179  : detail::constexpr_square_(constexpr_pow(base, exp / 2)) *
180  (exp % 2 ? base : T(1));
181 }
#define T(v)
Definition: http_parser.c:233
constexpr T constexpr_pow(T base, std::size_t exp)
constexpr T constexpr_square_(T t)
template<typename Char >
constexpr int folly::constexpr_strcmp ( const Char *  s1,
const Char *  s2 
)

Definition at line 75 of file Constexpr.h.

References folly::detail::constexpr_strcmp_internal().

Referenced by TEST().

75  {
76  return detail::constexpr_strcmp_internal(s1, s2);
77 }
constexpr int constexpr_strcmp_internal(const Char *s1, const Char *s2)
Definition: Constexpr.h:49
template<>
constexpr int folly::constexpr_strcmp ( const char *  s1,
const char *  s2 
)

Definition at line 80 of file Constexpr.h.

References folly::detail::constexpr_strcmp_internal().

80  {
81 #if FOLLY_HAS_FEATURE(cxx_constexpr_string_builtins)
82  // clang provides a constexpr builtin
83  return __builtin_strcmp(s1, s2);
84 #elif defined(__GNUC__) && !defined(__clang__)
85  // strcmp() happens to already be constexpr under gcc
86  return std::strcmp(s1, s2);
87 #else
88  return detail::constexpr_strcmp_internal(s1, s2);
89 #endif
90 }
constexpr int constexpr_strcmp_internal(const Char *s1, const Char *s2)
Definition: Constexpr.h:49
template<>
constexpr size_t folly::constexpr_strlen ( const char *  s)

Definition at line 62 of file Constexpr.h.

References folly::detail::constexpr_strlen_internal().

62  {
63 #if FOLLY_HAS_FEATURE(cxx_constexpr_string_builtins)
64  // clang provides a constexpr builtin
65  return __builtin_strlen(s);
66 #elif defined(__GNUC__) && !defined(__clang__)
67  // strlen() happens to already be constexpr under gcc
68  return std::strlen(s);
69 #else
71 #endif
72 }
constexpr size_t constexpr_strlen_internal(const Char *s, size_t len)
Definition: Constexpr.h:30
static set< string > s
template<typename T >
constexpr T folly::constexpr_sub_overflow_clamped ( T  a,
T  b 
)

Definition at line 240 of file ConstexprMath.h.

References b, constexpr_add_overflow_clamped(), constexpr_clamp(), M, max, min, T, type, and value.

Referenced by NoOverflowSub(), and TEST_F().

240  {
241  using L = std::numeric_limits<T>;
242  using M = std::intmax_t;
243  static_assert(
244  !std::is_integral<T>::value || sizeof(T) <= sizeof(M),
245  "Integral type too large!");
246  // clang-format off
247  return
248  // don't do anything special for non-integral types.
250  // for unsigned type, keep result >= 0.
251  std::is_unsigned<T>::value ? (a < b ? 0 : a - b) :
252  // for narrow signed integral types, just convert to intmax_t.
253  sizeof(T) < sizeof(M)
254  ? T(constexpr_clamp(M(a) - M(b), M(L::min()), M(L::max()))) :
255  // (a >= 0 && b >= 0) || (a < 0 && b < 0), `a - b` will always be valid.
256  (a < 0) == (b < 0) ? a - b :
257  // MIN < b, so `-b` should be in valid range (-MAX <= -b <= MAX),
258  // convert subtraction to addition.
260  // -b = -MIN = (MAX + 1) and a <= -1, result is in valid range.
261  a < 0 ? a - b :
262  // -b = -MIN = (MAX + 1) and a >= 0, result > MAX.
263  L::max();
264  // clang-format on
265 }
constexpr T const & constexpr_clamp(T const &v, T const &lo, T const &hi)
Definition: ConstexprMath.h:93
#define T(v)
Definition: http_parser.c:233
constexpr T constexpr_add_overflow_clamped(T a, T b)
char b
LogLevel max
Definition: LogLevel.cpp:31
LogLevel min
Definition: LogLevel.cpp:30
char a
static const char *const value
Definition: Conv.cpp:50
**Optimized Holders **The template hazptr_array< M > provides most of the functionality *of M hazptr_holder s but with faster construction destruction *for M
Definition: Hazptr.h:104
template<typename T >
T folly::convertTo ( const dynamic d)

Definition at line 394 of file DynamicConverter.h.

Referenced by TEST(), and toAppendStrImpl().

394  {
396 }
PskType type
template<>
wangle::SSLSessionCacheData folly::convertTo ( const dynamic d)

Definition at line 34 of file SSLSessionCacheData.cpp.

References wangle::SSLSessionCacheData::addedTime, folly::dynamic::asString(), data, folly::dynamic::getDefault(), wangle::SSLSessionCacheData::serviceIdentity, and wangle::SSLSessionCacheData::sessionData.

34  {
36  data.sessionData = d["session_data"].asString();
37  data.addedTime =
38  system_clock::time_point(system_clock::duration(d["added_time"].asInt()));
39  data.serviceIdentity = d.getDefault("service_identity", "").asString();
40  return data;
41 }
std::chrono::time_point< std::chrono::system_clock > addedTime
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
template<typename T >
constexpr std::decay<T>::type folly::copy ( T &&  value)
noexcept

copy

Usable when you have a function with two overloads:

class MyData;
void something(MyData&&);
void something(const MyData&);

Where the purpose is to make copies and moves explicit without having to spell out the full type names - in this case, for copies, to invoke copy constructors.

When the caller wants to pass a copy of an lvalue, the caller may:

void foo() {
  MyData data;
  something(folly::copy(data)); // explicit copy
  something(std::move(data)); // explicit move
  something(data); // const& - neither move nor copy
}

Note: If passed an rvalue, invokes the move-ctor, not the copy-ctor. This can be used to to force a move, where just using std::move would not:

std::copy(std::move(data)); // force-move, not just a cast to &&

Note: The following text appears in the standard:

In several places in this Clause the operation //DECAY_COPY(x)// is used. All such uses mean call the function decay_copy(x) and use the result, where decay_copy is defined as follows:

template <class t>=""> decay_t<T> decay_copy(T&& v) { return std::forward<T>(v); }

http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2014/n4296.pdf 30.2.6 decay_copy [thread.decaycopy].

We mimic it, with a noexcept specifier for good measure.

Definition at line 72 of file Utility.h.

References as_const(), and value().

Referenced by testing::ACTION_TEMPLATE(), allocate_unique(), folly::fbvector< HTTPHeaderCode >::assign(), BENCHMARK(), BENCHMARK_RELATIVE(), folly::detail::bulk_insert(), clause11_21_4_4(), clause11_21_4_6_1(), folly::BasicFixedString< Char, N >::copy(), folly::fbvector< HTTPHeaderCode >::erase(), folly::basic_fbstring< char >::erase(), folly::Function< std::vector< ResultT >(std::vector< InputT > &&)>::Function(), folly::Future< T >::get(), folly::ssl::OpenSSLUtils::getTLSClientRandom(), folly::ssl::OpenSSLUtils::getTLSMasterKey(), testing::internal::NativeArray< Element >::InitCopy(), folly::basic_fbstring< E, T, A, Storage >::insertImpl(), testing::internal::linked_ptr< const testing::MatcherInterface< const internal::string & > >::linked_ptr(), main(), merge(), folly::TDigest::merge(), deadlock.DiGraph::node_link_data(), folly::ThreadLocalPtr< T, Tag, AccessMode >::Accessor::Iterator::operator++(), folly::ThreadLocalPtr< T, Tag, AccessMode >::Accessor::Iterator::operator--(), folly::DelayedDestructionBase::IntrusivePtr< AliasType >::operator=(), testing::internal::linked_ptr< const testing::MatcherInterface< const internal::string & > >::operator=(), testing::internal::InvokeMethodAction< Class, MethodPtr >::Perform(), folly::TypedIOBuf< T >::push(), folly::Range< unsigned char * >::replaceAt(), folly::basic_fbstring< E, T, A, Storage >::replaceImpl(), folly::fbvector< HTTPHeaderCode >::resize(), runContendedReaders(), folly::EventBase::runInEventBaseThreadAndWait(), TEST(), TEST_F(), testCmp(), testRandom(), and folly::Function< std::vector< ResultT >(std::vector< InputT > &&)>::~Function().

73  {
74  return std::forward<T>(value);
75 }
static const char *const value
Definition: Conv.cpp:50
template<class Collection >
constexpr auto folly::crange ( Collection const &  v) -> Range<decltype(v.data())>

Definition at line 1131 of file Range.h.

Referenced by TEST().

1131  {
1132  return Range<decltype(v.data())>(v.data(), v.data() + v.size());
1133 }
template<class T , size_t n>
constexpr Range<T const*> folly::crange ( T const (&)  array[n])

Definition at line 1144 of file Range.h.

1144  {
1145  return Range<T const*>(array, array + n);
1146 }
template<class T , size_t n>
constexpr Range<T const*> folly::crange ( std::array< T, n > const &  array)

Definition at line 1157 of file Range.h.

1157  {
1158  return Range<T const*>{array};
1159 }
uint32_t folly::crc32 ( const uint8_t data,
size_t  nbytes,
uint32_t  startingChecksum = ~0U 
)

Compute the CRC-32 checksum of a buffer, using a hardware-accelerated implementation if available or a portable software implementation as a default.

Definition at line 136 of file Checksum.cpp.

References folly::detail::crc32_hw(), folly::detail::crc32_hw_supported(), folly::detail::crc32_sw(), and uint32_t.

Referenced by crc32_combine(), crc32_type(), and TEST().

136  {
138  return detail::crc32_hw(data, nbytes, startingChecksum);
139  } else {
140  return detail::crc32_sw(data, nbytes, startingChecksum);
141  }
142 }
uint32_t crc32_sw(const uint8_t *data, size_t nbytes, uint32_t startingChecksum)
Definition: Checksum.cpp:121
bool crc32_hw_supported()
Definition: Checksum.cpp:87
uint32_t crc32_hw(const uint8_t *, size_t, uint32_t)
Definition: Checksum.cpp:76
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
template<typename F >
static uint32_t folly::crc32_append_zeroes ( mult,
uint32_t  crc,
size_t  len,
uint32_t  polynomial,
std::array< uint32_t, 62 > const &  powers_array 
)
static

Definition at line 132 of file Crc32CombineDetail.cpp.

References findFirstSet().

Referenced by folly::detail::crc32_combine_hw(), folly::detail::crc32_combine_sw(), folly::detail::crc32c_combine_hw(), and folly::detail::crc32c_combine_sw().

137  {
138  auto powers = powers_array.data();
139 
140  // Append by multiplying by consecutive powers of two of the zeroes
141  // array
142  len >>= 2;
143 
144  while (len) {
145  // Advance directly to next bit set.
146  auto r = findFirstSet(len) - 1;
147  len >>= r;
148  powers += r;
149 
150  crc = mult(crc, *powers, polynomial);
151 
152  len >>= 1;
153  powers++;
154  }
155 
156  return crc;
157 }
BitIterator< BaseIter > findFirstSet(BitIterator< BaseIter >, BitIterator< BaseIter >)
Definition: BitIterator.h:170
uint32_t folly::crc32_combine ( uint32_t  crc1,
uint32_t  crc2,
size_t  crc2len 
)

Given two checksums, combine them in to one checksum.

Example: len1 len2 Given a buffer [ checksum 1 | checksum 2 ] such that the first buffer's crc is checksum1 and has length len1, and the remainder of the buffer's crc is checksum2 and len 2, a total checksum over the whole buffer can be made by:

crc32_combine(checksum1, checksum 2, len2); // len1 not needed.

Note that this is equivalent to:

crc32(buffer2, len2, crc32(buffer1, len1));

However, this allows calculating the checksums in parallel or calculating checksum 2 before checksum 1.

Additionally, this is also equivalent, but much slower: crc2 = crc32(buffer2, len2, 0); crc1 = crc32(buffer1, len1, 0); combined = crc2 ^ crc32(buffer_of_all_zeros, len2, crc1);

crc32[c]_combine is roughly ~10x faster than either of the other above two examples.

Definition at line 149 of file Checksum.cpp.

References crc32(), folly::detail::crc32_combine_hw(), folly::detail::crc32_combine_sw(), folly::detail::crc32_hw_supported(), and uint8_t.

Referenced by benchmarkCombineHardwareCrc32(), and TEST().

149  {
150  // Append up to 32 bits of zeroes in the normal way
151  uint8_t data[4] = {0, 0, 0, 0};
152  auto len = crc2len & 3;
153  if (len) {
154  crc1 = crc32(data, len, crc1);
155  }
156 
158  return detail::crc32_combine_hw(crc1, crc2, crc2len);
159  } else {
160  return detail::crc32_combine_sw(crc1, crc2, crc2len);
161  }
162 }
uint32_t crc32_combine_hw(uint32_t crc1, uint32_t crc2, size_t crc2len)
uint32_t crc32_combine_sw(uint32_t crc1, uint32_t crc2, size_t crc2len)
uint32_t crc32(const uint8_t *data, size_t nbytes, uint32_t startingChecksum)
Definition: Checksum.cpp:136
bool crc32_hw_supported()
Definition: Checksum.cpp:87
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
uint32_t folly::crc32_type ( const uint8_t data,
size_t  nbytes,
uint32_t  startingChecksum = ~0U 
)

Compute the CRC-32 checksum of a buffer, using a hardware-accelerated implementation if available or a portable software implementation as a default.

Note
compared to crc32(), crc32_type() uses a different set of default parameters to match the results returned by boost::crc_32_type and php's built-in crc32 implementation

Definition at line 145 of file Checksum.cpp.

References crc32().

145  {
146  return ~crc32(data, nbytes, startingChecksum);
147 }
uint32_t crc32(const uint8_t *data, size_t nbytes, uint32_t startingChecksum)
Definition: Checksum.cpp:136
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
uint32_t folly::crc32c ( const uint8_t data,
size_t  nbytes,
uint32_t  startingChecksum = ~0U 
)

Compute the CRC-32C checksum of a buffer, using a hardware-accelerated implementation if available or a portable software implementation as a default.

Note
CRC-32C is different from CRC-32; CRC-32C starts with a different polynomial and thus yields different results for the same input than a traditional CRC-32.

Definition at line 128 of file Checksum.cpp.

References folly::detail::crc32c_hw(), folly::detail::crc32c_hw_supported(), and folly::detail::crc32c_sw().

Referenced by benchmarkCombineSoftwareLinear(), crc32c_combine(), and TEST().

128  {
130  return detail::crc32c_hw(data, nbytes, startingChecksum);
131  } else {
132  return detail::crc32c_sw(data, nbytes, startingChecksum);
133  }
134 }
uint32_t crc32c_hw(const uint8_t *data, size_t nbytes, uint32_t startingChecksum=~0U)
uint32_t crc32c_sw(const uint8_t *data, size_t nbytes, uint32_t startingChecksum)
Definition: Checksum.cpp:115
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
bool crc32c_hw_supported()
Definition: Checksum.cpp:83
uint32_t folly::crc32c_combine ( uint32_t  crc1,
uint32_t  crc2,
size_t  crc2len 
)

Definition at line 164 of file Checksum.cpp.

References folly::detail::crc32_hw_supported(), crc32c(), folly::detail::crc32c_combine_hw(), folly::detail::crc32c_combine_sw(), and uint8_t.

Referenced by benchmarkCombineHardwareCrc32c(), and TEST().

164  {
165  // Append up to 32 bits of zeroes in the normal way
166  uint8_t data[4] = {0, 0, 0, 0};
167  auto len = crc2len & 3;
168  if (len) {
169  crc1 = crc32c(data, len, crc1);
170  }
171 
173  return detail::crc32c_combine_hw(crc1, crc2, crc2len - len);
174  } else {
175  return detail::crc32c_combine_sw(crc1, crc2, crc2len - len);
176  }
177 }
uint32_t crc32c(const uint8_t *data, size_t nbytes, uint32_t startingChecksum)
Definition: Checksum.cpp:128
uint32_t crc32c_combine_hw(uint32_t crc1, uint32_t crc2, size_t crc2len)
uint32_t crc32c_combine_sw(uint32_t crc1, uint32_t crc2, size_t crc2len)
bool crc32_hw_supported()
Definition: Checksum.cpp:87
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
template<class String >
void folly::cUnescape ( StringPiece  str,
String &  out,
bool  strict = true 
)

C-Unescape a string; the opposite of cEscape above. Appends the result to the output string.

Recognizes the standard C escape sequences:

\' " \? \
[0-7]+ [0-9a-fA-F]+

In strict mode (default), throws std::invalid_argument if it encounters an unrecognized escape sequence. In non-strict mode, it leaves the escape sequence unchanged.

Definition at line 86 of file String-inl.h.

References folly::Range< Iter >::begin(), c, folly::detail::cUnescapeTable, folly::Range< Iter >::end(), h, folly::detail::hexTable, i, folly::Range< Iter >::size(), folly::detail::uriEscapeTable, and val.

Referenced by cEscape(), and cUnescape().

86  {
87  out.reserve(out.size() + str.size());
88  auto p = str.begin();
89  auto last = p; // last regular character (not part of an escape sequence)
90  // We advance over runs of regular characters (not backslash) and copy them
91  // in one go; this is faster than calling push_back repeatedly.
92  while (p != str.end()) {
93  char c = *p;
94  if (c != '\\') { // normal case
95  ++p;
96  continue;
97  }
98  out.append(&*last, p - last);
99  ++p;
100  if (p == str.end()) { // backslash at end of string
101  if (strict) {
102  throw std::invalid_argument("incomplete escape sequence");
103  }
104  out.push_back('\\');
105  last = p;
106  continue;
107  }
108  char e = detail::cUnescapeTable[static_cast<unsigned char>(*p)];
109  if (e == 'O') { // octal
110  unsigned char val = 0;
111  for (int i = 0; i < 3 && p != str.end() && *p >= '0' && *p <= '7';
112  ++i, ++p) {
113  val <<= 3;
114  val |= (*p - '0');
115  }
116  out.push_back(val);
117  last = p;
118  } else if (e == 'X') { // hex
119  ++p;
120  if (p == str.end()) { // \x at end of string
121  if (strict) {
122  throw std::invalid_argument("incomplete hex escape sequence");
123  }
124  out.append("\\x");
125  last = p;
126  continue;
127  }
128  unsigned char val = 0;
129  unsigned char h;
130  for (; (p != str.end() &&
131  (h = detail::hexTable[static_cast<unsigned char>(*p)]) < 16);
132  ++p) {
133  val <<= 4;
134  val |= h;
135  }
136  out.push_back(val);
137  last = p;
138  } else if (e == 'I') { // invalid
139  if (strict) {
140  throw std::invalid_argument("invalid escape sequence");
141  }
142  out.push_back('\\');
143  out.push_back(*p);
144  ++p;
145  last = p;
146  } else { // standard escape sequence, \' etc
147  out.push_back(e);
148  ++p;
149  last = p;
150  }
151  }
152  out.append(&*last, p - last);
153 }
*than *hazptr_holder h
Definition: Hazptr.h:116
double val
Definition: String.cpp:273
const std::array< unsigned char, 256 > hexTable
Definition: String.cpp:120
const std::array< char, 256 > cUnescapeTable
Definition: String.cpp:118
char c
template<class String >
String folly::cUnescape ( StringPiece  str,
bool  strict = true 
)

Similar to cUnescape above, but returns the escaped string.

Definition at line 107 of file String.h.

References cUnescape().

107  {
108  String out;
109  cUnescape(str, out, strict);
110  return out;
111 }
String cUnescape(StringPiece str, bool strict=true)
Definition: String.h:107
template<typename C >
constexpr auto folly::data ( C c) -> decltype(c.data())

Definition at line 71 of file Access.h.

References c.

Referenced by folly::ConcurrentSkipList< T, Comp, NodeAlloc, MAX_HEIGHT >::addOrGetData(), folly::pushmi::any_constrained_single_sender< E, TP, VN... >::any_constrained_single_sender(), folly::pushmi::any_receiver< E, folly::pushmi::any_executor_ref< E > >::any_receiver(), folly::AsyncFileWriter::AsyncFileWriter(), folly::detail::atomic_notification::atomic_notify_all_impl(), folly::detail::atomic_notification::atomic_notify_one_impl(), BENCHMARK(), folly::RequestContext::clearContextData(), AcceptRoutingHandlerTest::clientConnectAndWrite(), fizz::detail::computeTranscriptHash(), folly::NotificationQueue< MessageT >::Consumer::consumeMessages(), folly::NotificationQueue< MessageT >::SimpleConsumer::consumeUntilDrained(), folly::detail::crc32_sw(), folly::detail::crc32c_sw(), folly::RequestContext::create(), fizz::test::HandshakeTypesTest::decodeHex(), fizz::test::ZlibCertificateCompressorTest::decodeHex(), folly::io::StreamCodec::doCompress(), folly::io::StreamCodec::doUncompress(), folly::ConcurrentSkipList< T, Comp, NodeAlloc, MAX_HEIGHT >::Accessor::erase(), folly::hash::SpookyHashV1::Final(), folly::hash::SpookyHashV2::Final(), folly::ConcurrentSkipList< T, Comp, NodeAlloc, MAX_HEIGHT >::findInsertionPointGetMaxLayer(), folly::AsyncFileWriter::flush(), folly::experimental::EnvironmentState::fromCurrentEnvironment(), folly::RequestEventBase::get(), folly::atomic_shared_ptr< T, Atom, CountedDetail >::get_newptr(), folly::SendMsgParamsCallbackBase::getAncillaryData(), folly::SendMsgDataCallback::getAncillaryData(), fizz::test::PlaintextRecordTest::getBuf(), fizz::extensions::test::TokenBindingConstructorTest::getBuf(), fizz::test::EncryptedRecordTest::getBuf(), fizz::test::RecordTest::getBuf(), fizz::extensions::test::ValidatorTest::getBuf(), folly::AsyncFileWriter::Data::getCurrentQueue(), fizz::detail::getFinishedData(), folly::AsyncFileWriter::getMaxBufferSize(), folly::observer::Observer< T >::getSnapshot(), folly::LockedPtrBase< SynchronizedType, SynchronizedType::MutexType, LockPolicy >::getSynchronized(), getVersionedSpdyFrame(), folly::ConcurrentSkipList< T, Comp, NodeAlloc, MAX_HEIGHT >::greater(), folly::AsyncUDPSocket::handleErrMessages(), folly::AsyncSocket::handleErrMessages(), folly::atomic_shared_ptr< T, Atom, CountedDetail >::init(), folly::ConcurrentSkipList< T, Comp, NodeAlloc, MAX_HEIGHT >::Accessor::insert(), folly::AsyncFileWriter::ioThread(), folly::ConcurrentSkipList< T, Comp, NodeAlloc, MAX_HEIGHT >::less(), makeUnpredictable(), folly::compression::maybeTestPrevious(), folly::compression::maybeTestPreviousValue(), ReadStats::messageReceived(), folly::AsyncUDPServerSocket::onDataAvailable(), folly::RequestContext::onSet(), folly::RequestContext::onUnset(), folly::pushmi::detail::via_fn::on_error_impl< Out >::operator()(), folly::padded::Node< T, NS, typename detail::NodeValid< T, NS >::type >::operator==(), folly::ParkingLot< Data >::park(), folly::ParkingLot< Data >::park_for(), folly::ParkingLot< Data >::park_until(), folly::SSLContext::passwordCollector(), preallocate_postallocate_bench(), folly::NotificationQueue< folly::AsyncServerSocket::QueueMessage >::putMessageImpl(), folly::NotificationQueue< folly::AsyncServerSocket::QueueMessage >::putMessagesImpl(), folly::LockedPtrBase< SynchronizedType, SynchronizedType::MutexType, LockPolicy >::reacquireLock(), folly::LockedPtrBase< SynchronizedType, std::mutex, LockPolicy >::reacquireLock(), folly::test::WriteFileAtomic::readData(), folly::LockedPtrBase< SynchronizedType, std::mutex, LockPolicy >::releaseLock(), folly::ConcurrentSkipList< T, Comp, NodeAlloc, MAX_HEIGHT >::remove(), folly::ConcurrentSkipList< T, Comp, NodeAlloc, MAX_HEIGHT >::Accessor::remove(), folly::SendMsgDataCallback::resetData(), folly::AsyncFileWriter::restartThread(), folly::LogMessage::sanitizeMessage(), folly::RequestContext::setContext(), RequestContextTest::setData(), folly::AsyncFileWriter::setMaxBufferSize(), folly::detail::distributed_mutex::spin(), inline_executor_flow_single< CancellationFactory >::submit(), inline_executor_flow_many::submit(), TEST(), TEST(), TEST_F(), TEST_P(), folly::compression::testAll(), folly::compression::testEmpty(), folly::compression::testSkip(), folly::compression::testSkipTo(), folly::test::testVarintFail(), folly::detail::distributed_mutex::timedLock(), folly::NotificationQueue< folly::AsyncServerSocket::QueueMessage >::tryConsume(), folly::detail::RingBufferSlot< T, Atom >::tryRead(), folly::io::Codec::type(), TYPED_TEST(), folly::io::StreamCodec::uncompressedLength(), folly::detail::RingBufferSlot< T, Atom >::waitAndTryRead(), folly::detail::RingBufferSlot< T, Atom >::write(), proxygen::http2::writeData(), writeFile(), folly::AsyncFileWriter::writeMessage(), ReadStats::writerFinished(), folly::AsyncFileWriter::~AsyncFileWriter(), folly::ExpectWriteErrorCallback::~ExpectWriteErrorCallback(), and folly::NotificationQueue< folly::AsyncServerSocket::QueueMessage >::~NotificationQueue().

71  {
72  return c.data();
73 }
char c
template<typename C >
constexpr auto folly::data ( C const &  c) -> decltype(c.data())

Definition at line 75 of file Access.h.

References c.

75  {
76  return c.data();
77 }
char c
template<typename T , std::size_t N>
constexpr T* folly::data ( T(&)  a[N])
noexcept

Definition at line 79 of file Access.h.

References a.

79  {
80  return a;
81 }
char a
template<typename E >
constexpr E const* folly::data ( std::initializer_list< E il)
noexcept

Definition at line 83 of file Access.h.

83  {
84  return il.begin();
85 }
void folly::deallocateBytes ( void *  p,
size_t  n 
)
inline

Definition at line 47 of file Memory.h.

References aligned_free(), aligned_malloc(), bm::free(), ptr, and size().

Referenced by TEST().

47  {
48 #if __cpp_sized_deallocation
49  return ::operator delete(p, n);
50 #else
51  (void)n;
52  return ::operator delete(p);
53 #endif
54 }
template<typename Alloc , size_t kAlign = alignof(typename std::allocator_traits<Alloc>::value_type)>
void folly::deallocateOverAligned ( Alloc const &  alloc,
typename std::allocator_traits< Alloc >::pointer  ptr,
size_t  n 
)

Definition at line 212 of file Memory.h.

Referenced by TEST().

215  {
216  void* raw = static_cast<void*>(std::addressof(*ptr));
217  detail::rawOverAlignedImpl<Alloc, kAlign, false>(alloc, n, raw);
218 }
void * ptr
template<class T >
uint64_t folly::decodeVarint ( Range< T * > &  data)
inline

Decode a value from a given buffer, advances data past the returned value. Throws on error.

Definition at line 135 of file Varint.h.

References TooManyBytes, and tryDecodeVarint().

Referenced by folly::test::TEST(), and folly::test::testVarint().

135  {
136  auto expected = tryDecodeVarint(data);
137  if (!expected) {
138  throw std::invalid_argument(
139  expected.error() == DecodeVarintError::TooManyBytes
140  ? "Invalid varint value: too many bytes."
141  : "Invalid varint value: too few bytes.");
142  }
143  return *expected;
144 }
Expected< uint64_t, DecodeVarintError > tryDecodeVarint(Range< T * > &data)
Definition: Varint.h:147
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
int64_t folly::decodeZigZag ( uint64_t  val)
inline

Definition at line 103 of file Varint.h.

References int64_t.

Referenced by folly::test::TEST().

103  {
104  return static_cast<int64_t>((val >> 1) ^ -(val & 1));
105 }
double val
Definition: String.cpp:273
template<template< typename > class Atom = std::atomic>
hazptr_domain<Atom>& folly::default_hazptr_domain ( )

default_hazptr_domain

Definition at line 363 of file HazptrDomain.h.

References Atom, and folly::hazptr_default_domain_helper< Atom >::get().

363  {
365 }
PUSHMI_INLINE_VAR constexpr detail::get_fn< T > get
Definition: submit.h:391
template<template< typename > class Atom>
FOLLY_ALWAYS_INLINE hazptr_domain<Atom>& folly::default_hazptr_domain ( )

default_hazptr_domain

Definition at line 363 of file HazptrDomain.h.

References Atom, and folly::hazptr_default_domain_helper< Atom >::get().

363  {
365 }
PUSHMI_INLINE_VAR constexpr detail::get_fn< T > get
Definition: submit.h:391
template<class Container , class Value >
detail::DefaultValueWrapper<Container, Value> folly::defaulted ( const Container &  c,
const Value &  v 
)

Definition at line 353 of file Format.h.

References testing::Args(), c, type, v, and value.

Referenced by TEST().

355  {
356  return detail::DefaultValueWrapper<Container, Value>(c, v);
357 }
auto v
char c
folly::DEFINE_int64 ( threadtimeout_ms  ,
60000  ,
"Idle time before ThreadPoolExecutor threads are joined"   
)
fbstring folly::demangle ( const std::type_info &  type)
inline

Definition at line 35 of file Demangle.h.

References demangle(), and name.

35  {
36  return demangle(type.name());
37 }
PskType type
size_t demangle(const std::type_info &type, char *buf, size_t bufSize)
Definition: Demangle.h:58
size_t folly::demangle ( const std::type_info &  type,
char *  buf,
size_t  bufSize 
)
inline

Definition at line 58 of file Demangle.h.

References demangle(), upload::dest, size(), and strlcpy().

58  {
59  return demangle(type.name(), buf, bufSize);
60 }
PskType type
size_t demangle(const std::type_info &type, char *buf, size_t bufSize)
Definition: Demangle.h:58
fbstring folly::demangle ( const char *  name)

Return the demangled (prettyfied) version of a C++ type.

This function tries to produce a human-readable type, but the type name will be returned unchanged in case of error or if demangling isn't supported on your system.

Use for debugging – do not rely on demangle() returning anything useful.

This function may allocate memory (and therefore throw std::bad_alloc).

Definition at line 111 of file Demangle.cpp.

References name.

Referenced by folly::exception_wrapper::class_name(), demangle(), folly::symbolizer::SymbolizedFrame::demangledName(), folly::detail::errorValue(), exceptionStr(), folly::detail::fallbackFormatOneArg(), folly::exception_tracer::getCurrentExceptions(), folly::ThreadPoolExecutor::getName(), folly::detail::TypeDescriptor::name(), folly::f14::operator<<(), folly::symbolizer::SymbolizePrinter::print(), folly::exception_tracer::printExceptionInfo(), folly::symbolizer::SymbolizePrinter::printTerse(), wangle::ContextImplBase< H, InboundHandlerContext< H::rout > >::setNextIn(), wangle::ContextImplBase< H, InboundHandlerContext< H::rout > >::setNextOut(), folly::detail::singletonThrowNullCreator(), and TEST().

111  {
112  return name;
113 }
const char * name
Definition: http_parser.c:437
size_t folly::demangle ( const char *  name,
char *  buf,
size_t  bufSize 
)

Return the demangled (prettyfied) version of a C++ type in a user-provided buffer.

The semantics are the same as for snprintf or strlcpy: bufSize is the size of the buffer, the string is always null-terminated, and the return value is the number of characters (not including the null terminator) that would have been written if the buffer was big enough. (So a return value >= bufSize indicates that the output was truncated)

This function does not allocate memory and is async-signal-safe.

Note that the underlying function for the fbstring-returning demangle is somewhat standard (abi::__cxa_demangle, which uses malloc), the underlying function for this version is less so (cplus_demangle_v3_callback from libiberty), so it is possible for the fbstring version to work, while this version returns the original, mangled name.

Definition at line 115 of file Demangle.cpp.

References strlcpy().

115  {
116  return folly::strlcpy(out, name, outSize);
117 }
const char * name
Definition: http_parser.c:437
size_t strlcpy(char *dest, const char *const src, size_t size)
Definition: Demangle.cpp:121
uint32_t folly::digits10 ( uint64_t  v)
inline

Returns the number of digits in the base 10 representation of an uint64_t. Useful for preallocating buffers and such. It's also used internally, see below. Measurements suggest that defining a separate overload for 32-bit integers is not worthwhile.

Definition at line 295 of file Conv.h.

References LIKELY, uint32_t, uint64_t, and UNLIKELY.

Referenced by testing::internal::CmpHelperFloatingPointEQ(), testing::internal::FloatingEqMatcher< FloatType >::Impl< T >::DescribeNegationTo(), testing::internal::FloatingEqMatcher< FloatType >::Impl< T >::DescribeTo(), folly::detail::digits_to(), estimateSpaceNeeded(), testing::internal::FloatingPointLE(), testing::Message::Message(), testing::internal::ShouldRunTestCase(), TEST(), u64ToAsciiTable(), and uint64ToBufferUnsafe().

295  {
296 #ifdef __x86_64__
297 
298  // For this arch we can get a little help from specialized CPU instructions
299  // which can count leading zeroes; 64 minus that is appx. log (base 2).
300  // Use that to approximate base-10 digits (log_10) and then adjust if needed.
301 
302  // 10^i, defined for i 0 through 19.
303  // This is 20 * 8 == 160 bytes, which fits neatly into 5 cache lines
304  // (assuming a cache line size of 64).
305  alignas(64) static const uint64_t powersOf10[20] = {
306  1,
307  10,
308  100,
309  1000,
310  10000,
311  100000,
312  1000000,
313  10000000,
314  100000000,
315  1000000000,
316  10000000000,
317  100000000000,
318  1000000000000,
319  10000000000000,
320  100000000000000,
321  1000000000000000,
322  10000000000000000,
323  100000000000000000,
324  1000000000000000000,
325  10000000000000000000UL,
326  };
327 
328  // "count leading zeroes" operation not valid; for 0; special case this.
329  if (UNLIKELY(!v)) {
330  return 1;
331  }
332 
333  // bits is in the ballpark of log_2(v).
334  const uint32_t leadingZeroes = __builtin_clzll(v);
335  const auto bits = 63 - leadingZeroes;
336 
337  // approximate log_10(v) == log_10(2) * bits.
338  // Integer magic below: 77/256 is appx. 0.3010 (log_10(2)).
339  // The +1 is to make this the ceiling of the log_10 estimate.
340  const uint32_t minLength = 1 + ((bits * 77) >> 8);
341 
342  // return that log_10 lower bound, plus adjust if input >= 10^(that bound)
343  // in case there's a small error and we misjudged length.
344  return minLength + uint32_t(v >= powersOf10[minLength]);
345 
346 #else
347 
348  uint32_t result = 1;
349  while (true) {
350  if (LIKELY(v < 10)) {
351  return result;
352  }
353  if (LIKELY(v < 100)) {
354  return result + 1;
355  }
356  if (LIKELY(v < 1000)) {
357  return result + 2;
358  }
359  if (LIKELY(v < 10000)) {
360  return result + 3;
361  }
362  // Skip ahead by 4 orders of magnitude
363  v /= 10000U;
364  result += 4;
365  }
366 
367 #endif
368 }
#define LIKELY(x)
Definition: Likely.h:47
#define UNLIKELY(x)
Definition: Likely.h:48
template<typename N , typename D >
constexpr detail::IdivResultType<N, D> folly::divCeil ( num,
D  denom 
)
inline

Returns num/denom, rounded toward positive infinity. Put another way, returns the smallest integral value that is greater than or equal to the exact (not rounded) fraction num/denom.

This function undergoes the same integer promotion rules as a built-in operator, except that we don't allow bool -> int promotion. This function is undefined if denom == 0. It is also undefined if the result type T is a signed type, num is std::numeric_limits<T>::min(), and denom is equal to -1 after conversion to the result type.

Definition at line 152 of file Math.h.

References value.

152  {
153  using R = decltype(num / denom);
154  return detail::IdivResultType<N, D>(
156  ? detail::divCeilBranchless<R>(num, denom)
157  : detail::divCeilBranchful<R>(num, denom));
158 }
constexpr auto kIntegerDivisionGivesRemainder
Definition: Math.h:111
static const char *const value
Definition: Conv.cpp:50
template<typename N , typename D >
constexpr detail::IdivResultType<N, D> folly::divFloor ( num,
D  denom 
)
inline

Returns num/denom, rounded toward negative infinity. Put another way, returns the largest integral value that is less than or equal to the exact (not rounded) fraction num/denom.

The matching remainder (num - divFloor(num, denom) * denom) can be negative only if denom is negative, unlike in truncating division. Note that for unsigned types this is the same as the normal integer division operator. divFloor is equivalent to python's integral division operator //.

This function undergoes the same integer promotion rules as a built-in operator, except that we don't allow bool -> int promotion. This function is undefined if denom == 0. It is also undefined if the result type T is a signed type, num is std::numeric_limits<T>::min(), and denom is equal to -1 after conversion to the result type.

Definition at line 132 of file Math.h.

References value.

132  {
133  using R = decltype(num / denom);
134  return detail::IdivResultType<N, D>(
136  ? detail::divFloorBranchless<R>(num, denom)
137  : detail::divFloorBranchful<R>(num, denom));
138 }
constexpr auto kIntegerDivisionGivesRemainder
Definition: Math.h:111
static const char *const value
Definition: Conv.cpp:50
template<typename N , typename D >
constexpr detail::IdivResultType<N, D> folly::divRoundAway ( num,
D  denom 
)
inline

Returns num/denom, rounded away from zero. If num and denom are non-zero and have different signs (so the unrounded fraction num/denom is negative), returns divFloor, otherwise returns divCeil. If T is an unsigned type then this is always equal to divCeil.

This function undergoes the same integer promotion rules as a built-in operator, except that we don't allow bool -> int promotion. This function is undefined if denom == 0. It is also undefined if the result type T is a signed type, num is std::numeric_limits<T>::min(), and denom is equal to -1 after conversion to the result type.

Definition at line 195 of file Math.h.

References value.

195  {
196  using R = decltype(num / denom);
197  return detail::IdivResultType<N, D>(
199  ? detail::divRoundAwayBranchless<R>(num, denom)
200  : detail::divRoundAwayBranchful<R>(num, denom));
201 }
constexpr auto kIntegerDivisionGivesRemainder
Definition: Math.h:111
static const char *const value
Definition: Conv.cpp:50
template<typename N , typename D >
constexpr detail::IdivResultType<N, D> folly::divTrunc ( num,
D  denom 
)
inline

Returns num/denom, rounded toward zero. If num and denom are non-zero and have different signs (so the unrounded fraction num/denom is negative), returns divCeil, otherwise returns divFloor. If T is an unsigned type then this is always equal to divFloor.

Note that this is the same as the normal integer division operator, at least since C99 (before then the rounding for negative results was implementation defined). This function is here for completeness and as a place to hang this comment.

This function undergoes the same integer promotion rules as a built-in operator, except that we don't allow bool -> int promotion. This function is undefined if denom == 0. It is also undefined if the result type T is a signed type, num is std::numeric_limits<T>::min(), and denom is equal to -1 after conversion to the result type.

Definition at line 178 of file Math.h.

178  {
179  return detail::IdivResultType<N, D>(num / denom);
180 }
template<typename T >
auto folly::doNotOptimizeAway ( const T datum) -> typename std::enable_if< !detail::DoNotOptimizeAwayNeedsIndirect<T>::value>::type

Definition at line 258 of file Benchmark.h.

References T, and type.

Referenced by addBenchmark(), assignmentFill(), assignmentOp(), atomicIncrBaseline(), BENCHMARK(), BENCHMARK_RELATIVE(), benchmarkCombineHardwareCrc32(), benchmarkCombineHardwareCrc32c(), benchmarkCombineSoftwareLinear(), benchmarkGet(), benchmarkHardwareCRC32(), benchmarkHardwareCRC32C(), benchmarkSet(), benchmarkSoftwareCRC32(), benchmarkSoftwareCRC32C(), detail::bmHasher(), folly::compression::bmJump(), folly::compression::bmJumpTo(), folly::compression::bmNext(), folly::compression::bmSkip(), folly::compression::bmSkipTo(), burn(), clibAtoiMeasure(), contentionAtWidth(), copyCtor(), countHits(), ctorFromArray(), ctorFromChar(), ctorFromTwoPointers(), defaultCtor(), folly::test::doWork(), doWork(), encryptGCM(), equality(), fillCtor(), findFirstOfRandom(), findFirstOfRange(), findSuccessful(), findUnsuccessful(), follyAtoiMeasure(), fun(), getline(), getNormalSingleton(), handwrittenAtoiMeasure(), i64ToStringFollyMeasureNeg(), i64ToStringFollyMeasurePos(), lexicalCastMeasure(), Lines_Gen(), main(), meyersSingleton(), normalSingleton(), StringIdenticalToBM< String >::operator()(), StringVariadicToBM< String >::operator()(), preallocate_postallocate_bench(), recurse(), replace(), resize(), Run(), runArithmeticBench(), runContendedReaders(), runMixed(), runPushBenchmark(), sizeCtor(), StringUnsplit_Gen(), test_operator_on_search(), u2aAppendClassicBM(), u2aAppendFollyBM(), u64ToAsciiClassicBM(), u64ToAsciiFollyBM(), u64ToAsciiTableBM(), u64ToStringClibMeasure(), and u64ToStringFollyMeasure().

259  {
260  // The "r" constraint forces the compiler to make datum available
261  // in a register to the asm block, which means that it must have
262  // computed/loaded it. We use this path for things that are <=
263  // sizeof(long) (they have to fit), trivial (otherwise the compiler
264  // doesn't want to put them in a register), and not a pointer (because
265  // doNotOptimizeAway(&foo) would otherwise be a foot gun that didn't
266  // necessarily compute foo).
267  //
268  // An earlier version of this method had a more permissive input operand
269  // constraint, but that caused unnecessary variation between clang and
270  // gcc benchmarks.
271  asm volatile("" ::"r"(datum));
272 }
int folly::dup2NoInt ( int  oldfd,
int  newfd 
)

Definition at line 72 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt().

Referenced by folly::ShutdownSocketSet::doShutdown().

72  {
73  return int(wrapNoInt(dup2, oldfd, newfd));
74 }
ssize_t wrapNoInt(F f, Args...args)
int folly::dupNoInt ( int  fd)

Definition at line 68 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt().

68  {
69  return int(wrapNoInt(dup, fd));
70 }
ssize_t wrapNoInt(F f, Args...args)
template<bool implicit_unpack = true, typename Container >
emplace_iterator<Container, implicit_unpack> folly::emplacer ( Container &  c,
typename Container::iterator  i 
)

Convenience function to construct a folly::emplace_iterator, analogous to std::inserter().

Setting implicit_unpack to false will disable implicit unpacking of single std::pair and std::tuple arguments to the iterator's operator=. That may be desirable in case of constructors that expect a std::pair or std::tuple argument.

Examples:
/facebook/proxygen/proxygen/folly/folly/container/Iterator.h.

Definition at line 445 of file Iterator.h.

References c, and folly::gen::move.

Referenced by TEST().

447  {
448  return emplace_iterator<Container, implicit_unpack>(c, std::move(i));
449 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
char c
template<typename C >
constexpr auto folly::empty ( C const &  c) -> decltype(c.empty())

Definition at line 55 of file Access.h.

References c.

Referenced by folly::futures::detail::WaitExecutor::add(), folly::Uri::authority(), folly::padded::Adaptor< IntNodeVec >::back(), folly::small_vector< Observer< T > *, InlineObservers >::back(), folly::basic_fbstring< char >::back(), checkTracepointArguments(), clause11_21_4_4(), folly::IOBuf::destroy(), folly::pushmi::operators::empty(), folly::Range< unsigned char * >::endsWith(), folly::basic_fbstring< E, T, A, Storage >::find_last_not_of(), folly::basic_fbstring< E, T, A, Storage >::find_last_of(), folly::padded::Adaptor< IntNodeVec >::front(), folly::small_vector< Observer< T > *, InlineObservers >::front(), folly::ssl::OpenSSLUtils::getCipherName(), proxygen::getCodecProtocolString(), folly::FutureDAG::hasCycle(), folly::symbolizer::Dwarf::LineNumberVM::init(), isSane(), folly::basic_fbstring< char >::isSane(), main(), testing::gtest_printers_test::AllowsGenericStreamingAndImplicitConversionTemplate< T >::operator bool(), folly::StringKeyedMap< Value, Compare, Alloc >::operator=(), folly::StringKeyedSetBase< Compare, Alloc >::operator=(), folly::F14VectorSet< Key, Hasher, KeyEqual, Alloc >::operator=(), folly::F14VectorMap< Key, Mapped, Hasher, KeyEqual, Alloc >::operator=(), folly::basic_fbstring< E, T, A, Storage >::operator=(), testing::internal::ParseGoogleTestFlag(), CurlService::CurlClient::parseHeaders(), testing::gmock_generated_actions_test::SubstractAction::Perform(), folly::padded::Adaptor< IntNodeVec >::pop_back(), folly::basic_fbstring< char >::pop_back(), runBenchmarks(), folly::io::test::StreamingCompressionTest::runCompressStreamTest(), folly::Range< unsigned char * >::startsWith(), folly::pushmi::detail::trampoline< E >::submit(), CommonTest< T >::TearDown(), TEST(), fizz::test::TEST(), testing::internal::TEST(), TEST(), testing::gtest_printers_test::TEST(), testing::gmock_generated_actions_test::TEST(), TEST_F(), test_moveConstructionWithAllocatorSupplied3(), folly::io::test::TEST_P(), testing::internal::To::To(), folly::observer::SimpleObservable< T >::Wrapper< T >::unsubscribe(), and folly::AtomicIntrusiveLinkedList< folly::fibers::Fiber,&folly::fibers::Fiber::nextRemoteReady_ >::~AtomicIntrusiveLinkedList().

55  {
56  return c.empty();
57 }
char c
template<typename T , std::size_t N>
constexpr bool folly::empty ( T const   (&)[N])
noexcept

Definition at line 59 of file Access.h.

59  {
60  // while zero-length arrays are not allowed in the language, some compilers
61  // may permit them in some cases
62  return N == 0;
63 }
template<typename E >
constexpr bool folly::empty ( std::initializer_list< E il)
noexcept

Definition at line 65 of file Access.h.

65  {
66  return il.size() == 0;
67 }
size_t folly::encodeVarint ( uint64_t  val,
uint8_t buf 
)
inline

Encode a value in the given buffer, returning the number of bytes used for encoding. buf must have enough space to represent the value (at least kMaxVarintLength64 bytes to encode arbitrary 64-bit values)

Definition at line 109 of file Varint.h.

References uint8_t.

Referenced by folly::io::StreamCodec::doUncompress(), folly::test::TEST(), and folly::test::testVarint().

109  {
110  uint8_t* p = buf;
111  while (val >= 128) {
112  *p++ = 0x80 | (val & 0x7f);
113  val >>= 7;
114  }
115  *p++ = uint8_t(val);
116  return size_t(p - buf);
117 }
double val
Definition: String.cpp:273
int folly::encodeVarintSize ( uint64_t  val)
inline

Determine the number of bytes needed to represent "val". 32-bit values need at most 5 bytes. 64-bit values need at most 10 bytes.

Definition at line 119 of file Varint.h.

References kIsArchAmd64, and s.

Referenced by folly::test::testVarint().

119  {
120  if (folly::kIsArchAmd64) {
121  // __builtin_clzll is undefined for 0
122  int highBit = 64 - __builtin_clzll(val | 1);
123  return (highBit + 6) / 7;
124  } else {
125  int s = 1;
126  while (val >= 128) {
127  ++s;
128  val >>= 7;
129  }
130  return s;
131  }
132 }
double val
Definition: String.cpp:273
static set< string > s
constexpr bool kIsArchAmd64
Definition: Portability.h:102
uint64_t folly::encodeZigZag ( int64_t  val)
inline

ZigZag encoding that maps signed integers with a small absolute value to unsigned integers with a small (positive) values. Without this, encoding negative values using Varint would use up 9 or 10 bytes.

if x >= 0, encodeZigZag(x) == 2*x if x < 0, encodeZigZag(x) == -2*x + 1

Definition at line 96 of file Varint.h.

References uint64_t, and val.

Referenced by folly::test::TEST().

96  {
97  // Bit-twiddling magic stolen from the Google protocol buffer document;
98  // val >> 63 is an arithmetic shift because val is signed
99  auto uval = static_cast<uint64_t>(val);
100  return static_cast<uint64_t>((uval << 1) ^ (val >> 63));
101 }
double val
Definition: String.cpp:273
fbstring folly::errnoStr ( int  err)

Return a fbstring containing the description of the given errno value. Takes care not to overwrite the actual system errno, so calling errnoStr(errno) is valid.

Definition at line 463 of file String.cpp.

References folly::basic_fbstring< E, T, A, Storage >::assign(), c, folly::gen::guard(), makeGuard(), uint32_t, uint64_t, and uint8_t.

Referenced by folly::AsyncIO::doWait(), folly::JemallocNodumpAllocator::extend_and_setup_arena(), getfds(), getLinuxVersion(), folly::AsyncSocketException::getMessage(), folly::detail::handleMallctlError(), fizz::tool::TerminalInputHandler::handlerReady(), folly::PriorityThreadFactory::newThread(), operator<<(), folly::JemallocNodumpAllocator::reallocate(), folly::EventHandler::registerImpl(), folly::NestedCommandLineApp::run(), folly::EventBase::scheduleTimeout(), folly::AsyncSocket::setCongestionFlavor(), folly::AsyncServerSocket::setKeepAliveEnabled(), folly::AsyncSocket::setNoDelay(), folly::AsyncSocket::setQuickAck(), folly::AsyncSocket::setRecvBufSize(), folly::AsyncSocket::setSendBufSize(), folly::AsyncSocket::setTCPProfile(), folly::AsyncServerSocket::setupSocket(), folly::Subprocess::spawnInternal(), folly::IPAddressV6::str(), TEST(), toSubprocessSpawnErrorMessage(), folly::ImmediateFileWriter::writeMessage(), and folly::AsyncIO::~AsyncIO().

463  {
464  int savedErrno = errno;
465 
466  // Ensure that we reset errno upon exit.
467  auto guard(makeGuard([&] { errno = savedErrno; }));
468 
469  char buf[1024];
470  buf[0] = '\0';
471 
472  fbstring result;
473 
474  // https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man3/strerror_r.3.html
475  // http://www.kernel.org/doc/man-pages/online/pages/man3/strerror.3.html
476 #if defined(_WIN32) && (defined(__MINGW32__) || defined(_MSC_VER))
477  // mingw64 has no strerror_r, but Windows has strerror_s, which C11 added
478  // as well. So maybe we should use this across all platforms (together
479  // with strerrorlen_s). Note strerror_r and _s have swapped args.
480  int r = strerror_s(buf, sizeof(buf), err);
481  if (r != 0) {
482  result = to<fbstring>(
483  "Unknown error ", err, " (strerror_r failed with error ", errno, ")");
484  } else {
485  result.assign(buf);
486  }
487 #elif FOLLY_HAVE_XSI_STRERROR_R || defined(__APPLE__)
488 
489  // Using XSI-compatible strerror_r
490  int r = strerror_r(err, buf, sizeof(buf));
491 
492  // OSX/FreeBSD use EINVAL and Linux uses -1 so just check for non-zero
493  if (r != 0) {
494  result = to<fbstring>(
495  "Unknown error ", err, " (strerror_r failed with error ", errno, ")");
496  } else {
497  result.assign(buf);
498  }
499 #else
500  // Using GNU strerror_r
501  result.assign(strerror_r(err, buf, sizeof(buf)));
502 #endif
503 
504  return result;
505 }
GuardImpl guard(ErrorHandler &&handler)
Definition: Base.h:840
FOLLY_NODISCARD detail::ScopeGuardImplDecay< F, true > makeGuard(F &&f) noexcept(noexcept(detail::ScopeGuardImplDecay< F, true >(static_cast< F && >(f))))
Definition: ScopeGuard.h:184
basic_fbstring< char > fbstring
Definition: FBString.h:2904
template<class T >
constexpr std::enable_if<std::is_same<T, char>::value, size_t>::type folly::estimateSpaceNeeded ( T  )

Definition at line 412 of file Conv.h.

Referenced by estimateSpaceNeeded(), my::estimateSpaceNeeded(), and toAppend().

412  {
413  return 1;
414 }
template<size_t N>
constexpr size_t folly::estimateSpaceNeeded ( const   char(&)[N])

Definition at line 417 of file Conv.h.

References type, and value.

417  {
418  return N;
419 }
template<class Src >
std::enable_if<std::is_convertible<Src, const char*>::value, size_t>:: type folly::estimateSpaceNeeded ( Src  value)

Definition at line 440 of file Conv.h.

References c, folly::Range< Iter >::size(), type, value, and value().

440  {
441  const char* c = value;
442  if (c) {
443  return folly::StringPiece(value).size();
444  };
445  return 0;
446 }
constexpr size_type size() const
Definition: Range.h:431
static const char *const value
Definition: Conv.cpp:50
Range< const char * > StringPiece
char c
template<class Src >
std::enable_if<IsSomeString<Src>::value, size_t>::type folly::estimateSpaceNeeded ( Src const &  value)

Definition at line 450 of file Conv.h.

References type, and value.

450  {
451  return value.size();
452 }
static const char *const value
Definition: Conv.cpp:50
template<class Src >
std::enable_if< std::is_convertible<Src, folly::StringPiece>::value && !IsSomeString<Src>::value && !std::is_convertible<Src, const char*>::value, size_t>::type folly::estimateSpaceNeeded ( Src  value)

Definition at line 460 of file Conv.h.

References folly::Range< Iter >::size().

460  {
461  return folly::StringPiece(value).size();
462 }
constexpr size_type size() const
Definition: Range.h:431
static const char *const value
Definition: Conv.cpp:50
Range< const char * > StringPiece
template<>
size_t folly::estimateSpaceNeeded ( std::nullptr_t  )
inline

Definition at line 465 of file Conv.h.

References type, value, and value().

465  {
466  return 0;
467 }
template<class Src >
std::enable_if< std::is_pointer<Src>::value && IsSomeString<std::remove_pointer<Src> >::value, size_t>::type folly::estimateSpaceNeeded ( Src  value)

Definition at line 474 of file Conv.h.

References type.

474  {
475  return value->size();
476 }
static const char *const value
Definition: Conv.cpp:50
template<class Tgt , class Src >
size_t::type folly::estimateSpaceNeeded ( Src  value)

Definition at line 585 of file Conv.h.

References buffer(), shell_builder::builder, digits10(), estimateSpaceNeeded(), int64_t, max, mode, T, toAppend(), type, uint64_t, uint64ToBufferUnsafe(), value, and value().

585  {
586  if (value < 0) {
587  // When "value" is the smallest negative, negating it would evoke
588  // undefined behavior, so, instead of writing "-value" below, we write
589  // "~static_cast<uint64_t>(value) + 1"
590  return 1 + digits10(~static_cast<uint64_t>(value) + 1);
591  }
592 
593  return digits10(static_cast<uint64_t>(value));
594 }
uint32_t digits10(uint64_t v)
Definition: Conv.h:295
static const char *const value
Definition: Conv.cpp:50
static double folly::estimateTime ( double *  begin,
double *  end 
)
static

Given a bunch of benchmark samples, estimate the actual run time.

Definition at line 117 of file Benchmark.cpp.

Referenced by runBenchmarkGetNSPerIteration().

117  {
118  assert(begin < end);
119 
120  // Current state of the art: get the minimum. After some
121  // experimentation, it seems taking the minimum is the best.
122  return *min_element(begin, end);
123 }
auto begin(TestAdlIterable &instance)
Definition: ForeachTest.cpp:56
auto end(TestAdlIterable &instance)
Definition: ForeachTest.cpp:62
auto folly::event_ref_flags ( struct event *  ev) -> decltype(std::ref(ev->ev_flags ))
inline
auto folly::event_ref_flags ( struct event const *  ev) -> decltype(std::cref(ev->ev_flags ))
inline

Definition at line 41 of file EventUtil.h.

49 {
fbstring folly::exceptionStr ( const std::exception &  e)
inline

Debug string for an exception: include type and what(), if defined.

Definition at line 33 of file ExceptionString.h.

References demangle().

Referenced by wangle::SSLContextManager::addSSLContextConfig(), folly::test::detail::checkThrowErrno(), folly::test::detail::checkThrowRegex(), ProxyService::ProxyHandler::connectError(), folly::observer_detail::ObserverManager::CurrentQueue::CurrentQueue(), folly::python::AsyncioExecutor::drive(), proxygen::HTTPMessage::getDecodedQueryParam(), folly::ssl::ssl_options_detail::logDfatal(), main(), wangle::ObservingHandler< T, R, P >::onError(), folly::AsyncFileWriter::onIoError(), proxygen::HTTPServerAcceptor::onNewConnection(), StaticService::StaticHandler::onRequest(), proxygen::GzipHeaderCodec::parseNameValues(), folly::exception_tracer::printExceptionInfo(), folly::LogCategory::processMessage(), FileServerHandler::read(), ProxyService::ProxyHandler::readErr(), TelnetHandler::readException(), wangle::BroadcastHandler< T, R >::readException(), EchoHandler::readException(), ProxyBackendHandler::readException(), wangle::ObservingHandler< T, R, P >::readException(), FileServerHandler::readException(), ProxyFrontendHandler::readException(), proxygen::compress::CompressionSimulator::readInputFromFileAndSchedule(), folly::observer_detail::Core::refresh(), folly::SerialExecutor::run(), folly::FunctionScheduler::runOneFunction(), folly::ssl::SSLCommonOptions::setClientOptions(), folly::LoggerDB::startConfigUpdate(), swap(), TEST(), ProxyFrontendHandler::transportActive(), and ProxyService::ProxyHandler::writeErr().

33  {
34 #ifdef FOLLY_HAS_RTTI
35  fbstring rv(demangle(typeid(e)));
36  rv += ": ";
37 #else
38  fbstring rv("Exception (no RTTI available): ");
39 #endif
40  rv += e.what();
41  return rv;
42 }
basic_fbstring< char > fbstring
Definition: FBString.h:2904
fbstring demangle(const char *name)
Definition: Demangle.cpp:111
template<typename E >
auto folly::exceptionStr ( const E e) -> typename std:: enable_if<!std::is_base_of<std::exception, E>::value, fbstring>::type

Definition at line 60 of file ExceptionString.h.

References demangle().

61  {
62 #ifdef FOLLY_HAS_RTTI
63  return demangle(typeid(e));
64 #else
65  (void)e;
66  return "Exception (no RTTI available) ";
67 #endif
68 }
fbstring demangle(const char *name)
Definition: Demangle.cpp:111
fbstring folly::exceptionStr ( exception_wrapper const &  ew)

Definition at line 101 of file ExceptionWrapper.cpp.

References folly::exception_wrapper::what().

101  {
102  return ew.what();
103 }
template<class T , class U = T>
T folly::exchange ( T obj,
U &&  new_value 
)

Definition at line 120 of file Utility.h.

References folly::gen::move, and T.

Referenced by folly::futures::detail::DeferredExecutor::add(), folly::pushmi::any_constrained_single_sender< E, TP, VN... >::any_constrained_single_sender(), folly::pushmi::any_flow_many_sender< PE, PV, E, VN >::any_flow_many_sender(), folly::pushmi::any_flow_receiver< PE, PV, E, VN >::any_flow_receiver(), folly::pushmi::any_flow_single_sender< PE, E, VN >::any_flow_single_sender(), folly::pushmi::any_many_sender< E, VN >::any_many_sender(), folly::pushmi::any_receiver< E, folly::pushmi::any_executor_ref< E > >::any_receiver(), folly::pushmi::any_single_sender< E, VN >::any_single_sender(), folly::test::TemporaryFile::assign(), folly::futures::detail::FutureBase< T >::assign(), folly::LockedPtrBase< SynchronizedType, SynchronizedType::MutexType, LockPolicy >::assignImpl(), folly::LockedPtrBase< SynchronizedType, std::mutex, LockPolicy >::assignImpl(), folly::coro::detail::InlineTask< T >::Awaiter::await_resume(), folly::coro::TaskWithExecutor< T >::Awaiter::await_resume(), folly::coro::detail::TaskPromiseBase::await_transform(), folly::futures::detail::chainExecutor(), folly::coro::detail::ViaCoroutine::destroy(), folly::Try< T >::destroy(), folly::futures::detail::DeferredExecutor::detach(), folly::detail::distributed_mutex::DistributedMutex< Atomic, TimePublishing >::DistributedMutexStateProxy< Atomic, TimePublishing >::DistributedMutexStateProxy(), folly::futures::detail::Core< T >::doCallback(), folly::detail::distributed_mutex::doFutexWait(), folly::futures::detail::WaitExecutor::drive(), folly::futures::detail::WaitExecutor::driveUntil(), ExpensiveCopy::ExpensiveCopy(), forward_like(), folly::observer_detail::ObserverManager::initCore(), folly::ThreadPoolExecutor::joinKeepAliveOnce(), folly::LockedPtrBase< SynchronizedType, SynchronizedType::MutexType, LockPolicy >::LockedPtrBase(), folly::LockedPtrBase< SynchronizedType, std::mutex, LockPolicy >::LockedPtrBase(), folly::LeakySingleton< T, Tag >::make_mock(), folly::LockedPtr< SynchronizedType, LockPolicy >::moveFromUpgradeToRead(), folly::LockedPtr< SynchronizedType, LockPolicy >::moveFromUpgradeToWrite(), folly::LockedPtr< SynchronizedType, LockPolicy >::moveFromWriteToRead(), folly::LockedPtr< SynchronizedType, LockPolicy >::moveFromWriteToUpgrade(), fizz::sm::negotiateParameters(), fizz::sm::negotiatePsk(), folly::coro::detail::InlineTask< T >::operator co_await(), folly::coro::TaskWithExecutor< T >::operator co_await(), folly::Executor::KeepAlive< folly::VirtualEventBase >::operator=(), folly::Promise< T >::operator=(), folly::ConcurrentHashMap< KeyType, ValueType, HashFn, KeyEqual, Allocator, ShardBits, Atom, Mutex >::ConstIterator::operator=(), folly::detail::ConcurrentHashMapSegment< KeyType, ValueType, ShardBits, HashFn, KeyEqual, Allocator, Atom, Mutex >::Iterator::operator=(), folly::Executor::KeepAlive< folly::VirtualEventBase >::reset(), folly::coro::Task< T >::scheduleOn(), folly::detail::ScopeGuardImpl< FunctionType, InvokeNoexcept >::ScopeGuardImpl(), folly::futures::detail::DeferredExecutor::setExecutor(), TEST(), TEST_F(), folly::detail::distributed_mutex::DistributedMutex< Atomic, TimePublishing >::unlock(), and unorderedReduce().

120  {
121  T old_value = std::move(obj);
122  obj = std::forward<U>(new_value);
123  return old_value;
124 }
#define T(v)
Definition: http_parser.c:233
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
int folly::fdatasyncNoInt ( int  fd)

Definition at line 76 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt().

Referenced by wangle::FilePersistenceLayer< K, V >::persist().

76  {
77 #if defined(__APPLE__)
78  return int(wrapNoInt(fcntl, fd, F_FULLFSYNC));
79 #elif defined(__FreeBSD__) || defined(_MSC_VER)
80  return int(wrapNoInt(fsync, fd));
81 #else
82  return int(wrapNoInt(fdatasync, fd));
83 #endif
84 }
ssize_t wrapNoInt(F f, Args...args)
template<typename Sequence , typename Index >
decltype(auto) FOLLY_CPP14_CONSTEXPR folly::fetch ( Sequence &&  sequence,
Index &&  index 
)

Utility method to help access elements of a sequence with one uniform interface.

This can be useful for example when you are looping through a sequence and want to modify another sequence based on the information in the current sequence:

auto range_one = std::make_tuple(1, 2, 3); auto range_two = std::make_tuple(4, 5, 6); folly::for_each(range_one, [&range_two](auto ele, auto index) { folly::fetch(range_two, index) = ele; });

For ranges, this works by first trying to use the iterator class if the iterator has been marked to be a random access iterator. This should be inspectable via the std::iterator_traits traits class. If the iterator class is not present or is not a random access iterator then the implementation falls back to trying to use the indexing operator (operator[]) to fetch the required element.

Definition at line 322 of file Foreach-inl.h.

References folly::for_each_detail::fetch_impl().

Referenced by BENCHMARK(), folly::detail::lock(), and TEST().

322  {
323  namespace fed = for_each_detail;
324  using tag = fed::SequenceTag<Sequence>;
326  tag{}, std::forward<Sequence>(sequence), std::forward<Index>(index));
327 }
decltype(auto) fetch_impl(RangeTag, Sequence &&sequence, Index &&index)
Definition: Foreach-inl.h:299
static int folly::filterCloseReturn ( int  r)
static

Definition at line 40 of file FileUtil.cpp.

Referenced by closeNoInt().

40  {
41  // Ignore EINTR. On Linux, close() may only return EINTR after the file
42  // descriptor has been closed, so you must not retry close() on EINTR --
43  // in the best case, you'll get EBADF, and in the worst case, you'll end up
44  // closing a different file (one opened from another thread).
45  //
46  // Interestingly enough, the Single Unix Specification says that the state
47  // of the file descriptor is unspecified if close returns EINTR. In that
48  // case, the safe thing to do is also not to retry close() -- leaking a file
49  // descriptor is definitely better than closing the wrong file.
50  if (r == -1 && errno == EINTR) {
51  return 0;
52  }
53  return r;
54 }
template<class BaseIter >
BitIterator< BaseIter > folly::findFirstSet ( BitIterator< BaseIter >  begin,
BitIterator< BaseIter >  end 
)

Find first bit set in a range of bit iterators. 4.5x faster than the obvious std::find(begin, end, true);

Definition at line 170 of file BitIterator.h.

References folly::BitIterator< BaseIter >::advanceInBlock(), folly::BitIterator< BaseIter >::advanceToNextBlock(), folly::test::begin(), folly::BitIterator< BaseIter >::bitOffset(), folly::test::end(), and folly::BitIterator< BaseIter >::findFirstSet.

Referenced by crc32_append_zeroes(), folly::json::firstEscapableInWord(), folly::HHWheelTimer::scheduleNextTimeout(), and TEST_F().

172  {
173  // shortcut to avoid ugly static_cast<>
174  static const typename std::iterator_traits<BaseIter>::value_type one = 1;
175 
176  while (begin.base() != end.base()) {
177  typename std::iterator_traits<BaseIter>::value_type v = *begin.base();
178  // mask out the bits that don't matter (< begin.bitOffset)
179  v &= ~((one << begin.bitOffset()) - 1);
180  size_t firstSet = findFirstSet(v);
181  if (firstSet) {
182  --firstSet; // now it's 0-based
183  assert(firstSet >= begin.bitOffset());
184  begin.advanceInBlock(firstSet - begin.bitOffset());
185  return begin;
186  }
187  begin.advanceToNextBlock();
188  }
189 
190  // now begin points to the same block as end
191  if (end.bitOffset() != 0) { // assume end is dereferenceable
192  typename std::iterator_traits<BaseIter>::value_type v = *begin.base();
193  // mask out the bits that don't matter (< begin.bitOffset)
194  v &= ~((one << begin.bitOffset()) - 1);
195  // mask out the bits that don't matter (>= end.bitOffset)
196  v &= (one << end.bitOffset()) - 1;
197  size_t firstSet = findFirstSet(v);
198  if (firstSet) {
199  --firstSet; // now it's 0-based
200  assert(firstSet >= begin.bitOffset());
201  begin.advanceInBlock(firstSet - begin.bitOffset());
202  return begin;
203  }
204  }
205 
206  return end;
207 }
BitIterator< BaseIter > findFirstSet(BitIterator< BaseIter >, BitIterator< BaseIter >)
Definition: BitIterator.h:170
auto begin(TestAdlIterable &instance)
Definition: ForeachTest.cpp:56
auto end(TestAdlIterable &instance)
Definition: ForeachTest.cpp:62
template<typename T >
constexpr unsigned int folly::findFirstSet ( T const  v)
inline

findFirstSet

Return the 1-based index of the least significant bit which is set. For x > 0, the exponent in the largest power of two which does not divide x.

Definition at line 82 of file Bits.h.

References folly::detail::bits_to_signed(), T, and value.

82  {
83  using S0 = int;
84  using S1 = long int;
85  using S2 = long long int;
87  static_assert(sizeof(T) <= sizeof(S2), "over-sized type");
88  static_assert(std::is_integral<T>::value, "non-integral type");
89  static_assert(!std::is_same<T, bool>::value, "bool type");
90 
91  // clang-format off
92  return static_cast<unsigned int>(
93  sizeof(T) <= sizeof(S0) ? __builtin_ffs(bits_to_signed<S0>(v)) :
94  sizeof(T) <= sizeof(S1) ? __builtin_ffsl(bits_to_signed<S1>(v)) :
95  sizeof(T) <= sizeof(S2) ? __builtin_ffsll(bits_to_signed<S2>(v)) :
96  0);
97  // clang-format on
98 }
#define T(v)
Definition: http_parser.c:233
struct folly::detail::LastElementImpl sizeof
constexpr std::make_signed_t< Dst > bits_to_signed(Src const s)
Definition: Bits.h:66
static const char *const value
Definition: Conv.cpp:50
template<typename T >
constexpr unsigned int folly::findLastSet ( T const  v)
inline

findLastSet

Return the 1-based index of the most significant bit which is set. For x > 0, findLastSet(x) == 1 + floor(log2(x)).

Definition at line 105 of file Bits.h.

References folly::detail::bits_to_unsigned(), size(), T, and value.

Referenced by benchmarkSet(), folly::compression::EliasFanoEncoderV2< Value, SkipValue, kSkipQuantum, kForwardQuantum >::defaultNumLowerBits(), folly::compression::EliasFanoReader< Encoder, Instructions, kUnchecked, SizeType >::EliasFanoReader(), folly::json::firstEscapableInWord(), nextPowTwo(), prevPowTwo(), and TEST_F().

105  {
106  using U0 = unsigned int;
107  using U1 = unsigned long int;
108  using U2 = unsigned long long int;
110  static_assert(sizeof(T) <= sizeof(U2), "over-sized type");
111  static_assert(std::is_integral<T>::value, "non-integral type");
112  static_assert(!std::is_same<T, bool>::value, "bool type");
113 
114  // If X is a power of two X - Y = 1 + ((X - 1) ^ Y). Doing this transformation
115  // allows GCC to remove its own xor that it adds to implement clz using bsr.
116  // clang-format off
117  using size = index_constant<constexpr_max(sizeof(T), sizeof(U0))>;
118  return v ? 1u + static_cast<unsigned int>((8u * size{} - 1u) ^ (
119  sizeof(T) <= sizeof(U0) ? __builtin_clz(bits_to_unsigned<U0>(v)) :
120  sizeof(T) <= sizeof(U1) ? __builtin_clzl(bits_to_unsigned<U1>(v)) :
121  sizeof(T) <= sizeof(U2) ? __builtin_clzll(bits_to_unsigned<U2>(v)) :
122  0)) : 0u;
123  // clang-format on
124 }
#define T(v)
Definition: http_parser.c:233
constexpr std::make_unsigned_t< Dst > bits_to_unsigned(Src const s)
Definition: Bits.h:71
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
static const char *const value
Definition: Conv.cpp:50
void folly::fingerprint128 ( StringPiece  str,
uint64_t msb,
uint64_t lsb 
)
inline

Compute the 128-bit Rabin fingerprint of a string. Return the 64 most significant bits in *msb, and the 64 least significant bits in *lsb.

Definition at line 217 of file Fingerprint.h.

References uint64_t, and folly::Fingerprint< BITS >::write().

Referenced by TEST().

217  {
218  uint64_t fp[2];
219  Fingerprint<128>().update(str).write(fp);
220  *msb = fp[0];
221  *lsb = fp[1];
222 }
uint64_t folly::fingerprint64 ( StringPiece  str)
inline

Return the 64-bit Rabin fingerprint of a string.

Definition at line 194 of file Fingerprint.h.

References uint64_t, and folly::Fingerprint< BITS >::write().

Referenced by TEST().

194  {
195  uint64_t fp;
196  Fingerprint<64>().update(str).write(&fp);
197  return fp;
198 }
void folly::fingerprint96 ( StringPiece  str,
uint64_t msb,
uint32_t lsb 
)
inline

Compute the 96-bit Rabin fingerprint of a string. Return the 64 most significant bits in *msb, and the 32 least significant bits in *lsb.

Definition at line 205 of file Fingerprint.h.

References uint32_t, uint64_t, and folly::Fingerprint< BITS >::write().

Referenced by TEST().

205  {
206  uint64_t fp[2];
207  Fingerprint<96>().update(str).write(fp);
208  *msb = fp[0];
209  *lsb = (uint32_t)(fp[1] >> 32);
210 }
int folly::flockNoInt ( int  fd,
int  operation 
)

Definition at line 94 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt().

Referenced by folly::File::doLock(), folly::File::doTryLock(), and folly::File::unlock().

94  {
95  return int(wrapNoInt(flock, fd, operation));
96 }
ssize_t wrapNoInt(F f, Args...args)
template<>
folly::FOLLY_ASSUME_RELOCATABLE ( T2  )
template<class T , class R , class A , class S >
folly::FOLLY_ASSUME_RELOCATABLE ( basic_fbstring< T, R, A, S )
void folly::folly_event_set ( event *  e,
int  fd,
short  s,
EventSetCallback  f,
void *  arg 
)
inline

Definition at line 50 of file Event.h.

References getLibeventFd().

Referenced by folly::AsyncTimeout::AsyncTimeout(), folly::EventHandler::changeHandlerFD(), folly::EventHandler::EventHandler(), and folly::EventHandler::initHandler().

50  {
51  auto lfd = getLibeventFd(fd);
52  event_set(e, lfd, s, f, arg);
53 }
auto f
libevent_fd_t getLibeventFd(int fd)
Definition: Event.h:40
static set< string > s
template<typename Range , typename Func >
FOLLY_CPP14_CONSTEXPR Func folly::for_each ( Range &&  range,
Func  func 
)

for_each

folly::for_each is a generalized iteration algorithm. Example:

auto one = std::make_tuple(1, 2, 3); auto two = std::vector<int>{1, 2, 3}; auto func = [](auto element, auto index) { cout << index << " : " << element << endl; }; folly::for_each(one, func); folly::for_each(two, func);

The for_each function allows iteration through sequences, these can either be runtime sequences (i.e. entities for which std::begin and std::end work) or compile time sequences (as deemed by the presence of std::tuple_length<> and member get<> or ADL get<> functions).

If a sequence type is both a runtime sequence (aka range) and a compile-time sequence (aka tuple), then it is treated as a range in preference to a tuple. An example of such a type is std::array.

The function is made to provide a convenient library based alternative to the proposal p0589r0, which aims to generalize the range based for loop even further to work with compile time sequences.

A drawback of using range based for loops is that sometimes you do not have access to the index within the range. This provides easy access to that, even with compile time sequences.

And breaking out is easy:

auto range_one = std::vector<int>{1, 2, 3}; auto range_two = std::make_tuple(1, 2, 3); auto func = [](auto ele, auto index) { cout << "Element at index " << index << " : " << ele; if (index == 1) { return folly::loop_break; } return folly::loop_continue; }; folly_for_each(range_one, func); folly_for_each(range_two, func);

A simple use case would be when using futures, if the user was doing calls to n servers then they would accept the callback with the futures like this:

auto vec = std::vector<std::future<int>>{request_one(), ...}; when_all(vec.begin(), vec.end()).then([](auto futures) { folly::for_each(futures, [](auto& fut) { ... }); });

Now when this code switches to use tuples instead of the runtime std::vector, then the loop does not need to change, the code will still work just fine:

when_all(future_one, future_two, future_three).then([](auto futures) { folly::for_each(futures, [](auto& fut) { ... }); });

template<typename Sequence , typename Func >
FOLLY_CPP14_CONSTEXPR Func folly::for_each ( Sequence &&  sequence,
Func  func 
)

Definition at line 314 of file Foreach-inl.h.

References folly::for_each_detail::for_each_impl().

Referenced by BENCHMARK(), folly::detail::lock(), lock(), and TEST().

314  {
315  namespace fed = for_each_detail;
316  using tag = fed::SequenceTag<Sequence>;
317  fed::for_each_impl(tag{}, std::forward<Sequence>(sequence), func);
318  return func;
319 }
static void for_each_impl(RangeTag, Sequence &&range, Func &func)
Definition: Foreach-inl.h:277
template<class... Args>
Formatter< false, Args... > folly::format ( StringPiece  fmt,
Args &&...  args 
)

Create a formatter object.

std::string formatted = format("{} {}", 23, 42).str(); LOG(INFO) << format("{} {}", 23, 42); writeTo(stdout, format("{} {}", 23, 42));

Definition at line 271 of file Format.h.

References testing::Args().

Referenced by fbcode_builder.FBCodeBuilder::__repr__(), docker_builder.DockerFBCodeBuilder::_change_user(), fbcode_builder.FBCodeBuilder::_make_vars(), fbcode_builder::_read_project_github_hashes(), fbcode_builder.FBCodeBuilder::add_option(), fbcode_builder.FBCodeBuilder::autoconf_install(), BENCHMARK(), BENCHMARK_RELATIVE(), fbcode_builder.FBCodeBuilder::cmake_configure(), fbcode_builder.FBCodeBuilder::cmake_install(), fbcode_builder.FBCodeBuilder::configure(), shell_builder.ShellFBCodeBuilder::copy_local_repo(), docker_builder.DockerFBCodeBuilder::copy_local_repo(), docker_builder.DockerFBCodeBuilder::debian_ccache_setup_steps(), fbcode_builder.FBCodeBuilder::diagnostics(), TestExtendingFormatter< containerMode, Args >::doFormatArg(), specs.fbzmq::fbcode_builder_spec(), gdb::fiber_activate(), folly::File::File(), folly::FormatValue< ToStringFailure >::format(), folly::FormatValue< KeyValue >::format(), folly::FormatValue< NoncopyableInt >::format(), folly::FormatValue< bool >::format(), folly::FormatValue< float >::format(), folly::FormatValue< dynamic >::format(), folly::FormatValue< detail::DefaultValueWrapper< dynamic, V > >::format(), format20Numbers(), folly::CustomLogFormatter::formatMessage(), folly::GlogStyleFormatter::formatMessage(), folly::ssl::getOpenSSLLongVersion(), fbcode_builder.FBCodeBuilder::github_project_workdir(), fbcode_builder.FBCodeBuilder::install_debian_deps(), fatal_test.FatalTests::is_debug_build(), folly::AutoTimer< Logger, Clock >::logFormat(), loggingFormatPrintf(), fbcode_builder.FBCodeBuilder::make_and_install(), make_docker_context::make_docker_context(), folly::MemoryMapping::mlock(), folly::SSLContext::needsPeerVerification(), fbcode_builder.FBCodeBuilder::option(), fbcode_builder.FBCodeBuilder::parallel_make(), parse_args::parse_args_to_fbcode_builder_opts(), testing::internal::PrintAsStringLiteralTo(), testing::internal::PrintCharAndCodeTo(), shell_quoting::raw_shell(), fbcode_builder.FBCodeBuilder::render(), rtrimWhitespace(), shell_builder.ShellFBCodeBuilder::run(), docker_builder.DockerFBCodeBuilder::run(), utils::run_command(), docker_builder.DockerFBCodeBuilder::setup(), shell_builder.ShellFBCodeBuilder::setup(), shell_quoting::shell_comment(), shell_builder.ShellFBCodeBuilder::step(), docker_builder.DockerFBCodeBuilder::step(), TEST(), uriUnescape(), shell_builder.ShellFBCodeBuilder::workdir(), docker_builder.DockerFBCodeBuilder::workdir(), and folly::MemoryMapping::~MemoryMapping().

271  {
272  return Formatter<false, Args...>(fmt, std::forward<Args>(args)...);
273 }
internal::ArgsMatcher< InnerMatcher > Args(const InnerMatcher &matcher)
template<class Str , class... Args>
std::enable_if<IsSomeString<Str>::value>::type folly::format ( Str *  out,
StringPiece  fmt,
Args &&...  args 
)

Append formatted output to a string.

std::string foo; format(&foo, "{} {}", 42, 23);

Shortcut for toAppend(format(...), &foo);

Definition at line 369 of file Format.h.

References type, and value.

Referenced by folly::Formatter< containerMode, Args >::doFormatArg(), formatChecked(), and sformat().

369  {
370  format(fmt, std::forward<Args>(args)...).appendTo(*out);
371 }
std::enable_if< IsSomeString< Str >::value >::type format(Str *out, StringPiece fmt, Args &&...args)
Definition: Format.h:369
template<class... Args>
Formatter<false, Args...> folly::formatChecked ( StringPiece  fmt,
Args &&...  args 
)

Definition at line 465 of file Format.h.

References testing::Args(), and format().

465  {
466  return format(fmt, std::forward<Args>(args)...);
467 }
std::enable_if< IsSomeString< Str >::value >::type format(Str *out, StringPiece fmt, Args &&...args)
Definition: Format.h:369
template<class Str , class... Args>
std::enable_if<IsSomeString<Str>::value>::type folly::formatChecked ( Str *  out,
StringPiece  fmt,
Args &&...  args 
)

Definition at line 484 of file Format.h.

References type, and value.

Referenced by sformatChecked().

484  {
485  formatChecked(fmt, std::forward<Args>(args)...).appendTo(*out);
486 }
std::enable_if< IsSomeString< Str >::value >::type formatChecked(Str *out, StringPiece fmt, Args &&...args)
Definition: Format.h:484
template<typename Src , typename Dst >
constexpr like_t<Src, Dst>&& folly::forward_like ( Dst &&  dst)
noexcept

Definition at line 107 of file Utility.h.

References exchange().

107  {
108  return static_cast<like_t<Src, Dst>&&>(std::forward<Dst>(dst));
109 }
template<typename Tuple >
auto folly::forward_tuple ( Tuple &&  tuple) -> decltype(detail::apply_tuple::adl::forward_tuple( std::declval<Tuple>(), std::declval< index_sequence_for_tuple<std::remove_reference_t<Tuple>>>()))
noexcept

Get a tuple of references from the passed tuple, forwarding will be applied on the individual types of the tuple based on the value category of the passed tuple

For example

forward_tuple(std::make_tuple(1, 2))

Returns a std::tuple<int&&, int&&>,

auto tuple = std::make_tuple(1, 2); forward_tuple(tuple)

Returns a std::tuple<int&, int&>

Definition at line 110 of file ApplyTuple.h.

References folly::detail::apply_tuple::adl::forward_tuple().

Referenced by TEST().

114  {
116  std::forward<Tuple>(tuple),
117  index_sequence_for_tuple<std::remove_reference_t<Tuple>>{});
118 }
make_index_sequence< std::tuple_size< Tuple >::value > index_sequence_for_tuple
Definition: ApplyTuple.h:36
auto forward_tuple(Tuple &&tuple) noexcept-> decltype(detail::apply_tuple::adl::forward_tuple(std::declval< Tuple >(), std::declval< index_sequence_for_tuple< std::remove_reference_t< Tuple >>>()))
Definition: ApplyTuple.h:110
template<bool implicit_unpack = true, typename Container >
front_emplace_iterator<Container, implicit_unpack> folly::front_emplacer ( Container &  c)

Convenience function to construct a folly::front_emplace_iterator, analogous to std::front_inserter().

Setting implicit_unpack to false will disable implicit unpacking of single std::pair and std::tuple arguments to the iterator's operator=. That may be desirable in case of constructors that expect a std::pair or std::tuple argument.

Examples:
/facebook/proxygen/proxygen/folly/folly/container/Iterator.h.

Definition at line 477 of file Iterator.h.

References c.

Referenced by TEST().

478  {
479  return front_emplace_iterator<Container, implicit_unpack>(c);
480 }
char c
int folly::fsyncNoInt ( int  fd)

Definition at line 64 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt().

Referenced by folly::detail::assertionFailure(), and folly::symbolizer::SafeStackTracePrinter::flush().

64  {
65  return int(wrapNoInt(fsync, fd));
66 }
ssize_t wrapNoInt(F f, Args...args)
int folly::ftruncateNoInt ( int  fd,
off_t  len 
)

Definition at line 86 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt().

Referenced by TEST().

86  {
87  return int(wrapNoInt(ftruncate, fd, len));
88 }
ssize_t wrapNoInt(F f, Args...args)
template<typename Map , typename Key >
Map::mapped_type folly::get_default ( const Map map,
const Key &  key 
)

Given a map and a key, return the value corresponding to the key in the map, or a given default value if the key doesn't exist in the map.

Definition at line 31 of file MapUtil.h.

References testing::Key(), type, value, and testing::Value().

Referenced by get_default(), folly::detail::EventBaseLocalBase::getVoid(), TEST(), and TEST_F().

31  {
32  auto pos = map.find(key);
33  return (pos != map.end()) ? (pos->second) : (typename Map::mapped_type{});
34 }
Definition: Traits.h:594
template<class Map , typename Key = typename Map::key_type, typename Value = typename Map::mapped_type, typename std::enable_if<!is_invocable< Value >::value >::type * = nullptr>
Map::mapped_type folly::get_default ( const Map map,
const Key &  key,
Value &&  dflt 
)

Definition at line 41 of file MapUtil.h.

References M.

41  {
42  using M = typename Map::mapped_type;
43  auto pos = map.find(key);
44  return (pos != map.end()) ? (pos->second) : M(std::forward<Value>(dflt));
45 }
Definition: Traits.h:594
**Optimized Holders **The template hazptr_array< M > provides most of the functionality *of M hazptr_holder s but with faster construction destruction *for M
Definition: Hazptr.h:104
template<class Map , typename Key = typename Map::key_type, typename Func , typename = typename std::enable_if< is_invocable_r<typename Map::mapped_type, Func>::value>::type>
Map::mapped_type folly::get_default ( const Map map,
const Key &  key,
Func &&  dflt 
)

Give a map and a key, return the value corresponding to the key in the map, or a given default value if the key doesn't exist in the map.

Definition at line 58 of file MapUtil.h.

58  {
59  auto pos = map.find(key);
60  return pos != map.end() ? pos->second : dflt();
61 }
Definition: Traits.h:594
template<class Map , class Key1 , class Key2 , class... KeysDefault, typename = typename std::enable_if<sizeof...(KeysDefault) != 0>::type>
auto folly::get_default ( const Map map,
const Key1 &  key1,
const Key2 &  key2,
const KeysDefault &...  keysDefault 
) -> typename detail::NestedMapType<Map, 1 + sizeof...(KeysDefault)>::type

Given a map and a path of keys, return the value corresponding to the nested value, or a given default value if the path doesn't exist in the map. The default value is the last parameter, and is copied when returned.

Definition at line 269 of file MapUtil.h.

References folly::detail::extract_default(), get_default(), get_ptr(), ptr, type, and value().

274  {
275  if (const auto* ptr = get_ptr(map, key1)) {
276  return get_default(*ptr, key2, keysDefault...);
277  }
278  return detail::extract_default(keysDefault...);
279 }
void * ptr
auto get_default(const Map &map, const Key1 &key1, const Key2 &key2, const KeysDefault &...keysDefault) -> typename detail::NestedMapType< Map, 1+sizeof...(KeysDefault)>::type
Definition: MapUtil.h:269
Definition: Traits.h:594
auto get_ptr(Map &map, const Key1 &key1, const Key2 &key2, const Keys &...keys) -> typename detail::NestedMapType< Map, 2+sizeof...(Keys)>::type *
Definition: MapUtil.h:252
auto extract_default(const KeysDefault &...keysDefault) -> typename DefaultType< KeysDefault... >::type const &
Definition: MapUtil.h:213
template<size_t I, typename... Args>
decltype(auto) folly::get_emplace_arg ( emplace_args< Args... > &&  args)
noexcept

Getter function for unpacking a single emplace argument.

Calling get_emplace_arg on an emplace_args rvalue reference results in perfect forwarding of the original input types. A special case are std::reference_wrapper and folly::rvalue_reference_wrapper objects within folly::emplace_args. These are also unwrapped so that the bare reference is returned.

std::get is not a customization point in the standard library, so the cleanest solution was to define our own getter function.

Examples:
/facebook/proxygen/proxygen/folly/folly/container/Iterator.h.

Definition at line 126 of file Iterator.h.

References testing::Args(), and folly::detail::unwrap_emplace_arg().

126  {
127  using Out = std::tuple<Args...>;
129  std::forward<std::tuple_element_t<I, Out>>(std::get<I>(args)));
130 }
decltype(auto) unwrap_emplace_arg(folly::rvalue_reference_wrapper< Arg > arg) noexcept
Definition: Iterator.h:107
internal::ArgsMatcher< InnerMatcher > Args(const InnerMatcher &matcher)
template<size_t I, typename... Args>
decltype(auto) folly::get_emplace_arg ( emplace_args< Args... > &  args)
noexcept

Definition at line 132 of file Iterator.h.

References testing::Args(), and folly::detail::unwrap_emplace_arg().

132  {
133  return detail::unwrap_emplace_arg(std::get<I>(args));
134 }
decltype(auto) unwrap_emplace_arg(folly::rvalue_reference_wrapper< Arg > arg) noexcept
Definition: Iterator.h:107
template<size_t I, typename... Args>
decltype(auto) folly::get_emplace_arg ( const emplace_args< Args... > &  args)
noexcept

Definition at line 136 of file Iterator.h.

References folly::detail::unwrap_emplace_arg().

136  {
137  return detail::unwrap_emplace_arg(std::get<I>(args));
138 }
decltype(auto) unwrap_emplace_arg(folly::rvalue_reference_wrapper< Arg > arg) noexcept
Definition: Iterator.h:107
template<size_t I, typename Args >
decltype(auto) folly::get_emplace_arg ( Args &&  args)
noexcept

Definition at line 140 of file Iterator.h.

References folly::gen::move.

140  {
141  return std::get<I>(std::move(args));
142 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<size_t I, typename Args >
decltype(auto) folly::get_emplace_arg ( Args &  args)
noexcept

Definition at line 144 of file Iterator.h.

144  {
145  return std::get<I>(args);
146 }
template<size_t I, typename Args >
decltype(auto) folly::get_emplace_arg ( const Args &  args)
noexcept

Definition at line 148 of file Iterator.h.

148  {
149  return std::get<I>(args);
150 }
template<class Map , typename Key = typename Map::key_type>
folly::Optional<typename Map::mapped_type> folly::get_optional ( const Map map,
const Key &  key 
)

Given a map and a key, return a Optional<V> if the key exists and None if the key does not exist in the map.

Definition at line 102 of file MapUtil.h.

References none.

Referenced by get_optional(), printResultComparison(), and TEST().

104  {
105  auto pos = map.find(key);
106  if (pos != map.end()) {
107  return folly::Optional<typename Map::mapped_type>(pos->second);
108  } else {
109  return folly::none;
110  }
111 }
Definition: Traits.h:594
constexpr None none
Definition: Optional.h:87
template<class Map , class Key1 , class Key2 , class... Keys>
auto folly::get_optional ( const Map map,
const Key1 &  key1,
const Key2 &  key2,
const Keys &...  keys 
) -> folly::Optional< typename detail::NestedMapType<Map, 2 + sizeof...(Keys)>::type>

Given a map of maps and a path of keys, return a Optional<V> if the nested key exists and None if the nested keys does not exist in the map.

Definition at line 224 of file MapUtil.h.

References get_optional(), and none.

230  {
231  auto pos = map.find(key1);
232  return pos != map.end() ? get_optional(pos->second, key2, keys...)
233  : folly::none;
234 }
—— Concurrent Priority Queue Implementation ——
Definition: AtomicBitSet.h:29
auto get_optional(const Map &map, const Key1 &key1, const Key2 &key2, const Keys &...keys) -> folly::Optional< typename detail::NestedMapType< Map, 2+sizeof...(Keys)>::type >
Definition: MapUtil.h:224
Definition: Traits.h:594
constexpr None none
Definition: Optional.h:87
template<class E = std::out_of_range, class Map , typename Key = typename Map::key_type>
const Map::mapped_type& folly::get_or_throw ( const Map map,
const Key &  key,
const std::string exceptionStrPrefix = std::string() 
)

Given a map and a key, return the value corresponding to the key in the map, or throw an exception of the specified type.

Definition at line 71 of file MapUtil.h.

Referenced by TEST(), and TEST_F().

74  {
75  auto pos = map.find(key);
76  if (pos != map.end()) {
77  return pos->second;
78  }
79  throw E(folly::to<std::string>(exceptionStrPrefix, key));
80 }
Definition: Traits.h:594
template<class E = std::out_of_range, class Map , typename Key = typename Map::key_type>
Map::mapped_type& folly::get_or_throw ( Map map,
const Key &  key,
const std::string exceptionStrPrefix = std::string() 
)

Definition at line 86 of file MapUtil.h.

89  {
90  auto pos = map.find(key);
91  if (pos != map.end()) {
92  return pos->second;
93  }
94  throw E(folly::to<std::string>(exceptionStrPrefix, key));
95 }
Definition: Traits.h:594
template<class T >
const T* folly::get_pointer ( const Optional< T > &  opt)

Definition at line 435 of file Optional.h.

References folly::Optional< Value >::get_pointer().

435  {
436  return opt.get_pointer();
437 }
template<class T >
T* folly::get_pointer ( Optional< T > &  opt)

Definition at line 440 of file Optional.h.

References folly::Optional< Value >::get_pointer().

440  {
441  return opt.get_pointer();
442 }
template<class Value , class Error >
const Value* folly::get_pointer ( const Expected< Value, Error > &  ex)
noexcept

Definition at line 1374 of file Expected.h.

Referenced by folly::Optional< NamedGroup >::get_pointer(), folly::Expected< int, E >::get_pointer(), and TEST().

1374  {
1375  return ex.get_pointer();
1376 }
template<class Value , class Error >
Value* folly::get_pointer ( Expected< Value, Error > &  ex)
noexcept

Definition at line 1379 of file Expected.h.

1379  {
1380  return ex.get_pointer();
1381 }
template<class Map , typename Key = typename Map::key_type>
const Map::mapped_type* folly::get_ptr ( const Map map,
const Key &  key 
)

Given a map and a key, return a pointer to the value corresponding to the key in the map, or nullptr if the key doesn't exist in the map.

Definition at line 169 of file MapUtil.h.

Referenced by folly::test::ManualSchedule::beforeSharedAccess(), folly::StandardLogHandlerFactory::createHandler(), get_default(), get_ptr(), get_ref_default(), folly::DynamicParser::optional(), TEST(), folly::TestLogHandlerFactory::updateHandler(), and folly::LogCategory::updateHandlers().

169  {
170  auto pos = map.find(key);
171  return (pos != map.end() ? &pos->second : nullptr);
172 }
Definition: Traits.h:594
template<class Map , typename Key = typename Map::key_type>
Map::mapped_type* folly::get_ptr ( Map map,
const Key &  key 
)

Non-const overload of the above.

Definition at line 178 of file MapUtil.h.

References T, and type.

178  {
179  auto pos = map.find(key);
180  return (pos != map.end() ? &pos->second : nullptr);
181 }
Definition: Traits.h:594
template<class Map , class Key1 , class Key2 , class... Keys>
auto folly::get_ptr ( const Map map,
const Key1 &  key1,
const Key2 &  key2,
const Keys &...  keys 
) -> typename detail::NestedMapType<Map, 2 + sizeof...(Keys)>::type const*

Given a map of maps and a path of keys, return a pointer to the nested value, or nullptr if the key doesn't exist in the map.

Definition at line 241 of file MapUtil.h.

References get_ptr().

246  {
247  auto pos = map.find(key1);
248  return pos != map.end() ? get_ptr(pos->second, key2, keys...) : nullptr;
249 }
#define nullptr
Definition: http_parser.c:41
Definition: Traits.h:594
auto get_ptr(Map &map, const Key1 &key1, const Key2 &key2, const Keys &...keys) -> typename detail::NestedMapType< Map, 2+sizeof...(Keys)>::type *
Definition: MapUtil.h:252
template<class Map , class Key1 , class Key2 , class... Keys>
auto folly::get_ptr ( Map map,
const Key1 &  key1,
const Key2 &  key2,
const Keys &...  keys 
) -> typename detail::NestedMapType<Map, 2 + sizeof...(Keys)>::type*

Definition at line 252 of file MapUtil.h.

References get_ptr(), and type.

253  {
254  auto pos = map.find(key1);
255  return pos != map.end() ? get_ptr(pos->second, key2, keys...) : nullptr;
256 }
#define nullptr
Definition: http_parser.c:41
Definition: Traits.h:594
auto get_ptr(Map &map, const Key1 &key1, const Key2 &key2, const Keys &...keys) -> typename detail::NestedMapType< Map, 2+sizeof...(Keys)>::type *
Definition: MapUtil.h:252
template<class Map , typename Key = typename Map::key_type>
const Map::mapped_type& folly::get_ref_default ( const Map map,
const Key &  key,
const typename Map::mapped_type &  dflt 
)

Given a map and a key, return a reference to the value corresponding to the key in the map, or the given default reference if the key doesn't exist in the map.

Definition at line 119 of file MapUtil.h.

References type, and value().

Referenced by get_ref_default(), folly::RequestContext::getContextData(), and TEST().

122  {
123  auto pos = map.find(key);
124  return (pos != map.end() ? pos->second : dflt);
125 }
Definition: Traits.h:594
template<class Map , typename Key = typename Map::key_type>
const Map::mapped_type& folly::get_ref_default ( const Map map,
const Key &  key,
typename Map::mapped_type &&  dflt 
)
delete

Passing a temporary default value returns a dangling reference when it is returned. Lifetime extension is broken by the indirection. The caller must ensure that the default value outlives the reference returned by get_ref_default().

template<class Map , typename Key = typename Map::key_type>
const Map::mapped_type& folly::get_ref_default ( const Map map,
const Key &  key,
const typename Map::mapped_type &&  dflt 
)
delete
template<class Map , typename Key = typename Map::key_type, typename Func , typename = typename std::enable_if< is_invocable_r<const typename Map::mapped_type&, Func>::value>::type, typename = typename std::enable_if< std::is_reference<invoke_result_t<Func>>::value>::type>
const Map::mapped_type& folly::get_ref_default ( const Map map,
const Key &  key,
Func &&  dflt 
)

Given a map and a key, return a reference to the value corresponding to the key in the map, or the given default reference if the key doesn't exist in the map.

Definition at line 159 of file MapUtil.h.

159  {
160  auto pos = map.find(key);
161  return (pos != map.end() ? pos->second : dflt());
162 }
Definition: Traits.h:594
template<class Map , class Key1 , class Key2 , class... KeysDefault, typename = typename std::enable_if<sizeof...(KeysDefault) != 0>::type, typename = typename std::enable_if<std::is_lvalue_reference< typename detail::DefaultType<KeysDefault...>::type>::value>::type>
auto folly::get_ref_default ( const Map map,
const Key1 &  key1,
const Key2 &  key2,
KeysDefault &&...  keysDefault 
) -> typename detail::NestedMapType<Map, 1 + sizeof...(KeysDefault)>::type const&

Given a map and a path of keys, return a reference to the value corresponding to the nested value, or the given default reference if the path doesn't exist in the map. The default value is the last parameter, and must be a lvalue reference.

Definition at line 295 of file MapUtil.h.

References folly::detail::extract_default(), get_ptr(), get_ref_default(), and ptr.

301  {
302  if (const auto* ptr = get_ptr(map, key1)) {
303  return get_ref_default(*ptr, key2, keysDefault...);
304  }
305  return detail::extract_default(keysDefault...);
306 }
void * ptr
auto get_ref_default(const Map &map, const Key1 &key1, const Key2 &key2, KeysDefault &&...keysDefault) -> typename detail::NestedMapType< Map, 1+sizeof...(KeysDefault)>::typeconst &
Definition: MapUtil.h:295
Definition: Traits.h:594
auto get_ptr(Map &map, const Key1 &key1, const Key2 &key2, const Keys &...keys) -> typename detail::NestedMapType< Map, 2+sizeof...(Keys)>::type *
Definition: MapUtil.h:252
auto extract_default(const KeysDefault &...keysDefault) -> typename DefaultType< KeysDefault... >::type const &
Definition: MapUtil.h:213
template<typename Pointer >
constexpr Pointer const& folly::get_underlying ( propagate_const< Pointer > const &  obj)

Definition at line 37 of file PropagateConst.h.

References folly::propagate_const< Pointer >::pointer_.

37  {
38  return obj.pointer_;
39 }
const char * folly::getBaseLoggingConfig ( )

folly::getBaseLoggingConfig() allows individual executables to easily customize their default logging configuration.

You can define this function in your executable and folly::initLogging() will call it to get the base logging configuration. The settings returned by getBaseLoggingConfig() will then be modified by updating them with the configuration string parameter passed to initLogging().

This allows the user-specified configuration passed to initLogging() to update the base configuration. The user-specified configuration can apply additional settings, and it may also override settings for categories and handlers defined in the base configuration.

See folly/logging/example/main.cpp for an example that defines getBaseLoggingConfig().

If this function returns a non-null pointer, it should point to a null-terminated string with static storage duration.

Definition at line 29 of file InitWeak.cpp.

Referenced by initLogging().

29  {
30  return nullptr;
31 }
template<typename T , size_t Stripes>
CxxAllocatorAdaptor<T, typename CoreRawAllocator<Stripes>::Allocator> folly::getCoreAllocator ( size_t  stripe)

Definition at line 522 of file CacheLocality.h.

References folly::Indestructible< T >::get().

522  {
523  // We cannot make sure that the allocator will be destroyed after
524  // all the objects allocated with it, so we leak it.
525  static Indestructible<CoreRawAllocator<Stripes>> allocator;
526  return CxxAllocatorAdaptor<T, typename CoreRawAllocator<Stripes>::Allocator>(
527  *allocator->get(stripe));
528 }
std::shared_ptr< folly::Executor > folly::getCPUExecutor ( )

Retrieve the global Executor. If there is none, a default InlineExecutor will be constructed and returned. This is named CPUExecutor to distinguish it from IOExecutor below and to hint that it's intended for CPU-bound tasks.

Can return nullptr on shutdown.

Definition at line 90 of file GlobalExecutor.cpp.

References singleton.

Referenced by async(), StaticService::StaticHandler::onEgressResumed(), StaticService::StaticHandler::onRequest(), and TEST().

90  {
91  if (auto singleton = gGlobalCPUExecutor.try_get()) {
92  return singleton->get();
93  }
94  return nullptr;
95 }
static Singleton< ShutdownSocketSet, PrivateTag > singleton
void folly::getctx ( std::shared_ptr< folly::SSLContext clientCtx,
std::shared_ptr< folly::SSLContext serverCtx 
)

Definition at line 131 of file AsyncSSLSocketTest.cpp.

References kTestCert, and kTestKey.

Referenced by folly::TestSSLAsyncCacheServer::getSessionCallback(), folly::SSLSessionTest::SetUp(), sslsocketpair(), and TEST().

133  {
134  clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
135 
136  serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
137  serverCtx->loadCertificate(kTestCert);
138  serverCtx->loadPrivateKey(kTestKey);
139 }
const char * kTestCert
const std::string kTestKey
uint64_t folly::getCurrentThreadID ( )
inline

Get a process-specific identifier for the current thread.

The return value will uniquely identify the thread within the current process.

Note that the return value does not necessarily correspond to an operating system thread ID. The return value is also only unique within the current process: getCurrentThreadID() may return the same value for two concurrently running threads in separate processes.

The thread ID may be reused once the thread it corresponds to has been joined.

Definition at line 42 of file ThreadId.h.

References uint64_t.

Referenced by folly::ssl::detail::callbackThreadID(), folly::HashingThreadId::get(), folly::detail::MemoryIdler::getVariationTimeout(), ShardedAtomicInt::inc(), and TEST().

42  {
43 #if __APPLE__
44  return uint64_t(pthread_mach_thread_np(pthread_self()));
45 #elif _WIN32
46  return uint64_t(GetCurrentThreadId());
47 #else
48  return uint64_t(pthread_self());
49 #endif
50 }
Optional< std::string > folly::getCurrentThreadName ( )

Equivalent to getThreadName(std::this_thread::get_id());

Definition at line 105 of file ThreadName.cpp.

References getThreadName().

Referenced by TEST(), and TEST_F().

105  {
106  return getThreadName(std::this_thread::get_id());
107 }
Optional< std::string > getThreadName(std::thread::id id)
Definition: ThreadName.cpp:90
void folly::getfds ( int  fds[2])

Definition at line 114 of file AsyncSSLSocketTest.cpp.

References errnoStr(), FAIL, and folly::netops::socketpair().

Referenced by folly::TestSSLAsyncCacheServer::getSessionCallback(), sslsocketpair(), TEST(), and TEST_F().

114  {
115  if (socketpair(PF_LOCAL, SOCK_STREAM, 0, fds) != 0) {
116  FAIL() << "failed to create socketpair: " << errnoStr(errno);
117  }
118  for (int idx = 0; idx < 2; ++idx) {
119  int flags = fcntl(fds[idx], F_GETFL, 0);
120  if (flags == -1) {
121  FAIL() << "failed to get flags for socket " << idx << ": "
122  << errnoStr(errno);
123  }
124  if (fcntl(fds[idx], F_SETFL, flags | O_NONBLOCK) != 0) {
125  FAIL() << "failed to put socket " << idx
126  << " in non-blocking mode: " << errnoStr(errno);
127  }
128  }
129 }
flags
Definition: http_parser.h:127
#define FAIL()
Definition: gtest.h:1822
fbstring errnoStr(int err)
Definition: String.cpp:463
int socketpair(int domain, int type, int protocol, NetworkSocket sv[2])
Definition: NetOps.cpp:416
std::string folly::getFileAsBuf ( const char *  fileName)

Definition at line 179 of file AsyncSSLSocketTest.cpp.

References buffer(), readFile(), and string.

Referenced by TEST().

179  {
181  folly::readFile(fileName, buffer);
182  return buffer;
183 }
std::vector< uint8_t > buffer(kBufferSize+16)
bool readFile(int fd, Container &out, size_t num_bytes=std::numeric_limits< size_t >::max())
Definition: FileUtil.h:125
const char * string
Definition: Conv.cpp:212
boost::program_options::options_description folly::getGFlags ( ProgramOptionsStyle  style)

Definition at line 270 of file ProgramOptions.cpp.

References folly::NestedCommandLineParseResult::command, f, folly::gen::move, folly::NestedCommandLineParseResult::options, parser, folly::NestedCommandLineParseResult::rest, and tokens.

Referenced by folly::NestedCommandLineApp::addGFlags(), and main().

270  {
271  static const std::unordered_set<std::string> gSkipFlags{
272  "flagfile",
273  "fromenv",
274  "tryfromenv",
275  "undefok",
276  "help",
277  "helpfull",
278  "helpshort",
279  "helpon",
280  "helpmatch",
281  "helppackage",
282  "helpxml",
283  "version",
284  "tab_completion_columns",
285  "tab_completion_word",
286  };
287 
288  po::options_description desc("GFlags");
289 
290  std::vector<gflags::CommandLineFlagInfo> allFlags;
291  gflags::GetAllFlags(&allFlags);
292 
293  for (auto& f : allFlags) {
294  if (gSkipFlags.count(f.name)) {
295  continue;
296  }
297  auto pos = gFlagAdders.find(f.type);
298  CHECK(pos != gFlagAdders.end()) << "Invalid flag type: " << f.type;
299  (*pos->second)(std::move(f), desc, style);
300  }
301 
302  return desc;
303 }
auto f
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
size_t folly::getGlobalBenchmarkBaselineIndex ( )

Definition at line 92 of file Benchmark.cpp.

References folly::detail::addBenchmarkImpl(), folly::test::begin(), benchmarks(), folly::test::end(), FB_FOLLY_GLOBAL_BENCHMARK_BASELINE, FB_STRINGIZE_X2, fun(), folly::gen::move, folly::detail::BenchmarkRegistration::name, and name.

Referenced by runBenchmarks().

92  {
94  auto it = std::find_if(
95  benchmarks().begin(),
96  benchmarks().end(),
97  [global](const detail::BenchmarkRegistration& v) {
98  return v.name == global;
99  });
100  CHECK(it != benchmarks().end());
101  return size_t(std::distance(benchmarks().begin(), it));
102 }
vector< detail::BenchmarkRegistration > & benchmarks()
Definition: Benchmark.cpp:75
#define FB_STRINGIZE_X2(x)
Definition: Benchmark.cpp:81
auto begin(TestAdlIterable &instance)
Definition: ForeachTest.cpp:56
auto end(TestAdlIterable &instance)
Definition: ForeachTest.cpp:62
#define FB_FOLLY_GLOBAL_BENCHMARK_BASELINE
Definition: Benchmark.cpp:80
const HugePageSize * folly::getHugePageSize ( size_t  size = 0)

Return the mount point for the requested huge page size. 0 = use smallest available. Returns nullptr if the requested huge page size is not available.

Definition at line 206 of file HugePages.cpp.

References getHugePageSizes().

206  {
207  // Linear search is just fine.
208  for (auto& p : getHugePageSizes()) {
209  if (p.mountPoint.empty()) {
210  continue;
211  }
212  if (size == 0 || size == p.size) {
213  return &p;
214  }
215  }
216  return nullptr;
217 }
const HugePageSizeVec & getHugePageSizes()
Definition: HugePages.cpp:201
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
const HugePageSize * folly::getHugePageSizeForDevice ( dev_t  device)

Return the huge page size for a device. returns nullptr if device does not refer to a huge page filesystem.

Definition at line 219 of file HugePages.cpp.

References getHugePageSizes().

Referenced by folly::MemoryMapping::MemoryMapping().

219  {
220  // Linear search is just fine.
221  for (auto& p : getHugePageSizes()) {
222  if (p.mountPoint.empty()) {
223  continue;
224  }
225  if (device == p.device) {
226  return &p;
227  }
228  }
229  return nullptr;
230 }
const HugePageSizeVec & getHugePageSizes()
Definition: HugePages.cpp:201
const HugePageSizeVec & folly::getHugePageSizes ( )

Get list of supported huge page sizes and their mount points, if hugetlbfs file systems are mounted for those sizes.

Definition at line 201 of file HugePages.cpp.

References sizes.

Referenced by getHugePageSize(), and getHugePageSizeForDevice().

201  {
202  static HugePageSizeVec sizes = readHugePageSizes();
203  return sizes;
204 }
std::vector< HugePageSize > HugePageSizeVec
Definition: HugePages.h:59
const int sizes[]
std::shared_ptr< IOExecutor > folly::getIOExecutor ( )

Retrieve the global IOExecutor. If there is none, a default IOThreadPoolExecutor will be constructed and returned.

IOExecutors differ from Executors in that they drive and provide access to one or more EventBases.

Can return nullptr on shutdown.

Definition at line 103 of file GlobalExecutor.cpp.

References singleton.

Referenced by folly::IOObjectCache< T >::get(), getEventBase(), and TEST().

103  {
104  if (auto singleton = gGlobalIOExecutor.try_get()) {
105  return singleton->get();
106  }
107  return nullptr;
108 }
static Singleton< ShutdownSocketSet, PrivateTag > singleton
template<typename ExecutorT >
Executor::KeepAlive<ExecutorT> folly::getKeepAliveToken ( ExecutorT *  executor)

Returns a keep-alive token which guarantees that Executor will keep processing tasks until the token is released (if supported by Executor). KeepAlive always contains a valid pointer to an Executor.

Definition at line 200 of file Executor.h.

References folly::Executor::getKeepAliveToken(), and value.

Referenced by keepAliveTest(), RecursiveAddTest(), folly::fibers::ExecutorLoopController::runLoop(), folly::fibers::EventBaseLoopController::runLoop(), folly::fibers::ExecutorLoopController::schedule(), folly::fibers::EventBaseLoopController::schedule(), folly::fibers::ExecutorLoopController::scheduleThreadSafe(), folly::fibers::EventBaseLoopController::scheduleThreadSafe(), folly::futures::detail::Core< T >::setExecutor(), SimpleTest(), folly::SemiFuture< T >::stealDeferredExecutor(), TEST(), folly::SemiFuture< T >::via(), folly::Future< T >::via(), folly::futures::detail::waitViaImpl(), and window().

200  {
201  static_assert(
203  "getKeepAliveToken only works for folly::Executor implementations.");
205 }
PUSHMI_INLINE_VAR constexpr __adl::get_executor_fn executor
Executor::KeepAlive< ExecutorT > getKeepAliveToken(ExecutorT &executor)
Definition: Executor.h:208
static const char *const value
Definition: Conv.cpp:50
template<typename ExecutorT >
Executor::KeepAlive<ExecutorT> folly::getKeepAliveToken ( ExecutorT &  executor)

Definition at line 208 of file Executor.h.

References folly::Executor::getKeepAliveToken(), and value.

208  {
209  static_assert(
211  "getKeepAliveToken only works for folly::Executor implementations.");
212  return getKeepAliveToken(&executor);
213 }
PUSHMI_INLINE_VAR constexpr __adl::get_executor_fn executor
Executor::KeepAlive< ExecutorT > getKeepAliveToken(ExecutorT &executor)
Definition: Executor.h:208
static const char *const value
Definition: Conv.cpp:50
libevent_fd_t folly::getLibeventFd ( int  fd)
inline

Definition at line 40 of file Event.h.

References folly::netops::detail::SocketFileDescriptorMap::fdToSocket().

Referenced by folly_event_set().

40  {
41  return netops::detail::SocketFileDescriptorMap::fdToSocket(fd);
42 }
static int folly::getLinuxVersion ( StringPiece  release)
static

Definition at line 47 of file TimeUtil.cpp.

References errnoStr(), f, FILE, folly::Range< Iter >::find(), int64_t, SCOPE_EXIT, and folly::Range< Iter >::subpiece().

47  {
48  auto dot1 = release.find('.');
49  if (dot1 == StringPiece::npos) {
50  throw std::invalid_argument("could not find first dot");
51  }
52  auto v1 = folly::to<int>(release.subpiece(0, dot1));
53 
54  auto dot2 = release.find('.', dot1 + 1);
55  if (dot2 == StringPiece::npos) {
56  throw std::invalid_argument("could not find second dot");
57  }
58  auto v2 = folly::to<int>(release.subpiece(dot1 + 1, dot2 - (dot1 + 1)));
59 
60  int dash = release.find('-', dot2 + 1);
61  auto v3 = folly::to<int>(release.subpiece(dot2 + 1, dash - (dot2 + 1)));
62 
63  return ((v1 * 1000 + v2) * 1000) + v3;
64 }
uint64_t folly::getOSThreadID ( )
inline

Get the operating-system level thread ID for the current thread.

The returned value will uniquely identify this thread on the system.

This makes it more suitable for logging or displaying in user interfaces than the result of getCurrentThreadID().

There are some potential caveats about this API, however:

  • In theory there is no guarantee that application threads map one-to-one to kernel threads. An application threading implementation could potentially share one OS thread across multiple application threads, and/or it could potentially move application threads between different OS threads over time. However, in practice all of the platforms we currently support have a one-to-one mapping between userspace threads and operating system threads.
  • This API may also be slightly slower than getCurrentThreadID() on some platforms. This API may require a system call, where getCurrentThreadID() may only need to read thread-local memory.

On Linux the returned value is a pid_t, and can be used in contexts requiring a thread pid_t.

The thread ID may be reused once the thread it corresponds to has been joined.

Definition at line 80 of file ThreadId.h.

References FOLLY_SYS_gettid, and uint64_t.

Referenced by folly::LogMessage::LogMessage(), folly::TimePoint::reset(), and TEST().

80  {
81 #if __APPLE__
82  uint64_t tid;
83  pthread_threadid_np(nullptr, &tid);
84  return tid;
85 #elif _WIN32
86  return uint64_t(GetCurrentThreadId());
87 #else
88  return uint64_t(syscall(FOLLY_SYS_gettid));
89 #endif
90 }
#define FOLLY_SYS_gettid
Definition: SysSyscall.h:27
static nanoseconds folly::getSchedTimeWaiting ( pid_t  tid)
static

Determine how long this process has spent waiting to get scheduled on the CPU.

Returns the number of nanoseconds spent waiting, or -1 if the amount of time cannot be determined.

Definition at line 160 of file TimeUtil.cpp.

References folly::netops::close(), int64_t, fizz::detail::read(), and uint64_t.

Referenced by folly::TimePoint::reset().

160  {
161 #ifndef __linux__
162  (void)tid;
163  return nanoseconds(0);
164 #else
165  static int64_t timeUnits = determineSchedstatUnits();
166  if (timeUnits < 0) {
167  // We couldn't figure out how many jiffies there are in a second.
168  // Don't bother reading the schedstat info if we can't interpret it.
169  return nanoseconds(0);
170  }
171 
172  int fd = -1;
173  try {
174  char schedstatFile[256];
175  snprintf(schedstatFile, sizeof(schedstatFile), "/proc/%d/schedstat", tid);
176  fd = open(schedstatFile, O_RDONLY);
177  if (fd < 0) {
178  throw std::runtime_error(
179  folly::to<string>("failed to open process schedstat file", errno));
180  }
181 
182  char buf[512];
183  ssize_t bytesReadRet = read(fd, buf, sizeof(buf) - 1);
184  if (bytesReadRet <= 0) {
185  throw std::runtime_error(
186  folly::to<string>("failed to read process schedstat file", errno));
187  }
188  size_t bytesRead = size_t(bytesReadRet);
189 
190  if (buf[bytesRead - 1] != '\n') {
191  throw std::runtime_error("expected newline at end of schedstat data");
192  }
193  assert(bytesRead < sizeof(buf));
194  buf[bytesRead] = '\0';
195 
196  uint64_t activeJiffies = 0;
197  uint64_t waitingJiffies = 0;
198  uint64_t numTasks = 0;
199  int rc = sscanf(
200  buf,
201  "%" PRIu64 " %" PRIu64 " %" PRIu64 "\n",
202  &activeJiffies,
203  &waitingJiffies,
204  &numTasks);
205  if (rc != 3) {
206  throw std::runtime_error("failed to parse schedstat data");
207  }
208 
209  close(fd);
210  return nanoseconds(waitingJiffies * timeUnits);
211  } catch (const std::runtime_error& e) {
212  if (fd >= 0) {
213  close(fd);
214  }
215  LOG(ERROR) << "error determining process wait time: %s" << e.what();
216  return nanoseconds(0);
217  }
218 #endif
219 }
size_t read(T &out, folly::io::Cursor &cursor)
Definition: Types-inl.h:258
int close(NetworkSocket s)
Definition: NetOps.cpp:90
SyncVecThreadPoolExecutors& folly::getSyncVecThreadPoolExecutors ( )

Definition at line 27 of file ThreadPoolExecutor.cpp.

References DEFINE_int64().

Referenced by folly::ThreadPoolExecutor::ThreadPoolExecutor(), folly::ThreadPoolExecutor::withAll(), and folly::ThreadPoolExecutor::~ThreadPoolExecutor().

27  {
28  static Indestructible<SyncVecThreadPoolExecutors> storage;
29  return *storage;
30 }
static CacheLocality folly::getSystemLocalityInfo ( )
static

Returns the best real CacheLocality information available.

Definition at line 36 of file CacheLocality.cpp.

References kIsLinux, folly::CacheLocality::readFromSysfs(), and folly::CacheLocality::uniform().

Referenced by CacheLocality::system< std::atomic >().

36  {
37  if (kIsLinux) {
38  try {
39  return CacheLocality::readFromSysfs();
40  } catch (...) {
41  // keep trying
42  }
43  }
44 
45  long numCpus = sysconf(_SC_NPROCESSORS_CONF);
46  if (numCpus <= 0) {
47  // This shouldn't happen, but if it does we should try to keep
48  // going. We are probably not going to be able to parse /sys on
49  // this box either (although we will try), which means we are going
50  // to fall back to the SequentialThreadId splitter. On my 16 core
51  // (x hyperthreading) dev box 16 stripes is enough to get pretty good
52  // contention avoidance with SequentialThreadId, and there is little
53  // improvement from going from 32 to 64. This default gives us some
54  // wiggle room
55  numCpus = 32;
56  }
57  return CacheLocality::uniform(size_t(numCpus));
58 }
constexpr auto kIsLinux
Definition: Portability.h:361
Optional< std::string > folly::getThreadName ( std::thread::id  tid)

Get the name of the given thread, or nothing if an error occurs or the functionality is not available.

Definition at line 90 of file ThreadName.cpp.

References make_optional(), and string.

Referenced by folly::EventBase::checkIsInEventBaseThread(), getCurrentThreadName(), and TEST().

90  {
91 #if FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME || \
92  FOLLY_HAS_PTHREAD_SETNAME_NP_NAME
93  std::array<char, kMaxThreadNameLength> buf;
94  if (pthread_getname_np(stdTidToPthreadId(id), buf.data(), buf.size()) != 0) {
95  return Optional<std::string>();
96  }
97  return folly::make_optional(std::string(buf.data()));
98 #else
99  // There's not actually a way to get the thread name on Windows because
100  // thread names are a concept managed by the debugger, not the runtime.
101  return Optional<std::string>();
102 #endif
103 }
constexpr Optional< _t< std::decay< T > > > make_optional(T &&v)
Definition: Optional.h:450
const char * string
Definition: Conv.cpp:212
static std::chrono::milliseconds folly::getTimeDelta ( std::chrono::steady_clock::time_point *  prev)
static

Definition at line 241 of file EventBase.cpp.

References now().

Referenced by folly::EventBase::loopBody().

242  {
243  auto result = std::chrono::steady_clock::now() - *prev;
245 
246  return std::chrono::duration_cast<std::chrono::milliseconds>(result);
247 }
std::chrono::steady_clock::time_point now()
folly::StringPiece folly::getXlogCategoryNameForFile ( folly::StringPiece  filename)

Get the default XLOG() category name for the given filename.

This function returns the category name that will be used by XLOG() if XLOG_SET_CATEGORY_NAME() has not been used.

Definition at line 57 of file xlog.cpp.

References folly::Range< Iter >::startsWith().

Referenced by folly::XlogCategoryInfo< IsInHeaderFile >::init(), folly::XlogLevelInfo< IsInHeaderFile >::loadLevelFull(), and TEST_F().

57  {
58  // Buck mangles the directory layout for header files. Rather than including
59  // them from their original location, it moves them into deep directories
60  // inside buck-out, and includes them from there.
61  //
62  // If this path looks like a buck header directory, try to strip off the
63  // buck-specific portion.
64  if (filename.startsWith("buck-out/")) {
65  filename = stripBuckOutPrefix(filename);
66  }
67 
68  return filename;
69 }
bool startsWith(const const_range_type &other) const
Definition: Range.h:828
static uint32_t folly::gf_multiply_crc32_hw ( uint64_t  ,
uint64_t  ,
uint32_t   
)
static

Definition at line 114 of file Crc32CombineDetail.cpp.

Referenced by folly::detail::crc32_combine_hw().

114  {
115  return 0;
116 }
static uint32_t folly::gf_multiply_crc32c_hw ( uint64_t  ,
uint64_t  ,
uint32_t   
)
static

Definition at line 111 of file Crc32CombineDetail.cpp.

Referenced by folly::detail::crc32c_combine_hw().

111  {
112  return 0;
113 }
static constexpr uint32_t folly::gf_multiply_sw ( uint32_t  a,
uint32_t  b,
uint32_t  m 
)
static

Definition at line 41 of file Crc32CombineDetail.cpp.

References gf_multiply_sw_1().

Referenced by folly::detail::crc32_combine_sw(), folly::detail::crc32c_combine_sw(), and gf_square_sw().

41  {
42  return gf_multiply_sw_1(/* i = */ 0, /* p = */ 0, a, b, m);
43 }
static constexpr uint32_t gf_multiply_sw_1(size_t i, uint32_t p, uint32_t a, uint32_t b, uint32_t m)
char b
static map< string, int > m
char a
static constexpr uint32_t folly::gf_multiply_sw_1 ( size_t  i,
uint32_t  p,
uint32_t  a,
uint32_t  b,
uint32_t  m 
)
static

Definition at line 31 of file Crc32CombineDetail.cpp.

Referenced by gf_multiply_sw().

31  {
32  // clang-format off
33  return i == 32 ? p : gf_multiply_sw_1(
34  /* i = */ i + 1,
35  /* p = */ p ^ (-((b >> 31) & 1) & a),
36  /* a = */ (a >> 1) ^ (-(a & 1) & m),
37  /* b = */ b << 1,
38  /* m = */ m);
39  // clang-format on
40 }
static constexpr uint32_t gf_multiply_sw_1(size_t i, uint32_t p, uint32_t a, uint32_t b, uint32_t m)
char b
static map< string, int > m
char a
static constexpr uint32_t folly::gf_square_sw ( uint32_t  a,
uint32_t  m 
)
static

Definition at line 45 of file Crc32CombineDetail.cpp.

References gf_multiply_sw().

45  {
46  return gf_multiply_sw(a, a, m);
47 }
static map< string, int > m
char a
static constexpr uint32_t gf_multiply_sw(uint32_t a, uint32_t b, uint32_t m)
JemallocNodumpAllocator & folly::globalJemallocNodumpAllocator ( )

JemallocNodumpAllocator singleton.

Definition at line 163 of file JemallocNodumpAllocator.cpp.

References folly::JemallocNodumpAllocator::JemallocNodumpAllocator().

163  {
164  static auto instance = new JemallocNodumpAllocator();
165  return *instance;
166 }
std::atomic<EventBaseManager*> folly::globalManager ( nullptr  )
size_t folly::goodMallocSize ( size_t  minSize)
inlinenoexcept
template<typename RHS , RHS rhs, typename LHS >
bool folly::greater_than ( LHS const  lhs)

Definition at line 704 of file Traits.h.

Referenced by folly::detail::convertTo().

704  {
705  return detail::
707  lhs);
708 }
PskType type
size_t folly::hash_value ( const IPAddressV4 addr)

Definition at line 33 of file IPAddressV4.cpp.

References folly::IPAddressV4::hash().

33  {
34  return addr.hash();
35 }
ThreadPoolListHook * addr
size_t folly::hash_value ( const IPAddress &  addr)

Definition at line 34 of file IPAddress.cpp.

Referenced by folly::IPAddressV4::AddressStorage::AddressStorage().

34  {
35  return addr.hash();
36 }
ThreadPoolListHook * addr
std::size_t folly::hash_value ( const IPAddressV6 addr)

Definition at line 51 of file IPAddressV6.cpp.

References folly::IPAddressV6::hash().

51  {
52  return addr.hash();
53 }
ThreadPoolListHook * addr
size_t folly::hash_value ( const SocketAddress address)

Hash a SocketAddress object.

boost::hash uses hash_value(), so this allows boost::hash to automatically work for SocketAddress.

Definition at line 771 of file SocketAddress.cpp.

References folly::SocketAddress::hash().

771  {
772  return address.hash();
773 }
template<template< typename > class Atom = std::atomic>
void folly::hazptr_cleanup ( hazptr_domain< Atom > &  domain = default_hazptr_domain<Atom>())
noexcept

hazptr_cleanup

hazptr_cleanup: Reclaims all reclaimable objects retired to the domain

Definition at line 384 of file HazptrDomain.h.

Referenced by cleanup_bench(), run_once(), and TEST().

384  {
385  domain.cleanup();
386 }
template<template< typename > class Atom = std::atomic>
void folly::hazptr_domain_push_retired ( hazptr_obj_list< Atom > &  l,
bool  check = true,
hazptr_domain< Atom > &  domain = default_hazptr_domain<Atom>() 
)
noexcept

hazptr_domain_push_retired

hazptr_domain_push_retired: push a list of retired objects into a domain

Definition at line 369 of file HazptrDomain.h.

References Atom, check(), D, and T.

Referenced by folly::hazptr_obj< Atom >::push_to_retired().

372  {
373  domain.push_retired(l, check);
374 }
bool check(const dynamic &schema, const dynamic &value, bool check=true)
template<template< typename > class Atom = std::atomic>
hazptr_priv<Atom>& folly::hazptr_priv_tls ( )

hazptr_priv_tls

template<template< typename > class Atom = std::atomic, typename T , typename D = std::default_delete<T>>
void folly::hazptr_retire ( T obj,
D  reclaim 
)

hazptr_retire

Definition at line 378 of file HazptrDomain.h.

References Atom, and folly::gen::move.

378  {
379  default_hazptr_domain<Atom>().retire(obj, std::move(reclaim));
380 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<template< typename > class Atom, typename T , typename D >
FOLLY_ALWAYS_INLINE void folly::hazptr_retire ( T obj,
D  reclaim 
)

hazptr_retire

Definition at line 378 of file HazptrDomain.h.

References Atom, and folly::gen::move.

378  {
379  default_hazptr_domain<Atom>().retire(obj, std::move(reclaim));
380 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<template< typename > class Atom = std::atomic>
hazptr_tc<Atom>& folly::hazptr_tc_tls ( )

hazptr_tc_tls

std::string folly::hexDump ( const void *  ptr,
size_t  size 
)

Return the hex dump of size bytes starting at ptr as a string.

Definition at line 457 of file String.cpp.

References hexDump().

457  {
458  std::ostringstream os;
459  hexDump(ptr, size, std::ostream_iterator<StringPiece>(os, "\n"));
460  return os.str();
461 }
void * ptr
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
std::string hexDump(const void *ptr, size_t size)
Definition: String.cpp:457
template<class OutIt >
void folly::hexDump ( const void *  ptr,
size_t  size,
OutIt  out 
)

Write a hex dump of size bytes starting at ptr to out.

The hex dump is formatted as follows:

for the string "abcdefghijklmnopqrstuvwxyz\x02" 00000000 61 62 63 64 65 66 67 68 69 6a 6b 6c 6d 6e 6f 70 |abcdefghijklmnop| 00000010 71 72 73 74 75 76 77 78 79 7a 02 |qrstuvwxyz. |

that is, we write 16 bytes per line, both as hex bytes and as printable characters. Non-printable characters are replaced with '.' Lines are written to out one by one (one StringPiece at a time) without delimiters.

Definition at line 645 of file String-inl.h.

References folly::detail::hexDumpLine(), and string.

Referenced by hexDump(), proxygen::HexFollyPrinter::print(), and TEST().

645  {
646  size_t offset = 0;
647  std::string line;
648  while (offset < size) {
649  offset += detail::hexDumpLine(ptr, offset, size, line);
650  *out++ = line;
651  }
652 }
void * ptr
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
size_t hexDumpLine(const void *ptr, size_t offset, size_t size, std::string &line)
Definition: String.cpp:651
const char * string
Definition: Conv.cpp:212
template<class OutputString = std::string>
OutputString folly::hexlify ( ByteRange  input)

Definition at line 260 of file String.h.

References hexlify(), and gmock_output_test::output.

260  {
261  OutputString output;
262  if (!hexlify(input, output)) {
263  // hexlify() currently always returns true, so this can't really happen
264  throw std::runtime_error("hexlify failed");
265  }
266  return output;
267 }
OutputString hexlify(StringPiece input)
Definition: String.h:270
template<class OutputString = std::string>
OutputString folly::hexlify ( StringPiece  input)

Definition at line 270 of file String.h.

References unhexlify().

270  {
271  return hexlify<OutputString>(ByteRange{input});
272 }
Range< const unsigned char * > ByteRange
Definition: Range.h:1163
template<class InputString , class OutputString >
bool folly::hexlify ( const InputString &  input,
OutputString &  output,
bool  append = false 
)

Same functionality as Python's binascii.hexlify. Returns true on successful conversion.

If append_output is true, append data to the output rather than replace it.

Definition at line 596 of file String-inl.h.

References ch, and i.

Referenced by BENCHMARK(), fizz::test::HandshakeTypesTest::encodeHex(), fizz::test::ZlibCertificateCompressorTest::encodeHex(), fizz::enumToHex(), fizz::test::PlaintextRecordTest::expectSame(), fizz::test::RecordTest::expectSame(), fizz::test::EncryptedRecordTest::expectSame(), folly::AsyncSSLSocket::getSSLClientCiphers(), hexlify(), humanify(), fizz::PlaintextReadRecordLayer::read(), fizz::server::test::TEST(), fizz::test::TEST(), TEST(), fizz::server::test::TEST_F(), fizz::test::TEST_F(), fizz::testing::TEST_P(), fizz::test::TEST_P(), and TEST_P().

599  {
600  if (!append_output) {
601  output.clear();
602  }
603 
604  static char hexValues[] = "0123456789abcdef";
605  auto j = output.size();
606  output.resize(2 * input.size() + output.size());
607  for (size_t i = 0; i < input.size(); ++i) {
608  int ch = input[i];
609  output[j++] = hexValues[(ch >> 4) & 0xf];
610  output[j++] = hexValues[ch & 0xf];
611  }
612  return true;
613 }
auto ch
template<bool implicit_unpack = true, typename Container >
hint_emplace_iterator<Container, implicit_unpack> folly::hint_emplacer ( Container &  c,
typename Container::iterator  i 
)

Convenience function to construct a folly::hint_emplace_iterator, analogous to std::inserter().

Setting implicit_unpack to false will disable implicit unpacking of single std::pair and std::tuple arguments to the iterator's operator=. That may be desirable in case of constructors that expect a std::pair or std::tuple argument.

Examples:
/facebook/proxygen/proxygen/folly/folly/container/Iterator.h.

Definition at line 461 of file Iterator.h.

References c, and folly::gen::move.

Referenced by TEST().

463  {
464  return hint_emplace_iterator<Container, implicit_unpack>(c, std::move(i));
465 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
char c
std::uint32_t folly::hsieh_hash32_buf ( const void *  buf,
std::size_t  len 
)
template<class String >
String folly::humanify ( const String &  input)

Definition at line 240 of file String.h.

References append(), hexlify(), humanify(), and gmock_output_test::output.

240  {
241  String output;
242  humanify(input, output);
243  return output;
244 }
String humanify(const String &input)
Definition: String.h:240
template<class String1 , class String2 >
void folly::humanify ( const String1 &  input,
String2 &  output 
)

Take a string and "humanify" it – that is, make it look better. Since "better" is subjective, caveat emptor. The basic approach is to count the number of unprintable characters. If there are none, then the output is the input. If there are relatively few, or if there is a long "enough" prefix of printable characters, use backslashify. If it is mostly binary, then simply hex encode.

This is an attempt to make a computer smart, and so likely is wrong most of the time.

Definition at line 552 of file String-inl.h.

References backslashify(), c, and hexlify().

Referenced by backslashify(), humanify(), and TEST().

552  {
553  size_t numUnprintable = 0;
554  size_t numPrintablePrefix = 0;
555  for (unsigned char c : input) {
556  if (c < 0x20 || c > 0x7e || c == '\\') {
557  ++numUnprintable;
558  }
559  if (numUnprintable == 0) {
560  ++numPrintablePrefix;
561  }
562  }
563 
564  // hexlify doubles a string's size; backslashify can potentially
565  // explode it by 4x. Now, the printable range of the ascii
566  // "spectrum" is around 95 out of 256 values, so a "random" binary
567  // string should be around 60% unprintable. We use a 50% hueristic
568  // here, so if a string is 60% unprintable, then we just use hex
569  // output. Otherwise we backslash.
570  //
571  // UTF8 is completely ignored; as a result, utf8 characters will
572  // likely be \x escaped (since most common glyphs fit in two bytes).
573  // This is a tradeoff of complexity/speed instead of a convenience
574  // that likely would rarely matter. Moreover, this function is more
575  // about displaying underlying bytes, not about displaying glyphs
576  // from languages.
577  if (numUnprintable == 0) {
578  output = input;
579  } else if (5 * numUnprintable >= 3 * input.size()) {
580  // However! If we have a "meaningful" prefix of printable
581  // characters, say 20% of the string, we backslashify under the
582  // assumption viewing the prefix as ascii is worth blowing the
583  // output size up a bit.
584  if (5 * numPrintablePrefix >= input.size()) {
585  backslashify(input, output);
586  } else {
587  output = "0x";
588  hexlify(input, output, true /* append output */);
589  }
590  } else {
591  backslashify(input, output);
592  }
593 }
void backslashify(folly::StringPiece input, OutputString &output, bool hex_style)
Definition: String-inl.h:507
bool hexlify(const InputString &input, OutputString &output, bool append_output)
Definition: String-inl.h:596
char c
static string folly::humanReadable ( double  n,
unsigned int  decimals,
const ScaleInfo scales 
)
static

Definition at line 227 of file Benchmark.cpp.

References folly::ScaleInfo::boundary, stringPrintf(), folly::ScaleInfo::suffix, and suffix.

Referenced by metricReadable(), and readableTime().

227  {
228  if (std::isinf(n) || std::isnan(n)) {
229  return folly::to<string>(n);
230  }
231 
232  const double absValue = fabs(n);
233  const ScaleInfo* scale = scales;
234  while (absValue < scale[0].boundary && scale[1].suffix != nullptr) {
235  ++scale;
236  }
237 
238  const double scaledValue = n / scale->boundary;
239  return stringPrintf("%.*f%s", decimals, scaledValue, scale->suffix);
240 }
std::string stringPrintf(const char *format,...)
Definition: String.cpp:223
const char * suffix
Definition: String.cpp:272
template<std::size_t I>
in_place_index_tag<I> folly::in_place_index ( in_place_index_tag< I >  = {})
inline

Definition at line 243 of file Utility.h.

243  {}) {
244  return {};
245 }
template<class T >
in_place_type_tag<T> folly::in_place_type ( in_place_type_tag< T = {})
inline

Definition at line 239 of file Utility.h.

239  {}) {
240  return {};
241 }
void folly::init ( int *  argc,
char ***  argv,
bool  removeFlags 
)

Definition at line 34 of file Init.cpp.

References initLoggingOrDie(), folly::symbolizer::installFatalSignalCallbacks(), folly::symbolizer::installFatalSignalHandler(), folly::SingletonVault::registrationComplete(), and folly::SingletonVault::singleton().

Referenced by folly::portability::ssl::BIO_set_init(), wangle::FilePoller::FilePoller(), folly::Init::Init(), inline_bulk_target(), folly::XlogCategoryInfo< IsInHeaderFile >::isInitialized(), main(), naive_executor_bulk_target(), folly::F14VectorSet< Key, Hasher, KeyEqual, Alloc >::operator=(), folly::F14VectorMap< Key, Mapped, Hasher, KeyEqual, Alloc >::operator=(), folly::NotificationQueue< MessageT >::Consumer::setActive(), folly::ConcurrentSkipList< T, Comp, NodeAlloc, MAX_HEIGHT >::Skipper::Skipper(), folly::NotificationQueue< MessageT >::Consumer::startConsuming(), folly::NotificationQueue< MessageT >::Consumer::startConsumingInternal(), and proxygen::ZlibStreamDecompressor::ZlibStreamDecompressor().

34  {
35 #if FOLLY_USE_SYMBOLIZER
36  // Install the handler now, to trap errors received during startup.
37  // The callbacks, if any, can be installed later
39 #elif !defined(_WIN32)
40  google::InstallFailureSignalHandler();
41 #endif
42 
43  // Move from the registration phase to the "you can actually instantiate
44  // things now" phase.
46 
47  gflags::ParseCommandLineFlags(argc, argv, removeFlags);
48 
49  folly::initLoggingOrDie(FLAGS_logging);
50  auto programName = argc && argv && *argc > 0 ? (*argv)[0] : "unknown";
51  google::InitGoogleLogging(programName);
52 
53 #if FOLLY_USE_SYMBOLIZER
54  // Don't use glog's DumpStackTraceAndExit; rely on our signal handler.
55  google::InstallFailureFunction(abort);
56 
57  // Actually install the callbacks into the handler.
59 #endif
60 }
static SingletonVault * singleton()
Definition: Singleton.h:495
void installFatalSignalCallbacks()
char ** argv
void installFatalSignalHandler()
void initLoggingOrDie(StringPiece configString)
Definition: Init.cpp:48
void folly::initializeLoggerDB ( LoggerDB db)

initializeLoggerDB() will be called to configure the main LoggerDB singleton the first time that LoggerDB::get() is called.

This function can be used apply basic default settings to the LoggerDB, including default log level and log handler settings.

A default implementation is provided as a weak symbol, so it can be overridden on a per-program basis if you want to customize the initial LoggerDB settings for your program.

However, note that this function may be invoked before main() starts (if other code that runs before main uses the logging library). Therefore you should be careful about what code runs here. For instance, you probably should not create LogHandler objects that spawn new threads. It is generally a good idea to defer more complicated setup until after main() starts.

In most situations it is normally better to override getBaseLoggingConfig() from logging/Init.h rather than overriding initializeLoggerDB(). You only need to override initializeLoggerDB() if you want to change the settings that are used for messages that get logged before initLogging() is called.

The default implementation configures the root log category to write all warning and higher-level log messages to stderr, using a format similar to that used by GLOG.

Definition at line 43 of file LoggerDB.cpp.

References config, db_, FOLLY_NONNULL, kDefaultLogLevel, folly::LoggerDB::registerHandlerFactory(), and folly::LoggerDB::updateConfig().

43  {
44  // Register the StreamHandlerFactory
45  //
46  // This is the only LogHandlerFactory that we register by default. We
47  // intentionally do not register FileHandlerFactory, since this allows
48  // LoggerDB::updateConfig() to open and write to arbitrary files. This is
49  // potentially a security concern if programs accept user-customizable log
50  // configuration settings from untrusted sources.
51  //
52  // Users can always register additional LogHandlerFactory objects on their
53  // own inside their main() function.
54  db.registerHandlerFactory(std::make_unique<StreamHandlerFactory>());
55 
56  // Build a default LogConfig object.
57  // This writes messages to stderr synchronously (immediately, in the thread
58  // that generated the message), using the default GLOG-style formatter.
59  auto defaultHandlerConfig =
60  LogHandlerConfig("stream", {{"stream", "stderr"}, {"async", "false"}});
61  auto rootCategoryConfig =
62  LogCategoryConfig(kDefaultLogLevel, false, {"default"});
63  LogConfig config(
64  /* handlerConfigs */ {{"default", defaultHandlerConfig}},
65  /* categoryConfig */ {{"", rootCategoryConfig}});
66 
67  // Update the configuration
68  db.updateConfig(config);
69 }
AHArrayT::Config config
constexpr LogLevel kDefaultLogLevel
Definition: LogLevel.h:102
void folly::initLogging ( folly::StringPiece  configString = "")

Initialize the logging library.

This function performs the following steps:

This function will throw an exception on error. Most errors are normally due to invalid logging configuration strings: e.g., invalid log level names or referencing undefined log handlers.

If you are invoking this from your program's main() function it is often more convenient to use initLoggingOrDie() to terminate your program gracefully on error rather than having to handle exceptions yourself.

Definition at line 25 of file Init.cpp.

References config, folly::Range< Iter >::empty(), folly::LoggerDB::get(), getBaseLoggingConfig(), parseLogConfig(), folly::LogConfig::update(), and folly::LoggerDB::updateConfig().

Referenced by initLoggingOrDie(), and TEST().

25  {
26  // Get the base logging configuration
27  auto* const baseConfigStr = getBaseLoggingConfig();
28  // Return early if we have nothing to do
29  if (!baseConfigStr && configString.empty()) {
30  return;
31  }
32 
33  // Parse the configuration string(s)
34  LogConfig config;
35  if (baseConfigStr) {
36  config = parseLogConfig(baseConfigStr);
37  if (!configString.empty()) {
38  config.update(parseLogConfig(configString));
39  }
40  } else {
41  config = parseLogConfig(configString);
42  }
43 
44  // Apply the config settings
45  LoggerDB::get().updateConfig(config);
46 }
const char * getBaseLoggingConfig()
Definition: InitWeak.cpp:29
LogConfig parseLogConfig(StringPiece value)
AHArrayT::Config config
constexpr bool empty() const
Definition: Range.h:443
PUSHMI_INLINE_VAR constexpr detail::get_fn< T > get
Definition: submit.h:391
void folly::initLoggingOrDie ( folly::StringPiece  configString = "")

Initialize the logging library, and exit the program on error.

This function behaves like initLogging(), but if an error occurs processing the logging configuration it will print an error message to stderr and then call exit(1) to terminate the program.

Definition at line 48 of file Init.cpp.

References initLogging().

Referenced by init().

48  {
49  try {
50  initLogging(configString);
51  } catch (const std::exception& ex) {
52  // Print the error message. We intentionally use ex.what() here instead
53  // of folly::exceptionStr() to avoid including the exception type name in
54  // the output. The exceptions thrown by the logging library on error
55  // should have enough information to diagnose what is wrong with the
56  // input config string.
57  //
58  // We want the output here to be user-friendly since this will be shown
59  // to any user invoking a program with an error in the logging
60  // configuration string. This output is intended for end users rather
61  // than developers.
62  fprintf(stderr, "error parsing logging configuration: %s\n", ex.what());
63  exit(1);
64  }
65 }
void initLogging(StringPiece configString)
Definition: Init.cpp:25
template<typename F , typename... Args>
constexpr auto folly::invoke ( F &&  f,
Args &&...  args 
) -> decltype(static_cast<F&&>(f)(static_cast<Args&&>(args)...))
noexcept
template<typename M , typename C , typename... Args>
constexpr auto folly::invoke ( MC::*  d,
Args &&...  args 
) -> decltype(std::mem_fn(d)(static_cast<Args&&>(args)...))

Definition at line 55 of file Invoke.h.

References testing::Args().

56  {
57  return std::mem_fn(d)(static_cast<Args&&>(args)...);
58 }
internal::ArgsMatcher< InnerMatcher > Args(const InnerMatcher &matcher)
template<typename F , typename... A>
FOLLY_NOINLINE FOLLY_COLD void folly::invoke_noreturn_cold ( F &&  f,
A &&...  a 
)

invoke_noreturn_cold

Invoke the provided function with the provided arguments. If the invocation returns, terminate.

May be used with throw_exception in cases where construction of the object to be thrown requires more than just invoking its constructor with a given sequence of arguments passed by reference - for example, if a string message must be computed before being passed to the constructor of the object to be thrown.

Usage note: Passing extra values as arguments rather than capturing them allows smaller bytecode at the call-site.

Example:

if (i < 0) { invoke_noreturn_cold( [](int j) { throw_exceptions(runtime_error(to<string>("invalid: ", j))); }, i); }

Definition at line 122 of file Exception.h.

References a, and f.

Referenced by TEST_F().

124  {
125  static_cast<F&&>(f)(static_cast<A&&>(a)...);
126  std::terminate();
127 }
auto f
char a
template<typename T >
constexpr bool folly::is_negative ( T  x)
template<typename T >
constexpr bool folly::is_non_negative ( T  x)

Definition at line 693 of file Traits.h.

693  {
694  return !x || is_positive(x);
695 }
Definition: InvokeTest.cpp:58
constexpr bool is_positive(T x)
Definition: Traits.h:687
template<typename T >
constexpr bool folly::is_non_positive ( T  x)

Definition at line 681 of file Traits.h.

Referenced by TEST().

681  {
682  return !x || folly::is_negative(x);
683 }
Definition: InvokeTest.cpp:58
constexpr bool is_negative(T x)
Definition: Traits.h:675
static bool folly::is_oddspace ( char  c)
inlinestatic

Definition at line 127 of file String.cpp.

Referenced by ltrimWhitespace(), and rtrimWhitespace().

127  {
128  return c == '\n' || c == '\t' || c == '\r';
129 }
char c
template<typename T >
constexpr bool folly::is_positive ( T  x)

Definition at line 687 of file Traits.h.

Referenced by testing::gmock_matchers_test::Type< T >::IsTypeOf(), and testing::gmock_matchers_test::TEST().

687  {
688  return !is_non_positive(x);
689 }
Definition: InvokeTest.cpp:58
constexpr bool is_non_positive(T x)
Definition: Traits.h:681
constexpr bool folly::isLogLevelFatal ( LogLevel  level)
inline

Returns true if and only if a LogLevel is fatal.

Definition at line 145 of file LogLevel.h.

References DFATAL, FATAL, and kIsDebug.

Referenced by folly::LogCategory::admitMessage().

145  {
146  return folly::kIsDebug ? (level >= LogLevel::DFATAL)
147  : (level >= LogLevel::FATAL);
148 }
constexpr auto kIsDebug
Definition: Portability.h:264
template<class T >
constexpr bool folly::isPowTwo ( T const  v)
inline

Definition at line 161 of file Bits.h.

References value.

Referenced by BENCHMARK(), folly::detail::ConcurrentHashMapSegment< KeyType, ValueType, ShardBits, HashFn, KeyEqual, Allocator, Atom, Mutex >::ConcurrentHashMapSegment(), and TEST().

161  {
162  static_assert(std::is_integral<T>::value, "non-integral type");
163  static_assert(std::is_unsigned<T>::value, "signed type");
164  static_assert(!std::is_same<T, bool>::value, "bool type");
165  return (v != 0) && !(v & (v - 1));
166 }
static const char *const value
Definition: Conv.cpp:50
bool folly::isSequencedExecutor ( folly::Executor executor)

Definition at line 27 of file SequencedExecutorTest.cpp.

References folly::Executor::add(), folly::SerialExecutor::create(), folly::Executor::getKeepAliveToken(), and folly::fibers::yield().

Referenced by testExecutor().

27  {
28  // Add can be called from different threads, but it should be sequenced.
29  auto cpuExecutor = std::make_shared<CPUThreadPoolExecutor>(4);
30  auto producer =
31  SerialExecutor::create(Executor::getKeepAliveToken(cpuExecutor.get()));
32 
33  std::atomic<size_t> nextCallIndex{0};
34  std::atomic<bool> result{true};
35 
36  auto joinPromise = std::make_shared<std::promise<void>>();
37  auto joinFuture = joinPromise->get_future();
38 
39  constexpr size_t kNumCalls = 10000;
40  for (size_t callIndex = 0; callIndex < kNumCalls; ++callIndex) {
41  producer->add([&result, &executor, &nextCallIndex, callIndex, joinPromise] {
42  executor.add([&result, &nextCallIndex, callIndex, joinPromise] {
43  if (nextCallIndex != callIndex) {
44  result = false;
45  }
47  if (nextCallIndex.exchange(callIndex + 1) != callIndex) {
48  result = false;
49  }
50  });
51  });
52  }
53 
54  joinPromise.reset();
55  joinFuture.wait();
56 
57  return result;
58 }
virtual void add(Func)=0
Executor::KeepAlive< ExecutorT > getKeepAliveToken(ExecutorT *executor)
Definition: Executor.h:200
bool folly::isSet ( WriteFlags  a,
WriteFlags  b 
)
inline
template<class Delim , class Iterator , class String >
void folly::join ( const Delim &  delimiter,
Iterator  begin,
Iterator  end,
String &  output 
)
template<class Delim , class Container , class String >
void folly::join ( const Delim &  delimiter,
const Container &  container,
String &  output 
)

Definition at line 511 of file String.h.

References join(), and gmock_output_test::output.

511  {
512  join(delimiter, container.begin(), container.end(), output);
513 }
std::string join(const Delim &delimiter, Iterator begin, Iterator end)
Definition: String.h:546
template<class Delim , class Value , class String >
void folly::join ( const Delim &  delimiter,
const std::initializer_list< Value > &  values,
String &  output 
)

Definition at line 516 of file String.h.

References join(), and gmock_output_test::output.

519  {
520  join(delimiter, values.begin(), values.end(), output);
521 }
std::string join(const Delim &delimiter, Iterator begin, Iterator end)
Definition: String.h:546
std::vector< int > values(1'000)
template<class Delim , class Container >
std::string folly::join ( const Delim &  delimiter,
const Container &  container 
)

Definition at line 524 of file String.h.

References join(), gmock_output_test::output, and string.

524  {
526  join(delimiter, container.begin(), container.end(), output);
527  return output;
528 }
std::string join(const Delim &delimiter, Iterator begin, Iterator end)
Definition: String.h:546
const char * string
Definition: Conv.cpp:212
template<class Delim , class Value >
std::string folly::join ( const Delim &  delimiter,
const std::initializer_list< Value > &  values 
)

Definition at line 531 of file String.h.

References join(), gmock_output_test::output, string, type, and value().

533  {
535  join(delimiter, values.begin(), values.end(), output);
536  return output;
537 }
std::string join(const Delim &delimiter, Iterator begin, Iterator end)
Definition: String.h:546
const char * string
Definition: Conv.cpp:212
std::vector< int > values(1'000)
template<class Delim , class Iterator , typename std::enable_if< std::is_base_of< std::forward_iterator_tag, typename std::iterator_traits< Iterator >::iterator_category >::value >::type * = nullptr>
std::string folly::join ( const Delim &  delimiter,
Iterator  begin,
Iterator  end 
)

Definition at line 546 of file String.h.

References join(), ltrimWhitespace(), gmock_output_test::output, rtrimWhitespace(), and string.

546  {
548  join(delimiter, begin, end, output);
549  return output;
550 }
auto begin(TestAdlIterable &instance)
Definition: ForeachTest.cpp:56
auto end(TestAdlIterable &instance)
Definition: ForeachTest.cpp:62
std::string join(const Delim &delimiter, Iterator begin, Iterator end)
Definition: String.h:546
const char * string
Definition: Conv.cpp:212
static double folly::k_to_q ( double  k,
double  d 
)
static

Definition at line 60 of file TDigest.cpp.

Referenced by folly::TDigest::merge().

60  {
61  double k_div_d = k / d;
62  if (k_div_d >= 0.5) {
63  double base = 1 - k_div_d;
64  return 1 - 2 * base * base;
65  } else {
66  return 2 * k_div_d * k_div_d;
67  }
68 }
KeyT k
template<typename T >
FOLLY_NODISCARD T* folly::launder ( T in)
inlinenoexcept

Approximate backport from C++17 of std::launder. It should be constexpr but that can't be done without specific support from the compiler.

Definition at line 48 of file Launder.h.

References testing::Args(), and T.

Referenced by folly::Replaceable< T >::emplace(), folly::Replaceable< T >::operator*(), folly::Replaceable< T >::operator->(), folly::replaceable_detail::move_assignment_mixin< T, true >::operator=(), folly::replaceable_detail::copy_assignment_mixin< T, true >::operator=(), TEST(), and folly::replaceable_detail::dtor_mixin< T, true, false >::~dtor_mixin().

48  {
49 #if FOLLY_HAS_BUILTIN(__builtin_launder) || __GNUC__ >= 7
50  // The builtin has no unwanted side-effects.
51  return __builtin_launder(in);
52 #elif __GNUC__
53  // This inline assembler block declares that `in` is an input and an output,
54  // so the compiler has to assume that it has been changed inside the block.
55  __asm__("" : "+r"(in));
56  return in;
57 #elif defined(_WIN32)
58  // MSVC does not currently have optimizations around const members of structs.
59  // _ReadWriteBarrier() will prevent compiler reordering memory accesses.
60  _ReadWriteBarrier();
61  return in;
62 #else
63  static_assert(
64  false, "folly::launder is not implemented for this environment");
65 #endif
66 }
void folly::launder ( void *  )
delete
void folly::launder ( void const *  )
delete
void folly::launder ( void volatile *  )
delete
void folly::launder ( void const volatile *  )
delete
template<typename T , typename... Args>
void folly::launder ( T(*)(Args...)  )
delete
template<class Func >
auto folly::lazy ( Func &&  fun)

Definition at line 138 of file Lazy.h.

References fun().

Referenced by TEST().

138  {
139  return detail::Lazy<remove_cvref_t<Func>>(std::forward<Func>(fun));
140 }
void fun()
template<typename RHS , RHS rhs, typename LHS >
bool folly::less_than ( LHS const  lhs)

Definition at line 698 of file Traits.h.

Referenced by folly::detail::convertTo().

int folly::libeventFdToFd ( libevent_fd_t  fd)
inline

Definition at line 44 of file Event.h.

References folly::netops::detail::SocketFileDescriptorMap::socketToFd().

Referenced by folly::AsyncTimeout::libeventCallback().

44  {
45  return netops::detail::SocketFileDescriptorMap::socketToFd(fd);
46 }
template<class T >
FOLLY_PACK_POP T folly::loadUnaligned ( const void *  p)
inline

Read an unaligned value of type T and return it.

Definition at line 298 of file Bits.h.

References kHasUnalignedAccess, T, and value().

298  {
299  static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
300  static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
301  if (kHasUnalignedAccess) {
302  return static_cast<const Unaligned<T>*>(p)->value;
303  } else {
304  T value;
305  memcpy(&value, p, sizeof(T));
306  return value;
307  }
308 }
constexpr bool kHasUnalignedAccess
Definition: Portability.h:29
#define T(v)
Definition: http_parser.c:233
static const char *const value
Definition: Conv.cpp:50
template<typename D , typename M , typename... Args>
auto folly::lock ( Synchronized< D, M > &  synchronized,
Args &&...  args 
)

Definition at line 1531 of file Synchronized.h.

References testing::Args(), D, folly::detail::lock(), and M.

Referenced by folly::python::GILAwareManualExecutor::add(), folly::ManualExecutor::add(), folly::DefaultKeepAliveExecutor::WeakRef::add(), folly::DefaultKeepAliveExecutor::WeakRef::addWithPriority(), BENCHMARK(), folly::basic_once_flag< SharedMutex >::call_once_slow(), folly::ManualExecutor::clear(), folly::ThreadedExecutor::controlWait(), folly::python::GILAwareManualExecutor::driveImpl(), folly::EventBase::EventBase(), folly::symbolizer::ElfCache::getFile(), folly::futures::detail::Core< T >::getInterruptHandler(), folly::AsyncIO::initializeContext(), folly::MicroLockBase< MaxSpins, MaxYields >::lock(), lock(), folly::futures::detail::Core< T >::raise(), folly::ManualExecutor::run(), folly::FunctionScheduler::run(), runBasicHoldersTest(), runBasicTest(), runBasicUpgradeTest(), runContendedReaders(), runFailingTryTimeoutTest(), runManyReadLocksTestWithoutTokens(), runManyReadLocksTestWithTokens(), runMixed(), runTimeoutInPastTest(), folly::ManualExecutor::scheduleAt(), folly::futures::detail::Core< T >::setInterruptHandler(), folly::pushmi::shared_entangle(), folly::ThreadedRepeatingFunctionRunner::stopImpl(), synchronized(), folly::futures::test::TEST(), TEST(), TEST(), TEST_F(), folly::PicoSpinLock< uintptr_t >::try_lock(), folly::PicoSpinLock< uintptr_t >::unlock(), unorderedReduce(), folly::ManualExecutor::wait(), folly::python::GILAwareManualExecutor::waitBeforeDrive(), folly::ThreadedRepeatingFunctionRunner::waitFor(), folly::HandshakeCallback::waitForHandshake(), with_unique_lock(), folly::SynchronizedBase< Subclass, detail::MutexLevel::UNIQUE >::withLock(), folly::SynchronizedBase< Subclass, detail::MutexLevel::UNIQUE >::withLockPtr(), and folly::EventBase::~EventBase().

1531  {
1532  return detail::lock(synchronized, std::forward<Args>(args)...);
1533 }
void lock(LockableOne &one, LockableTwo &two, Lockables &...lockables)
template<typename D , typename M , typename... Args>
auto folly::lock ( const Synchronized< D, M > &  synchronized,
Args &&...  args 
)

Definition at line 1535 of file Synchronized.h.

References folly::detail::lock().

1535  {
1536  return detail::lock(synchronized, std::forward<Args>(args)...);
1537 }
void lock(LockableOne &one, LockableTwo &two, Lockables &...lockables)
template<typename LockableOne , typename LockableTwo , typename... Lockables>
void folly::lock ( LockableOne &  one,
LockableTwo &  two,
Lockables &...  lockables 
)

Acquire locks on many lockables or synchronized instances in such a way that the sequence of calls within the function does not cause deadlocks.

This can often result in a performance boost as compared to simply acquiring your locks in an ordered manner. Even for very simple cases. The algorithm tried to adjust to contention by blocking on the mutex it thinks is the best fit, leaving all other mutexes open to be locked by other threads. See the benchmarks in folly/test/SynchronizedBenchmark.cpp for more

This works differently as compared to the locking algorithm in libstdc++ and is the recommended way to acquire mutexes in a generic order safe manner. Performance benchmarks show that this does better than the one in libstdc++ even for the simple cases

Usage is the same as std::lock() for arbitrary lockables

folly::lock(one, two, three);

To make it work with folly::Synchronized you have to specify how you want the locks to be acquired, use the folly::wlock(), folly::rlock(), folly::ulock() and folly::lock() helpers defined below

auto [one, two] = lock(folly::wlock(a), folly::rlock(b));

Note that you can/must avoid the folly:: namespace prefix on the lock() function if you use the helpers, ADL lookup is done to find the lock function

This will execute the deadlock avoidance algorithm and acquire a write lock for a and a read lock for b

Definition at line 1592 of file Synchronized.h.

References for_each(), lock(), folly::ssl::detail::locks(), and folly::detail::makeSynchronizedLocker().

Referenced by folly::LockedPtrBase< SynchronizedType, SynchronizedType::MutexType, LockPolicy >::LockedPtrBase(), folly::LockedPtrBase< SynchronizedType, std::mutex, LockPolicy >::LockedPtrBase(), and folly::LockedPtrBase< SynchronizedType, SynchronizedType::MutexType, LockPolicy >::reacquireLock().

1592  {
1593  auto locker = [](auto& lockable) {
1594  using Lockable = std::remove_reference_t<decltype(lockable)>;
1596  lockable,
1597  [](auto& l) { return std::unique_lock<Lockable>{l}; },
1598  [](auto& l) {
1599  auto lock = std::unique_lock<Lockable>{l, std::defer_lock};
1600  lock.try_lock();
1601  return lock;
1602  });
1603  };
1604  auto locks = lock(locker(one), locker(two), locker(lockables)...);
1605 
1606  // release ownership of the locks from the RAII lock wrapper returned by the
1607  // function above
1608  for_each(locks, [&](auto& lock) { lock.release(); });
1609 }
void lock(LockableOne &one, LockableTwo &two, Lockables &...lockables)
static std::unique_ptr< SSLLock[]> & locks()
auto makeSynchronizedLocker(Synchronized &synchronized, LockFunc &&lockFunc, TryLockFunc &&tryLockFunc, Args &&...args)
Definition: Synchronized.h:837
void for_each(T const &range, Function< void(typename T::value_type const &) const > const &func)
dynamic folly::logConfigToDynamic ( const LogConfig config)

Convert a LogConfig object to a folly::dynamic object.

This can be used to serialize it as a JSON string, which can later be read back using parseLogConfigJson().

Definition at line 553 of file LogConfigParser.cpp.

References folly::LogConfig::getCategoryConfigs(), folly::LogConfig::getHandlerConfigs(), folly::dynamic::insert(), folly::gen::move, and folly::dynamic::object().

Referenced by TEST().

553  {
554  dynamic categories = dynamic::object;
555  for (const auto& entry : config.getCategoryConfigs()) {
556  categories.insert(entry.first, logConfigToDynamic(entry.second));
557  }
558 
559  dynamic handlers = dynamic::object;
560  for (const auto& entry : config.getHandlerConfigs()) {
561  handlers.insert(entry.first, logConfigToDynamic(entry.second));
562  }
563 
564  return dynamic::object("categories", std::move(categories))(
565  "handlers", std::move(handlers));
566 }
void * object
Definition: AtFork.cpp:32
dynamic logConfigToDynamic(const LogCategoryConfig &config)
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
AHArrayT::Config config
dynamic folly::logConfigToDynamic ( const LogHandlerConfig config)

Definition at line 568 of file LogConfigParser.cpp.

References folly::Optional< Value >::hasValue(), folly::dynamic::insert(), folly::gen::move, folly::dynamic::object(), folly::LogHandlerConfig::options, folly::LogHandlerConfig::type, and folly::Optional< Value >::value().

568  {
569  dynamic options = dynamic::object;
570  for (const auto& opt : config.options) {
571  options.insert(opt.first, opt.second);
572  }
573  auto result = dynamic::object("options", options);
574  if (config.type.hasValue()) {
575  result("type", config.type.value());
576  }
577  return std::move(result);
578 }
void * object
Definition: AtFork.cpp:32
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
AHArrayT::Config config
dynamic folly::logConfigToDynamic ( const LogCategoryConfig config)

Definition at line 580 of file LogConfigParser.cpp.

References folly::dynamic::array(), folly::LogCategoryConfig::handlers, folly::Optional< Value >::hasValue(), folly::LogCategoryConfig::inheritParentLevel, folly::LogCategoryConfig::level, logLevelToString(), folly::gen::move, folly::dynamic::object(), value(), and folly::Optional< Value >::value().

580  {
581  auto value = dynamic::object("level", logLevelToString(config.level))(
582  "inherit", config.inheritParentLevel);
583  if (config.handlers.hasValue()) {
584  auto handlers = dynamic::array();
585  for (const auto& handlerName : config.handlers.value()) {
586  handlers.push_back(handlerName);
587  }
588  value("handlers", std::move(handlers));
589  }
590  return std::move(value);
591 }
void * object
Definition: AtFork.cpp:32
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
string logLevelToString(LogLevel level)
Definition: LogLevel.cpp:109
AHArrayT::Config config
static const char *const value
Definition: Conv.cpp:50
void folly::logDisabledHelper ( std::true_type  )
noexcept

Definition at line 228 of file LogStreamProcessor.cpp.

Referenced by logDisabledHelper().

228  {
229  // This function can only be reached if we had a disabled fatal log message.
230  // This should never happen: LogCategory::setLevelLocked() does not allow
231  // setting the threshold for a category lower than FATAL (in production
232  // builds) or DFATAL (in debug builds).
233  abort();
234 }
void folly::logDisabledHelper ( std::false_type  )
inlinenoexcept

logDisabledHelper() is invoked in FB_LOG() and XLOG() statements if the log admittance check fails.

This function exists solely to ensure that both sides of the log check are marked [[noreturn]] for fatal log messages. This allows the compiler to recognize that the full statement is noreturn, preventing warnings about missing return statements after fatal log messages.

Unfortunately it does not appear possible to get the compiler to recognize that the disabled side of the log statement should never be reached for fatal messages. Even if we make the check something like (isLogLevelFatal(level) || realCheck), where isLogLevelFatal() is constexpr, this is not sufficient for gcc or clang to recognize that the full expression is noreturn.

Ideally this would just be a template function specialized on a boolean IsFatal parameter. Unfortunately this triggers a bug in clang, which does not like differing noreturn behavior for different template instantiations. Therefore we overload on integral_constant instead.

clang-format also doesn't do a good job understanding this code and figuring out how to format it.

Definition at line 520 of file LogStreamProcessor.h.

References logDisabledHelper(), and folly::pushmi::__adl::noexcept().

520 {}
std::string folly::loggingFormatPrintf ( const char *  format,
  ... 
)
noexcept

Definition at line 25 of file printf.cpp.

References format(), SCOPE_EXIT, and stringVPrintf().

25  {
26  va_list ap;
27  va_start(ap, format);
28  SCOPE_EXIT {
29  va_end(ap);
30  };
31  try {
32  return stringVPrintf(format, ap);
33  } catch (const std::exception&) {
34  // We don't bother including the exception message here.
35  // The exceptions thrown by stringVPrintf() don't normally have much useful
36  // information regarding what precisely went wrong.
37  return folly::to<std::string>(
38  "error formatting printf-style log message: ", format);
39  }
40 }
std::string stringVPrintf(const char *format, va_list ap)
Definition: String.cpp:232
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
Formatter< false, Args... > format(StringPiece fmt, Args &&...args)
Definition: Format.h:271
std::string folly::loggingFormatPrintf ( FOLLY_PRINTF_FORMAT const char *  format,
  ... 
)
noexcept
std::string folly::logLevelToString ( LogLevel  level)

Get a human-readable string representing the LogLevel.

Definition at line 109 of file LogLevel.cpp.

References CRITICAL, DBG, DFATAL, ERR, FATAL, INFO, deadlock::info(), NONE, uint32_t, UNINITIALIZED, and WARN.

Referenced by logConfigToDynamic(), operator-=(), operator<<(), and TEST().

109  {
110  if (level == LogLevel::UNINITIALIZED) {
111  return "UNINITIALIZED";
112  } else if (level == LogLevel::NONE) {
113  return "NONE";
114  } else if (level == LogLevel::DBG) {
115  return "DEBUG";
116  } else if (level == LogLevel::INFO) {
117  return "INFO";
118  } else if (level == LogLevel::WARN) {
119  return "WARN";
120  } else if (level == LogLevel::ERR) {
121  return "ERR";
122  } else if (level == LogLevel::CRITICAL) {
123  return "CRITICAL";
124  } else if (level == LogLevel::DFATAL) {
125  return "DFATAL";
126  } else if (level == LogLevel::FATAL) {
127  return "FATAL";
128  }
129 
130  for (const auto& info : numberedLogLevels) {
131  if (static_cast<uint32_t>(level) <= static_cast<uint32_t>(info.max) &&
132  static_cast<uint32_t>(level) > static_cast<uint32_t>(info.min)) {
133  auto num = static_cast<uint32_t>(info.max) - static_cast<uint32_t>(level);
134  return folly::to<string>(info.upperPrefix, num);
135  }
136  }
137 
138  return folly::to<string>("LogLevel(", static_cast<uint32_t>(level), ")");
139 }
def info()
Definition: deadlock.py:447
StringPiece folly::ltrimWhitespace ( StringPiece  sp)

Returns a subpiece with all whitespace removed from the front of . Whitespace means any of [' ', '
', '', ''].

Definition at line 131 of file String.cpp.

References folly::Range< Iter >::empty(), folly::Range< Iter >::front(), is_oddspace(), and folly::Range< Iter >::pop_front().

Referenced by join(), proxygen::compress::prepareMessageForCompression(), skipWhitespace(), TEST(), and trimWhitespace().

131  {
132  // Spaces other than ' ' characters are less common but should be
133  // checked. This configuration where we loop on the ' '
134  // separately from oddspaces was empirically fastest.
135 
136  while (true) {
137  while (!sp.empty() && sp.front() == ' ') {
138  sp.pop_front();
139  }
140  if (!sp.empty() && is_oddspace(sp.front())) {
141  sp.pop_front();
142  continue;
143  }
144 
145  return sp;
146  }
147 }
static bool is_oddspace(char c)
Definition: String.cpp:127
template<typename D = void, typename... TList>
constexpr array_detail::return_type<D, TList...> folly::make_array ( TList &&...  t)

Definition at line 56 of file Array.h.

References D, folly::pushmi::detail::t, and type.

Referenced by TEST().

56  {
57  using value_type =
58  typename array_detail::return_type_helper<D, TList...>::type;
59  return {{static_cast<value_type>(std::forward<TList>(t))...}};
60 }
PskType type
#define D(name, bit)
Definition: CpuId.h:145
template<std::size_t Size, typename MakeItem >
constexpr auto folly::make_array_with ( MakeItem const &  make)

Definition at line 75 of file Array.h.

References folly::array_detail::make_array_with().

Referenced by TEST().

75  {
76  return array_detail::make_array_with(make, make_index_sequence<Size>{});
77 }
constexpr auto make_array_with(MakeItem const &make)
Definition: Array.h:75
template<typename... Args>
emplace_args<Args...> folly::make_emplace_args ( Args &&...  args)
noexcept
Examples:
/facebook/proxygen/proxygen/folly/folly/container/Iterator.h.

Definition at line 92 of file Iterator.h.

References testing::Args().

Referenced by TEST().

93  {
94  return emplace_args<Args...>(std::forward<Args>(args)...);
95 }
internal::ArgsMatcher< InnerMatcher > Args(const InnerMatcher &matcher)
template<class Ex , typename... As>
exception_wrapper folly::make_exception_wrapper ( As &&...  as)
Returns
An exception_wrapper that wraps an instance of type Ex that has been constructed with arguments std::forward<As>(as)....

Definition at line 626 of file ExceptionWrapper.h.

References folly::gen::as().

626  {
627  return exception_wrapper{in_place_type<Ex>, std::forward<As>(as)...};
628 }
Collect as()
Definition: Base.h:811
template<class T , class Tuple >
constexpr T folly::make_from_tuple ( Tuple &&  t)

Definition at line 204 of file ApplyTuple.h.

References apply(), and folly::pushmi::detail::t.

Referenced by uncurry().

204  {
205  return apply(detail::apply_tuple::Construct<T>(), std::forward<Tuple>(t));
206 }
decltype(auto) constexpr apply(F &&func, Tuple &&tuple)
Definition: ApplyTuple.h:87
template<class T >
constexpr Optional<_t<std::decay<T> > > folly::make_optional ( T &&  v)

Definition at line 450 of file Optional.h.

References testing::Args(), T, and v.

Referenced by getThreadName(), TEST(), TEST(), and folly::Optional< NamedGroup >::value_or().

450  {
451  using PrivateConstructor =
452  typename folly::Optional<_t<std::decay<T>>>::PrivateConstructor;
453  return {PrivateConstructor{}, std::forward<T>(v)};
454 }
auto v
template<class T , class... Args>
constexpr folly::Optional<T> folly::make_optional ( Args &&...  args)

Definition at line 457 of file Optional.h.

References testing::Args(), and T.

457  {
458  using PrivateConstructor = typename folly::Optional<T>::PrivateConstructor;
459  return {PrivateConstructor{}, std::forward<Args>(args)...};
460 }
template<class T , class U , class... Args>
constexpr folly::Optional<T> folly::make_optional ( std::initializer_list< U >  il,
Args &&...  args 
)

Definition at line 463 of file Optional.h.

465  {
466  using PrivateConstructor = typename folly::Optional<T>::PrivateConstructor;
467  return {PrivateConstructor{}, il, std::forward<Args>(args)...};
468 }
template<class T >
constexpr Replaceable<std::decay_t<T> > folly::make_replaceable ( T &&  t)

Definition at line 385 of file Replaceable.h.

References testing::Args(), folly::pushmi::detail::t, and T.

385  {
386  return Replaceable<std::decay_t<T>>(std::forward<T>(t));
387 }
template<class T , class... Args>
constexpr Replaceable<T> folly::make_replaceable ( Args &&...  args)

Definition at line 390 of file Replaceable.h.

References testing::Args(), in_place(), and T.

390  {
391  return Replaceable<T>(in_place, std::forward<Args>(args)...);
392 }
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
template<class T , class U , class... Args>
constexpr Replaceable<T> folly::make_replaceable ( std::initializer_list< U >  il,
Args &&...  args 
)

Definition at line 395 of file Replaceable.h.

References in_place().

397  {
398  return Replaceable<T>(in_place, il, std::forward<Args>(args)...);
399 }
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
template<typename T , typename... Args>
std::enable_if<!std::is_array<T>::value, std::unique_ptr<T> >::type folly::make_unique ( Args &&...  args)

For exception safety and consistency with make_shared. Erase me when we have std::make_unique().

Author
Louis Brandy (ldbra.nosp@m.ndy@.nosp@m.fb.co.nosp@m.m)
Xu Ning (xning.nosp@m.@fb..nosp@m.com)

Definition at line 259 of file Memory.h.

References T, type, and value.

Referenced by make_unique(), runMtProdCons(), runMtProdConsDeterministic(), runMtProdConsDeterministicDynamic(), runMtProdConsEmulatedFutex(), folly::futures::detail::DeferredExecutor::setNestedExecutors(), GenericFilterTest< Owned >::SetUp(), TEST(), TEST_F(), and times().

259  {
260  return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
261 }
#define T(v)
Definition: http_parser.c:233
template<typename T >
std::enable_if<std::is_array<T>::value, std::unique_ptr<T> >::type folly::make_unique ( const size_t  n)

Definition at line 266 of file Memory.h.

References testing::Args(), make_unique(), T, type, and value.

266  {
267  return std::unique_ptr<T>(new typename std::remove_extent<T>::type[n]());
268 }
PskType type
template<typename T , typename... Args>
std::enable_if<std::extent<T>::value != 0, std::unique_ptr<T> >::type folly::make_unique ( Args &&  ...)
delete
template<class Logger = GoogleLogger<GoogleLoggerStyle::PRETTY>, class Clock = std::chrono::high_resolution_clock>
auto folly::makeAutoTimer ( std::string &&  msg = "",
const std::chrono::duration< double > &  minTimeToLog = std::chrono::duration<double>::zero(),
Logger &&  logger = Logger() 
)

Definition at line 125 of file AutoTimer.h.

References folly::gen::move.

Referenced by TEST().

129  {
130  return AutoTimer<Logger, Clock>(
131  std::move(msg), minTimeToLog, std::move(logger));
132 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<class BaseIter >
BitIterator<BaseIter> folly::makeBitIterator ( const BaseIter &  iter)

Helper function, so you can write auto bi = makeBitIterator(container.begin());

Definition at line 161 of file BitIterator.h.

Referenced by folly::HHWheelTimer::Callback::cancelTimeoutImpl(), folly::HHWheelTimer::scheduleNextTimeout(), folly::HHWheelTimer::scheduleTimeoutImpl(), TEST(), TEST_P(), and folly::HHWheelTimer::timeoutExpired().

161  {
162  return BitIterator<BaseIter>(iter);
163 }
folly::Function< void(double)> folly::makeCompressionCounterHandler ( folly::io::CodecType  codecType,
folly::StringPiece  codecName,
folly::Optional< int >  level,
CompressionCounterKey  key,
CompressionCounterType  counterType 
)

This functions is an extension point when FOLLY_HAVE_WEAK_SYMBOLS is true. There is a default no-op implementation provided which can be overrided by linking in a library which provides its own definition.

Parameters
codecTypeThe type of the codec for this counter.
codecNameThe name of the codec for this counter. If the codecName is empty it should be defaulted using the codecType.
levelOptionally the level used to construct the codec.
keyThe key of the counter.
counterTypeThe type of the counter.
Returns
A function to increment the counter for the given key and type. It may be an empty folly::Function.

Definition at line 21 of file Counters.cpp.

Referenced by folly::detail::CompressionCounter::CompressionCounter().

26  {
27  return {};
28 }
ConversionError folly::makeConversionError ( ConversionCode  code,
StringPiece  input 
)

Definition at line 765 of file Conv.cpp.

References folly::Range< Iter >::data(), folly::Range< Iter >::empty(), EMPTY_INPUT_STRING, folly::Range< Iter >::size(), string, type, and value().

Referenced by folly::detail::enforceWhitespace(), and to().

765  {
766  using namespace detail;
767  static_assert(
769  "ConversionCode should be unsigned");
770  assert((std::size_t)code < kErrorStrings.size());
771  const ErrorString& err = kErrorStrings[(std::size_t)code];
772  if (code == ConversionCode::EMPTY_INPUT_STRING && input.empty()) {
773  return {err.string, code};
774  }
775  std::string tmp(err.string);
776  tmp.append(": ");
777  if (err.quote) {
778  tmp.append(1, '"');
779  }
780  if (input.size() > 0) {
781  tmp.append(input.data(), input.size());
782  }
783  if (err.quote) {
784  tmp.append(1, '"');
785  }
786  return {tmp, code};
787 }
PskType type
static const char *const value
Definition: Conv.cpp:50
const char * string
Definition: Conv.cpp:212
template<class Error , class Value >
constexpr Expected< typename std::decay< Value >::type, Error > folly::makeExpected ( Value &&  val)

For constructing an Expected object from a value, with the specified Error type. Usage is as follows:

enum MyErrorCode { BAD_ERROR, WORSE_ERROR }; Expected<int, MyErrorCode> myAPI() { int i = // ...; return i ? makeExpected<MyErrorCode>(i) : makeUnexpected(BAD_ERROR); }

Definition at line 1394 of file Expected.h.

References testing::Args(), folly::Optional< Value >::emplace(), folly::Expected< Value, Error >::error(), h, folly::Expected< Value, Error >::hasValue(), in_place(), makeUnexpected(), folly::gen::move, folly::pushmi::__adl::noexcept(), operator!=(), operator==(), operator>(), operator>=(), promise_, val, folly::Expected< Value, Error >::value(), and testing::Value().

1395  {
1397  in_place, static_cast<Value&&>(val)};
1398 }
PskType type
double val
Definition: String.cpp:273
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
bool Value(const T &value, M matcher)
error_stage Error
template<class Char , std::size_t N>
constexpr BasicFixedString<Char, N - 1u> folly::makeFixedString ( const Char(&)  a[N])
noexcept

Construct a BasicFixedString object from a null-terminated array of characters. The capacity and size of the string will be equal to one less than the size of the array.

Precondition
a contains no embedded null characters.
a[N-1] == Char(0)
Postcondition
For a returned string s, s[i]==a[i] for every i in [0,N-1].

Definition at line 2991 of file FixedString.h.

References a.

Referenced by TEST().

2992  {
2993  return {a};
2994 }
char a
template<class T >
Future< typename std::decay< T >::type > folly::makeFuture ( T &&  t)

Make a completed Future by moving in a value. e.g.

string foo = "foo"; auto f = makeFuture(std::move(foo));

or

auto f = makeFuture<string>("foo");

NOTE: This function is deprecated. Please use makeSemiFuture and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary.

Definition at line 1310 of file Future-inl.h.

References folly::Future< T >::makeFuture, folly::pushmi::detail::t, and type.

Referenced by fizz::server::test::ServerProtocolTest::acceptEarlyData(), aFunction(), folly::SomeClass::aMethod(), folly::SomeClass::aStaticMethod(), aStdFunction(), BENCHMARK(), BENCHMARK_RELATIVE(), call(), wangle::Service< std::string, std::string >::close(), wangle::CloseOnReleaseFilter< Req, Resp >::close(), wangle::AsyncSocketHandler::close(), complexBenchmark(), fizz::server::DualTicketCipher::decrypt(), MultiFilePollerTest::delayedWrite(), doWorkStatic(), doWorkStaticFuture(), doWorkStaticTry(), fGen(), wangle::ContextImpl< H >::fireClose(), wangle::OutboundContextImpl< H >::fireClose(), wangle::ContextImpl< H >::fireWrite(), wangle::OutboundContextImpl< H >::fireWrite(), wangle::ContextImpl< H >::fireWriteException(), wangle::OutboundContextImpl< H >::fireWriteException(), folly::Future< folly::folly::Unit >::Future(), futureExecutor(), folly::futures::map(), recursion(), removeThreadTest(), folly::futures::detail::retryingPolicyCappedJitteredExponentialBackoff(), wangle::AsyncSocketHandler::shutdown(), someFuture(), TEST(), TEST_F(), fizz::server::test::TEST_F(), throwAndCatchImpl(), throwAndCatchWrappedImpl(), throwWrappedAndCatchImpl(), throwWrappedAndCatchWrappedImpl(), TYPED_TEST(), WeakRefTest(), wangle::MessageToByteEncoder< T >::write(), wangle::test::BytesReflector::write(), wangle::AsyncSocketHandler::write(), and ConcreteHandler< Rin, Rout, Win, Wout >::write().

1310  {
1311  return makeFuture(Try<typename std::decay<T>::type>(std::forward<T>(t)));
1312 }
PskType type
Future< T > makeFuture(Try< T > t)
Definition: Future-inl.h:1364
Future< Unit > folly::makeFuture ( )
inline

Make a completed void Future.

NOTE: This function is deprecated. Please use makeSemiFuture and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary.

Definition at line 1314 of file Future-inl.h.

References folly::Future< T >::makeFuture, type, and folly::futures::detail::FutureBase< T >::value().

1314  {
1315  return makeFuture(Unit{});
1316 }
Future< T > makeFuture(Try< T > t)
Definition: Future-inl.h:1364
template<class T >
Future< T > folly::makeFuture ( std::exception_ptr const &  e)

Make a failed Future from an exception_ptr. Because the Future's type cannot be inferred you have to specify it, e.g.

auto f = makeFuture<string>(std::current_exception());

Definition at line 1347 of file Future-inl.h.

References folly::Future< T >::makeFuture.

1347  {
1348  return makeFuture(Try<T>(e));
1349 }
Future< T > makeFuture(Try< T > t)
Definition: Future-inl.h:1364
template<class T >
Future< T > folly::makeFuture ( exception_wrapper  ew)

Make a failed Future from an exception_wrapper. NOTE: This function is deprecated. Please use makeSemiFuture and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary.

Definition at line 1352 of file Future-inl.h.

References folly::Future< T >::makeFuture, folly::gen::move, type, and value.

1352  {
1353  return makeFuture(Try<T>(std::move(ew)));
1354 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
Future< T > makeFuture(Try< T > t)
Definition: Future-inl.h:1364
template<class T , class E >
std::enable_if< std::is_base_of< std::exception, E >::value, Future< T > >::type folly::makeFuture ( E const &  e)

Make a Future from an exception type E that can be passed to std::make_exception_ptr().

NOTE: This function is deprecated. Please use makeSemiFuture and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary.

Definition at line 1359 of file Future-inl.h.

References folly::Future< T >::makeFuture.

1359  {
1360  return makeFuture(Try<T>(make_exception_wrapper<E>(e)));
1361 }
Future< T > makeFuture(Try< T > t)
Definition: Future-inl.h:1364
template<class T >
Future< T > folly::makeFuture ( Try< T t)

Make a Future out of a Try

NOTE: This function is deprecated. Please use makeSemiFuture and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary.

Definition at line 1364 of file Future-inl.h.

References folly::futures::detail::Core< T >::make(), and folly::gen::move.

1364  {
1365  return Future<T>(Future<T>::Core::make(std::move(t)));
1366 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<class F >
std::enable_if< !(isFuture<invoke_result_t<F>>::value), Future<typename lift_unit<invoke_result_t<F> >::type> >::type folly::makeFutureWith ( F &&  func)

Make a Future by executing a function.

If the function returns a value of type T, makeFutureWith returns a completed Future<T>, capturing the value returned by the function.

If the function returns a Future<T> already, makeFutureWith returns just that.

Either way, if the function throws, a failed Future is returned that captures the exception.

Calling makeFutureWith(func) is equivalent to calling makeFuture().then(func).

NOTE: This function is deprecated. Please use makeSemiFutureWith and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary.

Definition at line 1322 of file Future-inl.h.

References makeTryWith(), type, and folly::futures::detail::FutureBase< T >::value().

Referenced by wangle::MockHandler< Rin, Rout, Win, Wout >::close(), folly::futures::map(), folly::futures::detail::retryingImpl(), TEST(), wangle::MockHandler< Rin, Rout, Win, Wout >::write(), and wangle::MockHandler< Rin, Rout, Win, Wout >::writeException().

1322  {
1323  using InnerType = typename isFuture<invoke_result_t<F>>::Inner;
1324  try {
1325  return std::forward<F>(func)();
1326  } catch (std::exception& e) {
1327  return makeFuture<InnerType>(
1328  exception_wrapper(std::current_exception(), e));
1329  } catch (...) {
1330  return makeFuture<InnerType>(exception_wrapper(std::current_exception()));
1331  }
1332 }
template<class F >
std::enable_if< isFuture< invoke_result_t< F > >::value, invoke_result_t< F > >::type folly::makeFutureWith ( F &&  func)

Make a Future by executing a function.

If the function returns a value of type T, makeFutureWith returns a completed Future<T>, capturing the value returned by the function.

If the function returns a Future<T> already, makeFutureWith returns just that.

Either way, if the function throws, a failed Future is returned that captures the exception.

Calling makeFutureWith(func) is equivalent to calling makeFuture().then(func).

NOTE: This function is deprecated. Please use makeSemiFutureWith and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary.

Definition at line 1322 of file Future-inl.h.

Referenced by wangle::MockHandler< Rin, Rout, Win, Wout >::close(), folly::futures::map(), folly::futures::detail::retryingImpl(), TEST(), wangle::MockHandler< Rin, Rout, Win, Wout >::write(), and wangle::MockHandler< Rin, Rout, Win, Wout >::writeException().

1322  {
1323  using InnerType = typename isFuture<invoke_result_t<F>>::Inner;
1324  try {
1325  return std::forward<F>(func)();
1326  } catch (std::exception& e) {
1327  return makeFuture<InnerType>(
1328  exception_wrapper(std::current_exception(), e));
1329  } catch (...) {
1330  return makeFuture<InnerType>(exception_wrapper(std::current_exception()));
1331  }
1332 }
template<class F >
std::enable_if< !(isFuture<invoke_result_t<F>>::value), Future<lift_unit_t<invoke_result_t<F> > > >::type folly::makeFutureWith ( F &&  func)

Make a Future by executing a function.

If the function returns a value of type T, makeFutureWith returns a completed Future<T>, capturing the value returned by the function.

If the function returns a Future<T> already, makeFutureWith returns just that.

Either way, if the function throws, a failed Future is returned that captures the exception.

Calling makeFutureWith(func) is equivalent to calling makeFuture().then(func).

NOTE: This function is deprecated. Please use makeSemiFutureWith and pass the appropriate executor to .via on the returned SemiFuture to get a valid Future where necessary.

Definition at line 1340 of file Future-inl.h.

References makeTryWith(), type, and folly::futures::detail::FutureBase< T >::value().

1340  {
1341  using LiftedResult = lift_unit_t<invoke_result_t<F>>;
1342  return makeFuture<LiftedResult>(
1343  makeTryWith([&func]() mutable { return std::forward<F>(func)(); }));
1344 }
std::enable_if< !std::is_same< invoke_result_t< F >, void >::value, Try< invoke_result_t< F > > >::type makeTryWith(F &&f)
Definition: Try-inl.h:223
template<typename F >
FOLLY_NODISCARD detail::ScopeGuardImplDecay<F, true> folly::makeGuard ( F &&  f)
noexcept

ScopeGuard is a general implementation of the "Initialization is Resource Acquisition" idiom. Basically, it guarantees that a function is executed upon leaving the currrent scope unless otherwise told.

The makeGuard() function is used to create a new ScopeGuard object. It can be instantiated with a lambda function, a std::function<void()>, a functor, or a void(*)() function pointer.

Usage example: Add a friend to memory if and only if it is also added to the db.

void User::addFriend(User& newFriend) { // add the friend to memory friends_.push_back(&newFriend);

// If the db insertion that follows fails, we should // remove it from memory. auto guard = makeGuard([&] { friends_.pop_back(); });

// this will throw an exception upon error, which // makes the ScopeGuard execute UserCont::pop_back() // once the Guard's destructor is called. db_->addFriend(GetName(), newFriend.GetName());

// an exception was not thrown, so don't execute // the Guard. guard.dismiss(); }

Examine ScopeGuardTest.cpp for some more sample usage.

Stolen from: Andrei's and Petru Marginean's CUJ article: http://drdobbs.com/184403758 and the loki library: http://loki-lib.sourceforge.net/index.php?n=Idioms.ScopeGuardPointer and triendl.kj article: http://www.codeproject.com/KB/cpp/scope_guard.aspx

Definition at line 184 of file ScopeGuard.h.

References f, folly::gen::move, folly::pushmi::__adl::noexcept(), folly::detail::operator+(), type, and uncaught_exceptions().

Referenced by wangle::SSLContextManager::addSSLContextConfig(), folly::coro::detail::InlineTask< T >::Awaiter::await_resume(), BENCHMARK(), folly::AsyncUDPSocket::bind(), folly::python::bridgeFibers(), folly::python::bridgeFuture(), errnoStr(), wangle::SSLUtil::getSubjectAltName(), wangle::SSLContextManager::insert(), proxygen::HTTP1xCodec::onHeadersComplete(), folly::symbolizer::ElfFile::openNoThrow(), proxygen::HTTP2Codec::parseHeadersDecodeFrames(), folly::ThreadLocalPtr< SubscriberMap >::reset(), proxygen::HTTPSession::runLoopCallback(), folly::threadlocal_detail::ElementWrapper::set(), folly::Subprocess::spawn(), TEST(), TEST(), TEST_F(), testFinally(), testUndoAction(), folly::HHWheelTimer::timeoutExpired(), folly::IOBufQueue::updateGuard(), virtualExecutorTest(), and folly::HHWheelTimer::~HHWheelTimer().

185  {
186  return detail::ScopeGuardImplDecay<F, true>(static_cast<F&&>(f));
187 }
auto f
template<class T , class T0 = typename std::remove_reference<T>::type>
MoveWrapper<T0> folly::makeMoveWrapper ( T &&  t)

Make a MoveWrapper from the argument. Because the name "makeMoveWrapper" is already quite transparent in its intent, this will work for lvalues as if you had wrapped them in std::move.

Definition at line 82 of file MoveWrapper.h.

References folly::pushmi::detail::t.

Referenced by TEST(), and TEST_F().

82  {
83  return MoveWrapper<T0>(std::forward<T0>(t));
84 }
template<class T >
std::pair<Promise<T>, SemiFuture<T> > folly::makePromiseContract ( )

Definition at line 925 of file Future.h.

References f, and folly::gen::move.

925  {
926  auto p = Promise<T>();
927  auto f = p.getSemiFuture();
928  return std::make_pair(std::move(p), std::move(f));
929 }
auto f
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<class T >
std::pair<Promise<T>, Future<T> > folly::makePromiseContract ( Executor e)

Definition at line 2033 of file Future.h.

References f, h, folly::futures::detail::FutureBase< T >::isReady(), folly::gen::move, and value().

2033  {
2034  auto p = Promise<T>();
2035  auto f = p.getSemiFuture().via(e);
2036  return std::make_pair(std::move(p), std::move(f));
2037 }
auto f
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<class T >
SemiFuture< typename std::decay< T >::type > folly::makeSemiFuture ( T &&  t)

Make a completed SemiFuture by moving in a value. e.g.

string foo = "foo"; auto f = makeSemiFuture(std::move(foo));

or

auto f = makeSemiFuture<string>("foo");

Definition at line 712 of file Future-inl.h.

References folly::pushmi::detail::t, type, and folly::futures::detail::FutureBase< T >::value().

Referenced by makeSemiFuture(), folly::futures::map(), and TEST().

712  {
713  return makeSemiFuture(Try<typename std::decay<T>::type>(std::forward<T>(t)));
714 }
PskType type
SemiFuture< Unit > makeSemiFuture()
Definition: Future-inl.h:770
template<class T >
SemiFuture< T > folly::makeSemiFuture ( std::exception_ptr const &  e)

Make a failed Future from an exception_ptr. Because the Future's type cannot be inferred you have to specify it, e.g.

auto f = makeSemiFuture<string>(std::current_exception());

Definition at line 747 of file Future-inl.h.

References makeSemiFuture().

747  {
748  return makeSemiFuture(Try<T>(e));
749 }
SemiFuture< Unit > makeSemiFuture()
Definition: Future-inl.h:770
template<class T >
SemiFuture< T > folly::makeSemiFuture ( exception_wrapper  ew)

Make a failed SemiFuture from an exception_wrapper.

Definition at line 752 of file Future-inl.h.

References makeSemiFuture(), folly::gen::move, type, and value.

752  {
753  return makeSemiFuture(Try<T>(std::move(ew)));
754 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
SemiFuture< Unit > makeSemiFuture()
Definition: Future-inl.h:770
template<class T , class E >
std::enable_if< std::is_base_of< std::exception, E >::value, SemiFuture< T > >::type folly::makeSemiFuture ( E const &  e)

Make a SemiFuture from an exception type E that can be passed to std::make_exception_ptr().

Definition at line 759 of file Future-inl.h.

References makeSemiFuture().

759  {
760  return makeSemiFuture(Try<T>(make_exception_wrapper<E>(e)));
761 }
SemiFuture< Unit > makeSemiFuture()
Definition: Future-inl.h:770
template<class T >
SemiFuture< T > folly::makeSemiFuture ( Try< T t)

Make a Future out of a Try

Definition at line 764 of file Future-inl.h.

References folly::futures::detail::Core< T >::make(), and folly::gen::move.

764  {
765  return SemiFuture<T>(SemiFuture<T>::Core::make(std::move(t)));
766 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
SemiFuture< Unit > folly::makeSemiFuture ( )
inline

Make a completed void SemiFuture.

Definition at line 770 of file Future-inl.h.

References makeSemiFuture().

770  {
771  return makeSemiFuture(Unit{});
772 }
SemiFuture< Unit > makeSemiFuture()
Definition: Future-inl.h:770
template<class F >
std::enable_if< !(isFutureOrSemiFuture<invoke_result_t<F>>::value), SemiFuture<typename lift_unit<invoke_result_t<F> >::type> >::type folly::makeSemiFutureWith ( F &&  func)

Make a SemiFuture by executing a function.

If the function returns a value of type T, makeSemiFutureWith returns a completed SemiFuture<T>, capturing the value returned by the function.

If the function returns a SemiFuture<T> already, makeSemiFutureWith returns just that.

Either way, if the function throws, a failed Future is returned that captures the exception.

Definition at line 721 of file Future-inl.h.

References makeTryWith(), type, and folly::futures::detail::FutureBase< T >::value().

Referenced by folly::futures::map(), TEST(), and window().

721  {
722  using InnerType = typename isFutureOrSemiFuture<invoke_result_t<F>>::Inner;
723  try {
724  return std::forward<F>(func)();
725  } catch (std::exception& e) {
726  return makeSemiFuture<InnerType>(
727  exception_wrapper(std::current_exception(), e));
728  } catch (...) {
729  return makeSemiFuture<InnerType>(
730  exception_wrapper(std::current_exception()));
731  }
732 }
template<class F >
std::enable_if< isFutureOrSemiFuture< invoke_result_t< F > >::value, SemiFuture< typename invoke_result_t< F >::value_type > >::type folly::makeSemiFutureWith ( F &&  func)

Make a SemiFuture by executing a function.

If the function returns a value of type T, makeSemiFutureWith returns a completed SemiFuture<T>, capturing the value returned by the function.

If the function returns a SemiFuture<T> already, makeSemiFutureWith returns just that.

Either way, if the function throws, a failed Future is returned that captures the exception.

Definition at line 721 of file Future-inl.h.

Referenced by folly::futures::map(), TEST(), and window().

721  {
722  using InnerType = typename isFutureOrSemiFuture<invoke_result_t<F>>::Inner;
723  try {
724  return std::forward<F>(func)();
725  } catch (std::exception& e) {
726  return makeSemiFuture<InnerType>(
727  exception_wrapper(std::current_exception(), e));
728  } catch (...) {
729  return makeSemiFuture<InnerType>(
730  exception_wrapper(std::current_exception()));
731  }
732 }
template<class F >
std::enable_if< !(isFutureOrSemiFuture<invoke_result_t<F>>::value), SemiFuture<lift_unit_t<invoke_result_t<F> > > >::type folly::makeSemiFutureWith ( F &&  func)

Make a SemiFuture by executing a function.

If the function returns a value of type T, makeSemiFutureWith returns a completed SemiFuture<T>, capturing the value returned by the function.

If the function returns a SemiFuture<T> already, makeSemiFutureWith returns just that.

Either way, if the function throws, a failed Future is returned that captures the exception.

Definition at line 740 of file Future-inl.h.

References makeTryWith(), type, and folly::futures::detail::FutureBase< T >::value().

740  {
741  using LiftedResult = lift_unit_t<invoke_result_t<F>>;
742  return makeSemiFuture<LiftedResult>(
743  makeTryWith([&func]() mutable { return std::forward<F>(func)(); }));
744 }
std::enable_if< !std::is_same< invoke_result_t< F >, void >::value, Try< invoke_result_t< F > > >::type makeTryWith(F &&f)
Definition: Try-inl.h:223
template<typename T >
StampedPtr<T> folly::makeStampedPtr ( T ptr,
uint16_t  stamp 
)

Definition at line 124 of file StampedPtr.h.

References folly::StampedPtr< T >::pack().

Referenced by TEST().

124  {
125  return StampedPtr<T>{StampedPtr<T>::pack(ptr, stamp)};
126 }
void * ptr
std::system_error folly::makeSystemError ( const char *  msg)
inline

Definition at line 55 of file Exception.h.

References testing::Args(), and makeSystemErrorExplicit().

Referenced by folly::test::TEST().

55  {
56  return makeSystemErrorExplicit(errno, msg);
57 }
std::system_error makeSystemErrorExplicit(int err, Args &&...args)
Definition: Exception.h:50
template<class... Args>
std::system_error folly::makeSystemError ( Args &&...  args)

Definition at line 60 of file Exception.h.

References makeSystemErrorExplicit().

60  {
61  return makeSystemErrorExplicit(errno, std::forward<Args>(args)...);
62 }
std::system_error makeSystemErrorExplicit(int err, Args &&...args)
Definition: Exception.h:50
std::system_error folly::makeSystemErrorExplicit ( int  err,
const char *  msg 
)
inline

Definition at line 38 of file Exception.h.

References testing::Args().

Referenced by makeSystemError(), makeSystemErrorExplicit(), folly::test::TEST(), and throwSystemErrorExplicit().

38  {
39  // TODO: The C++ standard indicates that std::generic_category() should be
40  // used for POSIX errno codes.
41  //
42  // We should ideally change this to use std::generic_category() instead of
43  // std::system_category(). However, undertaking this change will require
44  // updating existing call sites that currently catch exceptions thrown by
45  // this code and currently expect std::system_category.
46  return std::system_error(err, std::system_category(), msg);
47 }
template<class... Args>
std::system_error folly::makeSystemErrorExplicit ( int  err,
Args &&...  args 
)

Definition at line 50 of file Exception.h.

References makeSystemErrorExplicit().

50  {
52  err, to<fbstring>(std::forward<Args>(args)...).c_str());
53 }
std::system_error makeSystemErrorExplicit(int err, Args &&...args)
Definition: Exception.h:50
template<typename F >
std::enable_if< !std::is_same< invoke_result_t< F >, void >::value, Try< invoke_result_t< F > > >::type folly::makeTryWith ( F &&  f)

Definition at line 223 of file Try-inl.h.

References f, type, and folly::Try< T >::value().

Referenced by folly::fibers::TaskIterator< T >::addTask(), folly::fibers::FiberManager::addTaskRemoteFuture(), folly::python::bridgeFibers(), makeFutureWith(), makeSemiFutureWith(), folly::Future< T >::onTimeout(), folly::fibers::Promise< T, BatonT >::setWith(), folly::SharedPromise< T >::setWith(), folly::Promise< T >::setWith(), TEST(), folly::futures::detail::FutureBase< T >::thenImplementation(), and folly::futures::detail::CoreCallbackState< T, F >::tryInvoke().

223  {
224  using ResultType = invoke_result_t<F>;
225  try {
226  return Try<ResultType>(f());
227  } catch (std::exception& e) {
228  return Try<ResultType>(exception_wrapper(std::current_exception(), e));
229  } catch (...) {
230  return Try<ResultType>(exception_wrapper(std::current_exception()));
231  }
232 }
auto f
template<typename F >
std::enable_if< std::is_same< invoke_result_t< F >, void >::value, Try< void > >::type folly::makeTryWith ( F &&  f)

Definition at line 237 of file Try-inl.h.

References testing::Args(), f, and T.

237  {
238  try {
239  f();
240  return Try<void>();
241  } catch (std::exception& e) {
242  return Try<void>(exception_wrapper(std::current_exception(), e));
243  } catch (...) {
244  return Try<void>(exception_wrapper(std::current_exception()));
245  }
246 }
auto f
template<class Error >
constexpr Unexpected< typename std::decay< Error >::type > folly::makeUnexpected ( Error &&  err)

For constructing an Unexpected object from an error code. Unexpected objects are implicitly convertible to Expected object in the error state. Usage is as follows:

enum class MyErrorCode { BAD_ERROR, WORSE_ERROR }; Expected<int, MyErrorCode> myAPI() { int i = // ...; return i ? makeExpected<MyErrorCode>(i) : makeUnexpected(MyErrorCode::BAD_ERROR); }

Definition at line 785 of file Expected.h.

Referenced by folly::detail::chronoRangeCheck(), folly::detail::convertTo(), proxygen::GzipHeaderCodec::decode(), folly::detail::digits_to(), folly::detail::durationToPosixTime(), folly::detail::SignedValueHandler< T, true >::finalize(), proxygen::TestStreamingCallback::getResult(), proxygen::compress::SimStreamingCallback::getResult(), isLowercase(), makeExpected(), folly::File::makeFile(), folly::detail::CheckTrailingSpace::operator()(), proxygen::GzipHeaderCodec::parseNameValues(), my::parseTo(), folly::detail::posixTimeToDuration(), folly::detail::str_to_bool(), folly::detail::str_to_floating(), folly::detail::str_to_integral(), TEST(), folly::expected_detail::expected_detail_ExpectedHelper::ExpectedHelper::then_(), toAppend(), folly::json_pointer::try_parse(), folly::json_patch::try_parse(), tryDecodeVarint(), folly::IPAddressV4::tryFromBinary(), folly::IPAddressV6::tryFromBinary(), folly::IPAddressV4::tryFromString(), folly::IPAddressV6::tryFromString(), folly::detail::tryPosixTimeToDuration(), folly::IPAddressV4::trySetFromBinary(), folly::IPAddressV6::trySetFromBinary(), and tryTo().

786  {
788  static_cast<Error&&>(err)};
789 }
PskType type
error_stage Error
template<typename T >
auto folly::makeUnpredictable ( T datum) -> typename std::enable_if< !detail::DoNotOptimizeAwayNeedsIndirect<T>::value>::type

Definition at line 285 of file Benchmark.h.

References benchmarkResultsFromDynamic(), benchmarkResultsToDynamic(), data(), printResultComparison(), T, and type.

Referenced by addBenchmark(), BENCHMARK(), and Run().

286  {
287  asm volatile("" : "+r"(datum));
288 }
void folly::mallctlCall ( const char *  cmd)
inline

Definition at line 62 of file MallctlHelper.h.

References cmd.

Referenced by TEST_F().

62  {
63  // Use <unsigned> rather than <void> to avoid sizeof(void).
64  mallctlRead<unsigned>(cmd, nullptr);
65 }
cmd
Definition: gtest-cfgcmd.txt:1
template<typename T >
void folly::mallctlRead ( const char *  cmd,
T out 
)

Definition at line 48 of file MallctlHelper.h.

References folly::detail::mallctlHelper().

Referenced by folly::detail::MemoryIdler::flushLocalMallocCaches(), MallctlHelperTest::readArena0DecayTime(), and TEST_F().

48  {
49  detail::mallctlHelper(cmd, out, static_cast<T*>(nullptr));
50 }
void mallctlHelper(const char *cmd, T *out, T *in)
Definition: MallctlHelper.h:33
cmd
Definition: gtest-cfgcmd.txt:1
template<typename T >
void folly::mallctlReadWrite ( const char *  cmd,
T out,
T  in 
)

Definition at line 58 of file MallctlHelper.h.

References folly::detail::mallctlHelper().

Referenced by TEST_F().

58  {
59  detail::mallctlHelper(cmd, out, &in);
60 }
void mallctlHelper(const char *cmd, T *out, T *in)
Definition: MallctlHelper.h:33
cmd
Definition: gtest-cfgcmd.txt:1
template<typename T >
void folly::mallctlWrite ( const char *  cmd,
T  in 
)

Definition at line 53 of file MallctlHelper.h.

References folly::detail::mallctlHelper().

Referenced by MallctlHelperTest::TearDown(), and TEST_F().

53  {
54  detail::mallctlHelper(cmd, static_cast<T*>(nullptr), &in);
55 }
void mallctlHelper(const char *cmd, T *out, T *in)
Definition: MallctlHelper.h:33
cmd
Definition: gtest-cfgcmd.txt:1
template<class InputIt1 , class InputIt2 , class OutputIt , class Compare >
OutputIt folly::merge ( InputIt1  first1,
InputIt1  last1,
InputIt2  first2,
InputIt2  last2,
OutputIt  d_first,
Compare  comp 
)

Definition at line 46 of file Merge.h.

References copy().

Referenced by TEST().

52  {
53  for (; first1 != last1; ++d_first) {
54  if (first2 == last2) {
55  return std::copy(first1, last1, d_first);
56  }
57  if (comp(*first2, *first1)) {
58  *d_first = *first2;
59  ++first2;
60  } else {
61  *d_first = *first1;
62  ++first1;
63  }
64  }
65  return std::copy(first2, last2, d_first);
66 }
constexpr std::decay< T >::type copy(T &&value) noexcept(noexcept(typename std::decay< T >::type(std::forward< T >(value))))
Definition: Utility.h:72
template<class InputIt1 , class InputIt2 , class OutputIt >
OutputIt folly::merge ( InputIt1  first1,
InputIt1  last1,
InputIt2  first2,
InputIt2  last2,
OutputIt  d_first 
)

Definition at line 69 of file Merge.h.

References copy().

74  {
75  for (; first1 != last1; ++d_first) {
76  if (first2 == last2) {
77  return std::copy(first1, last1, d_first);
78  }
79  if (*first2 < *first1) {
80  *d_first = *first2;
81  ++first2;
82  } else {
83  *d_first = *first1;
84  ++first1;
85  }
86  }
87  return std::copy(first2, last2, d_first);
88 }
constexpr std::decay< T >::type copy(T &&value) noexcept(noexcept(typename std::decay< T >::type(std::forward< T >(value))))
Definition: Utility.h:72
static string folly::metricReadable ( double  n,
unsigned int  decimals 
)
static

Definition at line 246 of file Benchmark.cpp.

References humanReadable(), and kMetricSuffixes.

Referenced by printResultComparison().

246  {
247  return humanReadable(n, decimals, kMetricSuffixes);
248 }
static string humanReadable(double n, unsigned int decimals, const ScaleInfo *scales)
Definition: Benchmark.cpp:227
static const ScaleInfo kMetricSuffixes[]
Definition: Benchmark.cpp:204
void folly::mmapFileCopy ( const char *  src,
const char *  dest,
mode_t  mode = 0666 
)

Copy a file using mmap(). Overwrites dest.

Definition at line 411 of file MemoryMapping.cpp.

References alignedForwardMemcpy(), folly::Range< Iter >::data(), folly::MemoryMapping::hintLinearScan(), folly::MemoryMapping::range(), folly::Range< Iter >::size(), and folly::MemoryMapping::writable().

411  {
412  MemoryMapping srcMap(src);
413  srcMap.hintLinearScan();
414 
415  MemoryMapping destMap(
416  File(dest, O_RDWR | O_CREAT | O_TRUNC, mode),
417  0,
418  off_t(srcMap.range().size()),
419  MemoryMapping::writable());
420 
422  destMap.writableRange().data(),
423  srcMap.range().data(),
424  srcMap.range().size());
425 }
dest
Definition: upload.py:394
void alignedForwardMemcpy(void *dst, const void *src, size_t size)
folly::Optional< PskKeyExchangeMode > mode
int folly::openNoInt ( const char *  name,
int  flags,
mode_t  mode = 0666 
)

Convenience wrappers around some commonly used system calls. The *NoInt wrappers retry on EINTR. The *Full wrappers retry on EINTR and also loop until all data is written. Note that *Full wrappers weaken the thread semantics of underlying system calls.

Definition at line 36 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt().

Referenced by wangle::FilePersistenceLayer< K, V >::persist(), readFile(), folly::test::CaptureFD::readIncremental(), testEmptyFile(), testInvalidFile(), testValidFile(), and TYPED_TEST().

36  {
37  return int(wrapNoInt(open, name, flags, mode));
38 }
ssize_t wrapNoInt(F f, Args...args)
flags
Definition: http_parser.h:127
folly::Optional< PskKeyExchangeMode > mode
const char * name
Definition: http_parser.c:437
template<class I1 , class I2 , std::enable_if_t< detail::Comparable< I1, I2 >::value, int > = 0>
bool folly::operator!= ( Poly< I1 > const &  _this,
Poly< I2 > const &  that 
)

Definition at line 86 of file Regular.h.

References value.

86  {
87  return !(_this == that);
88 }
template<typename Pointer >
constexpr bool folly::operator!= ( propagate_const< Pointer > const &  a,
std::nullptr_t   
)

Definition at line 219 of file PropagateConst.h.

References get_underlying().

219  {
220  return get_underlying(a) != nullptr;
221 }
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
template<typename Pointer >
constexpr bool folly::operator!= ( std::nullptr_t  ,
propagate_const< Pointer > const &  a 
)

Definition at line 224 of file PropagateConst.h.

References get_underlying().

224  {
225  return nullptr != get_underlying(a);
226 }
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
bool folly::operator!= ( const DelayedDestructionBase::DestructorGuard left,
const DelayedDestructionBase::DestructorGuard right 
)
inline

Definition at line 235 of file DelayedDestructionBase.h.

References folly::DelayedDestructionBase::DestructorGuard::get().

237  {
238  return left.get() != right.get();
239 }
template<typename Pointer >
constexpr bool folly::operator!= ( propagate_const< Pointer > const &  a,
propagate_const< Pointer > const &  b 
)

Definition at line 236 of file PropagateConst.h.

References get_underlying().

238  {
239  return get_underlying(a) != get_underlying(b);
240 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
bool folly::operator!= ( const DelayedDestructionBase::DestructorGuard left,
std::nullptr_t   
)
inline

Definition at line 250 of file DelayedDestructionBase.h.

References folly::DelayedDestructionBase::DestructorGuard::get().

252  {
253  return left.get() != nullptr;
254 }
bool folly::operator!= ( std::nullptr_t  ,
const DelayedDestructionBase::DestructorGuard right 
)
inline

Definition at line 255 of file DelayedDestructionBase.h.

References folly::DelayedDestructionBase::DestructorGuard::get().

257  {
258  return nullptr != right.get();
259 }
template<typename LeftAliasType , typename RightAliasType >
bool folly::operator!= ( const DelayedDestructionBase::IntrusivePtr< LeftAliasType > &  left,
const DelayedDestructionBase::IntrusivePtr< RightAliasType > &  right 
)
inline

Definition at line 268 of file DelayedDestructionBase.h.

References folly::DelayedDestructionBase::IntrusivePtr< AliasType >::get().

270  {
271  return left.get() != right.get();
272 }
template<typename Pointer , typename Other >
constexpr auto folly::operator!= ( propagate_const< Pointer > const &  a,
Other const &  b 
) -> decltype(get_underlying(a) != b, false)

Definition at line 282 of file PropagateConst.h.

References a, b, and get_underlying().

283  {
284  return get_underlying(a) != b;
285 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
template<typename LeftAliasType >
bool folly::operator!= ( const DelayedDestructionBase::IntrusivePtr< LeftAliasType > &  left,
std::nullptr_t   
)
inline

Definition at line 286 of file DelayedDestructionBase.h.

References folly::DelayedDestructionBase::IntrusivePtr< AliasType >::get().

288  {
289  return left.get() != nullptr;
290 }
template<typename RightAliasType >
bool folly::operator!= ( std::nullptr_t  ,
const DelayedDestructionBase::IntrusivePtr< RightAliasType > &  right 
)
inline

Definition at line 292 of file DelayedDestructionBase.h.

References folly::DelayedDestructionBase::IntrusivePtr< AliasType >::get().

294  {
295  return nullptr != right.get();
296 }
template<typename Other , typename Pointer >
constexpr auto folly::operator!= ( Other const &  a,
propagate_const< Pointer > const &  b 
) -> decltype(a != get_underlying(b), false)

Definition at line 318 of file PropagateConst.h.

References b, and get_underlying().

319  {
320  return a != get_underlying(b);
321 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
bool folly::operator!= ( const IPAddressV4 a,
const IPAddressV4 b 
)
inline

Definition at line 325 of file IPAddressV4.h.

References b.

325  {
326  return !(a == b);
327 }
char b
char a
template<typename T , typename RefCount >
bool folly::operator!= ( const ReadMostlyMainPtr< T, RefCount > &  ptr,
std::nullptr_t   
)
inline

Definition at line 425 of file ReadMostlySharedPtr.h.

427  {
428  return !(ptr == nullptr);
429 }
void * ptr
template<typename T , typename RefCount >
bool folly::operator!= ( std::nullptr_t  ,
const ReadMostlyMainPtr< T, RefCount > &  ptr 
)
inline

Definition at line 432 of file ReadMostlySharedPtr.h.

434  {
435  return !(ptr == nullptr);
436 }
void * ptr
template<typename T , typename RefCount >
bool folly::operator!= ( const ReadMostlySharedPtr< T, RefCount > &  ptr,
std::nullptr_t   
)
inline

Definition at line 439 of file ReadMostlySharedPtr.h.

441  {
442  return !(ptr == nullptr);
443 }
void * ptr
template<typename T , typename RefCount >
bool folly::operator!= ( std::nullptr_t  ,
const ReadMostlySharedPtr< T, RefCount > &  ptr 
)
inline

Definition at line 446 of file ReadMostlySharedPtr.h.

448  {
449  return !(ptr == nullptr);
450 }
void * ptr
template<class U , class V >
constexpr bool folly::operator!= ( const Optional< U > &  a,
const V &  b 
)

Definition at line 479 of file Optional.h.

References b.

479  {
480  return !(a == b);
481 }
char b
char a
template<class U , class V >
constexpr bool folly::operator!= ( const U &  a,
const Optional< V > &  b 
)

Definition at line 489 of file Optional.h.

References b.

489  {
490  return !(a == b);
491 }
char b
char a
template<class U , class V >
constexpr bool folly::operator!= ( const Optional< U > &  a,
const Optional< V > &  b 
)

Definition at line 507 of file Optional.h.

References b.

507  {
508  return !(a == b);
509 }
char b
char a
template<class Error , bool FB_CONCATENATE = false, typename std::enable_if< (FB_CONCATENATE(FB_CONCATENATE(Folly, Requires), __LINE__)||static_cast< bool >(IsEqualityComparable< Error >::value)), int >::type = 0>
bool folly::operator!= ( const Unexpected< Error > &  lhs,
const Unexpected< Error > &  rhs 
)
inline

Definition at line 766 of file Expected.h.

References folly::detail::rhs.

Referenced by makeExpected(), and std::hash< TestStruct >::operator()().

768  {
769  return !(lhs == rhs);
770 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename FunctionType >
bool folly::operator!= ( const Function< FunctionType > &  fn,
std::nullptr_t   
)

Definition at line 831 of file Function.h.

831  {
832  return !(fn == nullptr);
833 }
template<typename FunctionType >
bool folly::operator!= ( std::nullptr_t  ,
const Function< FunctionType > &  fn 
)

Definition at line 836 of file Function.h.

References testing::Args().

836  {
837  return !(nullptr == fn);
838 }
template<class Iter >
bool folly::operator!= ( const Range< Iter > &  lhs,
const Range< Iter > &  rhs 
)
inline

Definition at line 1192 of file Range.h.

References operator==().

1192  {
1193  return !(operator==(lhs, rhs));
1194 }
bool operator==(const char *c, CStringRange::Sentinel)
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class T , class U >
_t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool> > folly::operator!= ( const T lhs,
const U &  rhs 
)

operator!= through conversion for Range<const char*>

Definition at line 1248 of file Range.h.

1248  {
1249  return StringPiece(lhs) != StringPiece(rhs);
1250 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
Range< const char * > StringPiece
template<class Value , class Error , bool FB_CONCATENATE = false, typename std::enable_if< (FB_CONCATENATE(FB_CONCATENATE(Folly, Requires), __LINE__)||static_cast< bool >(IsEqualityComparable< Value >::value)), int >::type = 0>
bool folly::operator!= ( const Expected< Value, Error > &  lhs,
const Expected< Value, Error > &  rhs 
)
inline

Definition at line 1313 of file Expected.h.

References type, and value.

1315  {
1316  return !(rhs == lhs);
1317 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class Value , class Error >
bool folly::operator!= ( const Expected< Value, Error > &  ,
const Value &  other 
)
delete
template<class Value , class Error >
bool folly::operator!= ( const Value &  other,
const Expected< Value, Error > &   
)
delete
template<typename E , class T , class A , class S >
bool folly::operator!= ( const basic_fbstring< E, T, A, S > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2613 of file FBString.h.

References folly::detail::rhs.

2615  {
2616  return !(lhs == rhs);
2617 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
bool folly::operator!= ( const typename basic_fbstring< E, T, A, S >::value_type *  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2620 of file FBString.h.

References folly::detail::rhs.

2622  {
2623  return !(lhs == rhs);
2624 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
bool folly::operator!= ( const basic_fbstring< E, T, A, S > &  lhs,
const typename basic_fbstring< E, T, A, S >::value_type *  rhs 
)
inline

Definition at line 2627 of file FBString.h.

References folly::detail::rhs.

2629  {
2630  return !(lhs == rhs);
2631 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S , class A2 >
bool folly::operator!= ( const basic_fbstring< E, T, A, S > &  lhs,
const std::basic_string< E, T, A2 > &  rhs 
)
inline

Definition at line 2834 of file FBString.h.

References folly::detail::rhs.

2836  {
2837  return !(lhs == rhs);
2838 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S , class A2 >
bool folly::operator!= ( const std::basic_string< E, T, A2 > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2841 of file FBString.h.

References folly::detail::rhs.

2843  {
2844  return !(lhs == rhs);
2845 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class Char , std::size_t A, std::size_t B>
constexpr bool folly::operator!= ( const BasicFixedString< Char, A > &  a,
const BasicFixedString< Char, B > &  b 
)

Definition at line 2926 of file FixedString.h.

References b.

2928  {
2929  return !(a == b);
2930 }
char b
char a
WriteFlags folly::operator& ( WriteFlags  a,
WriteFlags  b 
)
inline

Definition at line 89 of file AsyncTransport.h.

References a, and uint32_t.

Referenced by folly::LogStreamProcessor::LogStreamProcessor().

89  {
90  return static_cast<WriteFlags>(
91  static_cast<uint32_t>(a) & static_cast<uint32_t>(b));
92 }
char b
char a
WriteFlags& folly::operator&= ( WriteFlags a,
WriteFlags  b 
)
inline

Definition at line 97 of file AsyncTransport.h.

References a, and b.

97  {
98  a = a & b;
99  return a;
100 }
char b
char a
constexpr LogLevel folly::operator+ ( LogLevel  level,
uint32_t  value 
)
inline

Definition at line 108 of file LogLevel.h.

References MAX_LEVEL, and uint32_t.

108  {
109  // Cap the result at LogLevel::MAX_LEVEL
110  return ((static_cast<uint32_t>(level) + value) >
111  static_cast<uint32_t>(LogLevel::MAX_LEVEL))
112  ? LogLevel::MAX_LEVEL
113  : static_cast<LogLevel>(static_cast<uint32_t>(level) + value);
114 }
static const char *const value
Definition: Conv.cpp:50
LogLevel
Definition: LogLevel.h:38
template<typename E , class T , class A , class S >
basic_fbstring<E, T, A, S> folly::operator+ ( const basic_fbstring< E, T, A, S > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2447 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::append(), folly::gen::move, folly::basic_fbstring< E, T, A, Storage >::reserve(), and folly::basic_fbstring< E, T, A, Storage >::size().

Referenced by BENCHMARK(), and TEST().

2449  {
2450  basic_fbstring<E, T, A, S> result;
2451  result.reserve(lhs.size() + rhs.size());
2452  result.append(lhs).append(rhs);
2453  return std::move(result);
2454 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
basic_fbstring<E, T, A, S> folly::operator+ ( basic_fbstring< E, T, A, S > &&  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2458 of file FBString.h.

References folly::gen::move.

2460  {
2461  return std::move(lhs.append(rhs));
2462 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
basic_fbstring<E, T, A, S> folly::operator+ ( const basic_fbstring< E, T, A, S > &  lhs,
basic_fbstring< E, T, A, S > &&  rhs 
)
inline

Definition at line 2466 of file FBString.h.

References folly::fbstring_core< Char >::capacity(), folly::gen::move, folly::detail::rhs, folly::fbstring_core< Char >::size(), and folly::basic_fbstring< E, T, A, Storage >::size().

2468  {
2469  if (rhs.capacity() >= lhs.size() + rhs.size()) {
2470  // Good, at least we don't need to reallocate
2471  return std::move(rhs.insert(0, lhs));
2472  }
2473  // Meh, no go. Forward to operator+(const&, const&).
2474  auto const& rhsC = rhs;
2475  return lhs + rhsC;
2476 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
basic_fbstring<E, T, A, S> folly::operator+ ( basic_fbstring< E, T, A, S > &&  lhs,
basic_fbstring< E, T, A, S > &&  rhs 
)
inline

Definition at line 2480 of file FBString.h.

References folly::gen::move.

2482  {
2483  return std::move(lhs.append(rhs));
2484 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
basic_fbstring<E, T, A, S> folly::operator+ ( const E lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2488 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::append(), folly::basic_fbstring< E, T, A, Storage >::reserve(), and folly::basic_fbstring< E, T, A, Storage >::size().

2490  {
2491  //
2492  basic_fbstring<E, T, A, S> result;
2493  const auto len = basic_fbstring<E, T, A, S>::traits_type::length(lhs);
2494  result.reserve(len + rhs.size());
2495  result.append(lhs, len).append(rhs);
2496  return result;
2497 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
basic_fbstring<E, T, A, S> folly::operator+ ( const E lhs,
basic_fbstring< E, T, A, S > &&  rhs 
)
inline

Definition at line 2501 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::append(), folly::fbstring_core< Char >::capacity(), folly::gen::move, folly::basic_fbstring< E, T, A, Storage >::reserve(), and folly::fbstring_core< Char >::size().

2503  {
2504  //
2505  const auto len = basic_fbstring<E, T, A, S>::traits_type::length(lhs);
2506  if (rhs.capacity() >= len + rhs.size()) {
2507  // Good, at least we don't need to reallocate
2508  rhs.insert(rhs.begin(), lhs, lhs + len);
2509  return std::move(rhs);
2510  }
2511  // Meh, no go. Do it by hand since we have len already.
2512  basic_fbstring<E, T, A, S> result;
2513  result.reserve(len + rhs.size());
2514  result.append(lhs, len).append(rhs);
2515  return result;
2516 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
basic_fbstring<E, T, A, S> folly::operator+ ( E  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2520 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::append(), folly::basic_fbstring< E, T, A, Storage >::push_back(), folly::basic_fbstring< E, T, A, Storage >::reserve(), and folly::basic_fbstring< E, T, A, Storage >::size().

2522  {
2523  basic_fbstring<E, T, A, S> result;
2524  result.reserve(1 + rhs.size());
2525  result.push_back(lhs);
2526  result.append(rhs);
2527  return result;
2528 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
basic_fbstring<E, T, A, S> folly::operator+ ( E  lhs,
basic_fbstring< E, T, A, S > &&  rhs 
)
inline

Definition at line 2532 of file FBString.h.

References folly::fbstring_core< Char >::capacity(), folly::gen::move, folly::detail::rhs, and folly::fbstring_core< Char >::size().

2534  {
2535  //
2536  if (rhs.capacity() > rhs.size()) {
2537  // Good, at least we don't need to reallocate
2538  rhs.insert(rhs.begin(), lhs);
2539  return std::move(rhs);
2540  }
2541  // Meh, no go. Forward to operator+(E, const&).
2542  auto const& rhsC = rhs;
2543  return lhs + rhsC;
2544 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
basic_fbstring<E, T, A, S> folly::operator+ ( const basic_fbstring< E, T, A, S > &  lhs,
const E rhs 
)
inline

Definition at line 2548 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::append(), folly::basic_fbstring< E, T, A, Storage >::reserve(), and folly::basic_fbstring< E, T, A, Storage >::size().

2550  {
2551  typedef typename basic_fbstring<E, T, A, S>::size_type size_type;
2552  typedef typename basic_fbstring<E, T, A, S>::traits_type traits_type;
2553 
2554  basic_fbstring<E, T, A, S> result;
2555  const size_type len = traits_type::length(rhs);
2556  result.reserve(lhs.size() + len);
2557  result.append(lhs).append(rhs, len);
2558  return result;
2559 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
basic_fbstring<E, T, A, S> folly::operator+ ( basic_fbstring< E, T, A, S > &&  lhs,
const E rhs 
)
inline

Definition at line 2563 of file FBString.h.

References folly::gen::move.

2565  {
2566  //
2567  return std::move(lhs += rhs);
2568 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
basic_fbstring<E, T, A, S> folly::operator+ ( const basic_fbstring< E, T, A, S > &  lhs,
E  rhs 
)
inline

Definition at line 2572 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::append(), folly::basic_fbstring< E, T, A, Storage >::push_back(), folly::basic_fbstring< E, T, A, Storage >::reserve(), and folly::basic_fbstring< E, T, A, Storage >::size().

2574  {
2575  basic_fbstring<E, T, A, S> result;
2576  result.reserve(lhs.size() + 1);
2577  result.append(lhs);
2578  result.push_back(rhs);
2579  return result;
2580 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
basic_fbstring<E, T, A, S> folly::operator+ ( basic_fbstring< E, T, A, S > &&  lhs,
E  rhs 
)
inline

Definition at line 2584 of file FBString.h.

References folly::gen::move.

2586  {
2587  //
2588  return std::move(lhs += rhs);
2589 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class Char , std::size_t N, std::size_t M>
constexpr BasicFixedString<Char, N + M> folly::operator+ ( const BasicFixedString< Char, N > &  a,
const BasicFixedString< Char, M > &  b 
)
noexcept

Symmetric concatenation

Definition at line 2971 of file FixedString.h.

References a, b, and folly::detail::fixedstring::Helper::data_().

2973  {
2974  return detail::fixedstring::Helper::concat_<Char>(
2976  a.size(),
2978  b.size(),
2980 }
char b
make_integer_sequence< std::size_t, Size > make_index_sequence
Definition: Utility.h:209
char a
StringPiece data_
LogLevel& folly::operator+= ( LogLevel level,
uint32_t  value 
)
inline

Definition at line 115 of file LogLevel.h.

References value().

Referenced by BENCHMARK().

115  {
116  level = level + value;
117  return level;
118 }
static const char *const value
Definition: Conv.cpp:50
constexpr LogLevel folly::operator- ( LogLevel  level,
uint32_t  value 
)
inline

Definition at line 119 of file LogLevel.h.

References uint32_t.

119  {
120  return static_cast<LogLevel>(static_cast<uint32_t>(level) - value);
121 }
static const char *const value
Definition: Conv.cpp:50
LogLevel
Definition: LogLevel.h:38
LogLevel& folly::operator-= ( LogLevel level,
uint32_t  value 
)
inline

Definition at line 122 of file LogLevel.h.

References logLevelToString(), name, operator<<(), string, stringToLogLevel(), and value().

122  {
123  level = level - value;
124  return level;
125 }
static const char *const value
Definition: Conv.cpp:50
bool folly::operator< ( const HugePageSize a,
const HugePageSize b 
)
inline

Definition at line 46 of file HugePages.h.

References folly::HugePageSize::size.

46  {
47  return a.size < b.size;
48 }
char b
char a
template<class I1 , class I2 , std::enable_if_t< detail::Orderable< I1, I2 >::value, int > = 0>
bool folly::operator< ( Poly< I1 > const &  _this,
Poly< I2 > const &  that 
)

Definition at line 94 of file Regular.h.

References poly_empty(), and poly_type().

94  {
95  if (poly_empty(that)) {
96  return false;
97  } else if (poly_empty(_this)) {
98  return true;
99  } else if (poly_type(_this) != poly_type(that)) {
100  throw BadPolyCast{};
101  }
102  return ::folly::poly_call<0, poly::IStrictlyOrderable>(_this, that);
103 }
std::type_info const & poly_type(detail::PolyRoot< I > const &that) noexcept
Definition: Poly.h:358
bool poly_empty(detail::PolyRoot< I > const &that) noexcept
Definition: Poly.h:383
template<typename Pointer >
constexpr bool folly::operator< ( propagate_const< Pointer > const &  a,
propagate_const< Pointer > const &  b 
)

Definition at line 243 of file PropagateConst.h.

References get_underlying().

245  {
246  return get_underlying(a) < get_underlying(b);
247 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
template<typename Pointer , typename Other >
constexpr auto folly::operator< ( propagate_const< Pointer > const &  a,
Other const &  b 
) -> decltype(get_underlying(a) < b, false)

Definition at line 288 of file PropagateConst.h.

References b, and get_underlying().

289  {
290  return get_underlying(a) < b;
291 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
bool folly::operator< ( const IPAddressV4 addr1,
const IPAddressV4 addr2 
)
inline

Definition at line 321 of file IPAddressV4.h.

References folly::IPAddressV4::toLongHBO().

321  {
322  return (addr1.toLongHBO() < addr2.toLongHBO());
323 }
template<typename Other , typename Pointer >
constexpr auto folly::operator< ( Other const &  a,
propagate_const< Pointer > const &  b 
) -> decltype(a < get_underlying(b), false)

Definition at line 324 of file PropagateConst.h.

References b, and get_underlying().

325  {
326  return a < get_underlying(b);
327 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
bool folly::operator< ( const IPAddress &  addr1,
const IPAddress &  addr2 
)

Definition at line 405 of file IPAddress.cpp.

References folly::detail::familyNameStr(), folly::IPAddressV4::longestCommonPrefix(), folly::IPAddressV6::longestCommonPrefix(), prefix(), and sformat().

405  {
406  if (addr1.family() == addr2.family()) {
407  if (addr1.isV6()) {
408  return (addr1.asV6() < addr2.asV6());
409  } else if (addr1.isV4()) {
410  return (addr1.asV4() < addr2.asV4());
411  } else {
412  CHECK_EQ(addr1.family(), AF_UNSPEC);
413  // Two default initialized AF_UNSPEC addresses can not be less than each
414  // other. AF_UNSPEC is the only other value for which an IPAddress can be
415  // created, in the default constructor case.
416  return false;
417  }
418  }
419  if (addr1.isV6()) {
420  // means addr2 is v4, convert it to a mapped v6 address and compare
421  return addr1.asV6() < addr2.asV4().createIPv6();
422  }
423  if (addr2.isV6()) {
424  // means addr2 is v6, convert addr1 to v4 mapped and compare
425  return addr1.asV4().createIPv6() < addr2.asV6();
426  }
427  return false;
428 }
template<class U , class V >
FOLLY_CPP14_CONSTEXPR bool folly::operator< ( const Optional< U > &  a,
const Optional< V > &  b 
)

Definition at line 512 of file Optional.h.

References folly::Optional< Value >::hasValue(), and folly::Optional< Value >::value().

514  {
515  if (a.hasValue() != b.hasValue()) {
516  return a.hasValue() < b.hasValue();
517  }
518  if (a.hasValue()) {
519  return a.value() < b.value();
520  }
521  return false;
522 }
char b
char a
template<class V >
bool folly::operator< ( const Optional< V > &  ,
const V &  other 
)
delete
template<class V >
bool folly::operator< ( const V &  other,
const Optional< V > &   
)
delete
template<class V >
constexpr bool folly::operator< ( const Optional< V > &  ,
None   
)
noexcept

Definition at line 567 of file Optional.h.

567  {
568  return false;
569 }
template<class V >
constexpr bool folly::operator< ( None  ,
const Optional< V > &  a 
)
noexcept

Definition at line 571 of file Optional.h.

571  {
572  return a.hasValue();
573 }
char a
template<class Iter >
bool folly::operator< ( const Range< Iter > &  lhs,
const Range< Iter > &  rhs 
)
inline

Definition at line 1197 of file Range.h.

1197  {
1198  return lhs.compare(rhs) < 0;
1199 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class T , class U >
_t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool> > folly::operator< ( const T lhs,
const U &  rhs 
)

operator< through conversion for Range<const char*>

Definition at line 1257 of file Range.h.

1257  {
1258  return StringPiece(lhs) < StringPiece(rhs);
1259 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
Range< const char * > StringPiece
template<class Value , class Error >
std::enable_if<IsLessThanComparable<Value>::value, bool>::type folly::operator< ( const Expected< Value, Error > &  lhs,
const Expected< Value, Error > &  rhs 
)
inline

Definition at line 1321 of file Expected.h.

References FOLLY_REQUIRES_TRAILING, folly::Expected< Value, Error >::hasError(), folly::expected_detail::ExpectedStorage< Value, Error >::uninitializedByException(), UNLIKELY, value, testing::Value(), and folly::expected_detail::ExpectedStorage< Value, Error >::value_.

Referenced by BENCHMARK(), folly::sorted_vector_set< folly::RequestData * >::operator>=(), folly::sorted_vector_map< Key, Value, Compare, Allocator, GrowthPolicy, Container >::operator>=(), TEST(), and testing::TEST().

1323  {
1324  if (UNLIKELY(
1325  lhs.uninitializedByException() || rhs.uninitializedByException())) {
1326  throw_exception<BadExpectedAccess>();
1327  }
1328  if (UNLIKELY(lhs.hasError())) {
1329  return !rhs.hasError();
1330  }
1331  if (UNLIKELY(rhs.hasError())) {
1332  return false;
1333  }
1334  return lhs.value_ < rhs.value_;
1335 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
#define UNLIKELY(x)
Definition: Likely.h:48
template<class Value , class Error >
bool folly::operator< ( const Expected< Value, Error > &  ,
const Value &  other 
)
delete
template<class Value , class Error >
bool folly::operator< ( const Value &  other,
const Expected< Value, Error > &   
)
delete
template<typename E , class T , class A , class S >
bool folly::operator< ( const basic_fbstring< E, T, A, S > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2634 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::compare().

2636  {
2637  return lhs.compare(rhs) < 0;
2638 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
bool folly::operator< ( const basic_fbstring< E, T, A, S > &  lhs,
const typename basic_fbstring< E, T, A, S >::value_type *  rhs 
)
inline

Definition at line 2641 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::compare().

2643  {
2644  return lhs.compare(rhs) < 0;
2645 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
bool folly::operator< ( const typename basic_fbstring< E, T, A, S >::value_type *  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2648 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::compare().

2650  {
2651  return rhs.compare(lhs) > 0;
2652 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S , class A2 >
bool folly::operator< ( const basic_fbstring< E, T, A, S > &  lhs,
const std::basic_string< E, T, A2 > &  rhs 
)
inline

Definition at line 2848 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::compare(), and folly::basic_fbstring< E, T, A, Storage >::size().

2850  {
2851  return lhs.compare(0, lhs.size(), rhs.data(), rhs.size()) < 0;
2852 }
template<typename E , class T , class A , class S , class A2 >
bool folly::operator< ( const std::basic_string< E, T, A2 > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2862 of file FBString.h.

2864  {
2865  return rhs > lhs;
2866 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class Char , std::size_t A, std::size_t B>
constexpr bool folly::operator< ( const BasicFixedString< Char, A > &  a,
const BasicFixedString< Char, B > &  b 
)
noexcept

Definition at line 2933 of file FixedString.h.

References a, b, folly::detail::fixedstring::compare_(), folly::detail::fixedstring::Helper::data_(), and lt.

2935  {
2936  return ordering::lt ==
2939  0u,
2940  a.size(),
2942  0u,
2943  b.size());
2944 }
char b
char a
constexpr ordering compare_(const Left &left, std::size_t left_pos, std::size_t left_size, const Right &right, std::size_t right_pos, std::size_t right_size) noexcept
Definition: FixedString.h:111
StringPiece data_
std::ostream & folly::operator<< ( std::ostream &  os,
const LogConfig config 
)

Definition at line 27 of file ConfigHelpers.cpp.

References cc, folly::LogConfig::getCategoryConfigs(), folly::LogConfig::getHandlerConfigs(), and name.

27  {
28  // We could just use folly::toPrettyJson(logConfigToDynamic(config))
29  // However, the format here is much more compact and easier to read if there
30  // are discrepancies between configs in a test check.
31 
32  // Sort the categories by name before printing
33  os << "{\n categories: {\n";
34  std::vector<std::string> names;
35  const auto& catConfigs = config.getCategoryConfigs();
36  for (const auto& cc : catConfigs) {
37  names.push_back(cc.first);
38  }
39  std::sort(names.begin(), names.end());
40  for (const auto& name : names) {
41  os << " " << name << "=" << catConfigs.at(name) << "\n";
42  }
43 
44  // Sort the handlers by name before printing
45  os << " }\n handlers: {\n";
46  const auto& handlerConfigs = config.getHandlerConfigs();
47  names.clear();
48  for (const auto& cc : handlerConfigs) {
49  names.push_back(cc.first);
50  }
51  std::sort(names.begin(), names.end());
52  for (const auto& name : names) {
53  os << " " << name << "=" << handlerConfigs.at(name) << "\n";
54  }
55 
56  os << " }\n}";
57  return os;
58 }
The non test part of the code is expected to have failures gtest_output_test_ cc
AHArrayT::Config config
const char * name
Definition: http_parser.c:437
std::ostream & folly::operator<< ( ostream &  os,
const IPAddressV4 addr 
)

Definition at line 36 of file IPAddressV4.cpp.

References folly::IPAddressV4::str().

36  {
37  os << addr.str();
38  return os;
39 }
ThreadPoolListHook * addr
std::ostream& folly::operator<< ( std::ostream &  os,
E  e 
)

Definition at line 37 of file ExpectedTest.cpp.

References E1, and E2.

37  {
38  switch (e) {
39  case E::E1:
40  return os << "E::E1";
41  case E::E2:
42  return os << "E::E2";
43  default:;
44  }
45  return os;
46 }
ostream& folly::operator<< ( ostream &  os,
const IPAddress &  addr 
)

Definition at line 37 of file IPAddress.cpp.

37  {
38  os << addr.str();
39  return os;
40 }
ThreadPoolListHook * addr
template<class V , class E >
std::ostream& folly::operator<< ( std::ostream &  os,
const Expected< V, E > &  e 
)

Definition at line 49 of file ExpectedTest.cpp.

49  {
50  if (e) {
51  os << "Expected(" << e.value() << ')';
52  } else {
53  os << "Unexpected(" << e.error() << ')';
54  }
55  return os;
56 }
std::ostream & folly::operator<< ( ostream &  os,
const IPAddressV6 addr 
)

Definition at line 54 of file IPAddressV6.cpp.

References folly::IPAddressV6::str().

54  {
55  os << addr.str();
56  return os;
57 }
ThreadPoolListHook * addr
std::ostream & folly::operator<< ( std::ostream &  os,
const LogCategoryConfig config 
)

Definition at line 60 of file ConfigHelpers.cpp.

References folly::LogCategoryConfig::handlers, folly::Optional< Value >::hasValue(), folly::LogCategoryConfig::inheritParentLevel, join(), folly::LogCategoryConfig::level, logLevelToString(), and folly::Optional< Value >::value().

60  {
61  // Rather than printing the JSON configuration, we print a shorter
62  // representation closer to the basic config string format.
63  os << logLevelToString(config.level);
64  if (!config.inheritParentLevel) {
65  os << "!";
66  }
67  if (config.handlers.hasValue()) {
68  os << ":" << join(",", config.handlers.value());
69  }
70  return os;
71 }
string logLevelToString(LogLevel level)
Definition: LogLevel.cpp:109
AHArrayT::Config config
#define join
std::ostream & folly::operator<< ( std::ostream &  os,
const LogHandlerConfig config 
)

Definition at line 73 of file ConfigHelpers.cpp.

References folly::gen::first, folly::LogHandlerConfig::options, folly::LogHandlerConfig::type, and folly::Optional< Value >::value().

73  {
74  // Rather than printing the JSON configuration, we print a shorter
75  // representation closer to the basic config string format.
76  os << (config.type ? config.type.value() : "[no type]");
77  bool first = true;
78  for (const auto& opt : config.options) {
79  if (!first) {
80  os << ",";
81  } else {
82  os << ":";
83  first = false;
84  }
85  os << opt.first << "=" << opt.second;
86  }
87  return os;
88 }
AHArrayT::Config config
constexpr detail::First first
Definition: Base-inl.h:2553
template<class CharT , class Traits >
std::basic_ostream<CharT, Traits>& folly::operator<< ( std::basic_ostream< CharT, Traits > &  os,
const NetworkSocket addr 
)
inline

Definition at line 67 of file NetworkSocket.h.

References folly::NetworkSocket::data.

69  {
70  os << "folly::NetworkSocket(" << addr.data << ")";
71  return os;
72 }
ThreadPoolListHook * addr
std::ostream & folly::operator<< ( std::ostream &  os,
LogLevel  level 
)

Print a LogLevel in a human readable format.

Definition at line 141 of file LogLevel.cpp.

References logLevelToString().

141  {
142  os << logLevelToString(level);
143  return os;
144 }
string logLevelToString(LogLevel level)
Definition: LogLevel.cpp:109
std::ostream & folly::operator<< ( std::ostream &  os,
MacAddress  address 
)

Definition at line 147 of file MacAddress.cpp.

References folly::MacAddress::toString().

147  {
148  os << address.toString();
149  return os;
150 }
template<typename T >
std::ostream& folly::operator<< ( std::ostream &  os,
const PackedSyncPtr< T > &  ptr 
)

Definition at line 162 of file PackedSyncPtr.h.

References ptr.

162  {
163  os << "PackedSyncPtr(" << ptr.get() << ", " << ptr.extra() << ")";
164  return os;
165 }
void * ptr
std::ostream & folly::operator<< ( std::ostream &  os,
const TimePoint timePoint 
)

Definition at line 234 of file TimeUtil.cpp.

References folly::TimePoint::getTimeEnd(), folly::TimePoint::getTimeStart(), and folly::TimePoint::getTimeWaiting().

234  {
235  os << "TimePoint(" << timePoint.getTimeStart().time_since_epoch().count()
236  << ", " << timePoint.getTimeEnd().time_since_epoch().count() << ", "
237  << timePoint.getTimeWaiting().count() << ")";
238  return os;
239 }
template<bool containerMode, class... Args>
std::ostream& folly::operator<< ( std::ostream &  out,
const Formatter< containerMode, Args... > &  formatter 
)

Formatter objects can be written to streams.

Definition at line 245 of file Format.h.

References testing::Args(), FILE, and writeTo().

247  {
248  auto writer = [&out](StringPiece sp) {
249  out.write(sp.data(), std::streamsize(sp.size()));
250  };
251  formatter(writer);
252  return out;
253 }
Range< const char * > StringPiece
std::ostream & folly::operator<< ( std::ostream &  os,
const AsyncIOOp op 
)

Definition at line 388 of file AsyncIO.cpp.

References folly::AsyncIOOp::COMPLETED, errnoStr(), folly::AsyncIOOp::iocb_, folly::AsyncIOOp::result_, folly::AsyncIOOp::state_, and folly::AsyncIOOp::UNINITIALIZED.

388  {
389  os << "{" << op.state_ << ", ";
390 
391  if (op.state_ != AsyncIOOp::State::UNINITIALIZED) {
392  os << op.iocb_;
393  }
394 
395  if (op.state_ == AsyncIOOp::State::COMPLETED) {
396  os << "result=" << op.result_;
397  if (op.result_ < 0) {
398  os << " (" << errnoStr(-op.result_) << ')';
399  }
400  os << ", ";
401  }
402 
403  return os << "}";
404 }
fbstring errnoStr(int err)
Definition: String.cpp:463
std::ostream & folly::operator<< ( std::ostream &  os,
AsyncIOOp::State  state 
)

Definition at line 406 of file AsyncIO.cpp.

406  {
407  return os << asyncIoOpStateToString(state);
408 }
state
Definition: http_parser.c:272
template<class C , std::size_t N>
std::basic_ostream<C>& folly::operator<< ( std::basic_ostream< C > &  os,
const BasicFixedString< C, N > &  string 
)
inline

Definition at line 2903 of file FixedString.h.

References folly::test::begin(), and size().

2905  {
2906  using StreamSize = decltype(os.width());
2907  os.write(string.begin(), static_cast<StreamSize>(string.size()));
2908  return os;
2909 }
auto begin(TestAdlIterable &instance)
Definition: ForeachTest.cpp:56
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
std::ostream & folly::operator<< ( std::ostream &  os,
const PasswordCollector collector 
)

Definition at line 620 of file SSLContext.cpp.

References folly::PasswordCollector::describe().

620  {
621  os << collector.describe();
622  return os;
623 }
template<class Ch >
std::basic_ostream<Ch>& folly::operator<< ( std::basic_ostream< Ch > &  sout,
exception_wrapper const &  ew 
)

Inserts ew.what() into the ostream sout.

Returns
sout

Definition at line 635 of file ExceptionWrapper.h.

References folly::exception_wrapper::what().

637  {
638  return sout << ew.what();
639 }
std::ostream & folly::operator<< ( std::ostream &  os,
const SocketAddress addr 
)

Definition at line 775 of file SocketAddress.cpp.

References folly::SocketAddress::describe().

775  {
776  os << addr.describe();
777  return os;
778 }
ThreadPoolListHook * addr
std::ostream& folly::operator<< ( std::ostream &  out,
dynamic const &  d 
)
inline

Definition at line 1158 of file dynamic-inl.h.

References folly::dynamic::print().

Referenced by folly::IPAddressV4::AddressStorage::AddressStorage(), operator-=(), and toAppend().

1158  {
1159  d.print(out);
1160  return out;
1161 }
template<class C >
std::basic_ostream<C>& folly::operator<< ( std::basic_ostream< C > &  os,
Range< C * >  piece 
)

Definition at line 1176 of file Range.h.

1176  {
1177  using StreamSize = decltype(os.width());
1178  os.write(piece.start(), static_cast<StreamSize>(piece.size()));
1179  return os;
1180 }
template<class C >
std::basic_ostream<C>& folly::operator<< ( std::basic_ostream< C > &  os,
Range< C const * >  piece 
)

Definition at line 1167 of file Range.h.

References folly::Range< Iter >::size(), and folly::Range< Iter >::start().

1169  {
1170  using StreamSize = decltype(os.width());
1171  os.write(piece.start(), static_cast<StreamSize>(piece.size()));
1172  return os;
1173 }
template<typename E , class T , class A , class S >
std::basic_ostream< typename basic_fbstring<E, T, A, S>::value_type, typename basic_fbstring<E, T, A, S>::traits_type>& folly::operator<< ( std::basic_ostream< typename basic_fbstring< E, T, A, S >::value_type, typename basic_fbstring< E, T, A, S >::traits_type > &  os,
const basic_fbstring< E, T, A, S > &  str 
)
inline

Definition at line 2772 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::data(), failed, and folly::basic_fbstring< E, T, A, Storage >::size().

2776  {
2777 #if _LIBCPP_VERSION
2778  typedef std::basic_ostream<
2779  typename basic_fbstring<E, T, A, S>::value_type,
2780  typename basic_fbstring<E, T, A, S>::traits_type>
2781  _ostream_type;
2782  typename _ostream_type::sentry _s(os);
2783  if (_s) {
2784  typedef std::ostreambuf_iterator<
2785  typename basic_fbstring<E, T, A, S>::value_type,
2786  typename basic_fbstring<E, T, A, S>::traits_type>
2787  _Ip;
2788  size_t __len = str.size();
2789  bool __left =
2790  (os.flags() & _ostream_type::adjustfield) == _ostream_type::left;
2791  if (__pad_and_output(
2792  _Ip(os),
2793  str.data(),
2794  __left ? str.data() + __len : str.data(),
2795  str.data() + __len,
2796  os,
2797  os.fill())
2798  .failed()) {
2799  os.setstate(_ostream_type::badbit | _ostream_type::failbit);
2800  }
2801  }
2802 #elif defined(_MSC_VER)
2803  typedef decltype(os.precision()) streamsize;
2804  // MSVC doesn't define __ostream_insert
2805  os.write(str.data(), static_cast<streamsize>(str.size()));
2806 #else
2807  std::__ostream_insert(os, str.data(), str.size());
2808 #endif
2809  return os;
2810 }
static bool failed
std::ostream& folly::operator<< ( std::ostream &  os,
const AsyncSocket::StateEnum state 
)

Definition at line 2807 of file AsyncSocket.cpp.

2809  {
2810  os << static_cast<int>(state);
2811  return os;
2812 }
state
Definition: http_parser.c:272
template<class I1 , class I2 , std::enable_if_t< detail::Orderable< I1, I2 >::value, int > = 0>
bool folly::operator<= ( Poly< I1 > const &  _this,
Poly< I2 > const &  that 
)

Definition at line 117 of file Regular.h.

117  {
118  return !(that < _this);
119 }
template<typename Pointer >
constexpr bool folly::operator<= ( propagate_const< Pointer > const &  a,
propagate_const< Pointer > const &  b 
)

Definition at line 250 of file PropagateConst.h.

References get_underlying().

252  {
253  return get_underlying(a) <= get_underlying(b);
254 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
template<typename Pointer , typename Other >
constexpr auto folly::operator<= ( propagate_const< Pointer > const &  a,
Other const &  b 
) -> decltype(get_underlying(a) <= b, false)

Definition at line 294 of file PropagateConst.h.

References b, and get_underlying().

295  {
296  return get_underlying(a) <= b;
297 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
template<typename Other , typename Pointer >
constexpr auto folly::operator<= ( Other const &  a,
propagate_const< Pointer > const &  b 
) -> decltype(a <= get_underlying(b), false)

Definition at line 330 of file PropagateConst.h.

References b, and get_underlying().

331  {
332  return a <= get_underlying(b);
333 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
bool folly::operator<= ( const IPAddressV4 a,
const IPAddressV4 b 
)
inline

Definition at line 331 of file IPAddressV4.h.

References b.

331  {
332  return !(a > b);
333 }
char b
char a
template<class U , class V >
constexpr bool folly::operator<= ( const Optional< U > &  a,
const Optional< V > &  b 
)

Definition at line 530 of file Optional.h.

References a, and b.

530  {
531  return !(b < a);
532 }
char b
char a
template<class V >
bool folly::operator<= ( const Optional< V > &  ,
const V &  other 
)
delete
template<class V >
bool folly::operator<= ( const V &  other,
const Optional< V > &   
)
delete
template<class V >
constexpr bool folly::operator<= ( None  ,
const Optional< V > &   
)
noexcept

Definition at line 583 of file Optional.h.

583  {
584  return true;
585 }
template<class V >
constexpr bool folly::operator<= ( const Optional< V > &  a,
None   
)
noexcept

Definition at line 587 of file Optional.h.

587  {
588  return !a.hasValue();
589 }
char a
template<class Iter >
bool folly::operator<= ( const Range< Iter > &  lhs,
const Range< Iter > &  rhs 
)
inline

Definition at line 1202 of file Range.h.

1202  {
1203  return lhs.compare(rhs) <= 0;
1204 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class T , class U >
_t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool> > folly::operator<= ( const T lhs,
const U &  rhs 
)

operator< through conversion for Range<const char*>

Definition at line 1275 of file Range.h.

1275  {
1276  return StringPiece(lhs) <= StringPiece(rhs);
1277 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
Range< const char * > StringPiece
template<class Value , class Error , bool FB_CONCATENATE = false, typename std::enable_if< (FB_CONCATENATE(FB_CONCATENATE(Folly, Requires), __LINE__)||static_cast< bool >(IsLessThanComparable< Value >::value)), int >::type = 0>
bool folly::operator<= ( const Expected< Value, Error > &  lhs,
const Expected< Value, Error > &  rhs 
)
inline

Definition at line 1340 of file Expected.h.

References FOLLY_REQUIRES_TRAILING, value, and testing::Value().

Referenced by testing::TEST().

1342  {
1343  return !(rhs < lhs);
1344 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class Value , class Error >
bool folly::operator<= ( const Expected< Value, Error > &  ,
const Value &  other 
)
delete
template<class Value , class Error >
bool folly::operator<= ( const Value &  other,
const Expected< Value, Error > &   
)
delete
template<typename E , class T , class A , class S >
bool folly::operator<= ( const basic_fbstring< E, T, A, S > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2676 of file FBString.h.

2678  {
2679  return !(rhs < lhs);
2680 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
bool folly::operator<= ( const basic_fbstring< E, T, A, S > &  lhs,
const typename basic_fbstring< E, T, A, S >::value_type *  rhs 
)
inline

Definition at line 2683 of file FBString.h.

2685  {
2686  return !(rhs < lhs);
2687 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
bool folly::operator<= ( const typename basic_fbstring< E, T, A, S >::value_type *  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2690 of file FBString.h.

2692  {
2693  return !(rhs < lhs);
2694 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S , class A2 >
bool folly::operator<= ( const basic_fbstring< E, T, A, S > &  lhs,
const std::basic_string< E, T, A2 > &  rhs 
)
inline

Definition at line 2876 of file FBString.h.

References folly::detail::rhs.

2878  {
2879  return !(lhs > rhs);
2880 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S , class A2 >
bool folly::operator<= ( const std::basic_string< E, T, A2 > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2890 of file FBString.h.

References folly::detail::rhs.

2892  {
2893  return !(lhs > rhs);
2894 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class Char , std::size_t A, std::size_t B>
constexpr bool folly::operator<= ( const BasicFixedString< Char, A > &  a,
const BasicFixedString< Char, B > &  b 
)
noexcept

Definition at line 2954 of file FixedString.h.

References a, and b.

2956  {
2957  return !(b < a);
2958 }
char b
char a
bool folly::operator== ( const HugePageSize a,
const HugePageSize b 
)
inline

Definition at line 50 of file HugePages.h.

References folly::HugePageSize::size.

50  {
51  return a.size == b.size;
52 }
char b
char a
template<class I1 , class I2 , std::enable_if_t< detail::Comparable< I1, I2 >::value, int > = 0>
bool folly::operator== ( Poly< I1 > const &  _this,
Poly< I2 > const &  that 
)

Definition at line 71 of file Regular.h.

References poly_empty(), and poly_type().

71  {
72  if (poly_empty(_this) != poly_empty(that)) {
73  return false;
74  } else if (poly_empty(_this)) {
75  return true;
76  } else if (poly_type(_this) != poly_type(that)) {
77  throw BadPolyCast();
78  }
79  return ::folly::poly_call<0, poly::IEqualityComparable>(_this, that);
80 }
std::type_info const & poly_type(detail::PolyRoot< I > const &that) noexcept
Definition: Poly.h:358
bool poly_empty(detail::PolyRoot< I > const &that) noexcept
Definition: Poly.h:383
bool folly::operator== ( const MoveTester o1,
const MoveTester o2 
)

Definition at line 153 of file ExpectedTest.cpp.

References folly::MoveTester::s_.

153  {
154  return o1.s_ == o2.s_;
155 }
template<typename Pointer >
constexpr bool folly::operator== ( propagate_const< Pointer > const &  a,
std::nullptr_t   
)

Definition at line 209 of file PropagateConst.h.

References get_underlying().

209  {
210  return get_underlying(a) == nullptr;
211 }
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
template<typename Pointer >
constexpr bool folly::operator== ( std::nullptr_t  ,
propagate_const< Pointer > const &  a 
)

Definition at line 214 of file PropagateConst.h.

References get_underlying().

214  {
215  return nullptr == get_underlying(a);
216 }
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
template<typename Pointer >
constexpr bool folly::operator== ( propagate_const< Pointer > const &  a,
propagate_const< Pointer > const &  b 
)

Definition at line 229 of file PropagateConst.h.

References get_underlying().

231  {
232  return get_underlying(a) == get_underlying(b);
233 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
bool folly::operator== ( const DelayedDestructionBase::DestructorGuard left,
const DelayedDestructionBase::DestructorGuard right 
)
inline

Definition at line 230 of file DelayedDestructionBase.h.

References folly::DelayedDestructionBase::DestructorGuard::get().

232  {
233  return left.get() == right.get();
234 }
bool folly::operator== ( const DelayedDestructionBase::DestructorGuard left,
std::nullptr_t   
)
inline

Definition at line 240 of file DelayedDestructionBase.h.

References folly::DelayedDestructionBase::DestructorGuard::get().

242  {
243  return left.get() == nullptr;
244 }
bool folly::operator== ( std::nullptr_t  ,
const DelayedDestructionBase::DestructorGuard right 
)
inline

Definition at line 245 of file DelayedDestructionBase.h.

References folly::DelayedDestructionBase::DestructorGuard::get().

247  {
248  return nullptr == right.get();
249 }
template<typename LeftAliasType , typename RightAliasType >
bool folly::operator== ( const DelayedDestructionBase::IntrusivePtr< LeftAliasType > &  left,
const DelayedDestructionBase::IntrusivePtr< RightAliasType > &  right 
)
inline

Definition at line 262 of file DelayedDestructionBase.h.

References folly::DelayedDestructionBase::IntrusivePtr< AliasType >::get().

264  {
265  return left.get() == right.get();
266 }
template<typename LeftAliasType >
bool folly::operator== ( const DelayedDestructionBase::IntrusivePtr< LeftAliasType > &  left,
std::nullptr_t   
)
inline

Definition at line 274 of file DelayedDestructionBase.h.

References folly::DelayedDestructionBase::IntrusivePtr< AliasType >::get().

276  {
277  return left.get() == nullptr;
278 }
template<typename Pointer , typename Other >
constexpr auto folly::operator== ( propagate_const< Pointer > const &  a,
Other const &  b 
) -> decltype(get_underlying(a) == b, false)

Definition at line 276 of file PropagateConst.h.

References a, b, and get_underlying().

277  {
278  return get_underlying(a) == b;
279 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
template<typename RightAliasType >
bool folly::operator== ( std::nullptr_t  ,
const DelayedDestructionBase::IntrusivePtr< RightAliasType > &  right 
)
inline

Definition at line 280 of file DelayedDestructionBase.h.

References folly::DelayedDestructionBase::IntrusivePtr< AliasType >::get().

282  {
283  return nullptr == right.get();
284 }
template<typename Other , typename Pointer >
constexpr auto folly::operator== ( Other const &  a,
propagate_const< Pointer > const &  b 
) -> decltype(a == get_underlying(b), false)

Definition at line 312 of file PropagateConst.h.

References b, and get_underlying().

313  {
314  return a == get_underlying(b);
315 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
bool folly::operator== ( const IPAddressV4 addr1,
const IPAddressV4 addr2 
)
inline

Return true if two addresses are equal.

Definition at line 317 of file IPAddressV4.h.

References folly::IPAddressV4::toLong().

317  {
318  return (addr1.toLong() == addr2.toLong());
319 }
bool folly::operator== ( const IPAddress &  addr1,
const IPAddress &  addr2 
)

Definition at line 375 of file IPAddress.cpp.

375  {
376  if (addr1.family() == addr2.family()) {
377  if (addr1.isV6()) {
378  return (addr1.asV6() == addr2.asV6());
379  } else if (addr1.isV4()) {
380  return (addr1.asV4() == addr2.asV4());
381  } else {
382  CHECK_EQ(addr1.family(), AF_UNSPEC);
383  // Two default initialized AF_UNSPEC addresses should be considered equal.
384  // AF_UNSPEC is the only other value for which an IPAddress can be
385  // created, in the default constructor case.
386  return true;
387  }
388  }
389  // addr1 is v4 mapped v6 address, addr2 is v4
390  if (addr1.isIPv4Mapped() && addr2.isV4()) {
391  if (IPAddress::createIPv4(addr1) == addr2.asV4()) {
392  return true;
393  }
394  }
395  // addr2 is v4 mapped v6 address, addr1 is v4
396  if (addr2.isIPv4Mapped() && addr1.isV4()) {
397  if (IPAddress::createIPv4(addr2) == addr1.asV4()) {
398  return true;
399  }
400  }
401  // we only compare IPv4 and IPv6 addresses
402  return false;
403 }
template<typename T , typename RefCount >
bool folly::operator== ( const ReadMostlyMainPtr< T, RefCount > &  ptr,
std::nullptr_t   
)
inline

Definition at line 397 of file ReadMostlySharedPtr.h.

References folly::ReadMostlyMainPtr< T, RefCount >::get().

399  {
400  return ptr.get() == nullptr;
401 }
void * ptr
template<typename T , typename RefCount >
bool folly::operator== ( std::nullptr_t  ,
const ReadMostlyMainPtr< T, RefCount > &  ptr 
)
inline

Definition at line 404 of file ReadMostlySharedPtr.h.

References folly::ReadMostlyMainPtr< T, RefCount >::get().

406  {
407  return ptr.get() == nullptr;
408 }
void * ptr
template<typename T , typename RefCount >
bool folly::operator== ( const ReadMostlySharedPtr< T, RefCount > &  ptr,
std::nullptr_t   
)
inline

Definition at line 411 of file ReadMostlySharedPtr.h.

References folly::ReadMostlySharedPtr< T, RefCount >::get().

413  {
414  return ptr.get() == nullptr;
415 }
void * ptr
template<typename T , typename RefCount >
bool folly::operator== ( std::nullptr_t  ,
const ReadMostlySharedPtr< T, RefCount > &  ptr 
)
inline

Definition at line 418 of file ReadMostlySharedPtr.h.

References folly::ReadMostlySharedPtr< T, RefCount >::get().

420  {
421  return ptr.get() == nullptr;
422 }
void * ptr
template<class U , class V >
constexpr bool folly::operator== ( const Optional< U > &  a,
const V &  b 
)

Definition at line 474 of file Optional.h.

References b, folly::Optional< Value >::hasValue(), and folly::Optional< Value >::value().

474  {
475  return a.hasValue() && a.value() == b;
476 }
char b
char a
template<class U , class V >
constexpr bool folly::operator== ( const U &  a,
const Optional< V > &  b 
)

Definition at line 484 of file Optional.h.

References a, folly::Optional< Value >::hasValue(), and folly::Optional< Value >::value().

484  {
485  return b.hasValue() && b.value() == a;
486 }
char b
char a
template<class U , class V >
FOLLY_CPP14_CONSTEXPR bool folly::operator== ( const Optional< U > &  a,
const Optional< V > &  b 
)

Definition at line 494 of file Optional.h.

References folly::Optional< Value >::hasValue(), and folly::Optional< Value >::value().

496  {
497  if (a.hasValue() != b.hasValue()) {
498  return false;
499  }
500  if (a.hasValue()) {
501  return a.value() == b.value();
502  }
503  return true;
504 }
char b
char a
template<class V >
constexpr bool folly::operator== ( const Optional< V > &  a,
None   
)
noexcept

Definition at line 559 of file Optional.h.

References folly::Optional< Value >::hasValue().

559  {
560  return !a.hasValue();
561 }
char a
template<class V >
constexpr bool folly::operator== ( None  ,
const Optional< V > &  a 
)
noexcept

Definition at line 563 of file Optional.h.

563  {
564  return !a.hasValue();
565 }
char a
template<class Error , bool FB_CONCATENATE = false, typename std::enable_if< (FB_CONCATENATE(FB_CONCATENATE(Folly, Requires), __LINE__)||static_cast< bool >(IsEqualityComparable< Error >::value)), int >::type = 0>
bool folly::operator== ( const Unexpected< Error > &  lhs,
const Unexpected< Error > &  rhs 
)
inline
template<typename FunctionType >
bool folly::operator== ( const Function< FunctionType > &  fn,
std::nullptr_t   
)

Definition at line 821 of file Function.h.

821  {
822  return !fn;
823 }
template<typename FunctionType >
bool folly::operator== ( std::nullptr_t  ,
const Function< FunctionType > &  fn 
)

Definition at line 826 of file Function.h.

826  {
827  return !fn;
828 }
template<class Iter >
bool folly::operator== ( const Range< Iter > &  lhs,
const Range< Iter > &  rhs 
)
inline

Templated comparison operators

Definition at line 1187 of file Range.h.

References folly::Range< Iter >::compare(), and folly::Range< Iter >::size().

1187  {
1188  return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
1189 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class T , class U >
_t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool> > folly::operator== ( const T lhs,
const U &  rhs 
)

operator== through conversion for Range<const char*>

Definition at line 1239 of file Range.h.

1239  {
1240  return StringPiece(lhs) == StringPiece(rhs);
1241 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
Range< const char * > StringPiece
bool folly::operator== ( MutableStringPiece  mp,
StringPiece  sp 
)

Definition at line 1245 of file RangeTest.cpp.

References folly::Range< Iter >::compare().

1245  {
1246  return mp.compare(sp) == 0;
1247 }
int compare(const const_range_type &o) const
Definition: Range.h:602
bool folly::operator== ( StringPiece  sp,
MutableStringPiece  mp 
)

Definition at line 1249 of file RangeTest.cpp.

References folly::Range< Iter >::compare().

1249  {
1250  return mp.compare(sp) == 0;
1251 }
int compare(const const_range_type &o) const
Definition: Range.h:602
template<class Value , class Error >
std::enable_if<IsEqualityComparable<Value>::value, bool>::type folly::operator== ( const Expected< Value, Error > &  lhs,
const Expected< Value, Error > &  rhs 
)
inline

Definition at line 1295 of file Expected.h.

References FOLLY_REQUIRES_TRAILING, folly::Expected< Value, Error >::hasError(), folly::expected_detail::ExpectedStorage< Value, Error >::uninitializedByException(), UNLIKELY, value, testing::Value(), folly::expected_detail::ExpectedStorage< Value, Error >::value_, and folly::expected_detail::ExpectedStorage< Value, Error >::which_.

1297  {
1298  if (UNLIKELY(lhs.uninitializedByException())) {
1299  throw_exception<BadExpectedAccess>();
1300  }
1301  if (UNLIKELY(lhs.which_ != rhs.which_)) {
1302  return false;
1303  }
1304  if (UNLIKELY(lhs.hasError())) {
1305  return true; // All error states are considered equal
1306  }
1307  return lhs.value_ == rhs.value_;
1308 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
#define UNLIKELY(x)
Definition: Likely.h:48
template<class Value , class Error >
bool folly::operator== ( const Expected< Value, Error > &  ,
const Value &  other 
)
delete
template<class Value , class Error >
bool folly::operator== ( const Value &  other,
const Expected< Value, Error > &   
)
delete
template<typename E , class T , class A , class S >
bool folly::operator== ( const basic_fbstring< E, T, A, S > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2592 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::compare(), and folly::basic_fbstring< E, T, A, Storage >::size().

2594  {
2595  return lhs.size() == rhs.size() && lhs.compare(rhs) == 0;
2596 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
bool folly::operator== ( const typename basic_fbstring< E, T, A, S >::value_type *  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2599 of file FBString.h.

2601  {
2602  return rhs == lhs;
2603 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
bool folly::operator== ( const basic_fbstring< E, T, A, S > &  lhs,
const typename basic_fbstring< E, T, A, S >::value_type *  rhs 
)
inline

Definition at line 2606 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::compare().

2608  {
2609  return lhs.compare(rhs) == 0;
2610 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S , class A2 >
bool folly::operator== ( const basic_fbstring< E, T, A, S > &  lhs,
const std::basic_string< E, T, A2 > &  rhs 
)
inline

Definition at line 2820 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::compare(), and folly::basic_fbstring< E, T, A, Storage >::size().

2822  {
2823  return lhs.compare(0, lhs.size(), rhs.data(), rhs.size()) == 0;
2824 }
template<typename E , class T , class A , class S , class A2 >
bool folly::operator== ( const std::basic_string< E, T, A2 > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2827 of file FBString.h.

2829  {
2830  return rhs == lhs;
2831 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class Char , std::size_t A, std::size_t B>
constexpr bool folly::operator== ( const BasicFixedString< Char, A > &  a,
const BasicFixedString< Char, B > &  b 
)
noexcept

Symmetric relational operators

Definition at line 2915 of file FixedString.h.

References a, b, folly::detail::fixedstring::Helper::data_(), and folly::detail::fixedstring::equal_().

2917  {
2920  a.size(),
2922  b.size());
2923 }
char b
constexpr bool equal_(const Left &left, std::size_t left_size, const Right &right, std::size_t right_size) noexcept
Definition: FixedString.h:135
char a
StringPiece data_
template<class I1 , class I2 , std::enable_if_t< detail::Orderable< I1, I2 >::value, int > = 0>
bool folly::operator> ( Poly< I1 > const &  _this,
Poly< I2 > const &  that 
)

Definition at line 109 of file Regular.h.

109  {
110  return that < _this;
111 }
template<typename Pointer >
constexpr bool folly::operator> ( propagate_const< Pointer > const &  a,
propagate_const< Pointer > const &  b 
)

Definition at line 257 of file PropagateConst.h.

References get_underlying().

259  {
260  return get_underlying(a) > get_underlying(b);
261 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
template<typename Pointer , typename Other >
constexpr auto folly::operator> ( propagate_const< Pointer > const &  a,
Other const &  b 
) -> decltype(get_underlying(a) > b, false)

Definition at line 300 of file PropagateConst.h.

References b, and get_underlying().

301  {
302  return get_underlying(a) > b;
303 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
bool folly::operator> ( const IPAddressV4 a,
const IPAddressV4 b 
)
inline

Definition at line 328 of file IPAddressV4.h.

References a.

328  {
329  return b < a;
330 }
char b
char a
template<typename Other , typename Pointer >
constexpr auto folly::operator> ( Other const &  a,
propagate_const< Pointer > const &  b 
) -> decltype(a > get_underlying(b), false)

Definition at line 336 of file PropagateConst.h.

References b, and get_underlying().

337  {
338  return a > get_underlying(b);
339 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
template<class U , class V >
constexpr bool folly::operator> ( const Optional< U > &  a,
const Optional< V > &  b 
)

Definition at line 525 of file Optional.h.

References a.

525  {
526  return b < a;
527 }
char b
char a
template<class V >
bool folly::operator> ( const Optional< V > &  ,
const V &  other 
)
delete
template<class V >
bool folly::operator> ( const V &  other,
const Optional< V > &   
)
delete
template<class V >
constexpr bool folly::operator> ( const Optional< V > &  a,
None   
)
noexcept

Definition at line 575 of file Optional.h.

References folly::Optional< Value >::hasValue().

575  {
576  return a.hasValue();
577 }
char a
template<class V >
constexpr bool folly::operator> ( None  ,
const Optional< V > &   
)
noexcept

Definition at line 579 of file Optional.h.

579  {
580  return false;
581 }
template<class Iter >
bool folly::operator> ( const Range< Iter > &  lhs,
const Range< Iter > &  rhs 
)
inline

Definition at line 1207 of file Range.h.

References folly::Range< Iter >::compare().

1207  {
1208  return lhs.compare(rhs) > 0;
1209 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class T , class U >
_t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool> > folly::operator> ( const T lhs,
const U &  rhs 
)

operator> through conversion for Range<const char*>

Definition at line 1266 of file Range.h.

1266  {
1267  return StringPiece(lhs) > StringPiece(rhs);
1268 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
Range< const char * > StringPiece
template<class Value , class Error , bool FB_CONCATENATE = false, typename std::enable_if< (FB_CONCATENATE(FB_CONCATENATE(Folly, Requires), __LINE__)||static_cast< bool >(IsLessThanComparable< Value >::value)), int >::type = 0>
bool folly::operator> ( const Expected< Value, Error > &  lhs,
const Expected< Value, Error > &  rhs 
)
inline
template<class Value , class Error >
bool folly::operator> ( const Expected< Value, Error > &  ,
const Value &  other 
)
delete
template<class Value , class Error >
bool folly::operator> ( const Value &  other,
const Expected< Value, Error > &   
)
delete
template<typename E , class T , class A , class S >
bool folly::operator> ( const basic_fbstring< E, T, A, S > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2655 of file FBString.h.

2657  {
2658  return rhs < lhs;
2659 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
bool folly::operator> ( const basic_fbstring< E, T, A, S > &  lhs,
const typename basic_fbstring< E, T, A, S >::value_type *  rhs 
)
inline

Definition at line 2662 of file FBString.h.

2664  {
2665  return rhs < lhs;
2666 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
bool folly::operator> ( const typename basic_fbstring< E, T, A, S >::value_type *  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2669 of file FBString.h.

2671  {
2672  return rhs < lhs;
2673 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S , class A2 >
bool folly::operator> ( const basic_fbstring< E, T, A, S > &  lhs,
const std::basic_string< E, T, A2 > &  rhs 
)
inline

Definition at line 2855 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::compare(), and folly::basic_fbstring< E, T, A, Storage >::size().

2857  {
2858  return lhs.compare(0, lhs.size(), rhs.data(), rhs.size()) > 0;
2859 }
template<typename E , class T , class A , class S , class A2 >
bool folly::operator> ( const std::basic_string< E, T, A2 > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2869 of file FBString.h.

2871  {
2872  return rhs < lhs;
2873 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class Char , std::size_t A, std::size_t B>
constexpr bool folly::operator> ( const BasicFixedString< Char, A > &  a,
const BasicFixedString< Char, B > &  b 
)
noexcept

Definition at line 2947 of file FixedString.h.

References a, and b.

2949  {
2950  return b < a;
2951 }
char b
char a
template<class I1 , class I2 , std::enable_if_t< detail::Orderable< I1, I2 >::value, int > = 0>
bool folly::operator>= ( Poly< I1 > const &  _this,
Poly< I2 > const &  that 
)

Definition at line 125 of file Regular.h.

125  {
126  return !(_this < that);
127 }
template<typename Pointer >
constexpr bool folly::operator>= ( propagate_const< Pointer > const &  a,
propagate_const< Pointer > const &  b 
)

Definition at line 264 of file PropagateConst.h.

References get_underlying().

266  {
267  return get_underlying(a) >= get_underlying(b);
268 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
template<typename Pointer , typename Other >
constexpr auto folly::operator>= ( propagate_const< Pointer > const &  a,
Other const &  b 
) -> decltype(get_underlying(a) >= b, false)

Definition at line 306 of file PropagateConst.h.

References b, and get_underlying().

307  {
308  return get_underlying(a) >= b;
309 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
bool folly::operator>= ( const IPAddressV4 a,
const IPAddressV4 b 
)
inline

Definition at line 334 of file IPAddressV4.h.

References b.

334  {
335  return !(a < b);
336 }
char b
char a
template<typename Other , typename Pointer >
constexpr auto folly::operator>= ( Other const &  a,
propagate_const< Pointer > const &  b 
) -> decltype(a >= get_underlying(b), false)

Definition at line 342 of file PropagateConst.h.

References b, and get_underlying().

343  {
344  return a >= get_underlying(b);
345 }
char b
char a
constexpr Pointer const & get_underlying(propagate_const< Pointer > const &obj)
template<class U , class V >
constexpr bool folly::operator>= ( const Optional< U > &  a,
const Optional< V > &  b 
)

Definition at line 535 of file Optional.h.

References b, operator>(), and operator>=().

535  {
536  return !(a < b);
537 }
char b
char a
template<class V >
bool folly::operator>= ( const Optional< V > &  ,
const V &  other 
)
delete
template<class V >
bool folly::operator>= ( const V &  other,
const Optional< V > &   
)
delete
template<class V >
constexpr bool folly::operator>= ( const Optional< V > &  ,
None   
)
noexcept

Definition at line 591 of file Optional.h.

591  {
592  return true;
593 }
template<class V >
constexpr bool folly::operator>= ( None  ,
const Optional< V > &  a 
)
noexcept

Definition at line 595 of file Optional.h.

References FOLLY_NAMESPACE_STD_BEGIN.

595  {
596  return !a.hasValue();
597 }
char a
template<class Iter >
bool folly::operator>= ( const Range< Iter > &  lhs,
const Range< Iter > &  rhs 
)
inline

Definition at line 1212 of file Range.h.

References folly::Range< Iter >::compare().

1212  {
1213  return lhs.compare(rhs) >= 0;
1214 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class T , class U >
_t<std::enable_if<detail::ComparableAsStringPiece<T, U>::value, bool> > folly::operator>= ( const T lhs,
const U &  rhs 
)

operator> through conversion for Range<const char*>

Definition at line 1284 of file Range.h.

1284  {
1285  return StringPiece(lhs) >= StringPiece(rhs);
1286 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
Range< const char * > StringPiece
template<class Value , class Error , bool FB_CONCATENATE = false, typename std::enable_if< (FB_CONCATENATE(FB_CONCATENATE(Folly, Requires), __LINE__)||static_cast< bool >(IsLessThanComparable< Value >::value)), int >::type = 0>
bool folly::operator>= ( const Expected< Value, Error > &  lhs,
const Expected< Value, Error > &  rhs 
)
inline

Definition at line 1358 of file Expected.h.

References folly::detail::rhs.

Referenced by makeExpected(), operator>=(), and testing::TEST().

1360  {
1361  return !(lhs < rhs);
1362 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class Value , class Error >
bool folly::operator>= ( const Expected< Value, Error > &  ,
const Value &  other 
)
delete
template<class Value , class Error >
bool folly::operator>= ( const Value &  other,
const Expected< Value, Error > &   
)
delete
template<typename E , class T , class A , class S >
bool folly::operator>= ( const basic_fbstring< E, T, A, S > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2697 of file FBString.h.

References folly::detail::rhs.

2699  {
2700  return !(lhs < rhs);
2701 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
bool folly::operator>= ( const basic_fbstring< E, T, A, S > &  lhs,
const typename basic_fbstring< E, T, A, S >::value_type *  rhs 
)
inline

Definition at line 2704 of file FBString.h.

References folly::detail::rhs.

2706  {
2707  return !(lhs < rhs);
2708 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
bool folly::operator>= ( const typename basic_fbstring< E, T, A, S >::value_type *  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2711 of file FBString.h.

References folly::detail::rhs.

2713  {
2714  return !(lhs < rhs);
2715 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S , class A2 >
bool folly::operator>= ( const basic_fbstring< E, T, A, S > &  lhs,
const std::basic_string< E, T, A2 > &  rhs 
)
inline

Definition at line 2883 of file FBString.h.

References folly::detail::rhs.

2885  {
2886  return !(lhs < rhs);
2887 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S , class A2 >
bool folly::operator>= ( const std::basic_string< E, T, A2 > &  lhs,
const basic_fbstring< E, T, A, S > &  rhs 
)
inline

Definition at line 2897 of file FBString.h.

References folly::detail::rhs.

2899  {
2900  return !(lhs < rhs);
2901 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class Char , std::size_t A, std::size_t B>
constexpr bool folly::operator>= ( const BasicFixedString< Char, A > &  a,
const BasicFixedString< Char, B > &  b 
)
noexcept

Definition at line 2961 of file FixedString.h.

References a, and b.

2963  {
2964  return !(a < b);
2965 }
char b
char a
template<typename E , class T , class A , class S >
std::basic_istream< typename basic_fbstring<E, T, A, S>::value_type, typename basic_fbstring<E, T, A, S>::traits_type>& folly::operator>> ( std::basic_istream< typename basic_fbstring< E, T, A, S >::value_type, typename basic_fbstring< E, T, A, S >::traits_type > &  is,
basic_fbstring< E, T, A, S > &  str 
)
inline

Definition at line 2728 of file FBString.h.

References folly::basic_fbstring< E, T, A, Storage >::erase(), folly::basic_fbstring< E, T, A, Storage >::max_size(), and folly::basic_fbstring< E, T, A, Storage >::push_back().

2732  {
2733  typedef std::basic_istream<
2734  typename basic_fbstring<E, T, A, S>::value_type,
2735  typename basic_fbstring<E, T, A, S>::traits_type>
2736  _istream_type;
2737  typename _istream_type::sentry sentry(is);
2738  size_t extracted = 0;
2739  auto err = _istream_type::goodbit;
2740  if (sentry) {
2741  auto n = is.width();
2742  if (n <= 0) {
2743  n = str.max_size();
2744  }
2745  str.erase();
2746  for (auto got = is.rdbuf()->sgetc(); extracted != size_t(n); ++extracted) {
2747  if (got == T::eof()) {
2748  err |= _istream_type::eofbit;
2749  is.width(0);
2750  break;
2751  }
2752  if (isspace(got)) {
2753  break;
2754  }
2755  str.push_back(got);
2756  got = is.rdbuf()->snextc();
2757  }
2758  }
2759  if (!extracted) {
2760  err |= _istream_type::failbit;
2761  }
2762  if (err) {
2763  is.setstate(err);
2764  }
2765  return is;
2766 }
WriteFlags folly::operator| ( WriteFlags  a,
WriteFlags  b 
)
inline

Definition at line 73 of file AsyncTransport.h.

References a, and uint32_t.

73  {
74  return static_cast<WriteFlags>(
75  static_cast<uint32_t>(a) | static_cast<uint32_t>(b));
76 }
char b
char a
WriteFlags& folly::operator|= ( WriteFlags a,
WriteFlags  b 
)
inline

Definition at line 81 of file AsyncTransport.h.

References a, and b.

81  {
82  a = a | b;
83  return a;
84 }
char b
char a
WriteFlags folly::operator~ ( WriteFlags  a)
inline

Definition at line 105 of file AsyncTransport.h.

References a, and uint32_t.

105  {
106  return static_cast<WriteFlags>(~static_cast<uint32_t>(a));
107 }
char a
template<typename... Cases>
decltype(auto) folly::overload ( Cases &&...  cases)

Definition at line 62 of file Overload.h.

Referenced by folly::test::TEST(), TEST(), and variant_match().

62  {
64  std::forward<Cases>(cases)...};
65 }
PskType type
dynamic folly::parseJson ( StringPiece  range)

Definition at line 900 of file json.cpp.

Referenced by BENCHMARK(), compareJson(), compareJsonWithTolerance(), proxygen::HTTPArchive::fromFile(), proxygen::HTTPArchive::fromPublicFile(), wangle::FilePersistenceLayer< K, V >::load(), main(), parseLogConfigJson(), wangle::TLSCredProcessor::processTLSTickets(), resultsFromFile(), TEST(), and TEST_F().

900  {
901  return parseJson(range, json::serialization_opts());
902 }
dynamic parseJson(StringPiece range, json::serialization_opts const &opts)
Definition: json.cpp:904
Gen range(Value begin, Value end)
Definition: Base.h:467
dynamic folly::parseJson ( StringPiece  range,
json::serialization_opts const &  opts 
)

Definition at line 904 of file json.cpp.

904  {
905  json::Input in(range, &opts);
906 
907  auto ret = parseValue(in);
908  in.skipWhitespace();
909  if (in.size() && *in != '\0') {
910  in.error("parsing didn't consume all input");
911  }
912  return ret;
913 }
Gen range(Value begin, Value end)
Definition: Base.h:467
static size_t folly::parseLeadingNumber ( const std::string line)
static

Returns the first decimal number in the string, or throws an exception if the string does not start with a number terminated by ',', '-', '
', or eos.

Definition at line 85 of file CacheLocality.cpp.

References folly::test::end(), i, min, folly::gen::move, folly::CacheLocality::numCachesByLevel, folly::detail::rhs, sformat(), string, and val.

85  {
86  auto raw = line.c_str();
87  char* end;
88  unsigned long val = strtoul(raw, &end, 10);
89  if (end == raw || (*end != ',' && *end != '-' && *end != '\n' && *end != 0)) {
90  throw std::runtime_error(
91  to<std::string>("error parsing list '", line, "'").c_str());
92  }
93  return val;
94 }
double val
Definition: String.cpp:273
auto end(TestAdlIterable &instance)
Definition: ForeachTest.cpp:62
LogConfig folly::parseLogConfig ( StringPiece  value)

Parse a log configuration string.

See the documentation in logging/docs/Config.md for a description of the configuration string syntax.

Throws a LogConfigParseError on error.

Definition at line 446 of file LogConfigParser.cpp.

References FOLLY_SAFE_DCHECK, folly::gen::move, parseLogConfigJson(), split(), folly::Range< Iter >::startsWith(), and trimWhitespace().

Referenced by initLogging(), and TEST().

446  {
448  if (value.startsWith('{')) {
449  return parseLogConfigJson(value);
450  }
451 
452  // Split the input string on semicolons.
453  // Everything up to the first semicolon specifies log category configs.
454  // From then on each section specifies a single LogHandler config.
455  std::vector<StringPiece> pieces;
456  folly::split(";", value, pieces);
458  pieces.size() >= 1, "folly::split() always returns a list of length 1");
459 
460  auto categoryConfigs = parseCategoryConfigs(pieces[0]);
461  LogConfig::HandlerConfigMap handlerConfigs;
462  for (size_t n = 1; n < pieces.size(); ++n) {
463  auto handlerInfo = parseHandlerConfig(pieces[n]);
464  auto ret = handlerConfigs.emplace(
465  handlerInfo.first, std::move(handlerInfo.second));
466  if (!ret.second) {
467  throw LogConfigParseError{to<string>(
468  "configuration for log category \"",
469  handlerInfo.first,
470  "\" specified multiple times")};
471  }
472  }
473 
474  return LogConfig{std::move(handlerConfigs), std::move(categoryConfigs)};
475 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void split(const Delim &delimiter, const String &input, std::vector< OutputType > &out, bool ignoreEmpty)
Definition: String-inl.h:382
static const char *const value
Definition: Conv.cpp:50
StringPiece trimWhitespace(StringPiece sp)
Definition: String.h:568
LogConfig parseLogConfigJson(StringPiece value)
#define FOLLY_SAFE_DCHECK(expr, msg)
Definition: SafeAssert.h:42
LogConfig folly::parseLogConfigDynamic ( const dynamic value)

Parse a folly::dynamic object.

The input should be an object data type, and is parsed the same as a JSON object accpted by parseLogConfigJson().

Definition at line 484 of file LogConfigParser.cpp.

References folly::LogName::canonicalize(), folly::dynamic::get_ptr(), folly::dynamic::isObject(), and folly::gen::move.

Referenced by parseLogConfigJson().

484  {
485  if (!value.isObject()) {
486  throw LogConfigParseError{"JSON config input must be an object"};
487  }
488 
489  std::unordered_map<string, string> seenCategories;
490  LogConfig::CategoryConfigMap categoryConfigs;
491  auto* categories = value.get_ptr("categories");
492  if (categories) {
493  if (!categories->isObject()) {
494  throw LogConfigParseError{to<string>(
495  "unexpected data type for log categories config: got ",
496  dynamicTypename(*categories),
497  ", expected an object")};
498  }
499 
500  for (const auto& entry : categories->items()) {
501  if (!entry.first.isString()) {
502  // This shouldn't really ever happen.
503  // We deserialize the json with allow_non_string_keys set to False.
504  throw LogConfigParseError{"category name must be a string"};
505  }
506  auto categoryName = entry.first.asString();
507  auto categoryConfig = parseJsonCategoryConfig(entry.second, categoryName);
508 
509  // Check for multiple entries for the same category with different but
510  // equivalent names.
511  auto canonicalName = LogName::canonicalize(categoryName);
512  auto ret = seenCategories.emplace(canonicalName, categoryName);
513  if (!ret.second) {
514  throw LogConfigParseError{to<string>(
515  "category \"",
516  canonicalName,
517  "\" listed multiple times under different names: \"",
518  ret.first->second,
519  "\" and \"",
520  categoryName,
521  "\"")};
522  }
523 
524  categoryConfigs[canonicalName] = std::move(categoryConfig);
525  }
526  }
527 
528  LogConfig::HandlerConfigMap handlerConfigs;
529  auto* handlers = value.get_ptr("handlers");
530  if (handlers) {
531  if (!handlers->isObject()) {
532  throw LogConfigParseError{to<string>(
533  "unexpected data type for log handlers config: got ",
534  dynamicTypename(*handlers),
535  ", expected an object")};
536  }
537 
538  for (const auto& entry : handlers->items()) {
539  if (!entry.first.isString()) {
540  // This shouldn't really ever happen.
541  // We deserialize the json with allow_non_string_keys set to False.
542  throw LogConfigParseError{"handler name must be a string"};
543  }
544  auto handlerName = entry.first.asString();
545  handlerConfigs.emplace(
546  handlerName, parseJsonHandlerConfig(entry.second, handlerName));
547  }
548  }
549 
550  return LogConfig{std::move(handlerConfigs), std::move(categoryConfigs)};
551 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
static const char *const value
Definition: Conv.cpp:50
LogConfig folly::parseLogConfigJson ( StringPiece  value)

Parse a JSON configuration string.

See the documentation in logging/docs/Config.md for a description of the JSON configuration object format.

This function uses relaxed JSON parsing, allowing C and C++ style comments, as well as trailing commas.

Definition at line 477 of file LogConfigParser.cpp.

References folly::json::serialization_opts::allow_trailing_comma, parseJson(), parseLogConfigDynamic(), and folly::json::stripComments().

Referenced by parseLogConfig(), and TEST().

477  {
478  json::serialization_opts opts;
479  opts.allow_trailing_comma = true;
480  auto jsonData = folly::parseJson(json::stripComments(value), opts);
481  return parseLogConfigDynamic(jsonData);
482 }
dynamic parseJson(StringPiece range)
Definition: json.cpp:900
std::string stripComments(StringPiece jsonC)
Definition: json.cpp:837
LogConfig parseLogConfigDynamic(const dynamic &value)
static const char *const value
Definition: Conv.cpp:50
NestedCommandLineParseResult folly::parseNestedCommandLine ( int  argc,
const char *const  argv[],
const boost::program_options::options_description &  desc 
)
NestedCommandLineParseResult folly::parseNestedCommandLine ( const std::vector< std::string > &  cmdline,
const boost::program_options::options_description &  desc 
)
NestedCommandLineParseResult folly::parseNestedCommandLine ( int  argc,
const char *const  argv[],
const po::options_description &  desc 
)

Definition at line 342 of file ProgramOptions.cpp.

Referenced by folly::NestedCommandLineApp::doRun(), and main().

345  {
346  return doParseNestedCommandLine(po::command_line_parser(argc, argv), desc);
347 }
char ** argv
NestedCommandLineParseResult folly::parseNestedCommandLine ( const std::vector< std::string > &  cmdline,
const po::options_description &  desc 
)

Definition at line 349 of file ProgramOptions.cpp.

351  {
352  return doParseNestedCommandLine(po::command_line_parser(cmdline), desc);
353 }
template<typename Tgt >
FOLLY_NODISCARD std::enable_if< std::is_arithmetic<Tgt>::value, Expected<StringPiece, ConversionCode> >::type folly::parseTo ( StringPiece  src,
Tgt &  out 
)
inline

Parsing strings to numeric types.

Definition at line 1182 of file Conv.h.

References type, and value.

Referenced by parseTo(), folly::detail::parseToWrap(), to(), and tryTo().

1182  {
1183  return detail::convertTo<Tgt>(&src).then(
1184  [&](Tgt res) { return void(out = res), src; });
1185 }
template<class T >
FOLLY_NODISCARD std::enable_if< std::is_enum<T>::value, Expected<StringPiece, ConversionCode> >::type folly::parseTo ( StringPiece  in,
T out 
)
noexcept

Definition at line 1386 of file Conv.h.

References FOLLY_NODISCARD, parseTo(), T, and type.

1386  {
1387  typename std::underlying_type<T>::type tmp{};
1388  auto restOrError = parseTo(in, tmp);
1389  out = static_cast<T>(tmp); // Harmless if parseTo fails
1390  return restOrError;
1391 }
PskType type
folly::std T
FOLLY_NODISCARD Expected< StringPiece, ConversionCode > parseTo(StringPiece in, fbstring &out)
Definition: Conv.h:1411
FOLLY_NODISCARD Expected<StringPiece, ConversionCode> folly::parseTo ( StringPiece  in,
StringPiece out 
)
inlinenoexcept

Definition at line 1394 of file Conv.h.

References folly::Range< Iter >::end(), and FOLLY_NODISCARD.

1396  {
1397  out = in;
1398  return StringPiece{in.end(), in.end()};
1399 }
constexpr Iter end() const
Definition: Range.h:455
Range< const char * > StringPiece
FOLLY_NODISCARD Expected<StringPiece, ConversionCode> folly::parseTo ( StringPiece  in,
std::string out 
)
inline

Definition at line 1402 of file Conv.h.

References folly::Range< Iter >::data(), folly::Range< Iter >::end(), FOLLY_NODISCARD, and folly::Range< Iter >::size().

1404  {
1405  out.clear();
1406  out.append(in.data(), in.size()); // TODO try/catch?
1407  return StringPiece{in.end(), in.end()};
1408 }
constexpr Iter end() const
Definition: Range.h:455
Range< const char * > StringPiece
FOLLY_NODISCARD Expected<StringPiece, ConversionCode> folly::parseTo ( StringPiece  in,
fbstring out 
)
inline

Definition at line 1411 of file Conv.h.

References folly::basic_fbstring< E, T, A, Storage >::append(), folly::basic_fbstring< E, T, A, Storage >::clear(), folly::Range< Iter >::data(), folly::Range< Iter >::end(), and folly::Range< Iter >::size().

1413  {
1414  out.clear();
1415  out.append(in.data(), in.size()); // TODO try/catch?
1416  return StringPiece{in.end(), in.end()};
1417 }
constexpr Iter end() const
Definition: Range.h:455
Range< const char * > StringPiece
template<typename F , typename... Args>
auto folly::partial ( F &&  f,
Args &&...  args 
) -> detail::partial::Partial< typename std::decay<F>::type, std::tuple<typename std::decay<Args>::type...>>

Partially applies arguments to a callable

partial takes a callable and zero or more additional arguments and returns a callable object, which when called with zero or more arguments, will invoke the original callable with the additional arguments passed to partial, followed by those passed to the call.

E.g. partial(Foo, 1, 2)(3) is equivalent to Foo(1, 2, 3).

partial can be used to bind a class method to an instance: partial(&Foo::method, foo_pointer) returns a callable object that can be invoked in the same way as foo_pointer->method. In case the first argument in a call to partial is a member pointer, the second argument can be a reference, pointer or any object that can be dereferenced to an object of type Foo (like std::shared_ptr or std::unique_ptr).

partial is similar to std::bind, but you don't have to use placeholders to have arguments passed on. Any number of arguments passed to the object returned by partial when called will be added to those passed to partial and passed to the original callable.

Definition at line 119 of file Partial.h.

References f.

Referenced by proxygen::QPACKDecoder::decodeLiteralHeaderQ(), folly::f14::operator<<(), TEST(), and TEST_P().

121  {
122  return {detail::partial::PartialConstructFromCallable{},
123  std::forward<F>(f),
124  std::forward<Args>(args)...};
125 }
auto f
template<class T >
T folly::partialLoadUnaligned ( const void *  p,
size_t  l 
)
inline

Read l bytes into the low bits of a value of an unsigned integral type T, where l < sizeof(T).

This is intended as a complement to loadUnaligned to read the tail of a buffer when it is processed one word at a time.

Definition at line 318 of file Bits.h.

References assume(), kHasUnalignedAccess, kIsLittleEndian, T, value, and value().

318  {
319  static_assert(
321  sizeof(T) <= 8,
322  "Invalid type");
323  assume(l < sizeof(T));
324 
325  auto cp = static_cast<const char*>(p);
326  T value = 0;
328  // Unsupported, use memcpy.
329  memcpy(&value, cp, l);
330  return value;
331  }
332 
333  auto avail = l;
334  if (l & 4) {
335  avail -= 4;
336  value = static_cast<T>(loadUnaligned<uint32_t>(cp + avail)) << (avail * 8);
337  }
338  if (l & 2) {
339  avail -= 2;
340  value |= static_cast<T>(loadUnaligned<uint16_t>(cp + avail)) << (avail * 8);
341  }
342  if (l & 1) {
343  value |= loadUnaligned<uint8_t>(cp);
344  }
345  return value;
346 }
constexpr bool kHasUnalignedAccess
Definition: Portability.h:29
#define T(v)
Definition: http_parser.c:233
constexpr auto kIsLittleEndian
Definition: Portability.h:278
static const char *const value
Definition: Conv.cpp:50
FOLLY_ALWAYS_INLINE void assume(bool cond)
Definition: Assume.h:41
template<std::size_t N, typename This , typename... As>
auto folly::poly_call ( This &&  _this,
As &&...  as 
) -> decltype(detail::PolyAccess::call<N>( static_cast<This&&>(_this), static_cast<As&&>(as)...))

Call the N-th member of the currently-being-defined interface. When the first parameter is an object of type PolySelf<Base> (as opposed to *this) you must explicitly specify which interface through which to dispatch. For instance:

struct IAddable {
  template <class Base>
  struct Interface : Base {
    friend PolySelf<Base, Decay>
    operator+(PolySelf<Base> const& a, PolySelf<Base> const& b) {
      return folly::poly_call<0, IAddable>(a, b);
    }
  };
  template <class T>
  static auto plus_(T const& a, T const& b) -> decltype(a + b) {
    return a + b;
  }
  template <class T>
  using Members = FOLLY_POLY_MEMBERS(&plus_<std::decay_t<T>>);
};
See also
PolySelf

Definition at line 236 of file Poly.h.

References folly::gen::as().

Referenced by poly_call().

239  {
240  return detail::PolyAccess::call<N>(
241  static_cast<This&&>(_this), static_cast<As&&>(as)...);
242 }
template<std::size_t N, class I , class Tail , typename... As>
decltype(auto) folly::poly_call ( detail::PolyNode< I, Tail > &&  _this,
As &&...  as 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 246 of file Poly.h.

246  {
247  using This = detail::InterfaceOf<I, detail::PolyNode<I, Tail>>;
248  return detail::PolyAccess::call<N>(
249  static_cast<This&&>(_this), static_cast<As&&>(as)...);
250 }
Collect as()
Definition: Base.h:811
template<std::size_t N, class I , class Tail , typename... As>
decltype(auto) folly::poly_call ( detail::PolyNode< I, Tail > &  _this,
As &&...  as 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 254 of file Poly.h.

254  {
255  using This = detail::InterfaceOf<I, detail::PolyNode<I, Tail>>;
256  return detail::PolyAccess::call<N>(
257  static_cast<This&>(_this), static_cast<As&&>(as)...);
258 }
Collect as()
Definition: Base.h:811
template<std::size_t N, class I , class Tail , typename... As>
decltype(auto) folly::poly_call ( detail::PolyNode< I, Tail > const &  _this,
As &&...  as 
)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 262 of file Poly.h.

References upload::const, and value.

262  {
263  using This = detail::InterfaceOf<I, detail::PolyNode<I, Tail>>;
264  return detail::PolyAccess::call<N>(
265  static_cast<This const&>(_this), static_cast<As&&>(as)...);
266 }
const
Definition: upload.py:398
Collect as()
Definition: Base.h:811
template<std::size_t N, class I , class Poly , typename... As, std::enable_if_t< detail::IsPoly< Poly >::value, int > = 0>
auto folly::poly_call ( Poly &&  _this,
As &&...  as 
) -> decltype(poly_call<N, I>( static_cast<Poly&&>(_this).get(), static_cast<As&&>(as)...))

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 275 of file Poly.h.

References folly::gen::as(), assume_unreachable(), and poly_call().

277  {
278  return poly_call<N, I>(
279  static_cast<Poly&&>(_this).get(), static_cast<As&&>(as)...);
280 }
Collect as()
Definition: Base.h:811
template<class T , class I >
detail::AddCvrefOf< T, I > & folly::poly_cast ( detail::PolyRoot< I > &  that)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 310 of file Poly.h.

Referenced by poly_cast().

310  {
311  return detail::PolyAccess::cast<T>(that);
312 }
template<class T , class I >
detail::AddCvrefOf< T, I > const & folly::poly_cast ( detail::PolyRoot< I > const &  that)

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 316 of file Poly.h.

References assume_unreachable(), poly_cast(), and T.

316  {
317  return detail::PolyAccess::cast<T>(that);
318 }
template<class T , class I >
detail::AddCvrefOf<T, I>&& folly::poly_cast ( detail::PolyRoot< I > &&  that)

Try to cast the Poly object to the requested type. If the Poly stores an object of that type, return a reference to the object; otherwise, throw an exception.

Template Parameters
TThe (unqualified) type to which to cast the Poly object.
PolyThe type of the Poly object.
Parameters
thatThe Poly object to be cast.
Returns
A reference to the T object stored in or refered to by that.
Exceptions
BadPolyAccessif that is empty.
BadPolyCastif that does not store or refer to an object of type T.

Definition at line 304 of file Poly.h.

References folly::gen::move.

304  {
305  return detail::PolyAccess::cast<T>(std::move(that));
306 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<class T , class Poly , std::enable_if_t< detail::IsPoly< Poly >::value, int > = 0>
constexpr auto folly::poly_cast ( Poly &&  that) -> decltype(poly_cast<T>(std::declval<Poly>().get()))

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 346 of file Poly.h.

References poly_cast(), and T.

347  {
348  return poly_cast<T>(static_cast<Poly&&>(that).get());
349 }
#define T(v)
Definition: http_parser.c:233
constexpr auto poly_cast(Poly &&that) -> decltype(poly_cast< T >(std::declval< Poly >().get()))
Definition: Poly.h:346
template<class I >
bool folly::poly_empty ( detail::PolyRoot< I > const &  that)
noexcept

Returns true if that is not currently storing an object; false, otherwise.

Definition at line 383 of file Poly.h.

Referenced by folly::poly::IBooleanTestable::Interface< Base >::operator!(), operator<(), operator==(), poly_empty(), and TEST().

383  {
384  return detail::State::eEmpty == detail::PolyAccess::vtable(that)->state_;
385 }
template<class I >
constexpr bool folly::poly_empty ( detail::PolyRoot< I && > const &  )
noexcept

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 389 of file Poly.h.

389  {
390  return false;
391 }
template<class I >
constexpr bool folly::poly_empty ( detail::PolyRoot< I & > const &  )
noexcept

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 395 of file Poly.h.

395  {
396  return false;
397 }
template<class I >
constexpr bool folly::poly_empty ( Poly< I && > const &  )
noexcept

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 401 of file Poly.h.

401  {
402  return false;
403 }
template<class I >
constexpr bool folly::poly_empty ( Poly< I & > const &  )
noexcept

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 407 of file Poly.h.

References assume_unreachable(), folly::pushmi::__adl::noexcept(), poly_empty(), and value().

407  {
408  return false;
409 }
template<class I , std::enable_if_t< detail::Not< std::is_reference< I >>::value, int > = 0>
constexpr Poly<I>&& folly::poly_move ( detail::PolyRoot< I > &  that)
noexcept

Given a Poly<I&>, return a Poly<I&&>. Otherwise, when I is not a reference type, returns a Poly<I>&& when given a Poly<I>&, like std::move.

Definition at line 426 of file Poly.h.

References value().

Referenced by poly_move(), and TEST().

426  {
427  return static_cast<Poly<I>&&>(static_cast<Poly<I>&>(that));
428 }
template<class I , std::enable_if_t< detail::Not< std::is_const< I >>::value, int > = 0>
Poly<I&&> folly::poly_move ( detail::PolyRoot< I & > const &  that)
noexcept

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 434 of file Poly.h.

References folly::gen::move.

434  {
435  return detail::PolyAccess::move(that);
436 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<class I >
Poly<I const&> folly::poly_move ( detail::PolyRoot< I const & > const &  that)
noexcept

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 440 of file Poly.h.

References assume_unreachable(), folly::gen::move, folly::pushmi::__adl::noexcept(), poly_move(), and value.

440  {
441  return detail::PolyAccess::move(that);
442 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<class Poly , std::enable_if_t< detail::IsPoly< Poly >::value, int > = 0>
constexpr auto folly::poly_move ( Poly that) -> decltype(poly_move(that.get()))
noexcept

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 454 of file Poly.h.

References data, folly::pushmi::__adl::noexcept(), poly_move(), swap(), folly::pushmi::detail::t, T, and value.

455  {
456  return poly_move(that.get());
457 }
constexpr auto poly_move(Poly &that) noexcept-> decltype(poly_move(that.get()))
Definition: Poly.h:454
template<class I >
std::type_info const& folly::poly_type ( detail::PolyRoot< I > const &  that)
noexcept

Returns a reference to the std::type_info object corresponding to the object currently stored in that. If that is empty, returns typeid(void).

Definition at line 358 of file Poly.h.

References assume_unreachable(), folly::pushmi::__adl::noexcept(), type, and value.

Referenced by operator<(), operator==(), poly_type(), and TEST().

358  {
359  return detail::PolyAccess::type(that);
360 }
PskType type
template<class Poly , std::enable_if_t< detail::IsPoly< Poly >::value, int > = 0>
constexpr auto folly::poly_type ( Poly const &  that) -> decltype(poly_type(that.get()))
noexcept

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 372 of file Poly.h.

References poly_type().

373  {
374  return poly_type(that.get());
375 }
constexpr auto poly_type(Poly const &that) noexcept-> decltype(poly_type(that.get()))
Definition: Poly.h:372
template<typename T >
constexpr unsigned int folly::popcount ( T const  v)
inline

popcount

Returns the number of bits which are set.

Definition at line 130 of file Bits.h.

References folly::detail::bits_to_unsigned(), T, and value.

Referenced by folly::detail::ConcurrentHashMapSegment< KeyType, ValueType, ShardBits, HashFn, KeyEqual, Allocator, Atom, Mutex >::ConcurrentHashMapSegment(), folly::Bits< T, Traits >::count(), select64(), folly::compression::BitVectorReader< Encoder, Instructions, kUnchecked >::skip(), folly::compression::detail::UpperBitsReader< Encoder, Instructions, SizeType >::skip(), folly::compression::BitVectorReader< Encoder, Instructions, kUnchecked >::skipTo(), folly::compression::detail::UpperBitsReader< Encoder, Instructions, SizeType >::skipToNext(), TEST(), and TEST_F().

130  {
131  using U0 = unsigned int;
132  using U1 = unsigned long int;
133  using U2 = unsigned long long int;
135  static_assert(sizeof(T) <= sizeof(U2), "over-sized type");
136  static_assert(std::is_integral<T>::value, "non-integral type");
137  static_assert(!std::is_same<T, bool>::value, "bool type");
138 
139  // clang-format off
140  return static_cast<unsigned int>(
141  sizeof(T) <= sizeof(U0) ? __builtin_popcount(bits_to_unsigned<U0>(v)) :
142  sizeof(T) <= sizeof(U1) ? __builtin_popcountl(bits_to_unsigned<U1>(v)) :
143  sizeof(T) <= sizeof(U2) ? __builtin_popcountll(bits_to_unsigned<U2>(v)) :
144  0);
145  // clang-format on
146 }
#define T(v)
Definition: http_parser.c:233
struct folly::detail::LastElementImpl sizeof
constexpr std::make_unsigned_t< Dst > bits_to_unsigned(Src const s)
Definition: Bits.h:71
static const char *const value
Definition: Conv.cpp:50
FOLLY_NODISCARD ssize_t folly::preadFull ( int  fd,
void *  buf,
size_t  count,
off_t  offset 
)

Definition at line 130 of file FileUtil.cpp.

References folly::fileutil_detail::wrapFull().

Referenced by folly::test::CaptureFD::readIncremental(), and shutdownNoInt().

130  {
131  return wrapFull(pread, fd, buf, count, offset);
132 }
ssize_t wrapFull(F f, int fd, void *buf, size_t count, Offset...offset)
int * count
ssize_t folly::preadNoInt ( int  fd,
void *  buf,
size_t  count,
off_t  offset 
)

Definition at line 106 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt().

Referenced by shutdownNoInt().

106  {
107  return wrapNoInt(pread, fd, buf, count, offset);
108 }
ssize_t wrapNoInt(F f, Args...args)
int * count
FOLLY_NODISCARD ssize_t folly::preadvFull ( int  fd,
iovec *  iov,
int  count,
off_t  offset 
)

Definition at line 146 of file FileUtil.cpp.

References preadv(), and folly::fileutil_detail::wrapvFull().

Referenced by shutdownNoInt().

146  {
147  return wrapvFull(preadv, fd, iov, count, offset);
148 }
ssize_t wrapvFull(F f, int fd, iovec *iov, int count, Offset...offset)
ssize_t preadv(int fd, const iovec *iov, int count, off_t offset)
Definition: SysUio.cpp:52
int * count
std::string folly::prettyPrint ( double  val,
PrettyType  type,
bool  addSpace 
)

Definition at line 386 of file String.cpp.

References i, PRETTY_NUM_TYPES, string, suffix, and type.

Referenced by folly::GoogleLogger< Style >::operator()(), and TEST().

386  {
387  char buf[100];
388 
389  // pick the suffixes to use
390  assert(type >= 0);
391  assert(type < PRETTY_NUM_TYPES);
392  const PrettySuffix* suffixes = kPrettySuffixes[type];
393 
394  // find the first suffix we're bigger than -- then use it
395  double abs_val = fabs(val);
396  for (int i = 0; suffixes[i].suffix; ++i) {
397  if (abs_val >= suffixes[i].val) {
398  snprintf(
399  buf,
400  sizeof buf,
401  "%.4g%s%s",
402  (suffixes[i].val ? (val / suffixes[i].val) : val),
403  (addSpace ? " " : ""),
404  suffixes[i].suffix);
405  return std::string(buf);
406  }
407  }
408 
409  // no suffix, we've got a tiny value -- just print it in sci-notation
410  snprintf(buf, sizeof buf, "%.4g", val);
411  return std::string(buf);
412 }
PskType type
double val
Definition: String.cpp:273
const char * suffix
Definition: String.cpp:272
const char * string
Definition: Conv.cpp:212
double folly::prettyToDouble ( folly::StringPiece *const  prettyString,
const PrettyType  type 
)

This utility converts StringPiece in pretty format (look above) to double, with progress information. Alters the StringPiece parameter to get rid of the already-parsed characters. Expects string in form <floating point="" number>=""> {space}* [<suffix>] If string is not in correct format, utility finds longest valid prefix and if there at least one, returns double value based on that prefix and modifies string to what is left after parsing. Throws and std::range_error exception if there is no correct parse. Examples(for PRETTY_UNITS_METRIC): '10M' => 10 000 000 '10 M' => 10 000 000 '10' => 10 '10 Mx' => 10 000 000, prettyString == "x" 'abc' => throws std::range_error

Definition at line 416 of file String.cpp.

References folly::Range< Iter >::advance(), folly::Range< Iter >::front(), folly::Range< Iter >::size(), folly::Range< Iter >::startsWith(), suffix, type, and value().

Referenced by prettyToDouble(), and TEST().

418  {
419  double value = folly::to<double>(prettyString);
420  while (prettyString->size() > 0 && std::isspace(prettyString->front())) {
421  prettyString->advance(1); // Skipping spaces between number and suffix
422  }
423  const PrettySuffix* suffixes = kPrettySuffixes[type];
424  int longestPrefixLen = -1;
425  int bestPrefixId = -1;
426  for (int j = 0; suffixes[j].suffix; ++j) {
427  if (suffixes[j].suffix[0] == ' ') { // Checking for " " -> number rule.
428  if (longestPrefixLen == -1) {
429  longestPrefixLen = 0; // No characters to skip
430  bestPrefixId = j;
431  }
432  } else if (prettyString->startsWith(suffixes[j].suffix)) {
433  int suffixLen = int(strlen(suffixes[j].suffix));
434  // We are looking for a longest suffix matching prefix of the string
435  // after numeric value. We need this in case suffixes have common prefix.
436  if (suffixLen > longestPrefixLen) {
437  longestPrefixLen = suffixLen;
438  bestPrefixId = j;
439  }
440  }
441  }
442  if (bestPrefixId == -1) { // No valid suffix rule found
443  throw std::invalid_argument(folly::to<std::string>(
444  "Unable to parse suffix \"", *prettyString, "\""));
445  }
446  prettyString->advance(size_t(longestPrefixLen));
447  return suffixes[bestPrefixId].val ? value * suffixes[bestPrefixId].val
448  : value;
449 }
PskType type
void advance(size_type n)
Definition: Range.h:672
constexpr size_type size() const
Definition: Range.h:431
const char * suffix
Definition: String.cpp:272
static const char *const value
Definition: Conv.cpp:50
bool startsWith(const const_range_type &other) const
Definition: Range.h:828
value_type & front()
Definition: Range.h:464
double folly::prettyToDouble ( folly::StringPiece  prettyString,
const PrettyType  type 
)

Same as prettyToDouble(folly::StringPiece*, PrettyType), but expects whole string to be correctly parseable. Throws std::range_error otherwise

Definition at line 451 of file String.cpp.

References folly::detail::enforceWhitespace(), and prettyToDouble().

451  {
452  double result = prettyToDouble(&prettyString, type);
453  detail::enforceWhitespace(prettyString);
454  return result;
455 }
void enforceWhitespace(StringPiece sp)
Definition: Conv.h:130
double prettyToDouble(folly::StringPiece prettyString, const PrettyType type)
Definition: String.cpp:451
template<class T >
constexpr T folly::prevPowTwo ( T const  v)
inline

Definition at line 155 of file Bits.h.

References findLastSet(), T, and value.

Referenced by TEST().

155  {
156  static_assert(std::is_unsigned<T>::value, "signed type");
157  return v ? (T(1) << (findLastSet(v) - 1)) : T(0);
158 }
#define T(v)
Definition: http_parser.c:233
constexpr unsigned int findLastSet(T const v)
Definition: Bits.h:105
static const char *const value
Definition: Conv.cpp:50
static void folly::printBenchmarkResults ( const vector< detail::BenchmarkResult > &  data)
static

Definition at line 336 of file Benchmark.cpp.

References printBenchmarkResultsAsJson(), and printBenchmarkResultsAsVerboseJson().

Referenced by runBenchmarks().

336  {
337  if (FLAGS_json_verbose) {
339  return;
340  } else if (FLAGS_json) {
342  return;
343  }
344 
345  CHECK(FLAGS_json_verbose || FLAGS_json) << "Cannot print benchmark results";
346 }
static void printBenchmarkResultsAsVerboseJson(const vector< detail::BenchmarkResult > &data)
Definition: Benchmark.cpp:329
static void printBenchmarkResultsAsJson(const vector< detail::BenchmarkResult > &data)
Definition: Benchmark.cpp:319
static void folly::printBenchmarkResultsAsJson ( const vector< detail::BenchmarkResult > &  data)
static

Definition at line 319 of file Benchmark.cpp.

References object, and toPrettyJson().

Referenced by printBenchmarkResults().

320  {
321  dynamic d = dynamic::object;
322  for (auto& datum : data) {
323  d[datum.name] = datum.timeInNs * 1000.;
324  }
325 
326  printf("%s\n", toPrettyJson(d).c_str());
327 }
void * object
Definition: AtFork.cpp:32
std::string toPrettyJson(dynamic const &dyn)
Definition: json.cpp:919
static void folly::printBenchmarkResultsAsVerboseJson ( const vector< detail::BenchmarkResult > &  data)
static

Definition at line 329 of file Benchmark.cpp.

References benchmarkResultsToDynamic(), and toPrettyJson().

Referenced by printBenchmarkResults().

330  {
331  dynamic d;
332  benchmarkResultsToDynamic(data, d);
333  printf("%s\n", toPrettyJson(d).c_str());
334 }
void benchmarkResultsToDynamic(const vector< detail::BenchmarkResult > &data, dynamic &out)
Definition: Benchmark.cpp:348
std::string toPrettyJson(dynamic const &dyn)
Definition: json.cpp:919
void folly::printResultComparison ( const vector< detail::BenchmarkResult > &  base,
const vector< detail::BenchmarkResult > &  test 
)

Definition at line 371 of file Benchmark.cpp.

References columns, get_optional(), lastFile, max, metricReadable(), readableTime(), resultKey(), and s.

Referenced by compareBenchmarkResults(), and makeUnpredictable().

373  {
374  map<pair<StringPiece, StringPiece>, double> baselines;
375 
376  for (auto& baseResult : base) {
377  baselines[resultKey(baseResult)] = baseResult.timeInNs;
378  }
379  //
380  // Width available
381  static const unsigned int columns = 76;
382 
383  // Compute the longest benchmark name
384  size_t longestName = 0;
385  for (auto& datum : test) {
386  longestName = max(longestName, datum.name.size());
387  }
388 
389  // Print a horizontal rule
390  auto separator = [&](char pad) { puts(string(columns, pad).c_str()); };
391 
392  // Print header for a file
393  auto header = [&](const string& file) {
394  separator('=');
395  printf("%-*srelative time/iter iters/s\n", columns - 28, file.c_str());
396  separator('=');
397  };
398 
399  string lastFile;
400 
401  for (auto& datum : test) {
402  folly::Optional<double> baseline =
403  folly::get_optional(baselines, resultKey(datum));
404  auto file = datum.file;
405  if (file != lastFile) {
406  // New file starting
407  header(file);
408  lastFile = file;
409  }
410 
411  string s = datum.name;
412  if (s == "-") {
413  separator('-');
414  continue;
415  }
416  if (s[0] == '%') {
417  s.erase(0, 1);
418  }
419  s.resize(columns - 29, ' ');
420  auto nsPerIter = datum.timeInNs;
421  auto secPerIter = nsPerIter / 1E9;
422  auto itersPerSec = (secPerIter == 0)
423  ? std::numeric_limits<double>::infinity()
424  : (1 / secPerIter);
425  if (!baseline) {
426  // Print without baseline
427  printf(
428  "%*s %9s %7s\n",
429  static_cast<int>(s.size()),
430  s.c_str(),
431  readableTime(secPerIter, 2).c_str(),
432  metricReadable(itersPerSec, 2).c_str());
433  } else {
434  // Print with baseline
435  auto rel = *baseline / nsPerIter * 100.0;
436  printf(
437  "%*s %7.2f%% %9s %7s\n",
438  static_cast<int>(s.size()),
439  s.c_str(),
440  rel,
441  readableTime(secPerIter, 2).c_str(),
442  metricReadable(itersPerSec, 2).c_str());
443  }
444  }
445  separator('=');
446 }
LogLevel max
Definition: LogLevel.cpp:31
static string readableTime(double n, unsigned int decimals)
Definition: Benchmark.cpp:242
string lastFile
Definition: Benchmark.cpp:255
static string metricReadable(double n, unsigned int decimals)
Definition: Benchmark.cpp:246
folly::Optional< typename Map::mapped_type > get_optional(const Map &map, const Key &key)
Definition: MapUtil.h:102
static constexpr unsigned int columns
Definition: Benchmark.cpp:253
static set< string > s
static pair< StringPiece, StringPiece > resultKey(const detail::BenchmarkResult &result)
Definition: Benchmark.cpp:366
void folly::PrintTo ( const std::shared_ptr< LogHandler > &  handler,
std::ostream *  os 
)

Definition at line 90 of file ConfigHelpers.cpp.

90  {
91  *os << "Handler(" << handler->getConfig() << ")";
92 }
void handler(int, siginfo_t *, void *)
void folly::PrintTo ( StringPiece  sp,
::std::ostream *  os 
)
inline

Definition at line 272 of file TestUtils.h.

References testing::PrintToString(), and folly::Range< Iter >::str().

272  {
273  // gtest's PrintToString() function will quote the string and escape internal
274  // quotes and non-printable characters, the same way gtest does for the
275  // standard string types.
276  *os << ::testing::PrintToString(sp.str());
277 }
::std::string PrintToString(const T &value)
void folly::PrintTo ( const dynamic dyn,
std::ostream *  os 
)

Definition at line 937 of file json.cpp.

References folly::json::serialization_opts::allow_nan_inf, folly::json::serialization_opts::allow_non_string_keys, folly::json::serialization_opts::pretty_formatting, folly::json::serialize(), and folly::json::serialization_opts::sort_keys.

Referenced by TEST().

937  {
938  json::serialization_opts opts;
939  opts.allow_nan_inf = true;
940  opts.allow_non_string_keys = true;
941  opts.pretty_formatting = true;
942  opts.sort_keys = true;
943  *os << json::serialize(dyn, opts);
944 }
std::string serialize(dynamic const &dyn, serialization_opts const &opts)
Definition: json.cpp:621
ssize_t folly::pwriteFull ( int  fd,
const void *  buf,
size_t  count,
off_t  offset 
)

Definition at line 138 of file FileUtil.cpp.

References folly::fileutil_detail::wrapFull().

Referenced by shutdownNoInt(), and folly::RecordIOWriter::write().

138  {
139  return wrapFull(pwrite, fd, const_cast<void*>(buf), count, offset);
140 }
ssize_t wrapFull(F f, int fd, void *buf, size_t count, Offset...offset)
int * count
ssize_t folly::pwriteNoInt ( int  fd,
const void *  buf,
size_t  count,
off_t  offset 
)

Definition at line 118 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt().

Referenced by shutdownNoInt().

118  {
119  return wrapNoInt(pwrite, fd, buf, count, offset);
120 }
ssize_t wrapNoInt(F f, Args...args)
int * count
ssize_t folly::pwritevFull ( int  fd,
iovec *  iov,
int  count,
off_t  offset 
)

Definition at line 154 of file FileUtil.cpp.

References pwritev(), and folly::fileutil_detail::wrapvFull().

Referenced by shutdownNoInt(), and folly::RecordIOWriter::write().

154  {
155  return wrapvFull(pwritev, fd, iov, count, offset);
156 }
ssize_t pwritev(int fd, const iovec *iov, int count, off_t offset)
Definition: SysUio.cpp:58
ssize_t wrapvFull(F f, int fd, iovec *iov, int count, Offset...offset)
int * count
template<class Iter , class Comp = std::equal_to<typename Range<Iter>::value_type>>
size_t folly::qfind ( const Range< Iter > &  haystack,
const Range< Iter > &  needle,
Comp  eq = Comp() 
)
inline

Finds the first occurrence of needle in haystack. The algorithm is on average faster than O(haystack.size() * needle.size()) but not as fast as Boyer-Moore. On the upside, it does not do any upfront preprocessing and does not allocate memory.

Finds substrings faster than brute force by borrowing from Boyer-Moore

Definition at line 1292 of file Range.h.

References folly::Range< Iter >::begin(), folly::Range< Iter >::end(), i, folly::Range< Iter >::size(), and folly::gen::skip().

Referenced by TEST().

1292  {
1293  // Don't use std::search, use a Boyer-Moore-like trick by comparing
1294  // the last characters first
1295  auto const nsize = needle.size();
1296  if (haystack.size() < nsize) {
1297  return std::string::npos;
1298  }
1299  if (!nsize) {
1300  return 0;
1301  }
1302  auto const nsize_1 = nsize - 1;
1303  auto const lastNeedle = needle[nsize_1];
1304 
1305  // Boyer-Moore skip value for the last char in the needle. Zero is
1306  // not a valid value; skip will be computed the first time it's
1307  // needed.
1308  std::string::size_type skip = 0;
1309 
1310  auto i = haystack.begin();
1311  auto iEnd = haystack.end() - nsize_1;
1312 
1313  while (i < iEnd) {
1314  // Boyer-Moore: match the last element in the needle
1315  while (!eq(i[nsize_1], lastNeedle)) {
1316  if (++i == iEnd) {
1317  // not found
1318  return std::string::npos;
1319  }
1320  }
1321  // Here we know that the last char matches
1322  // Continue in pedestrian mode
1323  for (size_t j = 0;;) {
1324  assert(j < nsize);
1325  if (!eq(i[j], needle[j])) {
1326  // Not found, we can skip
1327  // Compute the skip value lazily
1328  if (skip == 0) {
1329  skip = 1;
1330  while (skip <= nsize_1 && !eq(needle[nsize_1 - skip], lastNeedle)) {
1331  ++skip;
1332  }
1333  }
1334  i += skip;
1335  break;
1336  }
1337  // Check if done searching
1338  if (++j == nsize) {
1339  // Yay
1340  return size_t(i - haystack.begin());
1341  }
1342  }
1343  }
1344  return std::string::npos;
1345 }
const string needle
detail::Skip skip(size_t count)
Definition: Base-inl.h:2598
template<class Iter >
size_t folly::qfind ( const Range< Iter > &  haystack,
const typename Range< Iter >::value_type &  needle 
)

Finds the first occurrence of needle in haystack. The result is the offset reported to the beginning of haystack, or string::npos if needle wasn't found.

Definition at line 1396 of file Range.h.

References folly::Range< Iter >::begin(), folly::Range< Iter >::data(), folly::Range< Iter >::end(), and needle.

1398  {
1399  auto pos = std::find(haystack.begin(), haystack.end(), needle);
1400  return pos == haystack.end() ? std::string::npos : pos - haystack.data();
1401 }
const string needle
template<>
size_t folly::qfind ( const Range< const char * > &  haystack,
const char &  needle 
)
inline

Definition at line 1417 of file Range.h.

References folly::Range< Iter >::data(), folly::Range< Iter >::empty(), needle, and folly::Range< Iter >::size().

1417  {
1418  // memchr expects a not-null pointer, early return if the range is empty.
1419  if (haystack.empty()) {
1420  return std::string::npos;
1421  }
1422  auto pos = static_cast<const char*>(
1423  ::memchr(haystack.data(), needle, haystack.size()));
1424  return pos == nullptr ? std::string::npos : pos - haystack.data();
1425 }
const string needle
template<>
size_t folly::qfind ( const Range< const unsigned char * > &  haystack,
const unsigned char &  needle 
)
inline

Definition at line 1440 of file Range.h.

References folly::Range< Iter >::data(), folly::Range< Iter >::empty(), needle, and folly::Range< Iter >::size().

Referenced by folly::Range< unsigned char * >::find().

1442  {
1443  // memchr expects a not-null pointer, early return if the range is empty.
1444  if (haystack.empty()) {
1445  return std::string::npos;
1446  }
1447  auto pos = static_cast<const unsigned char*>(
1448  ::memchr(haystack.data(), needle, haystack.size()));
1449  return pos == nullptr ? std::string::npos : pos - haystack.data();
1450 }
const string needle
template<class Iter >
size_t folly::qfind_first_of ( const Range< Iter > &  haystack,
const Range< Iter > &  needle 
)
inline

Finds the first occurrence of any element of needle in haystack. The algorithm is O(haystack.size() * needle.size()).

Definition at line 1466 of file Range.h.

References qfind_first_of().

1466  {
1467  return qfind_first_of(haystack, needles, AsciiCaseSensitive());
1468 }
size_t qfind_first_of(const Range< const unsigned char * > &haystack, const Range< const unsigned char * > &needles)
Definition: Range.h:1480
template<class Iter , class Comp >
size_t folly::qfind_first_of ( const Range< Iter > &  haystack,
const Range< Iter > &  needles,
Comp  eq 
)

Definition at line 1361 of file Range.h.

References folly::Range< Iter >::begin(), and folly::Range< Iter >::end().

1364  {
1365  auto ret = std::find_first_of(
1366  haystack.begin(), haystack.end(), needles.begin(), needles.end(), eq);
1367  return ret == haystack.end() ? std::string::npos : ret - haystack.begin();
1368 }
template<>
size_t folly::qfind_first_of ( const Range< const char * > &  haystack,
const Range< const char * > &  needles 
)
inline

Definition at line 1472 of file Range.h.

References folly::detail::qfind_first_byte_of().

1474  {
1475  return detail::qfind_first_byte_of(haystack, needles);
1476 }
size_t qfind_first_byte_of(const StringPiece haystack, const StringPiece needles)
Definition: Range.h:1349
template<>
size_t folly::qfind_first_of ( const Range< const unsigned char * > &  haystack,
const Range< const unsigned char * > &  needles 
)
inline

Definition at line 1480 of file Range.h.

References folly::detail::qfind_first_byte_of().

Referenced by folly::Range< unsigned char * >::find_first_of(), and qfind_first_of().

1482  {
1484  StringPiece(haystack), StringPiece(needles));
1485 }
size_t qfind_first_byte_of(const StringPiece haystack, const StringPiece needles)
Definition: Range.h:1349
Range< const char * > StringPiece
uint32_t folly::randomNumberSeed ( )
inline

Definition at line 367 of file Random.h.

References folly::Random::rand32().

Referenced by folly::sync_tests::getRNG(), folly::io::test::RandomDataHolder::RandomDataHolder(), TEST(), and TEST_F().

367  {
368  return Random::rand32();
369 }
template<class Iter >
constexpr Range<Iter> folly::range ( Iter  first,
Iter  last 
)

Create a range from two iterators, with type deduction.

Definition at line 1114 of file Range.h.

References folly::gen::first.

Referenced by folly::RecordIOReader::Iterator::advanceToValid(), folly::IOBufQueue::appendToString(), folly::gen::chunked(), fizz::server::AeadTokenCipher< AeadType, HkdfType >::clearSecrets(), fizz::KeyScheduler::clientKeyUpdate(), fizz::OpenSSLEVPCipher< EVPImpl >::createIV(), fizz::server::AeadTokenCipher< AeadType, HkdfType >::decrypt(), fizz::KeyScheduler::deriveAppTrafficSecrets(), fizz::KeyScheduler::deriveEarlySecret(), fizz::KeyScheduler::deriveHandshakeSecret(), fizz::KeyScheduler::deriveMasterSecret(), folly::io::Codec::doCompressString(), folly::io::StreamCodec::doUncompress(), folly::io::Codec::doUncompressString(), folly::AsyncIO::doWait(), fizz::sm::encodeAndAddBinders(), fizz::server::AeadTokenCipher< AeadType, HkdfType >::encrypt(), fizz::HkdfImpl< Hash >::expand(), fizz::HkdfImpl< Hash >::extract(), folly::for_each_detail::for_each_impl(), folly::for_each_detail::for_each_range_impl(), folly::IPAddressV6::fromInverseArpaName(), fizz::sm::generateTicket(), fizz::sm::getCertificateRequest(), fizz::EncryptedReadRecordLayer::getDecryptedBuf(), fizz::sm::getEarlyDataParams(), fizz::Exporter::getEkm(), folly::IPAddressV6::getMacAddressFromEUI64(), fizz::sm::getMaxEarlyDataSize(), fizz::sm::getReplayCacheResult(), fizz::KeyScheduler::getSecret(), fizz::sm::handleCertMsg(), folly::io::test::hashIOBuf(), fizz::HkdfImpl< Hash >::hkdf(), fizz::sm::negotiatePsk(), folly::pushmi::operators::from_fn::operator()(), folly::pushmi::operators::flow_from_fn::operator()(), preallocate_postallocate_bench(), folly::test::detail::random(), folly::sync_tests::randomSleep(), wangle::SocketPeeker::readDataAvailable(), fizz::KeyScheduler::serverKeyUpdate(), fizz::server::test::FizzTestServer::setResumption(), fizz::server::AeadTokenCipher< AeadType, HkdfType >::setSecrets(), fizz::test::HandshakeTest::SetUp(), fizz::sm::setupSchedulerAndContext(), stripLeftMargin(), fizz::test::TEST(), fizz::testing::TEST(), folly::test::TEST(), TEST(), fizz::test::TEST_F(), fizz::testing::TEST_P(), TEST_P(), testRangeFunc(), fizz::test::TYPED_TEST(), and fizz::EncryptedWriteRecordLayer::write().

1114  {
1115  return Range<Iter>(first, last);
1116 }
constexpr detail::First first
Definition: Base-inl.h:2553
template<class Collection >
constexpr auto folly::range ( Collection &  v) -> Range<decltype(v.data())>

Definition at line 1123 of file Range.h.

1123  {
1124  return Range<decltype(v.data())>(v.data(), v.data() + v.size());
1125 }
template<class Collection >
constexpr auto folly::range ( Collection const &  v) -> Range<decltype(v.data())>

Definition at line 1127 of file Range.h.

1127  {
1128  return Range<decltype(v.data())>(v.data(), v.data() + v.size());
1129 }
template<class T , size_t n>
constexpr Range<T*> folly::range ( T(&)  array[n])

Definition at line 1136 of file Range.h.

1136  {
1137  return Range<T*>(array, array + n);
1138 }
template<class T , size_t n>
constexpr Range<T const*> folly::range ( T const (&)  array[n])

Definition at line 1140 of file Range.h.

1140  {
1141  return Range<T const*>(array, array + n);
1142 }
template<class T , size_t n>
constexpr Range<T*> folly::range ( std::array< T, n > &  array)

Definition at line 1149 of file Range.h.

1149  {
1150  return Range<T*>{array};
1151 }
template<class T , size_t n>
constexpr Range<T const*> folly::range ( std::array< T, n > const &  array)

Definition at line 1153 of file Range.h.

1153  {
1154  return Range<T const*>{array};
1155 }
template<typename Tag = RcuTag>
void folly::rcu_barrier ( rcu_domain< Tag > *  domain = rcu_default_domain())
inlinenoexcept

Definition at line 456 of file Rcu.h.

References D, and T.

Referenced by TEST().

457  {
458  domain->synchronize();
459 }
rcu_domain<RcuTag>* folly::rcu_default_domain ( )
inline

Definition at line 385 of file Rcu.h.

References rcu_default_domain_.

Referenced by rcu_retire(), folly::rcu_obj_base< T, D, Tag >::retire(), and TEST().

385  {
386  return *rcu_default_domain_;
387 }
folly::Indestructible< rcu_domain< RcuTag > * > rcu_default_domain_
FOLLY_STATIC_CTOR_PRIORITY_MAX folly::Indestructible<rcu_domain<RcuTag>*> folly::rcu_default_domain_ ( folly::detail::createGlobal< rcu_domain< RcuTag >, RcuTag >  ())
template<typename T , typename D = std::default_delete<T>, typename Tag = RcuTag>
void folly::rcu_retire ( T p,
D  d = {},
rcu_domain< Tag > *  domain = rcu_default_domain() 
)

Definition at line 466 of file Rcu.h.

References folly::rcu_domain< Tag >::call(), folly::gen::move, rcu_default_domain(), and T.

Referenced by TEST(), and tryretire().

468  {},
469  rcu_domain<Tag>* domain = rcu_default_domain()) {
470  domain->call([p, del = std::move(d)]() { del(p); });
471 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
rcu_domain< RcuTag > * rcu_default_domain()
Definition: Rcu.h:385
static string folly::readableTime ( double  n,
unsigned int  decimals 
)
static

Definition at line 242 of file Benchmark.cpp.

References humanReadable(), and kTimeSuffixes.

Referenced by printResultComparison().

242  {
243  return humanReadable(n, decimals, kTimeSuffixes);
244 }
static const ScaleInfo kTimeSuffixes[]
Definition: Benchmark.cpp:190
static string humanReadable(double n, unsigned int decimals, const ScaleInfo *scales)
Definition: Benchmark.cpp:227
template<class Container >
bool folly::readFile ( int  fd,
Container &  out,
size_t  num_bytes = std::numeric_limits<size_t>::max() 
)

Read entire file (if num_bytes is defaulted) or no more than num_bytes (otherwise) into container *out. The container is assumed to be contiguous, with element size equal to 1, and offer size(), reserve(), and random access (e.g. std::vector<char>, std::string, fbstring).

Returns: true on success or false on failure. In the latter case errno will be set appropriately by the failing system primitive.

Definition at line 125 of file FileUtil.h.

References min, readFull(), and SCOPE_EXIT.

Referenced by fizz::server::test::FizzTestServer::enableClientAuthWithChain(), fizz::tool::fizzClientCommand(), fizz::tool::fizzServerCommand(), getFileAsBuf(), wangle::FilePersistenceLayer< K, V >::load(), StaticService::StaticHandler::onEgressResumed(), wangle::MultiFilePoller::onFileUpdated(), StaticService::StaticHandler::onRequest(), folly::PasswordInFile::PasswordInFile(), wangle::TLSCredProcessor::processTLSTickets(), PushService::PushRequestHandler::PushRequestHandler(), folly::test::CaptureFD::read(), fizz::FizzUtil::readChainFile(), folly::test::WriteFileAtomic::readData(), readFile(), fizz::FizzUtil::readPrivateKey(), folly::ssl::OpenSSLCertUtils::readStoreFromFile(), resultsFromFile(), TEST(), folly::test::TEST(), TEST_F(), and folly::test::TEST_F().

128  {
129  static_assert(
130  sizeof(out[0]) == 1,
131  "readFile: only containers with byte-sized elements accepted");
132 
133  size_t soFar = 0; // amount of bytes successfully read
134  SCOPE_EXIT {
135  DCHECK(out.size() >= soFar); // resize better doesn't throw
136  out.resize(soFar);
137  };
138 
139  // Obtain file size:
140  struct stat buf;
141  if (fstat(fd, &buf) == -1) {
142  return false;
143  }
144  // Some files (notably under /proc and /sys on Linux) lie about
145  // their size, so treat the size advertised by fstat under advise
146  // but don't rely on it. In particular, if the size is zero, we
147  // should attempt to read stuff. If not zero, we'll attempt to read
148  // one extra byte.
149  constexpr size_t initialAlloc = 1024 * 4;
150  out.resize(std::min(
151  buf.st_size > 0 ? (size_t(buf.st_size) + 1) : initialAlloc, num_bytes));
152 
153  while (soFar < out.size()) {
154  const auto actual = readFull(fd, &out[soFar], out.size() - soFar);
155  if (actual == -1) {
156  return false;
157  }
158  soFar += actual;
159  if (soFar < out.size()) {
160  // File exhausted
161  break;
162  }
163  // Ew, allocate more memory. Use exponential growth to avoid
164  // quadratic behavior. Cap size to num_bytes.
165  out.resize(std::min(out.size() * 3 / 2, num_bytes));
166  }
167 
168  return true;
169 }
ssize_t readFull(int fd, void *buf, size_t count)
Definition: FileUtil.cpp:126
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
LogLevel min
Definition: LogLevel.cpp:30
template<class Container >
bool folly::readFile ( const char *  file_name,
Container &  out,
size_t  num_bytes = std::numeric_limits<size_t>::max() 
)

Same as above, but takes in a file name instead of fd

Definition at line 175 of file FileUtil.h.

References closeNoInt(), openNoInt(), readFile(), and SCOPE_EXIT.

178  {
179  DCHECK(file_name);
180 
181  const auto fd = openNoInt(file_name, O_RDONLY | O_CLOEXEC);
182  if (fd == -1) {
183  return false;
184  }
185 
186  SCOPE_EXIT {
187  // Ignore errors when closing the file
188  closeNoInt(fd);
189  };
190 
191  return readFile(fd, out, num_bytes);
192 }
int closeNoInt(int fd)
Definition: FileUtil.cpp:56
bool readFile(const char *file_name, Container &out, size_t num_bytes=std::numeric_limits< size_t >::max())
Definition: FileUtil.h:175
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
int openNoInt(const char *name, int flags, mode_t mode)
Definition: FileUtil.cpp:36
FOLLY_NODISCARD ssize_t folly::readFull ( int  fd,
void *  buf,
size_t  n 
)

Wrapper around read() (and pread()) that, in addition to retrying on EINTR, will loop until all data is read.

This wrapper is only useful for blocking file descriptors (for non-blocking file descriptors, you have to be prepared to deal with incomplete reads anyway), and only exists because POSIX allows read() to return an incomplete read if interrupted by a signal (instead of returning -1 and setting errno to EINTR).

Note that this wrapper weakens the thread safety of read(): the file pointer is shared between threads, but the system call is atomic. If multiple threads are reading from a file at the same time, you don't know where your data came from in the file, but you do know that the returned bytes were contiguous. You can no longer make this assumption if using readFull(). You should probably use pread() when reading from the same file descriptor from multiple threads simultaneously, anyway.

Note that readvFull and preadvFull require iov to be non-const, unlike readv and preadv. The contents of iov after these functions return is unspecified.

Definition at line 126 of file FileUtil.cpp.

References fizz::detail::read(), and folly::fileutil_detail::wrapFull().

Referenced by readFile(), folly::symbolizer::LineReader::readLine(), shutdownNoInt(), and TEST().

126  {
127  return wrapFull(read, fd, buf, count);
128 }
size_t read(T &out, folly::io::Cursor &cursor)
Definition: Types-inl.h:258
ssize_t wrapFull(F f, int fd, void *buf, size_t count, Offset...offset)
int * count
FOLLY_NODISCARD ssize_t folly::readvFull ( int  fd,
iovec *  iov,
int  count 
)

Definition at line 142 of file FileUtil.cpp.

References folly::fileutil_detail::wrapvFull().

Referenced by shutdownNoInt().

142  {
143  return wrapvFull(readv, fd, iov, count);
144 }
ssize_t wrapvFull(F f, int fd, iovec *iov, int count, Offset...offset)
int * count
ssize_t folly::readvNoInt ( int  fd,
const iovec *  iov,
int  count 
)

Definition at line 110 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt().

Referenced by shutdownNoInt().

110  {
111  return wrapNoInt(readv, fd, iov, count);
112 }
ssize_t wrapNoInt(F f, Args...args)
int * count
template<class Collection , class T , class F >
auto folly::reduce ( Collection &&  c,
T &&  initial,
F &&  func 
) -> decltype(reduce( c.begin(), c.end(), std::forward<T>(initial), std::forward<F>(func)))

Sugar for the most common case.

Definition at line 462 of file helpers.h.

References c, reduce(), T, and unorderedReduce().

466  {
467  return reduce(
468  c.begin(), c.end(), std::forward<T>(initial), std::forward<F>(func));
469 }
auto reduce(Collection &&c, T &&initial, F &&func) -> decltype(reduce(c.begin(), c.end(), std::forward< T >(initial), std::forward< F >(func)))
Sugar for the most common case.
Definition: helpers.h:462
char c
template<class It , class T , class F >
Future< T > folly::reduce ( It  first,
It  last,
T &&  initial,
F &&  func 
)

repeatedly calls func on every result, e.g. reduce(reduce(reduce(T initial, result of first), result of second), ...)

The type of the final result is a Future of the type of the initial value.

Func can either return a T, or a Future<T>

func is called in order of the input, see unorderedReduce if that is not a requirement

Definition at line 1753 of file Future-inl.h.

References collectAllSemiFuture(), f, folly::gen::first, folly::Future< T >::makeFuture, folly::gen::move, folly::pushmi::detail::t, type, and folly::futures::detail::FutureBase< T >::value().

Referenced by folly::Future< folly::folly::Unit >::onError(), reduce(), and TEST().

1753  {
1754  if (first == last) {
1755  return makeFuture(std::forward<T>(initial));
1756  }
1757 
1758  typedef typename std::iterator_traits<It>::value_type::value_type ItT;
1759  typedef typename std::
1760  conditional<is_invocable<F, T&&, Try<ItT>&&>::value, Try<ItT>, ItT>::type
1761  Arg;
1762  typedef isTry<Arg> IsTry;
1763 
1764  auto sfunc = std::make_shared<std::decay_t<F>>(std::forward<F>(func));
1765 
1766  auto f = std::move(*first).thenTry(
1767  [initial = std::forward<T>(initial), sfunc](Try<ItT>&& head) mutable {
1768  return (*sfunc)(
1769  std::move(initial), head.template get<IsTry::value, Arg&&>());
1770  });
1771 
1772  for (++first; first != last; ++first) {
1773  f = collectAllSemiFuture(f, *first).toUnsafeFuture().thenValue(
1774  [sfunc](std::tuple<Try<T>, Try<ItT>>&& t) {
1775  return (*sfunc)(
1776  std::move(std::get<0>(t).value()),
1777  // Either return a ItT&& or a Try<ItT>&& depending
1778  // on the type of the argument of func.
1779  std::get<1>(t).template get<IsTry::value, Arg&&>());
1780  });
1781  }
1782 
1783  return f;
1784 }
auto f
PskType type
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
Future< T > makeFuture(Try< T > t)
Definition: Future-inl.h:1364
static const char *const value
Definition: Conv.cpp:50
SemiFuture< std::vector< Try< typename std::iterator_traits< InputIterator >::value_type::value_type > > > collectAllSemiFuture(InputIterator first, InputIterator last)
Definition: Future-inl.h:1487
constexpr detail::First first
Definition: Base-inl.h:2553
template<class T , class A >
T* folly::relinquish ( fbvector< T, A > &  v)

Definition at line 1744 of file FBVector.h.

References T.

Referenced by test_I_attach3(), and test_relinquish3().

1745  {
1746  T* ret = v.data();
1747  v.impl_.b_ = v.impl_.e_ = v.impl_.z_ = nullptr;
1748  return ret;
#define T(v)
Definition: http_parser.c:233
template<class Delimiter , class... Ts>
void folly::reserveInTargetDelim ( const Delimiter d,
const Ts &...  vs 
)

Definition at line 796 of file Conv.h.

References folly::detail::getLastElement(), and type.

Referenced by toAppendStrImpl().

796  {
797  static_assert(sizeof...(vs) >= 2, "Needs at least 2 args");
798  size_t fordelim = (sizeof...(vs) - 2) *
799  estimateSpaceToReserve(0, d, static_cast<std::string*>(nullptr));
800  getLastElement(vs...)->reserve(estimateSpaceToReserve(fordelim, vs...));
801 }
auto getLastElement(const Ts &...ts) -> decltype(LastElementImpl< Ts... >::call(ts...))
Definition: Conv.h:232
void folly::resizeWithoutInitialization ( std::string s,
std::size_t  n 
)
inline

Like calling s.resize(n), but when growing the string does not initialize new elements. It is undefined behavior to read from any element added to the string by this method unless it has been written to by an operation that follows this call.

IMPORTANT: Read the warning at the top of this header file.

Definition at line 86 of file UninitializedMemoryHacks.h.

References T, type, folly::detail::unsafeStringSetLargerSize(), and value.

Referenced by doResizeWithoutInit(), and testRandom().

86  {
87  if (n <= s.size()) {
88  s.resize(n);
89  } else {
90  // careful not to call reserve unless necessary, as it causes
91  // shrink_to_fit on many platforms
92  if (n > s.capacity()) {
93  s.reserve(n);
94  }
96  }
97 }
void unsafeStringSetLargerSize(std::string &s, std::size_t n)
static set< string > s
template<typename T , typename = typename std::enable_if< std::is_trivially_destructible<T>::value && !std::is_same<T, bool>::value>::type>
void folly::resizeWithoutInitialization ( std::vector< T > &  v,
std::size_t  n 
)

Like calling v.resize(n), but when growing the vector does not construct or initialize new elements. It is undefined behavior to read from any element added to the vector by this method unless it has been written to by an operation that follows this call.

Use the FOLLY_DECLARE_VECTOR_RESIZE_WITHOUT_INIT(T) macro to declare (and inline define) the internals required to call resizeWithoutInitialization for a std::vector<T>. This must be done exactly once in each translation unit that wants to call resizeWithoutInitialization(std::vector<T>&,size_t). char and unsigned char are provided by default. If you don't do this you will get linker errors about folly::detail::unsafeVectorSetLargerSize. Requiring that T be trivially_destructible is only an approximation of the property required of T. In fact what is required is that any random sequence of bytes may be safely reinterpreted as a T and passed to T's destructor.

std::vector<bool> has specialized internals and is not supported.

IMPORTANT: Read the warning at the top of this header file.

Definition at line 125 of file UninitializedMemoryHacks.h.

References B, s, string, T, folly::detail::unsafeStringSetLargerSize(), and folly::detail::unsafeVectorSetLargerSize().

125  {
126  if (n <= v.size()) {
127  v.resize(n);
128  } else {
129  if (n > v.capacity()) {
130  v.reserve(n);
131  }
133  }
134 }
void unsafeVectorSetLargerSize(std::vector< T > &v, std::size_t n)
static pair<StringPiece, StringPiece> folly::resultKey ( const detail::BenchmarkResult result)
static

Definition at line 366 of file Benchmark.cpp.

References folly::detail::BenchmarkResult::file, and folly::detail::BenchmarkResult::name.

Referenced by printResultComparison().

367  {
368  return pair<StringPiece, StringPiece>(result.file, result.name);
369 }
vector<detail::BenchmarkResult> folly::resultsFromFile ( const std::string filename)

Definition at line 26 of file BenchmarkCompare.cpp.

References benchmarkResultsFromDynamic(), parseJson(), and readFile().

Referenced by compareBenchmarkResults().

26  {
27  string content;
28  readFile(filename.c_str(), content);
29  vector<detail::BenchmarkResult> ret;
31  return ret;
32 }
bool readFile(int fd, Container &out, size_t num_bytes=std::numeric_limits< size_t >::max())
Definition: FileUtil.h:125
dynamic parseJson(StringPiece range)
Definition: json.cpp:900
void benchmarkResultsFromDynamic(const dynamic &d, vector< detail::BenchmarkResult > &results)
Definition: Benchmark.cpp:357
template<class Iter >
size_t folly::rfind ( const Range< Iter > &  haystack,
const typename Range< Iter >::value_type &  needle 
)

Finds the last occurrence of needle in haystack. The result is the offset reported to the beginning of haystack, or string::npos if needle wasn't found.

Definition at line 1404 of file Range.h.

References i, and folly::Range< Iter >::size().

Referenced by getContainingDirectory(), folly::Range< unsigned char * >::rfind(), folly::basic_fbstring< char >::rfind(), folly::BasicFixedString< Char, N >::rfind(), and TEST().

1406  {
1407  for (auto i = haystack.size(); i-- > 0;) {
1408  if (haystack[i] == needle) {
1409  return i;
1410  }
1411  }
1412  return std::string::npos;
1413 }
const string needle
template<>
size_t folly::rfind ( const Range< const char * > &  haystack,
const char &  needle 
)
inline

Definition at line 1428 of file Range.h.

References folly::Range< Iter >::data(), folly::Range< Iter >::empty(), memrchr(), needle, and folly::Range< Iter >::size().

1428  {
1429  // memchr expects a not-null pointer, early return if the range is empty.
1430  if (haystack.empty()) {
1431  return std::string::npos;
1432  }
1433  auto pos = static_cast<const char*>(
1434  ::memrchr(haystack.data(), needle, haystack.size()));
1435  return pos == nullptr ? std::string::npos : pos - haystack.data();
1436 }
const string needle
void * memrchr(const void *s, int c, size_t n)
Definition: String.cpp:20
template<>
size_t folly::rfind ( const Range< const unsigned char * > &  haystack,
const unsigned char &  needle 
)
inline

Definition at line 1453 of file Range.h.

References folly::Range< Iter >::data(), folly::Range< Iter >::empty(), memrchr(), needle, and folly::Range< Iter >::size().

1455  {
1456  // memchr expects a not-null pointer, early return if the range is empty.
1457  if (haystack.empty()) {
1458  return std::string::npos;
1459  }
1460  auto pos = static_cast<const unsigned char*>(
1461  ::memrchr(haystack.data(), needle, haystack.size()));
1462  return pos == nullptr ? std::string::npos : pos - haystack.data();
1463 }
const string needle
void * memrchr(const void *s, int c, size_t n)
Definition: String.cpp:20
template<typename Data , typename Mutex , typename... Args>
auto folly::rlock ( const Synchronized< Data, Mutex > &  synchronized,
Args &&...  args 
)
template<typename T >
rvalue_reference_wrapper<T> folly::rref ( T &&  value)
noexcept
Examples:
/facebook/proxygen/proxygen/folly/folly/lang/RValueReferenceWrapper.h.

Definition at line 149 of file RValueReferenceWrapper.h.

References folly::gen::move, folly::pushmi::__adl::noexcept(), T, and value().

Referenced by TEST().

149  {
150  return rvalue_reference_wrapper<T>(std::move(value));
151 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
static const char *const value
Definition: Conv.cpp:50
template<typename T >
rvalue_reference_wrapper<T> folly::rref ( T )
deletenoexcept
StringPiece folly::rtrimWhitespace ( StringPiece  sp)

Returns a subpiece with all whitespace removed from the back of . Whitespace means any of [' ', '
', '', ''].

Definition at line 149 of file String.cpp.

References folly::Range< Iter >::back(), folly::Range< Iter >::empty(), format(), is_oddspace(), gmock_output_test::output, folly::Range< Iter >::pop_back(), and string.

Referenced by join(), TEST(), and trimWhitespace().

149  {
150  // Spaces other than ' ' characters are less common but should be
151  // checked. This configuration where we loop on the ' '
152  // separately from oddspaces was empirically fastest.
153 
154  while (true) {
155  while (!sp.empty() && sp.back() == ' ') {
156  sp.pop_back();
157  }
158  if (!sp.empty() && is_oddspace(sp.back())) {
159  sp.pop_back();
160  continue;
161  }
162 
163  return sp;
164  }
165 }
static bool is_oddspace(char c)
Definition: String.cpp:127
static void folly::run ( EventBaseManager ebm,
EventBase eb,
folly::Baton<> *  stop,
const StringPiece name 
)
static

Definition at line 30 of file ScopedEventBaseThread.cpp.

References folly::EventBaseManager::clearEventBase(), folly::EventBase::loopForever(), folly::EventBase::runOnDestruction(), folly::EventBaseManager::setEventBase(), setThreadName(), folly::Range< Iter >::size(), folly::Baton< MayBlock, Atom >::wait(), and folly::EventBase::~EventBase().

Referenced by BENCHMARK(), ClientRunner::ClientRunner(), dummy(), folly::NestedCommandLineApp::globalOptions(), folly::ScopedEventBaseThread::ScopedEventBaseThread(), folly::FunctionScheduler::start(), TEST(), and folly::fibers::InlineFunctionRunner::~InlineFunctionRunner().

34  {
35  if (name.size()) {
37  }
38 
39  ebm->setEventBase(eb, false);
40  eb->loopForever();
41 
42  // must destruct in io thread for on-destruction callbacks
43  EventBase::StackFunctionLoopCallback cb([=] { ebm->clearEventBase(); });
44  eb->runOnDestruction(&cb);
45  // wait until terminateLoopSoon() is complete
46  stop->wait();
47  eb->~EventBase();
48 }
const char * name
Definition: http_parser.c:437
FOLLY_ALWAYS_INLINE void wait(const WaitOptions &opt=wait_options()) noexcept
Definition: Baton.h:170
bool setThreadName(std::thread::id tid, StringPiece name)
Definition: ThreadName.cpp:109
static double folly::runBenchmarkGetNSPerIteration ( const BenchmarkFun fun,
const double  globalBaseline 
)
static

Definition at line 125 of file Benchmark.cpp.

References count, estimateTime(), fun(), max, now(), uint32_t, and value.

Referenced by runBenchmarks().

127  {
128  using std::chrono::duration_cast;
129  using std::chrono::high_resolution_clock;
130  using std::chrono::microseconds;
131  using std::chrono::nanoseconds;
132  using std::chrono::seconds;
133 
134  // They key here is accuracy; too low numbers means the accuracy was
135  // coarse. We up the ante until we get to at least minNanoseconds
136  // timings.
137  static_assert(
139  "High resolution clock must be nanosecond resolution.");
140  // We choose a minimum minimum (sic) of 100,000 nanoseconds, but if
141  // the clock resolution is worse than that, it will be larger. In
142  // essence we're aiming at making the quantization noise 0.01%.
143  static const auto minNanoseconds = std::max<nanoseconds>(
144  nanoseconds(100000), microseconds(FLAGS_bm_min_usec));
145 
146  // We do measurements in several epochs and take the minimum, to
147  // account for jitter.
148  static const unsigned int epochs = 1000;
149  // We establish a total time budget as we don't want a measurement
150  // to take too long. This will curtail the number of actual epochs.
151  const auto timeBudget = seconds(FLAGS_bm_max_secs);
152  auto global = high_resolution_clock::now();
153 
154  double epochResults[epochs] = {0};
155  size_t actualEpochs = 0;
156 
157  for (; actualEpochs < epochs; ++actualEpochs) {
158  const auto maxIters = uint32_t(FLAGS_bm_max_iters);
159  for (auto n = uint32_t(FLAGS_bm_min_iters); n < maxIters; n *= 2) {
160  auto const nsecsAndIter = fun(static_cast<unsigned int>(n));
161  if (nsecsAndIter.first < minNanoseconds) {
162  continue;
163  }
164  // We got an accurate enough timing, done. But only save if
165  // smaller than the current result.
166  auto nsecs = duration_cast<nanoseconds>(nsecsAndIter.first).count();
167  epochResults[actualEpochs] =
168  max(0.0, double(nsecs) / nsecsAndIter.second - globalBaseline);
169  // Done with the current epoch, we got a meaningful timing.
170  break;
171  }
173  if (now - global >= timeBudget) {
174  // No more time budget available.
175  ++actualEpochs;
176  break;
177  }
178  }
179 
180  // If the benchmark was basically drowned in baseline noise, it's
181  // possible it became negative.
182  return max(0.0, estimateTime(epochResults, epochResults + actualEpochs));
183 }
LogLevel max
Definition: LogLevel.cpp:31
std::chrono::steady_clock::time_point now()
static double estimateTime(double *begin, double *end)
Definition: Benchmark.cpp:117
static const char *const value
Definition: Conv.cpp:50
int * count
void fun()
folly::runBenchmarks ( )

Runs all benchmarks defined. Usually put in main().

Definition at line 456 of file Benchmark.cpp.

References benchmarks(), checkRunMode(), empty(), FOR_EACH_RANGE, getGlobalBenchmarkBaselineIndex(), i, printBenchmarkResults(), runBenchmarkGetNSPerIteration(), and size().

Referenced by main(), runBenchmarksOnFlag(), and TEST().

456  {
457  CHECK(!benchmarks().empty());
458 
459  checkRunMode();
460 
461  vector<detail::BenchmarkResult> results;
462  results.reserve(benchmarks().size() - 1);
463 
464  std::unique_ptr<boost::regex> bmRegex;
465  if (!FLAGS_bm_regex.empty()) {
466  bmRegex = std::make_unique<boost::regex>(FLAGS_bm_regex);
467  }
468 
469  // PLEASE KEEP QUIET. MEASUREMENTS IN PROGRESS.
470 
471  size_t baselineIndex = getGlobalBenchmarkBaselineIndex();
472 
473  auto const globalBaseline =
474  runBenchmarkGetNSPerIteration(benchmarks()[baselineIndex].func, 0);
475  auto printer = BenchmarkResultsPrinter{};
476  FOR_EACH_RANGE (i, 0, benchmarks().size()) {
477  if (i == baselineIndex) {
478  continue;
479  }
480  double elapsed = 0.0;
481  auto& bm = benchmarks()[i];
482  if (bm.name != "-") { // skip separators
483  if (bmRegex && !boost::regex_search(bm.name, *bmRegex)) {
484  continue;
485  }
486  elapsed = runBenchmarkGetNSPerIteration(bm.func, globalBaseline);
487  }
488 
489  if (!FLAGS_json_verbose && !FLAGS_json) {
490  printer.print({{bm.file, bm.name, elapsed}});
491  } else {
492  results.push_back({bm.file, bm.name, elapsed});
493  }
494  }
495 
496  // PLEASE MAKE NOISE. MEASUREMENTS DONE.
497 
498  if (FLAGS_json_verbose || FLAGS_json) {
499  printBenchmarkResults(results);
500  } else {
501  printer.separator('=');
502  }
503 
504  checkRunMode();
505 }
size_t getGlobalBenchmarkBaselineIndex()
Definition: Benchmark.cpp:92
static void printBenchmarkResults(const vector< detail::BenchmarkResult > &data)
Definition: Benchmark.cpp:336
vector< detail::BenchmarkRegistration > & benchmarks()
Definition: Benchmark.cpp:75
#define FOR_EACH_RANGE(i, begin, end)
Definition: Foreach.h:313
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
constexpr auto empty(C const &c) -> decltype(c.empty())
Definition: Access.h:55
void checkRunMode()
Definition: Benchmark.cpp:448
static double runBenchmarkGetNSPerIteration(const BenchmarkFun &fun, const double globalBaseline)
Definition: Benchmark.cpp:125
bool folly::runBenchmarksOnFlag ( )
inline

Runs all benchmarks defined if and only if the –benchmark flag has been passed to the program. Usually put in main().

Definition at line 48 of file Benchmark.h.

References runBenchmarks().

Referenced by main().

48  {
49  if (FLAGS_benchmark) {
50  runBenchmarks();
51  }
52  return FLAGS_benchmark;
53 }
void runBenchmarks()
Definition: Benchmark.cpp:456
template<template< typename > class Atom>
void folly::runReader ( LockFreeRingBuffer< int, Atom > &  rb,
std::atomic< int32_t > &  writes 
)

Definition at line 109 of file LockFreeRingBufferTest.cpp.

References Atom, int32_t, and folly::LockFreeRingBuffer< T, Atom >::write().

111  {
112  int32_t idx;
113  while ((idx = writes--) > 0) {
114  rb.write(idx);
115  }
116 }
template<template< typename > class Atom>
void folly::runWritesNeverFail ( int  capacity,
int  writes,
int  writers 
)

Definition at line 119 of file LockFreeRingBufferTest.cpp.

References folly::netops::bind(), folly::LockFreeRingBuffer< T, Atom >::currentHead(), EXPECT_EQ, i, join, and threads.

119  {
121 
122  DeterministicSchedule sched(DeterministicSchedule::uniform(0));
123  LockFreeRingBuffer<int, Atom> rb(capacity);
124 
125  std::atomic<int32_t> writes_remaining(writes);
126  std::vector<std::thread> threads(writers);
127 
128  for (int i = 0; i < writers; i++) {
129  threads[i] = DeterministicSchedule::thread(
130  std::bind(runReader<Atom>, std::ref(rb), std::ref(writes_remaining)));
131  }
132 
133  for (auto& thread : threads) {
135  }
136 
137  EXPECT_EQ(writes, (value<int, Atom>)(rb.currentHead()));
138 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
std::vector< std::thread::id > threads
int bind(NetworkSocket s, const sockaddr *name, socklen_t namelen)
Definition: NetOps.cpp:76
#define join
template<class Instructions >
uint64_t folly::select64 ( uint64_t  x,
uint64_t  k 
)
inline

Returns the position of the k-th 1 in the 64-bit word x. k is 0-based, so k=0 returns the position of the first 1.

Uses the broadword selection algorithm by Vigna [1], improved by Gog and Petri [2] and Vigna [3].

[1] Sebastiano Vigna. Broadword Implementation of Rank/Select Queries. WEA, 2008

[2] Simon Gog, Matthias Petri. Optimized succinct data structures for massive data. Softw. Pract. Exper., 2014

[3] Sebastiano Vigna. MG4J 5.2.1. http://mg4j.di.unimi.it/

Definition at line 69 of file Select64.h.

References FOLLY_ALWAYS_INLINE, folly::detail::kSelectInByte, popcount(), s, uint64_t, and x.

69  {
70  DCHECK_LT(k, Instructions::popcount(x));
71 
72  constexpr uint64_t kOnesStep4 = 0x1111111111111111ULL;
73  constexpr uint64_t kOnesStep8 = 0x0101010101010101ULL;
74  constexpr uint64_t kMSBsStep8 = 0x80ULL * kOnesStep8;
75 
76  auto s = x;
77  s = s - ((s & 0xA * kOnesStep4) >> 1);
78  s = (s & 0x3 * kOnesStep4) + ((s >> 2) & 0x3 * kOnesStep4);
79  s = (s + (s >> 4)) & 0xF * kOnesStep8;
80  uint64_t byteSums = s * kOnesStep8;
81 
82  uint64_t kStep8 = k * kOnesStep8;
83  uint64_t geqKStep8 = (((kStep8 | kMSBsStep8) - byteSums) & kMSBsStep8);
84  uint64_t place = Instructions::popcount(geqKStep8) * 8;
85  uint64_t byteRank = k - (((byteSums << 8) >> place) & uint64_t(0xFF));
86  return place + detail::kSelectInByte[byteRank][((x >> place) & 0xFF)];
87 }
constexpr unsigned int popcount(T const v)
Definition: Bits.h:130
Definition: InvokeTest.cpp:58
const int x
FOLLY_STORAGE_CONSTEXPR std::array< std::array< std::uint8_t, 256 >, 8 > const kSelectInByte
Definition: Select64.cpp:57
static set< string > s
KeyT k

Definition at line 91 of file Select64.h.

References k, and uint64_t.

91  {
92 #if defined(__GNUC__) || defined(__clang__)
93  // GCC and Clang won't inline the intrinsics.
94  uint64_t result = uint64_t(1) << k;
95 
96  asm("pdep %1, %0, %0\n\t"
97  "tzcnt %0, %0"
98  : "+r"(result)
99  : "r"(x));
100 
101  return result;
102 #else
103  return _tzcnt_u64(_pdep_u64(1ULL << k, x));
104 #endif
105 }
Definition: InvokeTest.cpp:58
KeyT k
int folly::setCloseOnExec ( int  fd,
int  value 
)

Definition at line 61 of file AsyncServerSocket.cpp.

Referenced by folly::AsyncServerSocket::setupSocket().

61  {
62  // Read the current flags
63  int old_flags = fcntl(fd, F_GETFD, 0);
64 
65  // If reading the flags failed, return error indication now
66  if (old_flags < 0) {
67  return -1;
68  }
69 
70  // Set just the flag we want to set
71  int new_flags;
72  if (value != 0) {
73  new_flags = old_flags | FD_CLOEXEC;
74  } else {
75  new_flags = old_flags & ~FD_CLOEXEC;
76  }
77 
78  // Store modified flag word in the descriptor
79  return fcntl(fd, F_SETFD, new_flags);
80 }
static const char *const value
Definition: Conv.cpp:50
void folly::setCPUExecutor ( std::weak_ptr< folly::Executor executor)

Set an Executor to be the global Executor which will be returned by subsequent calls to getCPUExecutor().

Definition at line 97 of file GlobalExecutor.cpp.

References folly::gen::move, and singleton.

Referenced by main(), and TEST().

97  {
98  if (auto singleton = gGlobalCPUExecutor.try_get()) {
99  singleton->set(std::move(executor));
100  }
101 }
static Singleton< ShutdownSocketSet, PrivateTag > singleton
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void folly::setIOExecutor ( std::weak_ptr< IOExecutor executor)

Set an IOExecutor to be the global IOExecutor which will be returned by subsequent calls to getIOExecutor().

Definition at line 110 of file GlobalExecutor.cpp.

References folly::gen::move, and singleton.

Referenced by TEST().

110  {
111  if (auto singleton = gGlobalIOExecutor.try_get()) {
112  singleton->set(std::move(executor));
113  }
114 }
static Singleton< ShutdownSocketSet, PrivateTag > singleton
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
bool folly::setThreadName ( std::thread::id  tid,
StringPiece  name 
)

Set the name of the given thread. Returns false on failure, if an error occurs or the functionality is not available.

Definition at line 109 of file ThreadName.cpp.

References folly::Range< Iter >::data(), kMaxThreadNameLength, folly::Range< Iter >::size(), folly::Range< Iter >::str(), and folly::Range< Iter >::subpiece().

Referenced by folly::ThreadedRepeatingFunctionRunner::add(), folly::ThreadedExecutor::control(), folly::observer_detail::ObserverManager::CurrentQueue::CurrentQueue(), folly::AsyncFileWriter::ioThread(), folly::EventBase::loopBody(), folly::NamedThreadFactory::newThread(), run(), folly::FunctionScheduler::run(), folly::EventBase::setName(), setThreadName(), proxygen::ScopedHTTPServer::start(), wangle::LRUPersistentCache< K, V, MutexT >::syncThreadMain(), and TEST().

109  {
110  auto trimmedName = name.subpiece(0, kMaxThreadNameLength - 1).str();
111 #if _WIN32
112  static_assert(
113  sizeof(unsigned int) == sizeof(std::thread::id),
114  "This assumes std::thread::id is a thin wrapper around "
115  "the thread id as an unsigned int, but that doesn't appear to be true.");
116 
117 // http://msdn.microsoft.com/en-us/library/xcb2z8hs.aspx
118 #pragma pack(push, 8)
119  struct THREADNAME_INFO {
120  DWORD dwType; // Must be 0x1000
121  LPCSTR szName; // Pointer to name (in user address space)
122  DWORD dwThreadID; // Thread ID (-1 for caller thread)
123  DWORD dwFlags; // Reserved for future use; must be zero
124  };
125  union TNIUnion {
126  THREADNAME_INFO tni;
127  ULONG_PTR upArray[4];
128  };
129 #pragma pack(pop)
130 
131  static constexpr DWORD kMSVCException = 0x406D1388;
132 
133  // std::thread::id is a thin wrapper around an integral thread id,
134  // so just extract the ID.
135  unsigned int id;
136  std::memcpy(&id, &tid, sizeof(id));
137 
138  TNIUnion tniUnion = {0x1000, trimmedName.data(), id, 0};
139  // This has to be in a separate stack frame from trimmedName, which requires
140  // C++ object destruction semantics.
141  return [&]() {
142  __try {
143  RaiseException(kMSVCException, 0, 4, tniUnion.upArray);
144  } __except (
145  GetExceptionCode() == kMSVCException ? EXCEPTION_CONTINUE_EXECUTION
146  : EXCEPTION_EXECUTE_HANDLER) {
147  // Swallow the exception when a debugger isn't attached.
148  }
149  return true;
150  }();
151 #else
152  name = name.subpiece(0, kMaxThreadNameLength - 1);
153  char buf[kMaxThreadNameLength] = {};
154  std::memcpy(buf, name.data(), name.size());
155  auto id = stdTidToPthreadId(tid);
156 #if FOLLY_HAS_PTHREAD_SETNAME_NP_THREAD_NAME
157  return 0 == pthread_setname_np(id, buf);
158 #elif FOLLY_HAS_PTHREAD_SETNAME_NP_NAME
159  // Since macOS 10.6 and iOS 3.2 it is possible for a thread to set its own
160  // name, but not that of some other thread.
161  if (pthread_equal(pthread_self(), id)) {
162  return 0 == pthread_setname_np(buf);
163  }
164  return false;
165 #else
166  (void)id;
167  return false;
168 #endif
169 #endif
170 }
const char * name
Definition: http_parser.c:437
static constexpr size_t kMaxThreadNameLength
Definition: ThreadName.cpp:88
bool folly::setThreadName ( pthread_t  pid,
StringPiece  name 
)

Definition at line 172 of file ThreadName.cpp.

References setThreadName(), and value.

172  {
173 #if _WIN32
174  static_assert(
175  sizeof(unsigned int) == sizeof(std::thread::id),
176  "This assumes std::thread::id is a thin wrapper around "
177  "the thread id as an unsigned int, but that doesn't appear to be true.");
178 
179  // std::thread::id is a thin wrapper around an integral thread id,
180  // so just stick the ID in.
181  unsigned int tid = pthread_getw32threadid_np(pid);
182  std::thread::id id;
183  std::memcpy(&id, &tid, sizeof(id));
184  return setThreadName(id, name);
185 #else
186  static_assert(
188  "This assumes that the native handle type is pthread_t");
189  static_assert(
190  sizeof(std::thread::native_handle_type) == sizeof(std::thread::id),
191  "This assumes std::thread::id is a thin wrapper around "
192  "std::thread::native_handle_type, but that doesn't appear to be true.");
193  // In most implementations, std::thread::id is a thin wrapper around
194  // std::thread::native_handle_type, which means we can do unsafe things to
195  // extract it.
196  std::thread::id id;
197  std::memcpy(static_cast<void*>(&id), &pid, sizeof(id));
198  return setThreadName(id, name);
199 #endif
200 }
bool setThreadName(StringPiece name)
Definition: ThreadName.cpp:202
const char * name
Definition: http_parser.c:437
static const char *const value
Definition: Conv.cpp:50
bool folly::setThreadName ( StringPiece  name)

Equivalent to setThreadName(std::this_thread::get_id(), name);

Definition at line 202 of file ThreadName.cpp.

References setThreadName().

202  {
203  return setThreadName(std::this_thread::get_id(), name);
204 }
bool setThreadName(StringPiece name)
Definition: ThreadName.cpp:202
const char * name
Definition: http_parser.c:437
void folly::setupSSLLocks ( )

Definition at line 26 of file SSLContextInitializationTest.cpp.

References folly::ssl::NONE, folly::ssl::setLockTypes(), and folly::ssl::SPINLOCK.

Referenced by TEST().

26  {
28 #ifdef CRYPTO_LOCK_EVP_PKEY
29  {CRYPTO_LOCK_EVP_PKEY, folly::ssl::LockType::NONE},
30 #endif
31 #ifdef CRYPTO_LOCK_SSL_SESSION
32  {CRYPTO_LOCK_SSL_SESSION, folly::ssl::LockType::SPINLOCK},
33 #endif
34 #ifdef CRYPTO_LOCK_SSL_CTX
35  {CRYPTO_LOCK_SSL_CTX, folly::ssl::LockType::NONE}
36 #endif
37  });
38 }
void setLockTypes(LockTypeMapping inLockTypes)
Definition: Init.cpp:76
template<class... Args>
std::string folly::sformat ( StringPiece  fmt,
Args &&...  args 
)
inline

Like format(), but immediately returns the formatted string instead of an intermediate format object.

Definition at line 280 of file Format.h.

References format().

Referenced by folly::NestedCommandLineApp::addCommand(), detail::addHashBenchmark(), folly::dynamic::at(), folly::dynamic::atImpl(), BENCHMARK(), BENCHMARK_RELATIVE(), folly::ssl::OpenSSLHash::check_out_size_throw(), folly::fibers::detail::createABDTokenNotDispatchedExMsg(), folly::fibers::detail::createUnexpectedNumResultsABDUsageExMsg(), folly::observer_detail::ObserverManager::CurrentQueue::CurrentQueue(), TestExtendingFormatter< containerMode, Args >::doFormatArg(), folly::NestedCommandLineApp::doRun(), folly::detail::familyNameStrDefault(), folly::NestedCommandLineApp::findCommand(), folly::LogStreamProcessor::formatLogString(), folly::CustomLogFormatter::formatMessage(), folly::IPAddressV4::fromInverseArpaName(), folly::IPAddressV6::fromInverseArpaName(), folly::SocketAddress::getAddrInfo(), getExe(), folly::SocketAddress::getIpString(), folly::IPAddressV6::getIPv4For6To4(), folly::AsyncSocketException::getMessage(), folly::detail::getNthMSBitImplThrow(), folly::IPAddressV4::getNthMSByte(), folly::IPAddressV6::getNthMSByte(), folly::detail::handleMallctlError(), proxygen::hexStr(), folly::IPAddressV4::inSubnet(), folly::IPAddressV6::inSubnet(), folly::detail::Bytes::longestCommonPrefix(), folly::IPAddressV4::mask(), folly::IPAddressV6::mask(), TryWriteUntilCaller< Q, Clock, Duration >::methodName(), operator<(), folly::MacAddress::parse(), parseLeadingNumber(), producerConsumerBench(), FileServerHandler::read(), FileServerHandler::readException(), fizz::FizzUtil::readPrivateKey(), folly::NestedCommandLineApp::run(), folly::MacAddress::setFromBinary(), wangle::ContextImplBase< H, InboundHandlerContext< H::rout > >::setNextIn(), wangle::ContextImplBase< H, InboundHandlerContext< H::rout > >::setNextOut(), folly::detail::shellify(), folly::detail::singletonThrowNullCreator(), folly::IPAddressV6::str(), TEST(), fizz::client::test::TEST_F(), wangle::TEST_F(), testCmp(), folly::AsyncSSLSocket::timeoutExpired(), folly::AsyncSocket::timeoutExpired(), toAppend(), folly::IPAddressV4::toInverseArpaName(), folly::IPAddressV6::toInverseArpaName(), folly::IPAddressV4::toJson(), folly::IPAddressV6::toJson(), folly::IPAddressV4::toLong(), and validateTestCertBundle().

280  {
281  return format(fmt, std::forward<Args>(args)...).str();
282 }
std::enable_if< IsSomeString< Str >::value >::type format(Str *out, StringPiece fmt, Args &&...args)
Definition: Format.h:369
template<class... Args>
std::string folly::sformatChecked ( StringPiece  fmt,
Args &&...  args 
)
inline

Definition at line 469 of file Format.h.

References formatChecked().

469  {
470  return formatChecked(fmt, std::forward<Args>(args)...).str();
471 }
std::enable_if< IsSomeString< Str >::value >::type formatChecked(Str *out, StringPiece fmt, Args &&...args)
Definition: Format.h:484
template<typename... Arguments>
std::vector<std::string> folly::shellify ( StringPiece  format,
Arguments &&...  arguments 
)

Create argument array for Subprocess() for a process running in a shell.

The shell to use is always going to be /bin/sh.

This is deprecated in favour of the user-defined-literal _shellify from namespace folly::shell_literals because that requires that the format string is a compile-time constant which can be inspected during code reviews

Definition at line 88 of file Shell.h.

References folly::detail::shellify().

Referenced by folly::detail::ShellCmdFormat::operator()(), and TEST().

90  {
91  return detail::shellify(format, std::forward<Arguments>(arguments)...);
92 }
std::vector< std::string > shellify(StringPiece format, Arguments &&...arguments)
Definition: Shell.h:88
Formatter< false, Args... > format(StringPiece fmt, Args &&...args)
Definition: Format.h:271
std::string folly::shellQuote ( StringPiece  argument)

Quotes an argument to make it suitable for use as shell command arguments.

Definition at line 21 of file Shell.cpp.

References c, and string.

Referenced by folly::detail::shellify(), and TEST().

21  {
22  std::string quoted = "'";
23  for (auto c : argument) {
24  if (c == '\'') {
25  quoted += "'\\''";
26  } else {
27  quoted += c;
28  }
29  }
30  return quoted + "'";
31 }
const char * string
Definition: Conv.cpp:212
char c
void folly::shutdown ( TLRefCount c)

Definition at line 26 of file RefCountBenchmark.cpp.

References c, and folly::TLRefCount::useGlobal().

26  {
27  c.useGlobal();
28  --c;
29 }
char c
int folly::shutdownNoInt ( int  fd,
int  how 
)
inline
int folly::shutdownNoInt ( NetworkSocket  fd,
int  how 
)

Definition at line 98 of file FileUtil.cpp.

References folly::netops::shutdown(), and folly::fileutil_detail::wrapNoInt().

Referenced by folly::ShutdownSocketSet::doShutdown(), shutdownNoInt(), and folly::AsyncServerSocket::stopAccepting().

98  {
99  return int(wrapNoInt(netops::shutdown, fd, how));
100 }
ssize_t wrapNoInt(F f, Args...args)
void shutdown(Counter &)
template<typename C >
constexpr auto folly::size ( C const &  c) -> decltype(c.size())

Definition at line 45 of file Access.h.

References c.

Referenced by folly::Range< unsigned char * >::advance(), alignedForwardMemcpy(), folly::Arena< SysAllocator< void > >::allocate(), folly::fibers::Fiber::LocalData::allocateHeapBuffer(), folly::Arena< Alloc >::allocateSlow(), folly::basic_fbstring< E, T, A, Storage >::append(), testing::internal::ArrayEq(), folly::basic_fbstring< E, T, A, Storage >::assign(), folly::Range< unsigned char * >::at(), folly::small_vector< Observer< T > *, InlineObservers >::at(), folly::basic_fbstring< char >::at(), folly::Uri::authority(), folly::BasicFixedString< Char, N >::BasicFixedString(), BENCHMARK(), benchmarkGet(), benchmarkSet(), folly::fibers::StackCache::borrow(), folly::bser::bserEncodeInt(), folly::ssl::OpenSSLHash::check_out_size(), checkTracepointArguments(), clause11_21_4_2_j(), clause11_21_4_2_k(), folly::IOBuf::cloneOneInto(), folly::Range< unsigned char * >::compare(), folly::basic_fbstring< char >::compare(), fizz::ZlibCertificateCompressor::compress(), constexpr_find_first_set(), folly::basic_fbstring< char >::copy(), testing::internal::CopyArray(), folly::IOBuf::copyBuffer(), folly::fbstring_core< Char >::copyLarge(), folly::fbstring_core< Char >::copySmall(), folly::detail::SkipListNode< T >::create(), folly::fbstring_core< Char >::RefCounted::create(), folly::io::test::DataHolder::data(), deallocateBytes(), folly::bser::decodeArray(), proxygen::HPACKDecodeBuffer::decodeLiteral(), folly::bser::decodeObject(), folly::bser::decodeTemplate(), fizz::ZlibCertificateDecompressor::decompress(), demangle(), folly::detail::SkipListNode< T >::destroy(), folly::detail::digits_to(), doEmptyHeaderValueTest(), folly::small_vector< Observer< T > *, InlineObservers >::emplace_back(), folly::detail::ConcurrentHashMapSegment< KeyType, ValueType, ShardBits, HashFn, KeyEqual, Allocator, Atom, Mutex >::empty(), folly::AtomicHashArray< KeyT, ValueT, HashFcn, EqualFcn, Allocator, ProbeFcn, KeyConvertFcn >::empty(), folly::AtomicHashMap< int64_t, int64_t >::empty(), folly::small_vector< Observer< T > *, InlineObservers >::empty(), folly::basic_fbstring< char >::empty(), proxygen::HPACKEncodeBuffer::encodeHuffman(), encryptGCM(), folly::small_vector< Observer< T > *, InlineObservers >::end(), folly::Range< unsigned char * >::endsWith(), folly::Range< unsigned char * >::equals(), folly::small_vector< Observer< T > *, InlineObservers >::erase(), folly::basic_fbstring< char >::erase(), folly::fbstring_core< Char >::expandNoinit(), folly::dummy_fbstring_core< Char >::expandNoinit(), folly::fbstring_core< char >::fbstring_core(), folly::Range< unsigned char * >::find(), folly::basic_fbstring< E, T, A, Storage >::find(), folly::Range< unsigned char * >::find_first_of(), folly::basic_fbstring< E, T, A, Storage >::find_last_not_of(), findLastSet(), folly::Fingerprint< BITS >::Fingerprint(), folly::for_each_detail::for_each_tuple_impl(), folly::io::RWCursor< access >::gatherAtMost(), proxygen::HTTPCodec::generateConnectionPreface(), proxygen::HTTP2Codec::generateHeaderImpl(), proxygen::HTTP2Codec::generateTrailers(), folly::fibers::Fiber::LocalData::get(), get_rand_str(), proxygen::huffman::HuffTree::getEncodeSize(), proxygen::HTTP2Codec::getHeaderIndexingStrategy(), folly::basic_fbstring< E, T, A, Storage >::getlineImpl(), proxygen::Window::getNonNegativeSize(), folly::BlockingQueue< folly::CPUThreadPoolExecutor::CPUTask >::getNumPriorities(), proxygen::HTTPArchive::getSize(), getSynStream(), testing::TestPartResultArray::GetTestPartResult(), proxygen::HTTP2Codec::getUserAgent(), folly::ArenaAllocatorTraits< Alloc >::goodSize(), folly::io::test::DataHolder::hash(), folly::Range< unsigned char * >::hash(), folly::ssl::OpenSSLHash::Digest::hash_final(), folly::ssl::OpenSSLHash::Hmac::hash_final(), i64ToStringFollyMeasureNeg(), i64ToStringFollyMeasurePos(), folly::MemoryMapping::init(), proxygen::HTTPCommonHeaders::initHeaderNames(), folly::fbstring_core< Char >::initLarge(), folly::fbstring_core< Char >::initMedium(), folly::AtomicHashMap< int64_t, int64_t >::insert(), folly::small_vector< Observer< T > *, InlineObservers >::insert(), folly::small_vector< Observer< T > *, InlineObservers >::insertImpl(), folly::basic_fbstring< E, T, A, Storage >::insertImpl(), folly::basic_fbstring< E, T, A, Storage >::insertImplDiscr(), folly::detail::internalJoin(), folly::detail::MPMCQueueBase< Derived< T, Atom, Dynamic > >::isEmpty(), folly::detail::MPMCQueueBase< Derived< T, Atom, Dynamic > >::isFull(), isSane(), folly::basic_fbstring< char >::isSane(), folly::test::IovecBuffers::join(), folly::basic_fbstring< char >::length(), folly::small_vector< Observer< T > *, InlineObservers >::makeSize(), folly::AsyncSSLSocketWriteTest::makeVec(), testing::internal::SizeIsMatcher< SizeMatcher >::Impl< Container >::MatchAndExplain(), proxygen::MATCHER_P(), testing::internal::NoDefaultContructor::NoDefaultContructor(), proxygen::HTTPSession::numIncomingStreams(), folly::IOBuf::operator new(), folly::fibers::FiberManager::FibersPoolResizer::operator()(), operator<<(), folly::StringKeyedMap< Value, Compare, Alloc >::operator=(), folly::StringKeyedSetBase< Compare, Alloc >::operator=(), folly::F14VectorSet< Key, Hasher, KeyEqual, Alloc >::operator=(), folly::F14VectorMap< Key, Mapped, Hasher, KeyEqual, Alloc >::operator=(), folly::basic_fbstring< E, T, A, Storage >::operator=(), folly::small_vector< Observer< T > *, InlineObservers >::operator==(), testing::internal::NativeArray< Element >::operator==(), folly::Range< unsigned char * >::operator[](), folly::small_vector< Observer< T > *, InlineObservers >::operator[](), proxygen::PassThroughHTTPCodecFilter::PassThroughHTTPCodecFilter(), fizz::passwordCallback(), folly::AsyncFileWriter::performIO(), preallocate_postallocate_bench(), folly::FileWriterFactory::processOption(), randomBinaryString(), randomString(), folly::Range< unsigned char * >::Range(), fizz::detail::Reader< ServerName >::read(), folly::test::MockReadCallback::readDataAvailable(), proxygen::readFileToIOBuf(), folly::test::CaptureFD::readIncremental(), readNote(), folly::JemallocNodumpAllocator::reallocate(), folly::basic_fbstring< char >::replace(), folly::basic_fbstring< E, T, A, Storage >::replaceAliased(), folly::Range< unsigned char * >::replaceAt(), reserve(), folly::fbstring_core< Char >::reserveSmall(), folly::Range< unsigned char * >::reset(), folly::small_vector< Observer< T > *, InlineObservers >::resize(), folly::basic_fbstring< E, T, A, Storage >::resize(), proxygen::HTTPTransaction::resumeIngress(), runBenchmarks(), proxygen::HTTPTransaction::sendAbort(), proxygen::HTTPSession::sendHeaders(), proxygen::HTTPTransaction::sendHeadersWithOptionalEOM(), proxygen::HTTPSession::sendSettings(), proxygen::Window::setCapacity(), wangle::LoadShedConfiguration::setCpuUsageExceedWindowSize(), proxygen::HTTPMessage::setIngressHeaderSize(), folly::AsyncFileWriter::setMaxBufferSize(), fizz::EncryptedWriteRecordLayer::setMaxRecord(), fizz::EncryptedWriteRecordLayer::setMinDesiredRecord(), setNumbers(), folly::fbstring_core< char >::setSmallSize(), proxygen::ServiceConfiguration::setWriteBufferLimit(), folly::dummy_fbstring_core< Char >::shrink(), folly::basic_fbstring< char >::shrink_to_fit(), testing::internal::ShuffleRange(), sizeCtor(), folly::io::test::CompressionTest::split(), folly::Range< unsigned char * >::split_step(), folly::SSLContext::sslAcceptRunner(), folly::Range< unsigned char * >::startsWith(), folly::detail::str_to_floating(), stringPieceDup(), folly::Range< unsigned char * >::subpiece(), folly::basic_fbstring< char >::substr(), folly::Range< unsigned char * >::subtract(), proxygen::HTTP1xCodec::supportsPushTransactions(), proxygen::SPDYCodec::supportsPushTransactions(), folly::small_vector< Observer< T > *, InlineObservers >::swap(), folly::IOBuf::takeOwnership(), fizz::test::TEST(), TEST(), TEST(), testing::internal::TEST(), TEST_F(), proxygen::TEST_P(), testing::gmock_matchers_test::TEST_P(), testing::TestPartResultArray::TestPartResultArray(), to(), folly::basic_fbstring< char >::toStdString(), folly::detail::GroupVarintBase< T >::totalSize(), proxygen::HTTPTransactionTransportCallback::trackedByteFlushed(), type_pretty_name(), u64ToStringClibMeasure(), u64ToStringFollyMeasure(), folly::Range< unsigned char * >::uncheckedAdvance(), folly::Range< unsigned char * >::uncheckedSubpiece(), folly::Range< unsigned char * >::uncheckedSubtract(), unhexlify(), verify(), folly::f14::detail::F14BasicSet< Key, Hasher, KeyEqual, Alloc >::visitAllocationClasses(), folly::f14::detail::F14BasicMap< Key, Mapped, Hasher, KeyEqual, Alloc >::visitAllocationClasses(), folly::IndexedMemPool< T, NumLocalLists_, LocalListLimit_, Atom, Traits >::TaggedPtr::withSizeDecr(), folly::IndexedMemPool< T, NumLocalLists_, LocalListLimit_, Atom, Traits >::TaggedPtr::withSizeIncr(), folly::IOBuf::wrapBufferAsValue(), folly::Fingerprint< BITS >::write(), fizz::client::AsyncFizzClientT< SM >::writeAppData(), folly::test::MockWriteCallback::writeErr(), folly::Fingerprint< BITS >::xortab(), testing::internal::GTestFlagSaver::~GTestFlagSaver(), proxygen::huffman::HuffTree::~HuffTree(), proxygen::HeaderCodec::Stats::~Stats(), and proxygen::HTTPTransaction::Transport::~Transport().

45  {
46  return c.size();
47 }
char c
template<typename T , std::size_t N>
constexpr std::size_t folly::size ( T const   (&)[N])
noexcept

Definition at line 49 of file Access.h.

49  {
50  return N;
51 }
folly::std enable_if::typetoAppendDelimStrImpl const Delimiter, const Tv, Tgtresult folly::sizeof ( Ts  )
StringPiece folly::skipWhitespace ( StringPiece  sp)
inline

Returns a subpiece with all whitespace removed from the front of . Whitespace means any of [' ', '
', '', '']. DEPRECATED:

See also
ltrimWhitespace
rtrimWhitespace

Definition at line 577 of file String.h.

References ltrimWhitespace(), s, string, stripLeftMargin(), and toLowerAscii().

577  {
578  return ltrimWhitespace(sp);
579 }
StringPiece ltrimWhitespace(StringPiece sp)
Definition: String.cpp:131
void* folly::smartRealloc ( void *  p,
const size_t  currentSize,
const size_t  currentCapacity,
const size_t  newCapacity 
)
inline

This function tries to reallocate a buffer of which only the first currentSize bytes are used. The problem with using realloc is that if currentSize is relatively small and if realloc decides it needs to move the memory chunk to a new buffer, then realloc ends up copying data that is not used. It's generally not a win to try to hook in to realloc() behavior to avoid copies - at least in jemalloc, realloc() almost always ends up doing a copy, because there is little fragmentation / slack space to take advantage of.

Definition at line 261 of file Malloc.h.

References checkedMalloc(), checkedRealloc(), and bm::free().

Referenced by folly::fbstring_core< Char >::RefCounted::reallocate(), and folly::fbstring_core< Char >::reserveMedium().

265  {
266  assert(p);
267  assert(currentSize <= currentCapacity &&
268  currentCapacity < newCapacity);
269 
270  auto const slack = currentCapacity - currentSize;
271  if (slack * 2 > currentSize) {
272  // Too much slack, malloc-copy-free cycle:
273  auto const result = checkedMalloc(newCapacity);
274  std::memcpy(result, p, currentSize);
275  free(p);
276  return result;
277  }
278  // If there's not too much slack, we realloc in hope of coalescing
279  return checkedRealloc(p, newCapacity);
280 }
void * checkedMalloc(size_t size)
Definition: Malloc.h:227
void free()
void * checkedRealloc(void *ptr, size_t size)
Definition: Malloc.h:243
template<class T >
Future<T> folly::someFuture ( )

Definition at line 36 of file ThenCompileTest.h.

References makeFuture(), and T.

36  {
37  return makeFuture(T());
38 }
#define T(v)
Definition: http_parser.c:233
Future< typename std::decay< T >::type > makeFuture(T &&t)
Definition: Future-inl.h:1310
template<class Delim , class String , class OutputType >
void folly::split ( const Delim &  delimiter,
const String &  input,
fbvector< OutputType > &  out,
bool  ignoreEmpty 
)

Definition at line 395 of file String-inl.h.

References folly::detail::prepareDelim().

399  {
400  detail::internalSplit<OutputType>(
401  detail::prepareDelim(delimiter),
402  StringPiece(input),
403  std::back_inserter(out),
404  ignoreEmpty);
405 }
char prepareDelim(char c)
Definition: String-inl.h:331
Range< const char * > StringPiece
template<bool exact, class Delim , class... OutputTypes>
bool::type folly::split ( const Delim &  delimiter,
StringPiece  input,
OutputTypes &...  outputs 
)

Definition at line 426 of file String-inl.h.

References folly::detail::prepareDelim().

426  {
427  return detail::splitFixed<exact>(
428  detail::prepareDelim(delimiter), input, outputs...);
429 }
char prepareDelim(char c)
Definition: String-inl.h:331
template<class T >
FutureSplitter<T> folly::splitFuture ( Future< T > &&  future)

Convenience function, allowing us to exploit template argument deduction to improve readability.

Definition at line 99 of file FutureSplitter.h.

References folly::gen::move.

99  {
100  return FutureSplitter<T>{std::move(future)};
101 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<class OutputValueType , class Delim , class String , class OutputIterator >
void folly::splitTo ( const Delim &  delimiter,
const String &  input,
OutputIterator  out,
bool  ignoreEmpty 
)

Definition at line 412 of file String-inl.h.

References folly::detail::prepareDelim(), type, and value().

416  {
417  detail::internalSplit<OutputValueType>(
418  detail::prepareDelim(delimiter), StringPiece(input), out, ignoreEmpty);
419 }
char prepareDelim(char c)
Definition: String-inl.h:331
Range< const char * > StringPiece
void folly::sslsocketpair ( EventBase eventBase,
AsyncSSLSocket::UniquePtr clientSock,
AsyncSSLSocket::UniquePtr serverSock 
)

Definition at line 141 of file AsyncSSLSocketTest.cpp.

References getctx(), and getfds().

Referenced by folly::TestSSLAsyncCacheServer::getSessionCallback().

144  {
145  auto clientCtx = std::make_shared<folly::SSLContext>();
146  auto serverCtx = std::make_shared<folly::SSLContext>();
147  int fds[2];
148  getfds(fds);
149  getctx(clientCtx, serverCtx);
150  clientSock->reset(new AsyncSSLSocket(clientCtx, eventBase, fds[0], false));
151  serverSock->reset(new AsyncSSLSocket(serverCtx, eventBase, fds[1], true));
152 
153  // (*clientSock)->setSendTimeout(100);
154  // (*serverSock)->setSendTimeout(100);
155 }
void getfds(int fds[2])
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
template<class T >
void folly::storeUnaligned ( void *  p,
T  value 
)
inline

Write an unaligned value of type T.

Definition at line 352 of file Bits.h.

References assume(), kHasUnalignedAccess, and T.

Referenced by folly::io::QueueAppender::write(), and folly::io::QueueAppender::writeSlow().

352  {
353  static_assert(sizeof(Unaligned<T>) == sizeof(T), "Invalid unaligned size");
354  static_assert(alignof(Unaligned<T>) == 1, "Invalid alignment");
355  if (kHasUnalignedAccess) {
356  // Prior to C++14, the spec says that a placement new like this
357  // is required to check that p is not nullptr, and to do nothing
358  // if p is a nullptr. By assuming it's not a nullptr, we get a
359  // nice loud segfault in optimized builds if p is nullptr, rather
360  // than just silently doing nothing.
361  assume(p != nullptr);
362  new (p) Unaligned<T>(value);
363  } else {
364  memcpy(p, &value, sizeof(T));
365  }
366 }
constexpr bool kHasUnalignedAccess
Definition: Portability.h:29
#define T(v)
Definition: http_parser.c:233
static const char *const value
Definition: Conv.cpp:50
FOLLY_ALWAYS_INLINE void assume(bool cond)
Definition: Assume.h:41
template<typename RefCount >
void folly::stressTest ( size_t  itersCount)

Definition at line 85 of file RefCountTest.cpp.

References a, count, EXPECT_EQ, i, and mutex.

85  {
86  for (size_t i = 0; i < itersCount; ++i) {
87  RefCount count;
89  int a{1};
90 
91  std::thread t1([&]() {
92  if (++count) {
93  {
94  std::lock_guard<std::mutex> lg(mutex);
95  EXPECT_EQ(1, a);
96  }
97  --count;
98  }
99  });
100 
101  std::thread t2([&]() {
102  count.useGlobal();
103  if (--count == 0) {
104  std::lock_guard<std::mutex> lg(mutex);
105  a = 0;
106  }
107  });
108 
109  t1.join();
110  t2.join();
111 
112  EXPECT_EQ(0, ++count);
113  }
114 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
char a
int * count
std::mutex mutex
std::string void std::string& folly::stringAppendf ( std::string output,
FOLLY_PRINTF_FORMAT const char *  format,
  ... 
)
std::string& folly::stringAppendf ( std::string output,
const char *  format,
  ... 
)

Definition at line 240 of file String.cpp.

References SCOPE_EXIT, string, and stringVAppendf().

Referenced by BENCHMARK(), TEST(), and uriUnescape().

240  {
241  va_list ap;
242  va_start(ap, format);
243  SCOPE_EXIT {
244  va_end(ap);
245  };
246  return stringVAppendf(output, format, ap);
247 }
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
std::string & stringVAppendf(std::string *output, const char *format, va_list ap)
Definition: String.cpp:250
Formatter< false, Args... > format(StringPiece fmt, Args &&...args)
Definition: Format.h:271
template<class Alloc >
void folly::stringPieceDel ( StringPiece  piece,
const Alloc alloc 
)
template<class Alloc >
StringPiece folly::stringPieceDup ( StringPiece  piece,
const Alloc alloc 
)

Definition at line 28 of file StringKeyedCommon.h.

References folly::Range< Iter >::data(), size(), and folly::Range< Iter >::size().

Referenced by folly::StringKeyedSetBase< Compare, Alloc >::emplace(), folly::StringKeyedMap< Value, Compare, Alloc >::emplace(), folly::StringKeyedSetBase< Compare, Alloc >::insert(), folly::StringKeyedMap< Value, Compare, Alloc >::insert(), and folly::StringKeyedMap< Value, Compare, Alloc >::operator[]().

28  {
29  auto size = piece.size();
30  auto keyDup =
31  typename Alloc::template rebind<char>::other(alloc).allocate(size);
32  if (size) {
33  memcpy(
34  keyDup, piece.data(), size * sizeof(typename StringPiece::value_type));
35  }
36  return StringPiece(keyDup, size);
37 }
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
Range< const char * > StringPiece
std::string folly::stringPrintf ( FOLLY_PRINTF_FORMAT const char *  format,
  ... 
)

stringPrintf is much like printf but deposits its result into a string. Two signatures are supported: the first simply returns the resulting string, and the second appends the produced characters to the specified string and returns a reference to it.

std::string void folly::stringPrintf ( std::string out,
FOLLY_PRINTF_FORMAT const char *  fmt,
  ... 
)
std::string folly::stringPrintf ( const char *  format,
  ... 
)

Definition at line 223 of file String.cpp.

References SCOPE_EXIT, and stringVPrintf().

Referenced by wangle::SSLContextManager::addSSLContextConfig(), wangle::SSLContextManager::getSSLCtxByExactDomain(), wangle::SSLContextManager::getSSLCtxBySuffix(), humanReadable(), wangle::SSLContextManager::insertSSLCtxByDomainNameImpl(), stringPrintfOutputSize(), TEST(), and uriUnescape().

223  {
224  va_list ap;
225  va_start(ap, format);
226  SCOPE_EXIT {
227  va_end(ap);
228  };
229  return stringVPrintf(format, ap);
230 }
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
Formatter< false, Args... > format(StringPiece fmt, Args &&...args)
Definition: Format.h:271
void stringVPrintf(std::string *output, const char *format, va_list ap)
Definition: String.cpp:264
void folly::stringPrintf ( std::string output,
const char *  format,
  ... 
)

Definition at line 255 of file String.cpp.

References SCOPE_EXIT, and stringVPrintf().

255  {
256  va_list ap;
257  va_start(ap, format);
258  SCOPE_EXIT {
259  va_end(ap);
260  };
261  return stringVPrintf(output, format, ap);
262 }
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
Formatter< false, Args... > format(StringPiece fmt, Args &&...args)
Definition: Format.h:271
void stringVPrintf(std::string *output, const char *format, va_list ap)
Definition: String.cpp:264
LogLevel folly::stringToLogLevel ( folly::StringPiece  name)

Construct a LogLevel from a string name.

Definition at line 42 of file LogLevel.cpp.

References folly::Range< Iter >::advance(), c, CRITICAL, DBG, DFATAL, ERR, FATAL, INFO, deadlock::info(), MAX_LEVEL, NONE, folly::Range< Iter >::size(), UNINITIALIZED, and WARN.

Referenced by folly::StandardLogHandlerFactory::createHandler(), operator-=(), and TEST().

42  {
43  string lowerNameStr;
44  lowerNameStr.reserve(name.size());
45  for (char c : name) {
46  lowerNameStr.push_back(static_cast<char>(std::tolower(c)));
47  }
48  StringPiece lowerName{lowerNameStr};
49 
50  // If the string is of the form "LogLevel::foo" or "LogLevel(foo)"
51  // strip it down just to "foo". This makes sure we can process both
52  // the "LogLevel::WARN" and "LogLevel(1234)" formats produced by
53  // logLevelToString().
54  constexpr StringPiece lowercasePrefix{"loglevel::"};
55  constexpr StringPiece wrapperPrefix{"loglevel("};
56  if (lowerName.startsWith(lowercasePrefix)) {
57  lowerName.advance(lowercasePrefix.size());
58  } else if (lowerName.startsWith(wrapperPrefix) && lowerName.endsWith(")")) {
59  lowerName.advance(wrapperPrefix.size());
60  lowerName.subtract(1);
61  }
62 
63  if (lowerName == "uninitialized") {
64  return LogLevel::UNINITIALIZED;
65  } else if (lowerName == "none") {
66  return LogLevel::NONE;
67  } else if (lowerName == "debug" || lowerName == "dbg") {
68  return LogLevel::DBG;
69  } else if (lowerName == "info") {
70  return LogLevel::INFO;
71  } else if (lowerName == "warn" || lowerName == "warning") {
72  return LogLevel::WARN;
73  } else if (lowerName == "error" || lowerName == "err") {
74  return LogLevel::ERR;
75  } else if (lowerName == "critical") {
76  return LogLevel::CRITICAL;
77  } else if (lowerName == "dfatal") {
78  return LogLevel::DFATAL;
79  } else if (lowerName == "fatal") {
80  return LogLevel::FATAL;
81  } else if (lowerName == "max" || lowerName == "max_level") {
82  return LogLevel::MAX_LEVEL;
83  }
84 
85  for (const auto& info : numberedLogLevels) {
86  if (!lowerName.startsWith(info.lowerPrefix)) {
87  continue;
88  }
89  auto remainder = lowerName.subpiece(info.lowerPrefix.size());
90  auto level = folly::tryTo<int>(remainder).value_or(-1);
91  if (level < 0 ||
92  static_cast<unsigned int>(level) > (static_cast<uint32_t>(info.max) -
93  static_cast<uint32_t>(info.min))) {
94  throw std::range_error(to<string>(
95  "invalid ", info.lowerPrefix, " logger level: ", name.str()));
96  }
97  return info.max - level;
98  }
99 
100  // Try as an plain integer if all else fails
101  try {
102  auto level = folly::to<uint32_t>(lowerName);
103  return static_cast<LogLevel>(level);
104  } catch (const std::exception&) {
105  throw std::range_error("invalid logger level: " + name.str());
106  }
107 }
def info()
Definition: deadlock.py:447
void advance(size_type n)
Definition: Range.h:672
constexpr size_type size() const
Definition: Range.h:431
LogLevel
Definition: LogLevel.h:38
Range< const char * > StringPiece
char c
std::string & folly::stringVAppendf ( std::string output,
const char *  format,
va_list  ap 
)

Definition at line 250 of file String.cpp.

References gmock_output_test::output.

Referenced by stringAppendf(), uriUnescape(), and vprintfCheck().

250  {
251  stringAppendfImpl(*output, format, ap);
252  return *output;
253 }
Formatter< false, Args... > format(StringPiece fmt, Args &&...args)
Definition: Format.h:271
std::string void std::string std::string folly::stringVPrintf ( const char *  format,
va_list  ap 
)

Similar to stringPrintf, but accepts a va_list argument.

As with vsnprintf() itself, the value of ap is undefined after the call. These functions do not call va_end() on ap.

Definition at line 232 of file String.cpp.

References string.

Referenced by loggingFormatPrintf(), stringPrintf(), uriUnescape(), vprintfCheck(), and vprintfError().

232  {
233  std::string ret;
234  stringAppendfImpl(ret, format, ap);
235  return ret;
236 }
const char * string
Definition: Conv.cpp:212
Formatter< false, Args... > format(StringPiece fmt, Args &&...args)
Definition: Format.h:271
void folly::stringVPrintf ( std::string output,
const char *  format,
va_list  ap 
)

Definition at line 264 of file String.cpp.

264  {
265  output->clear();
266  stringAppendfImpl(*output, format, ap);
267 }
Formatter< false, Args... > format(StringPiece fmt, Args &&...args)
Definition: Format.h:271
std::string folly::stripLeftMargin ( std::string  s)

Strips the leading and the trailing whitespace-only lines. Then looks for the least indented non-whitespace-only line and removes its amount of leading whitespace from every line. Assumes leading whitespace is either all spaces or all tabs.

Purpose: including a multiline string literal in source code, indented to the level expected from context.

Definition at line 704 of file String.cpp.

References c, join(), max, needle, range(), and split().

Referenced by skipWhitespace(), and TEST().

704  {
705  std::vector<StringPiece> pieces;
706  split("\n", s, pieces);
707  auto piecer = range(pieces);
708 
709  auto piece = (piecer.end() - 1);
710  auto needle = std::find_if(piece->begin(), piece->end(), [](char c) {
711  return c != ' ' && c != '\t';
712  });
713  if (needle == piece->end()) {
714  (piecer.end() - 1)->clear();
715  }
716  piece = piecer.begin();
717  needle = std::find_if(piece->begin(), piece->end(), [](char c) {
718  return c != ' ' && c != '\t';
719  });
720  if (needle == piece->end()) {
721  piecer.erase(piecer.begin(), piecer.begin() + 1);
722  }
723 
724  const auto sentinel = std::numeric_limits<size_t>::max();
725  auto indent = sentinel;
726  size_t max_length = 0;
727  for (piece = piecer.begin(); piece != piecer.end(); piece++) {
728  needle = std::find_if(piece->begin(), piece->end(), [](char c) {
729  return c != ' ' && c != '\t';
730  });
731  if (needle != piece->end()) {
732  indent = std::min<size_t>(indent, size_t(needle - piece->begin()));
733  } else {
734  max_length = std::max<size_t>(piece->size(), max_length);
735  }
736  }
737  indent = indent == sentinel ? max_length : indent;
738  for (piece = piecer.begin(); piece != piecer.end(); piece++) {
739  if (piece->size() < indent) {
740  piece->clear();
741  } else {
742  piece->erase(piece->begin(), piece->begin() + indent);
743  }
744  }
745  return join("\n", piecer);
746 }
const string needle
LogLevel max
Definition: LogLevel.cpp:31
Gen range(Value begin, Value end)
Definition: Base.h:467
S split(const StringPiece source, char delimiter)
Definition: String.h:61
#define join
static set< string > s
char c
size_t folly::strlcpy ( char *  dest,
const char *const  src,
size_t  size 
)

Definition at line 121 of file Demangle.cpp.

References min.

Referenced by demangle(), and TEST().

121  {
122  size_t len = strlen(src);
123  if (size != 0) {
124  size_t n = std::min(len, size - 1); // always null terminate!
125  memcpy(dest, src, n);
126  dest[n] = '\0';
127  }
128  return len;
129 }
dest
Definition: upload.py:394
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
LogLevel min
Definition: LogLevel.cpp:30
template<class Container >
std::string folly::svformat ( StringPiece  fmt,
Container &&  container 
)
inline

Like vformat(), but immediately returns the formatted string instead of an intermediate format object.

Definition at line 307 of file Format.h.

References vformat().

Referenced by TEST().

307  {
308  return vformat(fmt, std::forward<Container>(container)).str();
309 }
std::enable_if< IsSomeString< Str >::value >::type vformat(Str *out, StringPiece fmt, Container &&container)
Definition: Format.h:378
template<class Container >
std::string folly::svformatChecked ( StringPiece  fmt,
Container &&  container 
)
inline

Definition at line 479 of file Format.h.

References testing::Args(), type, value, and vformatChecked().

479  {
480  return vformatChecked(fmt, std::forward<Container>(container)).str();
481 }
std::enable_if< IsSomeString< Str >::value >::type vformatChecked(Str *out, StringPiece fmt, Container &&container)
Definition: Format.h:489
void folly::swap ( File a,
File b 
)
noexcept

Definition at line 102 of file File.cpp.

References a, and b.

Referenced by folly::File::swap().

102  {
103  a.swap(b);
104 }
char b
char a
template<template< typename > class Atom = std::atomic>
void folly::swap ( hazptr_holder< Atom > &  lhs,
hazptr_holder< Atom > &  rhs 
)
noexcept

Free function swap of hazptr_holder-s

Free function swap of hazptr_holder-s.

Definition at line 187 of file HazptrHolder.h.

References Atom, and folly::detail::rhs.

Referenced by folly::hazptr_holder< Atom >::swap().

189  {
190  lhs.swap(rhs);
191 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<template< typename > class Atom>
FOLLY_ALWAYS_INLINE void folly::swap ( hazptr_holder< Atom > &  lhs,
hazptr_holder< Atom > &  rhs 
)
noexcept

Free function swap of hazptr_holder-s.

Definition at line 187 of file HazptrHolder.h.

References Atom, and folly::detail::rhs.

Referenced by folly::hazptr_holder< Atom >::swap().

189  {
190  lhs.swap(rhs);
191 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename Pointer >
FOLLY_CPP14_CONSTEXPR void folly::swap ( propagate_const< Pointer > &  a,
propagate_const< Pointer > &  b 
)
noexcept

Definition at line 202 of file PropagateConst.h.

References a, and b.

204  {
205  a.swap(b);
206 }
char b
char a
void folly::swap ( MemoryMapping a,
MemoryMapping b 
)
noexcept

Definition at line 386 of file MemoryMapping.cpp.

References a, and b.

Referenced by folly::MemoryMapping::swap().

386  {
387  a.swap(b);
388 }
char b
char a
template<typename Tag = RcuTag>
void folly::swap ( rcu_reader_domain< Tag > &  a,
rcu_reader_domain< Tag > &  b 
)
inlinenoexcept

Definition at line 443 of file Rcu.h.

References a, and b.

Referenced by folly::rcu_reader_domain< Tag >::swap().

445  {
446  a.swap(b);
447 }
char b
char a
template<class T >
void folly::swap ( Optional< T > &  a,
Optional< T > &  b 
)
noexcept

Definition at line 445 of file Optional.h.

References a, and b.

Referenced by folly::Optional< NamedGroup >::swap().

445  {
446  a.swap(b);
447 }
char b
char a
template<class T , class C , class A , class G >
void folly::swap ( sorted_vector_set< T, C, A, G > &  a,
sorted_vector_set< T, C, A, G > &  b 
)
inline

Definition at line 579 of file sorted_vector_types.h.

References testing::Key(), folly::sorted_vector_set< T, Compare, Allocator, GrowthPolicy, Container >::swap(), and testing::Value().

581  {
582  return a.swap(b);
583 }
char b
char a
template<typename FunctionType >
void folly::swap ( Function< FunctionType > &  lhs,
Function< FunctionType > &  rhs 
)
noexcept

Definition at line 816 of file Function.h.

References folly::detail::rhs.

Referenced by folly::Function< std::vector< ResultT >(std::vector< InputT > &&)>::swap().

816  {
817  lhs.swap(rhs);
818 }
template<class K , class V , class C , class A , class G >
void folly::swap ( sorted_vector_map< K, V, C, A, G > &  a,
sorted_vector_map< K, V, C, A, G > &  b 
)
inline
template<class Iter >
void folly::swap ( Range< Iter > &  lhs,
Range< Iter > &  rhs 
)

Definition at line 1106 of file Range.h.

References folly::Range< Iter >::swap().

Referenced by folly::Range< unsigned char * >::swap().

1106  {
1107  lhs.swap(rhs);
1108 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class I >
void folly::swap ( Poly< I > &  left,
Poly< I > &  right 
)
noexcept

Swap two Poly<I> instances.

Definition at line 1139 of file Poly.h.

1139  {
1140  left.swap(right);
1141 }
template<class Value , class Error >
void folly::swap ( Expected< Value, Error > &  lhs,
Expected< Value, Error > &  rhs 
)
noexcept

swap Expected values

Definition at line 1368 of file Expected.h.

Referenced by folly::Expected< int, E >::swap().

1369  {
1370  lhs.swap(rhs);
1371 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class T , class M >
void folly::swap ( Synchronized< T, M > &  lhs,
Synchronized< T, M > &  rhs 
)

Definition at line 1656 of file Synchronized.h.

References folly::Synchronized< T, Mutex >::swap().

Referenced by folly::Synchronized< std::vector< detail::folly::detail::TypeDescriptor >, folly::SharedMutexImpl >::swap().

1656  {
1657  lhs.swap(rhs);
1658 }
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<class T , class A >
void folly::swap ( fbvector< T, A > &  lhs,
fbvector< T, A > &  rhs 
)
noexcept

Definition at line 1697 of file FBVector.h.

References folly::detail::rhs.

Referenced by folly::fbvector< HTTPHeaderCode >::swap(), and folly::fbvector< T, Allocator >::Impl::swapData().

1698  {
1699  lhs.swap(rhs);
FOLLY_PUSH_WARNING RHS rhs
Definition: Traits.h:649
template<typename E , class T , class A , class S >
void folly::swap ( basic_fbstring< E, T, A, S > &  lhs,
basic_fbstring< E, T, A, S > &  rhs 
)
template<class Char , std::size_t N>
FOLLY_CPP14_CONSTEXPR void folly::swap ( BasicFixedString< Char, N > &  a,
BasicFixedString< Char, N > &  b 
)
noexcept

Swap function

Definition at line 3000 of file FixedString.h.

References a, and b.

3002  {
3003  a.swap(b);
3004 }
char b
char a
template<typename Tag = RcuTag>
void folly::synchronize_rcu ( rcu_domain< Tag > *  domain = rcu_default_domain())
inlinenoexcept

Definition at line 450 of file Rcu.h.

Referenced by TEST().

451  {
452  domain->synchronize();
453 }
template<typename Func , typename... SynchronizedLockers>
decltype(auto) folly::synchronized ( Func &&  func,
SynchronizedLockers &&...  lockers 
)

Acquire locks for multiple Synchronized<> objects, in a deadlock-safe manner.

Wrap the synchronized instances with the appropriate locking strategy by using one of the four strategies - folly::lock (exclusive acquire for exclusive only mutexes), folly::rlock (shared acquire for shareable mutexes), folly::wlock (exclusive acquire for shareable mutexes) or folly::ulock (upgrade acquire for upgrade mutexes) (see above)

The locks will be acquired and the passed callable will be invoked with the LockedPtr instances in the order that they were passed to the function

Definition at line 1553 of file Synchronized.h.

References apply(), and lock().

1553  {
1554  return apply(
1555  std::forward<Func>(func),
1556  lock(std::forward<SynchronizedLockers>(lockers)...));
1557 }
void lock(LockableOne &one, LockableTwo &two, Lockables &...lockables)
decltype(auto) constexpr apply(F &&func, Tuple &&tuple)
Definition: ApplyTuple.h:87
template<typename Ex >
FOLLY_NOINLINE FOLLY_COLD void folly::terminate_with ( Ex &&  ex)
noexcept

terminate_with

Terminates as if by forwarding to throw_exception but in a noexcept context.

Definition at line 45 of file Exception.h.

References throw_exception().

45  {
46  throw_exception(static_cast<Ex&&>(ex));
47 }
FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN void throw_exception(Args &&...args)
Definition: Exception.h:80
template<typename Ex , typename... Args>
FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN void folly::terminate_with ( Args &&...  args)
noexcept

terminate_with

Terminates as if by forwarding to throw_exception but in a noexcept context.

Definition at line 91 of file Exception.h.

References folly::detail::to_exception_arg_().

91  {
92  detail::terminate_with_<Ex>(
93  detail::to_exception_arg_(static_cast<Args&&>(args))...);
94 }
FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN char const * to_exception_arg_(char const (&array)[N])
Definition: Exception.h:56
folly::TEST ( AsyncTimeout  ,
make   
)

Definition at line 23 of file AsyncTimeoutTest.cpp.

References EXPECT_EQ, folly::EventBase::loop(), folly::AsyncTimeout::make(), folly::pushmi::__adl::noexcept(), and value().

23  {
24  int value = 0;
25  int const expected = 10;
26  EventBase manager;
27 
28  auto observer =
29  AsyncTimeout::make(manager, [&]() noexcept { value = expected; });
30 
31  observer->scheduleTimeout(std::chrono::milliseconds(100));
32 
33  manager.loop();
34 
35  EXPECT_EQ(expected, value);
36 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
requires E e noexcept(noexcept(s.error(std::move(e))))
static const char *const value
Definition: Conv.cpp:50
folly::TEST ( makeMoveWrapper  ,
Empty   
)

Definition at line 25 of file MoveWrapperTest.cpp.

References makeMoveWrapper().

25  {
26  // checks for crashes
27  auto p = makeMoveWrapper(std::unique_ptr<int>());
28 }
MoveWrapper< T0 > makeMoveWrapper(T &&t)
Definition: MoveWrapper.h:82
folly::TEST ( WriteFlagsTest  ,
isSet   
)

Definition at line 25 of file WriteFlagsTest.cpp.

References ASSERT_FALSE, ASSERT_TRUE, isSet(), and uint32_t.

25  {
26  WriteFlags flags = WriteFlags::NONE;
27  ASSERT_FALSE(isSet(flags, WriteFlags::CORK));
28  ASSERT_FALSE(isSet(flags, WriteFlags::EOR));
29 
30  flags = WriteFlags::CORK;
31  ASSERT_TRUE(isSet(flags, WriteFlags::CORK));
32  ASSERT_FALSE(isSet(flags, WriteFlags::EOR));
33 
34  flags = static_cast<WriteFlags>(
35  static_cast<uint32_t>(WriteFlags::CORK) |
36  static_cast<uint32_t>(WriteFlags::EOR));
37  ASSERT_TRUE(isSet(flags, WriteFlags::CORK));
38  ASSERT_TRUE(isSet(flags, WriteFlags::EOR));
39 }
flags
Definition: http_parser.h:127
bool isSet(WriteFlags a, WriteFlags b)
#define ASSERT_FALSE(condition)
Definition: gtest.h:1868
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST ( Lazy  ,
Simple   
)

Definition at line 26 of file LazyTest.cpp.

References EXPECT_EQ, i, lazy(), and val.

26  {
27  int computeCount = 0;
28 
29  auto const val = folly::lazy([&]() -> int {
30  ++computeCount;
31  EXPECT_EQ(computeCount, 1);
32  return 12;
33  });
34  EXPECT_EQ(computeCount, 0);
35 
36  for (int i = 0; i < 100; ++i) {
37  if (i > 50) {
38  EXPECT_EQ(val(), 12);
39  EXPECT_EQ(computeCount, 1);
40  } else {
41  EXPECT_EQ(computeCount, 0);
42  }
43  }
44  EXPECT_EQ(val(), 12);
45  EXPECT_EQ(computeCount, 1);
46 }
auto lazy(Func &&fun)
Definition: Lazy.h:138
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
double val
Definition: String.cpp:273
folly::TEST ( LockFreeRingBuffer  ,
writeReadSequentially   
)

Definition at line 26 of file LockFreeRingBufferTest.cpp.

References ASSERT_EQ, ASSERT_TRUE, folly::LockFreeRingBuffer< T, Atom >::currentHead(), upload::dest, folly::LockFreeRingBuffer< T, Atom >::Cursor::moveForward(), folly::LockFreeRingBuffer< T, Atom >::tryRead(), val, folly::LockFreeRingBuffer< T, Atom >::write(), and fizz::detail::write().

26  {
27  const int capacity = 256;
28  const int turns = 4;
29 
30  LockFreeRingBuffer<int> rb(capacity);
31  LockFreeRingBuffer<int>::Cursor cur = rb.currentHead();
32  for (unsigned int turn = 0; turn < turns; turn++) {
33  for (unsigned int write = 0; write < capacity; write++) {
34  int val = turn * capacity + write;
35  rb.write(val);
36  }
37 
38  for (unsigned int write = 0; write < capacity; write++) {
39  int dest = 0;
40  ASSERT_TRUE(rb.tryRead(dest, cur));
41  ASSERT_EQ(turn * capacity + write, dest);
42  cur.moveForward();
43  }
44  }
45 }
void write(const T &in, folly::io::Appender &appender)
Definition: Types-inl.h:112
#define ASSERT_EQ(val1, val2)
Definition: gtest.h:1956
dest
Definition: upload.py:394
double val
Definition: String.cpp:273
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST ( AsyncTransportTest  ,
getSocketFromSocket   
)

Definition at line 27 of file AsyncTransportTest.cpp.

References ASSERT_EQ.

27  {
28  AsyncSocket::UniquePtr transport(new AsyncSocket());
29  auto sock = transport->getUnderlyingTransport<AsyncSocket>();
30  ASSERT_EQ(transport.get(), sock);
31 }
#define ASSERT_EQ(val1, val2)
Definition: gtest.h:1956
folly::TEST ( AsyncSocketTest  ,
getSockOpt   
)

Definition at line 29 of file AsyncSocketTest.cpp.

References EXPECT_EQ, folly::netops::getsockopt(), folly::AsyncSocket::newSocket(), folly::netops::socket(), and val.

29  {
30  EventBase evb;
31  std::shared_ptr<AsyncSocket> socket = AsyncSocket::newSocket(&evb, 0);
32 
33  int val;
34  socklen_t len;
35 
36  int expectedRc =
37  getsockopt(socket->getFd(), SOL_SOCKET, SO_REUSEADDR, &val, &len);
38  int actualRc = socket->getSockOpt(SOL_SOCKET, SO_REUSEADDR, &val, &len);
39 
40  EXPECT_EQ(expectedRc, actualRc);
41 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
double val
Definition: String.cpp:273
int getsockopt(NetworkSocket s, int level, int optname, void *optval, socklen_t *optlen)
Definition: NetOps.cpp:112
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
folly::TEST ( MemoryMapping  ,
Basic   
)

Definition at line 29 of file MemoryMappingTest.cpp.

References folly::MemoryMapping::asRange(), data(), EXPECT_EQ, f, folly::File::fd(), kSomeDouble, m, folly::File::temporary(), and folly::MemoryMapping::writable().

29  {
30  File f = File::temporary();
31  {
32  MemoryMapping m(File(f.fd()), 0, sizeof(double), MemoryMapping::writable());
33  double* d = m.asWritableRange<double>().data();
34  *d = 37 * kSomeDouble;
35  }
36  {
37  MemoryMapping m(File(f.fd()), 0, 3);
38  EXPECT_EQ(0, m.asRange<int>().size()); // not big enough
39  }
40  {
41  MemoryMapping m(File(f.fd()), 0, sizeof(double));
42  const double* d = m.asRange<double>().data();
43  EXPECT_EQ(*d, 37 * kSomeDouble);
44  }
45 }
auto f
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
static constexpr double kSomeDouble
static map< string, int > m
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
folly::TEST ( makeMoveWrapper  ,
NonEmpty   
)

Definition at line 30 of file MoveWrapperTest.cpp.

References EXPECT_EQ, EXPECT_TRUE, makeMoveWrapper(), and folly::gen::move.

30  {
31  auto u = std::make_unique<int>(5);
32  EXPECT_EQ(*u, 5);
33  auto p = makeMoveWrapper(std::move(u));
34  EXPECT_TRUE(!u);
35  EXPECT_EQ(**p, 5);
36 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
MoveWrapper< T0 > makeMoveWrapper(T &&t)
Definition: MoveWrapper.h:82
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( AsyncSocketException  ,
SimpleTest   
)

Definition at line 32 of file AsyncSocketExceptionTest.cpp.

References EXPECT_EQ, folly::AsyncSocketException::getErrno(), folly::AsyncSocketException::getType(), and string.

32  {
33  AsyncSocketException ex1(
34  AsyncSocketException::AsyncSocketExceptionType::NOT_OPEN,
35  "test exception 1");
36 
37  EXPECT_EQ(
38  AsyncSocketException::AsyncSocketExceptionType::NOT_OPEN, ex1.getType());
39  EXPECT_EQ(0, ex1.getErrno());
40  EXPECT_EQ(
41  "AsyncSocketException: test exception 1, type = Socket not open",
42  std::string(ex1.what()));
43 
44  AsyncSocketException ex2(
45  AsyncSocketException::AsyncSocketExceptionType::BAD_ARGS,
46  "test exception 2",
47  ECONNREFUSED);
48 
49  EXPECT_EQ(
50  AsyncSocketException::AsyncSocketExceptionType::BAD_ARGS, ex2.getType());
51  EXPECT_EQ(ECONNREFUSED, ex2.getErrno());
52  EXPECT_EQ(
53  "AsyncSocketException: test exception 2, type = Invalid arguments, "
54  "errno = " +
55  to<std::string>(ECONNREFUSED) + " (Connection refused)",
56  std::string(ex2.what()));
57 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
const char * string
Definition: Conv.cpp:212
folly::TEST ( AsyncTransportTest  ,
getSocketFromWrappedTransport   
)

Definition at line 33 of file AsyncTransportTest.cpp.

References ASSERT_EQ, EXPECT_CALL, folly::AsyncTransportWrapper::getUnderlyingTransport(), and testing::Return().

33  {
34  AsyncSocket::UniquePtr transport(new AsyncSocket());
35  auto transportAddr = transport.get();
36 
37  test::MockAsyncTransport wrapped1;
38  test::MockAsyncTransport wrapped2;
39 
40  EXPECT_CALL(wrapped2, getWrappedTransport()).WillOnce(Return(&wrapped1));
41  EXPECT_CALL(wrapped1, getWrappedTransport()).WillOnce(Return(transportAddr));
42 
43  auto sock = wrapped2.getUnderlyingTransport<AsyncSocket>();
44  ASSERT_EQ(transportAddr, sock);
45 }
#define ASSERT_EQ(val1, val2)
Definition: gtest.h:1956
#define EXPECT_CALL(obj, call)
internal::ReturnAction< R > Return(R value)
folly::TEST ( AsyncTimeout  ,
schedule   
)

Definition at line 38 of file AsyncTimeoutTest.cpp.

References EXPECT_EQ, folly::EventBase::loop(), folly::pushmi::__adl::noexcept(), folly::AsyncTimeout::schedule(), and value().

38  {
39  int value = 0;
40  int const expected = 10;
41  EventBase manager;
42 
43  auto observer = AsyncTimeout::schedule(
44  std::chrono::milliseconds(100), manager, [&]() noexcept {
45  value = expected;
46  });
47 
48  manager.loop();
49 
50  EXPECT_EQ(expected, value);
51 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
requires E e noexcept(noexcept(s.error(std::move(e))))
static const char *const value
Definition: Conv.cpp:50
folly::TEST ( makeMoveWrapper  ,
rvalue   
)

Definition at line 38 of file MoveWrapperTest.cpp.

References makeMoveWrapper(), and folly::gen::move.

38  {
39  std::unique_ptr<int> p;
41 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
MoveWrapper< T0 > makeMoveWrapper(T &&t)
Definition: MoveWrapper.h:82
folly::TEST ( SSLContextInitializationTest  ,
SSLContextInitializeThenSetLocksAndInit   
)

Definition at line 40 of file SSLContextInitializationTest.cpp.

References folly::ssl::init(), and folly::ssl::setLockTypesAndInit().

40  {
41  EXPECT_DEATH(
42  {
45  },
46  "OpenSSL is already initialized");
47 }
void init()
Definition: Init.cpp:54
void setLockTypesAndInit(LockTypeMapping inLockTypes)
Definition: Init.cpp:69
folly::TEST ( WriteFlagsTest  ,
unionOperator   
)

Definition at line 41 of file WriteFlagsTest.cpp.

References ASSERT_EQ, and uint32_t.

41  {
42  WriteFlags flags = WriteFlags::CORK | WriteFlags::NONE;
43  ASSERT_EQ(flags, WriteFlags::CORK);
44 
45  flags = static_cast<WriteFlags>(
46  static_cast<uint32_t>(WriteFlags::CORK) |
47  static_cast<uint32_t>(WriteFlags::EOR));
48  ASSERT_EQ(flags, WriteFlags::CORK | WriteFlags::EOR);
49 }
flags
Definition: http_parser.h:127
#define ASSERT_EQ(val1, val2)
Definition: gtest.h:1956
folly::TEST ( ExecutorTest  ,
KeepAliveBasic   
)

Definition at line 42 of file ExecutorTest.cpp.

References EXPECT_EQ, EXPECT_TRUE, folly::Executor::getKeepAliveToken(), and folly::KeepAliveTestExecutor::refCount.

42  {
43  KeepAliveTestExecutor exec;
44 
45  {
46  auto ka = getKeepAliveToken(exec);
47  EXPECT_TRUE(ka);
48  EXPECT_EQ(&exec, ka.get());
49  EXPECT_EQ(1, exec.refCount);
50  }
51 
52  EXPECT_EQ(0, exec.refCount);
53 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
Executor::KeepAlive< ExecutorT > getKeepAliveToken(ExecutorT *executor)
Definition: Executor.h:200
folly::TEST ( makeMoveWrapper  ,
lvalue   
)

Definition at line 43 of file MoveWrapperTest.cpp.

References makeMoveWrapper().

43  {
44  std::unique_ptr<int> p;
45  makeMoveWrapper(p);
46 }
MoveWrapper< T0 > makeMoveWrapper(T &&t)
Definition: MoveWrapper.h:82
folly::TEST ( AsyncSocketTest  ,
REUSEPORT   
)

Definition at line 43 of file AsyncSocketTest.cpp.

References folly::SocketAddress::getAddress(), folly::SocketAddress::getPort(), INFO, and folly::AsyncServerSocket::newSocket().

43  {
44  EventBase base;
45  auto serverSocket = AsyncServerSocket::newSocket(&base);
46  serverSocket->bind(0);
47  serverSocket->listen(0);
48  serverSocket->startAccepting();
49 
50  try {
51  serverSocket->setReusePortEnabled(true);
52  } catch (...) {
53  LOG(INFO) << "Reuse port probably not supported";
54  return;
55  }
56 
57  SocketAddress address;
58  serverSocket->getAddress(&address);
59  int port = address.getPort();
60 
61  auto serverSocket2 = AsyncServerSocket::newSocket(&base);
62  serverSocket2->setReusePortEnabled(true);
63  serverSocket2->bind(port);
64  serverSocket2->listen(0);
65  serverSocket2->startAccepting();
66 }
folly::TEST ( MemoryMapping  ,
Move   
)

Definition at line 47 of file MemoryMappingTest.cpp.

References folly::MemoryMapping::asRange(), folly::MemoryMapping::asWritableRange(), data(), EXPECT_EQ, f, folly::File::fd(), kSomeDouble, m, folly::gen::move, folly::File::temporary(), and folly::MemoryMapping::writable().

47  {
48  File f = File::temporary();
49  {
50  MemoryMapping m(
51  File(f.fd()), 0, sizeof(double) * 2, MemoryMapping::writable());
52  double* d = m.asWritableRange<double>().data();
53  d[0] = 37 * kSomeDouble;
54  MemoryMapping m2(std::move(m));
55  double* d2 = m2.asWritableRange<double>().data();
56  d2[1] = 39 * kSomeDouble;
57  }
58  {
59  MemoryMapping m(File(f.fd()), 0, sizeof(double));
60  const double* d = m.asRange<double>().data();
61  EXPECT_EQ(d[0], 37 * kSomeDouble);
62  MemoryMapping m2(std::move(m));
63  const double* d2 = m2.asRange<double>().data();
64  EXPECT_EQ(d2[1], 39 * kSomeDouble);
65  }
66 }
auto f
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
static constexpr double kSomeDouble
static map< string, int > m
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
folly::TEST ( LockFreeRingBuffer  ,
writeReadSequentiallyBackward   
)

last write

Definition at line 47 of file LockFreeRingBufferTest.cpp.

References ASSERT_EQ, ASSERT_TRUE, folly::LockFreeRingBuffer< T, Atom >::currentHead(), folly::LockFreeRingBuffer< T, Atom >::Cursor::moveBackward(), folly::LockFreeRingBuffer< T, Atom >::tryRead(), val, folly::LockFreeRingBuffer< T, Atom >::write(), and fizz::detail::write().

47  {
48  const int capacity = 256;
49  const int turns = 4;
50 
51  LockFreeRingBuffer<int> rb(capacity);
52  for (unsigned int turn = 0; turn < turns; turn++) {
53  for (unsigned int write = 0; write < capacity; write++) {
54  int val = turn * capacity + write;
55  rb.write(val);
56  }
57 
58  LockFreeRingBuffer<int>::Cursor cur = rb.currentHead();
59  cur.moveBackward(1);
60  for (int write = capacity - 1; write >= 0; write--) {
61  int foo = 0;
62  ASSERT_TRUE(rb.tryRead(foo, cur));
63  ASSERT_EQ(turn * capacity + write, foo);
64  cur.moveBackward();
65  }
66  }
67 }
void write(const T &in, folly::io::Appender &appender)
Definition: Types-inl.h:112
#define ASSERT_EQ(val1, val2)
Definition: gtest.h:1956
double val
Definition: String.cpp:273
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST ( makeMoveWrapper  ,
lvalue_copyable   
)

Definition at line 48 of file MoveWrapperTest.cpp.

References makeMoveWrapper().

48  {
49  std::shared_ptr<int> p;
50  makeMoveWrapper(p);
51 }
MoveWrapper< T0 > makeMoveWrapper(T &&t)
Definition: MoveWrapper.h:82
folly::TEST ( SSLContextInitializationTest  ,
SSLContextSetLocksAndInitialize   
)

Definition at line 49 of file SSLContextInitializationTest.cpp.

References folly::ssl::setLockTypesAndInit().

49  {
50  EXPECT_DEATH(
51  {
54  },
55  "OpenSSL is already initialized");
56 }
void setLockTypesAndInit(LockTypeMapping inLockTypes)
Definition: Init.cpp:69
folly::TEST ( WriteFlagsTest  ,
intersectionOperator   
)

Definition at line 51 of file WriteFlagsTest.cpp.

References ASSERT_EQ.

51  {
52  ASSERT_EQ(WriteFlags::NONE & WriteFlags::CORK, WriteFlags::NONE);
53 
55  WriteFlags::CORK | WriteFlags::EOR | WriteFlags::WRITE_SHUTDOWN;
56  ASSERT_EQ(flags & WriteFlags::CORK, WriteFlags::CORK);
57  ASSERT_EQ(flags & WriteFlags::EOR, WriteFlags::EOR);
58  ASSERT_EQ(flags & WriteFlags::WRITE_SHUTDOWN, WriteFlags::WRITE_SHUTDOWN);
59 }
flags
Definition: http_parser.h:127
#define ASSERT_EQ(val1, val2)
Definition: gtest.h:1956
folly::TEST ( AsyncTimeout  ,
schedule_immediate   
)

Definition at line 53 of file AsyncTimeoutTest.cpp.

References EXPECT_EQ, folly::EventBase::loop(), folly::pushmi::__adl::noexcept(), folly::AsyncTimeout::schedule(), and value().

53  {
54  int value = 0;
55  int const expected = 10;
56  EventBase manager;
57 
58  auto observer = AsyncTimeout::schedule(
59  std::chrono::milliseconds(0), manager, [&]() noexcept {
60  value = expected;
61  });
62 
63  manager.loop();
64  EXPECT_EQ(expected, value);
65 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
requires E e noexcept(noexcept(s.error(std::move(e))))
static const char *const value
Definition: Conv.cpp:50
folly::TEST ( ExecutorTest  ,
KeepAliveMove   
)

Definition at line 55 of file ExecutorTest.cpp.

References EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, folly::Executor::getKeepAliveToken(), folly::gen::move, and folly::KeepAliveTestExecutor::refCount.

55  {
56  KeepAliveTestExecutor exec;
57 
58  {
59  auto ka = getKeepAliveToken(exec);
60  EXPECT_TRUE(ka);
61  EXPECT_EQ(&exec, ka.get());
62  EXPECT_EQ(1, exec.refCount);
63 
64  auto ka2 = std::move(ka);
65  EXPECT_FALSE(ka);
66  EXPECT_TRUE(ka2);
67  EXPECT_EQ(&exec, ka2.get());
68  EXPECT_EQ(1, exec.refCount);
69  }
70 
71  EXPECT_EQ(0, exec.refCount);
72 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
Executor::KeepAlive< ExecutorT > getKeepAliveToken(ExecutorT *executor)
Definition: Executor.h:200
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Lazy  ,
Global   
)

Definition at line 55 of file LazyTest.cpp.

References EXPECT_EQ, foo, and globalCount.

55  {
56  EXPECT_EQ(globalCount(), 0);
57  EXPECT_EQ(foo(), "YEP");
58  EXPECT_EQ(globalCount(), 1);
59 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
auto const foo
Definition: LazyTest.cpp:49
auto globalCount
Definition: LazyTest.cpp:48
folly::TEST ( SSLContextInitializationTest  ,
SSLContextLocks   
)

Definition at line 58 of file SSLContextInitializationTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, testing::Test::HasFailure(), INFO, folly::ssl::init(), folly::ssl::isLockDisabled(), and setupSSLLocks().

58  {
59  EXPECT_EXIT(
60  {
61  setupSSLLocks();
63 #ifdef CRYPTO_LOCK_EVP_PKEY
64  EXPECT_TRUE(folly::ssl::isLockDisabled(CRYPTO_LOCK_EVP_PKEY));
65 #endif
66 #ifdef CRYPTO_LOCK_SSL_SESSION
67  EXPECT_FALSE(folly::ssl::isLockDisabled(CRYPTO_LOCK_SSL_SESSION));
68 #endif
69 #ifdef CRYPTO_LOCK_ERR
70  EXPECT_FALSE(folly::ssl::isLockDisabled(CRYPTO_LOCK_ERR));
71 #endif
72  if (::testing::Test::HasFailure()) {
73  exit(1);
74  }
75  LOG(INFO) << "SSLContextLocks passed";
76  exit(0);
77  },
78  ::testing::ExitedWithCode(0),
79  "SSLContextLocks passed");
80 }
static bool HasFailure()
Definition: gtest.h:407
void init()
Definition: Init.cpp:54
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
bool isLockDisabled(int lockId)
Definition: Init.cpp:91
folly::TEST ( AsyncSocketException  ,
SSLExceptionType   
)

Definition at line 59 of file AsyncSocketExceptionTest.cpp.

References EXPECT_EQ, folly::AsyncSocketException::getType(), and folly::ssl::init().

59  {
60  {
61  // Initiailzes OpenSSL everything. Else some of the calls will block
63  SSLException eof(SSL_ERROR_ZERO_RETURN, 0, 0, 0);
64  EXPECT_EQ(eof.getType(), AsyncSocketException::END_OF_FILE);
65 
66  SSLException netEof(SSL_ERROR_SYSCALL, 0, 0, 0);
67  EXPECT_EQ(netEof.getType(), AsyncSocketException::END_OF_FILE);
68 
69  SSLException netOther(SSL_ERROR_SYSCALL, 0, 1, 0);
70  EXPECT_EQ(netOther.getType(), AsyncSocketException::NETWORK_ERROR);
71 
72  std::array<int, 6> sslErrs{{SSL_ERROR_SSL,
73  SSL_ERROR_WANT_READ,
74  SSL_ERROR_WANT_WRITE,
75  SSL_ERROR_WANT_X509_LOOKUP,
76  SSL_ERROR_WANT_CONNECT,
77  SSL_ERROR_WANT_ACCEPT}};
78 
79  for (auto& e : sslErrs) {
80  SSLException sslEx(e, 0, 0, 0);
81  EXPECT_EQ(sslEx.getType(), AsyncSocketException::SSL_ERROR);
82  }
83  }
84 
85  {
86  SSLException eof(SSLError::EOF_ERROR);
87  EXPECT_EQ(eof.getType(), AsyncSocketException::END_OF_FILE);
88 
89  SSLException net(SSLError::NETWORK_ERROR);
90  EXPECT_EQ(net.getType(), AsyncSocketException::NETWORK_ERROR);
91 
92  std::array<SSLError, 4> errs{{SSLError::CLIENT_RENEGOTIATION,
93  SSLError::INVALID_RENEGOTIATION,
94  SSLError::EARLY_WRITE,
95  SSLError::SSL_ERROR}};
96 
97  for (auto& e : errs) {
98  SSLException sslEx(e);
99  EXPECT_EQ(sslEx.getType(), AsyncSocketException::SSL_ERROR);
100  }
101  }
102 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
void init()
Definition: Init.cpp:54
folly::TEST ( WriteFlagsTest  ,
exclusionOperator   
)

Definition at line 61 of file WriteFlagsTest.cpp.

References ASSERT_FALSE, ASSERT_TRUE, and isSet().

61  {
62  ASSERT_FALSE(isSet(~WriteFlags::CORK, WriteFlags::CORK));
63  ASSERT_TRUE(isSet(~WriteFlags::CORK, WriteFlags::EOR));
64  ASSERT_TRUE(isSet(~WriteFlags::CORK, WriteFlags::WRITE_SHUTDOWN));
65 
66  ASSERT_FALSE(isSet(~WriteFlags::EOR, WriteFlags::EOR));
67  ASSERT_TRUE(isSet(~WriteFlags::EOR, WriteFlags::CORK));
68  ASSERT_TRUE(isSet(~WriteFlags::EOR, WriteFlags::WRITE_SHUTDOWN));
69 }
bool isSet(WriteFlags a, WriteFlags b)
#define ASSERT_FALSE(condition)
Definition: gtest.h:1868
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST ( Lazy  ,
Map   
)

Definition at line 61 of file LazyTest.cpp.

References EXPECT_EQ, lazy(), and size().

61  {
62  auto lazyMap = folly::lazy([]() -> std::map<std::string, std::string> {
63  return {
64  {"foo", "bar"},
65  {"baz", "quux"},
66  };
67  });
68 
69  EXPECT_EQ(lazyMap().size(), 2);
70  lazyMap()["blah"] = "asd";
71  EXPECT_EQ(lazyMap().size(), 3);
72 }
auto lazy(Func &&fun)
Definition: Lazy.h:138
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
folly::TEST ( Expected  ,
NoDefault   
)

Definition at line 63 of file ExpectedTest.cpp.

References EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, in_place(), makeUnexpected(), and value().

63  {
64  static_assert(
65  std::is_default_constructible<Expected<NoDefault, int>>::value, "");
66  Expected<NoDefault, int> x{in_place, 42, 42};
67  EXPECT_TRUE(bool(x));
68  x.emplace(4, 5);
69  EXPECT_TRUE(bool(x));
70  x = makeUnexpected(42);
71  EXPECT_FALSE(bool(x));
72  EXPECT_EQ(42, x.error());
73 }
Definition: InvokeTest.cpp:58
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
constexpr Unexpected< typename std::decay< Error >::type > makeUnexpected(Error &&)
Definition: Expected.h:785
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Optional  ,
NoDefault   
)

Definition at line 66 of file OptionalTest.cpp.

References folly::Optional< Value >::clear(), folly::Optional< Value >::emplace(), EXPECT_FALSE, EXPECT_TRUE, and x.

66  {
67  Optional<NoDefault> x;
68  EXPECT_FALSE(x);
69  x.emplace(4, 5);
70  EXPECT_TRUE(bool(x));
71  x.clear();
72  EXPECT_FALSE(x);
73 }
const int x
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncTimeout  ,
cancel_make   
)

Definition at line 67 of file AsyncTimeoutTest.cpp.

References EXPECT_EQ, EXPECT_NE, folly::EventBase::loop(), folly::AsyncTimeout::make(), folly::pushmi::__adl::noexcept(), folly::RequestContext::saveContext(), and value().

67  {
68  int value = 0;
69  int const expected = 10;
70  EventBase manager;
71 
72  auto observer =
73  AsyncTimeout::make(manager, [&]() noexcept { value = expected; });
74 
75  std::weak_ptr<RequestContext> rctx_weak_ptr;
76 
77  {
78  RequestContextScopeGuard rctx_guard;
79  rctx_weak_ptr = RequestContext::saveContext();
80  observer->scheduleTimeout(std::chrono::milliseconds(100));
81  observer->cancelTimeout();
82  }
83 
84  // Ensure that RequestContext created for the scope has been released and
85  // deleted.
86  EXPECT_EQ(rctx_weak_ptr.expired(), true);
87 
88  manager.loop();
89 
90  EXPECT_NE(expected, value);
91 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
requires E e noexcept(noexcept(s.error(std::move(e))))
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_NE(val1, val2)
Definition: gtest.h:1926
folly::TEST ( SequencedExecutor  ,
CPUThreadPoolExecutor   
)

Definition at line 68 of file SequencedExecutorTest.cpp.

References folly::pushmi::executor, and testExecutor().

Referenced by TEST().

68  {
69  CPUThreadPoolExecutor executor(4);
71 }
void testExecutor(folly::SequencedExecutor &executor)
PUSHMI_INLINE_VAR constexpr __adl::get_executor_fn executor
folly::TEST ( AsyncSocketTest  ,
v4v6samePort   
)

Definition at line 68 of file AsyncSocketTest.cpp.

References addr, ASSERT_GT, EXPECT_EQ, folly::AsyncServerSocket::newSocket(), and uint16_t.

68  {
69  EventBase base;
70  auto serverSocket = AsyncServerSocket::newSocket(&base);
71  serverSocket->bind(0);
72  auto addrs = serverSocket->getAddresses();
73  ASSERT_GT(addrs.size(), 0);
74  uint16_t port = addrs[0].getPort();
75  for (const auto& addr : addrs) {
76  EXPECT_EQ(port, addr.getPort());
77  }
78 }
#define ASSERT_GT(val1, val2)
Definition: gtest.h:1976
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
ThreadPoolListHook * addr
folly::TEST ( MemoryMapping  ,
DoublyMapped   
)

Definition at line 68 of file MemoryMappingTest.cpp.

References folly::MemoryMapping::asWritableRange(), b, count, data(), EXPECT_EQ, EXPECT_NE, f, folly::File::fd(), kSomeDouble, string, folly::File::temporary(), folly::MemoryMapping::writable(), and fizz::detail::write().

68  {
69  File f = File::temporary();
70  // two mappings of the same memory, different addresses.
71  MemoryMapping mw(File(f.fd()), 0, sizeof(double), MemoryMapping::writable());
72  MemoryMapping mr(File(f.fd()), 0, sizeof(double));
73 
74  double* dw = mw.asWritableRange<double>().data();
75  const double* dr = mr.asRange<double>().data();
76 
77  // Show that it's truly the same value, even though the pointers differ
78  EXPECT_NE(dw, dr);
79  *dw = 42 * kSomeDouble;
80  EXPECT_EQ(*dr, 42 * kSomeDouble);
81  *dw = 43 * kSomeDouble;
82  EXPECT_EQ(*dr, 43 * kSomeDouble);
83 }
auto f
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
static constexpr double kSomeDouble
#define EXPECT_NE(val1, val2)
Definition: gtest.h:1926
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
folly::TEST ( LockFreeRingBuffer  ,
readsCanBlock   
)

Definition at line 69 of file LockFreeRingBufferTest.cpp.

References Atom, folly::LockFreeRingBuffer< T, Atom >::currentHead(), EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, i, val, folly::LockFreeRingBuffer< T, Atom >::waitAndTryRead(), and folly::LockFreeRingBuffer< T, Atom >::write().

69  {
70  // Start a reader thread, confirm that reading can block
71  std::atomic<bool> readerHasRun(false);
72  LockFreeRingBuffer<int> rb(1);
73  auto cursor = rb.currentHead();
74  cursor.moveForward(3); // wait for the 4th write
75 
76  const int sentinel = 0xfaceb00c;
77 
78  auto reader = std::thread([&]() {
79  int val = 0;
80  EXPECT_TRUE(rb.waitAndTryRead(val, cursor));
81  readerHasRun = true;
82  EXPECT_EQ(sentinel, val);
83  });
84 
85  for (int i = 0; i < 4; i++) {
86  EXPECT_FALSE(readerHasRun);
87  int val = sentinel;
88  rb.write(val);
89  }
90  reader.join();
91  EXPECT_TRUE(readerHasRun);
92 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
double val
Definition: String.cpp:273
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( WriteFlagsTest  ,
unsetOperator   
)

Definition at line 71 of file WriteFlagsTest.cpp.

References ASSERT_FALSE, ASSERT_TRUE, and isSet().

71  {
73  WriteFlags::CORK | WriteFlags::EOR | WriteFlags::WRITE_SHUTDOWN;
74  ASSERT_TRUE(isSet(flags, WriteFlags::CORK));
75  ASSERT_TRUE(isSet(flags, WriteFlags::EOR));
76  ASSERT_TRUE(isSet(flags, WriteFlags::WRITE_SHUTDOWN));
77 
78  flags = WriteFlags::CORK;
79  ASSERT_TRUE(isSet(flags, WriteFlags::CORK));
80  ASSERT_FALSE(isSet(flags, WriteFlags::EOR));
81  ASSERT_FALSE(isSet(flags, WriteFlags::WRITE_SHUTDOWN));
82 }
flags
Definition: http_parser.h:127
bool isSet(WriteFlags a, WriteFlags b)
#define ASSERT_FALSE(condition)
Definition: gtest.h:1868
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST ( SequencedExecutor  ,
SerialCPUThreadPoolExecutor   
)

Definition at line 73 of file SequencedExecutorTest.cpp.

References folly::SerialExecutor::create(), folly::pushmi::executor, folly::Executor::getKeepAliveToken(), and testExecutor().

73  {
74  auto cpuExecutor = std::make_shared<CPUThreadPoolExecutor>(4);
75  auto executor =
76  SerialExecutor::create(Executor::getKeepAliveToken(cpuExecutor.get()));
77  testExecutor(*executor);
78 }
void testExecutor(folly::SequencedExecutor &executor)
PUSHMI_INLINE_VAR constexpr __adl::get_executor_fn executor
Executor::KeepAlive< ExecutorT > getKeepAliveToken(ExecutorT *executor)
Definition: Executor.h:200
folly::TEST ( ExecutorTest  ,
KeepAliveConvert   
)

Definition at line 74 of file ExecutorTest.cpp.

References EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, folly::Executor::KeepAlive< ExecutorT >::get(), folly::Executor::getKeepAliveToken(), folly::gen::move, and folly::KeepAliveTestExecutor::refCount.

74  {
75  KeepAliveTestExecutor exec;
76 
77  {
78  auto ka = getKeepAliveToken(exec);
79  EXPECT_TRUE(ka);
80  EXPECT_EQ(&exec, ka.get());
81  EXPECT_EQ(1, exec.refCount);
82 
83  Executor::KeepAlive<Executor> ka2 = std::move(ka); // conversion
84  EXPECT_FALSE(ka);
85  EXPECT_TRUE(ka2);
86  EXPECT_EQ(&exec, ka2.get());
87  EXPECT_EQ(1, exec.refCount);
88  }
89 
90  EXPECT_EQ(0, exec.refCount);
91 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
Executor::KeepAlive< ExecutorT > getKeepAliveToken(ExecutorT *executor)
Definition: Executor.h:200
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Expected  ,
String   
)

Definition at line 75 of file ExpectedTest.cpp.

References folly::Expected< Value, Error >::error(), EXPECT_EQ, EXPECT_FALSE, and EXPECT_TRUE.

75  {
76  Expected<std::string, int> maybeString;
77  EXPECT_FALSE(bool(maybeString));
78  EXPECT_EQ(0, maybeString.error());
79  maybeString = "hello";
80  EXPECT_TRUE(bool(maybeString));
81  EXPECT_EQ("hello", *maybeString);
82 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Optional  ,
Emplace   
)

Definition at line 75 of file OptionalTest.cpp.

References testing::ElementsAre(), folly::Optional< Value >::emplace(), and EXPECT_THAT.

75  {
76  Optional<std::vector<int>> opt;
77  auto& values1 = opt.emplace(3, 4);
78  EXPECT_THAT(values1, testing::ElementsAre(4, 4, 4));
79  auto& values2 = opt.emplace(2, 5);
80  EXPECT_THAT(values2, testing::ElementsAre(5, 5));
81 }
#define EXPECT_THAT(value, matcher)
internal::ElementsAreMatcher< ::testing::tuple<> > ElementsAre()
folly::TEST ( SequencedExecutor  ,
EventBase   
)

Definition at line 80 of file SequencedExecutorTest.cpp.

References getEventBase(), and testExecutor().

80  {
81  testExecutor(*ScopedEventBaseThread().getEventBase());
82 }
void testExecutor(folly::SequencedExecutor &executor)
EventBase * getEventBase()
folly::TEST ( AsyncSocketTest  ,
duplicateBind   
)

Definition at line 80 of file AsyncSocketTest.cpp.

References EXPECT_THROW, folly::SocketAddress::getAddress(), folly::SocketAddress::getPort(), and folly::AsyncServerSocket::newSocket().

80  {
81  EventBase base;
82  auto server1 = AsyncServerSocket::newSocket(&base);
83  server1->bind(0);
84  server1->listen(10);
85 
86  SocketAddress address;
87  server1->getAddress(std::addressof(address));
88 
89  auto server2 = AsyncServerSocket::newSocket(&base);
90  EXPECT_THROW(server2->bind(address.getPort()), std::exception);
91 }
#define EXPECT_THROW(statement, expected_exception)
Definition: gtest.h:1843
folly::TEST ( SSLContextInitializationTest  ,
SSLContextLocksSetAfterInitIgnored   
)

Definition at line 82 of file SSLContextInitializationTest.cpp.

References EXPECT_TRUE, testing::Test::HasFailure(), INFO, folly::ssl::init(), folly::ssl::isLockDisabled(), folly::ssl::setLockTypes(), and setupSSLLocks().

82  {
83  EXPECT_EXIT(
84  {
85  setupSSLLocks();
88 #ifdef CRYPTO_LOCK_EVP_PKEY
89  EXPECT_TRUE(folly::ssl::isLockDisabled(CRYPTO_LOCK_EVP_PKEY));
90 #endif
91  if (::testing::Test::HasFailure()) {
92  exit(1);
93  }
94  LOG(INFO) << "SSLContextLocksSetAfterInitIgnored passed";
95  exit(0);
96  },
97  ::testing::ExitedWithCode(0),
98  "SSLContextLocksSetAfterInitIgnored passed");
99 }
void setLockTypes(LockTypeMapping inLockTypes)
Definition: Init.cpp:76
static bool HasFailure()
Definition: gtest.h:407
void init()
Definition: Init.cpp:54
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
bool isLockDisabled(int lockId)
Definition: Init.cpp:91
folly::TEST ( Optional  ,
EmplaceInitializerList   
)

Definition at line 83 of file OptionalTest.cpp.

References testing::ElementsAre(), folly::Optional< Value >::emplace(), and EXPECT_THAT.

83  {
84  Optional<std::vector<int>> opt;
85  auto& values1 = opt.emplace({3, 4, 5});
86  EXPECT_THAT(values1, testing::ElementsAre(3, 4, 5));
87  auto& values2 = opt.emplace({4, 5, 6});
88  EXPECT_THAT(values2, testing::ElementsAre(4, 5, 6));
89 }
#define EXPECT_THAT(value, matcher)
internal::ElementsAreMatcher< ::testing::tuple<> > ElementsAre()
folly::TEST ( WriteFlagsTest  ,
compoundAssignmentUnionOperator   
)

Definition at line 84 of file WriteFlagsTest.cpp.

References ASSERT_EQ.

84  {
85  WriteFlags flags = WriteFlags::NONE;
86  flags |= WriteFlags::CORK;
87  ASSERT_EQ(flags, WriteFlags::CORK);
88 
89  flags = WriteFlags::CORK;
90  flags |= WriteFlags::EOR;
91  ASSERT_EQ(flags, WriteFlags::CORK | WriteFlags::EOR);
92 
93  flags = WriteFlags::CORK | WriteFlags::EOR;
94  flags |= WriteFlags::CORK;
95  ASSERT_EQ(flags, WriteFlags::CORK | WriteFlags::EOR);
96 }
flags
Definition: http_parser.h:127
#define ASSERT_EQ(val1, val2)
Definition: gtest.h:1956
folly::TEST ( Expected  ,
Ambiguous   
)

Definition at line 84 of file ExpectedTest.cpp.

References EXPECT_FALSE, and value().

84  {
85  // Potentially ambiguous and confusing construction and assignment disallowed:
86  EXPECT_FALSE((std::is_constructible<Expected<int, int>, int>::value));
87  EXPECT_FALSE((std::is_assignable<Expected<int, int>&, int>::value));
88 }
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Expected  ,
Const   
)

Definition at line 90 of file ExpectedTest.cpp.

References folly::Expected< Value, Error >::emplace(), folly::Expected< Value, Error >::error(), EXPECT_EQ, EXPECT_FALSE, in_place(), makeUnexpected(), folly::gen::move, and value().

90  {
91  { // default construct
92  Expected<const int, int> ex;
93  EXPECT_FALSE(bool(ex));
94  EXPECT_EQ(0, ex.error());
95  ex.emplace(4);
96  EXPECT_EQ(4, *ex);
97  ex.emplace(5);
98  EXPECT_EQ(5, *ex);
99  ex = makeUnexpected(42);
100  EXPECT_FALSE(bool(ex));
101  EXPECT_EQ(42, ex.error());
102  }
103  { // copy-constructed
104  const int x = 6;
105  Expected<const int, int> ex{in_place, x};
106  Expected<const int, int> ex2 = ex;
107  EXPECT_EQ(6, *ex2);
108  }
109  { // move-constructed
110  const int x = 7;
111  Expected<const int, int> ex{in_place, std::move(x)};
112  Expected<const int, int> ex2 = std::move(ex);
113  EXPECT_EQ(7, *ex2);
114  }
115  // no assignment allowed
116  EXPECT_FALSE((std::is_copy_assignable<Expected<const int, int>>::value));
117 }
Definition: InvokeTest.cpp:58
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
constexpr Unexpected< typename std::decay< Error >::type > makeUnexpected(Error &&)
Definition: Expected.h:785
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Lazy  ,
NonLambda   
)

Definition at line 90 of file LazyTest.cpp.

References folly::CopyCount::CopyCount(), EXPECT_EQ, f, and lazy().

90  {
91  auto const rval = folly::lazy(CopyCount());
93  EXPECT_EQ(rval(), true);
95 
96  CopyCount cpy;
97  auto const lval = folly::lazy(cpy);
99  EXPECT_EQ(lval(), true);
101 
102  std::function<bool()> f = [&] { return 12; };
103  auto const lazyF = folly::lazy(f);
104  EXPECT_EQ(lazyF(), true);
105 }
auto lazy(Func &&fun)
Definition: Lazy.h:138
auto f
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
int * count
folly::TEST ( Optional  ,
Reset   
)

Definition at line 91 of file OptionalTest.cpp.

References EXPECT_FALSE, and folly::Optional< Value >::reset().

91  {
92  Optional<int> opt(3);
93  opt.reset();
94  EXPECT_FALSE(opt);
95 }
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( ExecutorTest  ,
KeepAliveCopy   
)

Definition at line 93 of file ExecutorTest.cpp.

References EXPECT_EQ, EXPECT_TRUE, folly::Executor::getKeepAliveToken(), and folly::KeepAliveTestExecutor::refCount.

93  {
94  KeepAliveTestExecutor exec;
95 
96  {
97  auto ka = getKeepAliveToken(exec);
98  EXPECT_TRUE(ka);
99  EXPECT_EQ(&exec, ka.get());
100  EXPECT_EQ(1, exec.refCount);
101 
102  auto ka2 = ka.copy();
103  EXPECT_TRUE(ka);
104  EXPECT_TRUE(ka2);
105  EXPECT_EQ(&exec, ka2.get());
106  EXPECT_EQ(2, exec.refCount);
107  }
108 
109  EXPECT_EQ(0, exec.refCount);
110 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
Executor::KeepAlive< ExecutorT > getKeepAliveToken(ExecutorT *executor)
Definition: Executor.h:200
folly::TEST ( AsyncTimeout  ,
cancel_schedule   
)

Definition at line 93 of file AsyncTimeoutTest.cpp.

References folly::AsyncTimeout::cancelTimeout(), EXPECT_EQ, EXPECT_NE, folly::EventBase::loop(), folly::pushmi::__adl::noexcept(), folly::RequestContext::saveContext(), folly::AsyncTimeout::schedule(), and value().

93  {
94  int value = 0;
95  int const expected = 10;
96  EventBase manager;
97  std::unique_ptr<AsyncTimeout> observer;
98  std::weak_ptr<RequestContext> rctx_weak_ptr;
99 
100  {
101  RequestContextScopeGuard rctx_guard;
102  rctx_weak_ptr = RequestContext::saveContext();
103 
104  observer = AsyncTimeout::schedule(
105  std::chrono::milliseconds(100), manager, [&]() noexcept {
106  value = expected;
107  });
108 
109  observer->cancelTimeout();
110  }
111 
112  // Ensure that RequestContext created for the scope has been released and
113  // deleted.
114  EXPECT_EQ(rctx_weak_ptr.expired(), true);
115 
116  manager.loop();
117 
118  EXPECT_NE(expected, value);
119 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
requires E e noexcept(noexcept(s.error(std::move(e))))
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_NE(val1, val2)
Definition: gtest.h:1926
folly::TEST ( AsyncSocketTest  ,
tosReflect   
)

Definition at line 93 of file AsyncSocketTest.cpp.

References ASSERT_EQ, EXPECT_FALSE, EXPECT_TRUE, folly::netops::getsockopt(), folly::AsyncServerSocket::newSocket(), TCP_SAVE_SYN, and value().

93  {
94  EventBase base;
95  auto server1 = AsyncServerSocket::newSocket(&base);
96  server1->bind(0);
97  server1->listen(10);
98  int fd = server1->getSocket();
99 
100  // Verify if tos reflect is disabled by default
101  // and the TCP_SAVE_SYN setting is not enabled
102  EXPECT_FALSE(server1->getTosReflect());
103  int value;
104  socklen_t valueLength = sizeof(value);
105  int rc = getsockopt(fd, IPPROTO_TCP, TCP_SAVE_SYN, &value, &valueLength);
106  ASSERT_EQ(rc, 0);
107  ASSERT_EQ(value, 0);
108 
109  // Enable TOS reflect on the server socket
110  server1->setTosReflect(true);
111 
112  // Verify if tos reflect is enabled now
113  // and the TCP_SAVE_SYN setting is also enabled
114  EXPECT_TRUE(server1->getTosReflect());
115  rc = getsockopt(fd, IPPROTO_TCP, TCP_SAVE_SYN, &value, &valueLength);
116  ASSERT_EQ(rc, 0);
117  ASSERT_EQ(value, 1);
118 }
#define ASSERT_EQ(val1, val2)
Definition: gtest.h:1956
#define TCP_SAVE_SYN
int getsockopt(NetworkSocket s, int level, int optname, void *optval, socklen_t *optlen)
Definition: NetOps.cpp:112
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Optional  ,
String   
)

Definition at line 97 of file OptionalTest.cpp.

References EXPECT_FALSE, and EXPECT_TRUE.

97  {
98  Optional<std::string> maybeString;
99  EXPECT_FALSE(maybeString);
100  maybeString = "hello";
101  EXPECT_TRUE(bool(maybeString));
102 }
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( WriteFlagsTest  ,
compoundAssignmentIntersectionOperator   
)

Definition at line 98 of file WriteFlagsTest.cpp.

References ASSERT_EQ.

98  {
99  WriteFlags flags = WriteFlags::CORK | WriteFlags::EOR;
100  flags &= WriteFlags::CORK;
101  ASSERT_EQ(flags, WriteFlags::CORK);
102 
103  flags = WriteFlags::CORK | WriteFlags::EOR;
104  flags &= WriteFlags::EOR;
105  ASSERT_EQ(flags, WriteFlags::EOR);
106 
107  flags = WriteFlags::NONE;
108  flags &= WriteFlags::EOR;
109  ASSERT_EQ(flags, WriteFlags::NONE);
110 }
flags
Definition: http_parser.h:127
#define ASSERT_EQ(val1, val2)
Definition: gtest.h:1956
folly::TEST ( Optional  ,
Const   
)

Definition at line 104 of file OptionalTest.cpp.

References folly::Optional< Value >::clear(), folly::Optional< Value >::emplace(), EXPECT_EQ, EXPECT_FALSE, and folly::gen::move.

104  {
105  { // default construct
106  Optional<const int> opt;
107  EXPECT_FALSE(bool(opt));
108  opt.emplace(4);
109  EXPECT_EQ(*opt, 4);
110  opt.emplace(5);
111  EXPECT_EQ(*opt, 5);
112  opt.clear();
113  EXPECT_FALSE(bool(opt));
114  }
115  { // copy-constructed
116  const int x = 6;
117  Optional<const int> opt(x);
118  EXPECT_EQ(*opt, 6);
119  }
120  { // move-constructed
121  const int x = 7;
122  Optional<const int> opt(std::move(x));
123  EXPECT_EQ(*opt, 7);
124  }
125  // no assignment allowed
126 }
Definition: InvokeTest.cpp:58
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Lazy  ,
Consty   
)

Definition at line 107 of file LazyTest.cpp.

References EXPECT_EQ, f, and lazy().

107  {
108  std::function<int()> const f = [&] { return 12; };
109  auto lz = folly::lazy(f);
110  EXPECT_EQ(lz(), 12);
111 }
auto lazy(Func &&fun)
Definition: Lazy.h:138
auto f
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
folly::TEST ( MemoryMapping  ,
Simple   
)

Definition at line 109 of file MemoryMappingTest.cpp.

References folly::MemoryMapping::data(), EXPECT_EQ, f, folly::File::fd(), m, and folly::File::temporary().

109  {
110  File f = File::temporary();
111  writeStringToFileOrDie("hello", f.fd());
112 
113  {
114  MemoryMapping m(File(f.fd()));
115  EXPECT_EQ("hello", m.data());
116  }
117  {
118  MemoryMapping m(File(f.fd()), 1, 2);
119  EXPECT_EQ("el", m.data());
120  }
121 }
auto f
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
static map< string, int > m
folly::TEST ( TLRefCount  ,
Basic   
)

Definition at line 116 of file RefCountTest.cpp.

116  {
117  basicTest<TLRefCount>();
118 }
folly::TEST ( Expected  ,
Simple   
)

Definition at line 119 of file ExpectedTest.cpp.

References folly::Expected< Value, Error >::emplace(), EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, makeUnexpected(), and folly::Expected< Value, Error >::value_or().

119  {
120  Expected<int, int> ex;
121  EXPECT_FALSE(bool(ex));
122  EXPECT_EQ(42, ex.value_or(42));
123  ex.emplace(4);
124  EXPECT_TRUE(bool(ex));
125  EXPECT_EQ(4, *ex);
126  EXPECT_EQ(4, ex.value_or(42));
127  ex = makeUnexpected(-1);
128  EXPECT_FALSE(bool(ex));
129  EXPECT_EQ(-1, ex.error());
130  EXPECT_EQ(42, ex.value_or(42));
131 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr Unexpected< typename std::decay< Error >::type > makeUnexpected(Error &&)
Definition: Expected.h:785
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( TLRefCount  ,
Stress   
)

Definition at line 120 of file RefCountTest.cpp.

120  {
121  // This is absurdly slow, so we can't
122  // do it that many times.
123  stressTest<TLRefCount>(500);
124 }
folly::TEST ( MemoryMapping  ,
LargeFile   
)

Definition at line 123 of file MemoryMappingTest.cpp.

References folly::MemoryMapping::data(), EXPECT_EQ, f, folly::File::fd(), i, m, folly::Random::rand32(), s, size(), string, and folly::File::temporary().

123  {
124  std::string fileData;
125  size_t fileSize = sysconf(_SC_PAGESIZE) * 3 + 10;
126  fileData.reserve(fileSize);
127  for (size_t i = 0; i < fileSize; i++) {
128  fileData.push_back(0xff & Random::rand32());
129  }
130 
131  File f = File::temporary();
132  writeStringToFileOrDie(fileData, f.fd());
133 
134  {
135  MemoryMapping m(File(f.fd()));
136  EXPECT_EQ(fileData, m.data());
137  }
138  {
139  size_t size = sysconf(_SC_PAGESIZE) * 2;
140  StringPiece s(fileData.data() + 9, size - 9);
141  MemoryMapping m(File(f.fd()), 9, size - 9);
142  EXPECT_EQ(s.toString(), m.data());
143  }
144 }
auto f
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
static map< string, int > m
const char * string
Definition: Conv.cpp:212
static set< string > s
Range< const char * > StringPiece
folly::TEST ( Optional  ,
Simple   
)

Definition at line 128 of file OptionalTest.cpp.

References EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, folly::gen::move, folly::pushmi::__adl::noexcept(), operator==(), s, s_, and folly::Optional< Value >::value_or().

128  {
129  Optional<int> opt;
130  EXPECT_FALSE(bool(opt));
131  EXPECT_EQ(42, opt.value_or(42));
132  opt = 4;
133  EXPECT_TRUE(bool(opt));
134  EXPECT_EQ(4, *opt);
135  EXPECT_EQ(4, opt.value_or(42));
136  opt = 5;
137  EXPECT_EQ(5, *opt);
138  opt.clear();
139  EXPECT_FALSE(bool(opt));
140 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( LockFreeRingBuffer  ,
writesNeverFail   
)

Definition at line 140 of file LockFreeRingBufferTest.cpp.

140  {
143 
144  runWritesNeverFail<DeterministicAtomic>(1, 100, 4);
145  runWritesNeverFail<DeterministicAtomic>(10, 100, 4);
146  runWritesNeverFail<DeterministicAtomic>(100, 1000, 8);
147  runWritesNeverFail<DeterministicAtomic>(1000, 10000, 16);
148 
149  runWritesNeverFail<std::atomic>(1, 100, 4);
150  runWritesNeverFail<std::atomic>(10, 100, 4);
151  runWritesNeverFail<std::atomic>(100, 1000, 8);
152  runWritesNeverFail<std::atomic>(1000, 10000, 16);
153 
154  runWritesNeverFail<EmulatedFutexAtomic>(1, 100, 4);
155  runWritesNeverFail<EmulatedFutexAtomic>(10, 100, 4);
156  runWritesNeverFail<EmulatedFutexAtomic>(100, 1000, 8);
157  runWritesNeverFail<EmulatedFutexAtomic>(1000, 10000, 16);
158 }
DeterministicAtomicImpl< T, DeterministicSchedule > DeterministicAtomic
folly::TEST ( MemoryMapping  ,
ZeroLength   
)

Definition at line 146 of file MemoryMappingTest.cpp.

References folly::MemoryMapping::data(), EXPECT_EQ, EXPECT_TRUE, f, folly::File::fd(), m, folly::MemoryMapping::mlock(), folly::MemoryMapping::mlocked(), folly::MemoryMapping::MUST_LOCK, folly::Range< Iter >::size(), and folly::File::temporary().

146  {
147  File f = File::temporary();
148  MemoryMapping m(File(f.fd()));
149  EXPECT_TRUE(m.mlock(MemoryMapping::LockMode::MUST_LOCK));
150  EXPECT_TRUE(m.mlocked());
151  EXPECT_EQ(0, m.data().size());
152 }
auto f
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
static map< string, int > m
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( MemoryMapping  ,
Advise   
)

Definition at line 154 of file MemoryMappingTest.cpp.

References folly::MemoryMapping::advise(), f, folly::File::fd(), ftruncateNoInt(), kPageSize, m, size(), and folly::File::temporary().

154  {
155  File f = File::temporary();
156  size_t kPageSize = 4096;
157  size_t size = kPageSize + 10; // unaligned file size
158  PCHECK(ftruncateNoInt(f.fd(), size) == 0) << size;
159 
160  MemoryMapping m(File(f.fd()));
161 
162  // NOTE: advise crashes on bad input.
163 
164  m.advise(MADV_NORMAL, 0, kPageSize);
165  m.advise(MADV_NORMAL, 1, kPageSize);
166  m.advise(MADV_NORMAL, 0, 2);
167  m.advise(MADV_NORMAL, 1, 2);
168 
169  m.advise(MADV_NORMAL, kPageSize, 0);
170  m.advise(MADV_NORMAL, kPageSize, 1);
171  m.advise(MADV_NORMAL, kPageSize, size - kPageSize);
172 
173  auto off = kPageSize + 1;
174  m.advise(MADV_NORMAL, off, size - off);
175 
176  EXPECT_DEATH(m.advise(MADV_NORMAL, off, size - off + 1), "");
177 }
auto f
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
static map< string, int > m
const size_t kPageSize
Definition: RangeTest.cpp:1000
int ftruncateNoInt(int fd, off_t len)
Definition: FileUtil.cpp:86
folly::TEST ( Expected  ,
value_or_rvalue_arg   
)

Definition at line 157 of file ExpectedTest.cpp.

References EXPECT_EQ, makeUnexpected(), folly::gen::move, and folly::Expected< Value, Error >::value_or().

157  {
158  Expected<MoveTester, int> ex = makeUnexpected(-1);
159  MoveTester dflt = "hello";
160  EXPECT_EQ("hello", ex.value_or(dflt));
161  EXPECT_EQ("hello", dflt);
162  EXPECT_EQ("hello", ex.value_or(std::move(dflt)));
163  EXPECT_EQ("", dflt);
164  EXPECT_EQ("world", ex.value_or("world"));
165 
166  dflt = "hello";
167  // Make sure that the const overload works on const objects
168  const auto& exc = ex;
169  EXPECT_EQ("hello", exc.value_or(dflt));
170  EXPECT_EQ("hello", dflt);
171  EXPECT_EQ("hello", exc.value_or(std::move(dflt)));
172  EXPECT_EQ("", dflt);
173  EXPECT_EQ("world", exc.value_or("world"));
174 
175  dflt = "hello";
176  ex = "meow";
177  EXPECT_EQ("meow", ex.value_or(dflt));
178  EXPECT_EQ("hello", dflt);
179  EXPECT_EQ("meow", ex.value_or(std::move(dflt)));
180  EXPECT_EQ("hello", dflt); // only moved if used
181 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
constexpr Unexpected< typename std::decay< Error >::type > makeUnexpected(Error &&)
Definition: Expected.h:785
folly::TEST ( LockFreeRingBuffer  ,
readerCanDetectSkips   
)

Definition at line 160 of file LockFreeRingBufferTest.cpp.

References folly::LockFreeRingBuffer< T, Atom >::currentHead(), folly::LockFreeRingBuffer< T, Atom >::currentTail(), EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, i, folly::chrono::round(), folly::LockFreeRingBuffer< T, Atom >::tryRead(), val, folly::LockFreeRingBuffer< T, Atom >::waitAndTryRead(), and folly::LockFreeRingBuffer< T, Atom >::write().

160  {
161  const int capacity = 4;
162  const int rounds = 4;
163 
164  LockFreeRingBuffer<int> rb(capacity);
165  auto cursor = rb.currentHead();
166  cursor.moveForward(1);
167 
168  for (int round = 0; round < rounds; round++) {
169  for (int i = 0; i < capacity; i++) {
170  int val = round * capacity + i;
171  rb.write(val);
172  }
173  }
174 
175  int result = -1;
176  EXPECT_FALSE(rb.tryRead(result, cursor));
177  EXPECT_FALSE(rb.waitAndTryRead(result, cursor));
178  EXPECT_EQ(-1, result);
179 
180  cursor = rb.currentTail();
181  EXPECT_TRUE(rb.tryRead(result, cursor));
182  EXPECT_EQ(capacity * (rounds - 1), result);
183 
184  cursor = rb.currentTail(1.0);
185  EXPECT_TRUE(rb.tryRead(result, cursor));
186  EXPECT_EQ((capacity * rounds) - 1, result);
187 }
constexpr To round(std::chrono::duration< Rep, Period > const &d)
Definition: Chrono.h:139
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
double val
Definition: String.cpp:273
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AtomicWait  ,
Basic   
)

Definition at line 160 of file AtomicNotificationTest.cpp.

160  {
161  run_atomic_wait_basic<std::uint32_t>();
162 }
folly::TEST ( AtomicWait  ,
BasicNonStandardWidths   
)

Definition at line 164 of file AtomicNotificationTest.cpp.

164  {
165  run_atomic_wait_basic<std::uint8_t>();
166  run_atomic_wait_basic<std::uint16_t>();
167  run_atomic_wait_basic<std::uint64_t>();
168 }
folly::TEST ( Optional  ,
value_or_rvalue_arg   
)

Definition at line 170 of file OptionalTest.cpp.

References EXPECT_EQ, folly::gen::move, and folly::Optional< Value >::value_or().

170  {
171  Optional<MoveTester> opt;
172  MoveTester dflt = "hello";
173  EXPECT_EQ("hello", opt.value_or(dflt));
174  EXPECT_EQ("hello", dflt);
175  EXPECT_EQ("hello", opt.value_or(std::move(dflt)));
176  EXPECT_EQ("", dflt);
177  EXPECT_EQ("world", opt.value_or("world"));
178 
179  dflt = "hello";
180  // Make sure that the const overload works on const objects
181  const auto& optc = opt;
182  EXPECT_EQ("hello", optc.value_or(dflt));
183  EXPECT_EQ("hello", dflt);
184  EXPECT_EQ("hello", optc.value_or(std::move(dflt)));
185  EXPECT_EQ("", dflt);
186  EXPECT_EQ("world", optc.value_or("world"));
187 
188  dflt = "hello";
189  opt = "meow";
190  EXPECT_EQ("meow", opt.value_or(dflt));
191  EXPECT_EQ("hello", dflt);
192  EXPECT_EQ("meow", opt.value_or(std::move(dflt)));
193  EXPECT_EQ("hello", dflt); // only moved if used
194 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
folly::TEST ( AtomicWait  ,
AtomicWaitUntilTimeout   
)

Definition at line 170 of file AtomicNotificationTest.cpp.

170  {
171  run_atomic_wait_until_with_timeout<std::uint32_t>();
172 }
folly::TEST ( AtomicWait  ,
AtomicWaitUntilTimeoutNonStandardWidths   
)

Definition at line 174 of file AtomicNotificationTest.cpp.

174  {
175  run_atomic_wait_until_with_timeout<std::uint8_t>();
176  run_atomic_wait_until_with_timeout<std::uint16_t>();
177  run_atomic_wait_until_with_timeout<std::uint64_t>();
178 }
folly::TEST ( AsyncSSLSocketTest2  ,
AttachDetachSSLContext   
)

Test passing contexts between threads

Definition at line 178 of file AsyncSSLSocketTest2.cpp.

References EXPECT_TRUE, f, folly::TestSSLServer::getAddress(), and folly::gen::move.

178  {
179  // Start listening on a local port
180  WriteCallbackBase writeCallback;
181  ReadCallback readCallback(&writeCallback);
182  HandshakeCallback handshakeCallback(&readCallback);
183  SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
184  TestSSLServer server(&acceptCallback);
185 
186  std::shared_ptr<AttachDetachClient> client(
187  new AttachDetachClient(server.getAddress()));
188 
189  auto f = client->getFuture();
190  client->connect();
191  EXPECT_TRUE(std::move(f).within(std::chrono::seconds(3)).get());
192 }
auto f
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( AtomicWait  ,
AtomicWaitUntilNotified   
)

Definition at line 180 of file AtomicNotificationTest.cpp.

180  {
181  run_atomic_wait_until_with_notification<std::uint32_t>();
182 }
folly::TEST ( Expected  ,
value_or_noncopyable   
)

Definition at line 183 of file ExpectedTest.cpp.

References EXPECT_EQ, folly::gen::move, and unexpected().

183  {
184  Expected<std::unique_ptr<int>, int> ex{unexpected, 42};
185  std::unique_ptr<int> dflt(new int(42));
186  EXPECT_EQ(42, *std::move(ex).value_or(std::move(dflt)));
187 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
expected_detail::UnexpectedTag unexpected(expected_detail::UnexpectedTag={})
Definition: Expected.h:656
folly::TEST ( AtomicWait  ,
AtomicWaitUntilNotifiedNonStandardWidths   
)

Definition at line 184 of file AtomicNotificationTest.cpp.

184  {
185  run_atomic_wait_until_with_notification<std::uint8_t>();
186  run_atomic_wait_until_with_notification<std::uint16_t>();
187  run_atomic_wait_until_with_notification<std::uint64_t>();
188 }
folly::TEST ( LockFreeRingBuffer  ,
currentTailRange   
)

Definition at line 189 of file LockFreeRingBufferTest.cpp.

References folly::LockFreeRingBuffer< T, Atom >::currentTail(), EXPECT_EQ, EXPECT_TRUE, val, and folly::LockFreeRingBuffer< T, Atom >::write().

189  {
190  const int capacity = 4;
191  LockFreeRingBuffer<int> rb(capacity);
192 
193  // Workaround for template deduction failure
194  auto (&cursorValue)(value<int, std::atomic>);
195 
196  // Empty buffer - everything points to 0
197  EXPECT_EQ(0, cursorValue(rb.currentTail(0)));
198  EXPECT_EQ(0, cursorValue(rb.currentTail(0.5)));
199  EXPECT_EQ(0, cursorValue(rb.currentTail(1)));
200 
201  // Half-full
202  int val = 5;
203  rb.write(val);
204  rb.write(val);
205 
206  EXPECT_EQ(0, cursorValue(rb.currentTail(0)));
207  EXPECT_EQ(1, cursorValue(rb.currentTail(1)));
208 
209  // Full
210  rb.write(val);
211  rb.write(val);
212 
213  EXPECT_EQ(0, cursorValue(rb.currentTail(0)));
214  EXPECT_EQ(3, cursorValue(rb.currentTail(1)));
215 
216  auto midvalue = cursorValue(rb.currentTail(0.5));
217  // both rounding behaviours are acceptable
218  EXPECT_TRUE(midvalue == 1 || midvalue == 2);
219 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
double val
Definition: String.cpp:273
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( AsyncSSLSocketTest  ,
ConnectWriteReadClose   
)

Test connecting to, writing to, reading from, and closing the connection to the SSL server.

Definition at line 189 of file AsyncSSLSocketTest.cpp.

References EXPECT_EQ, folly::TestSSLServer::getAddress(), folly::netops::socket(), uint32_t, and uint8_t.

189  {
190  // Start listening on a local port
191  WriteCallbackBase writeCallback;
192  ReadCallback readCallback(&writeCallback);
193  HandshakeCallback handshakeCallback(&readCallback);
194  SSLServerAcceptCallback acceptCallback(&handshakeCallback);
195  TestSSLServer server(&acceptCallback);
196 
197  // Set up SSL context.
198  std::shared_ptr<SSLContext> sslContext(new SSLContext());
199  sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
200  // sslContext->loadTrustedCertificates("./trusted-ca-certificate.pem");
201  // sslContext->authenticate(true, false);
202 
203  // connect
204  auto socket =
205  std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
206  socket->open(std::chrono::milliseconds(10000));
207 
208  // write()
209  uint8_t buf[128];
210  memset(buf, 'a', sizeof(buf));
211  socket->write(buf, sizeof(buf));
212 
213  // read()
214  uint8_t readbuf[128];
215  uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
216  EXPECT_EQ(bytesRead, 128);
217  EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
218 
219  // close()
220  socket->close();
221 
222  cerr << "ConnectWriteReadClose test completed" << endl;
223  EXPECT_EQ(socket->getSSLSocket()->getTotalConnectTimeout().count(), 10000);
224 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
folly::TEST ( AtomicWait  ,
AtomicWaitAliasing   
)

Definition at line 190 of file AtomicNotificationTest.cpp.

190  {
191  run_atomic_aliasing<std::uint32_t>();
192 }
folly::TEST ( AtomicWait  ,
AtomicWaitAliasingNonStandardWidths   
)

Definition at line 194 of file AtomicNotificationTest.cpp.

194  {
195  run_atomic_aliasing<std::uint8_t>();
196  run_atomic_aliasing<std::uint16_t>();
197  run_atomic_aliasing<std::uint64_t>();
198 }
folly::TEST ( Optional  ,
value_or_noncopyable   
)

Definition at line 196 of file OptionalTest.cpp.

References EXPECT_EQ, and folly::gen::move.

196  {
197  Optional<std::unique_ptr<int>> opt;
198  std::unique_ptr<int> dflt(new int(42));
199  EXPECT_EQ(42, *std::move(opt).value_or(std::move(dflt)));
200 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
folly::TEST ( Expected  ,
value_move   
)

Definition at line 198 of file ExpectedTest.cpp.

References in_place(), ptr, and value().

198  {
199  auto ptr = Expected<std::unique_ptr<int, ExpectingDeleter>, int>(
200  in_place, new int(42), ExpectingDeleter{1337})
201  .value();
202  *ptr = 1337;
203 }
void * ptr
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
static const char *const value
Definition: Conv.cpp:50
folly::TEST ( Expected  ,
dereference_move   
)

Definition at line 205 of file ExpectedTest.cpp.

References in_place(), and ptr.

205  {
206  auto ptr = *Expected<std::unique_ptr<int, ExpectingDeleter>, int>(
207  in_place, new int(42), ExpectingDeleter{1337});
208  *ptr = 1337;
209 }
void * ptr
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
folly::TEST ( Optional  ,
value_move   
)

Definition at line 211 of file OptionalTest.cpp.

References ptr, and value().

211  {
212  auto ptr = Optional<std::unique_ptr<int, ExpectingDeleter>>(
213  {new int(42), ExpectingDeleter{1337}})
214  .value();
215  *ptr = 1337;
216 }
void * ptr
static const char *const value
Definition: Conv.cpp:50
folly::TEST ( Expected  ,
EmptyConstruct   
)

Definition at line 211 of file ExpectedTest.cpp.

References folly::Expected< Value, Error >::error(), EXPECT_EQ, EXPECT_FALSE, folly::gen::move, and unexpected().

211  {
212  Expected<int, int> ex{unexpected, 42};
213  EXPECT_FALSE(bool(ex));
214  Expected<int, int> test1(ex);
215  EXPECT_FALSE(bool(test1));
216  Expected<int, int> test2(std::move(ex));
217  EXPECT_FALSE(bool(test2));
218  EXPECT_EQ(42, test2.error());
219 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
expected_detail::UnexpectedTag unexpected(expected_detail::UnexpectedTag={})
Definition: Expected.h:656
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Optional  ,
dereference_move   
)

Definition at line 218 of file OptionalTest.cpp.

References ptr.

218  {
219  auto ptr = *Optional<std::unique_ptr<int, ExpectingDeleter>>(
220  {new int(42), ExpectingDeleter{1337}});
221  *ptr = 1337;
222 }
void * ptr
folly::TEST ( Expected  ,
Unique   
)

Definition at line 221 of file ExpectedTest.cpp.

References folly::Expected< Value, Error >::emplace(), EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, makeUnexpected(), and folly::gen::move.

221  {
222  Expected<unique_ptr<int>, int> ex;
223 
224  ex = makeUnexpected(-1);
225  EXPECT_FALSE(bool(ex));
226  // empty->emplaced
227  ex.emplace(new int(5));
228  EXPECT_TRUE(bool(ex));
229  EXPECT_EQ(5, **ex);
230 
231  ex = makeUnexpected(-1);
232  // empty->moved
233  ex = std::make_unique<int>(6);
234  EXPECT_EQ(6, **ex);
235  // full->moved
236  ex = std::make_unique<int>(7);
237  EXPECT_EQ(7, **ex);
238 
239  // move it out by move construct
240  Expected<unique_ptr<int>, int> moved(std::move(ex));
241  EXPECT_TRUE(bool(moved));
242  EXPECT_TRUE(bool(ex));
243  EXPECT_EQ(nullptr, ex->get());
244  EXPECT_EQ(7, **moved);
245 
246  EXPECT_TRUE(bool(moved));
247  ex = std::move(moved); // move it back by move assign
248  EXPECT_TRUE(bool(moved));
249  EXPECT_EQ(nullptr, moved->get());
250  EXPECT_TRUE(bool(ex));
251  EXPECT_EQ(7, **ex);
252 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
constexpr Unexpected< typename std::decay< Error >::type > makeUnexpected(Error &&)
Definition: Expected.h:785
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( LockFreeRingBuffer  ,
cursorFromWrites   
)

Definition at line 221 of file LockFreeRingBufferTest.cpp.

References EXPECT_EQ, val, and folly::LockFreeRingBuffer< T, Atom >::writeAndGetCursor().

221  {
222  const int capacity = 3;
223  LockFreeRingBuffer<int> rb(capacity);
224 
225  // Workaround for template deduction failure
226  auto (&cursorValue)(value<int, std::atomic>);
227 
228  int val = 0xfaceb00c;
229  EXPECT_EQ(0, cursorValue(rb.writeAndGetCursor(val)));
230  EXPECT_EQ(1, cursorValue(rb.writeAndGetCursor(val)));
231  EXPECT_EQ(2, cursorValue(rb.writeAndGetCursor(val)));
232 
233  // Check that rb is giving out actual cursors and not just
234  // pointing to the current slot.
235  EXPECT_EQ(3, cursorValue(rb.writeAndGetCursor(val)));
236 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
double val
Definition: String.cpp:273
folly::TEST ( Optional  ,
EmptyConstruct   
)

Definition at line 224 of file OptionalTest.cpp.

References EXPECT_FALSE, and folly::gen::move.

224  {
225  Optional<int> opt;
226  EXPECT_FALSE(bool(opt));
227  Optional<int> test1(opt);
228  EXPECT_FALSE(bool(test1));
229  Optional<int> test2(std::move(opt));
230  EXPECT_FALSE(bool(test2));
231 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncSSLSocketTest  ,
ReadAfterClose   
)

Test reading after server close.

Definition at line 229 of file AsyncSSLSocketTest.cpp.

References folly::HandshakeCallback::closeSocket(), EXPECT_EQ, folly::HandshakeCallback::getSocket(), and folly::netops::socket().

229  {
230  // Start listening on a local port
231  WriteCallbackBase writeCallback;
232  ReadEOFCallback readCallback(&writeCallback);
233  HandshakeCallback handshakeCallback(&readCallback);
234  SSLServerAcceptCallback acceptCallback(&handshakeCallback);
235  auto server = std::make_unique<TestSSLServer>(&acceptCallback);
236 
237  // Set up SSL context.
238  auto sslContext = std::make_shared<SSLContext>();
239  sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
240 
241  auto socket =
242  std::make_shared<BlockingSocket>(server->getAddress(), sslContext);
243  socket->open();
244 
245  // This should trigger an EOF on the client.
246  auto evb = handshakeCallback.getSocket()->getEventBase();
247  evb->runInEventBaseThreadAndWait([&]() { handshakeCallback.closeSocket(); });
248  std::array<uint8_t, 128> readbuf;
249  auto bytesRead = socket->read(readbuf.data(), readbuf.size());
250  EXPECT_EQ(0, bytesRead);
251 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
folly::TEST ( DistributedMutex  ,
InternalDetailTestOne   
)

Definition at line 231 of file DistributedMutexTest.cpp.

References EXPECT_EQ, ptr, and value.

231  {
232  auto value = 0;
233  auto ptr = reinterpret_cast<std::uintptr_t>(&value);
234  EXPECT_EQ(detail::distributed_mutex::extractAddress<int>(ptr), &value);
235  ptr = ptr | 0b1;
236  EXPECT_EQ(detail::distributed_mutex::extractAddress<int>(ptr), &value);
237 }
void * ptr
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
static const char *const value
Definition: Conv.cpp:50
folly::TEST ( Optional  ,
InPlaceConstruct   
)

Definition at line 233 of file OptionalTest.cpp.

References EXPECT_EQ, EXPECT_TRUE, and in_place().

233  {
234  using A = std::pair<int, double>;
235  Optional<A> opt(in_place, 5, 3.2);
236  EXPECT_TRUE(bool(opt));
237  EXPECT_EQ(5, opt->first);
238 }
std::unique_ptr< int > A
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( LockFreeRingBuffer  ,
moveBackwardsCanFail   
)

Definition at line 238 of file LockFreeRingBufferTest.cpp.

References folly::LockFreeRingBuffer< T, Atom >::currentHead(), EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, val, and folly::LockFreeRingBuffer< T, Atom >::write().

238  {
239  const int capacity = 3;
240  LockFreeRingBuffer<int> rb(capacity);
241 
242  // Workaround for template deduction failure
243  auto (&cursorValue)(value<int, std::atomic>);
244 
245  int val = 0xfaceb00c;
246  rb.write(val);
247  rb.write(val);
248 
249  auto cursor = rb.currentHead(); // points to 2
250  EXPECT_EQ(2, cursorValue(cursor));
251  EXPECT_TRUE(cursor.moveBackward());
252  EXPECT_TRUE(cursor.moveBackward()); // now at 0
253  EXPECT_FALSE(cursor.moveBackward()); // moving back does nothing
254 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
double val
Definition: String.cpp:273
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( DistributedMutex  ,
Basic   
)

Definition at line 239 of file DistributedMutexTest.cpp.

References folly::gen::move, and mutex.

239  {
240  auto&& mutex = DistributedMutex{};
241  auto state = mutex.lock();
242  mutex.unlock(std::move(state));
243 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::mutex mutex
detail::distributed_mutex::DistributedMutex<> DistributedMutex
state
Definition: http_parser.c:272
folly::TEST ( Optional  ,
InPlaceNestedConstruct   
)

Definition at line 240 of file OptionalTest.cpp.

References EXPECT_EQ, EXPECT_TRUE, and in_place().

240  {
241  using A = std::pair<int, double>;
242  Optional<Optional<A>> opt(in_place, in_place, 5, 3.2);
243  EXPECT_TRUE(bool(opt));
244  EXPECT_TRUE(bool(*opt));
245  EXPECT_EQ(5, (*opt)->first);
246 }
std::unique_ptr< int > A
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( DistributedMutex  ,
BasicTryLock   
)

Definition at line 245 of file DistributedMutexTest.cpp.

References folly::gen::move, and mutex.

245  {
246  auto&& mutex = DistributedMutex{};
247 
248  while (true) {
249  auto state = mutex.try_lock();
250  if (state) {
251  mutex.unlock(std::move(state));
252  break;
253  }
254  }
255 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::mutex mutex
detail::distributed_mutex::DistributedMutex<> DistributedMutex
state
Definition: http_parser.c:272
folly::TEST ( AsyncSSLSocketTest2  ,
TestTLS12DefaultClient   
)

Definition at line 245 of file AsyncSSLSocketTest2.cpp.

References EXPECT_TRUE, folly::gen::move, and folly::SSLContext::TLSv1_2.

245  {
246  // Start listening on a local port
247  NoopReadCallback readCallback;
248  HandshakeCallback handshakeCallback(&readCallback);
249  SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
250  auto ctx = std::make_shared<SSLContext>(SSLContext::TLSv1_2);
251  TestSSLServer server(&acceptCallback, ctx);
252  server.loadTestCerts();
253 
254  // create a default client
255  auto c1 = std::make_unique<ConnectClient>();
256  auto f1 = c1->getFuture();
257  c1->connect(server.getAddress());
258  EXPECT_TRUE(std::move(f1).within(std::chrono::seconds(3)).get());
259 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( Optional  ,
Unique   
)

Definition at line 248 of file OptionalTest.cpp.

References folly::Optional< Value >::clear(), folly::Optional< Value >::emplace(), EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, and folly::gen::move.

248  {
249  Optional<unique_ptr<int>> opt;
250 
251  opt.clear();
252  EXPECT_FALSE(bool(opt));
253  // empty->emplaced
254  opt.emplace(new int(5));
255  EXPECT_TRUE(bool(opt));
256  EXPECT_EQ(5, **opt);
257 
258  opt.clear();
259  // empty->moved
260  opt = std::make_unique<int>(6);
261  EXPECT_EQ(6, **opt);
262  // full->moved
263  opt = std::make_unique<int>(7);
264  EXPECT_EQ(7, **opt);
265 
266  // move it out by move construct
267  Optional<unique_ptr<int>> moved(std::move(opt));
268  EXPECT_TRUE(bool(moved));
269  EXPECT_FALSE(bool(opt));
270  EXPECT_EQ(7, **moved);
271 
272  EXPECT_TRUE(bool(moved));
273  opt = std::move(moved); // move it back by move assign
274  EXPECT_FALSE(bool(moved));
275  EXPECT_TRUE(bool(opt));
276  EXPECT_EQ(7, **opt);
277 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Expected  ,
Shared   
)

Definition at line 254 of file ExpectedTest.cpp.

References EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, makeUnexpected(), folly::gen::move, ptr, and unexpected().

254  {
256  Expected<shared_ptr<int>, int> ex{unexpected, -1};
257  EXPECT_FALSE(bool(ex));
258  // empty->emplaced
259  ex.emplace(new int(5));
260  EXPECT_TRUE(bool(ex));
261  ptr = ex.value();
262  EXPECT_EQ(ptr.get(), ex->get());
263  EXPECT_EQ(2, ptr.use_count());
264  ex = makeUnexpected(-1);
265  EXPECT_EQ(1, ptr.use_count());
266  // full->copied
267  ex = ptr;
268  EXPECT_EQ(2, ptr.use_count());
269  EXPECT_EQ(ptr.get(), ex->get());
270  ex = makeUnexpected(-1);
271  EXPECT_EQ(1, ptr.use_count());
272  // full->moved
273  ex = std::move(ptr);
274  EXPECT_EQ(1, ex->use_count());
275  EXPECT_EQ(nullptr, ptr.get());
276  {
277  EXPECT_EQ(1, ex->use_count());
278  Expected<shared_ptr<int>, int> copied(ex);
279  EXPECT_EQ(2, ex->use_count());
280  Expected<shared_ptr<int>, int> moved(std::move(ex));
281  EXPECT_EQ(2, moved->use_count());
282  moved.emplace(new int(6));
283  EXPECT_EQ(1, moved->use_count());
284  copied = moved;
285  EXPECT_EQ(2, moved->use_count());
286  }
287 }
void * ptr
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
constexpr Unexpected< typename std::decay< Error >::type > makeUnexpected(Error &&)
Definition: Expected.h:785
expected_detail::UnexpectedTag unexpected(expected_detail::UnexpectedTag={})
Definition: Expected.h:656
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( DistributedMutex  ,
TestSingleElementContentionChain   
)

Definition at line 257 of file DistributedMutexTest.cpp.

References i, folly::gen::move, and mutex.

257  {
258  using namespace folly::detail;
259 
260  // Acquire the mutex once, let another thread form a contention chain on the
261  // mutex, and then release it. Observe the other thread grab the lock
262  auto&& schedule = test::ManualSchedule{};
263  auto&& mutex = test::TestDistributedMutex<test::ManualAtomic>{};
264 
265  auto&& waiter = std::thread{[&]() {
266  schedule.setCallback([&, i = 0]() mutable {
267  if (i == 2) {
268  schedule.post(1);
269  }
270  ++i;
271  });
272 
273  schedule.wait(0);
274  auto state = mutex.lock();
275  mutex.unlock(std::move(state));
276  }};
277 
278  // lock the mutex, signal the waiter, and then wait till the first thread
279  // has gotten on the wait list
280  auto state = mutex.lock();
281  schedule.post(0);
282  schedule.wait(1);
283 
284  // release the mutex, and then wait for the waiter to acquire the lock
285  mutex.unlock(std::move(state));
286  waiter.join();
287 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::mutex mutex
state
Definition: http_parser.c:272
folly::TEST ( AsyncSSLSocketTest  ,
Renegotiate   
)

Test bad renegotiation

Definition at line 257 of file AsyncSSLSocketTest.cpp.

References ASSERT_TRUE, getctx(), getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, INFO, folly::EventBase::loop(), folly::EventBase::loopForever(), folly::EventBase::loopOnce(), folly::gen::move, folly::RenegotiatingServer::renegotiationError_, folly::netops::socket(), folly::pushmi::detail::t, and folly::EventBase::terminateLoopSoon().

257  {
258  EventBase eventBase;
259  auto clientCtx = std::make_shared<SSLContext>();
260  auto dfServerCtx = std::make_shared<SSLContext>();
261  std::array<int, 2> fds;
262  getfds(fds.data());
263  getctx(clientCtx, dfServerCtx);
264 
265  AsyncSSLSocket::UniquePtr clientSock(
266  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
267  AsyncSSLSocket::UniquePtr serverSock(
268  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
269  SSLHandshakeClient client(std::move(clientSock), true, true);
270  RenegotiatingServer server(std::move(serverSock));
271 
272  while (!client.handshakeSuccess_ && !client.handshakeError_) {
273  eventBase.loopOnce();
274  }
275 
276  ASSERT_TRUE(client.handshakeSuccess_);
277 
278  auto sslSock = std::move(client).moveSocket();
279  sslSock->detachEventBase();
280  // This is nasty, however we don't want to add support for
281  // renegotiation in AsyncSSLSocket.
282  SSL_renegotiate(const_cast<SSL*>(sslSock->getSSL()));
283 
284  auto socket = std::make_shared<BlockingSocket>(std::move(sslSock));
285 
286  std::thread t([&]() { eventBase.loopForever(); });
287 
288  // Trigger the renegotiation.
289  std::array<uint8_t, 128> buf;
290  memset(buf.data(), 'a', buf.size());
291  try {
292  socket->write(buf.data(), buf.size());
293  } catch (AsyncSocketException& e) {
294  LOG(INFO) << "client got error " << e.what();
295  }
296  eventBase.terminateLoopSoon();
297  t.join();
298 
299  eventBase.loop();
300  ASSERT_TRUE(server.renegotiationError_);
301 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void getfds(int fds[2])
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST ( AsyncSSLSocketTest2  ,
TestTLS12BadClient   
)

Definition at line 261 of file AsyncSSLSocketTest2.cpp.

References folly::HandshakeCallback::EXPECT_ERROR, EXPECT_FALSE, folly::gen::move, and folly::SSLContext::TLSv1_2.

261  {
262  // Start listening on a local port
263  NoopReadCallback readCallback;
264  HandshakeCallback handshakeCallback(
265  &readCallback, HandshakeCallback::EXPECT_ERROR);
266  SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
267  auto ctx = std::make_shared<SSLContext>(SSLContext::TLSv1_2);
268  TestSSLServer server(&acceptCallback, ctx);
269  server.loadTestCerts();
270 
271  // create a client that doesn't speak TLS 1.2
272  auto c2 = std::make_unique<ConnectClient>();
273  auto clientCtx = std::make_shared<SSLContext>();
274  clientCtx->setOptions(SSL_OP_NO_TLSv1_2);
275  c2->setCtx(clientCtx);
276  auto f2 = c2->getFuture();
277  c2->connect(server.getAddress());
278  EXPECT_FALSE(std::move(f2).within(std::chrono::seconds(3)).get());
279 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Optional  ,
Shared   
)

Definition at line 279 of file OptionalTest.cpp.

References folly::Optional< Value >::clear(), folly::Optional< Value >::emplace(), EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, folly::gen::move, ptr, and folly::Optional< Value >::value().

279  {
281  Optional<shared_ptr<int>> opt;
282  EXPECT_FALSE(bool(opt));
283  // empty->emplaced
284  opt.emplace(new int(5));
285  EXPECT_TRUE(bool(opt));
286  ptr = opt.value();
287  EXPECT_EQ(ptr.get(), opt->get());
288  EXPECT_EQ(2, ptr.use_count());
289  opt.clear();
290  EXPECT_EQ(1, ptr.use_count());
291  // full->copied
292  opt = ptr;
293  EXPECT_EQ(2, ptr.use_count());
294  EXPECT_EQ(ptr.get(), opt->get());
295  opt.clear();
296  EXPECT_EQ(1, ptr.use_count());
297  // full->moved
298  opt = std::move(ptr);
299  EXPECT_EQ(1, opt->use_count());
300  EXPECT_EQ(nullptr, ptr.get());
301  {
302  Optional<shared_ptr<int>> copied(opt);
303  EXPECT_EQ(2, opt->use_count());
304  Optional<shared_ptr<int>> moved(std::move(opt));
305  EXPECT_EQ(2, moved->use_count());
306  moved.emplace(new int(6));
307  EXPECT_EQ(1, moved->use_count());
308  copied = moved;
309  EXPECT_EQ(2, moved->use_count());
310  }
311 }
void * ptr
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( DistributedMutex  ,
TestTwoElementContentionChain   
)

Definition at line 289 of file DistributedMutexTest.cpp.

References i, folly::gen::move, and mutex.

289  {
290  using namespace folly::detail;
291 
292  // Acquire the mutex once, let another thread form a contention chain on the
293  // mutex, and then release it. Observe the other thread grab the lock
294  auto&& schedule = test::ManualSchedule{};
295  auto&& mutex = test::TestDistributedMutex<test::ManualAtomic>{};
296 
297  auto&& one = std::thread{[&]() {
298  schedule.setCallback([&, i = 0]() mutable {
299  if (i == 2) {
300  schedule.post(3);
301  }
302  ++i;
303  });
304 
305  schedule.wait(0);
306  auto state = mutex.lock();
307  mutex.unlock(std::move(state));
308  }};
309 
310  auto&& two = std::thread{[&]() {
311  schedule.setCallback([&, i = 0]() mutable {
312  if (i == 2) {
313  schedule.post(2);
314  }
315  ++i;
316  });
317 
318  schedule.wait(1);
319  auto state = mutex.lock();
320  mutex.unlock(std::move(state));
321  }};
322 
323  // lock the mutex, signal the waiter, and then wait till the first thread
324  // has gotten on the wait list
325  auto state = mutex.lock();
326  schedule.post(0);
327  schedule.post(1);
328  schedule.wait(2);
329  schedule.wait(3);
330 
331  // release the mutex, and then wait for the waiter to acquire the lock
332  mutex.unlock(std::move(state));
333  one.join();
334  two.join();
335 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::mutex mutex
state
Definition: http_parser.c:272
folly::TEST ( Expected  ,
Order   
)

Definition at line 289 of file ExpectedTest.cpp.

References E1, EXPECT_EQ, and unexpected().

289  {
290  std::vector<Expected<int, E>> vect{
291  {unexpected, E::E1},
292  {3},
293  {1},
294  {unexpected, E::E1},
295  {2},
296  };
297  std::vector<Expected<int, E>> expected{
298  {unexpected, E::E1},
299  {unexpected, E::E1},
300  {1},
301  {2},
302  {3},
303  };
304  std::sort(vect.begin(), vect.end());
305  EXPECT_EQ(vect, expected);
306 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
expected_detail::UnexpectedTag unexpected(expected_detail::UnexpectedTag={})
Definition: Expected.h:656
folly::TEST ( AsyncSSLSocketTest  ,
HandshakeError   
)

Negative test for handshakeError().

Definition at line 307 of file AsyncSSLSocketTest.cpp.

References EXPECT_TRUE, folly::TestSSLServer::getAddress(), folly::netops::socket(), uint32_t, and uint8_t.

307  {
308  // Start listening on a local port
309  WriteCallbackBase writeCallback;
310  WriteErrorCallback readCallback(&writeCallback);
311  HandshakeCallback handshakeCallback(&readCallback);
312  HandshakeErrorCallback acceptCallback(&handshakeCallback);
313  TestSSLServer server(&acceptCallback);
314 
315  // Set up SSL context.
316  std::shared_ptr<SSLContext> sslContext(new SSLContext());
317  sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
318 
319  // connect
320  auto socket =
321  std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
322  // read()
323  bool ex = false;
324  try {
325  socket->open();
326 
327  uint8_t readbuf[128];
328  uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
329  LOG(ERROR) << "readAll returned " << bytesRead << " instead of throwing";
330  } catch (AsyncSocketException&) {
331  ex = true;
332  }
333  EXPECT_TRUE(ex);
334 
335  // close()
336  socket->close();
337  cerr << "HandshakeError test completed" << endl;
338 }
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( Expected  ,
SwapMethod   
)

Definition at line 308 of file ExpectedTest.cpp.

References a, b, EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, folly::Expected< Value, Error >::hasValue(), folly::Expected< Value, Error >::swap(), and folly::Expected< Value, Error >::value().

308  {
309  Expected<std::string, E> a;
310  Expected<std::string, E> b;
311 
312  a.swap(b);
313  EXPECT_FALSE(a.hasValue());
314  EXPECT_FALSE(b.hasValue());
315 
316  a = "hello";
317  EXPECT_TRUE(a.hasValue());
318  EXPECT_FALSE(b.hasValue());
319  EXPECT_EQ("hello", a.value());
320 
321  b.swap(a);
322  EXPECT_FALSE(a.hasValue());
323  EXPECT_TRUE(b.hasValue());
324  EXPECT_EQ("hello", b.value());
325 
326  a = "bye";
327  EXPECT_TRUE(a.hasValue());
328  EXPECT_EQ("bye", a.value());
329 
330  a.swap(b);
331  EXPECT_EQ("hello", a.value());
332  EXPECT_EQ("bye", b.value());
333 }
char b
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
char a
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Optional  ,
Order   
)

Definition at line 313 of file OptionalTest.cpp.

References EXPECT_EQ, and none.

313  {
314  std::vector<Optional<int>> vect{
315  {none},
316  {3},
317  {1},
318  {none},
319  {2},
320  };
321  std::vector<Optional<int>> expected{
322  {none},
323  {none},
324  {1},
325  {2},
326  {3},
327  };
328  std::sort(vect.begin(), vect.end());
329  EXPECT_EQ(vect, expected);
330 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr None none
Definition: Optional.h:87
folly::TEST ( Optional  ,
Swap   
)

Definition at line 332 of file OptionalTest.cpp.

References folly::NoDefault::a, folly::NoDefault::b, EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, folly::Optional< Value >::hasValue(), swap(), and folly::Optional< Value >::value().

332  {
333  Optional<std::string> a;
334  Optional<std::string> b;
335 
336  swap(a, b);
337  EXPECT_FALSE(a.hasValue());
338  EXPECT_FALSE(b.hasValue());
339 
340  a = "hello";
341  EXPECT_TRUE(a.hasValue());
342  EXPECT_FALSE(b.hasValue());
343  EXPECT_EQ("hello", a.value());
344 
345  swap(a, b);
346  EXPECT_FALSE(a.hasValue());
347  EXPECT_TRUE(b.hasValue());
348  EXPECT_EQ("hello", b.value());
349 
350  a = "bye";
351  EXPECT_TRUE(a.hasValue());
352  EXPECT_EQ("bye", a.value());
353 
354  swap(a, b);
355  EXPECT_TRUE(a.hasValue());
356  EXPECT_TRUE(b.hasValue());
357  EXPECT_EQ("hello", a.value());
358  EXPECT_EQ("bye", b.value());
359 }
char b
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
char a
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
void swap(SwapTrackingAlloc< T > &, SwapTrackingAlloc< T > &)
Definition: F14TestUtil.h:414
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Expected  ,
StdSwapFunction   
)

Definition at line 335 of file ExpectedTest.cpp.

References a, b, EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, folly::Expected< Value, Error >::hasValue(), folly::f14::swap(), and folly::Expected< Value, Error >::value().

335  {
336  Expected<std::string, E> a;
337  Expected<std::string, E> b;
338 
339  std::swap(a, b);
340  EXPECT_FALSE(a.hasValue());
341  EXPECT_FALSE(b.hasValue());
342 
343  a = "greeting";
344  EXPECT_TRUE(a.hasValue());
345  EXPECT_FALSE(b.hasValue());
346  EXPECT_EQ("greeting", a.value());
347 
348  std::swap(a, b);
349  EXPECT_FALSE(a.hasValue());
350  EXPECT_TRUE(b.hasValue());
351  EXPECT_EQ("greeting", b.value());
352 
353  a = "goodbye";
354  EXPECT_TRUE(a.hasValue());
355  EXPECT_EQ("goodbye", a.value());
356 
357  std::swap(a, b);
358  EXPECT_EQ("greeting", a.value());
359  EXPECT_EQ("goodbye", b.value());
360 }
char b
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
char a
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
void swap(SwapTrackingAlloc< T > &, SwapTrackingAlloc< T > &)
Definition: F14TestUtil.h:414
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( DistributedMutex  ,
TestTwoContentionChains   
)

Definition at line 337 of file DistributedMutexTest.cpp.

References i, folly::gen::move, and mutex.

337  {
338  using namespace folly::detail;
339 
340  auto&& schedule = test::ManualSchedule{};
341  auto&& mutex = test::TestDistributedMutex<test::ManualAtomic>{};
342 
343  auto&& one = std::thread{[&]() {
344  schedule.setCallback([&, i = 0]() mutable {
345  if (i == 2) {
346  schedule.post(0);
347  }
348  ++i;
349  });
350 
351  schedule.wait(1);
352  auto state = mutex.lock();
353  schedule.wait(4);
354  mutex.unlock(std::move(state));
355  }};
356  auto&& two = std::thread{[&]() {
357  schedule.setCallback([&, i = 0]() mutable {
358  if (i == 2) {
359  schedule.post(2);
360  }
361  ++i;
362  });
363 
364  schedule.wait(3);
365  auto state = mutex.lock();
366  schedule.wait(5);
367  mutex.unlock(std::move(state));
368  }};
369 
370  auto state = mutex.lock();
371  schedule.post(1);
372  schedule.post(3);
373  schedule.wait(0);
374  schedule.wait(2);
375 
376  // at this point there is one contention chain. Release it
377  mutex.unlock(std::move(state));
378 
379  // then start a new contention chain
380  auto&& three = std::thread{[&]() {
381  schedule.setCallback([&, i = 0]() mutable {
382  if (i == 2) {
383  schedule.post(4);
384  schedule.post(5);
385  }
386  ++i;
387  });
388 
389  auto lockState = mutex.lock();
390  schedule.post(6);
391  mutex.unlock(std::move(lockState));
392  }};
393 
394  // wait for the third thread to pick up the lock
395  schedule.wait(6);
396  one.join();
397  two.join();
398  three.join();
399 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::mutex mutex
state
Definition: http_parser.c:272
folly::TEST ( AsyncSSLSocketTest  ,
ReadError   
)

Negative test for readError().

Definition at line 343 of file AsyncSSLSocketTest.cpp.

References folly::TestSSLServer::getAddress(), folly::netops::socket(), and uint8_t.

343  {
344  // Start listening on a local port
345  WriteCallbackBase writeCallback;
346  ReadErrorCallback readCallback(&writeCallback);
347  HandshakeCallback handshakeCallback(&readCallback);
348  SSLServerAcceptCallback acceptCallback(&handshakeCallback);
349  TestSSLServer server(&acceptCallback);
350 
351  // Set up SSL context.
352  std::shared_ptr<SSLContext> sslContext(new SSLContext());
353  sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
354 
355  // connect
356  auto socket =
357  std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
358  socket->open();
359 
360  // write something to trigger ssl handshake
361  uint8_t buf[128];
362  memset(buf, 'a', sizeof(buf));
363  socket->write(buf, sizeof(buf));
364 
365  socket->close();
366  cerr << "ReadError test completed" << endl;
367 }
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
folly::TEST ( Optional  ,
Comparisons   
)

Definition at line 361 of file OptionalTest.cpp.

References EXPECT_FALSE, and EXPECT_TRUE.

361  {
362  Optional<int> o_;
363  Optional<int> o1(1);
364  Optional<int> o2(2);
365 
366  EXPECT_TRUE(o_ <= (o_));
367  EXPECT_TRUE(o_ == (o_));
368  EXPECT_TRUE(o_ >= (o_));
369 
370  EXPECT_TRUE(o1 < o2);
371  EXPECT_TRUE(o1 <= o2);
372  EXPECT_TRUE(o1 <= (o1));
373  EXPECT_TRUE(o1 == (o1));
374  EXPECT_TRUE(o1 != o2);
375  EXPECT_TRUE(o1 >= (o1));
376  EXPECT_TRUE(o2 >= o1);
377  EXPECT_TRUE(o2 > o1);
378 
379  EXPECT_FALSE(o2 < o1);
380  EXPECT_FALSE(o2 <= o1);
381  EXPECT_FALSE(o2 <= o1);
382  EXPECT_FALSE(o2 == o1);
383  EXPECT_FALSE(o1 != (o1));
384  EXPECT_FALSE(o1 >= o2);
385  EXPECT_FALSE(o1 >= o2);
386  EXPECT_FALSE(o1 > o2);
387 
388  /* folly::Optional explicitly doesn't support comparisons with contained value
389  EXPECT_TRUE(1 < o2);
390  EXPECT_TRUE(1 <= o2);
391  EXPECT_TRUE(1 <= o1);
392  EXPECT_TRUE(1 == o1);
393  EXPECT_TRUE(2 != o1);
394  EXPECT_TRUE(1 >= o1);
395  EXPECT_TRUE(2 >= o1);
396  EXPECT_TRUE(2 > o1);
397 
398  EXPECT_FALSE(o2 < 1);
399  EXPECT_FALSE(o2 <= 1);
400  EXPECT_FALSE(o2 <= 1);
401  EXPECT_FALSE(o2 == 1);
402  EXPECT_FALSE(o2 != 2);
403  EXPECT_FALSE(o1 >= 2);
404  EXPECT_FALSE(o1 >= 2);
405  EXPECT_FALSE(o1 > 2);
406  */
407 
408  // boost::optional does support comparison with contained value, which can
409  // lead to confusion when a bool is contained
410  boost::optional<int> boi(3);
411  EXPECT_TRUE(boi < 5);
412  EXPECT_TRUE(boi <= 4);
413  EXPECT_TRUE(boi == 3);
414  EXPECT_TRUE(boi != 2);
415  EXPECT_TRUE(boi >= 1);
416  EXPECT_TRUE(boi > 0);
417  EXPECT_TRUE(1 < boi);
418  EXPECT_TRUE(2 <= boi);
419  EXPECT_TRUE(3 == boi);
420  EXPECT_TRUE(4 != boi);
421  EXPECT_TRUE(5 >= boi);
422  EXPECT_TRUE(6 > boi);
423 
424  boost::optional<bool> bob(false);
425  EXPECT_TRUE((bool)bob);
426  EXPECT_TRUE(bob == false); // well that was confusing
427  EXPECT_FALSE(bob != false);
428 }
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Expected  ,
FollySwapFunction   
)

Definition at line 362 of file ExpectedTest.cpp.

References a, b, EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, folly::Expected< Value, Error >::hasValue(), swap(), and folly::Expected< Value, Error >::value().

362  {
363  Expected<std::string, E> a;
364  Expected<std::string, E> b;
365 
366  folly::swap(a, b);
367  EXPECT_FALSE(a.hasValue());
368  EXPECT_FALSE(b.hasValue());
369 
370  a = "salute";
371  EXPECT_TRUE(a.hasValue());
372  EXPECT_FALSE(b.hasValue());
373  EXPECT_EQ("salute", a.value());
374 
375  folly::swap(a, b);
376  EXPECT_FALSE(a.hasValue());
377  EXPECT_TRUE(b.hasValue());
378  EXPECT_EQ("salute", b.value());
379 
380  a = "adieu";
381  EXPECT_TRUE(a.hasValue());
382  EXPECT_EQ("adieu", a.value());
383 
384  folly::swap(a, b);
385  EXPECT_EQ("salute", a.value());
386  EXPECT_EQ("adieu", b.value());
387 }
char b
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
char a
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
void swap(exception_wrapper &a, exception_wrapper &b) noexcept
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncSSLSocketTest  ,
WriteError   
)

Negative test for writeError().

Definition at line 372 of file AsyncSSLSocketTest.cpp.

References folly::TestSSLServer::getAddress(), folly::netops::socket(), and uint8_t.

372  {
373  // Start listening on a local port
374  WriteCallbackBase writeCallback;
375  WriteErrorCallback readCallback(&writeCallback);
376  HandshakeCallback handshakeCallback(&readCallback);
377  SSLServerAcceptCallback acceptCallback(&handshakeCallback);
378  TestSSLServer server(&acceptCallback);
379 
380  // Set up SSL context.
381  std::shared_ptr<SSLContext> sslContext(new SSLContext());
382  sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
383 
384  // connect
385  auto socket =
386  std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
387  socket->open();
388 
389  // write something to trigger ssl handshake
390  uint8_t buf[128];
391  memset(buf, 'a', sizeof(buf));
392  socket->write(buf, sizeof(buf));
393 
394  socket->close();
395  cerr << "WriteError test completed" << endl;
396 }
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
folly::TEST ( Expected  ,
Comparisons   
)

Definition at line 389 of file ExpectedTest.cpp.

References EXPECT_FALSE, and EXPECT_TRUE.

389  {
390  Expected<int, E> o_;
391  Expected<int, E> o1(1);
392  Expected<int, E> o2(2);
393 
394  EXPECT_TRUE(o_ <= (o_));
395  EXPECT_TRUE(o_ == (o_));
396  EXPECT_TRUE(o_ >= (o_));
397 
398  EXPECT_TRUE(o1 < o2);
399  EXPECT_TRUE(o1 <= o2);
400  EXPECT_TRUE(o1 <= (o1));
401  EXPECT_TRUE(o1 == (o1));
402  EXPECT_TRUE(o1 != o2);
403  EXPECT_TRUE(o1 >= (o1));
404  EXPECT_TRUE(o2 >= o1);
405  EXPECT_TRUE(o2 > o1);
406 
407  EXPECT_FALSE(o2 < o1);
408  EXPECT_FALSE(o2 <= o1);
409  EXPECT_FALSE(o2 <= o1);
410  EXPECT_FALSE(o2 == o1);
411  EXPECT_FALSE(o1 != (o1));
412  EXPECT_FALSE(o1 >= o2);
413  EXPECT_FALSE(o1 >= o2);
414  EXPECT_FALSE(o1 > o2);
415 
416  /* folly::Expected explicitly doesn't support comparisons with contained value
417  EXPECT_TRUE(1 < o2);
418  EXPECT_TRUE(1 <= o2);
419  EXPECT_TRUE(1 <= o1);
420  EXPECT_TRUE(1 == o1);
421  EXPECT_TRUE(2 != o1);
422  EXPECT_TRUE(1 >= o1);
423  EXPECT_TRUE(2 >= o1);
424  EXPECT_TRUE(2 > o1);
425 
426  EXPECT_FALSE(o2 < 1);
427  EXPECT_FALSE(o2 <= 1);
428  EXPECT_FALSE(o2 <= 1);
429  EXPECT_FALSE(o2 == 1);
430  EXPECT_FALSE(o2 != 2);
431  EXPECT_FALSE(o1 >= 2);
432  EXPECT_FALSE(o1 >= 2);
433  EXPECT_FALSE(o1 > 2);
434  */
435 }
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( DistributedMutex  ,
StressTwoThreads   
)

Definition at line 401 of file DistributedMutexTest.cpp.

401  {
402  basicNThreads(2);
403 }
folly::TEST ( AsyncSSLSocketTest  ,
SocketWithDelay   
)

Test a socket with TCP_NODELAY unset.

Definition at line 401 of file AsyncSSLSocketTest.cpp.

References folly::netops::connect(), EXPECT_EQ, EXPECT_FALSE, EXPECT_NE, EXPECT_TRUE, folly::TestSSLServer::getAddress(), getctx(), getfds(), i, folly::gen::move, folly::netops::socket(), string, testing::TEST_F(), uint32_t, and uint8_t.

401  {
402  // Start listening on a local port
403  WriteCallbackBase writeCallback;
404  ReadCallback readCallback(&writeCallback);
405  HandshakeCallback handshakeCallback(&readCallback);
406  SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
407  TestSSLServer server(&acceptCallback);
408 
409  // Set up SSL context.
410  std::shared_ptr<SSLContext> sslContext(new SSLContext());
411  sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
412 
413  // connect
414  auto socket =
415  std::make_shared<BlockingSocket>(server.getAddress(), sslContext);
416  socket->open();
417 
418  // write()
419  uint8_t buf[128];
420  memset(buf, 'a', sizeof(buf));
421  socket->write(buf, sizeof(buf));
422 
423  // read()
424  uint8_t readbuf[128];
425  uint32_t bytesRead = socket->readAll(readbuf, sizeof(readbuf));
426  EXPECT_EQ(bytesRead, 128);
427  EXPECT_EQ(memcmp(buf, readbuf, bytesRead), 0);
428 
429  // close()
430  socket->close();
431 
432  cerr << "SocketWithDelay test completed" << endl;
433 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
folly::TEST ( DistributedMutex  ,
StressThreeThreads   
)

Definition at line 404 of file DistributedMutexTest.cpp.

404  {
405  basicNThreads(3);
406 }
folly::TEST ( DistributedMutex  ,
StressFourThreads   
)

Definition at line 407 of file DistributedMutexTest.cpp.

407  {
408  basicNThreads(4);
409 }
folly::TEST ( DistributedMutex  ,
StressFiveThreads   
)

Definition at line 410 of file DistributedMutexTest.cpp.

410  {
411  basicNThreads(5);
412 }
folly::TEST ( DistributedMutex  ,
StressSixThreads   
)

Definition at line 413 of file DistributedMutexTest.cpp.

413  {
414  basicNThreads(6);
415 }
folly::TEST ( DistributedMutex  ,
StressSevenThreads   
)

Definition at line 416 of file DistributedMutexTest.cpp.

416  {
417  basicNThreads(7);
418 }
folly::TEST ( DistributedMutex  ,
StressEightThreads   
)

Definition at line 419 of file DistributedMutexTest.cpp.

419  {
420  basicNThreads(8);
421 }
folly::TEST ( DistributedMutex  ,
StressSixteenThreads   
)

Definition at line 422 of file DistributedMutexTest.cpp.

422  {
423  basicNThreads(16);
424 }
folly::TEST ( DistributedMutex  ,
StressThirtyTwoThreads   
)

Definition at line 425 of file DistributedMutexTest.cpp.

425  {
426  basicNThreads(32);
427 }
folly::TEST ( DistributedMutex  ,
StressSixtyFourThreads   
)

Definition at line 428 of file DistributedMutexTest.cpp.

428  {
429  basicNThreads(64);
430 }
folly::TEST ( Optional  ,
HeterogeneousComparisons   
)

Definition at line 430 of file OptionalTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, and uint64_t.

430  {
431  using opt8 = Optional<uint8_t>;
432  using opt64 = Optional<uint64_t>;
433 
434  EXPECT_TRUE(opt8(4) == uint64_t(4));
435  EXPECT_FALSE(opt8(8) == uint64_t(4));
436  EXPECT_FALSE(opt8() == uint64_t(4));
437 
438  EXPECT_TRUE(uint64_t(4) == opt8(4));
439  EXPECT_FALSE(uint64_t(4) == opt8(8));
440  EXPECT_FALSE(uint64_t(4) == opt8());
441 
442  EXPECT_FALSE(opt8(4) != uint64_t(4));
443  EXPECT_TRUE(opt8(8) != uint64_t(4));
444  EXPECT_TRUE(opt8() != uint64_t(4));
445 
446  EXPECT_FALSE(uint64_t(4) != opt8(4));
447  EXPECT_TRUE(uint64_t(4) != opt8(8));
448  EXPECT_TRUE(uint64_t(4) != opt8());
449 
450  EXPECT_TRUE(opt8() == opt64());
451  EXPECT_TRUE(opt8(4) == opt64(4));
452  EXPECT_FALSE(opt8(8) == opt64(4));
453  EXPECT_FALSE(opt8() == opt64(4));
454  EXPECT_FALSE(opt8(4) == opt64());
455 
456  EXPECT_FALSE(opt8() != opt64());
457  EXPECT_FALSE(opt8(4) != opt64(4));
458  EXPECT_TRUE(opt8(8) != opt64(4));
459  EXPECT_TRUE(opt8() != opt64(4));
460  EXPECT_TRUE(opt8(4) != opt64());
461 
462  EXPECT_TRUE(opt8() < opt64(4));
463  EXPECT_TRUE(opt8(4) < opt64(8));
464  EXPECT_FALSE(opt8() < opt64());
465  EXPECT_FALSE(opt8(4) < opt64(4));
466  EXPECT_FALSE(opt8(8) < opt64(4));
467  EXPECT_FALSE(opt8(4) < opt64());
468 
469  EXPECT_FALSE(opt8() > opt64(4));
470  EXPECT_FALSE(opt8(4) > opt64(8));
471  EXPECT_FALSE(opt8() > opt64());
472  EXPECT_FALSE(opt8(4) > opt64(4));
473  EXPECT_TRUE(opt8(8) > opt64(4));
474  EXPECT_TRUE(opt8(4) > opt64());
475 
476  EXPECT_TRUE(opt8() <= opt64(4));
477  EXPECT_TRUE(opt8(4) <= opt64(8));
478  EXPECT_TRUE(opt8() <= opt64());
479  EXPECT_TRUE(opt8(4) <= opt64(4));
480  EXPECT_FALSE(opt8(8) <= opt64(4));
481  EXPECT_FALSE(opt8(4) <= opt64());
482 
483  EXPECT_FALSE(opt8() >= opt64(4));
484  EXPECT_FALSE(opt8(4) >= opt64(8));
485  EXPECT_TRUE(opt8() >= opt64());
486  EXPECT_TRUE(opt8(4) >= opt64(4));
487  EXPECT_TRUE(opt8(8) >= opt64(4));
488  EXPECT_TRUE(opt8(4) >= opt64());
489 }
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( DistributedMutex  ,
StressHundredThreads   
)

Definition at line 431 of file DistributedMutexTest.cpp.

431  {
432  basicNThreads(100);
433 }
folly::TEST ( DistributedMutex  ,
StressHardwareConcurrencyThreads   
)

Definition at line 434 of file DistributedMutexTest.cpp.

434  {
435  basicNThreads(std::thread::hardware_concurrency());
436 }
folly::TEST ( Expected  ,
Conversions   
)

Definition at line 437 of file ExpectedTest.cpp.

References b, E1, EXPECT_FALSE, EXPECT_TRUE, unexpected(), and value().

437  {
438  Expected<bool, E> mbool;
439  Expected<short, E> mshort;
440  Expected<char*, E> mstr;
441  Expected<int, E> mint;
442 
443  EXPECT_FALSE((std::is_convertible<Expected<bool, E>&, bool>::value));
444  EXPECT_FALSE((std::is_convertible<Expected<short, E>&, short>::value));
445  EXPECT_FALSE((std::is_convertible<Expected<char*, E>&, char*>::value));
446  EXPECT_FALSE((std::is_convertible<Expected<int, E>&, int>::value));
447 
448  // intended explicit operator bool, for if (ex).
449  bool b(mbool);
450  EXPECT_FALSE(b);
451 
452  // Truthy tests work and are not ambiguous
453  if (mbool && mshort && mstr && mint) { // only checks not-empty
454  if (*mbool && *mshort && *mstr && *mint) { // only checks value
455  ;
456  }
457  }
458 
459  mbool = false;
460  EXPECT_TRUE(bool(mbool));
461  EXPECT_FALSE(*mbool);
462 
463  mbool = true;
464  EXPECT_TRUE(bool(mbool));
465  EXPECT_TRUE(*mbool);
466 
467  mbool = {unexpected, E::E1};
468  EXPECT_FALSE(bool(mbool));
469 
470  // No conversion allowed; does not compile
471  // mbool == false;
472 }
char b
expected_detail::UnexpectedTag unexpected(expected_detail::UnexpectedTag={})
Definition: Expected.h:656
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( DistributedMutex  ,
StressTryLock   
)

Definition at line 438 of file DistributedMutexTest.cpp.

References i, folly::gen::move, mutex, threads, and folly::test::DeterministicSchedule::uniform().

438  {
439  auto&& mutex = DistributedMutex{};
440 
441  for (auto i = 0; i < FLAGS_stress_factor; ++i) {
442  while (true) {
443  auto state = mutex.try_lock();
444  if (state) {
445  mutex.unlock(std::move(state));
446  break;
447  }
448  }
449  }
450 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::mutex mutex
detail::distributed_mutex::DistributedMutex<> DistributedMutex
state
Definition: http_parser.c:272
folly::TEST ( DistributedMutex  ,
DeterministicStressTwoThreads   
)

Definition at line 470 of file DistributedMutexTest.cpp.

470  {
471  runBasicNThreadsDeterministic(2, numIterationsDeterministicTest(2));
472 }
folly::TEST ( DistributedMutex  ,
DeterministicStressFourThreads   
)

Definition at line 473 of file DistributedMutexTest.cpp.

473  {
474  runBasicNThreadsDeterministic(4, numIterationsDeterministicTest(4));
475 }
folly::TEST ( Expected  ,
Pointee   
)

Definition at line 474 of file ExpectedTest.cpp.

References E1, EXPECT_FALSE, EXPECT_TRUE, get_pointer(), unexpected(), and x.

474  {
475  Expected<int, E> x;
477  x = 1;
479  *get_pointer(x) = 2;
480  EXPECT_TRUE(*x == 2);
481  x = {unexpected, E::E1};
483 }
const int x
expected_detail::UnexpectedTag unexpected(expected_detail::UnexpectedTag={})
Definition: Expected.h:656
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
const Value * get_pointer(const Expected< Value, Error > &ex) noexcept
Definition: Expected.h:1374
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( DistributedMutex  ,
DeterministicStressEightThreads   
)

Definition at line 476 of file DistributedMutexTest.cpp.

476  {
477  runBasicNThreadsDeterministic(8, numIterationsDeterministicTest(8));
478 }
folly::TEST ( DistributedMutex  ,
DeterministicStressSixteenThreads   
)

Definition at line 479 of file DistributedMutexTest.cpp.

479  {
480  runBasicNThreadsDeterministic(16, numIterationsDeterministicTest(16));
481 }
folly::TEST ( DistributedMutex  ,
DeterministicStressThirtyTwoThreads   
)

Definition at line 482 of file DistributedMutexTest.cpp.

482  {
483  runBasicNThreadsDeterministic(32, numIterationsDeterministicTest(32));
484 }
folly::TEST ( Expected  ,
MakeOptional   
)

Definition at line 485 of file ExpectedTest.cpp.

References ASSERT_TRUE, EXPECT_EQ, EXPECT_TRUE, folly::gen::move, s, and string.

485  {
486  // const L-value version
487  const std::string s("abc");
488  auto exStr = makeExpected<E>(s);
489  ASSERT_TRUE(exStr.hasValue());
490  EXPECT_EQ(*exStr, "abc");
491  *exStr = "cde";
492  EXPECT_EQ(s, "abc");
493  EXPECT_EQ(*exStr, "cde");
494 
495  // L-value version
496  std::string s2("abc");
497  auto exStr2 = makeExpected<E>(s2);
498  ASSERT_TRUE(exStr2.hasValue());
499  EXPECT_EQ(*exStr2, "abc");
500  *exStr2 = "cde";
501  // it's vital to check that s2 wasn't clobbered
502  EXPECT_EQ(s2, "abc");
503 
504  // L-value reference version
505  std::string& s3(s2);
506  auto exStr3 = makeExpected<E>(s3);
507  ASSERT_TRUE(exStr3.hasValue());
508  EXPECT_EQ(*exStr3, "abc");
509  *exStr3 = "cde";
510  EXPECT_EQ(s3, "abc");
511 
512  // R-value ref version
513  unique_ptr<int> pInt(new int(3));
514  auto exIntPtr = makeExpected<E>(std::move(pInt));
515  EXPECT_TRUE(pInt.get() == nullptr);
516  ASSERT_TRUE(exIntPtr.hasValue());
517  EXPECT_EQ(**exIntPtr, 3);
518 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
const char * string
Definition: Conv.cpp:212
static set< string > s
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST ( DistributedMutex  ,
TimedLockTimeout   
)

Definition at line 486 of file DistributedMutexTest.cpp.

References EXPECT_FALSE, folly::gen::move, mutex, and start.

486  {
487  auto&& mutex = DistributedMutex{};
488  auto&& start = folly::Baton<>{};
489  auto&& done = folly::Baton<>{};
490 
491  auto thread = std::thread{[&]() {
492  auto state = mutex.lock();
493  start.post();
494  done.wait();
495  mutex.unlock(std::move(state));
496  }};
497 
498  start.wait();
499  auto result = mutex.try_lock_for(10ms);
500  EXPECT_FALSE(result);
501  done.post();
502  thread.join();
503 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
auto start
std::mutex mutex
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
detail::distributed_mutex::DistributedMutex<> DistributedMutex
state
Definition: http_parser.c:272
folly::TEST ( Optional  ,
NoneComparisons   
)

Definition at line 491 of file OptionalTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, and none.

491  {
492  using opt = Optional<int>;
493  EXPECT_TRUE(opt() == none);
494  EXPECT_TRUE(none == opt());
495  EXPECT_FALSE(opt(1) == none);
496  EXPECT_FALSE(none == opt(1));
497 
498  EXPECT_FALSE(opt() != none);
499  EXPECT_FALSE(none != opt());
500  EXPECT_TRUE(opt(1) != none);
501  EXPECT_TRUE(none != opt(1));
502 
503  EXPECT_FALSE(opt() < none);
504  EXPECT_FALSE(none < opt());
505  EXPECT_FALSE(opt(1) < none);
506  EXPECT_TRUE(none < opt(1));
507 
508  EXPECT_FALSE(opt() > none);
509  EXPECT_FALSE(none > opt());
510  EXPECT_FALSE(none > opt(1));
511  EXPECT_TRUE(opt(1) > none);
512 
513  EXPECT_TRUE(opt() <= none);
514  EXPECT_TRUE(none <= opt());
515  EXPECT_FALSE(opt(1) <= none);
516  EXPECT_TRUE(none <= opt(1));
517 
518  EXPECT_TRUE(opt() >= none);
519  EXPECT_TRUE(none >= opt());
520  EXPECT_TRUE(opt(1) >= none);
521  EXPECT_FALSE(none >= opt(1));
522 }
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
constexpr None none
Definition: Optional.h:87
folly::TEST ( DistributedMutex  ,
TimedLockAcquireAfterUnlock   
)

Definition at line 505 of file DistributedMutexTest.cpp.

References EXPECT_TRUE, folly::gen::move, mutex, and start.

505  {
506  auto&& mutex = DistributedMutex{};
507  auto&& start = folly::Baton<>{};
508 
509  auto thread = std::thread{[&]() {
510  auto state = mutex.lock();
511  start.post();
512  /* sleep override */
513  std::this_thread::sleep_for(10ms);
514  mutex.unlock(std::move(state));
515  }};
516 
517  start.wait();
518  auto result = mutex.try_lock_for(kForever);
519  EXPECT_TRUE(result);
520  thread.join();
521 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
auto start
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
std::mutex mutex
detail::distributed_mutex::DistributedMutex<> DistributedMutex
state
Definition: http_parser.c:272
folly::TEST ( Expected  ,
SelfAssignment   
)

Definition at line 520 of file ExpectedTest.cpp.

References a, ASSERT_TRUE, b, folly::Expected< Value, Error >::hasValue(), and folly::Expected< Value, Error >::value().

520  {
521  Expected<std::string, E> a = "42";
522  a = static_cast<decltype(a)&>(a); // suppress self-assign warning
523  ASSERT_TRUE(a.hasValue() && a.value() == "42");
524 
525  Expected<std::string, E> b = "23333333";
526  b = static_cast<decltype(b)&&>(b); // suppress self-move warning
527  ASSERT_TRUE(b.hasValue() && b.value() == "23333333");
528 }
char b
char a
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST ( DistributedMutex  ,
TimedLockAcquireAfterLock   
)

Definition at line 523 of file DistributedMutexTest.cpp.

References EXPECT_TRUE, i, folly::gen::move, mutex, and folly::test::ManualSchedule::setCallback().

523  {
524  auto&& mutex = test::TestDistributedMutex<test::ManualAtomic>{};
525  auto&& schedule = test::ManualSchedule{};
526 
527  auto thread = std::thread{[&] {
528  schedule.setCallback([&, i = 0]() mutable {
529  if (i == 1) {
530  schedule.post(0);
531  schedule.wait(1);
532  }
533 
534  // when this thread goes into the atomic_notify_one() we let the other
535  // thread wake up
536  if (i == 3) {
537  schedule.post(2);
538  }
539 
540  ++i;
541  });
542 
543  auto state = mutex.lock();
544  mutex.unlock(std::move(state));
545  }};
546 
547  schedule.setCallback([&, i = 0]() mutable {
548  // allow the other thread to unlock after the current thread has set the
549  // timed waiter state into the mutex
550  if (i == 2) {
551  schedule.post(1);
552  schedule.wait(2);
553  }
554  ++i;
555  });
556  schedule.wait(0);
557  auto state = mutex.try_lock_for(kForever);
559  mutex.unlock(std::move(state));
560  thread.join();
561 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
std::mutex mutex
state
Definition: http_parser.c:272
folly::TEST ( Optional  ,
Conversions   
)

Definition at line 524 of file OptionalTest.cpp.

References folly::NoDefault::b, EXPECT_FALSE, EXPECT_TRUE, and none.

524  {
525  Optional<bool> mbool;
526  Optional<short> mshort;
527  Optional<char*> mstr;
528  Optional<int> mint;
529 
530  // These don't compile
531  // bool b = mbool;
532  // short s = mshort;
533  // char* c = mstr;
534  // int x = mint;
535  // char* c(mstr);
536  // short s(mshort);
537  // int x(mint);
538 
539  // intended explicit operator bool, for if (opt).
540  bool b(mbool);
541  EXPECT_FALSE(b);
542 
543  // Truthy tests work and are not ambiguous
544  if (mbool && mshort && mstr && mint) { // only checks not-empty
545  if (*mbool && *mshort && *mstr && *mint) { // only checks value
546  ;
547  }
548  }
549 
550  mbool = false;
551  EXPECT_TRUE(bool(mbool));
552  EXPECT_FALSE(*mbool);
553 
554  mbool = true;
555  EXPECT_TRUE(bool(mbool));
556  EXPECT_TRUE(*mbool);
557 
558  mbool = none;
559  EXPECT_FALSE(bool(mbool));
560 
561  // No conversion allowed; does not compile
562  // EXPECT_TRUE(mbool == false);
563 }
char b
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
constexpr None none
Definition: Optional.h:87
folly::TEST ( Expected  ,
AssignmentContained   
)

Test that a class containing an Expected can be copy and move assigned. This was broken under gcc 4.7 until assignment operators were explicitly defined.

Definition at line 555 of file ExpectedTest.cpp.

References EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, folly::ContainsExpected::hasValue(), folly::gen::move, and folly::ContainsExpected::value().

555  {
556  {
557  ContainsExpected source(5), target;
558  target = source;
559  EXPECT_TRUE(target.hasValue());
560  EXPECT_EQ(5, target.value());
561  }
562 
563  {
564  ContainsExpected source(5), target;
565  target = std::move(source);
566  EXPECT_TRUE(target.hasValue());
567  EXPECT_EQ(5, target.value());
568  EXPECT_TRUE(source.hasValue());
569  }
570 
571  {
572  ContainsExpected ex_uninit, target(10);
573  target = ex_uninit;
574  EXPECT_FALSE(target.hasValue());
575  }
576 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncSSLSocketTest  ,
SNITestMatch   
)
  1. Client sends TLSEXT_HOSTNAME in client hello.
  2. Server found a match SSL_CTX and use this SSL_CTX to continue the SSL handshake.
  3. Server sends back TLSEXT_HOSTNAME in server hello.

Definition at line 563 of file AsyncSSLSocketTest.cpp.

References EXPECT_TRUE, getctx(), getfds(), folly::EventBase::loop(), folly::gen::move, folly::SNIClient::serverNameMatch, folly::SNIServer::serverNameMatch, and string.

563  {
564  EventBase eventBase;
565  std::shared_ptr<SSLContext> clientCtx(new SSLContext);
566  std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
567  // Use the same SSLContext to continue the handshake after
568  // tlsext_hostname match.
569  std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
570  const std::string serverName("xyz.newdev.facebook.com");
571  int fds[2];
572  getfds(fds);
573  getctx(clientCtx, dfServerCtx);
574 
575  AsyncSSLSocket::UniquePtr clientSock(
576  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
577  AsyncSSLSocket::UniquePtr serverSock(
578  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
579  SNIClient client(std::move(clientSock));
580  SNIServer server(
581  std::move(serverSock), dfServerCtx, hskServerCtx, serverName);
582 
583  eventBase.loop();
584 
585  EXPECT_TRUE(client.serverNameMatch);
586  EXPECT_TRUE(server.serverNameMatch);
587 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
const char * string
Definition: Conv.cpp:212
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
folly::TEST ( DistributedMutex  ,
TimedLockAcquireAfterContentionChain   
)

Definition at line 563 of file DistributedMutexTest.cpp.

References Atom, EXPECT_EQ, EXPECT_TRUE, i, folly::test::DeterministicSchedule::join(), folly::gen::move, mutex, folly::test::ManualSchedule::setCallback(), folly::test::DeterministicSchedule::thread(), and threads.

563  {
564  auto&& mutex = test::TestDistributedMutex<test::ManualAtomic>{};
565  auto&& schedule = test::ManualSchedule{};
566 
567  auto one = std::thread{[&] {
568  schedule.setCallback([&, i = 0]() mutable {
569  if (i == 1) {
570  schedule.post(0);
571  schedule.wait(1);
572  schedule.wait(2);
573  }
574  ++i;
575  });
576 
577  auto state = mutex.lock();
578  mutex.unlock(std::move(state));
579  }};
580  auto two = std::thread{[&] {
581  schedule.setCallback([&, i = 0]() mutable {
582  // block the current thread until the first thread has acquired the
583  // lock
584  if (i == 0) {
585  schedule.wait(0);
586  }
587 
588  // when the current thread enqueues, let the first thread unlock so we
589  // get woken up
590  //
591  // then wait for the first thread to unlock
592  if (i == 2) {
593  schedule.post(1);
594  }
595 
596  ++i;
597  });
598 
599  auto state = mutex.lock();
600  mutex.unlock(std::move(state));
601  }};
602 
603  // make the current thread wait for the first thread to unlock
604  schedule.setCallback([&, i = 0]() mutable {
605  // let the first thread unlock after we have enqueued ourselves on the
606  // mutex
607  if (i == 2) {
608  schedule.post(2);
609  }
610  ++i;
611  });
612  auto state = mutex.try_lock_for(kForever);
614  mutex.unlock(std::move(state));
615 
616  one.join();
617  two.join();
618 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
std::mutex mutex
state
Definition: http_parser.c:272
folly::TEST ( Optional  ,
Pointee   
)

Definition at line 565 of file OptionalTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, get_pointer(), none, and x.

565  {
566  Optional<int> x;
568  x = 1;
570  *get_pointer(x) = 2;
571  EXPECT_TRUE(*x == 2);
572  x = none;
574 }
const int x
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
const Value * get_pointer(const Expected< Value, Error > &ex) noexcept
Definition: Expected.h:1374
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
constexpr None none
Definition: Optional.h:87
folly::TEST ( Expected  ,
Exceptions   
)

Definition at line 578 of file ExpectedTest.cpp.

References empty(), EXPECT_THROW, and folly::Expected< Value, Error >::value().

578  {
579  Expected<int, E> empty;
580  EXPECT_THROW(empty.value(), Unexpected<E>::BadExpectedAccess);
581 }
#define EXPECT_THROW(statement, expected_exception)
Definition: gtest.h:1843
constexpr auto empty(C const &c) -> decltype(c.empty())
Definition: Access.h:55
folly::TEST ( Expected  ,
NoThrowDefaultConstructible   
)

Definition at line 591 of file ExpectedTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, and value().

591  {
592  EXPECT_TRUE(
593  (std::is_nothrow_default_constructible<Expected<bool, E>>::value));
594  EXPECT_TRUE(
595  (std::is_nothrow_default_constructible<Expected<std::string, E>>::value));
596  EXPECT_TRUE((std::is_nothrow_default_constructible<
597  Expected<ThrowingBadness, E>>::value));
598  EXPECT_FALSE((std::is_nothrow_default_constructible<
599  Expected<int, ThrowingBadness>>::value));
600 }
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncSSLSocketTest  ,
SNITestNotMatch   
)
  1. Client sends TLSEXT_HOSTNAME in client hello.
  2. Server cannot find a matching SSL_CTX and continue to use the current SSL_CTX to do the handshake.
  3. Server does not send back TLSEXT_HOSTNAME in server hello.

Definition at line 595 of file AsyncSSLSocketTest.cpp.

References EXPECT_TRUE, getctx(), getfds(), folly::EventBase::loop(), folly::gen::move, folly::SNIClient::serverNameMatch, folly::SNIServer::serverNameMatch, and string.

595  {
596  EventBase eventBase;
597  std::shared_ptr<SSLContext> clientCtx(new SSLContext);
598  std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
599  // Use the same SSLContext to continue the handshake after
600  // tlsext_hostname match.
601  std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
602  const std::string clientRequestingServerName("foo.com");
603  const std::string serverExpectedServerName("xyz.newdev.facebook.com");
604 
605  int fds[2];
606  getfds(fds);
607  getctx(clientCtx, dfServerCtx);
608 
609  AsyncSSLSocket::UniquePtr clientSock(new AsyncSSLSocket(
610  clientCtx, &eventBase, fds[0], clientRequestingServerName));
611  AsyncSSLSocket::UniquePtr serverSock(
612  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
613  SNIClient client(std::move(clientSock));
614  SNIServer server(
615  std::move(serverSock),
616  dfServerCtx,
617  hskServerCtx,
618  serverExpectedServerName);
619 
620  eventBase.loop();
621 
622  EXPECT_TRUE(!client.serverNameMatch);
623  EXPECT_TRUE(!server.serverNameMatch);
624 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
const char * string
Definition: Conv.cpp:212
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
folly::TEST ( Expected  ,
NoThrowMoveConstructible   
)

Definition at line 602 of file ExpectedTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, and value().

602  {
603  EXPECT_TRUE((std::is_nothrow_move_constructible<Expected<bool, E>>::value));
604  EXPECT_TRUE((std::is_nothrow_move_constructible<
605  Expected<std::unique_ptr<int>, E>>::value));
606  EXPECT_FALSE((
607  std::is_nothrow_move_constructible<Expected<ThrowingBadness, E>>::value));
608 }
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( Optional  ,
MakeOptional   
)

Definition at line 606 of file OptionalTest.cpp.

References ASSERT_TRUE, EXPECT_EQ, EXPECT_TRUE, make_optional(), folly::gen::move, s, and string.

606  {
607  // const L-value version
608  const std::string s("abc");
609  auto optStr = folly::make_optional(s);
610  ASSERT_TRUE(optStr.hasValue());
611  EXPECT_EQ(*optStr, "abc");
612  *optStr = "cde";
613  EXPECT_EQ(s, "abc");
614  EXPECT_EQ(*optStr, "cde");
615 
616  // L-value version
617  std::string s2("abc");
618  auto optStr2 = folly::make_optional(s2);
619  ASSERT_TRUE(optStr2.hasValue());
620  EXPECT_EQ(*optStr2, "abc");
621  *optStr2 = "cde";
622  // it's vital to check that s2 wasn't clobbered
623  EXPECT_EQ(s2, "abc");
624 
625  // L-value reference version
626  std::string& s3(s2);
627  auto optStr3 = folly::make_optional(s3);
628  ASSERT_TRUE(optStr3.hasValue());
629  EXPECT_EQ(*optStr3, "abc");
630  *optStr3 = "cde";
631  EXPECT_EQ(s3, "abc");
632 
633  // R-value ref version
634  unique_ptr<int> pInt(new int(3));
635  auto optIntPtr = folly::make_optional(std::move(pInt));
636  EXPECT_TRUE(pInt.get() == nullptr);
637  ASSERT_TRUE(optIntPtr.hasValue());
638  EXPECT_EQ(**optIntPtr, 3);
639 
640  // variadic version
641  {
642  auto&& optional = make_optional<ConstructibleWithArgsOnly>(int{}, double{});
643  std::ignore = optional;
644  }
645  {
646  using Type = ConstructibleWithInitializerListAndArgsOnly;
647  auto&& optional = make_optional<Type>({int{}}, double{});
648  std::ignore = optional;
649  }
650 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
constexpr Optional< _t< std::decay< T > > > make_optional(T &&v)
Definition: Optional.h:450
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
const char * string
Definition: Conv.cpp:212
static set< string > s
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST ( Expected  ,
NoThrowMoveAssignable   
)

Definition at line 610 of file ExpectedTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, and value().

610  {
611  EXPECT_TRUE((std::is_nothrow_move_assignable<Expected<bool, E>>::value));
612  EXPECT_TRUE((std::is_nothrow_move_assignable<
613  Expected<std::unique_ptr<int>, E>>::value));
614  EXPECT_FALSE(
615  (std::is_nothrow_move_assignable<Expected<ThrowingBadness, E>>::value));
616 }
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncSSLSocketTest  ,
SNITestChangeServerName   
)
  1. Client sends TLSEXT_HOSTNAME in client hello.
  2. We then change the serverName.
  3. We expect that we get 'false' as the result for serNameMatch.

Definition at line 631 of file AsyncSSLSocketTest.cpp.

References EXPECT_TRUE, getctx(), getfds(), folly::EventBase::loop(), folly::gen::move, folly::SNIClient::serverNameMatch, and string.

631  {
632  EventBase eventBase;
633  std::shared_ptr<SSLContext> clientCtx(new SSLContext);
634  std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
635  // Use the same SSLContext to continue the handshake after
636  // tlsext_hostname match.
637  std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
638  const std::string serverName("xyz.newdev.facebook.com");
639  int fds[2];
640  getfds(fds);
641  getctx(clientCtx, dfServerCtx);
642 
643  AsyncSSLSocket::UniquePtr clientSock(
644  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
645  // Change the server name
646  std::string newName("new.com");
647  clientSock->setServerName(newName);
648  AsyncSSLSocket::UniquePtr serverSock(
649  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
650  SNIClient client(std::move(clientSock));
651  SNIServer server(
652  std::move(serverSock), dfServerCtx, hskServerCtx, serverName);
653 
654  eventBase.loop();
655 
656  EXPECT_TRUE(!client.serverNameMatch);
657 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
const char * string
Definition: Conv.cpp:212
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
folly::TEST ( Expected  ,
NoSelfAssign   
)

Definition at line 637 of file ExpectedTest.cpp.

637  {
638  folly::Expected<NoSelfAssign, int> e{NoSelfAssign{}};
639  e = static_cast<decltype(e)&>(e); // suppress self-assign warning
640  e = static_cast<decltype(e)&&>(e); // @nolint suppress self-move warning
641 }
folly::TEST ( Optional  ,
InitializerListConstruct   
)

Definition at line 652 of file OptionalTest.cpp.

References in_place().

652  {
653  using Type = ConstructibleWithInitializerListAndArgsOnly;
654  auto&& optional = Optional<Type>{in_place, {int{}}, double{}};
655  std::ignore = optional;
656 }
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
folly::TEST ( Expected  ,
TriviallyDestructible   
)

Definition at line 653 of file ExpectedTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, and value().

653  {
654  // These could all be static_asserts but EXPECT_* give much nicer output on
655  // failure.
656  EXPECT_TRUE(
657  (std::is_trivially_destructible<Expected<NoDestructor, E>>::value));
658  EXPECT_TRUE((std::is_trivially_destructible<Expected<int, E>>::value));
659  EXPECT_FALSE(
660  (std::is_trivially_destructible<Expected<WithDestructor, E>>::value));
661 }
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( DistributedMutex  ,
StressTryLockWithConcurrentLocksTwoThreads   
)

Definition at line 654 of file DistributedMutexTest.cpp.

654  {
655  stressTryLockWithConcurrentLocks(2);
656 }
folly::TEST ( DistributedMutex  ,
StressTryLockWithConcurrentLocksFourThreads   
)

Definition at line 657 of file DistributedMutexTest.cpp.

657  {
658  stressTryLockWithConcurrentLocks(4);
659 }
folly::TEST ( Optional  ,
TestDisambiguationMakeOptionalVariants   
)

Definition at line 658 of file OptionalTest.cpp.

References make_optional().

658  {
659  {
660  auto optional = make_optional<int>(1);
661  std::ignore = optional;
662  }
663  {
664  auto optional = make_optional(1);
665  std::ignore = optional;
666  }
667 }
constexpr Optional< _t< std::decay< T > > > make_optional(T &&v)
Definition: Optional.h:450
folly::TEST ( DistributedMutex  ,
StressTryLockWithConcurrentLocksEightThreads   
)

Definition at line 660 of file DistributedMutexTest.cpp.

660  {
661  stressTryLockWithConcurrentLocks(8);
662 }
folly::TEST ( DistributedMutex  ,
StressTryLockWithConcurrentLocksSixteenThreads   
)

Definition at line 663 of file DistributedMutexTest.cpp.

663  {
664  stressTryLockWithConcurrentLocks(16);
665 }
folly::TEST ( AsyncSSLSocketTest  ,
SNITestClientHelloNoHostname   
)
  1. Client does not send TLSEXT_HOSTNAME in client hello.
  2. Server does not send back TLSEXT_HOSTNAME in server hello.

Definition at line 663 of file AsyncSSLSocketTest.cpp.

References EXPECT_TRUE, getctx(), getfds(), folly::EventBase::loop(), folly::gen::move, folly::SNIClient::serverNameMatch, folly::SNIServer::serverNameMatch, and string.

663  {
664  EventBase eventBase;
665  std::shared_ptr<SSLContext> clientCtx(new SSLContext);
666  std::shared_ptr<SSLContext> dfServerCtx(new SSLContext);
667  // Use the same SSLContext to continue the handshake after
668  // tlsext_hostname match.
669  std::shared_ptr<SSLContext> hskServerCtx(dfServerCtx);
670  const std::string serverExpectedServerName("xyz.newdev.facebook.com");
671 
672  int fds[2];
673  getfds(fds);
674  getctx(clientCtx, dfServerCtx);
675 
676  AsyncSSLSocket::UniquePtr clientSock(
677  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
678  AsyncSSLSocket::UniquePtr serverSock(
679  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
680  SNIClient client(std::move(clientSock));
681  SNIServer server(
682  std::move(serverSock),
683  dfServerCtx,
684  hskServerCtx,
685  serverExpectedServerName);
686 
687  eventBase.loop();
688 
689  EXPECT_TRUE(!client.serverNameMatch);
690  EXPECT_TRUE(!server.serverNameMatch);
691 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
const char * string
Definition: Conv.cpp:212
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
folly::TEST ( DistributedMutex  ,
StressTryLockWithConcurrentLocksThirtyTwoThreads   
)

Definition at line 666 of file DistributedMutexTest.cpp.

666  {
667  stressTryLockWithConcurrentLocks(32);
668 }
folly::TEST ( Optional  ,
SelfAssignment   
)

Definition at line 669 of file OptionalTest.cpp.

References folly::NoDefault::a, ASSERT_TRUE, folly::NoDefault::b, folly::Optional< Value >::hasValue(), opt_, value(), and folly::Optional< Value >::value().

669  {
670  Optional<int> a = 42;
671  a = static_cast<decltype(a)&>(a); // suppress self-assign warning
672  ASSERT_TRUE(a.hasValue() && a.value() == 42);
673 
674  Optional<int> b = 23333333;
675  b = static_cast<decltype(b)&&>(b); // suppress self-move warning
676  ASSERT_TRUE(b.hasValue() && b.value() == 23333333);
677 }
char b
char a
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST ( DistributedMutex  ,
StressTryLockWithConcurrentLocksSixtyFourThreads   
)

Definition at line 669 of file DistributedMutexTest.cpp.

669  {
670  stressTryLockWithConcurrentLocks(64);
671 }
folly::TEST ( Expected  ,
TriviallyCopyable   
)

Definition at line 672 of file ExpectedTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, and value().

672  {
673  // These could all be static_asserts but EXPECT_* give much nicer output on
674  // failure.
675  EXPECT_TRUE((is_trivially_copyable<Expected<int, E>>::value));
676  EXPECT_TRUE((is_trivially_copyable<Expected<char*, E>>::value));
677  EXPECT_TRUE((is_trivially_copyable<Expected<NoDestructor, E>>::value));
678  EXPECT_FALSE((is_trivially_copyable<Expected<WithDestructor, E>>::value));
679  EXPECT_TRUE((is_trivially_copyable<Expected<NoConstructor, E>>::value));
680  EXPECT_FALSE((is_trivially_copyable<Expected<std::string, E>>::value));
681  EXPECT_FALSE((is_trivially_copyable<Expected<int, std::string>>::value));
682  EXPECT_TRUE((is_trivially_copyable<Expected<WithConstructor, E>>::value));
683  EXPECT_TRUE((is_trivially_copyable<Expected<Expected<int, E>, E>>::value));
684 }
std::is_trivially_copyable< T > is_trivially_copyable
Definition: Traits.h:313
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( DistributedMutex  ,
DeterministicTryLockWithLocksTwoThreads   
)

Definition at line 673 of file DistributedMutexTest.cpp.

References folly::test::DeterministicSchedule::uniform().

673  {
674  auto iterations = numIterationsDeterministicTest(2);
675  stressTryLockWithConcurrentLocks(2, iterations);
676 
677  for (auto pass = 0; pass < 3; ++pass) {
678  auto&& schedule = DSched{DSched::uniform(pass)};
679  stressTryLockWithConcurrentLocks<test::DeterministicAtomic>(2, iterations);
680  static_cast<void>(schedule);
681  }
682 }
static std::function< size_t(size_t)> uniform(uint64_t seed)
folly::TEST ( DistributedMutex  ,
DeterministicTryLockWithFourThreads   
)

Definition at line 683 of file DistributedMutexTest.cpp.

References folly::test::DeterministicSchedule::uniform().

683  {
684  auto iterations = numIterationsDeterministicTest(4);
685  stressTryLockWithConcurrentLocks(4, iterations);
686 
687  for (auto pass = 0; pass < 3; ++pass) {
688  auto&& schedule = DSched{DSched::uniform(pass)};
689  stressTryLockWithConcurrentLocks<test::DeterministicAtomic>(4, iterations);
690  static_cast<void>(schedule);
691  }
692 }
static std::function< size_t(size_t)> uniform(uint64_t seed)
folly::TEST ( Expected  ,
Then   
)

Definition at line 687 of file ExpectedTest.cpp.

References ADD_FAILURE, E1, folly::Expected< Value, Error >::error(), EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, i, in_place(), and unexpected().

687  {
688  // Lifting
689  {
690  Expected<int, E> ex =
691  Expected<std::unique_ptr<int>, E>{in_place, new int(42)}.then(
692  [](std::unique_ptr<int> p) { return *p; });
693  EXPECT_TRUE(bool(ex));
694  EXPECT_EQ(42, *ex);
695  }
696 
697  // Flattening
698  {
699  Expected<int, E> ex =
700  Expected<std::unique_ptr<int>, E>{in_place, new int(42)}.then(
701  [](std::unique_ptr<int> p) { return makeExpected<E>(*p); });
702  EXPECT_TRUE(bool(ex));
703  EXPECT_EQ(42, *ex);
704  }
705 
706  // Void
707  {
708  Expected<Unit, E> ex =
709  Expected<std::unique_ptr<int>, E>{in_place, new int(42)}.then(
710  [](std::unique_ptr<int>) {});
711  EXPECT_TRUE(bool(ex));
712  }
713 
714  // Non-flattening (different error codes)
715  {
716  Expected<Expected<int, int>, E> ex =
717  Expected<std::unique_ptr<int>, E>{in_place, new int(42)}.then(
718  [](std::unique_ptr<int> p) { return makeExpected<int>(*p); });
719  EXPECT_TRUE(bool(ex));
720  EXPECT_TRUE(bool(*ex));
721  EXPECT_EQ(42, **ex);
722  }
723 
724  {
725  // Error case:
726  Expected<int, E> ex =
727  Expected<std::unique_ptr<int>, E>{unexpected, E::E1}.then(
728  [](std::unique_ptr<int> p) -> int {
729  ADD_FAILURE();
730  return *p;
731  });
732  EXPECT_FALSE(bool(ex));
733  EXPECT_EQ(E::E1, ex.error());
734  }
735 
736  // Chaining
737  {
738  Expected<std::string, E> ex =
739  Expected<std::unique_ptr<int>, E>{in_place, new int(42)}.then(
740  [](std::unique_ptr<int> p) { return makeExpected<E>(*p); },
741  [](int i) { return i == 42 ? "yes" : "no"; });
742  EXPECT_TRUE(bool(ex));
743  EXPECT_EQ("yes", *ex);
744  }
745 
746  // Chaining with errors
747  {
748  Expected<std::string, E> ex =
749  Expected<std::unique_ptr<int>, E>{in_place, new int(42)}.then(
750  [](std::unique_ptr<int>) {
751  return Expected<int, E>(unexpected, E::E1);
752  },
753  [](int i) { return i == 42 ? "yes" : "no"; });
754  EXPECT_FALSE(bool(ex));
755  EXPECT_EQ(E::E1, ex.error());
756  }
757 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
expected_detail::UnexpectedTag unexpected(expected_detail::UnexpectedTag={})
Definition: Expected.h:656
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
#define ADD_FAILURE()
Definition: gtest.h:1808
folly::TEST ( DistributedMutex  ,
DeterministicTryLockWithLocksEightThreads   
)

Definition at line 693 of file DistributedMutexTest.cpp.

References folly::test::DeterministicSchedule::uniform().

693  {
694  auto iterations = numIterationsDeterministicTest(8);
695  stressTryLockWithConcurrentLocks(8, iterations);
696 
697  for (auto pass = 0; pass < 3; ++pass) {
698  auto&& schedule = DSched{DSched::uniform(pass)};
699  stressTryLockWithConcurrentLocks<test::DeterministicAtomic>(8, iterations);
700  static_cast<void>(schedule);
701  }
702 }
static std::function< size_t(size_t)> uniform(uint64_t seed)
folly::TEST ( AsyncSSLSocketTest  ,
SSLClientTest   
)

Test SSL client socket

Definition at line 697 of file AsyncSSLSocketTest.cpp.

References EXPECT_EQ, and folly::TestSSLServer::getAddress().

697  {
698  // Start listening on a local port
699  WriteCallbackBase writeCallback;
700  ReadCallback readCallback(&writeCallback);
701  HandshakeCallback handshakeCallback(&readCallback);
702  SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
703  TestSSLServer server(&acceptCallback);
704 
705  // Set up SSL client
706  EventBase eventBase;
707  auto client = std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1);
708 
709  client->connect();
710  EventBaseAborter eba(&eventBase, 3000);
711  eventBase.loop();
712 
713  EXPECT_EQ(client->getMiss(), 1);
714  EXPECT_EQ(client->getHit(), 0);
715 
716  cerr << "SSLClientTest test completed" << endl;
717 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
folly::TEST ( DistributedMutex  ,
DeterministicTryLockWithLocksSixteenThreads   
)

Definition at line 703 of file DistributedMutexTest.cpp.

References folly::test::DeterministicSchedule::uniform().

703  {
704  auto iterations = numIterationsDeterministicTest(16);
705  stressTryLockWithConcurrentLocks(16, iterations);
706 
707  for (auto pass = 0; pass < 3; ++pass) {
708  auto&& schedule = DSched{DSched::uniform(pass)};
709  stressTryLockWithConcurrentLocks<test::DeterministicAtomic>(16, iterations);
710  static_cast<void>(schedule);
711  }
712 }
static std::function< size_t(size_t)> uniform(uint64_t seed)
folly::TEST ( Optional  ,
AssignmentContained   
)

Test that a class containing an Optional can be copy and move assigned. This was broken under gcc 4.7 until assignment operators were explicitly defined.

Definition at line 708 of file OptionalTest.cpp.

References EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, and folly::gen::move.

708  {
709  {
710  ContainsOptional source(5), target;
711  target = source;
712  EXPECT_TRUE(target.hasValue());
713  EXPECT_EQ(5, target.value());
714  }
715 
716  {
717  ContainsOptional source(5), target;
718  target = std::move(source);
719  EXPECT_TRUE(target.hasValue());
720  EXPECT_EQ(5, target.value());
721  EXPECT_FALSE(source.hasValue());
722  }
723 
724  {
725  ContainsOptional opt_uninit, target(10);
726  target = opt_uninit;
727  EXPECT_FALSE(target.hasValue());
728  }
729 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( DistributedMutex  ,
DeterministicTryLockWithLocksThirtyTwoThreads   
)

Definition at line 713 of file DistributedMutexTest.cpp.

References folly::test::DeterministicSchedule::uniform().

713  {
714  auto iterations = numIterationsDeterministicTest(32);
715  stressTryLockWithConcurrentLocks(32, iterations);
716 
717  for (auto pass = 0; pass < 3; ++pass) {
718  auto&& schedule = DSched{DSched::uniform(pass)};
719  stressTryLockWithConcurrentLocks<test::DeterministicAtomic>(32, iterations);
720  static_cast<void>(schedule);
721  }
722 }
static std::function< size_t(size_t)> uniform(uint64_t seed)
folly::TEST ( AsyncSSLSocketTest  ,
SSLClientTestReuse   
)

Test SSL client socket session re-use

Definition at line 722 of file AsyncSSLSocketTest.cpp.

References EXPECT_EQ, and folly::TestSSLServer::getAddress().

722  {
723  // Start listening on a local port
724  WriteCallbackBase writeCallback;
725  ReadCallback readCallback(&writeCallback);
726  HandshakeCallback handshakeCallback(&readCallback);
727  SSLServerAcceptCallbackDelay acceptCallback(&handshakeCallback);
728  TestSSLServer server(&acceptCallback);
729 
730  // Set up SSL client
731  EventBase eventBase;
732  auto client =
733  std::make_shared<SSLClient>(&eventBase, server.getAddress(), 10);
734 
735  client->connect();
736  EventBaseAborter eba(&eventBase, 3000);
737  eventBase.loop();
738 
739  EXPECT_EQ(client->getMiss(), 1);
740  EXPECT_EQ(client->getHit(), 9);
741 
742  cerr << "SSLClientTestReuse test completed" << endl;
743 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
folly::TEST ( DistributedMutex  ,
DeterministicTryLockWithLocksSixtyFourThreads   
)

Definition at line 723 of file DistributedMutexTest.cpp.

References Atom, EXPECT_EQ, i, folly::test::DeterministicSchedule::join(), folly::gen::move, mutex, folly::test::DeterministicSchedule::thread(), threads, and folly::test::DeterministicSchedule::uniform().

723  {
724  stressTryLockWithConcurrentLocks(64, 5);
725 
726  for (auto pass = 0; pass < 3; ++pass) {
727  auto&& schedule = DSched{DSched::uniform(pass)};
728  stressTryLockWithConcurrentLocks<test::DeterministicAtomic>(64, 5);
729  static_cast<void>(schedule);
730  }
731 }
static std::function< size_t(size_t)> uniform(uint64_t seed)
folly::TEST ( Optional  ,
Exceptions   
)

Definition at line 731 of file OptionalTest.cpp.

References empty(), EXPECT_THROW, and folly::Optional< Value >::value().

731  {
732  Optional<int> empty;
733  EXPECT_THROW(empty.value(), OptionalEmptyException);
734 }
#define EXPECT_THROW(statement, expected_exception)
Definition: gtest.h:1843
constexpr auto empty(C const &c) -> decltype(c.empty())
Definition: Access.h:55
folly::TEST ( Optional  ,
NoThrowDefaultConstructible   
)

Definition at line 736 of file OptionalTest.cpp.

References EXPECT_TRUE, and value().

736  {
737  EXPECT_TRUE(std::is_nothrow_default_constructible<Optional<bool>>::value);
738 }
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( AsyncSSLSocketTest  ,
SSLClientTimeoutTest   
)

Test SSL client socket timeout

Definition at line 748 of file AsyncSSLSocketTest.cpp.

References folly::HandshakeCallback::closeSocket(), EXPECT_EQ, folly::TestSSLServer::getAddress(), folly::TestSSLAsyncCacheServer::getAsyncCallbacks(), folly::TestSSLAsyncCacheServer::getAsyncLookups(), folly::TestSSLServer::getEventBase(), folly::EventBase::loop(), folly::EventBase::runInEventBaseThread(), folly::ReadCallbackBase::state, STATE_WAITING, folly::EmptyReadCallback::tcpSocket_, testing::TEST(), and folly::HandshakeCallback::waitForHandshake().

748  {
749  // Start listening on a local port
750  EmptyReadCallback readCallback;
751  HandshakeCallback handshakeCallback(
752  &readCallback, HandshakeCallback::EXPECT_ERROR);
753  HandshakeTimeoutCallback acceptCallback(&handshakeCallback);
754  TestSSLServer server(&acceptCallback);
755 
756  // Set up SSL client
757  EventBase eventBase;
758  auto client =
759  std::make_shared<SSLClient>(&eventBase, server.getAddress(), 1, 10);
760  client->connect(true /* write before connect completes */);
761  EventBaseAborter eba(&eventBase, 3000);
762  eventBase.loop();
763 
764  usleep(100000);
765  // This is checking that the connectError callback precedes any queued
766  // writeError callbacks. This matches AsyncSocket's behavior
767  EXPECT_EQ(client->getWriteAfterConnectErrors(), 1);
768  EXPECT_EQ(client->getErrors(), 1);
769  EXPECT_EQ(client->getMiss(), 0);
770  EXPECT_EQ(client->getHit(), 0);
771 
772  cerr << "SSLClientTimeoutTest test completed" << endl;
773 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
folly::TEST ( Optional  ,
TriviallyDestructible   
)

Definition at line 750 of file OptionalTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, and value().

750  {
751  // These could all be static_asserts but EXPECT_* give much nicer output on
752  // failure.
753  EXPECT_TRUE(std::is_trivially_destructible<Optional<NoDestructor>>::value);
754  EXPECT_TRUE(std::is_trivially_destructible<Optional<int>>::value);
755  EXPECT_FALSE(std::is_trivially_destructible<Optional<WithDestructor>>::value);
756 }
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( DistributedMutex  ,
StressTryLockWithTwoThreads   
)

Definition at line 758 of file DistributedMutexTest.cpp.

758  {
759  concurrentTryLocks(2);
760 }
folly::TEST ( Optional  ,
Hash   
)

Definition at line 758 of file OptionalTest.cpp.

References none, val, and x.

758  {
759  // Test it's usable in std::unordered map (compile time check)
760  std::unordered_map<Optional<int>, Optional<int>> obj;
761  // Also check the std::hash template can be instantiated by the compiler
762  std::hash<Optional<int>>()(none);
763  std::hash<Optional<int>>()(3);
764 }
constexpr None none
Definition: Optional.h:87
folly::TEST ( Expected  ,
ThenOrThrow   
)

Definition at line 759 of file ExpectedTest.cpp.

References E1, EXPECT_EQ, EXPECT_THROW, in_place(), and unexpected().

759  {
760  {
761  int e =
762  Expected<std::unique_ptr<int>, E>{in_place, new int(42)}.thenOrThrow(
763  [](std::unique_ptr<int> p) { return *p; });
764  EXPECT_EQ(42, e);
765  }
766 
767  {
768  EXPECT_THROW(
769  (Expected<std::unique_ptr<int>, E>{unexpected, E::E1}.thenOrThrow(
770  [](std::unique_ptr<int> p) { return *p; })),
771  Unexpected<E>::BadExpectedAccess);
772  }
773 
774  {
775  EXPECT_THROW(
776  (Expected<std::unique_ptr<int>, E>{unexpected, E::E1}.thenOrThrow(
777  [](std::unique_ptr<int> p) { return *p; },
778  [](E) { return std::runtime_error(""); })),
779  std::runtime_error);
780  }
781 
782  {
783  EXPECT_THROW(
784  (Expected<std::unique_ptr<int>, E>{unexpected, E::E1}.thenOrThrow(
785  [](std::unique_ptr<int> p) { return *p; },
786  [](E) { throw std::runtime_error(""); })),
787  std::runtime_error);
788  }
789 
790  {
791  EXPECT_THROW(
792  (Expected<std::unique_ptr<int>, E>{unexpected, E::E1}.thenOrThrow(
793  [](std::unique_ptr<int> p) { return *p; }, [](E) {})),
794  Unexpected<E>::BadExpectedAccess);
795  }
796 }
#define EXPECT_THROW(statement, expected_exception)
Definition: gtest.h:1843
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
in_place_tag in_place(in_place_tag={})
Definition: Utility.h:235
expected_detail::UnexpectedTag unexpected(expected_detail::UnexpectedTag={})
Definition: Expected.h:656
folly::TEST ( DistributedMutex  ,
StressTryLockFourThreads   
)

Definition at line 761 of file DistributedMutexTest.cpp.

761  {
762  concurrentTryLocks(4);
763 }
folly::TEST ( DistributedMutex  ,
StressTryLockEightThreads   
)

Definition at line 764 of file DistributedMutexTest.cpp.

764  {
765  concurrentTryLocks(8);
766 }
folly::TEST ( DistributedMutex  ,
StressTryLockSixteenThreads   
)

Definition at line 767 of file DistributedMutexTest.cpp.

767  {
768  concurrentTryLocks(16);
769 }
folly::TEST ( DistributedMutex  ,
StressTryLockThirtyTwoThreads   
)

Definition at line 770 of file DistributedMutexTest.cpp.

770  {
771  concurrentTryLocks(32);
772 }
folly::TEST ( DistributedMutex  ,
StressTryLockSixtyFourThreads   
)

Definition at line 773 of file DistributedMutexTest.cpp.

773  {
774  concurrentTryLocks(64);
775 }
folly::TEST ( DistributedMutex  ,
DeterministicTryLockTwoThreads   
)

Definition at line 777 of file DistributedMutexTest.cpp.

References folly::test::DeterministicSchedule::uniform().

777  {
778  auto iterations = numIterationsDeterministicTest(2);
779  concurrentTryLocks(2, iterations);
780 
781  for (auto pass = 0; pass < 3; ++pass) {
782  auto&& schedule = DSched{DSched::uniform(pass)};
783  concurrentTryLocks<test::DeterministicAtomic>(2, iterations);
784  static_cast<void>(schedule);
785  }
786 }
static std::function< size_t(size_t)> uniform(uint64_t seed)
folly::TEST ( Optional  ,
ConstMember   
)

Definition at line 780 of file OptionalTest.cpp.

References EXPECT_EQ, and sum().

780  {
781  // Verify that the compiler doesn't optimize out the second load of
782  // o->x based on the assumption that the field is const.
783  //
784  // Current Optional implementation doesn't defend against that
785  // assumption, thus replacing an optional where the object has const
786  // members is technically UB and would require wrapping each access
787  // to the storage with std::launder, but this prevents useful
788  // optimizations.
789  //
790  // Implementations of std::optional in both libstdc++ and libc++ are
791  // subject to the same UB. It is then reasonable to believe that
792  // major compilers don't rely on the constness assumption.
793  Optional<WithConstMember> o(1);
794  int sum = 0;
795  sum += o->x;
796  replaceWith2(o);
797  sum += o->x;
798  EXPECT_EQ(sum, 3);
799 }
std::atomic< int64_t > sum(0)
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
folly::TEST ( DistributedMutex  ,
DeterministicTryLockFourThreads   
)

Definition at line 787 of file DistributedMutexTest.cpp.

References folly::test::DeterministicSchedule::uniform().

787  {
788  auto iterations = numIterationsDeterministicTest(4);
789  concurrentTryLocks(4, iterations);
790 
791  for (auto pass = 0; pass < 3; ++pass) {
792  auto&& schedule = DSched{DSched::uniform(pass)};
793  concurrentTryLocks<test::DeterministicAtomic>(4, iterations);
794  static_cast<void>(schedule);
795  }
796 }
static std::function< size_t(size_t)> uniform(uint64_t seed)
folly::TEST ( DistributedMutex  ,
DeterministicTryLockEightThreads   
)

Definition at line 797 of file DistributedMutexTest.cpp.

References folly::test::DeterministicSchedule::uniform().

797  {
798  auto iterations = numIterationsDeterministicTest(8);
799  concurrentTryLocks(8, iterations);
800 
801  for (auto pass = 0; pass < 3; ++pass) {
802  auto&& schedule = DSched{DSched::uniform(pass)};
803  concurrentTryLocks<test::DeterministicAtomic>(8, iterations);
804  static_cast<void>(schedule);
805  }
806 }
static std::function< size_t(size_t)> uniform(uint64_t seed)
folly::TEST ( Optional  ,
NoneMatchesNullopt   
)

Definition at line 801 of file OptionalTest.cpp.

References EXPECT_FALSE, and none.

801  {
802  auto op = make_optional<int>(10);
803  op = {};
804  EXPECT_FALSE(op.has_value());
805 
806  op = make_optional<int>(20);
807  op = none;
808  EXPECT_FALSE(op.has_value());
809 }
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
constexpr None none
Definition: Optional.h:87
folly::TEST ( DistributedMutex  ,
DeterministicTryLockSixteenThreads   
)

Definition at line 807 of file DistributedMutexTest.cpp.

References folly::test::DeterministicSchedule::uniform().

807  {
808  auto iterations = numIterationsDeterministicTest(16);
809  concurrentTryLocks(16, iterations);
810 
811  for (auto pass = 0; pass < 3; ++pass) {
812  auto&& schedule = DSched{DSched::uniform(pass)};
813  concurrentTryLocks<test::DeterministicAtomic>(16, iterations);
814  static_cast<void>(schedule);
815  }
816 }
static std::function< size_t(size_t)> uniform(uint64_t seed)
folly::TEST ( DistributedMutex  ,
DeterministicTryLockThirtyTwoThreads   
)

Definition at line 817 of file DistributedMutexTest.cpp.

References folly::test::DeterministicSchedule::uniform().

817  {
818  auto iterations = numIterationsDeterministicTest(32);
819  concurrentTryLocks(32, iterations);
820 
821  for (auto pass = 0; pass < 3; ++pass) {
822  auto&& schedule = DSched{DSched::uniform(pass)};
823  concurrentTryLocks<test::DeterministicAtomic>(32, iterations);
824  static_cast<void>(schedule);
825  }
826 }
static std::function< size_t(size_t)> uniform(uint64_t seed)
folly::TEST ( DistributedMutex  ,
DeterministicTryLockSixtyFourThreads   
)

Definition at line 827 of file DistributedMutexTest.cpp.

References folly::test::DeterministicSchedule::uniform().

827  {
828  concurrentTryLocks(64, 5);
829 
830  for (auto pass = 0; pass < 3; ++pass) {
831  auto&& schedule = DSched{DSched::uniform(pass)};
832  concurrentTryLocks<test::DeterministicAtomic>(64, 5);
833  static_cast<void>(schedule);
834  }
835 }
static std::function< size_t(size_t)> uniform(uint64_t seed)
folly::TEST ( FollyLockTest  ,
TestVariadicLockWithSynchronized   
)

Definition at line 884 of file SynchronizedTest.cpp.

References EXPECT_TRUE, lock(), folly::ssl::detail::locks(), rlock(), and wlock().

884  {
885  {
886  auto syncs = std::array<folly::Synchronized<int>, 3>{};
887  auto& one = syncs[0];
888  auto const& two = syncs[1];
889  auto& three = syncs[2];
890  auto locks =
891  lock(folly::wlock(one), folly::rlock(two), folly::wlock(three));
892  EXPECT_TRUE(std::get<0>(locks));
893  EXPECT_TRUE(std::get<1>(locks));
894  EXPECT_TRUE(std::get<2>(locks));
895  }
896  {
897  auto syncs = std::array<folly::Synchronized<int, std::mutex>, 2>{};
898  auto locks = lock(folly::lock(syncs[0]), folly::lock(syncs[1]));
899  EXPECT_TRUE(std::get<0>(locks));
900  EXPECT_TRUE(std::get<1>(locks));
901  }
902 }
auto wlock(Synchronized< D, M > &synchronized, Args &&...args)
static std::unique_ptr< SSLLock[]> & locks()
auto rlock(const Synchronized< Data, Mutex > &synchronized, Args &&...args)
auto lock(SynchronizedLocker...lockersIn) -> std::tuple< typename SynchronizedLocker::LockedPtr... >
Definition: Synchronized.h:871
auto lock(Synchronized< D, M > &synchronized, Args &&...args)
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( AsyncSSLSocketTest  ,
SSLParseClientHelloSuccess   
)

Verify Client Ciphers obtained using SSL MSG Callback.

Definition at line 901 of file AsyncSSLSocketTest.cpp.

References folly::SSLHandshakeServerParseClientHello::chosenCipher_, folly::SSLHandshakeServerParseClientHello::clientCiphers_, EXPECT_EQ, EXPECT_TRUE, getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, folly::SSLHandshakeBase::handshakeVerify_, kTestCA, kTestCert, kTestKey, folly::EventBase::loop(), and folly::gen::move.

901  {
902  EventBase eventBase;
903  auto clientCtx = std::make_shared<SSLContext>();
904  auto serverCtx = std::make_shared<SSLContext>();
905  serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
906  serverCtx->ciphers("ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA");
907  serverCtx->loadPrivateKey(kTestKey);
908  serverCtx->loadCertificate(kTestCert);
909  serverCtx->loadTrustedCertificates(kTestCA);
910  serverCtx->loadClientCAList(kTestCA);
911 
912  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
913  clientCtx->ciphers("AES256-SHA:AES128-SHA");
914  clientCtx->loadPrivateKey(kTestKey);
915  clientCtx->loadCertificate(kTestCert);
916  clientCtx->loadTrustedCertificates(kTestCA);
917 
918  int fds[2];
919  getfds(fds);
920 
921  AsyncSSLSocket::UniquePtr clientSock(
922  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
923  AsyncSSLSocket::UniquePtr serverSock(
924  new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
925 
926  SSLHandshakeClient client(std::move(clientSock), true, true);
927  SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true);
928 
929  eventBase.loop();
930 
931 #if defined(OPENSSL_IS_BORINGSSL)
932  EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA");
933 #else
934  EXPECT_EQ(server.clientCiphers_, "AES256-SHA:AES128-SHA:00ff");
935 #endif
936  EXPECT_EQ(server.chosenCipher_, "AES256-SHA");
937  EXPECT_TRUE(client.handshakeVerify_);
938  EXPECT_TRUE(client.handshakeSuccess_);
939  EXPECT_TRUE(!client.handshakeError_);
940  EXPECT_TRUE(server.handshakeVerify_);
941  EXPECT_TRUE(server.handshakeSuccess_);
942  EXPECT_TRUE(!server.handshakeError_);
943 }
const char * kTestCert
const std::string kTestKey
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * kTestCA
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( FollyLockTest  ,
TestVariadicLockWithArbitraryLockables   
)

Definition at line 904 of file SynchronizedTest.cpp.

References EXPECT_TRUE, and lock().

904  {
905  auto&& one = std::mutex{};
906  auto&& two = std::mutex{};
907 
908  auto lckOne = std::unique_lock<std::mutex>{one, std::defer_lock};
909  auto lckTwo = std::unique_lock<std::mutex>{two, std::defer_lock};
910  folly::lock(lckOne, lckTwo);
911  EXPECT_TRUE(lckOne);
912  EXPECT_TRUE(lckTwo);
913 }
auto lock(Synchronized< D, M > &synchronized, Args &&...args)
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
std::mutex mutex
folly::TEST ( FollyLockTest  ,
TestVariadicLockSmartAndPoliteAlgorithm   
)

Definition at line 915 of file SynchronizedTest.cpp.

References EXPECT_EQ, lock(), and makeGuard().

915  {
916  auto one = TestMutex{};
917  auto two = TestMutex{};
918  auto three = TestMutex{};
919  auto makeReset = [&] {
920  return folly::makeGuard([&] {
921  one = TestMutex{};
922  two = TestMutex{};
923  three = TestMutex{};
924  });
925  };
926 
927  {
928  auto reset = makeReset();
929  folly::lock(one, two, three);
930  EXPECT_EQ(one.numTimesLocked, 1);
931  EXPECT_EQ(one.numTimesUnlocked, 0);
932  EXPECT_EQ(two.numTimesLocked, 1);
933  EXPECT_EQ(two.numTimesUnlocked, 0);
934  EXPECT_EQ(three.numTimesLocked, 1);
935  EXPECT_EQ(three.numTimesUnlocked, 0);
936  }
937 
938  {
939  auto reset = makeReset();
940  two.shouldTryLockSucceed = false;
941  folly::lock(one, two, three);
942  EXPECT_EQ(one.numTimesLocked, 2);
943  EXPECT_EQ(one.numTimesUnlocked, 1);
944  EXPECT_EQ(two.numTimesLocked, 1);
945  EXPECT_EQ(two.numTimesUnlocked, 0);
946  EXPECT_EQ(three.numTimesLocked, 1);
947  EXPECT_EQ(three.numTimesUnlocked, 0);
948  }
949 
950  {
951  auto reset = makeReset();
952  three.shouldTryLockSucceed = false;
953  folly::lock(one, two, three);
954  EXPECT_EQ(one.numTimesLocked, 2);
955  EXPECT_EQ(one.numTimesUnlocked, 1);
956  EXPECT_EQ(two.numTimesLocked, 2);
957  EXPECT_EQ(two.numTimesUnlocked, 1);
958  EXPECT_EQ(three.numTimesLocked, 1);
959  EXPECT_EQ(three.numTimesUnlocked, 0);
960  }
961 
962  {
963  auto reset = makeReset();
964  three.shouldTryLockSucceed = false;
965 
966  three.onLock = [&] {
967  // when three gets locked make one fail
968  one.shouldTryLockSucceed = false;
969  // then when one gets locked make three succeed to finish the test
970  one.onLock = [&] { three.shouldTryLockSucceed = true; };
971  };
972 
973  folly::lock(one, two, three);
974  EXPECT_EQ(one.numTimesLocked, 2);
975  EXPECT_EQ(one.numTimesUnlocked, 1);
976  EXPECT_EQ(two.numTimesLocked, 2);
977  EXPECT_EQ(two.numTimesUnlocked, 1);
978  EXPECT_EQ(three.numTimesLocked, 2);
979  EXPECT_EQ(three.numTimesUnlocked, 1);
980  }
981 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
auto lock(Synchronized< D, M > &synchronized, Args &&...args)
FOLLY_NODISCARD detail::ScopeGuardImplDecay< F, true > makeGuard(F &&f) noexcept(noexcept(detail::ScopeGuardImplDecay< F, true >(static_cast< F && >(f))))
Definition: ScopeGuard.h:184
folly::TEST ( AsyncSSLSocketTest  ,
GetClientCertificate   
)

Verify that server is able to get client cert by getPeerCert() API.

Definition at line 948 of file AsyncSSLSocketTest.cpp.

References EXPECT_EQ, EXPECT_TRUE, getfds(), folly::SSLHandshakeBase::handshakeSuccess_, kClientTestCA, kClientTestCert, kClientTestKey, kTestCA, kTestCert, kTestKey, folly::EventBase::loop(), and folly::gen::move.

948  {
949  EventBase eventBase;
950  auto clientCtx = std::make_shared<SSLContext>();
951  auto serverCtx = std::make_shared<SSLContext>();
952  serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
953  serverCtx->ciphers("ECDHE-RSA-AES128-SHA:AES128-SHA:AES256-SHA");
954  serverCtx->loadPrivateKey(kTestKey);
955  serverCtx->loadCertificate(kTestCert);
956  serverCtx->loadTrustedCertificates(kClientTestCA);
957  serverCtx->loadClientCAList(kClientTestCA);
958 
959  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
960  clientCtx->ciphers("AES256-SHA:AES128-SHA");
961  clientCtx->loadPrivateKey(kClientTestKey);
962  clientCtx->loadCertificate(kClientTestCert);
963  clientCtx->loadTrustedCertificates(kTestCA);
964 
965  std::array<int, 2> fds;
966  getfds(fds.data());
967 
968  AsyncSSLSocket::UniquePtr clientSock(
969  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
970  AsyncSSLSocket::UniquePtr serverSock(
971  new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
972 
973  SSLHandshakeClient client(std::move(clientSock), true, true);
974  SSLHandshakeServerParseClientHello server(std::move(serverSock), true, true);
975 
976  eventBase.loop();
977 
978  // Handshake should succeed.
979  EXPECT_TRUE(client.handshakeSuccess_);
980  EXPECT_TRUE(server.handshakeSuccess_);
981 
982  // Reclaim the sockets from SSLHandshakeBase.
983  auto cliSocket = std::move(client).moveSocket();
984  auto srvSocket = std::move(server).moveSocket();
985 
986  // Client cert retrieved from server side.
987  folly::ssl::X509UniquePtr serverPeerCert = srvSocket->getPeerCert();
988  CHECK(serverPeerCert);
989 
990  // Client cert retrieved from client side.
991  const X509* clientSelfCert = cliSocket->getSelfCert();
992  CHECK(clientSelfCert);
993 
994  // The two certs should be the same.
995  EXPECT_EQ(0, X509_cmp(clientSelfCert, serverPeerCert.get()));
996 }
const char * kTestCert
std::unique_ptr< X509, X509Deleter > X509UniquePtr
const std::string kTestKey
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
const char * kClientTestKey
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * kClientTestCert
const char * kTestCA
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
const char * kClientTestCA
folly::TEST ( SynchronizedAlgorithmTest  ,
Basic   
)

Definition at line 983 of file SynchronizedTest.cpp.

References EXPECT_EQ, s, value(), and wlock().

983  {
984  auto sync = Synchronized<int>{0};
985  auto value = synchronized([](auto s) { return *s; }, wlock(sync));
986  EXPECT_EQ(value, 0);
987 }
auto wlock(Synchronized &synchronized, Args &&...args)
Definition: Synchronized.h:925
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
static const char *const value
Definition: Conv.cpp:50
static set< string > s
folly::TEST ( SynchronizedAlgorithmTest  ,
BasicNonShareableMutex   
)

Definition at line 989 of file SynchronizedTest.cpp.

References EXPECT_EQ, lock(), s, and value().

989  {
990  auto sync = Synchronized<int, std::mutex>{0};
991  auto value = synchronized([](auto s) { return *s; }, lock(sync));
992  EXPECT_EQ(value, 0);
993 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
auto lock(SynchronizedLocker...lockersIn) -> std::tuple< typename SynchronizedLocker::LockedPtr... >
Definition: Synchronized.h:871
static const char *const value
Definition: Conv.cpp:50
static set< string > s
folly::TEST ( Synchronized  ,
SynchronizedFunctionNonConst   
)

Definition at line 995 of file SynchronizedTest.cpp.

References EXPECT_EQ, std::tr1::make_tuple(), and wlock().

995  {
996  auto locked = 0;
997  auto unlocked = 0;
998  auto sync = Synchronized<int, TestSharedMutex>{
999  std::piecewise_construct,
1000  std::make_tuple(0),
1001  std::make_tuple([&] { ++locked; }, [&] { ++unlocked; }, [] {}, [] {})};
1002 
1003  synchronized([](auto) {}, wlock(sync));
1004  EXPECT_EQ(locked, 1);
1005  EXPECT_EQ(unlocked, 1);
1006 }
auto wlock(Synchronized &synchronized, Args &&...args)
Definition: Synchronized.h:925
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
tuple make_tuple()
Definition: gtest-tuple.h:675
folly::TEST ( AsyncSSLSocketTest  ,
SSLParseClientHelloOnePacket   
)

Definition at line 998 of file AsyncSSLSocketTest.cpp.

References EXPECT_EQ, EXPECT_TRUE, getfds(), SCOPE_EXIT, uint16_t, uint32_t, uint8_t, and folly::io::detail::Writable< Derived >::write().

998  {
999  EventBase eventBase;
1000  auto ctx = std::make_shared<SSLContext>();
1001 
1002  int fds[2];
1003  getfds(fds);
1004 
1005  int bufLen = 42;
1006  uint8_t majorVersion = 18;
1007  uint8_t minorVersion = 25;
1008 
1009  // Create callback buf
1010  auto buf = IOBuf::create(bufLen);
1011  buf->append(bufLen);
1012  folly::io::RWPrivateCursor cursor(buf.get());
1013  cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1014  cursor.write<uint16_t>(0);
1015  cursor.write<uint8_t>(38);
1016  cursor.write<uint8_t>(majorVersion);
1017  cursor.write<uint8_t>(minorVersion);
1018  cursor.skip(32);
1019  cursor.write<uint32_t>(0);
1020 
1021  SSL* ssl = ctx->createSSL();
1022  SCOPE_EXIT {
1023  SSL_free(ssl);
1024  };
1025  AsyncSSLSocket::UniquePtr sock(
1026  new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1027  sock->enableClientHelloParsing();
1028 
1029  // Test client hello parsing in one packet
1030  AsyncSSLSocket::clientHelloParsingCallback(
1031  0, 0, SSL3_RT_HANDSHAKE, buf->data(), buf->length(), ssl, sock.get());
1032  buf.reset();
1033 
1034  auto parsedClientHello = sock->getClientHelloInfo();
1035  EXPECT_TRUE(parsedClientHello != nullptr);
1036  EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1037  EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1038 }
std::enable_if< std::is_arithmetic< T >::value >::type write(T value)
Definition: Cursor.h:737
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( Synchronized  ,
SynchronizedFunctionConst   
)

Definition at line 1008 of file SynchronizedTest.cpp.

References EXPECT_EQ, std::tr1::make_tuple(), and rlock().

1008  {
1009  auto locked = 0;
1010  auto unlocked = 0;
1011  auto sync = Synchronized<int, TestSharedMutex>{
1012  std::piecewise_construct,
1013  std::make_tuple(0),
1014  std::make_tuple([] {}, [] {}, [&] { ++locked; }, [&] { ++unlocked; })};
1015 
1016  synchronized([](auto) {}, rlock(sync));
1017  EXPECT_EQ(locked, 1);
1018  EXPECT_EQ(unlocked, 1);
1019 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
auto rlock(Synchronized &synchronized, Args &&...args)
Definition: Synchronized.h:935
tuple make_tuple()
Definition: gtest-tuple.h:675
folly::TEST ( Synchronized  ,
SynchronizedFunctionManyObjects   
)

Definition at line 1021 of file SynchronizedTest.cpp.

References EXPECT_TRUE, fail(), std::tr1::make_tuple(), rlock(), and wlock().

1021  {
1022  auto fail = [] { EXPECT_TRUE(false); };
1023  auto pass = [] {};
1024 
1025  auto one = Synchronized<int, TestSharedMutex>{
1026  std::piecewise_construct,
1027  std::make_tuple(0),
1028  std::make_tuple(pass, pass, fail, fail)};
1029  auto two = Synchronized<std::string, TestSharedMutex>{
1030  std::piecewise_construct,
1031  std::make_tuple(),
1032  std::make_tuple(fail, fail, pass, pass)};
1033 
1034  synchronized([](auto, auto) {}, wlock(one), rlock(two));
1035 }
auto wlock(Synchronized &synchronized, Args &&...args)
Definition: Synchronized.h:925
auto rlock(Synchronized &synchronized, Args &&...args)
Definition: Synchronized.h:935
tuple make_tuple()
Definition: gtest-tuple.h:675
void fail()
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
folly::TEST ( AsyncSSLSocketTest  ,
SSLParseClientHelloTwoPackets   
)

Definition at line 1040 of file AsyncSSLSocketTest.cpp.

References folly::IOBuf::copyBuffer(), EXPECT_EQ, EXPECT_TRUE, getfds(), SCOPE_EXIT, uint16_t, uint32_t, uint8_t, and folly::io::detail::Writable< Derived >::write().

1040  {
1041  EventBase eventBase;
1042  auto ctx = std::make_shared<SSLContext>();
1043 
1044  int fds[2];
1045  getfds(fds);
1046 
1047  int bufLen = 42;
1048  uint8_t majorVersion = 18;
1049  uint8_t minorVersion = 25;
1050 
1051  // Create callback buf
1052  auto buf = IOBuf::create(bufLen);
1053  buf->append(bufLen);
1054  folly::io::RWPrivateCursor cursor(buf.get());
1055  cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1056  cursor.write<uint16_t>(0);
1057  cursor.write<uint8_t>(38);
1058  cursor.write<uint8_t>(majorVersion);
1059  cursor.write<uint8_t>(minorVersion);
1060  cursor.skip(32);
1061  cursor.write<uint32_t>(0);
1062 
1063  SSL* ssl = ctx->createSSL();
1064  SCOPE_EXIT {
1065  SSL_free(ssl);
1066  };
1067  AsyncSSLSocket::UniquePtr sock(
1068  new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1069  sock->enableClientHelloParsing();
1070 
1071  // Test parsing with two packets with first packet size < 3
1072  auto bufCopy = folly::IOBuf::copyBuffer(buf->data(), 2);
1073  AsyncSSLSocket::clientHelloParsingCallback(
1074  0,
1075  0,
1076  SSL3_RT_HANDSHAKE,
1077  bufCopy->data(),
1078  bufCopy->length(),
1079  ssl,
1080  sock.get());
1081  bufCopy.reset();
1082  bufCopy = folly::IOBuf::copyBuffer(buf->data() + 2, buf->length() - 2);
1083  AsyncSSLSocket::clientHelloParsingCallback(
1084  0,
1085  0,
1086  SSL3_RT_HANDSHAKE,
1087  bufCopy->data(),
1088  bufCopy->length(),
1089  ssl,
1090  sock.get());
1091  bufCopy.reset();
1092 
1093  auto parsedClientHello = sock->getClientHelloInfo();
1094  EXPECT_TRUE(parsedClientHello != nullptr);
1095  EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1096  EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1097 }
std::enable_if< std::is_arithmetic< T >::value >::type write(T value)
Definition: Cursor.h:737
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
static std::unique_ptr< IOBuf > copyBuffer(const void *buf, std::size_t size, std::size_t headroom=0, std::size_t minTailroom=0)
Definition: IOBuf.h:1587
folly::TEST ( AsyncSSLSocketTest  ,
SSLParseClientHelloMultiplePackets   
)

Definition at line 1099 of file AsyncSSLSocketTest.cpp.

References folly::IOBuf::copyBuffer(), EXPECT_EQ, EXPECT_TRUE, getfds(), i, min, SCOPE_EXIT, uint16_t, uint32_t, uint8_t, and folly::io::detail::Writable< Derived >::write().

1099  {
1100  EventBase eventBase;
1101  auto ctx = std::make_shared<SSLContext>();
1102 
1103  int fds[2];
1104  getfds(fds);
1105 
1106  int bufLen = 42;
1107  uint8_t majorVersion = 18;
1108  uint8_t minorVersion = 25;
1109 
1110  // Create callback buf
1111  auto buf = IOBuf::create(bufLen);
1112  buf->append(bufLen);
1113  folly::io::RWPrivateCursor cursor(buf.get());
1114  cursor.write<uint8_t>(SSL3_MT_CLIENT_HELLO);
1115  cursor.write<uint16_t>(0);
1116  cursor.write<uint8_t>(38);
1117  cursor.write<uint8_t>(majorVersion);
1118  cursor.write<uint8_t>(minorVersion);
1119  cursor.skip(32);
1120  cursor.write<uint32_t>(0);
1121 
1122  SSL* ssl = ctx->createSSL();
1123  SCOPE_EXIT {
1124  SSL_free(ssl);
1125  };
1126  AsyncSSLSocket::UniquePtr sock(
1127  new AsyncSSLSocket(ctx, &eventBase, fds[0], true));
1128  sock->enableClientHelloParsing();
1129 
1130  // Test parsing with multiple small packets
1131  for (std::size_t i = 0; i < buf->length(); i += 3) {
1132  auto bufCopy = folly::IOBuf::copyBuffer(
1133  buf->data() + i, std::min((std::size_t)3, buf->length() - i));
1134  AsyncSSLSocket::clientHelloParsingCallback(
1135  0,
1136  0,
1137  SSL3_RT_HANDSHAKE,
1138  bufCopy->data(),
1139  bufCopy->length(),
1140  ssl,
1141  sock.get());
1142  bufCopy.reset();
1143  }
1144 
1145  auto parsedClientHello = sock->getClientHelloInfo();
1146  EXPECT_TRUE(parsedClientHello != nullptr);
1147  EXPECT_EQ(parsedClientHello->clientHelloMajorVersion_, majorVersion);
1148  EXPECT_EQ(parsedClientHello->clientHelloMinorVersion_, minorVersion);
1149 }
std::enable_if< std::is_arithmetic< T >::value >::type write(T value)
Definition: Cursor.h:737
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
LogLevel min
Definition: LogLevel.cpp:30
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
static std::unique_ptr< IOBuf > copyBuffer(const void *buf, std::size_t size, std::size_t headroom=0, std::size_t minTailroom=0)
Definition: IOBuf.h:1587
folly::TEST ( AsyncSSLSocketTest  ,
SSLHandshakeValidationSuccess   
)

Verify sucessful behavior of SSL certificate validation.

Definition at line 1154 of file AsyncSSLSocketTest.cpp.

References EXPECT_LE, EXPECT_TRUE, getctx(), getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, folly::SSLHandshakeBase::handshakeTime, folly::SSLHandshakeBase::handshakeVerify_, kTestCA, folly::EventBase::loop(), and folly::gen::move.

1154  {
1155  EventBase eventBase;
1156  auto clientCtx = std::make_shared<SSLContext>();
1157  auto dfServerCtx = std::make_shared<SSLContext>();
1158 
1159  int fds[2];
1160  getfds(fds);
1161  getctx(clientCtx, dfServerCtx);
1162 
1163  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1164  dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1165 
1166  AsyncSSLSocket::UniquePtr clientSock(
1167  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1168  AsyncSSLSocket::UniquePtr serverSock(
1169  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1170 
1171  SSLHandshakeClient client(std::move(clientSock), true, true);
1172  clientCtx->loadTrustedCertificates(kTestCA);
1173 
1174  SSLHandshakeServer server(std::move(serverSock), true, true);
1175 
1176  eventBase.loop();
1177 
1178  EXPECT_TRUE(client.handshakeVerify_);
1179  EXPECT_TRUE(client.handshakeSuccess_);
1180  EXPECT_TRUE(!client.handshakeError_);
1181  EXPECT_LE(0, client.handshakeTime.count());
1182  EXPECT_TRUE(!server.handshakeVerify_);
1183  EXPECT_TRUE(server.handshakeSuccess_);
1184  EXPECT_TRUE(!server.handshakeError_);
1185  EXPECT_LE(0, server.handshakeTime.count());
1186 }
#define EXPECT_LE(val1, val2)
Definition: gtest.h:1928
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * kTestCA
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
folly::TEST ( AsyncSSLSocketTest  ,
SSLHandshakeValidationFailure   
)

Verify that the client's verification callback is able to fail SSL connection establishment.

Definition at line 1192 of file AsyncSSLSocketTest.cpp.

References EXPECT_LE, EXPECT_TRUE, getctx(), getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, folly::SSLHandshakeBase::handshakeTime, folly::SSLHandshakeBase::handshakeVerify_, kTestCA, folly::EventBase::loop(), and folly::gen::move.

1192  {
1193  EventBase eventBase;
1194  auto clientCtx = std::make_shared<SSLContext>();
1195  auto dfServerCtx = std::make_shared<SSLContext>();
1196 
1197  int fds[2];
1198  getfds(fds);
1199  getctx(clientCtx, dfServerCtx);
1200 
1201  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1202  dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1203 
1204  AsyncSSLSocket::UniquePtr clientSock(
1205  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1206  AsyncSSLSocket::UniquePtr serverSock(
1207  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1208 
1209  SSLHandshakeClient client(std::move(clientSock), true, false);
1210  clientCtx->loadTrustedCertificates(kTestCA);
1211 
1212  SSLHandshakeServer server(std::move(serverSock), true, true);
1213 
1214  eventBase.loop();
1215 
1216  EXPECT_TRUE(client.handshakeVerify_);
1217  EXPECT_TRUE(!client.handshakeSuccess_);
1218  EXPECT_TRUE(client.handshakeError_);
1219  EXPECT_LE(0, client.handshakeTime.count());
1220  EXPECT_TRUE(!server.handshakeVerify_);
1221  EXPECT_TRUE(!server.handshakeSuccess_);
1222  EXPECT_TRUE(server.handshakeError_);
1223  EXPECT_LE(0, server.handshakeTime.count());
1224 }
#define EXPECT_LE(val1, val2)
Definition: gtest.h:1928
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * kTestCA
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
folly::TEST ( AsyncSSLSocketTest  ,
OverrideSSLCtxDisableVerify   
)

Verify that the options in SSLContext can be overridden in sslConnect/Accept.i.e specifying that no validation should be performed allows an otherwise-invalid certificate to be accepted and doesn't fire the validation callback.

Definition at line 1232 of file AsyncSSLSocketTest.cpp.

References EXPECT_LE, EXPECT_TRUE, getctx(), getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, folly::SSLHandshakeBase::handshakeTime, folly::SSLHandshakeBase::handshakeVerify_, kTestCA, folly::EventBase::loop(), and folly::gen::move.

1232  {
1233  EventBase eventBase;
1234  auto clientCtx = std::make_shared<SSLContext>();
1235  auto dfServerCtx = std::make_shared<SSLContext>();
1236 
1237  int fds[2];
1238  getfds(fds);
1239  getctx(clientCtx, dfServerCtx);
1240 
1241  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1242  dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1243 
1244  AsyncSSLSocket::UniquePtr clientSock(
1245  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1246  AsyncSSLSocket::UniquePtr serverSock(
1247  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1248 
1249  SSLHandshakeClientNoVerify client(std::move(clientSock), false, false);
1250  clientCtx->loadTrustedCertificates(kTestCA);
1251 
1252  SSLHandshakeServerNoVerify server(std::move(serverSock), false, false);
1253 
1254  eventBase.loop();
1255 
1256  EXPECT_TRUE(!client.handshakeVerify_);
1257  EXPECT_TRUE(client.handshakeSuccess_);
1258  EXPECT_TRUE(!client.handshakeError_);
1259  EXPECT_LE(0, client.handshakeTime.count());
1260  EXPECT_TRUE(!server.handshakeVerify_);
1261  EXPECT_TRUE(server.handshakeSuccess_);
1262  EXPECT_TRUE(!server.handshakeError_);
1263  EXPECT_LE(0, server.handshakeTime.count());
1264 }
#define EXPECT_LE(val1, val2)
Definition: gtest.h:1928
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * kTestCA
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
folly::TEST ( AsyncSSLSocketTest  ,
OverrideSSLCtxEnableVerify   
)

Verify that the options in SSLContext can be overridden in sslConnect/Accept. Enable verification even if context says otherwise. Test requireClientCert with client cert

Definition at line 1271 of file AsyncSSLSocketTest.cpp.

References EXPECT_FALSE, EXPECT_LE, EXPECT_TRUE, getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, folly::SSLHandshakeBase::handshakeTime, folly::SSLHandshakeBase::handshakeVerify_, kTestCA, kTestCert, kTestKey, folly::EventBase::loop(), and folly::gen::move.

1271  {
1272  EventBase eventBase;
1273  auto clientCtx = std::make_shared<SSLContext>();
1274  auto serverCtx = std::make_shared<SSLContext>();
1275  serverCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1276  serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1277  serverCtx->loadPrivateKey(kTestKey);
1278  serverCtx->loadCertificate(kTestCert);
1279  serverCtx->loadTrustedCertificates(kTestCA);
1280  serverCtx->loadClientCAList(kTestCA);
1281 
1282  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1283  clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1284  clientCtx->loadPrivateKey(kTestKey);
1285  clientCtx->loadCertificate(kTestCert);
1286  clientCtx->loadTrustedCertificates(kTestCA);
1287 
1288  int fds[2];
1289  getfds(fds);
1290 
1291  AsyncSSLSocket::UniquePtr clientSock(
1292  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1293  AsyncSSLSocket::UniquePtr serverSock(
1294  new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1295 
1296  SSLHandshakeClientDoVerify client(std::move(clientSock), true, true);
1297  SSLHandshakeServerDoVerify server(std::move(serverSock), true, true);
1298 
1299  eventBase.loop();
1300 
1301  EXPECT_TRUE(client.handshakeVerify_);
1302  EXPECT_TRUE(client.handshakeSuccess_);
1303  EXPECT_FALSE(client.handshakeError_);
1304  EXPECT_LE(0, client.handshakeTime.count());
1305  EXPECT_TRUE(server.handshakeVerify_);
1306  EXPECT_TRUE(server.handshakeSuccess_);
1307  EXPECT_FALSE(server.handshakeError_);
1308  EXPECT_LE(0, server.handshakeTime.count());
1309 }
#define EXPECT_LE(val1, val2)
Definition: gtest.h:1928
const char * kTestCert
const std::string kTestKey
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * kTestCA
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncSSLSocketTest  ,
SSLHandshakeValidationOverride   
)

Verify that the client's verification callback is able to override the preverification failure and allow a successful connection.

Definition at line 1315 of file AsyncSSLSocketTest.cpp.

References EXPECT_LE, EXPECT_TRUE, getctx(), getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, folly::SSLHandshakeBase::handshakeTime, folly::SSLHandshakeBase::handshakeVerify_, folly::EventBase::loop(), and folly::gen::move.

1315  {
1316  EventBase eventBase;
1317  auto clientCtx = std::make_shared<SSLContext>();
1318  auto dfServerCtx = std::make_shared<SSLContext>();
1319 
1320  int fds[2];
1321  getfds(fds);
1322  getctx(clientCtx, dfServerCtx);
1323 
1324  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1325  dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1326 
1327  AsyncSSLSocket::UniquePtr clientSock(
1328  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1329  AsyncSSLSocket::UniquePtr serverSock(
1330  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1331 
1332  SSLHandshakeClient client(std::move(clientSock), false, true);
1333  SSLHandshakeServer server(std::move(serverSock), true, true);
1334 
1335  eventBase.loop();
1336 
1337  EXPECT_TRUE(client.handshakeVerify_);
1338  EXPECT_TRUE(client.handshakeSuccess_);
1339  EXPECT_TRUE(!client.handshakeError_);
1340  EXPECT_LE(0, client.handshakeTime.count());
1341  EXPECT_TRUE(!server.handshakeVerify_);
1342  EXPECT_TRUE(server.handshakeSuccess_);
1343  EXPECT_TRUE(!server.handshakeError_);
1344  EXPECT_LE(0, server.handshakeTime.count());
1345 }
#define EXPECT_LE(val1, val2)
Definition: gtest.h:1928
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
folly::TEST ( AsyncSSLSocketTest  ,
SSLHandshakeValidationSkip   
)

Verify that specifying that no validation should be performed allows an otherwise-invalid certificate to be accepted and doesn't fire the validation callback.

Definition at line 1352 of file AsyncSSLSocketTest.cpp.

References EXPECT_LE, EXPECT_TRUE, getctx(), getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, folly::SSLHandshakeBase::handshakeTime, folly::SSLHandshakeBase::handshakeVerify_, folly::EventBase::loop(), and folly::gen::move.

1352  {
1353  EventBase eventBase;
1354  auto clientCtx = std::make_shared<SSLContext>();
1355  auto dfServerCtx = std::make_shared<SSLContext>();
1356 
1357  int fds[2];
1358  getfds(fds);
1359  getctx(clientCtx, dfServerCtx);
1360 
1361  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1362  dfServerCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1363 
1364  AsyncSSLSocket::UniquePtr clientSock(
1365  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1366  AsyncSSLSocket::UniquePtr serverSock(
1367  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
1368 
1369  SSLHandshakeClient client(std::move(clientSock), false, false);
1370  SSLHandshakeServer server(std::move(serverSock), false, false);
1371 
1372  eventBase.loop();
1373 
1374  EXPECT_TRUE(!client.handshakeVerify_);
1375  EXPECT_TRUE(client.handshakeSuccess_);
1376  EXPECT_TRUE(!client.handshakeError_);
1377  EXPECT_LE(0, client.handshakeTime.count());
1378  EXPECT_TRUE(!server.handshakeVerify_);
1379  EXPECT_TRUE(server.handshakeSuccess_);
1380  EXPECT_TRUE(!server.handshakeError_);
1381  EXPECT_LE(0, server.handshakeTime.count());
1382 }
#define EXPECT_LE(val1, val2)
Definition: gtest.h:1928
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
folly::TEST ( AsyncSSLSocketTest  ,
ClientCertHandshakeSuccess   
)

Test requireClientCert with client cert

Definition at line 1387 of file AsyncSSLSocketTest.cpp.

References EXPECT_EQ, EXPECT_FALSE, EXPECT_LE, EXPECT_NE, EXPECT_TRUE, getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, folly::SSLHandshakeBase::handshakeTime, folly::SSLHandshakeBase::handshakeVerify_, kTestCA, kTestCert, kTestKey, folly::EventBase::loop(), and folly::gen::move.

1387  {
1388  EventBase eventBase;
1389  auto clientCtx = std::make_shared<SSLContext>();
1390  auto serverCtx = std::make_shared<SSLContext>();
1391  serverCtx->setVerificationOption(
1392  SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1393  serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1394  serverCtx->loadPrivateKey(kTestKey);
1395  serverCtx->loadCertificate(kTestCert);
1396  serverCtx->loadTrustedCertificates(kTestCA);
1397  serverCtx->loadClientCAList(kTestCA);
1398 
1399  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1400  clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1401  clientCtx->loadPrivateKey(kTestKey);
1402  clientCtx->loadCertificate(kTestCert);
1403  clientCtx->loadTrustedCertificates(kTestCA);
1404 
1405  int fds[2];
1406  getfds(fds);
1407 
1408  AsyncSSLSocket::UniquePtr clientSock(
1409  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1410  AsyncSSLSocket::UniquePtr serverSock(
1411  new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1412 
1413  SSLHandshakeClient client(std::move(clientSock), true, true);
1414  SSLHandshakeServer server(std::move(serverSock), true, true);
1415 
1416  eventBase.loop();
1417 
1418  EXPECT_TRUE(client.handshakeVerify_);
1419  EXPECT_TRUE(client.handshakeSuccess_);
1420  EXPECT_FALSE(client.handshakeError_);
1421  EXPECT_LE(0, client.handshakeTime.count());
1422  EXPECT_TRUE(server.handshakeVerify_);
1423  EXPECT_TRUE(server.handshakeSuccess_);
1424  EXPECT_FALSE(server.handshakeError_);
1425  EXPECT_LE(0, server.handshakeTime.count());
1426 
1427  // check certificates
1428  auto clientSsl = std::move(client).moveSocket();
1429  auto serverSsl = std::move(server).moveSocket();
1430 
1431  auto clientPeer = clientSsl->getPeerCertificate();
1432  auto clientSelf = clientSsl->getSelfCertificate();
1433  auto serverPeer = serverSsl->getPeerCertificate();
1434  auto serverSelf = serverSsl->getSelfCertificate();
1435 
1436  EXPECT_NE(clientPeer, nullptr);
1437  EXPECT_NE(clientSelf, nullptr);
1438  EXPECT_NE(serverPeer, nullptr);
1439  EXPECT_NE(serverSelf, nullptr);
1440 
1441  EXPECT_EQ(clientPeer->getIdentity(), serverSelf->getIdentity());
1442  EXPECT_EQ(clientSelf->getIdentity(), serverPeer->getIdentity());
1443 }
#define EXPECT_LE(val1, val2)
Definition: gtest.h:1928
const char * kTestCert
const std::string kTestKey
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * kTestCA
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_NE(val1, val2)
Definition: gtest.h:1926
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncSSLSocketTest  ,
NoClientCertHandshakeError   
)

Test requireClientCert with no client cert

Definition at line 1448 of file AsyncSSLSocketTest.cpp.

References folly::AsyncSSLSocket::closeNow(), EXPECT_FALSE, EXPECT_LE, EXPECT_TRUE, folly::pushmi::operators::from, folly::ScopedEventBaseThread::getEventBase(), getfds(), getFileAsBuf(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, folly::SSLHandshakeBase::handshakeTime, folly::SSLHandshakeBase::handshakeVerify_, INFO, kClientTestKey, kTestCA, kTestCert, kTestKey, folly::EventBase::loop(), folly::gen::move, folly::AsyncPipeWriter::newWriter(), pipe(), ptr, folly::EventBase::runInEventBaseThread(), folly::netops::socket(), testing::TEST(), to(), and uint8_t.

1448  {
1449  EventBase eventBase;
1450  auto clientCtx = std::make_shared<SSLContext>();
1451  auto serverCtx = std::make_shared<SSLContext>();
1452  serverCtx->setVerificationOption(
1453  SSLContext::SSLVerifyPeerEnum::VERIFY_REQ_CLIENT_CERT);
1454  serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1455  serverCtx->loadPrivateKey(kTestKey);
1456  serverCtx->loadCertificate(kTestCert);
1457  serverCtx->loadTrustedCertificates(kTestCA);
1458  serverCtx->loadClientCAList(kTestCA);
1459  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::NO_VERIFY);
1460  clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1461 
1462  int fds[2];
1463  getfds(fds);
1464 
1465  AsyncSSLSocket::UniquePtr clientSock(
1466  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1467  AsyncSSLSocket::UniquePtr serverSock(
1468  new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1469 
1470  SSLHandshakeClient client(std::move(clientSock), false, false);
1471  SSLHandshakeServer server(std::move(serverSock), false, false);
1472 
1473  eventBase.loop();
1474 
1475  EXPECT_FALSE(server.handshakeVerify_);
1476  EXPECT_FALSE(server.handshakeSuccess_);
1477  EXPECT_TRUE(server.handshakeError_);
1478  EXPECT_LE(0, client.handshakeTime.count());
1479  EXPECT_LE(0, server.handshakeTime.count());
1480 }
#define EXPECT_LE(val1, val2)
Definition: gtest.h:1928
const char * kTestCert
const std::string kTestKey
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * kTestCA
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncSSLSocketTest  ,
LoadCertFromMemory   
)

Test OpenSSL 1.1.0's async functionality

Definition at line 1787 of file AsyncSSLSocketTest.cpp.

References EXPECT_EQ, getFileAsBuf(), kTestCA, kTestCert, and kTestKey.

1787  {
1789  auto cert = getFileAsBuf(kTestCert);
1790  auto key = getFileAsBuf(kTestKey);
1791 
1792  ssl::BioUniquePtr certBio(BIO_new(BIO_s_mem()));
1793  BIO_write(certBio.get(), cert.data(), cert.size());
1794  ssl::BioUniquePtr keyBio(BIO_new(BIO_s_mem()));
1795  BIO_write(keyBio.get(), key.data(), key.size());
1796 
1797  // Create SSL structs from buffers to get properties
1798  ssl::X509UniquePtr certStruct(
1799  PEM_read_bio_X509(certBio.get(), nullptr, nullptr, nullptr));
1800  ssl::EvpPkeyUniquePtr keyStruct(
1801  PEM_read_bio_PrivateKey(keyBio.get(), nullptr, nullptr, nullptr));
1802  certBio = nullptr;
1803  keyBio = nullptr;
1804 
1805  auto origCommonName = OpenSSLUtils::getCommonName(certStruct.get());
1806  auto origKeySize = EVP_PKEY_bits(keyStruct.get());
1807  certStruct = nullptr;
1808  keyStruct = nullptr;
1809 
1810  auto ctx = std::make_shared<SSLContext>();
1811  ctx->loadPrivateKeyFromBufferPEM(key);
1812  ctx->loadCertificateFromBufferPEM(cert);
1813  ctx->loadTrustedCertificates(kTestCA);
1814 
1815  ssl::SSLUniquePtr ssl(ctx->createSSL());
1816 
1817  auto newCert = SSL_get_certificate(ssl.get());
1818  auto newKey = SSL_get_privatekey(ssl.get());
1819 
1820  // Get properties from SSL struct
1821  auto newCommonName = OpenSSLUtils::getCommonName(newCert);
1822  auto newKeySize = EVP_PKEY_bits(newKey);
1823 
1824  // Check that the key and cert have the expected properties
1825  EXPECT_EQ(origCommonName, newCommonName);
1826  EXPECT_EQ(origKeySize, newKeySize);
1827 }
std::string getFileAsBuf(const char *fileName)
const char * kTestCert
std::unique_ptr< X509, X509Deleter > X509UniquePtr
std::unique_ptr< BIO, BioDeleter > BioUniquePtr
const std::string kTestKey
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
std::unique_ptr< EVP_PKEY, EvpPkeyDeleter > EvpPkeyUniquePtr
const char * kTestCA
std::unique_ptr< SSL, SSLDeleter > SSLUniquePtr
folly::TEST ( AsyncSSLSocketTest  ,
MinWriteSizeTest   
)

Definition at line 1829 of file AsyncSSLSocketTest.cpp.

References EXPECT_EQ, and folly::netops::socket().

1829  {
1830  EventBase eb;
1831 
1832  // Set up SSL context.
1833  auto sslContext = std::make_shared<SSLContext>();
1834  sslContext->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1835 
1836  // create SSL socket
1837  AsyncSSLSocket::UniquePtr socket(new AsyncSSLSocket(sslContext, &eb));
1838 
1839  EXPECT_EQ(1500, socket->getMinWriteSize());
1840 
1841  socket->setMinWriteSize(0);
1842  EXPECT_EQ(0, socket->getMinWriteSize());
1843  socket->setMinWriteSize(50000);
1844  EXPECT_EQ(50000, socket->getMinWriteSize());
1845 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
folly::TEST ( AsyncSSLSocketTest  ,
UnencryptedTest   
)

Test a full unencrypted codepath

Definition at line 1873 of file AsyncSSLSocketTest.cpp.

References folly::ReadCallback::buffers, c, EXPECT_EQ, EXPECT_NE, getctx(), getfds(), folly::EventBase::loop(), folly::netops::recv(), folly::ReadCallbackBase::setSocket(), and uint8_t.

1873  {
1874  EventBase base;
1875 
1876  auto clientCtx = std::make_shared<folly::SSLContext>();
1877  auto serverCtx = std::make_shared<folly::SSLContext>();
1878  int fds[2];
1879  getfds(fds);
1880  getctx(clientCtx, serverCtx);
1881  auto client =
1882  AsyncSSLSocket::newSocket(clientCtx, &base, fds[0], false, true);
1883  auto server = AsyncSSLSocket::newSocket(serverCtx, &base, fds[1], true, true);
1884 
1885  ReadCallbackTerminator readCallback(&base, nullptr);
1886  server->setReadCB(&readCallback);
1887  readCallback.setSocket(server);
1888 
1889  uint8_t buf[128];
1890  memset(buf, 'a', sizeof(buf));
1891  client->write(nullptr, buf, sizeof(buf));
1892 
1893  // Check that bytes are unencrypted
1894  char c;
1895  EXPECT_EQ(1, recv(fds[1], &c, 1, MSG_PEEK));
1896  EXPECT_EQ('a', c);
1897 
1898  EventBaseAborter eba(&base, 3000);
1899  base.loop();
1900 
1901  EXPECT_EQ(1, readCallback.buffers.size());
1902  EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, client->getSSLState());
1903 
1904  server->setReadCB(&readCallback);
1905 
1906  // Unencrypted
1907  server->sslAccept(nullptr);
1908  client->sslConn(nullptr);
1909 
1910  // Do NOT wait for handshake, writing should be queued and happen after
1911 
1912  client->write(nullptr, buf, sizeof(buf));
1913 
1914  // Check that bytes are *not* unencrypted
1915  char c2;
1916  EXPECT_EQ(1, recv(fds[1], &c2, 1, MSG_PEEK));
1917  EXPECT_NE('a', c2);
1918 
1919  base.loop();
1920 
1921  EXPECT_EQ(2, readCallback.buffers.size());
1922  EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, client->getSSLState());
1923 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
void getfds(int fds[2])
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
#define EXPECT_NE(val1, val2)
Definition: gtest.h:1926
ssize_t recv(NetworkSocket s, void *buf, size_t len, int flags)
Definition: NetOps.cpp:180
char c
folly::TEST ( AsyncSSLSocketTest  ,
ConnectUnencryptedTest   
)

Definition at line 1925 of file AsyncSSLSocketTest.cpp.

References EXPECT_EQ, folly::TestSSLServer::getAddress(), getctx(), folly::EventBase::loop(), and folly::netops::socket().

1925  {
1926  auto clientCtx = std::make_shared<folly::SSLContext>();
1927  auto serverCtx = std::make_shared<folly::SSLContext>();
1928  getctx(clientCtx, serverCtx);
1929 
1930  WriteCallbackBase writeCallback;
1931  ReadCallback readCallback(&writeCallback);
1932  HandshakeCallback handshakeCallback(&readCallback);
1933  SSLServerAcceptCallback acceptCallback(&handshakeCallback);
1934  TestSSLServer server(&acceptCallback);
1935 
1936  EventBase evb;
1937  std::shared_ptr<AsyncSSLSocket> socket =
1938  AsyncSSLSocket::newSocket(clientCtx, &evb, true);
1939  socket->connect(nullptr, server.getAddress(), 0);
1940 
1941  evb.loop();
1942 
1943  EXPECT_EQ(AsyncSSLSocket::STATE_UNENCRYPTED, socket->getSSLState());
1944  socket->sslConn(nullptr);
1945  evb.loop();
1946  EXPECT_EQ(AsyncSSLSocket::STATE_ESTABLISHED, socket->getSSLState());
1947 
1948  // write()
1949  std::array<uint8_t, 128> buf;
1950  memset(buf.data(), 'a', buf.size());
1951  socket->write(nullptr, buf.data(), buf.size());
1952 
1953  socket->close();
1954 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
void getctx(std::shared_ptr< folly::SSLContext > clientCtx, std::shared_ptr< folly::SSLContext > serverCtx)
folly::TEST ( AsyncSSLSocketTest  ,
SSLAcceptRunnerBasic   
)

Test acceptrunner in various situations

Definition at line 1959 of file AsyncSSLSocketTest.cpp.

References EXPECT_FALSE, EXPECT_LE, EXPECT_TRUE, getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, folly::SSLHandshakeBase::handshakeTime, kTestCA, kTestCert, kTestKey, folly::EventBase::loop(), and folly::gen::move.

1959  {
1960  EventBase eventBase;
1961  auto clientCtx = std::make_shared<SSLContext>();
1962  auto serverCtx = std::make_shared<SSLContext>();
1963  serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1964  serverCtx->loadPrivateKey(kTestKey);
1965  serverCtx->loadCertificate(kTestCert);
1966 
1967  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
1968  clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1969  clientCtx->loadTrustedCertificates(kTestCA);
1970 
1971  int fds[2];
1972  getfds(fds);
1973 
1974  AsyncSSLSocket::UniquePtr clientSock(
1975  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
1976  AsyncSSLSocket::UniquePtr serverSock(
1977  new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
1978 
1979  serverCtx->sslAcceptRunner(std::make_unique<SSLAcceptEvbRunner>(&eventBase));
1980 
1981  SSLHandshakeClient client(std::move(clientSock), true, true);
1982  SSLHandshakeServer server(std::move(serverSock), true, true);
1983 
1984  eventBase.loop();
1985 
1986  EXPECT_TRUE(client.handshakeSuccess_);
1987  EXPECT_FALSE(client.handshakeError_);
1988  EXPECT_LE(0, client.handshakeTime.count());
1989  EXPECT_TRUE(server.handshakeSuccess_);
1990  EXPECT_FALSE(server.handshakeError_);
1991  EXPECT_LE(0, server.handshakeTime.count());
1992 }
#define EXPECT_LE(val1, val2)
Definition: gtest.h:1928
const char * kTestCert
const std::string kTestKey
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * kTestCA
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncSSLSocketTest  ,
SSLAcceptRunnerAcceptError   
)

Definition at line 1994 of file AsyncSSLSocketTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, kTestCA, kTestCert, kTestKey, folly::EventBase::loop(), and folly::gen::move.

1994  {
1995  EventBase eventBase;
1996  auto clientCtx = std::make_shared<SSLContext>();
1997  auto serverCtx = std::make_shared<SSLContext>();
1998  serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
1999  serverCtx->loadPrivateKey(kTestKey);
2000  serverCtx->loadCertificate(kTestCert);
2001 
2002  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
2003  clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2004  clientCtx->loadTrustedCertificates(kTestCA);
2005 
2006  int fds[2];
2007  getfds(fds);
2008 
2009  AsyncSSLSocket::UniquePtr clientSock(
2010  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
2011  AsyncSSLSocket::UniquePtr serverSock(
2012  new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
2013 
2014  serverCtx->sslAcceptRunner(
2015  std::make_unique<SSLAcceptErrorRunner>(&eventBase));
2016 
2017  SSLHandshakeClient client(std::move(clientSock), true, true);
2018  SSLHandshakeServer server(std::move(serverSock), true, true);
2019 
2020  eventBase.loop();
2021 
2022  EXPECT_FALSE(client.handshakeSuccess_);
2023  EXPECT_TRUE(client.handshakeError_);
2024  EXPECT_FALSE(server.handshakeSuccess_);
2025  EXPECT_TRUE(server.handshakeError_);
2026 }
const char * kTestCert
const std::string kTestKey
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * kTestCA
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncSSLSocketTest  ,
SSLAcceptRunnerAcceptClose   
)

Definition at line 2028 of file AsyncSSLSocketTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, kTestCA, kTestCert, kTestKey, folly::EventBase::loop(), and folly::gen::move.

2028  {
2029  EventBase eventBase;
2030  auto clientCtx = std::make_shared<SSLContext>();
2031  auto serverCtx = std::make_shared<SSLContext>();
2032  serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2033  serverCtx->loadPrivateKey(kTestKey);
2034  serverCtx->loadCertificate(kTestCert);
2035 
2036  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
2037  clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2038  clientCtx->loadTrustedCertificates(kTestCA);
2039 
2040  int fds[2];
2041  getfds(fds);
2042 
2043  AsyncSSLSocket::UniquePtr clientSock(
2044  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
2045  AsyncSSLSocket::UniquePtr serverSock(
2046  new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
2047 
2048  serverCtx->sslAcceptRunner(
2049  std::make_unique<SSLAcceptCloseRunner>(&eventBase, serverSock.get()));
2050 
2051  SSLHandshakeClient client(std::move(clientSock), true, true);
2052  SSLHandshakeServer server(std::move(serverSock), true, true);
2053 
2054  eventBase.loop();
2055 
2056  EXPECT_FALSE(client.handshakeSuccess_);
2057  EXPECT_TRUE(client.handshakeError_);
2058  EXPECT_FALSE(server.handshakeSuccess_);
2059  EXPECT_TRUE(server.handshakeError_);
2060 }
const char * kTestCert
const std::string kTestKey
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * kTestCA
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncSSLSocketTest  ,
SSLAcceptRunnerAcceptDestroy   
)

Definition at line 2062 of file AsyncSSLSocketTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, getfds(), folly::SSLHandshakeBase::handshakeError_, folly::SSLHandshakeBase::handshakeSuccess_, kTestCA, kTestCert, kTestKey, folly::EventBase::loop(), and folly::gen::move.

2062  {
2063  EventBase eventBase;
2064  auto clientCtx = std::make_shared<SSLContext>();
2065  auto serverCtx = std::make_shared<SSLContext>();
2066  serverCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2067  serverCtx->loadPrivateKey(kTestKey);
2068  serverCtx->loadCertificate(kTestCert);
2069 
2070  clientCtx->setVerificationOption(SSLContext::SSLVerifyPeerEnum::VERIFY);
2071  clientCtx->ciphers("ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH");
2072  clientCtx->loadTrustedCertificates(kTestCA);
2073 
2074  int fds[2];
2075  getfds(fds);
2076 
2077  AsyncSSLSocket::UniquePtr clientSock(
2078  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], false));
2079  AsyncSSLSocket::UniquePtr serverSock(
2080  new AsyncSSLSocket(serverCtx, &eventBase, fds[1], true));
2081 
2082  SSLHandshakeClient client(std::move(clientSock), true, true);
2083  SSLHandshakeServer server(std::move(serverSock), true, true);
2084 
2085  serverCtx->sslAcceptRunner(
2086  std::make_unique<SSLAcceptDestroyRunner>(&eventBase, &server));
2087 
2088  eventBase.loop();
2089 
2090  EXPECT_FALSE(client.handshakeSuccess_);
2091  EXPECT_TRUE(client.handshakeError_);
2092  EXPECT_FALSE(server.handshakeSuccess_);
2093  EXPECT_TRUE(server.handshakeError_);
2094 }
const char * kTestCert
const std::string kTestKey
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
const char * kTestCA
void getfds(int fds[2])
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST ( AsyncSSLSocketTest  ,
ConnResetErrorString   
)

Definition at line 2096 of file AsyncSSLSocketTest.cpp.

References folly::HandshakeCallback::errorString_, EXPECT_NE, folly::TestSSLServer::getAddress(), folly::netops::socket(), uint8_t, and folly::HandshakeCallback::waitForHandshake().

2096  {
2097  // Start listening on a local port
2098  WriteCallbackBase writeCallback;
2099  WriteErrorCallback readCallback(&writeCallback);
2100  HandshakeCallback handshakeCallback(
2101  &readCallback, HandshakeCallback::EXPECT_ERROR);
2102  SSLServerAcceptCallback acceptCallback(&handshakeCallback);
2103  TestSSLServer server(&acceptCallback);
2104 
2105  auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
2106  socket->open();
2107  uint8_t buf[3] = {0x16, 0x03, 0x01};
2108  socket->write(buf, sizeof(buf));
2109  socket->closeWithReset();
2110 
2111  handshakeCallback.waitForHandshake();
2112  EXPECT_NE(
2113  handshakeCallback.errorString_.find("Network error"), std::string::npos);
2114  EXPECT_NE(handshakeCallback.errorString_.find("104"), std::string::npos);
2115 }
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
#define EXPECT_NE(val1, val2)
Definition: gtest.h:1926
folly::TEST ( AsyncSSLSocketTest  ,
ConnEOFErrorString   
)

Definition at line 2117 of file AsyncSSLSocketTest.cpp.

References folly::HandshakeCallback::errorString_, EXPECT_NE, folly::TestSSLServer::getAddress(), folly::netops::socket(), uint8_t, and folly::HandshakeCallback::waitForHandshake().

2117  {
2118  // Start listening on a local port
2119  WriteCallbackBase writeCallback;
2120  WriteErrorCallback readCallback(&writeCallback);
2121  HandshakeCallback handshakeCallback(
2122  &readCallback, HandshakeCallback::EXPECT_ERROR);
2123  SSLServerAcceptCallback acceptCallback(&handshakeCallback);
2124  TestSSLServer server(&acceptCallback);
2125 
2126  auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
2127  socket->open();
2128  uint8_t buf[3] = {0x16, 0x03, 0x01};
2129  socket->write(buf, sizeof(buf));
2130  socket->close();
2131 
2132  handshakeCallback.waitForHandshake();
2133 #if FOLLY_OPENSSL_IS_110
2134  EXPECT_NE(
2135  handshakeCallback.errorString_.find("Network error"), std::string::npos);
2136 #else
2137  EXPECT_NE(
2138  handshakeCallback.errorString_.find("Connection EOF"), std::string::npos);
2139 #endif
2140 }
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
#define EXPECT_NE(val1, val2)
Definition: gtest.h:1926
folly::TEST ( AsyncSSLSocketTest  ,
ConnOpenSSLErrorString   
)

Definition at line 2142 of file AsyncSSLSocketTest.cpp.

References folly::HandshakeCallback::errorString_, EXPECT_NE, folly::TestSSLServer::getAddress(), folly::netops::socket(), uint8_t, and folly::HandshakeCallback::waitForHandshake().

2142  {
2143  // Start listening on a local port
2144  WriteCallbackBase writeCallback;
2145  WriteErrorCallback readCallback(&writeCallback);
2146  HandshakeCallback handshakeCallback(
2147  &readCallback, HandshakeCallback::EXPECT_ERROR);
2148  SSLServerAcceptCallback acceptCallback(&handshakeCallback);
2149  TestSSLServer server(&acceptCallback);
2150 
2151  auto socket = std::make_shared<BlockingSocket>(server.getAddress(), nullptr);
2152  socket->open();
2153  uint8_t buf[256] = {0x16, 0x03};
2154  memset(buf + 2, 'a', sizeof(buf) - 2);
2155  socket->write(buf, sizeof(buf));
2156  socket->close();
2157 
2158  handshakeCallback.waitForHandshake();
2159  EXPECT_NE(
2160  handshakeCallback.errorString_.find("SSL routines"), std::string::npos);
2161 #if defined(OPENSSL_IS_BORINGSSL)
2162  EXPECT_NE(
2163  handshakeCallback.errorString_.find("ENCRYPTED_LENGTH_TOO_LONG"),
2164  std::string::npos);
2165 #elif FOLLY_OPENSSL_IS_110
2166  EXPECT_NE(
2167  handshakeCallback.errorString_.find("packet length too long"),
2168  std::string::npos);
2169 #else
2170  EXPECT_NE(
2171  handshakeCallback.errorString_.find("unknown protocol"),
2172  std::string::npos);
2173 #endif
2174 }
NetworkSocket socket(int af, int type, int protocol)
Definition: NetOps.cpp:412
#define EXPECT_NE(val1, val2)
Definition: gtest.h:1926
folly::TEST ( AsyncSSLSocketTest  ,
TestSSLCipherCodeToNameMap   
)
folly::TEST_F ( SSLOptionsTest  ,
TestSetCommonCipherList   
)

Definition at line 29 of file SSLOptionsTest.cpp.

References ASSERT_EQ, ASSERT_STREQ, cipher, folly::SSLContext::createSSL(), and i.

29  {
30  SSLContext ctx;
31  ssl::setCipherSuites<ssl::SSLCommonOptions>(ctx);
32 
33  int i = 0;
34  ssl::SSLUniquePtr ssl(ctx.createSSL());
35  for (auto& cipher : ssl::SSLCommonOptions::kCipherList) {
36  ASSERT_STREQ(cipher, SSL_get_cipher_list(ssl.get(), i++));
37  }
38  ASSERT_EQ(nullptr, SSL_get_cipher_list(ssl.get(), i));
39 }
#define ASSERT_STREQ(s1, s2)
Definition: gtest.h:2004
#define ASSERT_EQ(val1, val2)
Definition: gtest.h:1956
CipherSuite cipher
std::unique_ptr< SSL, SSLDeleter > SSLUniquePtr
folly::TEST_F ( SSLContextTest  ,
TestSetCipherString   
)

Definition at line 42 of file SSLContextTest.cpp.

42  {
43  ctx.ciphers("AES128-SHA:ECDHE-RSA-AES256-SHA384");
44  verifySSLCipherList({"AES128-SHA", "ECDHE-RSA-AES256-SHA384"});
45 }
folly::TEST_F ( SSLContextTest  ,
TestSetCipherList   
)

Definition at line 47 of file SSLContextTest.cpp.

47  {
48  const vector<string> ciphers = {"ECDHE-RSA-AES128-SHA", "AES256-SHA"};
49  ctx.setCipherList(ciphers);
50  verifySSLCipherList(ciphers);
51 }
folly::TEST_F ( SSLContextTest  ,
TestLoadCertKey   
)

Definition at line 53 of file SSLContextTest.cpp.

References EXPECT_FALSE, EXPECT_THROW, EXPECT_TRUE, folly::SSLContext::isCertKeyPairValid(), folly::SSLContext::loadCertificate(), folly::SSLContext::loadCertificateFromBufferPEM(), folly::SSLContext::loadCertKeyPairFromBufferPEM(), folly::SSLContext::loadCertKeyPairFromFiles(), folly::SSLContext::loadPrivateKey(), folly::SSLContext::loadPrivateKeyFromBufferPEM(), readFile(), SCOPED_TRACE, and string.

53  {
54  std::string certData, keyData, anotherKeyData;
55  const char* certPath = "folly/io/async/test/certs/tests-cert.pem";
56  const char* keyPath = "folly/io/async/test/certs/tests-key.pem";
57  const char* anotherKeyPath = "folly/io/async/test/certs/client_key.pem";
58  folly::readFile(certPath, certData);
59  folly::readFile(keyPath, keyData);
60  folly::readFile(anotherKeyPath, anotherKeyData);
61 
62  {
63  SCOPED_TRACE("Valid cert/key pair from buffer");
64  SSLContext tmpCtx;
65  tmpCtx.loadCertificateFromBufferPEM(certData);
66  tmpCtx.loadPrivateKeyFromBufferPEM(keyData);
67  EXPECT_TRUE(tmpCtx.isCertKeyPairValid());
68  }
69 
70  {
71  SCOPED_TRACE("Valid cert/key pair from files");
72  SSLContext tmpCtx;
73  tmpCtx.loadCertificate(certPath);
74  tmpCtx.loadPrivateKey(keyPath);
75  EXPECT_TRUE(tmpCtx.isCertKeyPairValid());
76  }
77 
78  {
79  SCOPED_TRACE("Invalid cert/key pair from file. Load cert first");
80  SSLContext tmpCtx;
81  tmpCtx.loadCertificate(certPath);
82  EXPECT_THROW(tmpCtx.loadPrivateKey(anotherKeyPath), std::runtime_error);
83  }
84 
85  {
86  SCOPED_TRACE("Invalid cert/key pair from file. Load key first");
87  SSLContext tmpCtx;
88  tmpCtx.loadPrivateKey(anotherKeyPath);
89  tmpCtx.loadCertificate(certPath);
90  EXPECT_FALSE(tmpCtx.isCertKeyPairValid());
91  }
92 
93  {
94  SCOPED_TRACE("Invalid key/cert pair from buf. Load cert first");
95  SSLContext tmpCtx;
96  tmpCtx.loadCertificateFromBufferPEM(certData);
98  tmpCtx.loadPrivateKeyFromBufferPEM(anotherKeyData), std::runtime_error);
99  }
100 
101  {
102  SCOPED_TRACE("Invalid key/cert pair from buf. Load key first");
103  SSLContext tmpCtx;
104  tmpCtx.loadPrivateKeyFromBufferPEM(anotherKeyData);
105  tmpCtx.loadCertificateFromBufferPEM(certData);
106  EXPECT_FALSE(tmpCtx.isCertKeyPairValid());
107  }
108 
109  {
110  SCOPED_TRACE(
111  "loadCertKeyPairFromBufferPEM() must throw when cert/key mismatch");
112  SSLContext tmpCtx;
113  EXPECT_THROW(
114  tmpCtx.loadCertKeyPairFromBufferPEM(certData, anotherKeyData),
115  std::runtime_error);
116  }
117 
118  {
119  SCOPED_TRACE(
120  "loadCertKeyPairFromBufferPEM() must succeed when cert/key match");
121  SSLContext tmpCtx;
122  tmpCtx.loadCertKeyPairFromBufferPEM(certData, keyData);
123  }
124 
125  {
126  SCOPED_TRACE(
127  "loadCertKeyPairFromFiles() must throw when cert/key mismatch");
128  SSLContext tmpCtx;
129  EXPECT_THROW(
130  tmpCtx.loadCertKeyPairFromFiles(certPath, anotherKeyPath),
131  std::runtime_error);
132  }
133 
134  {
135  SCOPED_TRACE("loadCertKeyPairFromFiles() must succeed when cert/key match");
136  SSLContext tmpCtx;
137  tmpCtx.loadCertKeyPairFromFiles(certPath, keyPath);
138  }
139 }
bool readFile(int fd, Container &out, size_t num_bytes=std::numeric_limits< size_t >::max())
Definition: FileUtil.h:125
#define EXPECT_THROW(statement, expected_exception)
Definition: gtest.h:1843
#define SCOPED_TRACE(message)
Definition: gtest.h:2115
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
const char * string
Definition: Conv.cpp:212
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST_F ( SSLSessionTest  ,
BasicTest   
)
  1. Client sends TLSEXT_HOSTNAME in client hello.
  2. Server found a match SSL_CTX and use this SSL_CTX to continue the SSL handshake.
  3. Server sends back TLSEXT_HOSTNAME in server hello.

Definition at line 84 of file SSLSessionTest.cpp.

References ASSERT_NE, ASSERT_TRUE, getfds(), folly::ssl::SSLSession::getRawSSLSessionDangerous(), folly::SSLHandshakeBase::handshakeSuccess_, and folly::gen::move.

84  {
85  std::unique_ptr<SSLSession> sess;
86 
87  {
88  int fds[2];
89  getfds(fds);
90  AsyncSSLSocket::UniquePtr clientSock(
91  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
92  auto clientPtr = clientSock.get();
93  AsyncSSLSocket::UniquePtr serverSock(
94  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
95  SSLHandshakeClient client(std::move(clientSock), false, false);
96  SSLHandshakeServerParseClientHello server(
97  std::move(serverSock), false, false);
98 
99  eventBase.loop();
100  ASSERT_TRUE(client.handshakeSuccess_);
101 
102  sess = std::make_unique<SSLSession>(clientPtr->getSSLSession());
103  ASSERT_NE(sess.get(), nullptr);
104  }
105 
106  {
107  int fds[2];
108  getfds(fds);
109  AsyncSSLSocket::UniquePtr clientSock(
110  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
111  auto clientPtr = clientSock.get();
112  clientSock->setSSLSession(sess->getRawSSLSessionDangerous(), true);
113  AsyncSSLSocket::UniquePtr serverSock(
114  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
115  SSLHandshakeClient client(std::move(clientSock), false, false);
116  SSLHandshakeServerParseClientHello server(
117  std::move(serverSock), false, false);
118 
119  eventBase.loop();
120  ASSERT_TRUE(client.handshakeSuccess_);
121  ASSERT_TRUE(clientPtr->getSSLSessionReused());
122  }
123 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
SSL_SESSION * getRawSSLSessionDangerous()
Definition: SSLSession.h:56
void getfds(int fds[2])
#define ASSERT_NE(val1, val2)
Definition: gtest.h:1960
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST_F ( AsyncSSLSocketWriteTest  ,
write_coalescing1   
)

Definition at line 120 of file AsyncSSLSocketWriteTest.cpp.

References testing::_, EXPECT_CALL, EXPECT_EQ, testing::Invoke(), m, sock_, and uint32_t.

120  {
121  int n = 3;
122  auto vec = makeVec({3, 3, 3});
123  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 9))
124  .WillOnce(Invoke([this](SSL*, const void* buf, int m) {
125  verifyVec(buf, m, 0);
126  return 9;
127  }));
128  uint32_t countWritten = 0;
129  uint32_t partialWritten = 0;
130  sock_->testPerformWrite(
131  vec.get(), n, WriteFlags::NONE, &countWritten, &partialWritten);
132  EXPECT_EQ(countWritten, n);
133  EXPECT_EQ(partialWritten, 0);
134 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
static map< string, int > m
AsyncSocket::UniquePtr sock_
Definition: Traits.h:588
#define EXPECT_CALL(obj, call)
const internal::AnythingMatcher _
folly::TEST_F ( SSLSessionTest  ,
SerializeDeserializeTest   
)

Definition at line 124 of file SSLSessionTest.cpp.

References ASSERT_NE, ASSERT_TRUE, getfds(), folly::ssl::SSLSession::getRawSSLSessionDangerous(), folly::SSLHandshakeBase::handshakeSuccess_, folly::gen::move, folly::ssl::SSLSession::serialize(), and string.

124  {
125  std::string sessiondata;
126 
127  {
128  int fds[2];
129  getfds(fds);
130  AsyncSSLSocket::UniquePtr clientSock(
131  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
132  auto clientPtr = clientSock.get();
133  AsyncSSLSocket::UniquePtr serverSock(
134  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
135  SSLHandshakeClient client(std::move(clientSock), false, false);
136  SSLHandshakeServerParseClientHello server(
137  std::move(serverSock), false, false);
138 
139  eventBase.loop();
140  ASSERT_TRUE(client.handshakeSuccess_);
141 
142  std::unique_ptr<SSLSession> sess =
143  std::make_unique<SSLSession>(clientPtr->getSSLSession());
144  sessiondata = sess->serialize();
145  ASSERT_TRUE(!sessiondata.empty());
146  }
147 
148  {
149  int fds[2];
150  getfds(fds);
151  AsyncSSLSocket::UniquePtr clientSock(
152  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
153  auto clientPtr = clientSock.get();
154  std::unique_ptr<SSLSession> sess =
155  std::make_unique<SSLSession>(sessiondata);
156  ASSERT_NE(sess.get(), nullptr);
157  clientSock->setSSLSession(sess->getRawSSLSessionDangerous(), true);
158  AsyncSSLSocket::UniquePtr serverSock(
159  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
160  SSLHandshakeClient client(std::move(clientSock), false, false);
161  SSLHandshakeServerParseClientHello server(
162  std::move(serverSock), false, false);
163 
164  eventBase.loop();
165  ASSERT_TRUE(client.handshakeSuccess_);
166  ASSERT_TRUE(clientPtr->getSSLSessionReused());
167  }
168 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
SSL_SESSION * getRawSSLSessionDangerous()
Definition: SSLSession.h:56
void getfds(int fds[2])
std::string serialize() const
Definition: SSLSession.h:38
const char * string
Definition: Conv.cpp:212
#define ASSERT_NE(val1, val2)
Definition: gtest.h:1960
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST_F ( AsyncSSLSocketWriteTest  ,
write_coalescing2   
)

Definition at line 137 of file AsyncSSLSocketWriteTest.cpp.

References testing::_, EXPECT_CALL, EXPECT_EQ, testing::Invoke(), m, sock_, and uint32_t.

137  {
138  int n = 3;
139  auto vec = makeVec({1500, 3, 3});
140  int pos = 0;
141  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 1500))
142  .WillOnce(Invoke([this, &pos](SSL*, const void* buf, int m) {
143  verifyVec(buf, m, pos);
144  pos += m;
145  return m;
146  }));
147  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 6))
148  .WillOnce(Invoke([this, &pos](SSL*, const void* buf, int m) {
149  verifyVec(buf, m, pos);
150  pos += m;
151  return m;
152  }));
153  uint32_t countWritten = 0;
154  uint32_t partialWritten = 0;
155  sock_->testPerformWrite(
156  vec.get(), n, WriteFlags::NONE, &countWritten, &partialWritten);
157  EXPECT_EQ(countWritten, n);
158  EXPECT_EQ(partialWritten, 0);
159 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
static map< string, int > m
AsyncSocket::UniquePtr sock_
Definition: Traits.h:588
#define EXPECT_CALL(obj, call)
const internal::AnythingMatcher _
folly::TEST_F ( AsyncSSLSocketWriteTest  ,
write_coalescing3   
)

Definition at line 162 of file AsyncSSLSocketWriteTest.cpp.

References testing::_, EXPECT_CALL, EXPECT_EQ, testing::Invoke(), m, sock_, and uint32_t.

162  {
163  int n = 3;
164  auto vec = makeVec({1000, 1000, 1000});
165  int pos = 0;
166  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 1500))
167  .Times(2)
168  .WillRepeatedly(Invoke([this, &pos](SSL*, const void* buf, int m) {
169  verifyVec(buf, m, pos);
170  pos += m;
171  return m;
172  }));
173  uint32_t countWritten = 0;
174  uint32_t partialWritten = 0;
175  sock_->testPerformWrite(
176  vec.get(), n, WriteFlags::NONE, &countWritten, &partialWritten);
177  EXPECT_EQ(countWritten, n);
178  EXPECT_EQ(partialWritten, 0);
179 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
static map< string, int > m
AsyncSocket::UniquePtr sock_
Definition: Traits.h:588
#define EXPECT_CALL(obj, call)
const internal::AnythingMatcher _
folly::TEST_F ( AtomicFetchSetTest  ,
Basic   
)

Definition at line 164 of file AtomicUtilTest.cpp.

164  {
165  atomic_fetch_set_basic<std::uint16_t>();
166  atomic_fetch_set_basic<std::uint32_t>();
167  atomic_fetch_set_basic<std::uint64_t>();
168  atomic_fetch_set_basic<std::uint8_t>();
169 }
folly::TEST_F ( SSLSessionTest  ,
GetSessionID   
)

Definition at line 170 of file SSLSessionTest.cpp.

References ASSERT_GE, ASSERT_NE, ASSERT_TRUE, getfds(), folly::ssl::SSLSession::getSessionID(), folly::SSLHandshakeBase::handshakeSuccess_, and folly::gen::move.

170  {
171  int fds[2];
172  getfds(fds);
173  AsyncSSLSocket::UniquePtr clientSock(
174  new AsyncSSLSocket(clientCtx, &eventBase, fds[0], serverName));
175  auto clientPtr = clientSock.get();
176  AsyncSSLSocket::UniquePtr serverSock(
177  new AsyncSSLSocket(dfServerCtx, &eventBase, fds[1], true));
178  SSLHandshakeClient client(std::move(clientSock), false, false);
179  SSLHandshakeServerParseClientHello server(
180  std::move(serverSock), false, false);
181 
182  eventBase.loop();
183  ASSERT_TRUE(client.handshakeSuccess_);
184 
185  std::unique_ptr<SSLSession> sess =
186  std::make_unique<SSLSession>(clientPtr->getSSLSession());
187  ASSERT_NE(sess, nullptr);
188  auto sessID = sess->getSessionID();
189  ASSERT_GE(sessID.length(), 0);
190 }
#define ASSERT_GE(val1, val2)
Definition: gtest.h:1972
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::string getSessionID() const
Definition: SSLSession.h:43
void getfds(int fds[2])
#define ASSERT_NE(val1, val2)
Definition: gtest.h:1960
#define ASSERT_TRUE(condition)
Definition: gtest.h:1865
folly::TEST_F ( AtomicFetchResetTest  ,
Basic   
)

Definition at line 171 of file AtomicUtilTest.cpp.

171  {
172  atomic_fetch_reset_basic<std::uint16_t>();
173  atomic_fetch_reset_basic<std::uint32_t>();
174  atomic_fetch_reset_basic<std::uint64_t>();
175  atomic_fetch_reset_basic<std::uint8_t>();
176 }
folly::TEST_F ( AtomicFetchSetTest  ,
EnsureFetchOrUsed   
)

Definition at line 178 of file AtomicUtilTest.cpp.

178  {
179  atomic_fetch_set_non_std_atomic<std::uint8_t>();
180  atomic_fetch_set_non_std_atomic<std::uint16_t>();
181  atomic_fetch_set_non_std_atomic<std::uint32_t>();
182  atomic_fetch_set_non_std_atomic<std::uint64_t>();
183 }
folly::TEST_F ( AsyncSSLSocketWriteTest  ,
write_coalescing4   
)

Definition at line 182 of file AsyncSSLSocketWriteTest.cpp.

References testing::_, EXPECT_CALL, EXPECT_EQ, testing::Invoke(), m, sock_, and uint32_t.

182  {
183  int n = 5;
184  auto vec = makeVec({300, 300, 300, 300, 300});
185  int pos = 0;
186  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 1500))
187  .WillOnce(Invoke([this, &pos](SSL*, const void* buf, int m) {
188  verifyVec(buf, m, pos);
189  pos += 1000;
190  return 1000; /* 500 bytes "pending" */
191  }));
192  uint32_t countWritten = 0;
193  uint32_t partialWritten = 0;
194  sock_->testPerformWrite(
195  vec.get(), n, WriteFlags::NONE, &countWritten, &partialWritten);
196  EXPECT_EQ(countWritten, 3);
197  EXPECT_EQ(partialWritten, 100);
198  consumeVec(vec.get(), countWritten, partialWritten);
199  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 500))
200  .WillOnce(Invoke([this, &pos](SSL*, const void* buf, int m) {
201  verifyVec(buf, m, pos);
202  pos += m;
203  return 500;
204  }));
205  sock_->testPerformWrite(
206  vec.get() + countWritten,
207  n - countWritten,
208  WriteFlags::NONE,
209  &countWritten,
210  &partialWritten);
211  EXPECT_EQ(countWritten, 2);
212  EXPECT_EQ(partialWritten, 0);
213 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
static map< string, int > m
AsyncSocket::UniquePtr sock_
Definition: Traits.h:588
#define EXPECT_CALL(obj, call)
const internal::AnythingMatcher _
folly::TEST_F ( AtomicFetchResetTest  ,
EnsureFetchAndUsed   
)

Definition at line 185 of file AtomicUtilTest.cpp.

185  {
186  atomic_fetch_reset_non_std_atomic<std::uint8_t>();
187  atomic_fetch_reset_non_std_atomic<std::uint16_t>();
188  atomic_fetch_reset_non_std_atomic<std::uint32_t>();
189  atomic_fetch_reset_non_std_atomic<std::uint64_t>();
190 }
folly::TEST_F ( AtomicFetchSetTest  ,
FetchSetDefault   
)

Definition at line 192 of file AtomicUtilTest.cpp.

References folly::detail::atomic_fetch_set_default().

192  {
193  auto fetch_set = [](auto&&... args) {
194  return detail::atomic_fetch_set_default(args..., std::memory_order_seq_cst);
195  };
196 
197  atomic_fetch_set_basic<std::uint16_t>(fetch_set);
198  atomic_fetch_set_basic<std::uint32_t>(fetch_set);
199  atomic_fetch_set_basic<std::uint64_t>(fetch_set);
200  atomic_fetch_set_basic<std::uint8_t>(fetch_set);
201 
202  atomic_fetch_set_non_std_atomic<std::uint8_t>(fetch_set);
203  atomic_fetch_set_non_std_atomic<std::uint16_t>(fetch_set);
204  atomic_fetch_set_non_std_atomic<std::uint32_t>(fetch_set);
205  atomic_fetch_set_non_std_atomic<std::uint64_t>(fetch_set);
206 }
bool atomic_fetch_set_default(Atomic &atomic, std::size_t bit, std::memory_order order)
folly::TEST_F ( AtomicFetchSetTest  ,
FetchResetDefault   
)

Definition at line 208 of file AtomicUtilTest.cpp.

References folly::detail::atomic_fetch_reset_default().

208  {
209  auto fetch_reset = [](auto&&... args) {
211  args..., std::memory_order_seq_cst);
212  };
213 
214  atomic_fetch_reset_basic<std::uint16_t>(fetch_reset);
215  atomic_fetch_reset_basic<std::uint32_t>(fetch_reset);
216  atomic_fetch_reset_basic<std::uint64_t>(fetch_reset);
217  atomic_fetch_reset_basic<std::uint8_t>(fetch_reset);
218 
219  atomic_fetch_reset_non_std_atomic<std::uint8_t>(fetch_reset);
220  atomic_fetch_reset_non_std_atomic<std::uint16_t>(fetch_reset);
221  atomic_fetch_reset_non_std_atomic<std::uint32_t>(fetch_reset);
222  atomic_fetch_reset_non_std_atomic<std::uint64_t>(fetch_reset);
223 }
bool atomic_fetch_reset_default(Atomic &atomic, std::size_t bit, std::memory_order order)
folly::TEST_F ( AsyncSSLSocketWriteTest  ,
write_coalescing5   
)

Definition at line 216 of file AsyncSSLSocketWriteTest.cpp.

References testing::_, EXPECT_CALL, EXPECT_EQ, testing::Invoke(), m, sock_, and uint32_t.

216  {
217  int n = 3;
218  auto vec = makeVec({1000, 500, 500});
219  int pos = 0;
220  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 1500))
221  .WillOnce(Invoke([this, &pos](SSL*, const void* buf, int m) {
222  verifyVec(buf, m, pos);
223  pos += m;
224  return m;
225  }));
226  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 500))
227  .WillOnce(Invoke([this, &pos](SSL*, const void* buf, int m) {
228  verifyVec(buf, m, pos);
229  pos += m;
230  return m;
231  }));
232  uint32_t countWritten = 0;
233  uint32_t partialWritten = 0;
234  sock_->testPerformWrite(
235  vec.get(), n, WriteFlags::NONE, &countWritten, &partialWritten);
236  EXPECT_EQ(countWritten, 3);
237  EXPECT_EQ(partialWritten, 0);
238 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
static map< string, int > m
AsyncSocket::UniquePtr sock_
Definition: Traits.h:588
#define EXPECT_CALL(obj, call)
const internal::AnythingMatcher _
folly::TEST_F ( AtomicFetchSetTest  ,
FetchSetX86   
)

Definition at line 225 of file AtomicUtilTest.cpp.

References folly::detail::atomic_fetch_set_x86(), and kIsArchAmd64.

225  {
226  if (folly::kIsArchAmd64) {
227  auto fetch_set = [](auto&&... args) {
228  return detail::atomic_fetch_set_x86(args..., std::memory_order_seq_cst);
229  };
230 
231  atomic_fetch_set_basic<std::uint16_t>(fetch_set);
232  atomic_fetch_set_basic<std::uint32_t>(fetch_set);
233  atomic_fetch_set_basic<std::uint64_t>(fetch_set);
234  atomic_fetch_set_basic<std::uint8_t>(fetch_set);
235 
236  atomic_fetch_set_non_std_atomic<std::uint8_t>(fetch_set);
237  atomic_fetch_set_non_std_atomic<std::uint16_t>(fetch_set);
238  atomic_fetch_set_non_std_atomic<std::uint32_t>(fetch_set);
239  atomic_fetch_set_non_std_atomic<std::uint64_t>(fetch_set);
240  }
241 }
constexpr bool kIsArchAmd64
Definition: Portability.h:102
bool atomic_fetch_set_x86(Atomic &, std::size_t, std::memory_order) noexcept
folly::TEST_F ( AsyncSSLSocketWriteTest  ,
write_coalescing6   
)

Definition at line 241 of file AsyncSSLSocketWriteTest.cpp.

References testing::_, EXPECT_CALL, EXPECT_EQ, testing::Invoke(), m, sock_, and uint32_t.

241  {
242  int n = 2;
243  auto vec = makeVec({1000, 500});
244  int pos = 0;
245  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 1500))
246  .WillOnce(Invoke([this, &pos](SSL*, const void* buf, int m) {
247  verifyVec(buf, m, pos);
248  pos += 700;
249  return 700;
250  }));
251  uint32_t countWritten = 0;
252  uint32_t partialWritten = 0;
253  sock_->testPerformWrite(
254  vec.get(), n, WriteFlags::NONE, &countWritten, &partialWritten);
255  EXPECT_EQ(countWritten, 0);
256  EXPECT_EQ(partialWritten, 700);
257  consumeVec(vec.get(), countWritten, partialWritten);
258  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 800))
259  .WillOnce(Invoke([this, &pos](SSL*, const void* buf, int m) {
260  verifyVec(buf, m, pos);
261  pos += m;
262  return m;
263  }));
264  sock_->testPerformWrite(
265  vec.get() + countWritten,
266  n - countWritten,
267  WriteFlags::NONE,
268  &countWritten,
269  &partialWritten);
270  EXPECT_EQ(countWritten, 2);
271  EXPECT_EQ(partialWritten, 0);
272 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
static map< string, int > m
AsyncSocket::UniquePtr sock_
Definition: Traits.h:588
#define EXPECT_CALL(obj, call)
const internal::AnythingMatcher _
folly::TEST_F ( AtomicFetchResetTest  ,
FetchResetX86   
)

Definition at line 243 of file AtomicUtilTest.cpp.

References folly::detail::atomic_fetch_reset_x86(), and kIsArchAmd64.

243  {
244  if (folly::kIsArchAmd64) {
245  auto fetch_reset = [](auto&&... args) {
246  return detail::atomic_fetch_reset_x86(args..., std::memory_order_seq_cst);
247  };
248 
249  atomic_fetch_reset_basic<std::uint16_t>(fetch_reset);
250  atomic_fetch_reset_basic<std::uint32_t>(fetch_reset);
251  atomic_fetch_reset_basic<std::uint64_t>(fetch_reset);
252  atomic_fetch_reset_basic<std::uint8_t>(fetch_reset);
253 
254  atomic_fetch_reset_non_std_atomic<std::uint8_t>(fetch_reset);
255  atomic_fetch_reset_non_std_atomic<std::uint16_t>(fetch_reset);
256  atomic_fetch_reset_non_std_atomic<std::uint32_t>(fetch_reset);
257  atomic_fetch_reset_non_std_atomic<std::uint64_t>(fetch_reset);
258  }
259 }
bool atomic_fetch_reset_x86(Atomic &, std::size_t, std::memory_order) noexcept
constexpr bool kIsArchAmd64
Definition: Portability.h:102
folly::TEST_F ( AsyncSSLSocketWriteTest  ,
write_with_eor1   
)

Definition at line 275 of file AsyncSSLSocketWriteTest.cpp.

References testing::_, EXPECT_CALL, EXPECT_EQ, EXPECT_FALSE, EXPECT_TRUE, testing::Invoke(), m, testing::Return(), sock_, and uint32_t.

275  {
276  int n = 3;
277  auto vec = makeVec({1500, 3, 3});
278  int pos = 0;
279  const size_t initAppBytesWritten = 500;
280  const size_t appEor = initAppBytesWritten + 1506;
281 
282  sock_->setAppBytesWritten(initAppBytesWritten);
283  EXPECT_FALSE(sock_->isEorTrackingEnabled());
284  sock_->setEorTracking(true);
285  EXPECT_TRUE(sock_->isEorTrackingEnabled());
286 
287  EXPECT_CALL(*(sock_.get()), getRawBytesWritten())
288  // rawBytesWritten after writting initAppBytesWritten + 1500
289  // + some random SSL overhead
290  .WillOnce(Return(3600u))
291  // rawBytesWritten after writting last 6 bytes
292  // + some random SSL overhead
293  .WillOnce(Return(3728u));
294  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 1500))
295  .WillOnce(Invoke([=, &pos](SSL*, const void* buf, int m) {
296  // the first 1500 does not have the EOR byte
297  sock_->checkEor(0, 0);
298  verifyVec(buf, m, pos);
299  pos += m;
300  return m;
301  }));
302  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 6))
303  .WillOnce(Invoke([=, &pos](SSL*, const void* buf, int m) {
304  sock_->checkEor(appEor, 3600 + m);
305  verifyVec(buf, m, pos);
306  pos += m;
307  return m;
308  }));
309 
310  uint32_t countWritten = 0;
311  uint32_t partialWritten = 0;
312  sock_->testPerformWrite(
313  vec.get(), n, WriteFlags::EOR, &countWritten, &partialWritten);
314  EXPECT_EQ(countWritten, n);
315  EXPECT_EQ(partialWritten, 0);
316  sock_->checkEor(0, 0);
317 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
static map< string, int > m
AsyncSocket::UniquePtr sock_
Definition: Traits.h:588
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_CALL(obj, call)
const internal::AnythingMatcher _
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
internal::ReturnAction< R > Return(R value)
folly::TEST_F ( AsyncSSLSocketWriteTest  ,
write_with_eor2   
)

Definition at line 321 of file AsyncSSLSocketWriteTest.cpp.

References testing::_, EXPECT_CALL, EXPECT_EQ, testing::Invoke(), m, testing::Return(), sock_, and uint32_t.

321  {
322  int n = 3;
323  auto vec = makeVec({600, 600, 600});
324  int pos = 0;
325  const size_t initAppBytesWritten = 500;
326  const size_t appEor = initAppBytesWritten + 1800;
327 
328  sock_->setAppBytesWritten(initAppBytesWritten);
329  sock_->setEorTracking(true);
330 
331  EXPECT_CALL(*(sock_.get()), getRawBytesWritten())
332  // rawBytesWritten after writting initAppBytesWritten + 1500 bytes
333  // + some random SSL overhead
334  .WillOnce(Return(3600))
335  // rawBytesWritten after writting last 300 bytes
336  // + some random SSL overhead
337  .WillOnce(Return(4100));
338  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 1500))
339  .WillOnce(Invoke([=, &pos](SSL*, const void* buf, int m) {
340  // the first 1500 does not have the EOR byte
341  sock_->checkEor(0, 0);
342  verifyVec(buf, m, pos);
343  pos += m;
344  return m;
345  }));
346  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 300))
347  .WillOnce(Invoke([=, &pos](SSL*, const void* buf, int m) {
348  sock_->checkEor(appEor, 3600 + m);
349  verifyVec(buf, m, pos);
350  pos += m;
351  return m;
352  }));
353 
354  uint32_t countWritten = 0;
355  uint32_t partialWritten = 0;
356  sock_->testPerformWrite(
357  vec.get(), n, WriteFlags::EOR, &countWritten, &partialWritten);
358  EXPECT_EQ(countWritten, n);
359  EXPECT_EQ(partialWritten, 0);
360  sock_->checkEor(0, 0);
361 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
static map< string, int > m
AsyncSocket::UniquePtr sock_
Definition: Traits.h:588
#define EXPECT_CALL(obj, call)
const internal::AnythingMatcher _
internal::ReturnAction< R > Return(R value)
folly::TEST_F ( SynchronizedLockTest  ,
TestCopyConstructibleValues   
)

Definition at line 362 of file SynchronizedTest.cpp.

References EXPECT_FALSE, EXPECT_TRUE, and value().

362  {
363  struct NonCopyConstructible {
364  NonCopyConstructible(const NonCopyConstructible&) = delete;
365  NonCopyConstructible& operator=(const NonCopyConstructible&) = delete;
366  };
367  struct CopyConstructible {};
368  EXPECT_FALSE(std::is_copy_constructible<
370  EXPECT_FALSE(std::is_copy_assignable<
372  EXPECT_TRUE(std::is_copy_constructible<
374  EXPECT_TRUE(
375  std::is_copy_assignable<folly::Synchronized<CopyConstructible>>::value);
376 }
static const char *const value
Definition: Conv.cpp:50
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
folly::TEST_F ( AsyncSSLSocketWriteTest  ,
write_with_eor3   
)

Definition at line 366 of file AsyncSSLSocketWriteTest.cpp.

References testing::_, EXPECT_CALL, EXPECT_EQ, testing::Invoke(), m, testing::Return(), sock_, and uint32_t.

366  {
367  int n = 1;
368  auto vec = makeVec({1600});
369  int pos = 0;
370  static constexpr size_t initAppBytesWritten = 500;
371  static constexpr size_t appEor = initAppBytesWritten + 1600;
372 
373  sock_->setAppBytesWritten(initAppBytesWritten);
374  sock_->setEorTracking(true);
375 
376  EXPECT_CALL(*(sock_.get()), getRawBytesWritten())
377  // rawBytesWritten after the initAppBytesWritten
378  // + some random SSL overhead
379  .WillOnce(Return(2000))
380  // rawBytesWritten after the initAppBytesWritten + 1000 (with 100
381  // overhead)
382  // + some random SSL overhead
383  .WillOnce(Return(3100));
384  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 1600))
385  .WillOnce(Invoke([this, &pos](SSL*, const void* buf, int m) {
386  sock_->checkEor(appEor, 2000 + m);
387  verifyVec(buf, m, pos);
388  pos += 1000;
389  return 1000;
390  }));
391 
392  uint32_t countWritten = 0;
393  uint32_t partialWritten = 0;
394  sock_->testPerformWrite(
395  vec.get(), n, WriteFlags::EOR, &countWritten, &partialWritten);
396  EXPECT_EQ(countWritten, 0);
397  EXPECT_EQ(partialWritten, 1000);
398  sock_->checkEor(appEor, 2000 + 1600);
399  consumeVec(vec.get(), countWritten, partialWritten);
400 
401  EXPECT_CALL(*(sock_.get()), getRawBytesWritten())
402  .WillOnce(Return(3100))
403  .WillOnce(Return(3800));
404  EXPECT_CALL(*(sock_.get()), sslWriteImpl(_, _, 600))
405  .WillOnce(Invoke([this, &pos](SSL*, const void* buf, int m) {
406  sock_->checkEor(appEor, 3100 + m);
407  verifyVec(buf, m, pos);
408  pos += m;
409  return m;
410  }));
411  sock_->testPerformWrite(
412  vec.get() + countWritten,
413  n - countWritten,
414  WriteFlags::EOR,
415  &countWritten,
416  &partialWritten);
417  EXPECT_EQ(countWritten, n);
418  EXPECT_EQ(partialWritten, 0);
419  sock_->checkEor(0, 0);
420 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
PolymorphicAction< internal::InvokeAction< FunctionImpl > > Invoke(FunctionImpl function_impl)
static map< string, int > m
AsyncSocket::UniquePtr sock_
Definition: Traits.h:588
#define EXPECT_CALL(obj, call)
const internal::AnythingMatcher _
internal::ReturnAction< R > Return(R value)
folly::TEST_F ( SynchronizedLockTest  ,
UpgradableLocking   
)

Definition at line 378 of file SynchronizedTest.cpp.

References EXPECT_EQ, folly::FakeAllPowerfulAssertingMutexInternal::lock_state, folly::FakeAllPowerfulAssertingMutexInternal::SHARED, type, ulock(), folly::FakeAllPowerfulAssertingMutexInternal::UNIQUE, folly::FakeAllPowerfulAssertingMutexInternal::UNLOCKED, folly::FakeAllPowerfulAssertingMutexInternal::UPGRADE, value(), and wlock().

378  {
380 
381  // sanity assert
382  static_assert(
383  std::is_same<std::decay<decltype(*sync.ulock())>::type, int>::value,
384  "The ulock function was not well configured, blame aary@instagram.com");
385 
386  {
387  auto ulock = sync.ulock();
388  EXPECT_EQ(
391  }
392 
393  // should be unlocked here
394  EXPECT_EQ(
396  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNLOCKED);
397 
398  // test going from upgrade to exclusive
399  {
400  auto ulock = sync.ulock();
401  auto wlock = ulock.moveFromUpgradeToWrite();
402  EXPECT_EQ(static_cast<bool>(ulock), false);
403  EXPECT_EQ(
405  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNIQUE);
406  }
407 
408  // should be unlocked here
409  EXPECT_EQ(
411  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNLOCKED);
412 
413  // test going from upgrade to shared
414  {
415  auto ulock = sync.ulock();
416  auto slock = ulock.moveFromUpgradeToRead();
417  EXPECT_EQ(static_cast<bool>(ulock), false);
418  EXPECT_EQ(
420  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::SHARED);
421  }
422 
423  // should be unlocked here
424  EXPECT_EQ(
426  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNLOCKED);
427 
428  // test going from exclusive to upgrade
429  {
430  auto wlock = sync.wlock();
431  auto ulock = wlock.moveFromWriteToUpgrade();
432  EXPECT_EQ(static_cast<bool>(wlock), false);
433  EXPECT_EQ(
436  }
437 
438  // should be unlocked here
439  EXPECT_EQ(
441  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNLOCKED);
442 
443  // test going from exclusive to shared
444  {
445  auto wlock = sync.wlock();
446  auto slock = wlock.moveFromWriteToRead();
447  EXPECT_EQ(static_cast<bool>(wlock), false);
448  EXPECT_EQ(
450  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::SHARED);
451  }
452 
453  // should be unlocked here
454  EXPECT_EQ(
456  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNLOCKED);
457 }
auto wlock(Synchronized &synchronized, Args &&...args)
Definition: Synchronized.h:925
static FakeAllPowerfulAssertingMutexInternal globalAllPowerfulAssertingMutex
PskType type
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
#define UPGRADE
Definition: http_parser.c:144
auto ulock(Synchronized &synchronized, Args &&...args)
Definition: Synchronized.h:945
static const char *const value
Definition: Conv.cpp:50
folly::TEST_F ( SynchronizedLockTest  ,
UpgradableLockingWithULock   
)

Definition at line 459 of file SynchronizedTest.cpp.

References EXPECT_EQ, folly::FakeAllPowerfulAssertingMutexInternal::lock_state, folly::FakeAllPowerfulAssertingMutexInternal::SHARED, type, ulock(), folly::FakeAllPowerfulAssertingMutexInternal::UNIQUE, folly::FakeAllPowerfulAssertingMutexInternal::UNLOCKED, folly::FakeAllPowerfulAssertingMutexInternal::UPGRADE, value(), and wlock().

459  {
461 
462  // sanity assert
463  static_assert(
464  std::is_same<std::decay<decltype(*sync.ulock())>::type, int>::value,
465  "The ulock function was not well configured, blame aary@instagram.com");
466 
467  // test from upgrade to write
468  sync.withULockPtr([](auto ulock) {
469  EXPECT_EQ(static_cast<bool>(ulock), true);
470  EXPECT_EQ(
473 
474  auto wlock = ulock.moveFromUpgradeToWrite();
475  EXPECT_EQ(static_cast<bool>(ulock), false);
476  EXPECT_EQ(
478  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNIQUE);
479  });
480 
481  // should be unlocked here
482  EXPECT_EQ(
484  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNLOCKED);
485 
486  // test from write to upgrade
487  sync.withWLockPtr([](auto wlock) {
488  EXPECT_EQ(static_cast<bool>(wlock), true);
489  EXPECT_EQ(
491  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNIQUE);
492 
493  auto ulock = wlock.moveFromWriteToUpgrade();
494  EXPECT_EQ(static_cast<bool>(wlock), false);
495  EXPECT_EQ(
498  });
499 
500  // should be unlocked here
501  EXPECT_EQ(
503  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNLOCKED);
504 
505  // test from upgrade to shared
506  sync.withULockPtr([](auto ulock) {
507  EXPECT_EQ(static_cast<bool>(ulock), true);
508  EXPECT_EQ(
511 
512  auto slock = ulock.moveFromUpgradeToRead();
513  EXPECT_EQ(static_cast<bool>(ulock), false);
514  EXPECT_EQ(
516  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::SHARED);
517  });
518 
519  // should be unlocked here
520  EXPECT_EQ(
522  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNLOCKED);
523 
524  // test from write to shared
525  sync.withWLockPtr([](auto wlock) {
526  EXPECT_EQ(static_cast<bool>(wlock), true);
527  EXPECT_EQ(
529  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNIQUE);
530 
531  auto slock = wlock.moveFromWriteToRead();
532  EXPECT_EQ(static_cast<bool>(wlock), false);
533  EXPECT_EQ(
535  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::SHARED);
536  });
537 
538  // should be unlocked here
539  EXPECT_EQ(
541  FakeAllPowerfulAssertingMutexInternal::CurrentLockState::UNLOCKED);
542 }
auto wlock(Synchronized &synchronized, Args &&...args)
Definition: Synchronized.h:925
static FakeAllPowerfulAssertingMutexInternal globalAllPowerfulAssertingMutex
PskType type
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
#define UPGRADE
Definition: http_parser.c:144
auto ulock(Synchronized &synchronized, Args &&...args)
Definition: Synchronized.h:945
static const char *const value
Definition: Conv.cpp:50
folly::TEST_F ( SynchronizedLockTest  ,
TestPieceWiseConstruct   
)

Definition at line 544 of file SynchronizedTest.cpp.

References EXPECT_EQ, EXPECT_TRUE, kShouldSucceed, lock(), folly::gen::move, onLock, onUnlock, and folly::NonDefaultConstructibleMutex::value.

544  {
546  std::piecewise_construct,
547  std::forward_as_tuple(3),
548  std::forward_as_tuple(1)};
549 
550  EXPECT_EQ(*synchronized.lock(), 3);
552 }
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
auto lock(SynchronizedLocker...lockersIn) -> std::tuple< typename SynchronizedLocker::LockedPtr... >
Definition: Synchronized.h:871
static const char *const value
Definition: Conv.cpp:50
folly::TEST_F ( SynchronizedLockTest  ,
TestTryLock   
)

Definition at line 750 of file SynchronizedTest.cpp.

750  {
751  testTryLock<kLockable>(
752  [](auto& synchronized) { return synchronized.tryLock(); });
753 }
folly::TEST_F ( SynchronizedLockTest  ,
TestTryWLock   
)

Definition at line 755 of file SynchronizedTest.cpp.

755  {
756  testTryLock<kWLockable>(
757  [](auto& synchronized) { return synchronized.tryWLock(); });
758 }
folly::TEST_F ( SynchronizedLockTest  ,
TestTryRLock   
)

Definition at line 760 of file SynchronizedTest.cpp.

760  {
761  testTryLock<kRLockable>(
762  [](auto& synchronized) { return synchronized.tryRLock(); });
763 }
folly::TEST_F ( SynchronizedLockTest  ,
TestTryULock   
)

Definition at line 765 of file SynchronizedTest.cpp.

765  {
766  testTryLock<kULockable>(
767  [](auto& synchronized) { return synchronized.tryULock(); });
768 }
folly::TEST_F ( SynchronizedLockTest  ,
TestLockedPtrCompatibilityExclusive   
)

Definition at line 856 of file SynchronizedTest.cpp.

856  {
857  testLockedPtrCompatibilityExclusive<std::is_assignable>();
858  testLockedPtrCompatibilityExclusive<std::is_constructible>();
859 }
folly::TEST_F ( SynchronizedLockTest  ,
TestLockedPtrCompatibilityShared   
)

Definition at line 861 of file SynchronizedTest.cpp.

861  {
862  testLockedPtrCompatibilityShared<std::is_assignable>();
863  testLockedPtrCompatibilityShared<std::is_constructible>();
864 }
folly::TEST_F ( SynchronizedLockTest  ,
TestLockedPtrCompatibilityUpgrade   
)

Definition at line 866 of file SynchronizedTest.cpp.

866  {
867  testLockedPtrCompatibilityUpgrade<std::is_assignable>();
868  testLockedPtrCompatibilityUpgrade<std::is_constructible>();
869 }
folly::TEST_F ( SynchronizedLockTest  ,
TestConvertTryLockToLock   
)

Definition at line 871 of file SynchronizedTest.cpp.

References EXPECT_EQ, ulock(), value(), and wlock().

871  {
872  auto synchronized = folly::Synchronized<int>{0};
873  auto wlock = synchronized.wlock();
874  wlock.unlock();
875 
876  auto ulock = synchronized.ulock();
877  wlock = ulock.moveFromUpgradeToWrite();
878  wlock.unlock();
879 
880  auto value = synchronized.withWLock([](auto& integer) { return integer; });
881  EXPECT_EQ(value, 0);
882 }
auto wlock(Synchronized &synchronized, Args &&...args)
Definition: Synchronized.h:925
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
auto ulock(Synchronized &synchronized, Args &&...args)
Definition: Synchronized.h:945
static const char *const value
Definition: Conv.cpp:50
void folly::testExecutor ( folly::Executor executor)

Definition at line 60 of file SequencedExecutorTest.cpp.

References EXPECT_FALSE, and isSequencedExecutor().

Referenced by TEST().

60  {
62 }
bool isSequencedExecutor(folly::Executor &executor)
#define EXPECT_FALSE(condition)
Definition: gtest.h:1862
void folly::testExecutor ( folly::SequencedExecutor executor)

Definition at line 64 of file SequencedExecutorTest.cpp.

References EXPECT_TRUE, and isSequencedExecutor().

64  {
66 }
bool isSequencedExecutor(folly::Executor &executor)
#define EXPECT_TRUE(condition)
Definition: gtest.h:1859
template<typename Ex >
FOLLY_NOINLINE FOLLY_COLD void folly::throw_exception ( Ex &&  ex)

throw_exception

Throw an exception if exceptions are enabled, or terminate if compiled with -fno-exceptions.

Definition at line 32 of file Exception.h.

Referenced by folly::Arena< Alloc >::allocateSlow(), folly::Arena< SysAllocator< void > >::Arena(), folly::detail::enforceWhitespace(), folly::exception_wrapper::exception_wrapper(), terminate_with(), folly::detail::terminate_with_(), folly::expected_detail::expected_detail_ExpectedHelper::ExpectedHelper::thenOrThrow_(), folly::detail::throw_exception_(), and to().

32  {
33 #if FOLLY_HAS_EXCEPTIONS
34  throw static_cast<Ex&&>(ex);
35 #else
36  (void)ex;
37  std::terminate();
38 #endif
39 }
template<typename Ex , typename... Args>
FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN void folly::throw_exception ( Args &&...  args)

throw_exception

Construct and throw an exception if exceptions are enabled, or terminate if compiled with -fno-exceptions.

Converts any arguments of type char const[N] to char const*.

Definition at line 80 of file Exception.h.

References testing::Args(), FOLLY_ALWAYS_INLINE, FOLLY_ATTR_VISIBILITY_HIDDEN, and folly::detail::to_exception_arg_().

80  {
81  detail::throw_exception_<Ex>(
82  detail::to_exception_arg_(static_cast<Args&&>(args))...);
83 }
FOLLY_ALWAYS_INLINE FOLLY_ATTR_VISIBILITY_HIDDEN char const * to_exception_arg_(char const (&array)[N])
Definition: Exception.h:56
void folly::throwSystemErrorExplicit ( int  err,
const char *  msg 
)
inline

Definition at line 65 of file Exception.h.

References testing::Args(), and makeSystemErrorExplicit().

Referenced by checkFopenErrorExplicit(), checkKernelError(), checkPosixError(), checkUnixErrorExplicit(), folly::AsyncIO::submit(), folly::test::TEST(), and throwSystemError().

65  {
66  throw makeSystemErrorExplicit(err, msg);
67 }
std::system_error makeSystemErrorExplicit(int err, Args &&...args)
Definition: Exception.h:50
template<class... Args>
void folly::throwSystemErrorExplicit ( int  err,
Args &&...  args 
)

Definition at line 70 of file Exception.h.

References testing::Args(), and makeSystemErrorExplicit().

70  {
71  throw makeSystemErrorExplicit(err, std::forward<Args>(args)...);
72 }
std::system_error makeSystemErrorExplicit(int err, Args &&...args)
Definition: Exception.h:50
template<class F >
Future<Unit> folly::times ( const int  n,
F &&  thunk 
)

Repeat the given future (i.e., the computation it contains) n times.

thunk behaves like std::function<Future<T2>(void)>

Definition at line 2348 of file Future-inl.h.

References count, make_unique(), and whileDo().

Referenced by addBenchmark(), folly::MultiLevelTimeSeries< VT, CT >::count(), HTTPDownstreamTest< SPDY3_1CodecPair >::expectResponses(), ExpensiveCopy::ExpensiveCopy(), folly::Future< folly::folly::Unit >::Future(), folly::TimeseriesHistogram< T, CT, C >::rate(), TEST(), and TEST_F().

2348  {
2349  return folly::whileDo(
2350  [n, count = std::make_unique<std::atomic<int>>(0)]() mutable {
2351  return count->fetch_add(1, std::memory_order_relaxed) < n;
2352  },
2353  std::forward<F>(thunk));
2354 }
Future< Unit > whileDo(P &&predicate, F &&thunk)
Definition: Future-inl.h:2335
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&...args)
Definition: Memory.h:259
int * count
template<class Tgt , class Src >
std::enable_if< std::is_same<Tgt, typename std::decay<Src>::type>::value, Tgt>::type folly::to ( Src &&  value)

Definition at line 154 of file Conv.h.

References type, value, and value().

154  {
155  return std::forward<Src>(value);
156 }
static const char *const value
Definition: Conv.cpp:50
template<class Tgt , class Src >
std::enable_if< std::is_arithmetic<Src>::value && !std::is_same<Tgt, Src>::value && std::is_same<Tgt, bool>::value, Tgt>::type folly::to ( const Src &  value)

Definition at line 181 of file Conv.h.

References folly::pushmi::operators::get, folly::detail::getLastElement(), size(), and type.

181  {
182  return value != Src();
183 }
static const char *const value
Definition: Conv.cpp:50
template<typename Tgt , typename Src >
std::enable_if<detail::is_chrono_conversion<Tgt, Src>::value, Tgt>:: type folly::to ( const Src &  value)
folly::std enable_if::typetoAppendDelimStrImpl const Delimiter, const Tv, Tgtresult bool Tgt ::type folly::to ( const char *  b,
const char *  e 
)

Definition at line 1163 of file Conv.h.

References b, FOLLY_NODISCARD, makeConversionError(), type, and value.

1163  {
1164  return tryTo<Tgt>(b, e).thenOrThrow(
1165  [](Tgt res) { return res; },
1166  [=](ConversionCode code) {
1167  return makeConversionError(code, StringPiece(b, e));
1168  });
1169 }
char b
ConversionCode
Definition: Conv.h:53
Range< const char * > StringPiece
ConversionError makeConversionError(ConversionCode code, StringPiece input)
Definition: Conv.cpp:765
template<typename Tgt , typename Src >
std::enable_if<detail::IsArithToArith<Tgt, Src>::value, Tgt>::type folly::to ( const Src &  value)

Definition at line 1361 of file Conv.h.

References FOLLY_NODISCARD, makeConversionError(), type, value, and value().

1362  {
1363  return tryTo<Tgt>(value).thenOrThrow(
1364  [](Tgt res) { return res; },
1365  [&](ConversionCode e) {
1366  return makeConversionError(e, detail::errorValue<Tgt>(value));
1367  });
1368 }
ConversionCode
Definition: Conv.h:53
static const char *const value
Definition: Conv.cpp:50
ConversionError makeConversionError(ConversionCode code, StringPiece input)
Definition: Conv.cpp:765
template<class Tgt , class Src >
std::enable_if< IsSomeString<Src>::value && !std::is_same<StringPiece, Tgt>::value, Tgt>::type folly::to ( Src const &  src)
inline

Definition at line 1491 of file Conv.h.

References type, and value.

1491  {
1492  return to<Tgt>(StringPiece(src.data(), src.size()));
1493 }
Range< const char * > StringPiece
template<class Tgt >
std::enable_if<!std::is_same<StringPiece, Tgt>::value, Tgt>::type folly::to ( StringPiece  src)
inline

Definition at line 1498 of file Conv.h.

References makeConversionError(), folly::gen::move, folly::detail::parseToWrap(), throw_exception(), and type.

1498  {
1499  Tgt result{};
1500  using Error = detail::ParseToError<Tgt>;
1501  using Check = typename std::conditional<
1503  detail::CheckTrailingSpace,
1504  detail::ReturnUnit<Error>>::type;
1505  auto tmp = detail::parseToWrap(src, result);
1506  return tmp
1507  .thenOrThrow(
1508  Check(),
1509  [&](Error e) { throw_exception(makeConversionError(e, src)); })
1510  .thenOrThrow(
1511  [&](Unit) { return std::move(result); },
1512  [&](Error e) {
1513  throw_exception(makeConversionError(e, tmp.value()));
1514  });
1515 }
PskType type
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
error_stage Error
static const char *const value
Definition: Conv.cpp:50
std::enable_if< !std::is_void< ParseToResult< Tgt > >::value, ParseToResult< Tgt > >::type parseToWrap(StringPiece sp, Tgt &out)
Definition: Conv.h:1456
FOLLY_NOINLINE FOLLY_COLD void throw_exception(Ex &&ex)
Definition: Exception.h:32
ConversionError makeConversionError(ConversionCode code, StringPiece input)
Definition: Conv.cpp:765
template<class Tgt >
Tgt folly::to ( StringPiece src)

Definition at line 1532 of file Conv.h.

References makeConversionError(), folly::gen::move, parseTo(), type, and value.

1532  {
1533  Tgt result{};
1534  using Error = detail::ParseToError<Tgt>;
1535  return parseTo(*src, result)
1536  .thenOrThrow(
1537  [&, src](StringPiece sp) -> Tgt {
1538  *src = sp;
1539  return std::move(result);
1540  },
1541  [=](Error e) { return makeConversionError(e, *src); });
1542 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
FOLLY_NODISCARD Expected< StringPiece, ConversionCode > parseTo(StringPiece in, fbstring &out)
Definition: Conv.h:1411
error_stage Error
Range< const char * > StringPiece
ConversionError makeConversionError(ConversionCode code, StringPiece input)
Definition: Conv.cpp:765
template<class Tgt , class Src >
std::enable_if< std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value && !std::is_convertible<Tgt, StringPiece>::value, Tgt>::type folly::to ( const Src &  value)

Definition at line 1573 of file Conv.h.

References type, value, and value().

1573  {
1574  return to<Tgt>(static_cast<typename std::underlying_type<Src>::type>(value));
1575 }
PskType type
static const char *const value
Definition: Conv.cpp:50
template<class Tgt , class Src >
std::enable_if< !std::is_convertible<Src, StringPiece>::value && std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Tgt>::type folly::to ( const Src &  value)

Definition at line 1582 of file Conv.h.

References type, and value().

1582  {
1583  return static_cast<Tgt>(to<typename std::underlying_type<Tgt>::type>(value));
1584 }
PskType type
static const char *const value
Definition: Conv.cpp:50
template<typename T >
constexpr ordering folly::to_ordering ( T  c)

Definition at line 24 of file Ordering.h.

References T.

Referenced by folly::IOBufCompare::impl(), and TEST_F().

24  {
25  return ordering(int(c < T(0)) * -1 + int(c > T(0)));
26 }
#define T(v)
Definition: http_parser.c:233
ordering
Definition: Ordering.h:21
char c
template<typename T , typename D >
std::shared_ptr<T> folly::to_shared_ptr ( std::unique_ptr< T, D > &&  ptr)

to_shared_ptr

Convert unique_ptr to shared_ptr without specifying the template type parameter and letting the compiler deduce it.

So you can write this:

auto sptr = to_shared_ptr(getSomethingUnique<T>());

Instead of this:

auto sptr = shared_ptr<T>(getSomethingUnique<T>());

Useful when T is long, such as:

using T = foobar::FooBarAsyncClient;

Definition at line 323 of file Memory.h.

References folly::gen::move.

Referenced by TEST().

323  {
324  return std::shared_ptr<T>(std::move(ptr));
325 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
template<typename T >
constexpr auto folly::to_signed ( T const &  t) -> typename std::make_signed<T>::type

Definition at line 389 of file Utility.h.

References max, folly::pushmi::detail::t, and type.

Referenced by folly::detail::bits_to_signed(), folly::detail::CheckOverflowToDuration< IsFloatingPoint >::check(), and TEST_F().

389  {
390  using S = typename std::make_signed<T>::type;
391  // note: static_cast<S>(t) would be more straightforward, but it would also be
392  // implementation-defined behavior and that is typically to be avoided; the
393  // following code optimized into the same thing, though
394  return std::numeric_limits<S>::max() < t ? -static_cast<S>(~t) + S{-1}
395  : static_cast<S>(t);
396 }
LogLevel max
Definition: LogLevel.cpp:31
PskType type
template<typename T >
constexpr auto folly::to_unsigned ( T const &  t) -> typename std::make_unsigned<T>::type
template<typename T >
std::weak_ptr<T> folly::to_weak_ptr ( const std::shared_ptr< T > &  ptr)

to_weak_ptr

Make a weak_ptr and return it from a shared_ptr without specifying the template type parameter and letting the compiler deduce it.

So you can write this:

auto wptr = to_weak_ptr(getSomethingShared<T>());

Instead of this:

auto wptr = weak_ptr<T>(getSomethingShared<T>());

Useful when T is long, such as:

using T = foobar::FooBarAsyncClient;

Definition at line 346 of file Memory.h.

References ptr.

Referenced by TEST(), and folly::futures::detail::FutureBase< T >::withinImplementation().

346  {
347  return std::weak_ptr<T>(ptr);
348 }
void * ptr
void folly::toAppend ( IPAddressV4  addr,
string result 
)

Definition at line 40 of file IPAddressV4.cpp.

References folly::IPAddressV4::str().

40  {
41  result->append(addr.str());
42 }
ThreadPoolListHook * addr
void folly::toAppend ( IPAddress  addr,
string result 
)

Definition at line 41 of file IPAddress.cpp.

41  {
42  result->append(addr.str());
43 }
ThreadPoolListHook * addr
void folly::toAppend ( IPAddressV4  addr,
fbstring result 
)

Definition at line 43 of file IPAddressV4.cpp.

References folly::basic_fbstring< E, T, A, Storage >::append(), and folly::IPAddressV4::str().

43  {
44  result->append(addr.str());
45 }
ThreadPoolListHook * addr
void folly::toAppend ( IPAddressV6  addr,
string result 
)

Definition at line 58 of file IPAddressV6.cpp.

References folly::IPAddressV6::str().

58  {
59  result->append(addr.str());
60 }
ThreadPoolListHook * addr
void folly::toAppend ( IPAddressV6  addr,
fbstring result 
)

Definition at line 61 of file IPAddressV6.cpp.

References folly::basic_fbstring< E, T, A, Storage >::append(), and folly::IPAddressV6::str().

61  {
62  result->append(addr.str());
63 }
ThreadPoolListHook * addr
template<class Tgt >
std::enable_if<IsSomeString<Tgt>::value>::type folly::toAppend ( MacAddress  address,
Tgt *  result 
)

Definition at line 225 of file MacAddress.h.

References operator<<(), toAppend(), and folly::MacAddress::toString().

227  {
228  toAppend(address.toString(), result);
229 }
std::enable_if< IsSomeString< Tgt >::value >::type toAppend(MacAddress address, Tgt *result)
Definition: MacAddress.h:225
template<class Tgt , class Src >
std::enable_if< std::is_convertible<Src, const char*>::value && IsSomeString<Tgt>::value>::type folly::toAppend ( Src  value,
Tgt *  result 
)

Everything implicitly convertible to const char* gets appended.

Definition at line 428 of file Conv.h.

References c, type, value, and value().

428  {
429  // Treat null pointers like an empty string, as in:
430  // operator<<(std::ostream&, const char*).
431  const char* c = value;
432  if (c) {
433  result->append(value);
434  }
435 }
static const char *const value
Definition: Conv.cpp:50
char c
template<class Tgt , class Src >
std::enable_if< IsSomeString<Src>::value && IsSomeString<Tgt>::value>::type folly::toAppend ( const Src &  value,
Tgt *  result 
)

Strings get appended, too.

Definition at line 484 of file Conv.h.

484  {
485  result->append(value);
486 }
static const char *const value
Definition: Conv.cpp:50
template<class Tgt >
std::enable_if<IsSomeString<Tgt>::value>::type folly::toAppend ( StringPiece  value,
Tgt *  result 
)

and StringPiece objects too

Definition at line 492 of file Conv.h.

References folly::Range< Iter >::data(), and folly::Range< Iter >::size().

494  {
495  result->append(value.data(), value.size());
496 }
static const char *const value
Definition: Conv.cpp:50
template<class Tgt >
std::enable_if<IsSomeString<Tgt>::value>::type folly::toAppend ( const fbstring value,
Tgt *  result 
)

There's no implicit conversion from fbstring to other string types, so make a specialization.

Definition at line 503 of file Conv.h.

References buffer(), folly::basic_fbstring< E, T, A, Storage >::data(), estimateSpaceNeeded(), folly::basic_fbstring< E, T, A, Storage >::size(), T, toAppend(), type, uint64_t, uint64ToBufferUnsafe(), value, and value().

505  {
506  result->append(value.data(), value.size());
507 }
static const char *const value
Definition: Conv.cpp:50
template<class T , class Tgt >
std::enable_if< IsSomeString<typename std::remove_pointer<Tgt>::type>::value>::type folly::toAppendStrImpl ( const T v,
Tgt  result 
)

Variadic base case: append one element

Definition at line 809 of file Conv.h.

References a, b, convertTo(), Delimiter, folly::detail::digits_to(), folly::detail::digits_to< char >(), folly::detail::digits_to< int >(), folly::detail::digits_to< long >(), folly::detail::digits_to< long long >(), folly::detail::digits_to< short >(), folly::detail::digits_to< signed char >(), folly::detail::digits_to< unsigned char >(), folly::detail::digits_to< unsigned int >(), folly::detail::digits_to< unsigned long >(), folly::detail::digits_to< unsigned long long >(), folly::detail::digits_to< unsigned short >(), folly::detail::getLastElement(), folly::pushmi::__adl::noexcept(), reserveInTargetDelim(), folly::detail::str_to_bool(), folly::detail::str_to_floating(), folly::detail::str_to_floating< double >(), folly::detail::str_to_floating< float >(), folly::detail::str_to_integral(), folly::detail::str_to_integral< char >(), folly::detail::str_to_integral< int >(), folly::detail::str_to_integral< long >(), folly::detail::str_to_integral< long long >(), folly::detail::str_to_integral< short >(), folly::detail::str_to_integral< signed char >(), folly::detail::str_to_integral< unsigned char >(), folly::detail::str_to_integral< unsigned int >(), folly::detail::str_to_integral< unsigned long >(), folly::detail::str_to_integral< unsigned long long >(), folly::detail::str_to_integral< unsigned short >(), T, to(), toAppend(), tryTo(), type, uint64_t, value, and value().

809  {
810  toAppend(v, result);
811 }
toAppend(v, result)
template<>
folly::dynamic folly::toDynamic ( const wangle::SSLSessionCacheData data)

Definition at line 24 of file SSLSessionCacheData.cpp.

References wangle::SSLSessionCacheData::addedTime, folly::dynamic::object(), wangle::SSLSessionCacheData::serviceIdentity, wangle::SSLSessionCacheData::sessionData, and folly::basic_fbstring< E, T, A, Storage >::toStdString().

24  {
26  ret["session_data"] = folly::dynamic(data.sessionData.toStdString());
27  system_clock::duration::rep rep = data.addedTime.time_since_epoch().count();
28  ret["added_time"] = folly::dynamic(static_cast<uint64_t>(rep));
29  ret["service_identity"] = folly::dynamic(data.serviceIdentity.toStdString());
30  return ret;
31 }
static ObjectMaker object()
Definition: dynamic-inl.h:240
std::basic_string< E, T, A > toStdString() const
Definition: FBString.h:1227
std::chrono::time_point< std::chrono::system_clock > addedTime
std::string folly::toJson ( dynamic const &  dyn)

Definition at line 915 of file json.cpp.

References folly::json::serialize().

Referenced by BENCHMARK(), proxygen::TraceEvent::MetaData::ConvVisitor< std::string >::operator()(), and TEST().

915  {
916  return json::serialize(dyn, json::serialization_opts());
917 }
std::string serialize(dynamic const &dyn, serialization_opts const &opts)
Definition: json.cpp:621
void folly::toLowerAscii ( MutableStringPiece  str)
inline

Definition at line 601 of file String.h.

References folly::Range< Iter >::begin(), folly::Range< Iter >::size(), and toLowerAscii().

601  {
602  toLowerAscii(str.begin(), str.size());
603 }
void toLowerAscii(std::string &str)
Definition: String.h:605
void folly::toLowerAscii ( char *  str,
size_t  length 
)

Fast, in-place lowercasing of ASCII alphabetic characters in strings. Leaves all other characters unchanged, including those with the 0x80 bit set.

Parameters
strString to convert
lengthLength of str, in bytes

Definition at line 601 of file String.cpp.

References min, uint32_t, and uint64_t.

Referenced by BENCHMARK(), proxygen::GzipHeaderCodec::encode(), fizz::server::CertManager::getCert(), fizz::server::getKeyFromIdent(), proxygen::HTTPCommonHeaders::initHeaderNames(), proxygen::ZlibServerFilter::isCompressibleContentType(), wangle::SSLContextKeyHash::operator()(), skipWhitespace(), TEST(), and toLowerAscii().

601  {
602  static const size_t kAlignMask64 = 7;
603  static const size_t kAlignMask32 = 3;
604 
605  // Convert a character at a time until we reach an address that
606  // is at least 32-bit aligned
607  size_t n = (size_t)str;
608  n &= kAlignMask32;
609  n = std::min(n, length);
610  size_t offset = 0;
611  if (n != 0) {
612  n = std::min(4 - n, length);
613  do {
614  toLowerAscii8(str[offset]);
615  offset++;
616  } while (offset < n);
617  }
618 
619  n = (size_t)(str + offset);
620  n &= kAlignMask64;
621  if ((n != 0) && (offset + 4 <= length)) {
622  // The next address is 32-bit aligned but not 64-bit aligned.
623  // Convert the next 4 bytes in order to get to the 64-bit aligned
624  // part of the input.
625  toLowerAscii32(*(uint32_t*)(str + offset));
626  offset += 4;
627  }
628 
629  // Convert 8 characters at a time
630  while (offset + 8 <= length) {
631  toLowerAscii64(*(uint64_t*)(str + offset));
632  offset += 8;
633  }
634 
635  // Convert 4 characters at a time
636  while (offset + 4 <= length) {
637  toLowerAscii32(*(uint32_t*)(str + offset));
638  offset += 4;
639  }
640 
641  // Convert any characters remaining after the last 4-byte aligned group
642  while (offset < length) {
643  toLowerAscii8(str[offset]);
644  offset++;
645  }
646 }
LogLevel min
Definition: LogLevel.cpp:30
void folly::toLowerAscii ( std::string str)
inline

Definition at line 605 of file String.h.

References toLowerAscii().

605  {
606  // str[0] is legal also if the string is empty.
607  toLowerAscii(&str[0], str.size());
608 }
void toLowerAscii(std::string &str)
Definition: String.h:605
std::string folly::toPrettyJson ( dynamic const &  dyn)

Definition at line 919 of file json.cpp.

References folly::json::serialization_opts::pretty_formatting, and folly::json::serialize().

Referenced by printBenchmarkResultsAsJson(), and printBenchmarkResultsAsVerboseJson().

919  {
920  json::serialization_opts opts;
921  opts.pretty_formatting = true;
922  return json::serialize(dyn, opts);
923 }
std::string serialize(dynamic const &dyn, serialization_opts const &opts)
Definition: json.cpp:621
std::string folly::toStdString ( const folly::fbstring s)
inline

Definition at line 41 of file String.h.

References folly::basic_fbstring< E, T, A, Storage >::data(), folly::basic_fbstring< E, T, A, Storage >::size(), and string.

Referenced by folly::ThreadPoolExecutor::getName(), and folly::basic_fbstring< char >::toStdString().

41  {
42  return std::string(s.data(), s.size());
43 }
size_type size() const
Definition: FBString.h:1337
const value_type * data() const
Definition: FBString.h:1716
const char * string
Definition: Conv.cpp:212
const std::string& folly::toStdString ( const std::string s)
inline

Definition at line 45 of file String.h.

References s.

45  {
46  return s;
47 }
static set< string > s
std::string&& folly::toStdString ( std::string &&  s)
inline

Definition at line 51 of file String.h.

References cEscape(), folly::gen::move, and s.

51  {
52  return std::move(s);
53 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
static set< string > s
static std::string folly::toSubprocessSpawnErrorMessage ( char const *  executable,
int  errCode,
int  errnoValue 
)
inlinestatic

Definition at line 133 of file Subprocess.cpp.

References errnoStr(), kExecFailure, and prefix().

136  {
137  auto prefix = errCode == kExecFailure ? "failed to execute "
138  : "error preparing to execute ";
139  return to<std::string>(prefix, executable, ": ", errnoStr(errnoValue));
140 }
constexpr int kExecFailure
Definition: Subprocess.cpp:49
bool prefix(Cursor &c, uint32_t expected)
int errCode
Definition: Subprocess.cpp:224
fbstring errnoStr(int err)
Definition: String.cpp:463
int errnoValue
Definition: Subprocess.cpp:225
StringPiece folly::trimWhitespace ( StringPiece  sp)
inline

Returns a subpiece with all whitespace removed from the back and front of . Whitespace means any of [' ', '
', '', ''].

Definition at line 568 of file String.h.

References ltrimWhitespace(), and rtrimWhitespace().

Referenced by proxygen::HTTP1xCodec::generateHeader(), parseLogConfig(), and TEST().

568  {
569  return ltrimWhitespace(rtrimWhitespace(sp));
570 }
StringPiece ltrimWhitespace(StringPiece sp)
Definition: String.cpp:131
StringPiece rtrimWhitespace(StringPiece sp)
Definition: String.cpp:149
int folly::truncateNoInt ( const char *  path,
off_t  len 
)

Definition at line 90 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt().

90  {
91  return int(wrapNoInt(truncate, path, len));
92 }
ssize_t wrapNoInt(F f, Args...args)
template<typename... Exceptions, typename F >
exception_wrapper folly::try_and_catch ( F &&  fn)

try_and_catch is a simple replacement for try {} catch(){}` that allows you to specify which derived exceptions you would like to catch and store in an exception_wrapper.

Because we cannot build an equivalent of std::current_exception(), we need to catch every derived exception that we are interested in catching.

Exceptions should be listed in the reverse order that you would write your catch statements (that is, std::exception& should be first).

Example Usage:
// This catches my runtime_error and if I call throw_exception() on ew, it
// will throw a runtime_error
auto ew = folly::try_and_catch<std::exception, std::runtime_error>([=]() {
if (badThingHappens()) {
throw std::runtime_error("ZOMG!");
}
});
// This will catch the exception and if I call throw_exception() on ew, it
// will throw a std::exception
auto ew = folly::try_and_catch<std::exception, std::runtime_error>([=]() {
if (badThingHappens()) {
throw std::exception();
}
});
// This will not catch the exception and it will be thrown.
auto ew = folly::try_and_catch<std::runtime_error>([=]() {
if (badThingHappens()) {
throw std::exception();
}
});

Definition at line 703 of file ExceptionWrapper.h.

References folly::detail::try_and_catch_().

703  {
704  return detail::try_and_catch_<F, Exceptions...>(std::forward<F>(fn));
705 }
exception_wrapper try_and_catch_(F &&f)
template<class T >
Expected< uint64_t, DecodeVarintError > folly::tryDecodeVarint ( Range< T * > &  data)
inline

A variant of decodeVarint() that does not throw on error. Useful in contexts where only part of a serialized varint may be attempted to be decoded, e.g., when a serialized varint arrives on the boundary of a network packet.

Definition at line 147 of file Varint.h.

References b, folly::test::begin(), folly::Range< Iter >::begin(), folly::test::end(), folly::Range< Iter >::end(), int64_t, int8_t, LIKELY, makeUnexpected(), TooFewBytes, TooManyBytes, type, uint64_t, folly::Range< Iter >::uncheckedAdvance(), val, and value().

Referenced by decodeVarint(), folly::io::StreamCodec::doUncompress(), and folly::test::testVarintFail().

147  {
148  static_assert(
149  std::is_same<typename std::remove_cv<T>::type, char>::value ||
150  std::is_same<typename std::remove_cv<T>::type, unsigned char>::value,
151  "Only character ranges are supported");
152 
153  const int8_t* begin = reinterpret_cast<const int8_t*>(data.begin());
154  const int8_t* end = reinterpret_cast<const int8_t*>(data.end());
155  const int8_t* p = begin;
156  uint64_t val = 0;
157 
158  // end is always greater than or equal to begin, so this subtraction is safe
159  if (LIKELY(size_t(end - begin) >= kMaxVarintLength64)) { // fast path
160  int64_t b;
161  do {
162  b = *p++;
163  val = (b & 0x7f);
164  if (b >= 0) {
165  break;
166  }
167  b = *p++;
168  val |= (b & 0x7f) << 7;
169  if (b >= 0) {
170  break;
171  }
172  b = *p++;
173  val |= (b & 0x7f) << 14;
174  if (b >= 0) {
175  break;
176  }
177  b = *p++;
178  val |= (b & 0x7f) << 21;
179  if (b >= 0) {
180  break;
181  }
182  b = *p++;
183  val |= (b & 0x7f) << 28;
184  if (b >= 0) {
185  break;
186  }
187  b = *p++;
188  val |= (b & 0x7f) << 35;
189  if (b >= 0) {
190  break;
191  }
192  b = *p++;
193  val |= (b & 0x7f) << 42;
194  if (b >= 0) {
195  break;
196  }
197  b = *p++;
198  val |= (b & 0x7f) << 49;
199  if (b >= 0) {
200  break;
201  }
202  b = *p++;
203  val |= (b & 0x7f) << 56;
204  if (b >= 0) {
205  break;
206  }
207  b = *p++;
208  val |= (b & 0x01) << 63;
209  if (b >= 0) {
210  break;
211  }
212  return makeUnexpected(DecodeVarintError::TooManyBytes);
213  } while (false);
214  } else {
215  int shift = 0;
216  while (p != end && *p < 0) {
217  val |= static_cast<uint64_t>(*p++ & 0x7f) << shift;
218  shift += 7;
219  }
220  if (p == end) {
221  return makeUnexpected(DecodeVarintError::TooFewBytes);
222  }
223  val |= static_cast<uint64_t>(*p++) << shift;
224  }
225 
226  data.uncheckedAdvance(p - begin);
227  return val;
228 }
char b
PskType type
constexpr size_t kMaxVarintLength64
Definition: Varint.h:50
#define LIKELY(x)
Definition: Likely.h:47
auto begin(TestAdlIterable &instance)
Definition: ForeachTest.cpp:56
double val
Definition: String.cpp:273
constexpr Unexpected< typename std::decay< Error >::type > makeUnexpected(Error &&)
Definition: Expected.h:785
auto end(TestAdlIterable &instance)
Definition: ForeachTest.cpp:62
static const char *const value
Definition: Conv.cpp:50
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
template<typename T , typename... Args>
T * folly::tryEmplace ( Try< T > &  t,
Args &&...  args 
)
noexcept

Definition at line 249 of file Try-inl.h.

References folly::Try< T >::emplace(), and folly::Try< T >::emplaceException().

Referenced by folly::coro::TimedWaitAwaitable< Awaitable >::SharedState::setValue(), and TEST().

249  {
250  try {
251  return std::addressof(t.emplace(static_cast<Args&&>(args)...));
252  } catch (const std::exception& ex) {
253  t.emplaceException(std::current_exception(), ex);
254  return nullptr;
255  } catch (...) {
256  t.emplaceException(std::current_exception());
257  return nullptr;
258  }
259 }
void folly::tryEmplace ( Try< void > &  t)
inlinenoexcept

Definition at line 261 of file Try-inl.h.

References folly::pushmi::detail::t.

261  {
262  t.emplace();
263 }
template<typename T , typename Func >
T * folly::tryEmplaceWith ( Try< T > &  t,
Func &&  func 
)
noexcept

Definition at line 266 of file Try-inl.h.

References folly::Try< T >::emplace(), folly::Try< T >::emplaceException(), and folly::Try< T >::value().

Referenced by folly::fibers::FiberManager::AddTaskFinallyHelper< F, G >::Func::operator()(), folly::fibers::FiberManager::runInMainContext(), and TEST().

266  {
267  static_assert(
268  std::is_constructible<T, folly::invoke_result_t<Func>>::value,
269  "Unable to initialise a value of type T with the result of 'func'");
270  try {
271  return std::addressof(t.emplace(static_cast<Func&&>(func)()));
272  } catch (const std::exception& ex) {
273  t.emplaceException(std::current_exception(), ex);
274  return nullptr;
275  } catch (...) {
276  t.emplaceException(std::current_exception());
277  return nullptr;
278  }
279 }
#define T(v)
Definition: http_parser.c:233
typename invoke_result< F, Args... >::type invoke_result_t
Definition: Invoke.h:142
static const char *const value
Definition: Conv.cpp:50
template<typename Func >
bool folly::tryEmplaceWith ( Try< void > &  t,
Func &&  func 
)
noexcept

Definition at line 282 of file Try-inl.h.

References folly::Try< void >::emplace(), folly::Try< void >::emplaceException(), and folly::Try< T >::value().

282  {
283  static_assert(
284  std::is_void<folly::invoke_result_t<Func>>::value,
285  "Func returns non-void. Cannot be used to emplace Try<void>");
286  try {
287  static_cast<Func&&>(func)();
288  t.emplace();
289  return true;
290  } catch (const std::exception& ex) {
291  t.emplaceException(std::current_exception(), ex);
292  return false;
293  } catch (...) {
294  t.emplaceException(std::current_exception());
295  return false;
296  }
297 }
typename invoke_result< F, Args... >::type invoke_result_t
Definition: Invoke.h:142
Function< void()> Func
Definition: Executor.h:27
static const char *const value
Definition: Conv.cpp:50
std::shared_ptr< ShutdownSocketSet > folly::tryGetShutdownSocketSet ( )

Definition at line 29 of file GlobalShutdownSocketSet.cpp.

References folly::Singleton< T, Tag, VaultTag >::try_get().

29  {
30  return singleton.try_get();
31 }
static Singleton< ShutdownSocketSet, PrivateTag > singleton
ReadMostlySharedPtr< ShutdownSocketSet > folly::tryGetShutdownSocketSetFast ( )

Definition at line 32 of file GlobalShutdownSocketSet.cpp.

References folly::Singleton< T, Tag, VaultTag >::try_get_fast().

32  {
33  return singleton.try_get_fast();
34 }
static Singleton< ShutdownSocketSet, PrivateTag > singleton
template<class Tgt , class Src >
std::enable_if< std::is_same<Tgt, typename std::decay<Src>::type>::value, Expected<Tgt, ConversionCode> >::type folly::tryTo ( Src &&  value)

The identity conversion function. tryTo<T>(T) returns itself for all types T.

Definition at line 146 of file Conv.h.

References type, and value().

146  {
147  return std::forward<Src>(value);
148 }
static const char *const value
Definition: Conv.cpp:50
template<class Tgt , class Src >
std::enable_if< std::is_arithmetic<Src>::value && !std::is_same<Tgt, Src>::value && std::is_same<Tgt, bool>::value, Expected<Tgt, ConversionCode> >::type folly::tryTo ( const Src &  value)

Unchecked conversion from arithmetic to boolean. This is different from the other arithmetic conversions because we use the C convention of treating any non-zero value as true, instead of range checking.

Definition at line 172 of file Conv.h.

References type, and value.

172  {
173  return value != Src();
174 }
static const char *const value
Definition: Conv.cpp:50
template<typename Tgt >
std::enable_if< detail::is_duration<Tgt>::value, Expected<Tgt, ConversionCode> >::type folly::tryTo ( const struct timespec &  ts)

struct timespec to std::chrono::duration

Definition at line 595 of file Conv.h.

References type.

Referenced by toAppendStrImpl().

595  {
596  return detail::tryPosixTimeToDuration<Tgt, std::nano>(ts.tv_sec, ts.tv_nsec);
597 }
template<typename Tgt >
std::enable_if< detail::is_duration<Tgt>::value, Expected<Tgt, ConversionCode> >::type folly::tryTo ( const struct timeval &  tv)

struct timeval to std::chrono::duration

Definition at line 606 of file Conv.h.

References type.

606  {
607  return detail::tryPosixTimeToDuration<Tgt, std::micro>(tv.tv_sec, tv.tv_usec);
608 }
template<typename Tgt , typename Src >
std::enable_if< detail::is_time_point<Tgt>::value && detail::is_posix_time_type<Src>::value, Expected<Tgt, ConversionCode> >::type folly::tryTo ( const Src &  value)

timespec or timeval to std::chrono::time_point

Definition at line 617 of file Conv.h.

References type, value, and value().

617  {
618  return tryTo<typename Tgt::duration>(value).then(
619  [](typename Tgt::duration result) { return Tgt(result); });
620 }
static const char *const value
Definition: Conv.cpp:50
template<typename Tgt , typename Rep , typename Period >
std::enable_if< std::is_same<Tgt, struct timespec>::value, Expected<Tgt, ConversionCode> >::type folly::tryTo ( const std::chrono::duration< Rep, Period > &  duration)

std::chrono::duration to struct timespec

Definition at line 629 of file Conv.h.

References makeUnexpected(), type, and value.

629  {
630  auto result = detail::durationToPosixTime<std::nano>(duration);
631  if (result.hasError()) {
632  return makeUnexpected(result.error());
633  }
634 
635  struct timespec ts;
636  ts.tv_sec = result.value().first;
637  ts.tv_nsec = result.value().second;
638  return ts;
639 }
constexpr Unexpected< typename std::decay< Error >::type > makeUnexpected(Error &&)
Definition: Expected.h:785
template<typename Tgt , typename Rep , typename Period >
std::enable_if< std::is_same<Tgt, struct timeval>::value, Expected<Tgt, ConversionCode> >::type folly::tryTo ( const std::chrono::duration< Rep, Period > &  duration)

std::chrono::duration to struct timeval

Definition at line 648 of file Conv.h.

References makeUnexpected(), and type.

648  {
649  auto result = detail::durationToPosixTime<std::micro>(duration);
650  if (result.hasError()) {
651  return makeUnexpected(result.error());
652  }
653 
654  struct timeval tv;
655  tv.tv_sec = result.value().first;
656  tv.tv_usec = result.value().second;
657  return tv;
658 }
constexpr Unexpected< typename std::decay< Error >::type > makeUnexpected(Error &&)
Definition: Expected.h:785
template<typename Tgt , typename Clock , typename Duration >
std::enable_if< detail::is_posix_time_type<Tgt>::value, Expected<Tgt, ConversionCode> >::type folly::tryTo ( const std::chrono::time_point< Clock, Duration > &  timePoint)

std::chrono::time_point to timespec or timeval

Definition at line 667 of file Conv.h.

References type, and value.

667  {
668  return tryTo<Tgt>(timePoint.time_since_epoch());
669 }
template<typename Tgt , typename Src >
std::enable_if< detail::IsArithToArith<Tgt, Src>::value, Expected<Tgt, ConversionCode> >::type folly::tryTo ( const Src &  value)
noexcept

Definition at line 1356 of file Conv.h.

References value().

1356  {
1357  return detail::convertTo<Tgt>(value);
1358 }
static const char *const value
Definition: Conv.cpp:50
template<class Tgt >
std::enable_if< !std::is_same<StringPiece, Tgt>::value, Expected<Tgt, detail::ParseToError<Tgt> > >::type folly::tryTo ( StringPiece  src)
inline

String or StringPiece to target conversion. Accepts leading and trailing whitespace, but no non-space trailing characters.

Definition at line 1475 of file Conv.h.

References folly::gen::move, parseTo(), type, and value.

1475  {
1476  Tgt result{};
1477  using Error = detail::ParseToError<Tgt>;
1478  using Check = typename std::conditional<
1480  detail::CheckTrailingSpace,
1481  detail::ReturnUnit<Error>>::type;
1482  return parseTo(src, result).then(Check(), [&](Unit) {
1483  return std::move(result);
1484  });
1485 }
PskType type
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
FOLLY_NODISCARD Expected< StringPiece, ConversionCode > parseTo(StringPiece in, fbstring &out)
Definition: Conv.h:1411
error_stage Error
static const char *const value
Definition: Conv.cpp:50
template<class Tgt >
Expected<Tgt, detail::ParseToError<Tgt> > folly::tryTo ( StringPiece src)

tryTo/to that take the strings by pointer so the caller gets information about how much of the string was consumed by the conversion. These do not check for trailing whitepsace.

Definition at line 1523 of file Conv.h.

References folly::gen::move, and parseTo().

1523  {
1524  Tgt result;
1525  return parseTo(*src, result).then([&, src](StringPiece sp) -> Tgt {
1526  *src = sp;
1527  return std::move(result);
1528  });
1529 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
FOLLY_NODISCARD Expected< StringPiece, ConversionCode > parseTo(StringPiece in, fbstring &out)
Definition: Conv.h:1411
Range< const char * > StringPiece
template<class Tgt , class Src >
std::enable_if< std::is_enum<Src>::value && !std::is_same<Src, Tgt>::value && !std::is_convertible<Tgt, StringPiece>::value, Expected<Tgt, ConversionCode> >::type folly::tryTo ( const Src &  value)

Definition at line 1553 of file Conv.h.

References type, value, and value().

1553  {
1554  using I = typename std::underlying_type<Src>::type;
1555  return tryTo<Tgt>(static_cast<I>(value));
1556 }
PskType type
static const char *const value
Definition: Conv.cpp:50
template<class Tgt , class Src >
std::enable_if< !std::is_convertible<Src, StringPiece>::value && std::is_enum<Tgt>::value && !std::is_same<Src, Tgt>::value, Expected<Tgt, ConversionCode> >::type folly::tryTo ( const Src &  value)

Definition at line 1563 of file Conv.h.

References i, type, value, and value().

1563  {
1564  using I = typename std::underlying_type<Tgt>::type;
1565  return tryTo<I>(value).then([](I i) { return static_cast<Tgt>(i); });
1566 }
PskType type
static const char *const value
Definition: Conv.cpp:50
template<class T , class U >
auto folly::tuplePrepend ( T &&  car,
U &&  cdr 
) -> decltype(std::tuple_cat( std::make_tuple(std::forward<T>(car)), std::forward<U>(cdr)))

Definition at line 117 of file TupleOps.h.

References std::tr1::make_tuple().

Referenced by folly::test::TupleTo< std::tuple< U, Us... >, T >::convert(), and folly::test::TEST().

119  {
120  return std::tuple_cat(
121  std::make_tuple(std::forward<T>(car)), std::forward<U>(cdr));
122 }
tuple make_tuple()
Definition: gtest-tuple.h:675
template<std::size_t start = 0, std::size_t n = std::numeric_limits<std::size_t>::max(), class T , class Seq = typename TemplateTupleRange<T, start, n>::type>
auto folly::tupleRange ( T &&  v) -> decltype(detail::TupleSelect<Seq>::select(std::forward<T>(v)))

Definition at line 110 of file TupleOps.h.

111  {
112  return detail::TupleSelect<Seq>::select(std::forward<T>(v));
113 }
folly::TYPED_TEST ( SynchronizedTest  ,
Basic   
)

Definition at line 61 of file SynchronizedTest.cpp.

61  {
62  testBasic<TypeParam>();
63 }
folly::TYPED_TEST ( SynchronizedTest  ,
WithLock   
)

Definition at line 65 of file SynchronizedTest.cpp.

65  {
66  testWithLock<TypeParam>();
67 }
folly::TYPED_TEST ( SynchronizedTest  ,
Unlock   
)

Definition at line 69 of file SynchronizedTest.cpp.

69  {
70  testUnlock<TypeParam>();
71 }
folly::TYPED_TEST ( SynchronizedTest  ,
Deprecated   
)

Definition at line 73 of file SynchronizedTest.cpp.

73  {
74  testDeprecated<TypeParam>();
75 }
folly::TYPED_TEST ( SynchronizedTest  ,
Concurrency   
)

Definition at line 77 of file SynchronizedTest.cpp.

77  {
78  testConcurrency<TypeParam>();
79 }
folly::TYPED_TEST ( SynchronizedTest  ,
AcquireLocked   
)

Definition at line 81 of file SynchronizedTest.cpp.

81  {
82  testAcquireLocked<TypeParam>();
83 }
folly::TYPED_TEST ( SynchronizedTest  ,
AcquireLockedWithConst   
)

Definition at line 85 of file SynchronizedTest.cpp.

85  {
86  testAcquireLockedWithConst<TypeParam>();
87 }
folly::TYPED_TEST ( SynchronizedTest  ,
DualLocking   
)

Definition at line 89 of file SynchronizedTest.cpp.

89  {
90  testDualLocking<TypeParam>();
91 }
folly::TYPED_TEST ( SynchronizedTest  ,
DualLockingWithConst   
)

Definition at line 93 of file SynchronizedTest.cpp.

93  {
94  testDualLockingWithConst<TypeParam>();
95 }
folly::TYPED_TEST ( SynchronizedTest  ,
ConstCopy   
)

Definition at line 97 of file SynchronizedTest.cpp.

97  {
98  testConstCopy<TypeParam>();
99 }
folly::TYPED_TEST ( SynchronizedTest  ,
InPlaceConstruction   
)

Definition at line 101 of file SynchronizedTest.cpp.

101  {
102  testInPlaceConstruction<TypeParam>();
103 }
folly::TYPED_TEST ( SynchronizedTest  ,
Exchange   
)

Definition at line 105 of file SynchronizedTest.cpp.

105  {
106  testExchange<TypeParam>();
107 }
folly::TYPED_TEST ( SynchronizedTimedTest  ,
Timed   
)

Definition at line 128 of file SynchronizedTest.cpp.

128  {
129  testTimed<TypeParam>();
130 }
folly::TYPED_TEST ( SynchronizedTimedTest  ,
TimedSynchronized   
)

Definition at line 132 of file SynchronizedTest.cpp.

132  {
133  testTimedSynchronized<TypeParam>();
134 }
folly::TYPED_TEST ( SynchronizedTimedWithConstTest  ,
TimedShared   
)

Definition at line 153 of file SynchronizedTest.cpp.

153  {
154  testTimedShared<TypeParam>();
155 }
folly::TYPED_TEST ( SynchronizedTimedWithConstTest  ,
TimedSynchronizeWithConst   
)

Definition at line 157 of file SynchronizedTest.cpp.

157  {
158  testTimedSynchronizedWithConst<TypeParam>();
159 }
folly::TYPED_TEST_CASE ( SynchronizedTest  ,
SynchronizedTestTypes   
)
folly::TYPED_TEST_CASE ( SynchronizedTimedTest  ,
SynchronizedTimedTestTypes   
)
uint32_t folly::uint64ToBufferUnsafe ( uint64_t  v,
char *const  buffer 
)
inline

Copies the ASCII base 10 representation of v into buffer and returns the number of bytes written. Does NOT append a \0. Assumes the buffer points to digits10(v) bytes of valid memory. Note that uint64 needs at most 20 bytes, uint32_t needs at most 10 bytes, uint16_t needs at most 5 bytes, and so on. Measurements suggest that defining a separate overload for 32-bit integers is not worthwhile.

This primitive is unsafe because it makes the size assumption and because it does not add a terminating \0.

Definition at line 383 of file Conv.h.

References digits10(), and uint32_t.

Referenced by folly::detail::assertionFailure(), folly::FormatValue< T, typename std::enable_if< std::is_integral< T >::value &&!std::is_same< T, bool >::value >::type >::doFormat(), estimateSpaceNeeded(), folly::symbolizer::SymbolizePrinter::print(), toAppend(), u2aAppendFollyBM(), and u64ToAsciiFollyBM().

383  {
384  auto const result = digits10(v);
385  // WARNING: using size_t or pointer arithmetic for pos slows down
386  // the loop below 20x. This is because several 32-bit ops can be
387  // done in parallel, but only fewer 64-bit ones.
388  uint32_t pos = result - 1;
389  while (v >= 10) {
390  // Keep these together so a peephole optimization "sees" them and
391  // computes them in one shot.
392  auto const q = v / 10;
393  auto const r = v % 10;
394  buffer[pos--] = static_cast<char>('0' + r);
395  v = q;
396  }
397  // Last digit is trivial to handle
398  buffer[pos] = static_cast<char>(v + '0');
399  return result;
400 }
std::vector< uint8_t > buffer(kBufferSize+16)
uint32_t digits10(uint64_t v)
Definition: Conv.h:295
int folly::uncaught_exceptions ( )
inlinenoexcept

Returns the number of uncaught exceptions.

This function is based on Evgeny Panasyuk's implementation from here: http://fburl.com/15190026

Definition at line 52 of file UncaughtExceptions.h.

References __cxxabiv1::__cxa_get_globals().

Referenced by InheritsThrowingConstructor::InheritsThrowingConstructor(), makeGuard(), TEST(), Validator::validate(), and ThrowInDestructor< N, I >::~ThrowInDestructor().

52  {
53 #if defined(FOLLY_EXCEPTION_COUNT_USE_CXA_GET_GLOBALS)
54  // __cxa_get_globals returns a __cxa_eh_globals* (defined in unwind-cxx.h).
55  // The offset below returns __cxa_eh_globals::uncaughtExceptions.
56  return *(reinterpret_cast<unsigned int*>(
57  static_cast<char*>(static_cast<void*>(__cxxabiv1::__cxa_get_globals())) +
58  sizeof(void*)));
59 #elif defined(FOLLY_EXCEPTION_COUNT_USE_GETPTD)
60  // _getptd() returns a _tiddata* (defined in mtdll.h).
61  // The offset below returns _tiddata::_ProcessingThrow.
62  return *(reinterpret_cast<int*>(
63  static_cast<char*>(static_cast<void*>(_getptd())) + sizeof(void*) * 28 +
64  0x4 * 8));
65 #elif defined(FOLLY_EXCEPTION_COUNT_USE_STD)
66  return std::uncaught_exceptions();
67 #endif
68 }
int uncaught_exceptions() noexcept
__cxa_eh_globals * __cxa_get_globals(void) noexcept
template<class F >
auto folly::uncurry ( F &&  f) -> detail::apply_tuple::Uncurry<typename std::decay<F>::type>

Wraps a function taking N arguments into a function which accepts a tuple of N arguments. Note: This function will also accept an std::pair if N == 2.

For example, given the below code:

std::vector<std::tuple<int, int, int>> rows = ...; auto test = [](std::tuple<int, int, int>& row) { return std::get<0>(row) * std::get<1>(row) * std::get<2>(row) == 24; }; auto found = std::find_if(rows.begin(), rows.end(), test);

'test' could be rewritten as:

auto test = folly::uncurry([](int a, int b, int c) { return a * b * c == 24; });

Definition at line 178 of file ApplyTuple.h.

References f, and make_from_tuple().

Referenced by TEST().

179  {
181  std::forward<F>(f));
182 }
auto f
PskType type

Definition at line 656 of file Expected.h.

Referenced by TEST().

657  {}) {
658  return {};
659 }
template<class OutputString = std::string>
OutputString folly::unhexlify ( StringPiece  input)

Definition at line 282 of file String.h.

References gmock_output_test::output, and unhexlify().

282  {
283  OutputString output;
284  if (!unhexlify(input, output)) {
285  // unhexlify() fails if the input has non-hexidecimal characters,
286  // or if it doesn't consist of a whole number of bytes
287  throw std::domain_error("unhexlify() called with non-hex input");
288  }
289  return output;
290 }
OutputString unhexlify(StringPiece input)
Definition: String.h:282
template<class InputString , class OutputString >
bool folly::unhexlify ( const InputString &  input,
OutputString &  output 
)

Same functionality as Python's binascii.unhexlify. Returns true on successful conversion.

Definition at line 616 of file String-inl.h.

References folly::detail::hexDumpLine(), folly::detail::hexTable, i, ptr, size(), string, and uint8_t.

Referenced by BENCHMARK(), fizz::test::HandshakeTypesTest::decodeHex(), fizz::test::ZlibCertificateCompressorTest::decodeHex(), fizz::test::ExtensionsTest::getBuf(), fizz::test::PlaintextRecordTest::getBuf(), fizz::extensions::test::TokenBindingConstructorTest::getBuf(), fizz::test::EncryptedRecordTest::getBuf(), fizz::test::RecordTest::getBuf(), fizz::extensions::test::ValidatorTest::getBuf(), fizz::testing::getKey(), fizz::test::getKey(), fizz::server::test::getV2ClientHello(), hexlify(), fizz::testing::setPoint(), fizz::test::setPoint(), fizz::test::TEST(), TEST(), fizz::test::TEST_F(), fizz::testing::TEST_P(), TEST_P(), fizz::test::toIOBuf(), toIOBuf(), fizz::test::TYPED_TEST(), and unhexlify().

616  {
617  if (input.size() % 2 != 0) {
618  return false;
619  }
620  output.resize(input.size() / 2);
621  int j = 0;
622 
623  for (size_t i = 0; i < input.size(); i += 2) {
624  int highBits = detail::hexTable[static_cast<uint8_t>(input[i])];
625  int lowBits = detail::hexTable[static_cast<uint8_t>(input[i + 1])];
626  if ((highBits | lowBits) & 0x10) {
627  // One of the characters wasn't a hex digit
628  return false;
629  }
630  output[j++] = (highBits << 4) + lowBits;
631  }
632  return true;
633 }
const std::array< unsigned char, 256 > hexTable
Definition: String.cpp:120
template<class Collection , class T , class F >
auto folly::unorderedReduce ( Collection &&  c,
T &&  initial,
F &&  func 
) -> decltype(unorderedReduce( c.begin(), c.end(), std::forward<T>(initial), std::forward<F>(func)))

Sugar for the most common case.

Definition at line 479 of file helpers.h.

References c, and unorderedReduce().

484  {
485  return unorderedReduce(
486  c.begin(), c.end(), std::forward<T>(initial), std::forward<F>(func));
487 }
auto unorderedReduce(Collection &&c, T &&initial, F &&func) -> decltype(unorderedReduce(c.begin(), c.end(), std::forward< T >(initial), std::forward< F >(func)))
Sugar for the most common case.
Definition: helpers.h:479
char c
template<class It , class T , class F >
Future< T > folly::unorderedReduce ( It  first,
It  last,
T  initial,
func 
)

like reduce, but calls func on finished futures as they complete does NOT keep the order of the input

Definition at line 1881 of file Future-inl.h.

References exchange(), f, folly::gen::first, folly::Promise< T >::getFuture(), i, folly::InlineExecutor::instance(), lock(), folly::Future< T >::makeFuture, folly::gen::move, promise_, folly::pushmi::detail::t, and T.

Referenced by reduce(), TEST(), and unorderedReduce().

1881  {
1882  using ItF = typename std::iterator_traits<It>::value_type;
1883  using ItT = typename ItF::value_type;
1884  using Arg = MaybeTryArg<F, T, ItT>;
1885 
1886  if (first == last) {
1887  return makeFuture(std::move(initial));
1888  }
1889 
1890  typedef isTry<Arg> IsTry;
1891 
1892  struct Context {
1893  Context(T&& memo, F&& fn, size_t n)
1894  : lock_(),
1895  memo_(makeFuture<T>(std::move(memo))),
1896  func_(std::move(fn)),
1897  numThens_(0),
1898  numFutures_(n),
1899  promise_() {}
1900 
1901  folly::MicroSpinLock lock_; // protects memo_ and numThens_
1902  Future<T> memo_;
1903  F func_;
1904  size_t numThens_; // how many Futures completed and called .then()
1905  size_t numFutures_; // how many Futures in total
1906  Promise<T> promise_;
1907  };
1908 
1909  struct Fulfill {
1910  void operator()(Promise<T>&& p, T&& v) const {
1911  p.setValue(std::move(v));
1912  }
1913  void operator()(Promise<T>&& p, Future<T>&& f) const {
1914  f.setCallback_(
1915  [p = std::move(p)](Try<T>&& t) mutable { p.setTry(std::move(t)); });
1916  }
1917  };
1918 
1919  auto ctx = std::make_shared<Context>(
1920  std::move(initial), std::move(func), std::distance(first, last));
1921  for (size_t i = 0; first != last; ++first, ++i) {
1922  first->setCallback_([i, ctx](Try<ItT>&& t) {
1923  (void)i;
1924  // Futures can be completed in any order, simultaneously.
1925  // To make this non-blocking, we create a new Future chain in
1926  // the order of completion to reduce the values.
1927  // The spinlock just protects chaining a new Future, not actually
1928  // executing the reduce, which should be really fast.
1929  Promise<T> p;
1930  auto f = p.getFuture();
1931  {
1932  folly::MSLGuard lock(ctx->lock_);
1933  f = exchange(ctx->memo_, std::move(f));
1934  if (++ctx->numThens_ == ctx->numFutures_) {
1935  // After reducing the value of the last Future, fulfill the Promise
1936  ctx->memo_.setCallback_(
1937  [ctx](Try<T>&& t2) { ctx->promise_.setValue(std::move(t2)); });
1938  }
1939  }
1940  f.setCallback_(
1941  [ctx, mp = std::move(p), mt = std::move(t)](Try<T>&& v) mutable {
1942  if (v.hasValue()) {
1943  try {
1944  Fulfill{}(
1945  std::move(mp),
1946  ctx->func_(
1947  std::move(v.value()),
1948  mt.template get<IsTry::value, Arg&&>()));
1949  } catch (std::exception& e) {
1950  mp.setException(exception_wrapper(std::current_exception(), e));
1951  } catch (...) {
1952  mp.setException(exception_wrapper(std::current_exception()));
1953  }
1954  } else {
1955  mp.setTry(std::move(v));
1956  }
1957  });
1958  });
1959  }
1960  return ctx->promise_.getSemiFuture().via(&InlineExecutor::instance());
1961 }
#define T(v)
Definition: http_parser.c:233
auto f
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
std::lock_guard< MicroSpinLock > MSLGuard
STL namespace.
Future< T > makeFuture(Try< T > t)
Definition: Future-inl.h:1364
auto lock(SynchronizedLocker...lockersIn) -> std::tuple< typename SynchronizedLocker::LockedPtr... >
Definition: Synchronized.h:871
Promise< Unit > promise_
T exchange(T &obj, U &&new_value)
Definition: Utility.h:120
constexpr detail::First first
Definition: Base-inl.h:2553
static uint16_t folly::unpack ( uint8_t  lobyte,
uint8_t  hibyte 
)
inlinestatic

Definition at line 236 of file IPAddressV6.cpp.

References uint16_t.

Referenced by unpackInto().

236  {
237  return uint16_t((uint16_t(hibyte) << 8) | lobyte);
238 }
static void folly::unpackInto ( const unsigned char *  src,
uint16_t dest,
size_t  count 
)
inlinestatic

Definition at line 243 of file IPAddressV6.cpp.

References count, i, and unpack().

Referenced by folly::IPAddressV6::getIPv4For6To4(), and folly::IPAddressV6::type().

243  {
244  for (size_t i = 0, hi = 1, lo = 0; i < count; i++) {
245  dest[i] = unpack(src[hi], src[lo]);
246  hi += 2;
247  lo += 2;
248  }
249 }
dest
Definition: upload.py:394
static uint16_t unpack(uint8_t lobyte, uint8_t hibyte)
int * count
WriteFlags folly::unSet ( WriteFlags  a,
WriteFlags  b 
)
inline
template<typename Tuple >
auto folly::unwrapTryTuple ( Tuple &&  )

Tuple<Try<Type>...> -> std::tuple<Type...>

Unwraps a tuple-like type containing a sequence of Try<Type> instances to std::tuple<Type>

Definition at line 320 of file Try-inl.h.

References type, and folly::try_detail::unwrapTryTupleImpl().

Referenced by collect(), and TEST().

320  {
321  using TupleDecayed = typename std::decay<Tuple>::type;
323  return try_detail::unwrapTryTupleImpl(Seq{}, std::forward<Tuple>(instance));
324 }
PskType type
make_integer_sequence< std::size_t, Size > make_index_sequence
Definition: Utility.h:209
auto unwrapTryTupleImpl(folly::index_sequence< Indices... >, Tuple &&instance)
Definition: Try-inl.h:312
template<class String >
String folly::uriEscape ( StringPiece  str,
UriEscapeMode  mode = UriEscapeMode::ALL 
)

Similar to uriEscape above, but returns the escaped string.

Definition at line 137 of file String.h.

References ALL, mode, uriEscape(), and uriUnescape().

137  {
138  String out;
139  uriEscape(str, out, mode);
140  return out;
141 }
folly::Optional< PskKeyExchangeMode > mode
String uriEscape(StringPiece str, UriEscapeMode mode=UriEscapeMode::ALL)
Definition: String.h:137
template<class String >
void folly::uriEscape ( StringPiece  str,
String &  out,
UriEscapeMode  mode 
)

Definition at line 166 of file String-inl.h.

References folly::Range< Iter >::begin(), c, folly::Range< Iter >::end(), LIKELY, mode, QUERY, folly::Range< Iter >::size(), folly::detail::uriEscapeTable, and v.

Referenced by TEST(), and uriEscape().

166  {
167  static const char hexValues[] = "0123456789abcdef";
168  char esc[3];
169  esc[0] = '%';
170  // Preallocate assuming that 25% of the input string will be escaped
171  out.reserve(out.size() + str.size() + 3 * (str.size() / 4));
172  auto p = str.begin();
173  auto last = p; // last regular character
174  // We advance over runs of passthrough characters and copy them in one go;
175  // this is faster than calling push_back repeatedly.
176  unsigned char minEncode = static_cast<unsigned char>(mode);
177  while (p != str.end()) {
178  char c = *p;
179  unsigned char v = static_cast<unsigned char>(c);
180  unsigned char discriminator = detail::uriEscapeTable[v];
181  if (LIKELY(discriminator <= minEncode)) {
182  ++p;
183  } else if (mode == UriEscapeMode::QUERY && discriminator == 3) {
184  out.append(&*last, size_t(p - last));
185  out.push_back('+');
186  ++p;
187  last = p;
188  } else {
189  out.append(&*last, size_t(p - last));
190  esc[1] = hexValues[v >> 4];
191  esc[2] = hexValues[v & 0x0f];
192  out.append(esc, 3);
193  ++p;
194  last = p;
195  }
196  }
197  out.append(&*last, size_t(p - last));
198 }
const std::array< unsigned char, 256 > uriEscapeTable
Definition: String.cpp:122
auto v
#define LIKELY(x)
Definition: Likely.h:47
folly::Optional< PskKeyExchangeMode > mode
char c
template<class String >
String folly::uriUnescape ( StringPiece  str,
UriEscapeMode  mode = UriEscapeMode::ALL 
)

Similar to uriUnescape above, but returns the unescaped string.

Definition at line 159 of file String.h.

References backslashify(), FOLLY_PRINTF_FORMAT, FOLLY_PRINTF_FORMAT_ATTR, format(), mode, gmock_output_test::output, string, stringAppendf(), stringPrintf(), stringVAppendf(), stringVPrintf(), and uriUnescape().

159  {
160  String out;
161  uriUnescape(str, out, mode);
162  return out;
163 }
String uriUnescape(StringPiece str, UriEscapeMode mode=UriEscapeMode::ALL)
Definition: String.h:159
folly::Optional< PskKeyExchangeMode > mode
template<class String >
void folly::uriUnescape ( StringPiece  str,
String &  out,
UriEscapeMode  mode = UriEscapeMode::ALL 
)

URI-unescape a string. Appends the result to the output string.

In QUERY mode, '+' are replaced by space. XX sequences are decoded if XX is a valid hex sequence, otherwise we throw invalid_argument.

Definition at line 201 of file String-inl.h.

References folly::Range< Iter >::begin(), c, folly::Range< Iter >::end(), FOLLY_FALLTHROUGH, folly::detail::hexTable, QUERY, folly::Range< Iter >::size(), and UNLIKELY.

Referenced by proxygen::HTTPMessage::getDecodedQueryParam(), TEST(), uriEscape(), and uriUnescape().

201  {
202  out.reserve(out.size() + str.size());
203  auto p = str.begin();
204  auto last = p;
205  // We advance over runs of passthrough characters and copy them in one go;
206  // this is faster than calling push_back repeatedly.
207  while (p != str.end()) {
208  char c = *p;
209  switch (c) {
210  case '%': {
211  if (UNLIKELY(std::distance(p, str.end()) < 3)) {
212  throw std::invalid_argument("incomplete percent encode sequence");
213  }
214  auto h1 = detail::hexTable[static_cast<unsigned char>(p[1])];
215  auto h2 = detail::hexTable[static_cast<unsigned char>(p[2])];
216  if (UNLIKELY(h1 == 16 || h2 == 16)) {
217  throw std::invalid_argument("invalid percent encode sequence");
218  }
219  out.append(&*last, size_t(p - last));
220  out.push_back((h1 << 4) | h2);
221  p += 3;
222  last = p;
223  break;
224  }
225  case '+':
226  if (mode == UriEscapeMode::QUERY) {
227  out.append(&*last, size_t(p - last));
228  out.push_back(' ');
229  ++p;
230  last = p;
231  break;
232  }
233  // else fallthrough
235  default:
236  ++p;
237  break;
238  }
239  }
240  out.append(&*last, size_t(p - last));
241 }
folly::Optional< PskKeyExchangeMode > mode
const std::array< unsigned char, 256 > hexTable
Definition: String.cpp:120
#define UNLIKELY(x)
Definition: Likely.h:48
char c
#define FOLLY_FALLTHROUGH
Definition: CppAttributes.h:63
bool folly::usingJEMalloc ( )
inlinenoexcept

Determine if we are using jemalloc or not.

Definition at line 147 of file Malloc.h.

References counter, dallocx, mallctl, mallctlbymib, mallctlnametomib, mallocx, nallocx, folly::pushmi::__adl::noexcept(), ptr, rallocx, sallocx, sdallocx, uint64_t, and xallocx.

Referenced by folly::fbvector< T, Allocator >::emplace_back_aux(), folly::detail::MemoryIdler::flushLocalMallocCaches(), goodMallocSize(), folly::JemallocHugePageAllocator::init(), main(), folly::detail::mallctlHelper(), folly::TypedIOBuf< T >::push(), folly::threadlocal_detail::StaticMetaBase::reallocate(), folly::fbvector< HTTPHeaderCode >::reserve_in_place(), folly::IOBuf::reserveSlow(), folly::fbvector< HTTPHeaderCode >::shrink_to_fit(), and TEST().

147  {
148  // Checking for rallocx != nullptr is not sufficient; we may be in a
149  // dlopen()ed module that depends on libjemalloc, so rallocx is resolved, but
150  // the main program might be using a different memory allocator.
151  // How do we determine that we're using jemalloc? In the hackiest
152  // way possible. We allocate memory using malloc() and see if the
153  // per-thread counter of allocated memory increases. This makes me
154  // feel dirty inside. Also note that this requires jemalloc to have
155  // been compiled with --enable-stats.
156  static const bool result = []() noexcept {
157  // Some platforms (*cough* OSX *cough*) require weak symbol checks to be
158  // in the form if (mallctl != nullptr). Not if (mallctl) or if (!mallctl)
159  // (!!). http://goo.gl/xpmctm
160  if (mallocx == nullptr || rallocx == nullptr || xallocx == nullptr ||
161  sallocx == nullptr || dallocx == nullptr || sdallocx == nullptr ||
162  nallocx == nullptr || mallctl == nullptr ||
163  mallctlnametomib == nullptr || mallctlbymib == nullptr) {
164  return false;
165  }
166 
167  // "volatile" because gcc optimizes out the reads from *counter, because
168  // it "knows" malloc doesn't modify global state...
169  /* nolint */ volatile uint64_t* counter;
170  size_t counterLen = sizeof(uint64_t*);
171 
172  if (mallctl(
173  "thread.allocatedp",
174  static_cast<void*>(&counter),
175  &counterLen,
176  nullptr,
177  0) != 0) {
178  return false;
179  }
180 
181  if (counterLen != sizeof(uint64_t*)) {
182  return false;
183  }
184 
185  uint64_t origAllocated = *counter;
186 
187  static const void* volatile ptr = malloc(1);
188  if (!ptr) {
189  // wtf, failing to allocate 1 byte
190  return false;
191  }
192 
193  return (origAllocated != *counter);
194  }
195  ();
196 
197  return result;
198 }
void * ptr
void(* dallocx)(void *, int)
Definition: MallocImpl.cpp:39
requires E e noexcept(noexcept(s.error(std::move(e))))
int(* mallctlbymib)(const size_t *, size_t, void *, size_t *, void *, size_t)
Definition: MallocImpl.cpp:44
size_t(* xallocx)(void *, size_t, size_t, int)
Definition: MallocImpl.cpp:37
size_t(* nallocx)(size_t, int)
Definition: MallocImpl.cpp:41
int(* mallctl)(const char *, void *, size_t *, void *, size_t)
Definition: MallocImpl.cpp:42
void(* sdallocx)(void *, size_t, int)
Definition: MallocImpl.cpp:40
void *(* mallocx)(size_t, int)
Definition: MallocImpl.cpp:35
size_t(* sallocx)(const void *, int)
Definition: MallocImpl.cpp:38
std::atomic< int > counter
int(* mallctlnametomib)(const char *, size_t *, size_t *)
Definition: MallocImpl.cpp:43
void *(* rallocx)(void *, size_t, int)
Definition: MallocImpl.cpp:36
char32_t folly::utf8ToCodePoint ( const unsigned char *&  p,
const unsigned char *const  e,
bool  skipOnError 
)

Definition at line 52 of file Unicode.cpp.

References i, folly::gen::skip(), and uint32_t.

Referenced by folly::json::escapeStringImpl(), testInvalid(), and testValid().

55  {
56  /* The following encodings are valid, except for the 5 and 6 byte
57  * combinations:
58  * 0xxxxxxx
59  * 110xxxxx 10xxxxxx
60  * 1110xxxx 10xxxxxx 10xxxxxx
61  * 11110xxx 10xxxxxx 10xxxxxx 10xxxxxx
62  * 111110xx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
63  * 1111110x 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx 10xxxxxx
64  */
65 
66  const auto skip = [&] {
67  ++p;
68  return U'\ufffd';
69  };
70 
71  if (p >= e) {
72  if (skipOnError) {
73  return skip();
74  }
75  throw std::runtime_error("folly::utf8ToCodePoint empty/invalid string");
76  }
77 
78  unsigned char fst = *p;
79  if (!(fst & 0x80)) {
80  // trivial case
81  return *p++;
82  }
83 
84  static const uint32_t bitMask[] = {
85  (1 << 7) - 1,
86  (1 << 11) - 1,
87  (1 << 16) - 1,
88  (1 << 21) - 1,
89  };
90 
91  // upper control bits are masked out later
92  uint32_t d = fst;
93 
94  if ((fst & 0xC0) != 0xC0) {
95  if (skipOnError) {
96  return skip();
97  }
98  throw std::runtime_error(
99  to<std::string>("folly::utf8ToCodePoint i=0 d=", d));
100  }
101 
102  fst <<= 1;
103 
104  for (unsigned int i = 1; i != 4 && p + i < e; ++i) {
105  const unsigned char tmp = p[i];
106 
107  if ((tmp & 0xC0) != 0x80) {
108  if (skipOnError) {
109  return skip();
110  }
111  throw std::runtime_error(to<std::string>(
112  "folly::utf8ToCodePoint i=", i, " tmp=", (uint32_t)tmp));
113  }
114 
115  d = (d << 6) | (tmp & 0x3F);
116  fst <<= 1;
117 
118  if (!(fst & 0x80)) {
119  d &= bitMask[i];
120 
121  // overlong, could have been encoded with i bytes
122  if ((d & ~bitMask[i - 1]) == 0) {
123  if (skipOnError) {
124  return skip();
125  }
126  throw std::runtime_error(
127  to<std::string>("folly::utf8ToCodePoint i=", i, " d=", d));
128  }
129 
130  // check for surrogates only needed for 3 bytes
131  if (i == 2) {
132  if ((d >= 0xD800 && d <= 0xDFFF) || d > 0x10FFFF) {
133  if (skipOnError) {
134  return skip();
135  }
136  throw std::runtime_error(
137  to<std::string>("folly::utf8ToCodePoint i=", i, " d=", d));
138  }
139  }
140 
141  p += i + 1;
142  return d;
143  }
144  }
145 
146  if (skipOnError) {
147  return skip();
148  }
149  throw std::runtime_error("folly::utf8ToCodePoint encoding length maxed out");
150 }
detail::Skip skip(size_t count)
Definition: Base-inl.h:2598
template<typename T , template< typename > class Atom>
uint64_t folly::value ( const typename LockFreeRingBuffer< T, Atom >::Cursor &  rbcursor)
Examples:
/facebook/proxygen/proxygen/folly/folly/lang/RValueReferenceWrapper.h.

Definition at line 96 of file LockFreeRingBufferTest.cpp.

References Atom, ticket, and uint64_t.

Referenced by folly::compression::BitVectorEncoder< Value, SkipValue, kSkipQuantum, kForwardQuantum >::add(), folly::compression::EliasFanoEncoderV2< Value, SkipValue, kSkipQuantum, kForwardQuantum >::add(), folly::FutureExecutor< ExecutorImpl >::addFuture(), folly::fibers::TaskIterator< T >::addTask(), folly::fibers::FiberManager::addTaskFinally(), allocationBytesForOverAligned(), folly::gen::detail::Interleave< Container >::Generator< Value, Source >::apply(), folly::gen::detail::Zip< Container >::Generator< Value1, Source, Value2, Result >::apply(), folly::gen::detail::PMap< Predicate >::Generator< Value, Source, Input, Output >::apply(), folly::DynamicParser::arrayItems(), folly::expected_detail::ExpectedStorage< Value, Error >::assign(), folly::expected_detail::ExpectedStorage< Value, Error, StorageType::eUnion >::assign(), folly::expected_detail::ExpectedStorage< Value, Error, StorageType::ePODStruct >::assign(), folly::expected_detail::ExpectedStorage< Value, Error, StorageType::eUnion >::assignValue(), folly::detail::avgHelper(), folly::fibers::TaskIterator< T >::awaitNext(), BENCHMARK(), folly::AsyncUDPSocket::bind(), folly::Bits< T, Traits >::blockCount(), folly::gen::detail::PMap< Predicate >::Generator< Value, Source, Input, Output >::ExecutionPipeline::blockingWrite(), folly::detail::chronoRangeCheck(), folly::Optional< Value >::StorageNonTriviallyDestructible::clear(), folly::expected_detail::ExpectedStorage< Value, Error, StorageType::eUnion >::clear(), folly::fibers::collectAll(), folly::fibers::collectAny(), folly::fibers::collectN(), non_atomic< T >::compare_exchange_strong(), non_atomic< T >::compare_exchange_weak(), folly::gen::detail::Parallel< Ops >::Generator< Input, Source, InputDecayed, Composed, Output, OutputDecayed >::Pusher< all >::compose(), folly::SSLServerAcceptCallbackDelay::connAccepted(), folly::detail::convertTo(), copy(), folly::io::compression::detail::dataStartsWithLE(), folly::exception_wrapper_detail::dont_slice(), folly::Optional< NamedGroup >::emplace(), folly::AtomicUnorderedInsertMap< Key, Value, Hash, KeyEqual, SkipKeyValueDeletion, Atom, IndexType, Allocator >::emplace(), folly::detail::enforceWhitespace(), folly::detail::errorValue(), folly::TDigest::estimateQuantile(), estimateSpaceNeeded(), folly::exception_wrapper::exception_wrapper(), folly::Expected< int, E >::Expected(), folly::detail::SignedValueHandler< T, false >::finalize(), folly::gen::detail::PMap< Predicate >::Generator< Value, Source, Input, Output >::foreach(), folly::settings::Snapshot::forEachSetting(), folly::experimental::EnvironmentState::fromCurrentEnvironment(), folly::padded::Adaptor< IntNodeVec >::fullNode(), folly::Future< folly::folly::Unit >::Future(), folly::FutureExecutor< ExecutorImpl >::FutureExecutor(), folly::compression::generateRandomList(), folly::Try< folly::folly::Unit >::get(), folly::coro::get_awaiter(), get_default(), get_ref_default(), folly::LogCategory::getLevelInfo(), folly::detail::HistogramBuckets< ValueType, ContainerType >::getNumBuckets(), folly::LogName::hash(), folly::detail::ReadMostlySharedPtrCore< T, DefaultRefCount >::increfWeak(), folly::Indestructible< T >::Indestructible(), folly::sorted_vector_set< folly::RequestData * >::insert(), folly::sorted_vector_map< Key, Value, Compare, Allocator, GrowthPolicy, Container >::insert(), folly::detail::insert_with_hint(), folly::InlineExecutor::instance(), folly::poly::INullablePointer::Interface< Base >::Interface(), folly::for_each_detail::invoke_returning_loop_control(), is_const(), join(), folly::gen::just(), non_atomic< T >::load(), loadUnaligned(), logConfigToDynamic(), Application::loop(), makeConversionError(), makePromiseContract(), folly::futures::map(), folly::TimeseriesHistogram< T, CT, C >::maybeHandleSingleUniqueValue(), SimpleDigest< MergeSize >::merge(), folly::pushmi::__adl::noexcept(), folly::NonDefaultConstructibleMutex::NonDefaultConstructibleMutex(), folly::DynamicParser::objectItems(), folly::gen::Get< n >::operator()(), folly::gen::Cast< Dest >::operator()(), folly::gen::To< Dest >::operator()(), folly::gen::TryTo< Dest >::operator()(), folly::detail::ReturnUnit< Error >::operator()(), folly::Try< folly::folly::Unit >::operator*(), folly::Optional< NamedGroup >::operator*(), folly::Try< void >::operator*(), folly::Expected< int, E >::operator*(), folly::TLRefCount::operator++(), operator+=(), operator-=(), folly::Try< folly::folly::Unit >::operator->(), folly::Optional< NamedGroup >::operator->(), folly::Expected< int, E >::operator->(), operator<<(), folly::poly::INullablePointer::Interface< Base >::operator=(), folly::F14VectorSet< Key, Hasher, KeyEqual, Alloc >::operator=(), folly::F14VectorMap< Key, Mapped, Hasher, KeyEqual, Alloc >::operator=(), CheckedInt::operator=(), folly::DynamicParser::optional(), folly::DynamicParser::ParserStack::ParserStack(), folly::detail::parseToWrap(), partialLoadUnaligned(), poly_empty(), poly_move(), prettyToDouble(), folly::FileWriterFactory::processOption(), folly::TimeseriesHistogram< T, CT, C >::rate(), folly::detail::rawOverAlignedImpl(), folly::Replaceable< T >::Replaceable(), folly::DynamicParser::required(), folly::EventBase::SmoothLoopTime::reset(), folly::futures::detail::retryingImpl(), folly::coro::detail::TaskPromise< T >::return_value(), rref(), folly::test::run_timed_wait_regular_test(), folly::settings::detail::saveValueForOutstandingSnapshots(), folly::SemiFuture< T >::SemiFuture(), folly::DynamicParser::setAllowNonStringKeyErrors(), folly::FlatCombining< T, Mutex, Atom, Req >::Rec::setFn(), folly::EventBase::setMaxLatency(), folly::AsyncSocket::setNoDelay(), folly::AsyncSocket::setQuickAck(), folly::SharedPromise< folly::folly::Unit >::setValue(), folly::coro::TimedWaitAwaitable< Awaitable >::SharedState::setValue(), folly::Promise< folly::folly::Unit >::setValue(), folly::AtomicHashMap< KeyT, ValueT, HashFcn, EqualFcn, Allocator, ProbeFcn, KeyConvertFcn >::SimpleRetT::SimpleRetT(), folly::compression::BitVectorReader< Encoder, Instructions, kUnchecked >::skipTo(), folly::EventBase::SmoothLoopTime::SmoothLoopTime(), folly::detail::splitFixed(), splitTo(), folly::Optional< NamedGroup >::swap(), folly::test::TEST(), TEST(), TEST(), TEST_F(), TEST_F(), testFiberLocal(), folly::compression::testJumpTo(), testRangeFunc(), folly::compression::testSkipTo(), folly::sync_tests::testUnlock(), folly::sync_tests::testUnlockCommon(), folly::expected_detail::expected_detail_ExpectedHelper::ExpectedHelper::then_(), folly::expected_detail::expected_detail_ExpectedHelper::ExpectedHelper::thenOrThrow_(), folly::settings::detail::SettingCore< T >::tlValue(), folly::settings::detail::SettingCore< T >::tlValueSlow(), to(), toAppend(), toAppendStrImpl(), folly::experimental::EnvironmentState::toPointerArray(), folly::Try< folly::folly::Unit >::Try(), folly::RWSpinLock::try_lock_shared(), folly::RWSpinLock::try_lock_upgrade(), tryDecodeVarint(), tryTo(), folly::MacAddress::u64HBO(), folly::futures::detail::FutureBase< T >::valid(), AtomicBatchDispatcherTesting::validateResults(), folly::detail::distributed_mutex::wake(), folly::SemiFuture< T >::within(), folly::detail::LifoSemHead::withPush(), folly::detail::LifoSemHead::withValueDecr(), folly::gen::detail::PMap< Predicate >::Generator< Value, Source, Input, Output >::ExecutionPipeline::write(), folly::LockFreeRingBuffer< T, Atom >::write(), folly::detail::RingBufferSlot< T, Atom >::write(), folly::io::detail::Writable< Appender >::write(), folly::io::QueueAppender::write(), folly::LockFreeRingBuffer< T, Atom >::writeAndGetCursor(), folly::detail::writeIntegerString(), folly::io::QueueAppender::writeSlow(), folly::coro::detail::BlockingWaitPromise< T & >::yield_value(), folly::detail::BufferedStat< folly::TDigest, ClockT >::~BufferedStat(), folly::StandardLogHandlerFactory::OptionProcessor::~OptionProcessor(), and folly::detail::SingleElementQueue< T, Atom >::~SingleElementQueue().

96  {
97  typedef typename LockFreeRingBuffer<T, Atom>::Cursor RBCursor;
98 
99  struct ExposedCursor : RBCursor {
100  ExposedCursor(const RBCursor& cursor) : RBCursor(cursor) {}
101  uint64_t value() {
102  return this->ticket;
103  }
104  };
105  return ExposedCursor(rbcursor).value();
106 }
static constexpr StringPiece ticket
uint64_t value(const typename LockFreeRingBuffer< T, Atom >::Cursor &rbcursor)
template<typename Variant , typename... Cases>
decltype(auto) folly::variant_match ( Variant &&  variant,
Cases &&...  cases 
)
template<class C >
Formatter<true, C> folly::vformat ( StringPiece  fmt,
C &&  container 
)
template<class Container >
Formatter<true, Container> folly::vformat ( StringPiece  fmt,
Container &&  container 
)

Create a formatter object that takes one argument (of container type) and uses that container to get argument values from.

std::map<string, string> map { {"hello", "world"}, {"answer", "42"} };

The following are equivalent: format("{0[hello]} {0[answer]}", map);

vformat("{hello} {answer}", map);

but the latter is cleaner.

Definition at line 298 of file Format.h.

298  {
299  return Formatter<true, Container>(fmt, std::forward<Container>(container));
300 }
template<class Str , class Container >
std::enable_if<IsSomeString<Str>::value>::type folly::vformat ( Str *  out,
StringPiece  fmt,
Container &&  container 
)

Append vformatted output to a string.

Definition at line 378 of file Format.h.

References testing::Args(), folly::format_value::formatFormatter(), folly::format_value::formatNumber(), folly::format_value::formatString(), and val.

Referenced by svformat(), and vformatChecked().

378  {
379  vformat(fmt, std::forward<Container>(container)).appendTo(*out);
380 }
std::enable_if< IsSomeString< Str >::value >::type vformat(Str *out, StringPiece fmt, Container &&container)
Definition: Format.h:378
template<class Container >
Formatter<true, Container> folly::vformatChecked ( StringPiece  fmt,
Container &&  container 
)

Definition at line 473 of file Format.h.

References vformat().

475  {
476  return vformat(fmt, std::forward<Container>(container));
477 }
std::enable_if< IsSomeString< Str >::value >::type vformat(Str *out, StringPiece fmt, Container &&container)
Definition: Format.h:378
template<class Str , class Container >
std::enable_if<IsSomeString<Str>::value>::type folly::vformatChecked ( Str *  out,
StringPiece  fmt,
Container &&  container 
)

Definition at line 489 of file Format.h.

References FOLLY_POP_WARNING.

Referenced by svformatChecked().

489  {
490  vformatChecked(fmt, std::forward<Container>(container)).appendTo(*out);
491 }
std::enable_if< IsSomeString< Str >::value >::type vformatChecked(Str *out, StringPiece fmt, Container &&container)
Definition: Format.h:489
template<class Func >
auto folly::via ( Executor ,
Func &&  func 
) -> Future< typename isFutureOrSemiFuture< decltype(std::declval< Func >()())>::Inner >

Execute a function via the given executor and return a future. This is semantically equivalent to via(executor).then(func), but easier to read and slightly more efficient.

Definition at line 1290 of file Future-inl.h.

References f, and folly::Future< T >::via().

Referenced by wangle::ServerBootstrap< DefaultPipeline >::bind(), fGen(), folly::Future< folly::folly::Unit >::Future(), keepAliveTest(), folly::futures::map(), folly::SemiFuture< T >::SemiFuture(), TEST(), TEST_F(), folly::Future< folly::folly::Unit >::then(), virtualExecutorTest(), and WeakRefTest().

1291  {
1292  // TODO make this actually more performant. :-P #7260175
1293  return via(x).thenValue([f = std::forward<Func>(func)](auto&&) mutable {
1294  return std::forward<Func>(f)();
1295  });
1296 }
Definition: InvokeTest.cpp:58
auto f
Future< Unit > via(Executor::KeepAlive<> executor, int8_t priority)
Definition: Future-inl.h:1373
template<class Func >
auto folly::via ( Executor::KeepAlive<>  x,
Func &&  func 
) -> Future< typename isFutureOrSemiFuture< decltype(std::declval< Func >()())>::Inner >

Definition at line 1299 of file Future-inl.h.

References f, folly::gen::move, and folly::Future< T >::via().

1300  {
1301  return via(std::move(x))
1302  .thenValue([f = std::forward<Func>(func)](auto&&) mutable {
1303  return std::forward<Func>(f)();
1304  });
1305 }
Definition: InvokeTest.cpp:58
auto f
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
Future< Unit > via(Executor::KeepAlive<> executor, int8_t priority)
Definition: Future-inl.h:1373
Future< Unit > folly::via ( Executor executor,
int8_t  priority 
)
inline

Definition at line 1369 of file Future-inl.h.

References folly::Future< T >::makeFuture.

1369  {
1370  return makeFuture().via(executor, priority);
1371 }
PUSHMI_INLINE_VAR constexpr __adl::get_executor_fn executor
Future< T > makeFuture(Try< T > t)
Definition: Future-inl.h:1364
Future< Unit > folly::via ( Executor::KeepAlive<>  executor,
int8_t  priority 
)
inline

Definition at line 1373 of file Future-inl.h.

References FOLLY_ALWAYS_INLINE, FOLLY_ATTR_VISIBILITY_HIDDEN, folly::Future< T >::makeFuture, and folly::gen::move.

1373  {
1374  return makeFuture().via(std::move(executor), priority);
1375 }
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
PUSHMI_INLINE_VAR constexpr __adl::get_executor_fn executor
Future< T > makeFuture(Try< T > t)
Definition: Future-inl.h:1364
template<class F >
Future<Unit> folly::when ( bool  p,
F &&  thunk 
)
template<class P , class F >
Future<Unit> folly::whileDo ( P &&  predicate,
F &&  thunk 
)

Carry out the computation contained in the given future if while the predicate continues to hold.

thunk behaves like std::function<Future<T2>(void)>

predicate behaves like std::function<bool(void)>

Definition at line 2335 of file Future-inl.h.

References folly::Future< T >::makeFuture, folly::gen::move, and folly::Future< T >::whileDo.

Referenced by folly::Future< folly::folly::Unit >::Future(), TEST(), and times().

2335  {
2336  if (predicate()) {
2337  auto future = thunk();
2338  return std::move(future).thenValue(
2339  [predicate = std::forward<P>(predicate),
2340  thunk = std::forward<F>(thunk)](auto&&) mutable {
2341  return whileDo(std::forward<P>(predicate), std::forward<F>(thunk));
2342  });
2343  }
2344  return makeFuture();
2345 }
Future< Unit > whileDo(P &&predicate, F &&thunk)
Definition: Future-inl.h:2335
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
Future< T > makeFuture(Try< T > t)
Definition: Future-inl.h:1364
template<class Collection , class F , class ItT , class Result >
std::vector< Future< Result > > folly::window ( Collection  input,
func,
size_t  n 
)

window creates up to n Futures using the values in the collection, and then another Future for each Future that completes

this is basically a sliding window of Futures of size n

func must return a Future for each value in input

Definition at line 1789 of file Future-inl.h.

References folly::pushmi::executor, folly::QueuedImmediateExecutor::instance(), and folly::gen::move.

Referenced by collectN(), TEST(), and window().

1789  {
1790  // Use global QueuedImmediateExecutor singleton to avoid stack overflow.
1791  auto executor = &QueuedImmediateExecutor::instance();
1792  return window(executor, std::move(input), std::move(func), n);
1793 }
std::vector< Future< Result > > window(Executor::KeepAlive<> executor, Collection input, F func, size_t n)
Definition: Future-inl.h:1810
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
PUSHMI_INLINE_VAR constexpr __adl::get_executor_fn executor
template<class F >
auto folly::window ( size_t  times,
func,
size_t  n 
) -> std::vector<invoke_result_t<F, size_t>>

Definition at line 1796 of file Future-inl.h.

References folly::gen::move, folly::Future< T >::times, and window().

1797  {
1798  return window(futures::detail::WindowFakeVector(times), std::move(func), n);
1799 }
std::vector< Future< Result > > window(Executor::KeepAlive<> executor, Collection input, F func, size_t n)
Definition: Future-inl.h:1810
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
Future< Unit > times(const int n, F &&thunk)
Definition: Future-inl.h:2348
template<class Collection , class F , class ItT , class Result >
std::vector< Future< Result > > folly::window ( Executor executor,
Collection  input,
func,
size_t  n 
)

Definition at line 1803 of file Future-inl.h.

References getKeepAliveToken(), folly::gen::move, and window().

1803  {
1804  return window(
1805  getKeepAliveToken(executor), std::move(input), std::move(func), n);
1806 }
std::vector< Future< Result > > window(Executor::KeepAlive<> executor, Collection input, F func, size_t n)
Definition: Future-inl.h:1810
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
PUSHMI_INLINE_VAR constexpr __adl::get_executor_fn executor
Executor::KeepAlive< ExecutorT > getKeepAliveToken(ExecutorT *executor)
Definition: Executor.h:200
template<class Collection , class F , class ItT , class Result >
std::vector< Future< Result > > folly::window ( Executor::KeepAlive<>  executor,
Collection  input,
func,
size_t  n 
)

Definition at line 1810 of file Future-inl.h.

References folly::Executor::KeepAlive< ExecutorT >::copy(), folly::pushmi::executor, i, makeSemiFutureWith(), max, min, folly::gen::move, folly::pushmi::detail::t, and folly::Future< T >::via().

1810  {
1811  struct WindowContext {
1812  WindowContext(
1813  Executor::KeepAlive<> executor_,
1814  Collection&& input_,
1815  F&& func_)
1816  : executor(std::move(executor_)),
1817  input(std::move(input_)),
1818  promises(input.size()),
1819  func(std::move(func_)) {}
1820  std::atomic<size_t> i{0};
1821  Executor::KeepAlive<> executor;
1822  Collection input;
1823  std::vector<Promise<Result>> promises;
1824  F func;
1825 
1826  static void spawn(std::shared_ptr<WindowContext> ctx) {
1827  size_t i = ctx->i.fetch_add(1, std::memory_order_relaxed);
1828  if (i < ctx->input.size()) {
1829  auto fut = makeSemiFutureWith(
1830  [&] { return ctx->func(std::move(ctx->input[i])); })
1831  .via(ctx->executor.get());
1832 
1833  fut.setCallback_([ctx = std::move(ctx), i](Try<Result>&& t) mutable {
1834  ctx->promises[i].setTry(std::move(t));
1835  // Chain another future onto this one
1836  spawn(std::move(ctx));
1837  });
1838  }
1839  }
1840  };
1841 
1842  auto max = std::min(n, input.size());
1843 
1844  auto ctx = std::make_shared<WindowContext>(
1845  executor.copy(), std::move(input), std::move(func));
1846 
1847  // Start the first n Futures
1848  for (size_t i = 0; i < max; ++i) {
1849  executor->add([ctx]() mutable { WindowContext::spawn(std::move(ctx)); });
1850  }
1851 
1852  std::vector<Future<Result>> futures;
1853  futures.reserve(ctx->promises.size());
1854  for (auto& promise : ctx->promises) {
1855  futures.emplace_back(promise.getSemiFuture().via(executor.copy()));
1856  }
1857 
1858  return futures;
1859 }
std::enable_if< !(isFutureOrSemiFuture< invoke_result_t< F >>::value), SemiFuture< lift_unit_t< invoke_result_t< F > > > >::type makeSemiFutureWith(F &&func)
Definition: Future-inl.h:740
LogLevel max
Definition: LogLevel.cpp:31
constexpr detail::Map< Move > move
Definition: Base-inl.h:2567
STL namespace.
PUSHMI_INLINE_VAR constexpr __adl::get_executor_fn executor
constexpr auto size(C const &c) -> decltype(c.size())
Definition: Access.h:45
LogLevel min
Definition: LogLevel.cpp:30
Future< Unit > via(Executor::KeepAlive<> executor, int8_t priority)
Definition: Future-inl.h:1373
template<typename F >
static auto folly::with_unique_lock ( std::mutex m,
F &&  f 
) -> decltype(f())
static

Definition at line 29 of file ThreadedExecutor.cpp.

References f, lock(), and m.

Referenced by folly::ThreadedExecutor::add(), folly::ThreadedExecutor::controlJoinFinishedThreads(), folly::ThreadedExecutor::controlLaunchEnqueuedTasks(), folly::ThreadedExecutor::notify(), and folly::ThreadedExecutor::work().

29  {
30  std::unique_lock<std::mutex> lock(m);
31  return f();
32 }
auto f
auto lock(SynchronizedLocker...lockersIn) -> std::tuple< typename SynchronizedLocker::LockedPtr... >
Definition: Synchronized.h:871
static map< string, int > m
template<typename D , typename M , typename... Args>
auto folly::wlock ( Synchronized< D, M > &  synchronized,
Args &&...  args 
)

Helper functions that should be passed to either a lock() or synchronized() invocation, these return implementation defined structs that will be used to lock the synchronized instance appropriately.

lock(wlock(one), rlock(two), wlock(three)); synchronized([](auto one, two) { ... }, wlock(one), rlock(two));

For example in the above rlock() produces an implementation defined read locking helper instance and wlock() a write locking helper

Subsequent arguments passed to these locking helpers, after the first, will be passed by const-ref to the corresponding function on the synchronized instance. This means that if the function accepts these parameters by value, they will be copied. Note that it is not necessary that the primary locking function will be invoked at all (for eg. the implementation might just invoke the try*Lock() method)

// Try to acquire the lock for one second synchronized([](auto) { ... }, wlock(one, 1s));

// The timed lock acquire might never actually be called, if it is not // needed by the underlying deadlock avoiding algorithm synchronized([](auto, auto) { ... }, rlock(one), wlock(two, 1s));

Note that the arguments passed to to *lock() calls will be passed by const-ref to the function invocation, as the implementation might use them many times

Definition at line 1519 of file Synchronized.h.

References testing::Args(), Mutex, and folly::detail::wlock().

Referenced by folly::RequestContext::clearContextData(), folly::threadlocal_detail::StaticMetaBase::destroy(), folly::RequestContext::doSetContextData(), TEST(), TEST_F(), folly::SynchronizedPtr< PointerType, MutexType >::withWLock(), folly::SynchronizedBase< Subclass, detail::MutexLevel::SHARED >::withWLock(), and folly::SynchronizedBase< Subclass, detail::MutexLevel::SHARED >::withWLockPtr().

1519  {
1520  return detail::wlock(synchronized, std::forward<Args>(args)...);
1521 }
auto wlock(Synchronized< D, M > &synchronized, Args &&...args)
template<class Container >
bool folly::writeFile ( const Container &  data,
const char *  filename,
int  flags = O_WRONLY | O_CREAT | O_TRUNC,
mode_t  mode = 0666 
)

Writes container to file. The container is assumed to be contiguous, with element size equal to 1, and offering STL-like methods empty(), size(), and indexed access (e.g. std::vector<char>, std::string, fbstring, StringPiece).

"flags" dictates the open flags to use. Default is to create file if it doesn't exist and truncate it.

Returns: true on success or false on failure. In the latter case errno will be set appropriately by the failing system primitive.

Note that this function may leave the file in a partially written state on failure. Use writeFileAtomic() if you want to ensure that the existing file state will be unchanged on error.

Definition at line 211 of file FileUtil.h.

References closeNoInt(), data(), mode, writeFileAtomic(), writeFileAtomicNoThrow(), and writeFull().

Referenced by MultiFilePollerTest::delayedWrite(), WriteFileAfterFork::operator()(), folly::test::ReadFileFd::SetUp(), folly::test::TEST(), TEST(), and TEST_F().

215  {
216  static_assert(
217  sizeof(data[0]) == 1, "writeFile works with element size equal to 1");
218  int fd = open(filename, flags, mode);
219  if (fd == -1) {
220  return false;
221  }
222  bool ok = data.empty() ||
223  writeFull(fd, &data[0], data.size()) == static_cast<ssize_t>(data.size());
224  return closeNoInt(fd) == 0 && ok;
225 }
flags
Definition: http_parser.h:127
int closeNoInt(int fd)
Definition: FileUtil.cpp:56
folly::Optional< PskKeyExchangeMode > mode
ssize_t writeFull(int fd, const void *buf, size_t count)
Definition: FileUtil.cpp:134
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
void folly::writeFileAtomic ( StringPiece  filename,
iovec *  iov,
int  count,
mode_t  permissions = 0644 
)

Write file contents "atomically".

This writes the data to a temporary file in the destination directory, and then renames it to the specified path. This guarantees that the specified file will be replaced the the specified contents on success, or will not be modified on failure.

Note that on platforms that do not provide atomic filesystem rename functionality (e.g., Windows) this behavior may not be truly atomic.

Definition at line 224 of file FileUtil.cpp.

References folly::Range< Iter >::str(), string, and writeFileAtomicNoThrow().

Referenced by fizz::test::TEST(), folly::test::TEST_F(), writeFile(), and writeFileAtomic().

228  {
229  auto rc = writeFileAtomicNoThrow(filename, iov, count, permissions);
230  if (rc != 0) {
231  auto msg = std::string(__func__) + "() failed to update " + filename.str();
232  throw std::system_error(rc, std::generic_category(), msg);
233  }
234 }
int writeFileAtomicNoThrow(StringPiece filename, iovec *iov, int count, mode_t permissions)
Definition: FileUtil.cpp:158
int * count
const char * string
Definition: Conv.cpp:212
void folly::writeFileAtomic ( StringPiece  filename,
ByteRange  data,
mode_t  permissions 
)

Definition at line 236 of file FileUtil.cpp.

References folly::Range< Iter >::data(), folly::Range< Iter >::size(), and writeFileAtomic().

236  {
237  iovec iov;
238  iov.iov_base = const_cast<unsigned char*>(data.data());
239  iov.iov_len = data.size();
240  writeFileAtomic(filename, &iov, 1, permissions);
241 }
void writeFileAtomic(StringPiece filename, StringPiece data, mode_t permissions)
Definition: FileUtil.cpp:243
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
void folly::writeFileAtomic ( StringPiece  filename,
StringPiece  data,
mode_t  permissions 
)

Definition at line 243 of file FileUtil.cpp.

References writeFileAtomic().

246  {
247  writeFileAtomic(filename, ByteRange(data), permissions);
248 }
void writeFileAtomic(StringPiece filename, StringPiece data, mode_t permissions)
Definition: FileUtil.cpp:243
Range< const unsigned char * > ByteRange
Definition: Range.h:1163
static constexpr uint64_t data[1]
Definition: Fingerprint.cpp:43
int folly::writeFileAtomicNoThrow ( StringPiece  filename,
iovec *  iov,
int  count,
mode_t  permissions = 0644 
)

A version of writeFileAtomic() that returns an errno value instead of throwing on error.

Returns 0 on success or an errno value on error.

Definition at line 158 of file FileUtil.cpp.

References folly::netops::close(), folly::Range< Iter >::data(), SCOPE_EXIT, folly::Range< Iter >::size(), folly::detail::success, suffix, and writevFull().

Referenced by writeFile(), and writeFileAtomic().

162  {
163  // We write the data to a temporary file name first, then atomically rename
164  // it into place. This ensures that the file contents will always be valid,
165  // even if we crash or are killed partway through writing out data.
166  //
167  // Create a buffer that will contain two things:
168  // - A nul-terminated version of the filename
169  // - The temporary file name
170  std::vector<char> pathBuffer;
171  // Note that we have to explicitly pass in the size here to make
172  // sure the nul byte gets included in the data.
173  constexpr folly::StringPiece suffix(".XXXXXX\0", 8);
174  pathBuffer.resize((2 * filename.size()) + 1 + suffix.size());
175  // Copy in the filename and then a nul terminator
176  memcpy(pathBuffer.data(), filename.data(), filename.size());
177  pathBuffer[filename.size()] = '\0';
178  const char* const filenameCStr = pathBuffer.data();
179  // Now prepare the temporary path template
180  char* const tempPath = pathBuffer.data() + filename.size() + 1;
181  memcpy(tempPath, filename.data(), filename.size());
182  memcpy(tempPath + filename.size(), suffix.data(), suffix.size());
183 
184  auto tmpFD = mkstemp(tempPath);
185  if (tmpFD == -1) {
186  return errno;
187  }
188  bool success = false;
189  SCOPE_EXIT {
190  if (tmpFD != -1) {
191  close(tmpFD);
192  }
193  if (!success) {
194  unlink(tempPath);
195  }
196  };
197 
198  auto rc = writevFull(tmpFD, iov, count);
199  if (rc == -1) {
200  return errno;
201  }
202 
203  rc = fchmod(tmpFD, permissions);
204  if (rc == -1) {
205  return errno;
206  }
207 
208  // Close the file before renaming to make sure all data has
209  // been successfully written.
210  rc = close(tmpFD);
211  tmpFD = -1;
212  if (rc == -1) {
213  return errno;
214  }
215 
216  rc = rename(tempPath, filenameCStr);
217  if (rc == -1) {
218  return errno;
219  }
220  success = true;
221  return 0;
222 }
#define SCOPE_EXIT
Definition: ScopeGuard.h:274
ssize_t writevFull(int fd, iovec *iov, int count)
Definition: FileUtil.cpp:150
const char * suffix
Definition: String.cpp:272
int * count
int close(NetworkSocket s)
Definition: NetOps.cpp:90
ssize_t folly::writeFull ( int  fd,
const void *  buf,
size_t  n 
)

Similar to readFull and preadFull above, wrappers around write() and pwrite() that loop until all data is written.

Generally, the write() / pwrite() system call may always write fewer bytes than requested, just like read(). In certain cases (such as when writing to a pipe), POSIX provides stronger guarantees, but not in the general case. For example, Linux (even on a 64-bit platform) won't write more than 2GB in one write() system call.

Note that writevFull and pwritevFull require iov to be non-const, unlike writev and pwritev. The contents of iov after these functions return is unspecified.

These functions return -1 on error, or the total number of bytes written (which is always the same as the number of requested bytes) on success.

Definition at line 134 of file FileUtil.cpp.

References folly::fileutil_detail::wrapFull(), and fizz::detail::write().

Referenced by folly::LogCategory::admitMessage(), folly::detail::assertionFailure(), folly::LoggerDB::defaultInternalWarningImpl(), folly::symbolizer::FDSymbolizePrinter::doPrint(), folly::symbolizer::FDSymbolizePrinter::flush(), folly::AsyncFileWriter::performIO(), wangle::FilePersistenceLayer< K, V >::persist(), shutdownNoInt(), TEST(), TEST_F(), testInvalidFile(), testValidFile(), TYPED_TEST(), folly::symbolizer::test::writeAll(), writeFile(), and folly::ImmediateFileWriter::writeMessage().

134  {
135  return wrapFull(write, fd, const_cast<void*>(buf), count);
136 }
void write(const T &in, folly::io::Appender &appender)
Definition: Types-inl.h:112
ssize_t wrapFull(F f, int fd, void *buf, size_t count, Offset...offset)
int * count
ssize_t folly::writeNoInt ( int  fd,
const void *  buf,
size_t  count 
)

Definition at line 114 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt(), and fizz::detail::write().

Referenced by folly::AsyncPipeWriter::handleWrite(), folly::Subprocess::pid(), shutdownNoInt(), and TEST().

114  {
115  return wrapNoInt(write, fd, buf, count);
116 }
ssize_t wrapNoInt(F f, Args...args)
void write(const T &in, folly::io::Appender &appender)
Definition: Types-inl.h:112
int * count
template<class Derived , bool containerMode, class... Args>
void folly::writeTo ( FILE fp,
const BaseFormatter< Derived, containerMode, Args... > &  formatter 
)

Formatter objects can be written to stdio FILEs.

Definition at line 283 of file Format-inl.h.

References throwSystemError().

Referenced by operator<<(), and TEST().

285  {
286  auto writer = [fp](StringPiece sp) {
287  size_t n = fwrite(sp.data(), 1, sp.size(), fp);
288  if (n < sp.size()) {
289  throwSystemError("Formatter writeTo", "fwrite failed");
290  }
291  };
292  formatter(writer);
293 }
void throwSystemError(Args &&...args)
Definition: Exception.h:76
Range< const char * > StringPiece
ssize_t folly::writevFull ( int  fd,
iovec *  iov,
int  count 
)

Definition at line 150 of file FileUtil.cpp.

References folly::fileutil_detail::wrapvFull().

Referenced by folly::AsyncFileWriter::performIO(), shutdownNoInt(), and writeFileAtomicNoThrow().

150  {
151  return wrapvFull(writev, fd, iov, count);
152 }
ssize_t wrapvFull(F f, int fd, iovec *iov, int count, Offset...offset)
int * count
ssize_t folly::writevNoInt ( int  fd,
const iovec *  iov,
int  count 
)

Definition at line 122 of file FileUtil.cpp.

References folly::fileutil_detail::wrapNoInt().

Referenced by shutdownNoInt().

122  {
123  return wrapNoInt(writev, fd, iov, count);
124 }
ssize_t wrapNoInt(F f, Args...args)
int * count
constexpr bool folly::xlogIsDirSeparator ( char  c)

Definition at line 508 of file xlog.h.

References kIsWindows, and folly::detail::xlogStripFilenameRecursive().

Referenced by folly::detail::xlogStripFilenameMatchFound(), and folly::detail::xlogStripFilenameRecursive().

508  {
509  return c == '/' || (kIsWindows && c == '\\');
510 }
constexpr auto kIsWindows
Definition: Portability.h:367
char c
constexpr const char* folly::xlogStripFilename ( const char *  filename,
const char *  prefixes 
)

Strip directory prefixes from a filename before using it in XLOG macros.

This is primarily used to strip off the initial project directory path for projects that invoke the compiler with absolute path names.

The filename argument is the filename to process. This is normally the contents of the FILE macro from the invoking file.

prefixes is a colon-separated list of directory prefixes to strip off if present at the beginning of the filename. The prefix list is searched in order, and only the first match found will be stripped.

e.g., xlogStripFilename("/my/project/src/foo.cpp", "/tmp:/my/project") would return "src/foo.cpp"

Definition at line 575 of file xlog.h.

References folly::detail::xlogStripFilenameRecursive().

Referenced by TEST().

577  {
578  return detail::xlogStripFilenameRecursive(filename, prefixes, 0, 0, true);
579 }
constexpr const char * xlogStripFilenameRecursive(const char *filename, const char *prefixes, size_t prefixIdx, size_t filenameIdx, bool match)
Definition: xlog.h:531

Variable Documentation

constexpr uint32_t folly::crc32_m = 0xedb88320
static

Definition at line 121 of file Crc32CombineDetail.cpp.

constexpr std::array<uint32_t, 62> const folly::crc32_powers
static
Initial value:
=
gf_powers_make<crc32_m>{}(make_index_sequence<62>{})

Definition at line 128 of file Crc32CombineDetail.cpp.

constexpr uint32_t folly::crc32c_m = 0x82f63b78
static

Definition at line 120 of file Crc32CombineDetail.cpp.

constexpr std::array<uint32_t, 62> const folly::crc32c_powers
static
Initial value:
=
gf_powers_make<crc32c_m>{}(make_index_sequence<62>{})

Definition at line 126 of file Crc32CombineDetail.cpp.

FOLLY_STATIC_CTOR_PRIORITY_MAX hazptr_domain< std::atomic > folly::default_domain

Global default domain defined in Hazptr.cpp

Definition at line 23 of file Hazptr.cpp.

Referenced by folly::hazptr_default_domain_helper< std::atomic >::get().

class folly::PackedSyncPtr folly::FOLLY_PACK_ATTR
auto const folly::foo
Initial value:
return std::string("YEP");
})
auto lazy(Func &&fun)
Definition: Lazy.h:138
#define EXPECT_EQ(val1, val2)
Definition: gtest.h:1922
auto globalCount
Definition: LazyTest.cpp:48
const char * string
Definition: Conv.cpp:212

Definition at line 49 of file LazyTest.cpp.

Referenced by shared_ptr_test(), TEST(), and TEST().

FakeAllPowerfulAssertingMutexInternal folly::globalAllPowerfulAssertingMutex
static

The following works around the internal mutex for synchronized being private

This is horridly thread unsafe.

Definition at line 284 of file SynchronizedTest.cpp.

auto folly::globalCount = folly::lazy([] { return 0; })

Definition at line 48 of file LazyTest.cpp.

Referenced by TEST().

constexpr std::size_t folly::hardware_constructive_interference_size = 64

Definition at line 118 of file Align.h.

constexpr initlist_construct_t folly::initlist_construct {}

Definition at line 290 of file Utility.h.

const char * folly::kClientTestCA = "folly/io/async/test/certs/client_ca_cert.pem"

Definition at line 26 of file TestSSLServer.cpp.

Referenced by TEST().

const char * folly::kClientTestCert = "folly/io/async/test/certs/client_cert.pem"

Definition at line 24 of file TestSSLServer.cpp.

Referenced by TEST().

const char * folly::kClientTestKey = "folly/io/async/test/certs/client_key.pem"

Definition at line 25 of file TestSSLServer.cpp.

Referenced by TEST().

constexpr auto folly::kCpplibVer = 0

Definition at line 405 of file Portability.h.

constexpr LogLevel folly::kDefaultLogLevel = LogLevel::INFO
constexpr auto folly::kIntegerDivisionGivesRemainder = true

Definition at line 111 of file Math.h.

constexpr size_t folly::kIovMax = UIO_MAXIOV
constexpr bool folly::kIsArchAArch64 = 0 == 1

Definition at line 103 of file Portability.h.

constexpr bool folly::kIsArchAmd64 = 0 == 1
constexpr bool folly::kIsArchArm = 0 == 1

Definition at line 101 of file Portability.h.

constexpr bool folly::kIsArchPPC64 = 0 == 1

Definition at line 104 of file Portability.h.

constexpr auto folly::kIsBigEndian = !kIsLittleEndian

Definition at line 280 of file Portability.h.

Referenced by folly::detail::EndianInt< T >::little().

constexpr auto folly::kIsGlibcxx = false

Definition at line 373 of file Portability.h.

Referenced by message_for_terminate(), and message_for_terminate_with().

constexpr auto folly::kIsLibcpp = false

Definition at line 379 of file Portability.h.

Referenced by message_for_terminate(), and message_for_terminate_with().

constexpr auto folly::kIsLibstdcpp = false

Definition at line 385 of file Portability.h.

constexpr auto folly::kIsLittleEndian = __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
constexpr auto folly::kIsMobile = false

Definition at line 355 of file Portability.h.

Referenced by folly::parking_lot_detail::Bucket::bucketFor().

constexpr auto folly::kIsObjC = false

Definition at line 349 of file Portability.h.

constexpr bool folly::kIsSanitize = false

Definition at line 130 of file Portability.h.

Referenced by checkRunMode(), and TEST().

constexpr bool folly::kIsSanitizeAddress = false

folly::kIsSanitizeAddress reports if folly was compiled with ASAN enabled. Note that for compilation units outside of folly that include folly/Portability.h, the value of kIsSanitizeAddress may be different from whether or not the current compilation unit is being compiled with ASAN.

Definition at line 118 of file Portability.h.

Referenced by expectAsanFailure(), and TEST().

constexpr auto folly::kIsWindows = false
constexpr size_t folly::kMaxThreadNameLength = 16
static

Definition at line 88 of file ThreadName.cpp.

Referenced by setThreadName().

constexpr size_t folly::kMaxVarintLength32 = 5

Variable-length integer encoding, using a little-endian, base-128 representation.

The MSb is set on all bytes except the last.

Details: https://developers.google.com/protocol-buffers/docs/encoding#varints

If you want to encode multiple values, GroupVarint (in GroupVarint.h) is faster and likely smaller. Maximum length (in bytes) of the varint encoding of a 32-bit value.

Definition at line 45 of file Varint.h.

constexpr size_t folly::kMaxVarintLength64 = 10

Maximum length (in bytes) of the varint encoding of a 64-bit value.

Definition at line 50 of file Varint.h.

Referenced by folly::io::StreamCodec::doUncompress(), folly::test::TEST(), folly::io::test::TEST(), and folly::test::testVarint().

const ScaleInfo folly::kMetricSuffixes[]
static
Initial value:
{
{1E24, "Y"},
{1E21, "Z"},
{1E18, "X"},
{1E15, "P"},
{1E12, "T"},
{1E9, "G"},
{1E6, "M"},
{1E3, "K"},
{1, ""},
{1E-3, "m"},
{1E-6, "u"},
{1E-9, "n"},
{1E-12, "p"},
{1E-15, "f"},
{1E-18, "a"},
{1E-21, "z"},
{1E-24, "y"},
{0, nullptr},
}

Definition at line 204 of file Benchmark.cpp.

Referenced by metricReadable().

constexpr auto folly::kMicrosoftAbiVer = 0
constexpr auto folly::kMscVer = 0

Definition at line 391 of file Portability.h.

const char * folly::kTestCA = "folly/io/async/test/certs/ca-cert.pem"

Definition at line 22 of file TestSSLServer.cpp.

Referenced by TEST().

const char * folly::kTestCert = "folly/io/async/test/certs/tests-cert.pem"

Definition at line 20 of file TestSSLServer.cpp.

Referenced by getctx(), and TEST().

const char * folly::kTestKey = "folly/io/async/test/certs/tests-key.pem"

Definition at line 21 of file TestSSLServer.cpp.

const ScaleInfo folly::kTimeSuffixes[]
static
Initial value:
{
{365.25 * 24 * 3600, "years"},
{24 * 3600, "days"},
{3600, "hr"},
{60, "min"},
{1, "s"},
{1E-3, "ms"},
{1E-6, "us"},
{1E-9, "ns"},
{1E-12, "ps"},
{1E-15, "fs"},
{0, nullptr},
}

Definition at line 190 of file Benchmark.cpp.

Referenced by readableTime().

std::mutex folly::libevent_mutex_
static

Definition at line 70 of file EventBase.cpp.

constexpr auto folly::loop_break = for_each_detail::LoopControl::BREAK
constexpr std::size_t folly::max_align_v = detail::max_align_v_::value
constexpr bool folly::msgErrQueueSupported
static
Initial value:
=
false

Definition at line 50 of file AsyncSocket.cpp.

constexpr bool folly::msgErrQueueSupported
static
Initial value:
=
false

Definition at line 50 of file AsyncServerSocket.cpp.

constexpr None folly::none {None::_secret::_token}

Definition at line 87 of file Optional.h.

Referenced by folly::gen::detail::GroupByAdjacent< Selector >::Generator< Value, Source, ValueDecayed, Key, KeyDecayed >::apply(), folly::ConcurrentHashMap< KeyType, ValueType, HashFn, KeyEqual, Allocator, ShardBits, Atom, Mutex >::assign(), folly::ConcurrentHashMap< KeyType, ValueType, HashFn, KeyEqual, Allocator, ShardBits, Atom, Mutex >::assign_if_equal(), folly::coro::TimedWaitAwaitable< Awaitable >::await_resume(), proxygen::checkForProtocolUpgrade(), fizz::KeyScheduler::clearMasterSecret(), fizz::client::AsyncFizzClientT< SM >::connect(), fizz::client::AsyncFizzClientT< SM >::connectSuccess(), BogoTestClient::connectSuccess(), wangle::LRUInMemoryCache< K, V, MutexT >::convertToKeyValuePairs(), fizz::ReadRecordLayer::decodeHandshakeMessage(), fizz::server::AeadTokenCipher< AeadType, HkdfType >::decrypt(), fizz::server::AeadCookieCipher< AeadType, HkdfType >::decrypt(), fizz::server::AeadTicketCipher< AeadType, CodecType, HkdfType >::decrypt(), fizz::client::AsyncFizzClientT< SM >::deliverHandshakeError(), fizz::test::HandshakeTest::doClientHandshake(), fizz::test::HandshakeTest::doHandshake(), fizz::server::AeadTokenCipher< AeadType, HkdfType >::encrypt(), fizz::server::AeadTicketCipher< AeadType, CodecType, HkdfType >::encrypt(), fizz::detail::evpDecrypt(), folly::exception_wrapper::exception_wrapper(), fizz::server::CertManager::findCert(), fizz::client::test::AsyncFizzClientTest::fullHandshakeSuccess(), proxygen::HTTP2Codec::generateExHeader(), proxygen::HTTP2Codec::generateHeader(), proxygen::HTTP2Codec::generatePushPromise(), fizz::sm::generateTicket(), wangle::LRUInMemoryCache< K, V, MutexT >::get(), get_optional(), folly::settings::Snapshot::getAsString(), proxygen::SecondaryAuthManager::getCertId(), fizz::sm::getCertificateRequest(), fizz::sm::getClockSkew(), folly::ssl::OpenSSLCertUtils::getCommonName(), fizz::sm::getCookieState(), fizz::EncryptedReadRecordLayer::getDecryptedBuf(), fizz::sm::getEarlyDataParams(), fizz::getExtension(), wangle::Acceptor::getFizzPeeker(), fizz::server::getHrrGroup(), fizz::sm::getHrrKeyExchangers(), TestPriorityAdapter::getHTTPPriority(), proxygen::HTTPSession::getHTTPPriority(), folly::ssl::OpenSSLCertUtils::getIssuer(), folly::IPAddressV6::getMacAddressFromEUI64(), folly::IPAddressV6::getMacAddressFromLinkLocal(), proxygen::HTTPMessage::getMethod(), proxygen::SecondaryAuthManager::getPeerCert(), fizz::client::SynchronizedLruPskCache::getPsk(), fizz::client::BasicPskCache::getPsk(), fizz::client::FizzClientContext::getPsk(), fizz::detail::getRequestedSchemes(), fizz::sm::getResumptionState(), folly::settings::getSettingsMeta(), proxygen::PerfectIndexMap< typename T::TKey, T::TOtherKey, T::TNoneKey, T::Hash, T::TAllowDuplicates, T::TCaseInsensitive >::getSingleOrNone(), folly::ssl::OpenSSLCertUtils::getSubject(), proxygen::SPDYCodec::getVersion(), fizz::sm::handleCertMsg(), fizz::sm::handleEarlyAppWrite(), fizz::client::AsyncFizzClientT< SM >::handleEarlyReject(), fizz::server::detail::handleInvalidEvent(), fizz::client::detail::handleInvalidEvent(), proxygen::spdy::httpToSpdySettingsId(), fizz::sm::ignoreEarlyAppWrite(), folly::dynamicconverter_detail::Transformer< T, It >::increment(), proxygen::HeaderDecodeInfo::init(), folly::compression::instructionsOverride(), TryFromStringTest::ipInOutProvider(), wangle::FilePersistenceLayer< K, V >::load(), fizz::server::negotiate(), fizz::sm::negotiateGroup(), fizz::extensions::TokenBindingServerExtension::negotiateVersion(), fizz::sm::negotiateVersion(), fizz::client::AsyncFizzClientT< SM >::ActionMoveVisitor::operator()(), proxygen::HTTP2Codec::parseContinuation(), proxygen::HTTP2Codec::parseExHeaders(), proxygen::http2::parseExHeaders(), proxygen::HTTP2Codec::parseHeaders(), proxygen::http2::parseHeaders(), proxygen::parseHTTPDateTime(), proxygen::HTTP2Codec::parsePushPromise(), wangle::PeekingAcceptorHandshakeHelper::peekError(), PerfectIndexMapGetCodeBench(), PerfectIndexMapGetStringBench(), fizz::client::ClientStateMachine::processSocketData(), fizz::server::ServerStateMachine::processSocketData(), wangle::TLSCredProcessor::processTLSTickets(), fizz::PlaintextReadRecordLayer::read(), fizz::EncryptedReadRecordLayer::read(), wangle::SerialClientDispatcher< wangle::Pipeline, folly::Req, Resp >::read(), fizz::ReadRecordLayer::readEvent(), runRemoteUnlock(), proxygen::HTTPMessage::setPriority(), fizz::test::HandshakeTest::setupResume(), fizz::test::HandshakeTest::setupResumeWithHRR(), proxygen::spdy::spdyToHttpSettingsId(), wangle::UnencryptedAcceptorHandshakeHelper::start(), proxygen::stringToMethod(), TEST(), fizz::server::test::TEST(), test(), TEST(), folly::io::test::TEST(), fizz::server::test::TEST_F(), fizz::test::TEST_F(), TEST_F(), fizz::client::test::TEST_F(), folly::io::test::TEST_P(), folly::ssl::OpenSSLCertUtils::toString(), folly::UnboundedBlockingQueue< T >::try_take_for(), folly::LifoSemMPMCQueue< T, kBehavior >::try_take_for(), folly::PriorityLifoSemMPMCQueue< T, kBehavior >::try_take_for(), folly::ThreadPoolExecutor::StoppedThreadQueue::try_take_for(), folly::io::Codec::type(), UnorderedMapGetBench(), fizz::ExportedAuthenticator::validate(), fizz::sm::validateAcceptedEarly(), fizz::sm::validatePsk(), fizz::extensions::Validator::validateTokenBinding(), proxygen::SecondaryAuthManager::verifyContext(), proxygen::http2::writeAltSvc(), proxygen::http2::writeCertificate(), proxygen::http2::writeCertificateRequest(), proxygen::http2::writeContinuation(), proxygen::http2::writeData(), proxygen::http2::writeGoaway(), proxygen::http2::writePing(), proxygen::http2::writePushPromise(), proxygen::http2::writeRstStream(), proxygen::http2::writeSettings(), proxygen::http2::writeSettingsAck(), proxygen::http2::writeWindowUpdate(), and folly::io::StreamCodec::~StreamCodec().

constexpr presorted_t folly::presorted {}

Definition at line 311 of file Utility.h.

Referenced by merge(), and folly::TDigest::merge().

folly::Indestructible<rcu_domain<RcuTag>*> folly::rcu_default_domain_

Referenced by rcu_default_domain().

template<class Tgt , class Src >
std::enable_if< std::is_integral<Src>::value && IsSomeString<Tgt>::value && sizeof(Src) < 4>::typetoAppend(Src value, Tgt* result) { typedef typename std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>:: type Intermediate; toAppend<Tgt>static_cast<Intermediate>value), result);}template <class Src>typename std::enable_if< std::is_integral<Src>::value && sizeof(Src) < 4 && !std::is_same<Src, char>::value, size_t>::typeestimateSpaceNeeded(Src value) { typedef typename std::conditional<std::is_signed<Src>::value, int64_t, uint64_t>:: type Intermediate; return estimateSpaceNeeded(static_cast<Intermediate>value));}template <class Tgt, class Src>typename std::enable_if< std::is_enum<Src>::value && IsSomeString<Tgt>::value>::typetoAppend(Src value, Tgt* result) { toAppend( static_cast<typename std::underlying_type<Src>::type>value), result);}template <class Src>typename std::enable_if<std::is_enum<Src>::value, size_t>::typeestimateSpaceNeeded(Src value) { return estimateSpaceNeeded( static_cast<typename std::underlying_type<Src>::type>value));}namespace detail {constexpr int kConvMaxDecimalInShortestLow = -6;constexpr int kConvMaxDecimalInShortestHigh = 21;} template <class Tgt, class Src>typename std::enable_if< std::is_floating_point<Src>::value && IsSomeString<Tgt>::value>::typetoAppend( Src value, Tgt* result, double_conversion::DoubleToStringConverter::DtoaMode mode, unsigned int numDigits) { using namespace double_conversion; DoubleToStringConverter conv( DoubleToStringConverter::NO_FLAGS, "Infinity", "NaN", 'E', detail::kConvMaxDecimalInShortestLow, detail::kConvMaxDecimalInShortestHigh, 6, 1); char buffer[256]; StringBuilder builder(buffer, sizeof(buffer)); switch (mode) { case DoubleToStringConverter::SHORTEST: conv.ToShortest(value, &builder); break; case DoubleToStringConverter::SHORTEST_SINGLE: conv.ToShortestSingle(static_cast<float>value), &builder); break; case DoubleToStringConverter::FIXED: conv.ToFixed(value, int(numDigits), &builder); break; default: CHECK(mode == DoubleToStringConverter::PRECISION); conv.ToPrecision(value, int(numDigits), &builder); break; } const size_t length = size_t(builder.position()); builder.Finalize(); result->append(buffer, length);}template <class Tgt, class Src>typename std::enable_if< std::is_floating_point<Src>::value && IsSomeString<Tgt>::value>::typetoAppend(Src value, Tgt* result) { toAppend( value, result, double_conversion::DoubleToStringConverter::SHORTEST, 0);}template <class Src>typename std::enable_if<std::is_floating_point<Src>::value, size_t>::typeestimateSpaceNeeded(Src value) { constexpr int kMaxMantissaSpace = double_conversion::DoubleToStringConverter::kBase10MaximalLength + 1; constexpr int kMaxExponentSpace = 2 + 3; static const int kMaxPositiveSpace = std::max({ kMaxMantissaSpace + kMaxExponentSpace, kMaxMantissaSpace - detail::kConvMaxDecimalInShortestLow, detail::kConvMaxDecimalInShortestHigh, }); return size_t( kMaxPositiveSpace + (value < 0 ? 1 : 0)); }template <class Src>struct HasLengthEstimator : std::false_type {};template <class Src>constexpr typename std::enable_if< !std::is_fundamental<Src>::value && !IsSomeString<Src>::value && !std::is_convertible<Src, const char*>::value && !std::is_convertible<Src, StringPiece>::value && !std::is_enum<Src>::value && !HasLengthEstimator<Src>::value, size_t>::typeestimateSpaceNeeded(const Src&) { return sizeof(Src) + 1; }namespace detail {template <class Tgt>typename std::enable_if<IsSomeString<Tgt>::value, size_t>::typeestimateSpaceToReserve(size_t sofar, Tgt*) { return sofar;}template <class T, class... Ts>size_t estimateSpaceToReserve(size_t sofar, const T& v, const Ts&... vs) { return estimateSpaceToReserve(sofar + estimateSpaceNeeded(v), vs...);}template <class... Ts>void reserveInTarget(const Ts&... vs) { getLastElement(vs...)-> folly::reserve(estimateSpaceToReserve(0, vs...))

All small signed and unsigned integers to string go through 32-bit types int32_t and uint32_t, respectively.

Definition at line 792 of file Conv.h.

Referenced by folly::fibers::TaskIterator< T >::awaitNextResult(), folly::threadlocal_detail::StaticMetaBase::erase(), folly::F14VectorSet< Key, Hasher, KeyEqual, Alloc >::operator=(), and folly::F14VectorMap< Key, Mapped, Hasher, KeyEqual, Alloc >::operator=().

template<class Sig >
constexpr detail::Sig<Sig> const folly::sig = {}

Pseudo-function template handy for disambiguating function overloads.

For example, given: struct S { int property() const; void property(int); };

You can get a member function pointer to the first overload with: folly::sig<int()const>(&S::property);

This is arguably a nicer syntax that using the built-in static_cast: static_cast<int (S::*)() const>(&S::property);

sig is also more permissive than static_cast about const. For instance, the following also works: folly::sig<int()>(&S::property);

The above is permitted

Definition at line 1165 of file Poly.h.

Referenced by folly::Subprocess::Options::chdir(), fizz::sm::getCertificateRequest(), fizz::ExportedAuthenticator::makeAuthenticator(), folly::Subprocess::prepareChild(), runChild(), fizz::test::TEST_F(), fizz::testing::TEST_P(), and fizz::test::TYPED_TEST().

const AsyncSocketException folly::socketClosedLocallyEx(AsyncSocketException::END_OF_FILE,"socket closed locally")
const AsyncSocketException folly::socketShutdownForWritesEx(AsyncSocketException::END_OF_FILE,"socket shutdown for writes")
folly::std folly::T
Examples:
/facebook/proxygen/proxygen/folly/folly/container/Iterator.h, and /facebook/proxygen/proxygen/folly/folly/lang/RValueReferenceWrapper.h.

Referenced by folly::fibers::FiberManager::add(), addBenchmark(), folly::FutureExecutor< ExecutorImpl >::addFuture(), folly::fibers::TaskIterator< T >::addTask(), folly::fibers::FiberManager::addTaskFuture(), aFunction(), folly::CxxHugePageAllocator< T >::allocate(), ExpectingAlloc< T >::allocate(), folly::SysAllocator< T >::allocate(), folly::f14::SwapTrackingAlloc< T >::allocate(), folly::AlignedSysAllocator< T, Align >::allocate(), folly::f14::GenericAlloc< T >::allocate(), folly::CxxAllocatorAdaptor< T, Inner >::allocate(), allocate_unique(), allocationBytesForOverAligned(), folly::SomeClass::aMethod(), as_const(), folly::detail::as_sorted(), folly::MemoryMapping::asRange(), folly::fbvector< HTTPHeaderCode >::assign(), folly::SomeClass::aStaticMethod(), aStdFunction(), folly::MemoryMapping::asWritableRange(), folly::symbolizer::ElfFile::at(), folly::coro::AwaitableReady< T >::await_resume(), folly::RelaxedConcurrentPriorityQueue< T, MayBlock, SupportsSize, PopBatch, ListTargetSize, Mutex, Atom >::binarySearchPosition(), bitReverse(), folly::Bits< T, Traits >::blockCount(), folly::hazptr_obj_base_linked< NodeAuto< Atom >, Atom >::call_push_links(), folly::TypedIOBuf< T >::cast(), folly::Bits< T, Traits >::clear(), collect(), collectAllSemiFuture(), collectAny(), collectAnyWithoutException(), collectN(), folly::FlatCombining< FcSimpleExample< Mutex, Atom >, Mutex, Atom >::combiningSession(), folly::hash::commutative_hash_combine_generic(), complexBenchmark(), folly::fbvector< HTTPHeaderCode >::computeInsertCapacity(), folly::fbvector< HTTPHeaderCode >::computePushBackCapacity(), constexpr_add_overflow_clamped(), constexpr_ceil(), constexpr_find_first_set(), constexpr_find_last_set(), constexpr_log2(), folly::detail::constexpr_log2_(), folly::detail::constexpr_log2_ceil_(), constexpr_max(), constexpr_min(), constexpr_pow(), constexpr_sub_overflow_clamped(), folly::detail::fixedstring::constexpr_swap(), folly::test::TupleTo< std::tuple<>, std::tuple<> >::convert(), folly::test::TupleTo2< TemplateSeq< std::size_t, Ns... > >::convert(), folly::DynamicConverter< T, typename std::enable_if< std::is_enum< T >::value >::type >::convert(), folly::settings::detail::convertOrConstruct(), folly::replaceable_detail::copy_ctor_mixin< T, true >::copy_ctor_mixin(), folly::futures::detail::coreDetachPromiseMaybeWithResult(), folly::detail::StaticSingletonManager::create(), folly::detail::createGlobal(), folly::detail::SingletonHolder< T >::createInstance(), folly::fbvector< T, Allocator >::Impl::D_allocate(), folly::fibers::Fiber::LocalData::dataBufferDestructor(), folly::fibers::Fiber::LocalData::dataCopyConstructor(), folly::fibers::Fiber::LocalData::dataHeapDestructor(), folly::io::compression::detail::dataStartsWithLE(), folly::CxxHugePageAllocator< T >::deallocate(), folly::f14::SwapTrackingAlloc< T >::deallocate(), folly::f14::GenericAlloc< T >::deallocate(), folly::AtomicStruct< folly::IndexedMemPool::TaggedPtr, Atom >::decode(), folly::replaceable_detail::default_and_move_ctor_mixin< T, true, true >::default_and_move_ctor_mixin(), folly::replaceable_detail::default_and_move_ctor_mixin< T, true, false >::default_and_move_ctor_mixin(), folly::replaceable_detail::default_and_move_ctor_mixin< T, false, true >::default_and_move_ctor_mixin(), folly::RelaxedConcurrentPriorityQueue< T, MayBlock, SupportsSize, PopBatch, ListTargetSize, Mutex, Atom >::deferSettingRootSize(), folly::ThreadLocalPtr< T, Tag, AccessMode >::Accessor::Iterator::dereference(), folly::fbvector< HTTPHeaderCode >::do_real_insert(), folly::expected_detail::doEmplaceAssign(), doNotOptimizeAway(), folly::dynamic::dynamic(), folly::Try< T >::emplace(), folly::Replaceable< T >::emplace(), folly::fbvector< T, Allocator >::emplace_back_aux(), folly::AtomicStruct< folly::IndexedMemPool::TaggedPtr, Atom >::encode(), folly::detail::SingleElementQueue< T, Atom >::enqueue(), folly::detail::SingleElementQueue< T, Atom >::enqueueImpl(), folly::fbvector< HTTPHeaderCode >::erase(), estimateSpaceNeeded(), folly::EventBase::EventBase(), non_atomic< T >::exchange(), exchange(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::exchange(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::fetch_add(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::fetch_and(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::fetch_or(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::fetch_sub(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::fetch_xor(), fGen(), folly::Future< T >::filter(), folly::detail::SignedValueHandler< T, true >::finalize(), findFirstSet(), findLastSet(), folly::json::firstEscapableInWord(), folly::RelaxedConcurrentPriorityQueue< T, MayBlock, SupportsSize, PopBatch, ListTargetSize, Mutex, Atom >::forceInsert(), from_eptr(), folly::Future< folly::folly::Unit >::Future(), folly::Future< T >::Future(), folly::futures::detail::FutureBase< T >::FutureBase(), PThreadGetSpecific< T >::get(), folly::EventBaseLocal< T >::get(), folly::rvalue_reference_wrapper< T >::get(), folly::PackedSyncPtr< T >::get(), folly::DiscriminatedPtr< Types >::get(), folly::fibers::Fiber::LocalData::get(), folly::ThreadLocalPtr< SubscriberMap >::get(), folly::DiscriminatedPtr< Types >::get_nothrow(), folly::hazptr_holder< Atom >::get_protected(), get_ptr(), folly::detail::shared_ptr_internals::get_shared_ptr(), folly::BlockingQueue< folly::CPUThreadPoolExecutor::CPUTask >::getNumPriorities(), folly::EventBaseLocal< T >::getOrCreate(), folly::EventBaseLocal< T >::getOrCreateFn(), folly::detail::HistogramBuckets< T, BucketT >::getPercentileEstimate(), folly::coro::detail::TaskPromise< T >::getResult(), folly::fibers::Fiber::LocalData::getSlow(), folly::observer::Observer< T >::getSnapshot(), folly::Singleton< folly::observer_detail::ObserverManager >::getTeardownFunc(), folly::AsyncTransportWrapper::getUnderlyingTransport(), folly::SingletonThreadLocal< T, Tag, Make, TLTag >::getWrapper(), folly::hash::hash_combine_generic(), hazptr_domain_push_retired(), AnnotatedAtomicCounter< T >::incBug(), folly::Indestructible< T >::Indestructible(), folly::fbvector< T, Allocator >::Impl::init(), folly::fbvector< HTTPHeaderCode >::insert(), folly::UnboundedQueue< T, SingleProducer, SingleConsumer, MayBlock, LgSegmentSize, LgAlign, Atom >::Entry::itemPtr(), launder(), folly::LeakySingleton< T, Tag >::LeakySingleton(), folly::Tearable< T >::load(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::load(), loadUnaligned(), folly::fibers::FiberManager::local(), folly::fibers::local(), folly::fibers::FiberManager::localThread(), folly::Singleton< folly::observer_detail::ObserverManager >::make_mock(), folly::LeakySingleton< T, Tag >::make_mock(), make_optional(), make_replaceable(), make_unique(), folly::fbvector< HTTPHeaderCode >::make_window(), folly::futures::detail::makeCoreCallbackState(), makeTryWith(), makeUnpredictable(), folly::detail::mallctlHelper(), folly::futures::map(), folly::RelaxedConcurrentPriorityQueue< T, MayBlock, SupportsSize, PopBatch, ListTargetSize, Mutex, Atom >::mergeDown(), nextPowTwo(), folly::Future< T >::onError(), PThreadGetSpecific< T >::OnThreadExit(), folly::pushmi::concepts::detail::Not< T >::operator bool(), folly::pushmi::concepts::detail::And< T, U >::operator bool(), folly::pushmi::concepts::detail::Or< T, U >::operator bool(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::operator T(), folly::pushmi::concepts::detail::Not< T >::operator!(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::operator&=(), folly::detail::DefaultMake< T >::operator()(), folly::pushmi::for_each_fn::identity::operator()(), folly::pushmi::reduce_fn::identity::operator()(), folly::pushmi::pipe_fn::operator()(), folly::ApplyInvoke::operator()(), folly::pushmi::detail::id_fn::operator()(), folly::dptr_detail::ApplyVisitor1< 1, V, R, T, Types... >::operator()(), folly::dptr_detail::ApplyConstVisitor1< 1, V, R, T, Types... >::operator()(), folly::detail::apply_tuple::Construct< T >::operator()(), std::hash< TestStruct >::operator()(), folly::DefaultWeightFn< T >::operator()(), folly::pushmi::detail::get_fn< T >::on_value_impl::operator()(), folly::Hash::operator()(), TestHasher::operator()(), folly::allocator_delete< Alloc >::operator()(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::operator++(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::operator+=(), folly::expected_detail::expected_detail_ExpectedHelper::operator,(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::operator--(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::operator-=(), folly::pushmi::detail::opt< std::tuple< std::decay_t< TN >... > >::operator=(), folly::Try< T >::operator=(), folly::F14VectorSet< Key, Hasher, KeyEqual, Alloc >::operator=(), folly::F14VectorMap< Key, Mapped, Hasher, KeyEqual, Alloc >::operator=(), folly::replaceable_detail::move_assignment_mixin< T, true >::operator=(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::operator=(), folly::replaceable_detail::copy_assignment_mixin< T, true >::operator=(), folly::Future< T >::operator=(), folly::padded::Node< T, NS, typename detail::NodeValid< T, NS >::type >::operator==(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::operator^=(), folly::test::DeterministicAtomicImpl< T, Schedule, Atom >::operator|=(), folly::pushmi::detail::opt< std::tuple< std::decay_t< TN >... > >::opt(), folly::padded::Node< T, NS, typename detail::NodeValid< T, NS >::type >::paddingBytes(), folly::CachelinePadded< std::atomic< Version > >::paddingSize(), parseTo(), partialLoadUnaligned(), poly_cast(), poly_move(), popcount(), folly::io::compression::detail::prefixToStringLE(), prevPowTwo(), folly::FlatCombining< FcSimpleExample< Mutex, Atom >, Mutex, Atom >::processReq(), folly::pushmi::detail::opt< std::tuple< std::decay_t< TN >... > >::ptr(), folly::UnboundedQueue< T, SingleProducer, SingleConsumer, MayBlock, LgSegmentSize, LgAlign, Atom >::Segment::push_links(), folly::UnboundedQueue< T, SingleProducer, SingleConsumer, MayBlock, LgSegmentSize, LgAlign, Atom >::Entry::putItem(), folly::detail::qfind_first_byte_of_sse42(), folly::test::detail::RandomList(), folly::detail::rawOverAlignedImpl(), rcu_barrier(), rcu_retire(), folly::io::detail::CursorBase< Cursor, const IOBuf >::read(), folly::io::detail::CursorBase< Cursor, const IOBuf >::readSlow(), reduce(), folly::Future< T >::reduce(), folly::RelaxedConcurrentPriorityQueue< T, MayBlock, SupportsSize, PopBatch, ListTargetSize, Mutex, Atom >::regularInsert(), folly::ThreadLocalPtr< SubscriberMap >::release(), relinquish(), folly::fbvector< HTTPHeaderCode >::relocate_move_or_memcpy(), folly::Replaceable< T >::Replaceable(), folly::fbvector< HTTPHeaderCode >::reserve(), folly::fbvector< HTTPHeaderCode >::reserve_in_place(), folly::hazptr_holder< Atom >::reset(), folly::ThreadLocalPtr< SubscriberMap >::reset(), folly::fbvector< HTTPHeaderCode >::resize(), folly::hazptr_domain< DeterministicAtomic >::retire(), folly::futures::detail::retrying(), folly::futures::detail::retryingImpl(), folly::expected_detail::expected_detail_ExpectedHelper::ExpectedHelper::return_(), folly::AtomicIntrusiveLinkedList< folly::fibers::Fiber,&folly::fibers::Fiber::nextRemoteReady_ >::reverse(), rref(), runArithmeticBench(), runMultiBitTest64(), runMultiBitTest8(), runSignedMultiBitTest8(), runSimpleTest64(), runSimpleTest8(), folly::rvalue_reference_wrapper< T >::rvalue_reference_wrapper(), folly::fbvector< HTTPHeaderCode >::S_copy_n(), folly::fbvector< HTTPHeaderCode >::S_uninitialized_copy_bits(), folly::fbvector< HTTPHeaderCode >::S_uninitialized_fill_n(), folly::TypedIOBuf< T >::sdiv(), folly::symbolizer::Dwarf::Section::Section(), folly::Random::secureRandom(), folly::detail::TupleSelect< TemplateSeq< std::size_t, Ns... > >::select(), folly::SemiFuture< T >::SemiFuture(), folly::Bits< T, Traits >::set(), folly::settings::detail::set(), folly::hazptr_obj_base< Node, Atom >::set_reclaim(), folly::AsyncSocket::setSockOpt(), folly::SharedPromise< folly::folly::Unit >::setValue(), folly::Promise< folly::folly::Unit >::setValue(), folly::fbvector< HTTPHeaderCode >::shrink_to_fit(), folly::detail::SingletonHolder< T >::singleton(), folly::Singleton< folly::observer_detail::ObserverManager >::Singleton(), folly::TypedIOBuf< T >::smul(), someFuture(), folly::Indestructible< T >::Storage::Storage(), folly::Tearable< T >::store(), folly::detail::type< T >::store(), storeUnaligned(), folly::detail::EndianInt< T >::swap(), folly::UnboundedBlockingQueue< T >::take(), folly::LifoSemMPMCQueue< T, kBehavior >::take(), folly::PriorityLifoSemMPMCQueue< T, kBehavior >::take(), folly::DynamicBoundedQueue< T, SingleProducer, SingleConsumer, MayBlock, LgSegmentSize, LgAlign, WeightFn, Atom >::takeCredit(), folly::fibers::TaskIterator< T >::TaskIterator(), folly::test::TEST(), TEST(), testIsRelocatable(), folly::Future< T >::then(), p1054::then_execute(), folly::ThreadLocal< std::queue< folly::Function > >::ThreadLocal(), folly::detail::to_exception_arg_(), to_ordering(), toAppend(), toAppendStrImpl(), folly::Try< folly::folly::Unit >::Try(), folly::Try< T >::Try(), folly::hazptr_holder< Atom >::try_protect(), folly::UnboundedBlockingQueue< T >::try_take_for(), folly::LifoSemMPMCQueue< T, kBehavior >::try_take_for(), folly::PriorityLifoSemMPMCQueue< T, kBehavior >::try_take_for(), folly::RelaxedConcurrentPriorityQueue< T, MayBlock, SupportsSize, PopBatch, ListTargetSize, Mutex, Atom >::trylockNode(), folly::detail::RingBufferSlot< T, Atom >::tryRead(), folly::io::detail::CursorBase< Cursor, const IOBuf >::tryRead(), p1054::twoway_execute(), unorderedReduce(), folly::StampedPtr< T >::unpackPtr(), folly::Try< T >::value(), folly::Optional< NamedGroup >::value_or(), folly::symbolizer::ElfFile::valueAt(), folly::detail::RingBufferSlot< T, Atom >::waitAndTryRead(), folly::futures::detail::waitViaImpl(), folly::ProducerConsumerQueue< T >::write(), folly::io::detail::Writable< Appender >::write(), folly::io::QueueAppender::write(), folly::io::QueueAppender::writeSlow(), folly::coro::detail::BlockingWaitPromise< T & >::yield_value(), folly::AtomicLinkedList< T >::~AtomicLinkedList(), folly::replaceable_detail::dtor_mixin< T, true, false >::~dtor_mixin(), and folly::detail::SingleElementQueue< T, Atom >::~SingleElementQueue().

constexpr unsorted_t folly::unsorted {}

Definition at line 332 of file Utility.h.