├── folly ├── VERSION ├── docs │ ├── .gitignore │ ├── Fbvector--graphical_solutions.png │ ├── style.css │ ├── Makefile │ ├── SmallLocks.md │ └── FBString.md ├── test │ ├── .gitignore │ ├── json_test_data │ │ ├── commented.json.exp │ │ └── commented.json │ ├── function_benchmark │ │ ├── Makefile.am │ │ ├── test_functions.h │ │ ├── benchmark_impl.cpp │ │ ├── benchmark_impl.h │ │ └── test_functions.cpp │ ├── CpuIdTest.cpp │ ├── SafeAssertTest.cpp │ ├── AsciiCaseInsensitiveTest.cpp │ ├── FileTestLockHelper.cpp │ ├── PortabilityTest.cpp │ ├── HistogramBenchmark.cpp │ ├── MoveWrapperTest.cpp │ ├── SynchronizedTestLib.h │ ├── AtomicBitSetTest.cpp │ ├── DemangleTest.cpp │ ├── DeterministicScheduleTest.cpp │ ├── SingletonVaultCTest.cpp │ ├── EndianTest.cpp │ ├── MapUtilTest.cpp │ └── MergeTest.cpp ├── wangle │ ├── codec │ │ ├── README.md │ │ ├── ByteToMessageCodec.cpp │ │ ├── StringCodec.h │ │ ├── FixedLengthFrameDecoder.h │ │ ├── LineBasedFrameDecoder.h │ │ ├── ByteToMessageCodec.h │ │ └── LengthFieldPrepender.h │ ├── ssl │ │ ├── TLSTicketKeySeeds.h │ │ ├── SSLCacheOptions.h │ │ ├── ClientHelloExtStats.h │ │ ├── PasswordInFile.cpp │ │ ├── PasswordInFile.h │ │ └── SSLStats.h │ ├── acceptor │ │ ├── SocketOptions.h │ │ ├── SocketOptions.cpp │ │ ├── LoadShedConfiguration.cpp │ │ ├── ConnectionCounter.h │ │ ├── NetworkAddress.h │ │ ├── DomainNameMisc.h │ │ ├── TransportInfo.cpp │ │ └── ManagedConnection.cpp │ ├── rx │ │ ├── Dummy.cpp │ │ ├── types.h │ │ ├── Subject.h │ │ ├── Subscription.h │ │ └── README.md │ ├── concurrent │ │ ├── ThreadFactory.h │ │ ├── BlockingQueue.h │ │ ├── test │ │ │ └── CodelTest.cpp │ │ ├── LifoSemMPMCQueue.h │ │ ├── NamedThreadFactory.h │ │ ├── FiberIOExecutor.h │ │ ├── IOExecutor.h │ │ └── GlobalExecutor.h │ ├── service │ │ └── ServerDispatcher.h │ └── channel │ │ └── EventBaseHandler.h ├── experimental │ ├── io │ │ ├── test │ │ │ └── Makefile.am │ │ ├── FsUtil.cpp │ │ └── FsUtil.h │ ├── symbolizer │ │ ├── test │ │ │ ├── Crash.cpp │ │ │ └── SignalHandlerTest.h │ │ ├── ElfUtil.cpp │ │ ├── StackTrace.h │ │ └── SignalHandler.h │ ├── fibers │ │ ├── GenericBaton.h │ │ ├── FiberManagerMap.h │ │ ├── GuardPageAllocator.h │ │ ├── test │ │ │ └── main.cpp │ │ ├── ExecutionObserver.h │ │ ├── ForEach.h │ │ ├── LoopController.h │ │ └── EventBaseLoopController.h │ ├── SharedMutex.cpp │ ├── exception_tracer │ │ ├── README.md │ │ ├── ExceptionTracerBenchmark.cpp │ │ ├── ExceptionTracer.h │ │ └── ExceptionAbi.h │ ├── StringKeyedCommon.h │ └── JSONSchemaTester.cpp ├── futures │ ├── exercises │ │ ├── README.md │ │ ├── Koan.h │ │ └── main.cpp │ ├── InlineExecutor.cpp │ ├── Deprecated.h │ ├── detail │ │ ├── Types.h │ │ └── ThreadWheelTimekeeper.h │ ├── test │ │ ├── ClientCompile.cpp │ │ ├── main.cpp │ │ ├── UnitTest.cpp │ │ ├── SugarTest.cpp │ │ ├── thens.rb │ │ └── Try.cpp │ ├── InlineExecutor.h │ ├── QueuedImmediateExecutor.h │ ├── QueuedImmediateExecutor.cpp │ ├── Unit.h │ ├── DrivableExecutor.h │ ├── Future.cpp │ ├── OpaqueCallbackShunt.h │ └── ScheduledExecutor.h ├── Version.cpp ├── detail │ ├── ExceptionWrapper.h │ ├── MallocImpl.cpp │ ├── FunctionalExcept.h │ ├── FunctionalExcept.cpp │ ├── Clock.h │ ├── AtomicHashUtils.h │ ├── BitsDetail.h │ ├── Malloc.h │ └── Clock.cpp ├── io │ └── async │ │ ├── AsyncSocketBase.h │ │ ├── Request.cpp │ │ ├── test │ │ ├── certs │ │ │ ├── tests-cert.pem │ │ │ ├── ca-cert.pem │ │ │ └── tests-key.pem │ │ ├── SocketPair.h │ │ ├── MockAsyncSocket.h │ │ └── MockAsyncServerSocket.h │ │ └── EventUtil.h ├── GroupVarint.cpp ├── Chrono.h ├── gen │ ├── Core.h │ ├── Combine.h │ ├── test │ │ └── Bench.h │ └── ParallelMap.h ├── Unicode.h ├── Likely.h ├── StringBase.cpp ├── bootstrap-osx-homebrew.sh ├── SingletonVault_c.h ├── SingletonVault_c.cpp ├── Checksum.h ├── ThreadName.h ├── SpinLock.h ├── Uri-inl.h ├── LifoSem.cpp ├── ThreadCachedArena.cpp ├── SafeAssert.cpp ├── SingletonStackTrace.cpp ├── Unicode.cpp ├── SafeAssert.h ├── Executor.h └── CPortability.h └── .gitignore /folly/VERSION: -------------------------------------------------------------------------------- 1 | 40:0 2 | -------------------------------------------------------------------------------- /folly/docs/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | -------------------------------------------------------------------------------- /folly/test/.gitignore: -------------------------------------------------------------------------------- 1 | *.log 2 | *.trs 3 | gtest*/* 4 | -------------------------------------------------------------------------------- /folly/docs/Fbvector--graphical_solutions.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/clearlinux/folly/master/folly/docs/Fbvector--graphical_solutions.png -------------------------------------------------------------------------------- /folly/test/json_test_data/commented.json.exp: -------------------------------------------------------------------------------- 1 | { 2 | "test": "foo", "test2": "foo // bar", 3 | "test4": "foo /* bar", 4 | "te//": "foo", 5 | "te/*": "bar", 6 | "\\\"": "\\" 7 | } 8 | -------------------------------------------------------------------------------- /folly/docs/style.css: -------------------------------------------------------------------------------- 1 | 8 | -------------------------------------------------------------------------------- /folly/wangle/codec/README.md: -------------------------------------------------------------------------------- 1 | Codecs are modeled after netty's codecs: 2 | 3 | https://github.com/netty/netty/tree/master/codec/src/main/java/io/netty/handler/codec 4 | 5 | Most of the changes are due to differing memory allocation strategies. -------------------------------------------------------------------------------- /folly/test/json_test_data/commented.json: -------------------------------------------------------------------------------- 1 | { 2 | // comment 3 | "test": "foo", // comment 4 | "test2": "foo // bar", // more comments 5 | /* 6 | "test3": "baz" 7 | */ 8 | "test4": "foo /* bar", /* comment */ 9 | "te//": "foo", 10 | "te/*": "bar", 11 | "\\\"": "\\" /* comment */ 12 | } 13 | -------------------------------------------------------------------------------- /folly/test/function_benchmark/Makefile.am: -------------------------------------------------------------------------------- 1 | ACLOCAL_AMFLAGS = -I m4 2 | 3 | # depends on libfollybenchmark 4 | 5 | # TESTS = function_benchmark 6 | 7 | # check_PROGRAMS = $(TESTS) 8 | 9 | # noinst_HEADERS = test_functions.h benchmark_impl.h 10 | 11 | # function_benchmark_SOURCES = benchmark_impl.cpp main.cpp test_functions.cpp 12 | -------------------------------------------------------------------------------- /folly/experimental/io/test/Makefile.am: -------------------------------------------------------------------------------- 1 | ACLOCAL_AMFLAGS = -I m4 2 | 3 | TESTS = iobuf_test \ 4 | iobuf_cursor_test 5 | 6 | check_PROGRAMS = $(TESTS) 7 | 8 | iobuf_test_SOURCES = IOBufTest.cpp 9 | iobuf_test_LDADD = $(top_builddir)/libfollyio.la 10 | 11 | iobuf_cursor_test_SOURCES = IOBufCursorTest.cpp 12 | iobuf_cursor_test_LDADD = $(top_builddir)/libfollyio.la $(top_builddir)/libfollybenchmark.la 13 | -------------------------------------------------------------------------------- /folly/futures/exercises/README.md: -------------------------------------------------------------------------------- 1 | Working through [Programming Koans][1] can be a fun, lightweight, and fast way to 2 | learn a new language or pattern with small, focused exercises. Therefore, we 3 | present Koans for Futures. Perhaps you will call them "Koans to Be". 4 | 5 | Edit the topical files one at a time, moving the "compilation cursor" down one 6 | exercise at a time, and getting them to pass by filling in the blanks. 7 | 8 | [1] http://www.lauradhamilton.com/learn-a-new-programming-language-today-with-koans 9 | [2] http://catb.org/esr/writings/unix-koans/ten-thousand.html 10 | -------------------------------------------------------------------------------- /folly/wangle/ssl/TLSTicketKeySeeds.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #pragma once 11 | 12 | namespace folly { 13 | 14 | struct TLSTicketKeySeeds { 15 | std::vector oldSeeds; 16 | std::vector currentSeeds; 17 | std::vector newSeeds; 18 | }; 19 | 20 | } 21 | -------------------------------------------------------------------------------- /folly/wangle/ssl/SSLCacheOptions.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #pragma once 11 | 12 | #include 13 | #include 14 | 15 | namespace folly { 16 | 17 | struct SSLCacheOptions { 18 | std::chrono::seconds sslCacheTimeout; 19 | uint64_t maxSSLCacheSize; 20 | uint64_t sslCacheFlushSize; 21 | }; 22 | 23 | } 24 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.o 2 | *.lo 3 | *.la 4 | .dirstamp 5 | Makefile 6 | Makefile.in 7 | .libs 8 | .deps 9 | stamp-h1 10 | folly-config.h 11 | _configs.sed 12 | aclocal.m4 13 | autom4te.cache 14 | build-aux 15 | libtool 16 | folly/test/gtest-1.6.0 17 | folly/folly-config.h 18 | folly/test/*_benchmark 19 | folly/test/*_test 20 | folly/test/*_test_using_jemalloc 21 | folly/config.* 22 | folly/configure 23 | folly/m4/libtool.m4 24 | folly/m4/ltoptions.m4 25 | folly/m4/ltsugar.m4 26 | folly/m4/ltversion.m4 27 | folly/m4/lt~obsolete.m4 28 | folly/generate_fingerprint_tables 29 | folly/FormatTables.cpp 30 | folly/EscapeTables.cpp 31 | folly/GroupVarintTables.cpp 32 | folly/FingerprintTables.cpp 33 | -------------------------------------------------------------------------------- /folly/futures/InlineExecutor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | -------------------------------------------------------------------------------- /folly/wangle/ssl/ClientHelloExtStats.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #pragma once 11 | 12 | namespace folly { 13 | 14 | class ClientHelloExtStats { 15 | public: 16 | virtual ~ClientHelloExtStats() noexcept {} 17 | 18 | // client hello 19 | virtual void recordAbsentHostname() noexcept = 0; 20 | virtual void recordMatch() noexcept = 0; 21 | virtual void recordNotMatch() noexcept = 0; 22 | }; 23 | 24 | } 25 | -------------------------------------------------------------------------------- /folly/wangle/acceptor/SocketOptions.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #pragma once 11 | 12 | #include 13 | 14 | namespace folly { 15 | 16 | /** 17 | * Returns a copy of the socket options excluding options with the given 18 | * level. 19 | */ 20 | AsyncSocket::OptionMap filterIPSocketOptions( 21 | const AsyncSocket::OptionMap& allOptions, 22 | const int addrFamily); 23 | 24 | } 25 | -------------------------------------------------------------------------------- /folly/futures/Deprecated.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | #define DEPRECATED __attribute__((__deprecated__)) 19 | -------------------------------------------------------------------------------- /folly/futures/exercises/Koan.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | #include 18 | #include 19 | #include 20 | -------------------------------------------------------------------------------- /folly/futures/detail/Types.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | namespace folly { 22 | 23 | using Duration = std::chrono::milliseconds; 24 | 25 | } 26 | -------------------------------------------------------------------------------- /folly/Version.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | namespace folly { namespace detail { 20 | 21 | FOLLY_VERSION_CHECK(folly, FOLLY_VERSION) 22 | 23 | }} // namespaces 24 | -------------------------------------------------------------------------------- /folly/wangle/rx/Dummy.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // fbbuild is too dumb to know that .h files in the directory affect 18 | // our project, unless we have a .cpp file in the target, in the same 19 | // directory. 20 | -------------------------------------------------------------------------------- /folly/docs/Makefile: -------------------------------------------------------------------------------- 1 | SOURCES=$(wildcard *.md) 2 | PDF=$(SOURCES:%.md=%.pdf) 3 | HTML=$(SOURCES:%.md=%.html) 4 | INSTALL=install -c -m 644 5 | PYTHON=python 6 | PANDOCARGS=-s 7 | PANDOC=/usr/bin/pandoc 8 | 9 | export LANGUAGE=C 10 | export LC_ALL=C 11 | 12 | all: html index.html 13 | 14 | pdf: $(PDF) 15 | 16 | html: $(HTML) 17 | 18 | # This needs pandoc 1.9 or later to work 19 | %.pdf: %.md 20 | $(PANDOC) -f markdown -o $*.pdf $*.md 21 | 22 | %.html: %.md style.css 23 | $(PANDOC) $(PANDOCARGS) -H style.css -f markdown -t html --toc -o $*.html $*.md 24 | 25 | docs.md: $(SOURCES) style.css 26 | $(PANDOC) $(PANDOCARGS) -H style.css -f markdown -t markdown --toc -o $@ *.md 27 | 28 | index.html: $(SOURCES) style.css 29 | $(PANDOC) $(PANDOCARGS) -H style.css -f markdown -t html --toc -o $@ *.md 30 | 31 | 32 | clean: 33 | $(RM) $(PDF) $(HTML) index.html 34 | -------------------------------------------------------------------------------- /folly/experimental/symbolizer/test/Crash.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | int main() { 20 | folly::symbolizer::installFatalSignalHandler(); 21 | __builtin_trap(); 22 | return 0; 23 | } 24 | -------------------------------------------------------------------------------- /folly/futures/exercises/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #include "Koan.h" 17 | 18 | int main(int argc, char** argv) { 19 | ::testing::InitGoogleTest(&argc, argv); 20 | ::gflags::ParseCommandLineFlags(&argc, &argv, true); 21 | return RUN_ALL_TESTS(); 22 | } 23 | -------------------------------------------------------------------------------- /folly/experimental/fibers/GenericBaton.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | 20 | #include 21 | 22 | namespace folly { namespace fibers { 23 | 24 | typedef Baton GenericBaton; 25 | 26 | }} 27 | -------------------------------------------------------------------------------- /folly/wangle/ssl/PasswordInFile.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #include 11 | 12 | #include 13 | 14 | using namespace std; 15 | 16 | namespace folly { 17 | 18 | PasswordInFile::PasswordInFile(const string& file) 19 | : fileName_(file) { 20 | folly::readFile(file.c_str(), password_); 21 | auto p = password_.find('\0'); 22 | if (p != std::string::npos) { 23 | password_.erase(p); 24 | } 25 | } 26 | 27 | PasswordInFile::~PasswordInFile() { 28 | OPENSSL_cleanse((char *)password_.data(), password_.length()); 29 | } 30 | 31 | } 32 | -------------------------------------------------------------------------------- /folly/experimental/SharedMutex.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include "SharedMutex.h" 18 | 19 | COMMON_CONCURRENCY_SHARED_MUTEX_DECLARE_STATIC_STORAGE( 20 | folly::SharedMutexReadPriority); 21 | COMMON_CONCURRENCY_SHARED_MUTEX_DECLARE_STATIC_STORAGE( 22 | folly::SharedMutexWritePriority); 23 | -------------------------------------------------------------------------------- /folly/futures/test/ClientCompile.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // amazing what things can go wrong if you include things in an unexpected 18 | // order. 19 | #include 20 | #include 21 | #include 22 | int main() { return 0; } 23 | -------------------------------------------------------------------------------- /folly/test/CpuIdTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | 22 | using namespace folly; 23 | 24 | TEST(CpuId, Simple) { 25 | // All CPUs should support MMX 26 | CpuId id; 27 | EXPECT_TRUE(id.mmx()); 28 | } 29 | -------------------------------------------------------------------------------- /folly/futures/test/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | int main(int argc, char** argv) { 22 | ::testing::InitGoogleTest(&argc, argv); 23 | ::gflags::ParseCommandLineFlags(&argc, &argv, true); 24 | return RUN_ALL_TESTS(); 25 | } 26 | -------------------------------------------------------------------------------- /folly/wangle/concurrent/ThreadFactory.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | #include 19 | 20 | #include 21 | 22 | namespace folly { namespace wangle { 23 | 24 | class ThreadFactory { 25 | public: 26 | virtual ~ThreadFactory() {} 27 | virtual std::thread newThread(Func&& func) = 0; 28 | }; 29 | 30 | }} // folly::wangle 31 | -------------------------------------------------------------------------------- /folly/detail/ExceptionWrapper.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_DETAIL_EXCEPTIONWRAPPER_H 18 | #define FOLLY_DETAIL_EXCEPTIONWRAPPER_H 19 | 20 | namespace folly { namespace detail { 21 | 22 | template 23 | class Thrower { 24 | public: 25 | static void doThrow(std::exception* obj) { 26 | throw *static_cast(obj); 27 | } 28 | }; 29 | 30 | }} 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /folly/experimental/fibers/FiberManagerMap.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | #include 20 | 21 | namespace folly { namespace fibers { 22 | 23 | FiberManager& getFiberManager( 24 | folly::EventBase& evb, 25 | const FiberManager::Options& opts = FiberManager::Options()); 26 | 27 | }} 28 | -------------------------------------------------------------------------------- /folly/wangle/ssl/PasswordInFile.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #pragma once 11 | 12 | #include // PasswordCollector 13 | 14 | namespace folly { 15 | 16 | class PasswordInFile: public folly::PasswordCollector { 17 | public: 18 | explicit PasswordInFile(const std::string& file); 19 | ~PasswordInFile(); 20 | 21 | void getPassword(std::string& password, int size) override { 22 | password = password_; 23 | } 24 | 25 | const char* getPasswordStr() const { 26 | return password_.c_str(); 27 | } 28 | 29 | std::string describe() const override { 30 | return fileName_; 31 | } 32 | 33 | protected: 34 | std::string fileName_; 35 | std::string password_; 36 | }; 37 | 38 | } 39 | -------------------------------------------------------------------------------- /folly/io/async/AsyncSocketBase.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | #include 20 | 21 | namespace folly { 22 | 23 | class AsyncSocketBase { 24 | public: 25 | virtual EventBase* getEventBase() const = 0; 26 | virtual ~AsyncSocketBase() = default; 27 | virtual void getAddress(SocketAddress*) const = 0; 28 | }; 29 | 30 | } // namespace 31 | -------------------------------------------------------------------------------- /folly/io/async/Request.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed to the Apache Software Foundation (ASF) under one 5 | * or more contributor license agreements. See the NOTICE file 6 | * distributed with this work for additional information 7 | * regarding copyright ownership. The ASF licenses this file 8 | * to you under the Apache License, Version 2.0 (the 9 | * "License"); you may not use this file except in compliance 10 | * with the License. You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, 15 | * software distributed under the License is distributed on an 16 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | * KIND, either express or implied. See the License for the 18 | * specific language governing permissions and limitations 19 | * under the License. 20 | */ 21 | #include 22 | 23 | namespace folly { 24 | 25 | RequestContext* defaultContext; 26 | 27 | } 28 | -------------------------------------------------------------------------------- /folly/experimental/symbolizer/test/SignalHandlerTest.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_SYMBOLIZER_TEST_SIGNALHANDLERTEST_H_ 18 | #define FOLLY_SYMBOLIZER_TEST_SIGNALHANDLERTEST_H_ 19 | 20 | namespace folly { namespace symbolizer { namespace test { 21 | 22 | inline void failHard() { 23 | *(/* nolint */ volatile char*)42; // SIGSEGV 24 | } 25 | 26 | }}} // namespaces 27 | 28 | #endif /* FOLLY_SYMBOLIZER_TEST_SIGNALHANDLERTEST_H_ */ 29 | -------------------------------------------------------------------------------- /folly/futures/InlineExecutor.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | #include 19 | 20 | namespace folly { 21 | 22 | /// When work is "queued", execute it immediately inline. 23 | /// Usually when you think you want this, you actually want a 24 | /// QueuedImmediateExecutor. 25 | class InlineExecutor : public Executor { 26 | public: 27 | void add(Func f) override { 28 | f(); 29 | } 30 | }; 31 | 32 | } 33 | -------------------------------------------------------------------------------- /folly/GroupVarint.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #if HAVE_GROUP_VARINT 20 | namespace folly { 21 | 22 | const uint32_t GroupVarint32::kMask[] = { 23 | 0xff, 0xffff, 0xffffff, 0xffffffff 24 | }; 25 | 26 | const uint64_t GroupVarint64::kMask[] = { 27 | 0xff, 0xffff, 0xffffff, 0xffffffff, 28 | 0xffffffffffULL, 0xffffffffffffULL, 0xffffffffffffffULL, 29 | 0xffffffffffffffffULL 30 | }; 31 | 32 | } // namespace folly 33 | #endif 34 | -------------------------------------------------------------------------------- /folly/docs/SmallLocks.md: -------------------------------------------------------------------------------- 1 | `folly/SmallLocks.h` 2 | -------------------- 3 | 4 | This module is currently x64 only. 5 | 6 | This header defines two very small mutex types. These are useful in 7 | highly memory-constrained environments where contention is unlikely. 8 | The purpose of these is to allow fine-grained locking in massive data 9 | structures where memory is at a premium. Often, each record may have 10 | a spare bit or byte lying around, so sometimes these can be tacked on 11 | with no additional memory cost. 12 | 13 | There are two types exported from this header. `MicroSpinLock` is a 14 | single byte lock, and `PicoSpinLock` can be wrapped around an 15 | integer to use a single bit as a lock. Why do we have both? 16 | Because you can't use x64 `bts` on a single byte, so 17 | `sizeof(MicroSpinLock)` is smaller than `sizeof(PicoSpinLock)` can 18 | be, giving it some use cases. 19 | 20 | Both the locks in this header model the C++11 Lockable concept. So 21 | you can use `std::lock_guard` or `std::unique_lock` to lock them in an 22 | RAII way if you want. 23 | 24 | Additional information is in the header. 25 | -------------------------------------------------------------------------------- /folly/experimental/fibers/GuardPageAllocator.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | namespace folly { namespace fibers { 19 | 20 | /** 21 | * Stack allocator that protects an extra memory page after 22 | * the end of the stack. 23 | */ 24 | class GuardPageAllocator { 25 | public: 26 | inline unsigned char* allocate(size_t size); 27 | inline void deallocate(unsigned char* up, size_t size); 28 | }; 29 | 30 | }} // folly::fibers 31 | 32 | #include "GuardPageAllocator-inl.h" 33 | -------------------------------------------------------------------------------- /folly/experimental/fibers/test/main.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #include 17 | 18 | #include 19 | 20 | // for backward compatibility with gflags 21 | namespace gflags { } 22 | namespace google { using namespace gflags; } 23 | 24 | int main(int argc, char** argv) { 25 | testing::InitGoogleTest(&argc, argv); 26 | gflags::ParseCommandLineFlags(&argc, &argv, true); 27 | 28 | auto rc = RUN_ALL_TESTS(); 29 | folly::runBenchmarksOnFlag(); 30 | return rc; 31 | } 32 | -------------------------------------------------------------------------------- /folly/test/SafeAssertTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | 22 | #include 23 | 24 | using namespace folly; 25 | 26 | void fail() { 27 | FOLLY_SAFE_CHECK(0, "hello"); 28 | } 29 | 30 | void succeed() { 31 | FOLLY_SAFE_CHECK(1, "world"); 32 | } 33 | 34 | TEST(SafeAssert, AssertionFailure) { 35 | succeed(); 36 | EXPECT_DEATH(fail(), ".*Assertion failure:.*hello.*"); 37 | } 38 | -------------------------------------------------------------------------------- /folly/wangle/codec/ByteToMessageCodec.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #include 17 | 18 | namespace folly { namespace wangle { 19 | 20 | void ByteToMessageCodec::read(Context* ctx, IOBufQueue& q) { 21 | size_t needed = 0; 22 | std::unique_ptr result; 23 | while (true) { 24 | result = decode(ctx, q, needed); 25 | if (result) { 26 | ctx->fireRead(std::move(result)); 27 | } else { 28 | break; 29 | } 30 | } 31 | } 32 | 33 | }} // namespace 34 | -------------------------------------------------------------------------------- /folly/futures/QueuedImmediateExecutor.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | namespace folly { 22 | 23 | /** 24 | * Runs inline like InlineExecutor, but with a queue so that any tasks added 25 | * to this executor by one of its own callbacks will be queued instead of 26 | * executed inline (nested). This is usually better behavior than Inline. 27 | */ 28 | class QueuedImmediateExecutor : public Executor { 29 | public: 30 | void add(Func) override; 31 | }; 32 | 33 | } // folly 34 | -------------------------------------------------------------------------------- /folly/wangle/acceptor/SocketOptions.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #include 11 | 12 | #include 13 | #include 14 | 15 | namespace folly { 16 | 17 | AsyncSocket::OptionMap filterIPSocketOptions( 18 | const AsyncSocket::OptionMap& allOptions, 19 | const int addrFamily) { 20 | AsyncSocket::OptionMap opts; 21 | int exclude; 22 | if (addrFamily == AF_INET) { 23 | exclude = IPPROTO_IPV6; 24 | } else if (addrFamily == AF_INET6) { 25 | exclude = IPPROTO_IP; 26 | } else { 27 | LOG(FATAL) << "Address family " << addrFamily << " was not IPv4 or IPv6"; 28 | return opts; 29 | } 30 | for (const auto& opt: allOptions) { 31 | if (opt.first.level != exclude) { 32 | opts[opt.first] = opt.second; 33 | } 34 | } 35 | return opts; 36 | } 37 | 38 | } 39 | -------------------------------------------------------------------------------- /folly/futures/QueuedImmediateExecutor.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | namespace folly { 22 | 23 | void QueuedImmediateExecutor::add(Func callback) { 24 | thread_local std::queue q; 25 | 26 | if (q.empty()) { 27 | q.push(std::move(callback)); 28 | while (!q.empty()) { 29 | q.front()(); 30 | q.pop(); 31 | } 32 | } else { 33 | q.push(callback); 34 | } 35 | } 36 | 37 | } // namespace 38 | -------------------------------------------------------------------------------- /folly/futures/Unit.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | namespace folly { 18 | 19 | struct Unit { 20 | template struct Lift : public std::false_type { 21 | using type = T; 22 | }; 23 | }; 24 | 25 | template <> 26 | struct Unit::Lift : public std::true_type { 27 | using type = Unit; 28 | }; 29 | 30 | template 31 | struct is_void_or_unit : public std::conditional< 32 | std::is_void::value || std::is_same::value, 33 | std::true_type, 34 | std::false_type>::type 35 | {}; 36 | 37 | } 38 | -------------------------------------------------------------------------------- /folly/Chrono.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Wrapper around that hides away some gcc 4.6 issues 18 | #ifndef FOLLY_CHRONO_H_ 19 | #define FOLLY_CHRONO_H_ 20 | 21 | #include 22 | #include 23 | 24 | // gcc 4.6 uses an obsolete name for steady_clock, although the implementation 25 | // is the same 26 | #if __GNUC_PREREQ(4, 6) && !__GNUC_PREREQ(4, 7) 27 | namespace std { namespace chrono { 28 | typedef monotonic_clock steady_clock; 29 | }} // namespaces 30 | #endif 31 | 32 | #endif /* FOLLY_CHRONO_H_ */ 33 | -------------------------------------------------------------------------------- /folly/detail/MallocImpl.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | extern "C" { 20 | 21 | #if !FOLLY_HAVE_WEAK_SYMBOLS 22 | void* (*mallocx)(size_t, int) = nullptr; 23 | void* (*rallocx)(void*, size_t, int) = nullptr; 24 | size_t (*xallocx)(void*, size_t, size_t, int) = nullptr; 25 | size_t (*sallocx)(const void*, int) = nullptr; 26 | void (*dallocx)(void*, int) = nullptr; 27 | size_t (*nallocx)(size_t, int) = nullptr; 28 | int (*mallctl)(const char*, void*, size_t*, void*, size_t) = nullptr; 29 | #endif 30 | 31 | } 32 | -------------------------------------------------------------------------------- /folly/detail/FunctionalExcept.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_DETAIL_FUNCTIONAL_EXCEPT_H 18 | #define FOLLY_DETAIL_FUNCTIONAL_EXCEPT_H 19 | 20 | #include 21 | 22 | FOLLY_NAMESPACE_STD_BEGIN 23 | 24 | FOLLY_NORETURN void __throw_length_error(const char* msg); 25 | FOLLY_NORETURN void __throw_logic_error(const char* msg); 26 | FOLLY_NORETURN void __throw_out_of_range(const char* msg); 27 | 28 | #ifdef _MSC_VER 29 | FOLLY_NORETURN void __throw_bad_alloc(); 30 | #endif 31 | 32 | FOLLY_NAMESPACE_STD_END 33 | 34 | #endif 35 | -------------------------------------------------------------------------------- /folly/wangle/concurrent/BlockingQueue.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | namespace folly { namespace wangle { 22 | 23 | template 24 | class BlockingQueue { 25 | public: 26 | virtual ~BlockingQueue() {} 27 | virtual void add(T item) = 0; 28 | virtual void addWithPriority(T item, int8_t priority) { 29 | add(std::move(item)); 30 | } 31 | virtual uint8_t getNumPriorities() { 32 | return 1; 33 | } 34 | virtual T take() = 0; 35 | virtual size_t size() = 0; 36 | }; 37 | 38 | }} // folly::wangle 39 | -------------------------------------------------------------------------------- /folly/experimental/exception_tracer/README.md: -------------------------------------------------------------------------------- 1 | Exception tracer library 2 | 3 | This library allows you to inspect the exception stack at runtime. 4 | The library can be used in three ways: 5 | 6 | 1. Link in the exception_tracer_base library. You get access to the functions 7 | in ExceptionTracer.h, but no stack traces. This has no runtime overhead, 8 | and is compliant with the C++ ABI. 9 | 10 | 2. Link in the (full) exception_tracer library. You get access to the 11 | functions in ExceptionTracer.h, the std::terminate and std::unexpected 12 | handlers are installed by default, and you get full stack traces with 13 | all exceptions. This has some runtime overhead (the stack trace must be 14 | captured and stored whenever an exception is thrown) added to throw 15 | and catch, but no runtime overhead otherwise. This is less portable 16 | (depends on internal details of GNU's libstdc++). 17 | 18 | 3. LD_PRELOAD libexceptiontracer.so. This is equivalent to #2 above, but 19 | requires no link-time changes. On the other hand, you need to ensure that 20 | libexceptiontracer.so is compiled with the same compiler and flags as 21 | your binary, and the usual caveats about LD_PRELOAD apply (it propagates 22 | to child processes, etc). 23 | -------------------------------------------------------------------------------- /folly/detail/FunctionalExcept.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | 21 | FOLLY_NAMESPACE_STD_BEGIN 22 | 23 | void __throw_length_error(const char* msg) { 24 | throw std::length_error(msg); 25 | } 26 | 27 | void __throw_logic_error(const char* msg) { 28 | throw std::logic_error(msg); 29 | } 30 | 31 | void __throw_out_of_range(const char* msg) { 32 | throw std::out_of_range(msg); 33 | } 34 | 35 | #if defined(_MSC_VER) 36 | void __throw_bad_alloc() { 37 | throw std::bad_alloc(); 38 | } 39 | #endif 40 | 41 | FOLLY_NAMESPACE_STD_END 42 | -------------------------------------------------------------------------------- /folly/gen/Core.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_GEN_CORE_H 18 | #define FOLLY_GEN_CORE_H 19 | 20 | namespace folly { namespace gen { 21 | 22 | template 23 | class GenImpl; 24 | 25 | template 26 | class Operator; 27 | 28 | namespace detail { 29 | 30 | template 31 | struct FBounded; 32 | 33 | template 34 | class Composed; 35 | 36 | template 37 | class Chain; 38 | 39 | } // detail 40 | 41 | }} // folly::gen 42 | 43 | #include 44 | 45 | #endif // FOLLY_GEN_CORE_H 46 | -------------------------------------------------------------------------------- /folly/Unicode.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Some utility routines relating to unicode. 18 | 19 | #ifndef FOLLY_UNICODE_H_ 20 | #define FOLLY_UNICODE_H_ 21 | 22 | #include 23 | 24 | namespace folly { 25 | 26 | ////////////////////////////////////////////////////////////////////// 27 | 28 | /* 29 | * Encode a single unicode code point into a UTF-8 byte sequence. 30 | * 31 | * Return value is undefined if `cp' is an invalid code point. 32 | */ 33 | fbstring codePointToUtf8(char32_t cp); 34 | 35 | ////////////////////////////////////////////////////////////////////// 36 | 37 | } 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /folly/Likely.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | /** 18 | * Compiler hints to indicate the fast path of an "if" branch: whether 19 | * the if condition is likely to be true or false. 20 | * 21 | * @author Tudor Bosman (tudorb@fb.com) 22 | */ 23 | 24 | #ifndef FOLLY_BASE_LIKELY_H_ 25 | #define FOLLY_BASE_LIKELY_H_ 26 | 27 | #undef LIKELY 28 | #undef UNLIKELY 29 | 30 | #if defined(__GNUC__) && __GNUC__ >= 4 31 | #define LIKELY(x) (__builtin_expect((x), 1)) 32 | #define UNLIKELY(x) (__builtin_expect((x), 0)) 33 | #else 34 | #define LIKELY(x) (x) 35 | #define UNLIKELY(x) (x) 36 | #endif 37 | 38 | #endif /* FOLLY_BASE_LIKELY_H_ */ 39 | -------------------------------------------------------------------------------- /folly/io/async/test/certs/tests-cert.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDKzCCAhOgAwIBAgIBCjANBgkqhkiG9w0BAQUFADBFMQswCQYDVQQGEwJVUzEP 3 | MA0GA1UECgwGVGhyaWZ0MSUwIwYDVQQDDBxUaHJpZnQgQ2VydGlmaWNhdGUgQXV0 4 | aG9yaXR5MB4XDTE0MDUxNjIwMjg1MloXDTQxMTAwMTIwMjg1MlowRjELMAkGA1UE 5 | BhMCVVMxDTALBgNVBAgTBE9oaW8xETAPBgNVBAcTCEhpbGxpYXJkMRUwEwYDVQQD 6 | EwxBc294IENvbXBhbnkwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQCz 7 | ZGrJ5XQHAuMYHlBgn32OOc9l0n3RjXccio2ceeWctXkSxDP3vFyZ4kBILF1lsY1g 8 | o8UTjMkqSDYcytCLK0qavrv9BZRLB9FcpqJ9o4V9feaI/HsHa8DYHyEs8qyNTTNG 9 | YQ3i4j+AA9iDSpezIYy/tyAOAjrSquUW1jI4tzKTBh8hk8MAMvR2/NPHPkrp4gI+ 10 | EMH6u4vWdr4F9bbriLFWoU04T9mWOMk7G+h8BS9sgINg2+v5cWvl3BC4kLk5L1yJ 11 | FEyuofSSCEEe6dDf7uVh+RPKa4hEkIYo31AEOPFrN56d+pCj/5l67HTWXoQx3rjy 12 | dNXMvgU75urm6TQe8dB5AgMBAAGjJTAjMCEGA1UdEQQaMBiHBH8AAAGHEAAAAAAA 13 | AAAAAAAAAAAAAAEwDQYJKoZIhvcNAQEFBQADggEBAD26XYInaEvlWZJYgtl3yQyC 14 | 3NRQc3LG7XxWg4aFdXCxYLPRAL2HLoarKYH8GPFso57t5xnhA8WfP7iJxmgsKdCS 15 | 0pNIicOWsMmXvYLib0j9tMCFR+a8rn3f4n+clwnqas4w/vWBJUoMgyxtkP8NNNZO 16 | kIl02JKRhuyiFyPLilVp5tu0e+lmyUER+ak53WjLq2yoytYAlHkzkOpc4MZ/TNt5 17 | UTEtx/WVlZvlrPi3dsi7QikkjQgo1wCnm7owtuAHlPDMAB8wKk4+vvIOjsGM33T/ 18 | 8ffq/4X1HeYM0w0fM+SVlX1rwkXA1RW/jn48VWFHpWbE10+m196OdiToGfm2OJI= 19 | -----END CERTIFICATE----- 20 | -------------------------------------------------------------------------------- /folly/test/AsciiCaseInsensitiveTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | using namespace std; 24 | using namespace folly; 25 | 26 | TEST(CaseInsensitiveMatch, CompareWithLegacy) { 27 | AsciiCaseInsensitive cmp; 28 | for (int i=0; i<(1<<8); i++) { 29 | EXPECT_TRUE(cmp(tolower(i), toupper(i))); 30 | EXPECT_TRUE(cmp(toupper(i), tolower(i))); 31 | } 32 | } 33 | 34 | int main(int argc, char** argv) { 35 | testing::InitGoogleTest(&argc, argv); 36 | gflags::ParseCommandLineFlags(&argc, &argv, true); 37 | return RUN_ALL_TESTS(); 38 | } 39 | -------------------------------------------------------------------------------- /folly/StringBase.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | namespace folly { 20 | 21 | StringPiece skipWhitespace(StringPiece sp) { 22 | // Spaces other than ' ' characters are less common but should be 23 | // checked. This configuration where we loop on the ' ' 24 | // separately from oddspaces was empirically fastest. 25 | auto oddspace = [] (char c) { 26 | return c == '\n' || c == '\t' || c == '\r'; 27 | }; 28 | 29 | loop: 30 | for (; !sp.empty() && sp.front() == ' '; sp.pop_front()) { 31 | } 32 | if (!sp.empty() && oddspace(sp.front())) { 33 | sp.pop_front(); 34 | goto loop; 35 | } 36 | 37 | return sp; 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /folly/io/async/test/certs/ca-cert.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN CERTIFICATE----- 2 | MIIDXTCCAkWgAwIBAgIJAKMZICGWUzawMA0GCSqGSIb3DQEBBQUAMEUxCzAJBgNV 3 | BAYTAlVTMQ8wDQYDVQQKDAZUaHJpZnQxJTAjBgNVBAMMHFRocmlmdCBDZXJ0aWZp 4 | Y2F0ZSBBdXRob3JpdHkwHhcNMTQwNTE2MjAyODUyWhcNNDExMDAxMjAyODUyWjBF 5 | MQswCQYDVQQGEwJVUzEPMA0GA1UECgwGVGhyaWZ0MSUwIwYDVQQDDBxUaHJpZnQg 6 | Q2VydGlmaWNhdGUgQXV0aG9yaXR5MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIB 7 | CgKCAQEA1Bx2vUvXZ8PrvEBxwdH5qM1F2Xo7UkeC1jzQ+OLUBEcCiEduyStitSvB 8 | NOAzAGdjt7NmHTP/7OJngp2vzQGjSQzm20XacyTieFUuPBuikUc0Ge3Tf+uQXtiU 9 | zZPh+xn6arHH+zBWtmUCt3cBrpgRqdnWUsbl8eqo5HsczY781FxQbDoT9VP6A+9R 10 | KGTsEhxxKbWJ1C7OngwLKc7Zv4DtTC1JFlFyKd8ryDtxP4s/GgsXJkoK0Hkpputr 11 | cMxMm6OGt77mFvzR2qRY1CpEK/9rjBB6Gqd8GakXsvoOsqL/37k2wVhN/JoS/Pde 12 | 12Mp6TZ2rA8NW8vRujfWU0u55gnQnwIDAQABo1AwTjAdBgNVHQ4EFgQUQ00NGVmY 13 | NZ6LJg8UQUOVLZX1Gh8wHwYDVR0jBBgwFoAUQ00NGVmYNZ6LJg8UQUOVLZX1Gh8w 14 | DAYDVR0TBAUwAwEB/zANBgkqhkiG9w0BAQUFAAOCAQEAdlxt5+z9uXCBr1Wt6r49 15 | 4MmOYw9lOnEOG1JPMRo108TLpmwXEWReCAtjQuR7BitRJW0kJtlO1M6t3qoIh6GA 16 | sBkgsjQM1xNY3YEpx71MLt1V+JD+2WtSBKMyysj1TiOmIH66kkvXO3ptXzhjhZyX 17 | G6B+kxLtxrqkn9SJULyN55X8T+dkW28UIBZVLavoREDU+UPrYU9JgZeIVObtGSWi 18 | DvS4RIJZNjgG3vTrT00rfUGEfTlI54Vbcmv0cYvswP/nMsLtDStCdgI7c/ipyJve 19 | dfuI4CedjE240AxK5OFxFg/k/IfnB4a5oojbdIR9hKrTU57TPaUVD50Na9WA1aqX 20 | 5Q== 21 | -----END CERTIFICATE----- 22 | -------------------------------------------------------------------------------- /folly/test/FileTestLockHelper.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include 19 | 20 | #include 21 | 22 | DEFINE_bool(s, false, "get shared lock"); 23 | DEFINE_bool(x, false, "get exclusive lock"); 24 | 25 | int main(int argc, char *argv[]) { 26 | gflags::ParseCommandLineFlags(&argc, &argv, true); 27 | google::InitGoogleLogging(argv[0]); 28 | CHECK_EQ(FLAGS_s + FLAGS_x, 1) 29 | << "exactly one of -s and -x must be specified"; 30 | CHECK_EQ(argc, 2); 31 | folly::File f(argv[1], O_RDWR); 32 | bool r; 33 | if (FLAGS_s) { 34 | r = f.try_lock_shared(); 35 | } else { 36 | r = f.try_lock(); 37 | } 38 | return r ? 0 : 42; 39 | } 40 | -------------------------------------------------------------------------------- /folly/test/function_benchmark/test_functions.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef TEST_FUNCTIONS_H_ 18 | #define TEST_FUNCTIONS_H_ 19 | 20 | #include 21 | #include 22 | 23 | void doNothing(); 24 | 25 | void throwException(); 26 | std::exception_ptr returnExceptionPtr(); 27 | void exceptionPtrReturnParam(std::exception_ptr* excReturn); 28 | std::string returnString(); 29 | std::string returnStringNoExcept() noexcept; 30 | int returnCode(int value); 31 | int returnCodeNoExcept(int value) noexcept; 32 | 33 | class TestClass { 34 | public: 35 | void doNothing(); 36 | }; 37 | 38 | class VirtualClass { 39 | public: 40 | virtual ~VirtualClass(); 41 | virtual void doNothing(); 42 | }; 43 | 44 | #endif // TEST_FUNCTIONS_H_ 45 | -------------------------------------------------------------------------------- /folly/bootstrap-osx-homebrew.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash -x 2 | # The only prerequisite should be homebrew. If something doesn't work out of 3 | # the box with just homebrew, let's fix it. 4 | 5 | # fail fast 6 | set -e 7 | 8 | brewget() { 9 | brew install $@ || brew upgrade $@ 10 | } 11 | 12 | # tool dependencies: autotools and scons (for double-conversion) 13 | brewget autoconf automake libtool scons 14 | 15 | # dependencies 16 | brewget glog gflags boost libevent 17 | 18 | # Install the double-conversion library. 19 | # NB their install target installs the libs but not the headers, hence the 20 | # CPPFLAGS and link shenanigans. 21 | test -d double-conversion || { 22 | git clone https://github.com/floitsch/double-conversion.git 23 | pushd double-conversion/src 24 | ln -s . double-conversion 25 | popd 26 | } 27 | pushd double-conversion 28 | scons 29 | # fool libtool into using static linkage 30 | # (this won't work if you've already installed libdouble-conversion into a 31 | # default search path) 32 | rm -f libdouble-conversion*dylib 33 | DOUBLE_CONVERSION_HOME=$(pwd) 34 | popd 35 | 36 | autoreconf -i 37 | ./configure CPPFLAGS=-I"$DOUBLE_CONVERSION_HOME/src" LDFLAGS=-L"$DOUBLE_CONVERSION_HOME" 38 | 39 | pushd test 40 | test -e gtest-1.7.0.zip || { 41 | curl -O https://googletest.googlecode.com/files/gtest-1.7.0.zip 42 | unzip gtest-1.7.0.zip 43 | } 44 | popd 45 | -------------------------------------------------------------------------------- /folly/SingletonVault_c.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Plain C interface to SingletonVault. This facilitates combining programs 18 | // that cannot use C++ (e.g. programs written in C) with libraries that use 19 | // Singleton, by allowing the program to perform the required SingletonVault 20 | // lifecycle calls. 21 | 22 | #pragma once 23 | 24 | #ifdef __cplusplus 25 | extern "C" { 26 | #endif 27 | 28 | typedef void SingletonVault_t; 29 | 30 | SingletonVault_t *SingletonVault_singleton(); 31 | void SingletonVault_registrationComplete(SingletonVault_t *vault); 32 | void SingletonVault_destroyInstances(SingletonVault_t *vault); 33 | void SingletonVault_reenableInstances(SingletonVault_t *vault); 34 | 35 | #ifdef __cplusplus 36 | } // extern "C" 37 | #endif 38 | -------------------------------------------------------------------------------- /folly/detail/Clock.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_DETAIL_CLOCK_H_ 18 | #define FOLLY_DETAIL_CLOCK_H_ 19 | 20 | #include 21 | #include 22 | 23 | #include 24 | 25 | #if FOLLY_HAVE_CLOCK_GETTIME 26 | #error This should only be used as a workaround for platforms \ 27 | that do not support clock_gettime(2). 28 | #endif 29 | 30 | /* For windows, we'll use pthread's time implementations */ 31 | #ifdef _MSC_VER 32 | #include 33 | #include 34 | #else 35 | typedef uint8_t clockid_t; 36 | #define CLOCK_REALTIME 0 37 | 38 | int clock_gettime(clockid_t clk_id, struct timespec* ts); 39 | int clock_getres(clockid_t clk_id, struct timespec* ts); 40 | #endif 41 | 42 | #endif /* FOLLY_DETAIL_CLOCK_H_ */ 43 | -------------------------------------------------------------------------------- /folly/wangle/acceptor/LoadShedConfiguration.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #include 11 | 12 | #include 13 | #include 14 | 15 | using std::string; 16 | 17 | namespace folly { 18 | 19 | void LoadShedConfiguration::addWhitelistAddr(folly::StringPiece input) { 20 | auto addr = input.str(); 21 | size_t separator = addr.find_first_of('/'); 22 | if (separator == string::npos) { 23 | whitelistAddrs_.insert(SocketAddress(addr, 0)); 24 | } else { 25 | unsigned prefixLen = folly::to(addr.substr(separator + 1)); 26 | addr.erase(separator); 27 | whitelistNetworks_.insert(NetworkAddress(SocketAddress(addr, 0), prefixLen)); 28 | } 29 | } 30 | 31 | bool LoadShedConfiguration::isWhitelisted(const SocketAddress& address) const { 32 | if (whitelistAddrs_.find(address) != whitelistAddrs_.end()) { 33 | return true; 34 | } 35 | for (auto& network : whitelistNetworks_) { 36 | if (network.contains(address)) { 37 | return true; 38 | } 39 | } 40 | return false; 41 | } 42 | 43 | } 44 | -------------------------------------------------------------------------------- /folly/SingletonVault_c.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include 19 | 20 | #ifdef __cplusplus 21 | extern "C" { 22 | #endif 23 | 24 | SingletonVault_t *SingletonVault_singleton() { 25 | return folly::SingletonVault::singleton(); 26 | } 27 | 28 | void SingletonVault_registrationComplete(SingletonVault_t *vault) { 29 | ((folly::SingletonVault*) vault)->registrationComplete(); 30 | } 31 | 32 | void SingletonVault_destroyInstances(SingletonVault_t *vault) { 33 | ((folly::SingletonVault*) vault)->destroyInstances(); 34 | } 35 | 36 | void SingletonVault_reenableInstances(SingletonVault_t *vault) { 37 | ((folly::SingletonVault*) vault)->reenableInstances(); 38 | } 39 | 40 | #ifdef __cplusplus 41 | } // extern "C" 42 | #endif 43 | -------------------------------------------------------------------------------- /folly/gen/Combine.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_GEN_COMBINE_H 18 | #define FOLLY_GEN_COMBINE_H 19 | 20 | #include 21 | 22 | namespace folly { 23 | namespace gen { 24 | namespace detail { 25 | 26 | template 27 | class Interleave; 28 | 29 | template 30 | class Zip; 31 | 32 | } // namespace detail 33 | 34 | template::type, 36 | class Interleave = detail::Interleave> 37 | Interleave interleave(Source2&& source2) { 38 | return Interleave(std::forward(source2)); 39 | } 40 | 41 | } // namespace gen 42 | } // namespace folly 43 | 44 | #include 45 | 46 | #endif // FOLLY_GEN_COMBINE_H 47 | -------------------------------------------------------------------------------- /folly/wangle/rx/types.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | #include 21 | 22 | namespace folly { namespace wangle { 23 | typedef folly::exception_wrapper Error; 24 | // The Executor is basically an rx Scheduler (by design). So just 25 | // alias it. 26 | typedef std::shared_ptr SchedulerPtr; 27 | 28 | template class Observable; 29 | template struct Observer; 30 | template struct Subject; 31 | 32 | template using ObservablePtr = std::shared_ptr>; 33 | template using ObserverPtr = std::shared_ptr>; 34 | template using SubjectPtr = std::shared_ptr>; 35 | }} 36 | -------------------------------------------------------------------------------- /folly/Checksum.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_CHECKSUM_H_ 18 | #define FOLLY_CHECKSUM_H_ 19 | 20 | #include 21 | #include 22 | 23 | /* 24 | * Checksum functions 25 | */ 26 | 27 | namespace folly { 28 | 29 | /** 30 | * Compute the CRC-32C checksum of a buffer, using a hardware-accelerated 31 | * implementation if available or a portable software implementation as 32 | * a default. 33 | * 34 | * @note CRC-32C is different from CRC-32; CRC-32C starts with a different 35 | * polynomial and thus yields different results for the same input 36 | * than a traditional CRC-32. 37 | */ 38 | uint32_t crc32c(const uint8_t* data, size_t nbytes, 39 | uint32_t startingChecksum = ~0U); 40 | 41 | } // folly 42 | 43 | #endif /* FOLLY_CHECKSUM_H_ */ 44 | -------------------------------------------------------------------------------- /folly/ThreadName.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | #include 21 | 22 | namespace folly { 23 | 24 | // This looks a bit weird, but it's necessary to avoid 25 | // having an undefined compiler function called. 26 | #if defined(__GLIBC__) && !defined(__APPLE__) && !defined(__ANDROID__) 27 | #if __GLIBC_PREREQ(2, 12) 28 | # define FOLLY_HAS_PTHREAD_SETNAME_NP 29 | #endif 30 | #endif 31 | 32 | inline bool setThreadName(pthread_t id, StringPiece name) { 33 | #ifdef FOLLY_HAS_PTHREAD_SETNAME_NP 34 | return 0 == pthread_setname_np(id, name.fbstr().substr(0, 15).c_str()); 35 | #else 36 | return false; 37 | #endif 38 | } 39 | 40 | inline bool setThreadName(StringPiece name) { 41 | return setThreadName(pthread_self(), name); 42 | } 43 | 44 | } 45 | -------------------------------------------------------------------------------- /folly/SpinLock.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | namespace folly { 22 | 23 | #if __x86_64__ 24 | typedef SpinLockMslImpl SpinLock; 25 | #elif __APPLE__ 26 | typedef SpinLockAppleImpl SpinLock; 27 | #elif FOLLY_HAVE_PTHREAD_SPINLOCK_T 28 | typedef SpinLockPthreadImpl SpinLock; 29 | #else 30 | typedef SpinLockPthreadMutexImpl SpinLock; 31 | #endif 32 | 33 | template 34 | class SpinLockGuardImpl : private boost::noncopyable { 35 | public: 36 | FOLLY_ALWAYS_INLINE explicit SpinLockGuardImpl(LOCK& lock) : 37 | lock_(lock) { 38 | lock_.lock(); 39 | } 40 | FOLLY_ALWAYS_INLINE ~SpinLockGuardImpl() { 41 | lock_.unlock(); 42 | } 43 | private: 44 | LOCK& lock_; 45 | }; 46 | 47 | typedef SpinLockGuardImpl SpinLockGuard; 48 | 49 | } 50 | -------------------------------------------------------------------------------- /folly/Uri-inl.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_URI_H_ 18 | #error This file may only be included from folly/Uri.h 19 | #endif 20 | 21 | #include 22 | 23 | namespace folly { 24 | 25 | template 26 | String Uri::toString() const { 27 | String str; 28 | toAppend(scheme_, "://", &str); 29 | if (!password_.empty()) { 30 | toAppend(username_, ":", password_, "@", &str); 31 | } else if (!username_.empty()) { 32 | toAppend(username_, "@", &str); 33 | } 34 | toAppend(host_, &str); 35 | if (port_ != 0) { 36 | toAppend(":", port_, &str); 37 | } 38 | toAppend(path_, &str); 39 | if (!query_.empty()) { 40 | toAppend("?", query_, &str); 41 | } 42 | if (!fragment_.empty()) { 43 | toAppend("#", fragment_, &str); 44 | } 45 | return str; 46 | } 47 | 48 | } // namespace folly 49 | -------------------------------------------------------------------------------- /folly/test/PortabilityTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | 21 | #include 22 | 23 | class Base { 24 | public: 25 | virtual ~Base() { } 26 | virtual int foo() const { return 1; } 27 | }; 28 | 29 | class Derived : public Base { 30 | public: 31 | virtual int foo() const FOLLY_FINAL { return 2; } 32 | }; 33 | 34 | // A compiler that supports final will likely inline the call to p->foo() 35 | // in fooDerived (but not in fooBase) as it knows that Derived::foo() can 36 | // no longer be overridden. 37 | int fooBase(const Base* p) { return p->foo() + 1; } 38 | int fooDerived(const Derived* p) { return p->foo() + 1; } 39 | 40 | TEST(Portability, Final) { 41 | std::unique_ptr p(new Derived); 42 | EXPECT_EQ(3, fooBase(p.get())); 43 | EXPECT_EQ(3, fooDerived(p.get())); 44 | } 45 | -------------------------------------------------------------------------------- /folly/io/async/EventUtil.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed to the Apache Software Foundation (ASF) under one 5 | * or more contributor license agreements. See the NOTICE file 6 | * distributed with this work for additional information 7 | * regarding copyright ownership. The ASF licenses this file 8 | * to you under the Apache License, Version 2.0 (the 9 | * "License"); you may not use this file except in compliance 10 | * with the License. You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, 15 | * software distributed under the License is distributed on an 16 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 17 | * KIND, either express or implied. See the License for the 18 | * specific language governing permissions and limitations 19 | * under the License. 20 | */ 21 | #pragma once 22 | 23 | #include // libevent 24 | 25 | namespace folly { 26 | 27 | /** 28 | * low-level libevent utility functions 29 | */ 30 | class EventUtil { 31 | public: 32 | static bool isEventRegistered(const struct event* ev) { 33 | // If any of these flags are set, the event is registered. 34 | enum { 35 | EVLIST_REGISTERED = (EVLIST_INSERTED | EVLIST_ACTIVE | 36 | EVLIST_TIMEOUT | EVLIST_SIGNAL) 37 | }; 38 | return (ev->ev_flags & EVLIST_REGISTERED); 39 | } 40 | }; 41 | 42 | } // folly 43 | -------------------------------------------------------------------------------- /folly/test/HistogramBenchmark.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #include 17 | 18 | #include 19 | 20 | #include 21 | #include 22 | 23 | using folly::Histogram; 24 | 25 | void addValue(unsigned int n, int64_t bucketSize, int64_t min, int64_t max) { 26 | Histogram hist(bucketSize, min, max); 27 | int64_t num = min; 28 | FOR_EACH_RANGE (i, 0, n) { 29 | hist.addValue(num); 30 | ++num; 31 | if (num > max) { num = min; } 32 | } 33 | } 34 | 35 | BENCHMARK_NAMED_PARAM(addValue, 0_to_100, 1, 0, 100); 36 | BENCHMARK_NAMED_PARAM(addValue, 0_to_1000, 10, 0, 1000); 37 | BENCHMARK_NAMED_PARAM(addValue, 5k_to_20k, 250, 5000, 20000); 38 | 39 | int main(int argc, char *argv[]) { 40 | gflags::ParseCommandLineFlags(&argc, &argv, true); 41 | folly::runBenchmarks(); 42 | return 0; 43 | } 44 | -------------------------------------------------------------------------------- /folly/futures/test/UnitTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include 19 | 20 | using namespace folly; 21 | 22 | TEST(Unit, FutureDefaultCtor) { 23 | Future(); 24 | } 25 | 26 | TEST(Unit, voidOrUnit) { 27 | EXPECT_TRUE(is_void_or_unit::value); 28 | EXPECT_TRUE(is_void_or_unit::value); 29 | EXPECT_FALSE(is_void_or_unit::value); 30 | } 31 | 32 | TEST(Unit, PromiseSetValue) { 33 | Promise p; 34 | p.setValue(); 35 | } 36 | 37 | TEST(Unit, LiftInt) { 38 | using Lifted = Unit::Lift; 39 | EXPECT_FALSE(Lifted::value); 40 | auto v = std::is_same::value; 41 | EXPECT_TRUE(v); 42 | } 43 | 44 | TEST(Unit, LiftVoid) { 45 | using Lifted = Unit::Lift; 46 | EXPECT_TRUE(Lifted::value); 47 | auto v = std::is_same::value; 48 | EXPECT_TRUE(v); 49 | } 50 | -------------------------------------------------------------------------------- /folly/gen/test/Bench.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_GEN_BENCH_H_ 18 | #define FOLLY_GEN_BENCH_H_ 19 | 20 | #include 21 | 22 | #define BENCH_GEN_IMPL(gen, prefix) \ 23 | static bool FB_ANONYMOUS_VARIABLE(benchGen) = ( \ 24 | ::folly::addBenchmark(__FILE__, prefix FB_STRINGIZE(gen), \ 25 | [](unsigned iters){ \ 26 | const unsigned num = iters; \ 27 | while (iters--) { \ 28 | folly::doNotOptimizeAway(gen); \ 29 | } \ 30 | return num; \ 31 | }), true) 32 | #define BENCH_GEN(gen) BENCH_GEN_IMPL(gen, "") 33 | #define BENCH_GEN_REL(gen) BENCH_GEN_IMPL(gen, "%") 34 | 35 | #endif 36 | -------------------------------------------------------------------------------- /folly/test/MoveWrapperTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | 22 | namespace folly { 23 | 24 | TEST(makeMoveWrapper, Empty) { 25 | // checks for crashes 26 | auto p = makeMoveWrapper(std::unique_ptr()); 27 | } 28 | 29 | TEST(makeMoveWrapper, NonEmpty) { 30 | auto u = std::unique_ptr(new int(5)); 31 | EXPECT_EQ(*u, 5); 32 | auto p = makeMoveWrapper(std::move(u)); 33 | EXPECT_TRUE(!u); 34 | EXPECT_EQ(**p, 5); 35 | } 36 | 37 | TEST(makeMoveWrapper, rvalue) { 38 | std::unique_ptr p; 39 | makeMoveWrapper(std::move(p)); 40 | } 41 | 42 | TEST(makeMoveWrapper, lvalue) { 43 | std::unique_ptr p; 44 | makeMoveWrapper(p); 45 | } 46 | 47 | TEST(makeMoveWrapper, lvalue_copyable) { 48 | std::shared_ptr p; 49 | makeMoveWrapper(p); 50 | } 51 | 52 | } // namespace 53 | -------------------------------------------------------------------------------- /folly/experimental/symbolizer/ElfUtil.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | #include 19 | 20 | #include 21 | 22 | #include 23 | #include 24 | 25 | using namespace folly; 26 | using namespace folly::symbolizer; 27 | 28 | int main(int argc, char *argv[]) { 29 | gflags::ParseCommandLineFlags(&argc, &argv, true); 30 | CHECK_GE(argc, 2); 31 | 32 | ElfFile elf(argv[1]); 33 | 34 | if (argc > 2) { 35 | auto section = elf.getSectionByName(argv[2]); 36 | printf("Section %s: %s\n", 37 | argv[2], 38 | (section ? "found" : "not found")); 39 | } 40 | 41 | auto sym = elf.getDefinitionByAddress(reinterpret_cast(main)); 42 | if (sym.first) { 43 | printf("found %s\n", elf.getSymbolName(sym)); 44 | } else { 45 | printf("main not found\n"); 46 | } 47 | 48 | return 0; 49 | } 50 | -------------------------------------------------------------------------------- /folly/LifoSem.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | /// Raw node storage is preallocated in a contiguous memory segment, 20 | /// but we use an anonymous mmap so the physical memory used (RSS) will 21 | /// only reflect the maximum number of waiters that actually existed 22 | /// concurrently. For blocked threads the max node count is limited by the 23 | /// number of threads, so we can conservatively estimate that this will be 24 | /// < 10k. For LifoEventSem, however, we could potentially have many more. 25 | /// 26 | /// On a 64-bit architecture each LifoSemRawNode takes 16 bytes. We make 27 | /// the pool 1 million entries. 28 | 29 | LIFOSEM_DECLARE_POOL(std::atomic, 1000000) 30 | 31 | namespace folly { 32 | 33 | ShutdownSemError::ShutdownSemError(const std::string& msg) 34 | : std::runtime_error(msg) 35 | {} 36 | 37 | ShutdownSemError::~ShutdownSemError() noexcept { 38 | } 39 | 40 | } 41 | -------------------------------------------------------------------------------- /folly/wangle/service/ServerDispatcher.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | #include 20 | 21 | namespace folly { namespace wangle { 22 | 23 | /** 24 | * Dispatch requests from pipeline one at a time synchronously. 25 | * Concurrent requests are queued in the pipeline. 26 | */ 27 | template 28 | class SerialServerDispatcher : public HandlerAdapter { 29 | public: 30 | 31 | typedef typename HandlerAdapter::Context Context; 32 | 33 | explicit SerialServerDispatcher(Service* service) 34 | : service_(service) {} 35 | 36 | void read(Context* ctx, Req in) override { 37 | auto resp = (*service_)(std::move(in)).get(); 38 | ctx->fireWrite(std::move(resp)); 39 | } 40 | 41 | private: 42 | 43 | Service* service_; 44 | }; 45 | 46 | }} // namespace 47 | -------------------------------------------------------------------------------- /folly/ThreadCachedArena.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | namespace folly { 20 | 21 | ThreadCachedArena::ThreadCachedArena(size_t minBlockSize, size_t maxAlign) 22 | : minBlockSize_(minBlockSize), maxAlign_(maxAlign) { 23 | } 24 | 25 | SysArena* ThreadCachedArena::allocateThreadLocalArena() { 26 | SysArena* arena = 27 | new SysArena(minBlockSize_, SysArena::kNoSizeLimit, maxAlign_); 28 | auto disposer = [this] (SysArena* t, TLPDestructionMode mode) { 29 | std::unique_ptr tp(t); // ensure it gets deleted 30 | if (mode == TLPDestructionMode::THIS_THREAD) { 31 | zombify(std::move(*t)); 32 | } 33 | }; 34 | arena_.reset(arena, disposer); 35 | return arena; 36 | } 37 | 38 | void ThreadCachedArena::zombify(SysArena&& arena) { 39 | std::lock_guard lock(zombiesMutex_); 40 | zombies_.merge(std::move(arena)); 41 | } 42 | 43 | } // namespace folly 44 | -------------------------------------------------------------------------------- /folly/io/async/test/SocketPair.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Licensed to the Apache Software Foundation (ASF) under one 3 | * or more contributor license agreements. See the NOTICE file 4 | * distributed with this work for additional information 5 | * regarding copyright ownership. The ASF licenses this file 6 | * to you under the Apache License, Version 2.0 (the 7 | * "License"); you may not use this file except in compliance 8 | * with the License. You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, 13 | * software distributed under the License is distributed on an 14 | * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY 15 | * KIND, either express or implied. See the License for the 16 | * specific language governing permissions and limitations 17 | * under the License. 18 | */ 19 | #pragma once 20 | 21 | namespace folly { 22 | 23 | class SocketPair { 24 | public: 25 | enum Mode { 26 | BLOCKING, 27 | NONBLOCKING 28 | }; 29 | 30 | explicit SocketPair(Mode mode = NONBLOCKING); 31 | ~SocketPair(); 32 | 33 | int operator[](int index) const { 34 | return fds_[index]; 35 | } 36 | 37 | void closeFD0(); 38 | void closeFD1(); 39 | 40 | int extractFD0() { 41 | return extractFD(0); 42 | } 43 | int extractFD1() { 44 | return extractFD(1); 45 | } 46 | int extractFD(int index) { 47 | int fd = fds_[index]; 48 | fds_[index] = -1; 49 | return fd; 50 | } 51 | 52 | private: 53 | int fds_[2]; 54 | }; 55 | 56 | } 57 | -------------------------------------------------------------------------------- /folly/experimental/fibers/ExecutionObserver.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | 20 | namespace folly { namespace fibers { 21 | 22 | /** 23 | * Observes the execution of a task. 24 | */ 25 | class ExecutionObserver { 26 | public: 27 | virtual ~ExecutionObserver() { } 28 | 29 | /** 30 | * Called when a task is about to start executing. 31 | * 32 | * @param id Unique id for the fiber which is starting. 33 | */ 34 | virtual void starting(uintptr_t id) noexcept = 0; 35 | 36 | /** 37 | * Called when a task is ready to run. 38 | * 39 | * @param id Unique id for the fiber which is ready to run. 40 | */ 41 | virtual void runnable(uintptr_t id) noexcept = 0; 42 | 43 | /** 44 | * Called just after a task stops executing. 45 | * 46 | * @param id Unique id for the fiber which is stopping. 47 | */ 48 | virtual void stopped(uintptr_t id) noexcept = 0; 49 | }; 50 | 51 | }} // namespace folly::fibers 52 | -------------------------------------------------------------------------------- /folly/SafeAssert.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | 22 | namespace folly { namespace detail { 23 | 24 | namespace { 25 | void writeStderr(const char* s) { 26 | writeFull(STDERR_FILENO, s, strlen(s)); 27 | } 28 | } // namespace 29 | 30 | void assertionFailure(const char* expr, const char* msg, const char* file, 31 | unsigned int line, const char* function) { 32 | writeStderr("\n\nAssertion failure: "); 33 | writeStderr(expr); 34 | writeStderr("\nMessage: "); 35 | writeStderr(msg); 36 | writeStderr("\nFile: "); 37 | writeStderr(file); 38 | writeStderr("\nLine: "); 39 | char buf[20]; 40 | uint32_t n = uint64ToBufferUnsafe(line, buf); 41 | writeFull(STDERR_FILENO, buf, n); 42 | writeStderr("\nFunction: "); 43 | writeStderr(function); 44 | writeStderr("\n"); 45 | fsyncNoInt(STDERR_FILENO); 46 | abort(); 47 | } 48 | 49 | }} // namespaces 50 | -------------------------------------------------------------------------------- /folly/detail/AtomicHashUtils.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // Some utilities used by AtomicHashArray and AtomicHashMap 18 | // 19 | // Note: no include guard; different -inl.h files include this and 20 | // undef it more than once in a translation unit. 21 | // override-include-guard 22 | 23 | #if !(defined(__x86__) || defined(__i386__) || FOLLY_X64) 24 | #define FOLLY_SPIN_WAIT(condition) \ 25 | for (int counter = 0; condition; ++counter) { \ 26 | if (counter < 10000) continue; \ 27 | pthread_yield(); \ 28 | } 29 | #else 30 | #define FOLLY_SPIN_WAIT(condition) \ 31 | for (int counter = 0; condition; ++counter) { \ 32 | if (counter < 10000) { \ 33 | asm volatile("pause"); \ 34 | continue; \ 35 | } \ 36 | pthread_yield(); \ 37 | } 38 | #endif 39 | -------------------------------------------------------------------------------- /folly/wangle/concurrent/test/CodelTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | TEST(CodelTest, Basic) { 23 | using std::chrono::milliseconds; 24 | folly::wangle::Codel c; 25 | std::this_thread::sleep_for(milliseconds(110)); 26 | // This interval is overloaded 27 | EXPECT_FALSE(c.overloaded(milliseconds(100))); 28 | std::this_thread::sleep_for(milliseconds(90)); 29 | // At least two requests must happen in an interval before they will fail 30 | EXPECT_FALSE(c.overloaded(milliseconds(50))); 31 | EXPECT_TRUE(c.overloaded(milliseconds(50))); 32 | std::this_thread::sleep_for(milliseconds(110)); 33 | // Previous interval is overloaded, but 2ms isn't enough to fail 34 | EXPECT_FALSE(c.overloaded(milliseconds(2))); 35 | std::this_thread::sleep_for(milliseconds(90)); 36 | // 20 ms > target interval * 2 37 | EXPECT_TRUE(c.overloaded(milliseconds(20))); 38 | } 39 | -------------------------------------------------------------------------------- /folly/wangle/codec/StringCodec.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | namespace folly { namespace wangle { 22 | 23 | /* 24 | * StringCodec converts a pipeline from IOBufs to std::strings. 25 | */ 26 | class StringCodec : public Handler, std::string, 27 | std::string, std::unique_ptr> { 28 | public: 29 | typedef typename Handler< 30 | std::unique_ptr, std::string, 31 | std::string, std::unique_ptr>::Context Context; 32 | 33 | void read(Context* ctx, std::unique_ptr buf) override { 34 | buf->coalesce(); 35 | std::string data((const char*)buf->data(), buf->length()); 36 | 37 | ctx->fireRead(data); 38 | } 39 | 40 | Future write(Context* ctx, std::string msg) override { 41 | auto buf = IOBuf::copyBuffer(msg.data(), msg.length()); 42 | return ctx->fireWrite(std::move(buf)); 43 | } 44 | }; 45 | 46 | }} // namespace 47 | -------------------------------------------------------------------------------- /folly/gen/ParallelMap.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_GEN_PARALLELMAP_H 18 | #define FOLLY_GEN_PARALLELMAP_H 19 | 20 | #include 21 | 22 | namespace folly { namespace gen { 23 | 24 | namespace detail { 25 | 26 | template 27 | class PMap; 28 | 29 | } // namespace detail 30 | 31 | /** 32 | * Run `pred` in parallel in nThreads. Results are returned in the 33 | * same order in which they were retrieved from the source generator 34 | * (similar to map). 35 | * 36 | * NOTE: Only `pred` is run from separate threads; the source 37 | * generator and the rest of the pipeline is executed in the 38 | * caller thread. 39 | */ 40 | template> 42 | PMap pmap(Predicate pred = Predicate(), size_t nThreads = 0) { 43 | return PMap(std::move(pred), nThreads); 44 | } 45 | 46 | }} // namespaces 47 | 48 | #include 49 | 50 | #endif // FOLLY_GEN_PARALLELMAP_H 51 | -------------------------------------------------------------------------------- /folly/wangle/rx/Subject.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include // must come first 20 | #include 21 | #include 22 | 23 | namespace folly { namespace wangle { 24 | 25 | /// Subject interface. A Subject is both an Observable and an Observer. There 26 | /// is a default implementation of the Observer methods that just forwards the 27 | /// observed events to the Subject's observers. 28 | template 29 | struct Subject : public Observable, public Observer { 30 | void onNext(const T& val) override { 31 | this->forEachObserver([&](Observer* o){ 32 | o->onNext(val); 33 | }); 34 | } 35 | void onError(Error e) override { 36 | this->forEachObserver([&](Observer* o){ 37 | o->onError(e); 38 | }); 39 | } 40 | void onCompleted() override { 41 | this->forEachObserver([](Observer* o){ 42 | o->onCompleted(); 43 | }); 44 | } 45 | }; 46 | 47 | }} 48 | -------------------------------------------------------------------------------- /folly/wangle/channel/EventBaseHandler.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | namespace folly { namespace wangle { 19 | 20 | class EventBaseHandler : public OutboundBytesToBytesHandler { 21 | public: 22 | folly::Future write( 23 | Context* ctx, 24 | std::unique_ptr buf) override { 25 | folly::Future retval; 26 | DCHECK(ctx->getTransport()); 27 | DCHECK(ctx->getTransport()->getEventBase()); 28 | ctx->getTransport()->getEventBase()->runImmediatelyOrRunInEventBaseThreadAndWait([&](){ 29 | retval = ctx->fireWrite(std::move(buf)); 30 | }); 31 | return retval; 32 | } 33 | 34 | Future close(Context* ctx) override { 35 | DCHECK(ctx->getTransport()); 36 | DCHECK(ctx->getTransport()->getEventBase()); 37 | Future retval; 38 | ctx->getTransport()->getEventBase()->runImmediatelyOrRunInEventBaseThreadAndWait([&](){ 39 | retval = ctx->fireClose(); 40 | }); 41 | return retval; 42 | } 43 | }; 44 | 45 | }} // namespace 46 | -------------------------------------------------------------------------------- /folly/experimental/StringKeyedCommon.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | // Copyright 2013-present Facebook. All Rights Reserved. 17 | // @author: Pavlo Kushnir (pavlo) 18 | 19 | #ifndef FOLLY_EXPERIMENTAL_STRINGKEYEDCOMMON_H_ 20 | #define FOLLY_EXPERIMENTAL_STRINGKEYEDCOMMON_H_ 21 | 22 | #include 23 | #include 24 | 25 | namespace folly { 26 | 27 | template 28 | StringPiece stringPieceDup(StringPiece piece, const Alloc& alloc) { 29 | auto size = piece.size(); 30 | auto keyDup = typename Alloc::template rebind::other(alloc) 31 | .allocate(size); 32 | memcpy(keyDup, piece.data(), size * sizeof(typename StringPiece::value_type)); 33 | return StringPiece(keyDup, size); 34 | } 35 | 36 | template 37 | void stringPieceDel(StringPiece piece, const Alloc& alloc) { 38 | typename Alloc::template rebind::other(alloc) 39 | .deallocate(const_cast(piece.data()), piece.size()); 40 | } 41 | 42 | } // folly 43 | 44 | #endif /* FOLLY_EXPERIMENTAL_STRINGKEYEDCOMMON_H_ */ 45 | -------------------------------------------------------------------------------- /folly/experimental/symbolizer/StackTrace.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_SYMBOLIZER_STACKTRACE_H_ 18 | #define FOLLY_SYMBOLIZER_STACKTRACE_H_ 19 | 20 | #include 21 | #include 22 | 23 | namespace folly { namespace symbolizer { 24 | 25 | /** 26 | * Get the current stack trace into addresses, which has room for at least 27 | * maxAddresses frames. 28 | * 29 | * Returns the number of frames written in the array. 30 | * Returns -1 on failure. 31 | * 32 | * NOT async-signal-safe, but fast. 33 | */ 34 | ssize_t getStackTrace(uintptr_t* addresses, size_t maxAddresses); 35 | 36 | /** 37 | * Get the current stack trace into addresses, which has room for at least 38 | * maxAddresses frames. 39 | * 40 | * Returns the number of frames written in the array. 41 | * Returns -1 on failure. 42 | * 43 | * Async-signal-safe, but likely slower. 44 | */ 45 | ssize_t getStackTraceSafe(uintptr_t* addresses, size_t maxAddresses); 46 | 47 | }} // namespaces 48 | 49 | #endif /* FOLLY_SYMBOLIZER_STACKTRACE_H_ */ 50 | -------------------------------------------------------------------------------- /folly/SingletonStackTrace.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #include 17 | #include 18 | 19 | namespace folly { 20 | 21 | namespace { 22 | 23 | std::string stackTraceGetter() { 24 | // Get and symbolize stack trace 25 | constexpr size_t kMaxStackTraceDepth = 100; 26 | symbolizer::FrameArray addresses; 27 | 28 | if (!getStackTraceSafe(addresses)) { 29 | return ""; 30 | } else { 31 | constexpr size_t kDefaultCapacity = 500; 32 | symbolizer::ElfCache elfCache(kDefaultCapacity); 33 | 34 | symbolizer::Symbolizer symbolizer(&elfCache); 35 | symbolizer.symbolize(addresses); 36 | 37 | symbolizer::StringSymbolizePrinter printer; 38 | printer.println(addresses); 39 | return printer.str(); 40 | } 41 | } 42 | 43 | struct SetStackTraceGetter { 44 | SetStackTraceGetter() { 45 | SingletonVault::stackTraceGetter().store(stackTraceGetter); 46 | } 47 | }; 48 | 49 | SetStackTraceGetter setStackTraceGetter; 50 | 51 | } 52 | 53 | } 54 | -------------------------------------------------------------------------------- /folly/futures/DrivableExecutor.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | namespace folly { 22 | 23 | /* 24 | * A DrivableExecutor can be driven via its drive() method 25 | * Examples include EventBase (via loopOnce()) and ManualExecutor 26 | * (via makeProgress()). 27 | * 28 | * This interface is most handy in conjunction with 29 | * Future::getVia(DrivableExecutor*) and 30 | * Future::waitVia(DrivableExecutor*) 31 | * 32 | * These call drive() * repeatedly until the Future is fulfilled. 33 | * getVia() returns the value (or throws the exception) and waitVia() returns 34 | * the same Future for chainability. 35 | * 36 | * These will be most helpful in tests, for instance if you need to pump a mock 37 | * EventBase until Futures complete. 38 | */ 39 | class DrivableExecutor : public virtual Executor { 40 | public: 41 | virtual ~DrivableExecutor() = default; 42 | 43 | // Make progress on this Executor's work. 44 | virtual void drive() = 0; 45 | }; 46 | 47 | } // folly 48 | -------------------------------------------------------------------------------- /folly/wangle/concurrent/LifoSemMPMCQueue.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | #include 19 | #include 20 | #include 21 | 22 | namespace folly { namespace wangle { 23 | 24 | template 25 | class LifoSemMPMCQueue : public BlockingQueue { 26 | public: 27 | explicit LifoSemMPMCQueue(size_t max_capacity) : queue_(max_capacity) {} 28 | 29 | void add(T item) override { 30 | if (!queue_.write(std::move(item))) { 31 | throw std::runtime_error("LifoSemMPMCQueue full, can't add item"); 32 | } 33 | sem_.post(); 34 | } 35 | 36 | T take() override { 37 | T item; 38 | while (!queue_.read(item)) { 39 | sem_.wait(); 40 | } 41 | return item; 42 | } 43 | 44 | size_t capacity() { 45 | return queue_.capacity(); 46 | } 47 | 48 | size_t size() override { 49 | return queue_.size(); 50 | } 51 | 52 | private: 53 | LifoSem sem_; 54 | MPMCQueue queue_; 55 | }; 56 | 57 | }} // folly::wangle 58 | -------------------------------------------------------------------------------- /folly/detail/BitsDetail.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_DETAIL_BITSDETAIL_H_ 18 | #define FOLLY_DETAIL_BITSDETAIL_H_ 19 | 20 | namespace folly { 21 | namespace detail { 22 | 23 | // If we're targeting an architecture with popcnt support, use 24 | // __builtin_popcount directly, as it's presumably inlined. 25 | // If not, use runtime detection using __attribute__((__ifunc__)) 26 | // (see Bits.cpp) 27 | #ifdef _MSC_VER 28 | inline int popcount(unsigned int x) { 29 | return __popcnt(x); 30 | } 31 | inline int popcountll(unsigned long long x) { 32 | return __popcnt64(x); 33 | } 34 | #elif defined(__POPCNT__) 35 | 36 | inline int popcount(unsigned int x) { 37 | return __builtin_popcount(x); 38 | } 39 | inline int popcountll(unsigned long long x) { 40 | return __builtin_popcountll(x); 41 | } 42 | 43 | #else /* !__POPCNT__ */ 44 | 45 | int popcount(unsigned int x); 46 | int popcountll(unsigned long long x); 47 | 48 | #endif /* !__POPCNT__ */ 49 | 50 | } // namespace detail 51 | } // namespace folly 52 | 53 | #endif /* FOLLY_DETAIL_BITSDETAIL_H_ */ 54 | -------------------------------------------------------------------------------- /folly/futures/Future.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #include 17 | #include 18 | #include 19 | 20 | namespace folly { 21 | 22 | // Instantiate the most common Future types to save compile time 23 | template class Future; 24 | template class Future; 25 | template class Future; 26 | template class Future; 27 | template class Future; 28 | template class Future; 29 | 30 | } 31 | 32 | namespace folly { namespace futures { 33 | 34 | Future sleep(Duration dur, Timekeeper* tk) { 35 | if (LIKELY(!tk)) { 36 | tk = detail::getTimekeeperSingleton(); 37 | } 38 | return tk->after(dur); 39 | } 40 | 41 | }} 42 | 43 | namespace folly { namespace detail { 44 | 45 | template <> 46 | CollectContext::~CollectContext() { 47 | if (!threw.exchange(true)) { 48 | p.setValue(); 49 | } 50 | } 51 | 52 | template <> 53 | void CollectContext::setPartialResult(size_t i, Try& t) { 54 | // Nothing to do for void 55 | } 56 | 57 | }} 58 | -------------------------------------------------------------------------------- /folly/test/function_benchmark/benchmark_impl.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | 21 | /* 22 | * These functions are defined in a separate file so that gcc won't be able to 23 | * inline them and optimize away the indirect calls. 24 | */ 25 | 26 | void BM_fn_ptr_invoke_impl(int iters, void (*fn)()) { 27 | for (int n = 0; n < iters; ++n) { 28 | fn(); 29 | } 30 | } 31 | 32 | void BM_std_function_invoke_impl(int iters, 33 | const std::function& fn) { 34 | for (int n = 0; n < iters; ++n) { 35 | fn(); 36 | } 37 | } 38 | 39 | void BM_mem_fn_invoke_impl(int iters, 40 | TestClass* tc, 41 | void (TestClass::*memfn)()) { 42 | for (int n = 0; n < iters; ++n) { 43 | (tc->*memfn)(); 44 | } 45 | } 46 | 47 | void BM_virtual_fn_invoke_impl(int iters, VirtualClass* vc) { 48 | for (int n = 0; n < iters; ++n) { 49 | vc->doNothing(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /folly/io/async/test/MockAsyncSocket.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | 20 | #include 21 | #include 22 | 23 | namespace folly { 24 | 25 | namespace test { 26 | 27 | class MockAsyncSocket : public AsyncSocket { 28 | public: 29 | typedef std::unique_ptr UniquePtr; 30 | 31 | explicit MockAsyncSocket(EventBase* base) : AsyncSocket(base) { 32 | } 33 | 34 | GMOCK_METHOD5_(, noexcept, , connect, 35 | void(AsyncSocket::ConnectCallback*, 36 | const folly::SocketAddress&, 37 | int, 38 | const OptionMap&, 39 | const folly::SocketAddress&)); 40 | 41 | MOCK_CONST_METHOD1(getPeerAddress, 42 | void(folly::SocketAddress*)); 43 | MOCK_METHOD0(detachFd, int()); 44 | MOCK_CONST_METHOD0(getFd, int()); 45 | MOCK_METHOD0(closeNow, void()); 46 | MOCK_CONST_METHOD0(good, bool()); 47 | MOCK_CONST_METHOD0(readable, bool()); 48 | MOCK_CONST_METHOD0(hangup, bool()); 49 | }; 50 | 51 | }} 52 | -------------------------------------------------------------------------------- /folly/test/SynchronizedTestLib.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_TEST_SYNCHRONIZEDTESTLIB_H 18 | #define FOLLY_TEST_SYNCHRONIZEDTESTLIB_H 19 | 20 | // We have mutex types outside of folly that we want to test with Synchronized. 21 | // Make it easy for mutex implementators to test their classes with 22 | // Synchronized by just having a test like: 23 | // 24 | // class MyMutex { ... }; 25 | // 26 | // TEST(Synchronized, Basic) { 27 | // testBasic(); 28 | // } 29 | // 30 | // ... similar for testConcurrency, testDualLocking, etc. 31 | 32 | 33 | template void testBasic(); 34 | 35 | template void testConcurrency(); 36 | 37 | template void testDualLocking(); 38 | 39 | template void testDualLockingWithConst(); 40 | 41 | template void testTimedSynchronized(); 42 | 43 | template void testTimedSynchronizedWithConst(); 44 | 45 | template void testConstCopy(); 46 | 47 | #include 48 | 49 | #endif /* FOLLY_TEST_SYNCHRONIZEDTESTLIB_H */ 50 | -------------------------------------------------------------------------------- /folly/wangle/acceptor/ConnectionCounter.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #pragma once 11 | 12 | namespace folly { 13 | 14 | class IConnectionCounter { 15 | public: 16 | virtual uint64_t getNumConnections() const = 0; 17 | 18 | /** 19 | * Get the maximum number of non-whitelisted client-side connections 20 | * across all Acceptors managed by this. A value 21 | * of zero means "unlimited." 22 | */ 23 | virtual uint64_t getMaxConnections() const = 0; 24 | 25 | /** 26 | * Increment the count of client-side connections. 27 | */ 28 | virtual void onConnectionAdded() = 0; 29 | 30 | /** 31 | * Decrement the count of client-side connections. 32 | */ 33 | virtual void onConnectionRemoved() = 0; 34 | virtual ~IConnectionCounter() {} 35 | }; 36 | 37 | class SimpleConnectionCounter: public IConnectionCounter { 38 | public: 39 | uint64_t getNumConnections() const override { return numConnections_; } 40 | uint64_t getMaxConnections() const override { return maxConnections_; } 41 | void setMaxConnections(uint64_t maxConnections) { 42 | maxConnections_ = maxConnections; 43 | } 44 | 45 | void onConnectionAdded() override { numConnections_++; } 46 | void onConnectionRemoved() override { numConnections_--; } 47 | virtual ~SimpleConnectionCounter() {} 48 | 49 | protected: 50 | uint64_t maxConnections_{0}; 51 | uint64_t numConnections_{0}; 52 | }; 53 | 54 | } 55 | -------------------------------------------------------------------------------- /folly/docs/FBString.md: -------------------------------------------------------------------------------- 1 | `folly/FBString.h` 2 | ------------------ 3 | 4 | `fbstring` is a drop-in replacement for `std::string`. The main 5 | benefit of `fbstring` is significantly increased performance on 6 | virtually all important primitives. This is achieved by using a 7 | three-tiered storage strategy and by cooperating with the memory 8 | allocator. In particular, `fbstring` is designed to detect use of 9 | jemalloc and cooperate with it to achieve significant improvements in 10 | speed and memory usage. 11 | 12 | `fbstring` supports x32 and x64 architectures. Porting it to big endian 13 | architectures would require some changes. 14 | 15 | ### Storage strategies 16 | *** 17 | 18 | * Small strings (<= 23 chars) are stored in-situ without memory 19 | allocation. 20 | 21 | * Medium strings (24 - 255 chars) are stored in malloc-allocated 22 | memory and copied eagerly. 23 | 24 | * Large strings (> 255 chars) are stored in malloc-allocated memory and 25 | copied lazily. 26 | 27 | ### Implementation highlights 28 | *** 29 | 30 | * 100% compatible with `std::string`. 31 | 32 | * Thread-safe reference counted copy-on-write for strings "large" 33 | strings (> 255 chars). 34 | 35 | * Uses `malloc` instead of allocators. 36 | 37 | * Jemalloc-friendly. `fbstring` automatically detects if application 38 | uses jemalloc and if so, significantly improves allocation 39 | strategy by using non-standard jemalloc extensions. 40 | 41 | * `find()` is implemented using simplified Boyer-Moore 42 | algorithm. Casual tests indicate a 30x speed improvement over 43 | `string::find()` for successful searches and a 1.5x speed 44 | improvement for failed searches. 45 | 46 | * Offers conversions to and from `std::string`. -------------------------------------------------------------------------------- /folly/wangle/concurrent/NamedThreadFactory.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | namespace folly { namespace wangle { 29 | 30 | class NamedThreadFactory : public ThreadFactory { 31 | public: 32 | explicit NamedThreadFactory(folly::StringPiece prefix) 33 | : prefix_(prefix.str()), suffix_(0) {} 34 | 35 | std::thread newThread(Func&& func) override { 36 | auto thread = std::thread(std::move(func)); 37 | folly::setThreadName( 38 | thread.native_handle(), 39 | folly::to(prefix_, suffix_++)); 40 | return thread; 41 | } 42 | 43 | void setNamePrefix(folly::StringPiece prefix) { 44 | prefix_ = prefix.str(); 45 | } 46 | 47 | std::string getNamePrefix() { 48 | return prefix_; 49 | } 50 | 51 | private: 52 | std::string prefix_; 53 | std::atomic suffix_; 54 | }; 55 | 56 | }} // folly::wangle 57 | -------------------------------------------------------------------------------- /folly/test/AtomicBitSetTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | 22 | namespace folly { namespace test { 23 | 24 | TEST(AtomicBitSet, Simple) { 25 | constexpr size_t kSize = 1000; 26 | AtomicBitSet bs; 27 | 28 | EXPECT_EQ(kSize, bs.size()); 29 | 30 | for (size_t i = 0; i < kSize; ++i) { 31 | EXPECT_FALSE(bs[i]); 32 | } 33 | 34 | bs.set(42); 35 | for (size_t i = 0; i < kSize; ++i) { 36 | EXPECT_EQ(i == 42, bs[i]); 37 | } 38 | 39 | bs.set(43); 40 | for (size_t i = 0; i < kSize; ++i) { 41 | EXPECT_EQ((i == 42 || i == 43), bs[i]); 42 | } 43 | 44 | bs.reset(42); 45 | for (size_t i = 0; i < kSize; ++i) { 46 | EXPECT_EQ((i == 43), bs[i]); 47 | } 48 | 49 | bs.reset(43); 50 | for (size_t i = 0; i < kSize; ++i) { 51 | EXPECT_FALSE(bs[i]); 52 | } 53 | } 54 | 55 | }} // namespaces 56 | 57 | int main(int argc, char *argv[]) { 58 | testing::InitGoogleTest(&argc, argv); 59 | gflags::ParseCommandLineFlags(&argc, &argv, true); 60 | return RUN_ALL_TESTS(); 61 | } 62 | -------------------------------------------------------------------------------- /folly/detail/Malloc.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_DETAIL_MALLOC_H 18 | #define FOLLY_DETAIL_MALLOC_H 19 | 20 | #include 21 | 22 | #include 23 | 24 | extern "C" { 25 | 26 | #if FOLLY_HAVE_WEAK_SYMBOLS 27 | void* mallocx(size_t, int) __attribute__((__weak__)); 28 | void* rallocx(void*, size_t, int) __attribute__((__weak__)); 29 | size_t xallocx(void*, size_t, size_t, int) __attribute__((__weak__)); 30 | size_t sallocx(const void*, int) __attribute__((__weak__)); 31 | void dallocx(void*, int) __attribute__((__weak__)); 32 | size_t nallocx(size_t, int) __attribute__((__weak__)); 33 | int mallctl(const char*, void*, size_t*, void*, size_t) 34 | __attribute__((__weak__)); 35 | #else 36 | extern void* (*mallocx)(size_t, int); 37 | extern void* (*rallocx)(void*, size_t, int); 38 | extern size_t (*xallocx)(void*, size_t, size_t, int); 39 | extern size_t (*sallocx)(const void*, int); 40 | extern void (*dallocx)(void*, int); 41 | extern size_t (*nallocx)(size_t, int); 42 | extern int (*mallctl)(const char*, void*, size_t*, void*, size_t); 43 | #endif 44 | 45 | } 46 | 47 | #endif 48 | -------------------------------------------------------------------------------- /folly/wangle/concurrent/FiberIOExecutor.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | #include 20 | 21 | namespace folly { namespace fibers { 22 | 23 | /** 24 | * @class FiberIOExecutor 25 | * @brief An IOExecutor that executes funcs under mapped fiber context 26 | * 27 | * A FiberIOExecutor wraps an IOExecutor, but executes funcs on the FiberManager 28 | * mapped to the underlying IOExector's event base. 29 | */ 30 | class FiberIOExecutor : public folly::wangle::IOExecutor { 31 | public: 32 | explicit FiberIOExecutor( 33 | const std::shared_ptr& ioExecutor) 34 | : ioExecutor_(ioExecutor) {} 35 | 36 | virtual void add(std::function f) override { 37 | auto eventBase = ioExecutor_->getEventBase(); 38 | getFiberManager(*eventBase).add(std::move(f)); 39 | } 40 | 41 | virtual EventBase* getEventBase() override { 42 | return ioExecutor_->getEventBase(); 43 | } 44 | 45 | private: 46 | std::shared_ptr ioExecutor_; 47 | }; 48 | 49 | }} 50 | -------------------------------------------------------------------------------- /folly/wangle/concurrent/IOExecutor.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | #include 21 | 22 | namespace folly { 23 | class EventBase; 24 | } 25 | 26 | namespace folly { namespace wangle { 27 | 28 | // An IOExecutor is an executor that operates on at least one EventBase. One of 29 | // these EventBases should be accessible via getEventBase(). The event base 30 | // returned by a call to getEventBase() is implementation dependent. 31 | // 32 | // Note that IOExecutors don't necessarily loop on the base themselves - for 33 | // instance, EventBase itself is an IOExecutor but doesn't drive itself. 34 | // 35 | // Implementations of IOExecutor are eligible to become the global IO executor, 36 | // returned on every call to getIOExecutor(), via setIOExecutor(). 37 | // These functions are declared in GlobalExecutor.h 38 | // 39 | // If getIOExecutor is called and none has been set, a default global 40 | // IOThreadPoolExecutor will be created and returned. 41 | class IOExecutor : public virtual Executor { 42 | public: 43 | virtual ~IOExecutor() {} 44 | virtual EventBase* getEventBase() = 0; 45 | }; 46 | 47 | }} 48 | -------------------------------------------------------------------------------- /folly/futures/test/SugarTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | 21 | using namespace folly; 22 | 23 | TEST(Sugar, pollReady) { 24 | Promise p; 25 | auto f = p.getFuture(); 26 | p.setValue(42); 27 | EXPECT_EQ(42, f.poll().value().value()); 28 | } 29 | 30 | TEST(Sugar, pollNotReady) { 31 | Promise p; 32 | auto f = p.getFuture(); 33 | EXPECT_FALSE(f.poll().hasValue()); 34 | } 35 | 36 | TEST(Sugar, pollException) { 37 | Promise p; 38 | auto f = p.getFuture(); 39 | p.setWith([] { throw std::runtime_error("Runtime"); }); 40 | EXPECT_TRUE(f.poll().value().hasException()); 41 | } 42 | 43 | TEST(Sugar, filterTrue) { 44 | EXPECT_EQ(42, makeFuture(42).filter([](int){ return true; }).get()); 45 | } 46 | 47 | TEST(Sugar, filterFalse) { 48 | EXPECT_THROW(makeFuture(42).filter([](int){ return false; }).get(), 49 | folly::PredicateDoesNotObtain); 50 | } 51 | 52 | TEST(Sugar, filterMoveonly) { 53 | EXPECT_EQ(42, 54 | *makeFuture(folly::make_unique(42)) 55 | .filter([](std::unique_ptr const&) { return true; }) 56 | .get()); 57 | } 58 | -------------------------------------------------------------------------------- /folly/io/async/test/certs/tests-key.pem: -------------------------------------------------------------------------------- 1 | -----BEGIN RSA PRIVATE KEY----- 2 | MIIEpAIBAAKCAQEAs2RqyeV0BwLjGB5QYJ99jjnPZdJ90Y13HIqNnHnlnLV5EsQz 3 | 97xcmeJASCxdZbGNYKPFE4zJKkg2HMrQiytKmr67/QWUSwfRXKaifaOFfX3miPx7 4 | B2vA2B8hLPKsjU0zRmEN4uI/gAPYg0qXsyGMv7cgDgI60qrlFtYyOLcykwYfIZPD 5 | ADL0dvzTxz5K6eICPhDB+ruL1na+BfW264ixVqFNOE/ZljjJOxvofAUvbICDYNvr 6 | +XFr5dwQuJC5OS9ciRRMrqH0kghBHunQ3+7lYfkTymuIRJCGKN9QBDjxazeenfqQ 7 | o/+Zeux01l6EMd648nTVzL4FO+bq5uk0HvHQeQIDAQABAoIBAQCSPcBYindF5/Kd 8 | jMjVm+9M7I/IYAo1tG9vkvvSngSy9bWXuN7sjF+pCyqAK7qP1mh8acWVJGYx0+BZ 9 | JHVRnp8Y+3hg0hWL/PmN4EICzjVakjJHZhwddpglF2uCKurD3jV4oFIjrXE6uOfe 10 | UAbO/wCwoWa+RM8TQkGzljYmyiGufCcXlgEKMNA7TIvbJ9TVx3VTCOQy6EjZ13jd 11 | M6X7byV/ZOFpZ2H0QV46LvZraw04riXQ/59gVmzizYdI+BwnxxapsCmalTJoV/Y0 12 | LMI2ylat4PTMVTxPF+ti7Nt+rUkkEx6kuiAgfc+bzE4BSD5X4wy3fdLVLccoxXYw 13 | 4N3fOuQhAoGBAOLrMhiSCrzXGjDWTbPrwzxXDO0qm+wURELi3N5SXIkKUdG2/In6 14 | wNdpXdvqblOm7SASgPf9KCwUSADrNw6R6nbfrrir5EHg66YydI/OW42QzJKcBUFh 15 | 5Q5na3fvoL/zRhsmh0gEymBg+OIfNel2LY69bl8aAko2y0R1kj7zb8X1AoGBAMph 16 | 9hlnkIBSw60+pKHaOqo2t/kihNNMFyfOgJvh8960eFeMDhMIXgxPUR8yaPX0bBMb 17 | bCdEJJ2pmq7zUBPvxVJLedwkGMhywElA8yYVh+S6x4Cg+lYo4spIjrHQ/WTvJkHB 18 | GrDskxdq80lbXjwRd0dPJZkxhKJec1o0n8S03Mn1AoGAGarK5taWGlgmYUHMVj6j 19 | vc6G6si4DFMaiYpJu2gLiYC+Un9lP2I6r+L+N+LjidjG16rgJazf/2Rn5Jq2hpJg 20 | uAODKuZekkkTvp/UaXPJDVFEooy9V3DwTNnL4SwcvbmRw35vLOlFzvMJE+K94WN5 21 | sbyhoGY7vhNGmL7HxREaIoUCgYEAwpteVWFz3yE2ziF9l7FMVh7V23go9zGk1n9I 22 | xhyJL26khbLEWeLi5L1kiTYlHdUSE3F8F2n8N6s+ddq79t/KA29WV6xSNHW7lvUg 23 | mk975CMC8hpZfn5ETjVlGXGYJ/Wa+QGiE9z5ODx8gt6cB/DXnLdrtRqbqrJeA7C0 24 | rScpY/0CgYBCC1QeuAiwWHOqQn3BwsZo9JQBTyT0QvDqLH/F+h9QbXep+4HvyAxG 25 | nTMNDtGyfyKGDaDUn5hyeU7Oxvzq0K9P+eZD3MjQeaMEg/++GPGUPmDUTqyb2UT8 26 | 5s0NIUobxfKnTD6IpgOIq7ffvVY6cKBMyuLmu/gSvscsbONHjKti3Q== 27 | -----END RSA PRIVATE KEY----- 28 | -------------------------------------------------------------------------------- /folly/wangle/ssl/SSLStats.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #pragma once 11 | 12 | namespace folly { 13 | 14 | class SSLStats { 15 | public: 16 | virtual ~SSLStats() noexcept {} 17 | 18 | // downstream 19 | virtual void recordSSLAcceptLatency(int64_t latency) noexcept = 0; 20 | virtual void recordTLSTicket(bool ticketNew, bool ticketHit) noexcept = 0; 21 | virtual void recordSSLSession(bool sessionNew, bool sessionHit, bool foreign) 22 | noexcept = 0; 23 | virtual void recordSSLSessionRemove() noexcept = 0; 24 | virtual void recordSSLSessionFree(uint32_t freed) noexcept = 0; 25 | virtual void recordSSLSessionSetError(uint32_t err) noexcept = 0; 26 | virtual void recordSSLSessionGetError(uint32_t err) noexcept = 0; 27 | virtual void recordClientRenegotiation() noexcept = 0; 28 | 29 | // upstream 30 | virtual void recordSSLUpstreamConnection(bool handshake) noexcept = 0; 31 | virtual void recordSSLUpstreamConnectionError(bool verifyError) noexcept = 0; 32 | virtual void recordCryptoSSLExternalAttempt() noexcept = 0; 33 | virtual void recordCryptoSSLExternalConnAlreadyClosed() noexcept = 0; 34 | virtual void recordCryptoSSLExternalApplicationException() noexcept = 0; 35 | virtual void recordCryptoSSLExternalSuccess() noexcept = 0; 36 | virtual void recordCryptoSSLExternalDuration(uint64_t duration) noexcept = 0; 37 | virtual void recordCryptoSSLLocalAttempt() noexcept = 0; 38 | virtual void recordCryptoSSLLocalSuccess() noexcept = 0; 39 | 40 | }; 41 | 42 | } 43 | -------------------------------------------------------------------------------- /folly/wangle/codec/FixedLengthFrameDecoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | 20 | namespace folly {namespace wangle { 21 | 22 | /** 23 | * A decoder that splits the received IOBufs by the fixed number 24 | * of bytes. For example, if you received the following four 25 | * fragmented packets: 26 | * 27 | * +---+----+------+----+ 28 | * | A | BC | DEFG | HI | 29 | * +---+----+------+----+ 30 | * 31 | * A FixedLengthFrameDecoder will decode them into the following three 32 | * packets with the fixed length: 33 | * 34 | * +-----+-----+-----+ 35 | * | ABC | DEF | GHI | 36 | * +-----+-----+-----+ 37 | * 38 | */ 39 | class FixedLengthFrameDecoder 40 | : public ByteToMessageCodec { 41 | public: 42 | 43 | FixedLengthFrameDecoder(size_t length) 44 | : length_(length) {} 45 | 46 | std::unique_ptr decode(Context* ctx, IOBufQueue& q, size_t& needed) { 47 | if (q.chainLength() < length_) { 48 | needed = length_ - q.chainLength(); 49 | return nullptr; 50 | } 51 | 52 | return q.split(length_); 53 | } 54 | 55 | private: 56 | size_t length_; 57 | }; 58 | 59 | }} // Namespace 60 | -------------------------------------------------------------------------------- /folly/test/function_benchmark/benchmark_impl.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #ifndef BENCHMARK_IMPL_H_ 17 | #define BENCHMARK_IMPL_H_ 18 | 19 | #include 20 | 21 | class TestClass; 22 | class VirtualClass; 23 | 24 | void BM_fn_ptr_invoke_impl(int iters, void (*fn)()); 25 | void BM_std_function_invoke_impl(int iters, const std::function& fn); 26 | void BM_mem_fn_invoke_impl(int iters, 27 | TestClass* tc, 28 | void (TestClass::*memfn)()); 29 | void BM_virtual_fn_invoke_impl(int iters, VirtualClass* vc); 30 | 31 | // Inlined version of BM_fn_ptr_invoke_impl(). 32 | // The compiler could potentially even optimize the call to the function 33 | // pointer if it is a constexpr. 34 | inline void BM_fn_ptr_invoke_inlined_impl(int iters, void (*fn)()) { 35 | for (int n = 0; n < iters; ++n) { 36 | fn(); 37 | } 38 | } 39 | 40 | // Invoke a function object as a template parameter. 41 | // This can be used to directly invoke lambda functions 42 | template 43 | void BM_invoke_fn_template_impl(int iters, const T& fn) { 44 | for (int n = 0; n < iters; ++n) { 45 | fn(); 46 | } 47 | } 48 | 49 | #endif // BENCHMARK_IMPL_H_ 50 | -------------------------------------------------------------------------------- /folly/detail/Clock.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #if __MACH__ 20 | #include 21 | #include 22 | 23 | static mach_timebase_info_data_t tb_info; 24 | static bool tb_init = mach_timebase_info(&tb_info) == KERN_SUCCESS; 25 | 26 | int clock_gettime(clockid_t clk_id, struct timespec* ts) { 27 | if (!tb_init) { 28 | errno = EINVAL; 29 | return -1; 30 | } 31 | 32 | uint64_t now_ticks = mach_absolute_time(); 33 | uint64_t now_ns = (now_ticks * tb_info.numer) / tb_info.denom; 34 | ts->tv_sec = now_ns / 1000000000; 35 | ts->tv_nsec = now_ns % 1000000000; 36 | 37 | return 0; 38 | } 39 | 40 | int clock_getres(clockid_t clk_id, struct timespec* ts) { 41 | if (!tb_init) { 42 | errno = EINVAL; 43 | return -1; 44 | } 45 | 46 | ts->tv_sec = 0; 47 | ts->tv_nsec = tb_info.numer / tb_info.denom; 48 | 49 | return 0; 50 | } 51 | #elif _MSC_VER 52 | // using winpthreads from mingw-w64 53 | // has clock_gettime and friends 54 | // make sure to include as well for typedefs of timespec/etc 55 | #else 56 | #error No clock_gettime(2) compatibility wrapper available for this platform. 57 | #endif 58 | -------------------------------------------------------------------------------- /folly/wangle/acceptor/NetworkAddress.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #pragma once 11 | 12 | #include 13 | 14 | namespace folly { 15 | 16 | /** 17 | * A simple wrapper around SocketAddress that represents 18 | * a network in CIDR notation 19 | */ 20 | class NetworkAddress { 21 | public: 22 | /** 23 | * Create a NetworkAddress for an addr/prefixLen 24 | * @param addr IPv4 or IPv6 address of the network 25 | * @param prefixLen Prefix length, in bits 26 | */ 27 | NetworkAddress(const folly::SocketAddress& addr, 28 | unsigned prefixLen): 29 | addr_(addr), prefixLen_(prefixLen) {} 30 | 31 | /** Get the network address */ 32 | const folly::SocketAddress& getAddress() const { 33 | return addr_; 34 | } 35 | 36 | /** Get the prefix length in bits */ 37 | unsigned getPrefixLength() const { return prefixLen_; } 38 | 39 | /** Check whether a given address lies within the network */ 40 | bool contains(const folly::SocketAddress& addr) const { 41 | return addr_.prefixMatch(addr, prefixLen_); 42 | } 43 | 44 | /** Comparison operator to enable use in ordered collections */ 45 | bool operator<(const NetworkAddress& other) const { 46 | if (addr_ < other.addr_) { 47 | return true; 48 | } else if (other.addr_ < addr_) { 49 | return false; 50 | } else { 51 | return (prefixLen_ < other.prefixLen_); 52 | } 53 | } 54 | 55 | private: 56 | folly::SocketAddress addr_; 57 | unsigned prefixLen_; 58 | }; 59 | 60 | } // namespace 61 | -------------------------------------------------------------------------------- /folly/experimental/fibers/ForEach.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | namespace folly { namespace fibers { 19 | 20 | /** 21 | * Schedules several tasks and blocks until all of them are completed. 22 | * In the process of their successfull completion given callback would be called 23 | * for each of them with the index of the task and the result it returned (if 24 | * not void). 25 | * If any of these n tasks throws an exception, this exception will be 26 | * re-thrown, but only when all tasks are complete. If several tasks throw 27 | * exceptions one of them will be re-thrown. Callback won't be called for 28 | * tasks that throw exception. 29 | * 30 | * @param first Range of tasks to be scheduled 31 | * @param last 32 | * @param F callback to call for each result. 33 | * In case of each task returning void it should be callable 34 | * F(size_t id) 35 | * otherwise should be callable 36 | * F(size_t id, Result) 37 | */ 38 | template 39 | inline void forEach(InputIterator first, InputIterator last, F&& f); 40 | 41 | }} // folly::fibers 42 | 43 | #include 44 | -------------------------------------------------------------------------------- /folly/wangle/acceptor/DomainNameMisc.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #pragma once 11 | 12 | #include 13 | 14 | namespace folly { 15 | 16 | struct dn_char_traits : public std::char_traits { 17 | static bool eq(char c1, char c2) { 18 | return ::tolower(c1) == ::tolower(c2); 19 | } 20 | 21 | static bool ne(char c1, char c2) { 22 | return ::tolower(c1) != ::tolower(c2); 23 | } 24 | 25 | static bool lt(char c1, char c2) { 26 | return ::tolower(c1) < ::tolower(c2); 27 | } 28 | 29 | static int compare(const char* s1, const char* s2, size_t n) { 30 | while (n--) { 31 | if(::tolower(*s1) < ::tolower(*s2) ) { 32 | return -1; 33 | } 34 | if(::tolower(*s1) > ::tolower(*s2) ) { 35 | return 1; 36 | } 37 | ++s1; 38 | ++s2; 39 | } 40 | return 0; 41 | } 42 | 43 | static const char* find(const char* s, size_t n, char a) { 44 | char la = ::tolower(a); 45 | while (n--) { 46 | if(::tolower(*s) == la) { 47 | return s; 48 | } else { 49 | ++s; 50 | } 51 | } 52 | return nullptr; 53 | } 54 | }; 55 | 56 | // Case insensitive string 57 | typedef std::basic_string DNString; 58 | 59 | struct DNStringHash : public std::hash { 60 | size_t operator()(const DNString& s1) const noexcept { 61 | std::string s2(s1.data(), s1.size()); 62 | for (char& c : s2) 63 | c = ::tolower(c); 64 | return std::hash()(s2); 65 | } 66 | }; 67 | 68 | } // namespace 69 | -------------------------------------------------------------------------------- /folly/test/DemangleTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | 22 | using folly::demangle; 23 | 24 | namespace folly_test { 25 | struct ThisIsAVeryLongStructureName { 26 | }; 27 | } // namespace folly_test 28 | 29 | #if FOLLY_HAVE_CPLUS_DEMANGLE_V3_CALLBACK 30 | TEST(Demangle, demangle) { 31 | char expected[] = "folly_test::ThisIsAVeryLongStructureName"; 32 | EXPECT_STREQ( 33 | expected, 34 | demangle(typeid(folly_test::ThisIsAVeryLongStructureName)).c_str()); 35 | 36 | { 37 | char buf[sizeof(expected)]; 38 | EXPECT_EQ(sizeof(expected) - 1, 39 | demangle(typeid(folly_test::ThisIsAVeryLongStructureName), 40 | buf, sizeof(buf))); 41 | EXPECT_STREQ(expected, buf); 42 | 43 | EXPECT_EQ(sizeof(expected) - 1, 44 | demangle(typeid(folly_test::ThisIsAVeryLongStructureName), 45 | buf, 11)); 46 | EXPECT_STREQ("folly_test", buf); 47 | } 48 | } 49 | #endif 50 | 51 | int main(int argc, char *argv[]) { 52 | testing::InitGoogleTest(&argc, argv); 53 | gflags::ParseCommandLineFlags(&argc, &argv, true); 54 | return RUN_ALL_TESTS(); 55 | } 56 | -------------------------------------------------------------------------------- /folly/futures/detail/ThreadWheelTimekeeper.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | #include 24 | 25 | namespace folly { namespace detail { 26 | 27 | /// The default Timekeeper implementation which uses a HHWheelTimer on an 28 | /// EventBase in a dedicated thread. Users needn't deal with this directly, it 29 | /// is used by default by Future methods that work with timeouts. 30 | class ThreadWheelTimekeeper : public Timekeeper { 31 | public: 32 | /// But it doesn't *have* to be a singleton. 33 | ThreadWheelTimekeeper(); 34 | ~ThreadWheelTimekeeper(); 35 | 36 | /// Implement the Timekeeper interface 37 | /// This future *does* complete on the timer thread. You should almost 38 | /// certainly follow it with a via() call or the accuracy of other timers 39 | /// will suffer. 40 | Future after(Duration) override; 41 | 42 | protected: 43 | folly::EventBase eventBase_; 44 | std::thread thread_; 45 | HHWheelTimer::UniquePtr wheelTimer_; 46 | }; 47 | 48 | Timekeeper* getTimekeeperSingleton(); 49 | 50 | }} // folly::detail 51 | -------------------------------------------------------------------------------- /folly/futures/test/thens.rb: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | # ruby folly/futures/test/thens.rb > folly/futures/test/Thens.cpp 4 | 5 | # An exercise in combinatorics. 6 | # (ordinary/static function, member function, std::function, lambda) 7 | # X 8 | # returns (Future, R) 9 | # X 10 | # accepts (Try&&, Try const&, Try, T&&, T const&, T, nothing) 11 | 12 | def test(*args) 13 | args = args.join(", ") 14 | [ 15 | "{Future f = someFuture().then(#{args});}", 16 | #"{Future f = makeFuture(A()).then(#{args}, anExecutor);}", 17 | ] 18 | end 19 | 20 | def retval(ret) 21 | { 22 | "Future" => "someFuture()", 23 | "Try" => "Try(B())", 24 | "B" => "B()" 25 | }[ret] 26 | end 27 | 28 | return_types = [ 29 | "Future", 30 | "B", 31 | #"Try", 32 | ] 33 | param_types = [ 34 | "Try&&", 35 | "Try const&", 36 | "Try", 37 | "Try&", 38 | "A&&", 39 | "A const&", 40 | "A", 41 | "A&", 42 | "", 43 | ] 44 | 45 | tests = ( 46 | return_types.map { |ret| 47 | param_types.map { |param| 48 | if param != "" then 49 | both = "#{ret}, #{param}" 50 | [ 51 | ["&aFunction<#{both}>"], 52 | ["&SomeClass::aStaticMethod<#{both}>"], 53 | ["&SomeClass::aMethod<#{both}>", "&anObject"], 54 | ["aStdFunction<#{both}>()"], 55 | ["[&](#{param}){return #{retval(ret)};}"], 56 | ] 57 | else 58 | [["[&](){return #{retval(ret)};}"]] 59 | end 60 | } 61 | }.flatten(2) 62 | ).map {|a| test(a)}.flatten 63 | 64 | print < 68 | 69 | TEST(Future, thenVariants) { 70 | SomeClass anObject; 71 | folly::Executor* anExecutor; 72 | 73 | #{tests.join("\n ")} 74 | } 75 | 76 | EOF 77 | -------------------------------------------------------------------------------- /folly/test/DeterministicScheduleTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | 22 | using namespace folly::test; 23 | 24 | TEST(DeterministicSchedule, uniform) { 25 | auto p = DeterministicSchedule::uniform(0); 26 | int buckets[10] = {}; 27 | for (int i = 0; i < 100000; ++i) { 28 | buckets[p(10)]++; 29 | } 30 | for (int i = 0; i < 10; ++i) { 31 | EXPECT_TRUE(buckets[i] > 9000); 32 | } 33 | } 34 | 35 | TEST(DeterministicSchedule, uniformSubset) { 36 | auto ps = DeterministicSchedule::uniformSubset(0, 3, 100); 37 | int buckets[10] = {}; 38 | std::set seen; 39 | for (int i = 0; i < 100000; ++i) { 40 | if (i > 0 && (i % 100) == 0) { 41 | EXPECT_EQ(seen.size(), 3); 42 | seen.clear(); 43 | } 44 | int x = ps(10); 45 | seen.insert(x); 46 | EXPECT_TRUE(seen.size() <= 3); 47 | buckets[x]++; 48 | } 49 | for (int i = 0; i < 10; ++i) { 50 | EXPECT_TRUE(buckets[i] > 9000); 51 | } 52 | } 53 | 54 | int main(int argc, char** argv) { 55 | testing::InitGoogleTest(&argc, argv); 56 | gflags::ParseCommandLineFlags(&argc, &argv, true); 57 | return RUN_ALL_TESTS(); 58 | } 59 | -------------------------------------------------------------------------------- /folly/experimental/fibers/LoopController.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | #include 20 | 21 | namespace folly { namespace fibers { 22 | 23 | class FiberManager; 24 | 25 | class LoopController { 26 | public: 27 | typedef std::chrono::steady_clock Clock; 28 | typedef std::chrono::time_point TimePoint; 29 | 30 | virtual ~LoopController() {} 31 | 32 | /** 33 | * Called by FiberManager to associate itself with the LoopController. 34 | */ 35 | virtual void setFiberManager(FiberManager*) = 0; 36 | 37 | /** 38 | * Called by FiberManager to schedule the loop function run 39 | * at some point in the future. 40 | */ 41 | virtual void schedule() = 0; 42 | 43 | /** 44 | * Same as schedule(), but safe to call from any thread. 45 | */ 46 | virtual void scheduleThreadSafe() = 0; 47 | 48 | /** 49 | * Called by FiberManager to cancel a previously scheduled 50 | * loop function run. 51 | */ 52 | virtual void cancel() = 0; 53 | 54 | /** 55 | * Called by FiberManager to schedule some function to be run at some time. 56 | */ 57 | virtual void timedSchedule(std::function func, TimePoint time) = 0; 58 | }; 59 | 60 | }} // folly::fibers 61 | -------------------------------------------------------------------------------- /folly/wangle/codec/LineBasedFrameDecoder.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | #include 20 | 21 | namespace folly { namespace wangle { 22 | 23 | /** 24 | * A decoder that splits the received IOBufQueue on line endings. 25 | * 26 | * Both "\n" and "\r\n" are handled, or optionally reqire only 27 | * one or the other. 28 | */ 29 | class LineBasedFrameDecoder : public ByteToMessageCodec { 30 | public: 31 | enum class TerminatorType { 32 | BOTH, 33 | NEWLINE, 34 | CARRIAGENEWLINE 35 | }; 36 | 37 | LineBasedFrameDecoder(uint32_t maxLength = UINT_MAX, 38 | bool stripDelimiter = true, 39 | TerminatorType terminatorType = 40 | TerminatorType::BOTH); 41 | 42 | std::unique_ptr decode(Context* ctx, IOBufQueue& buf, size_t&); 43 | 44 | private: 45 | 46 | int64_t findEndOfLine(IOBufQueue& buf); 47 | 48 | void fail(Context* ctx, std::string len); 49 | 50 | uint32_t maxLength_; 51 | bool stripDelimiter_; 52 | 53 | bool discarding_{false}; 54 | uint32_t discardedBytes_{0}; 55 | 56 | TerminatorType terminatorType_; 57 | }; 58 | 59 | }} // namespace 60 | -------------------------------------------------------------------------------- /folly/io/async/test/MockAsyncServerSocket.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | 20 | #include 21 | #include 22 | 23 | namespace folly { 24 | 25 | namespace test { 26 | 27 | class MockAsyncServerSocket : public AsyncServerSocket { 28 | public: 29 | typedef std::unique_ptr UniquePtr; 30 | 31 | // We explicitly do not mock destroy(), since the base class implementation 32 | // in TDelayedDestruction is what actually deletes the object. 33 | //MOCK_METHOD0(destroy, 34 | // void()); 35 | MOCK_METHOD1(bind, 36 | void(const folly::SocketAddress& address)); 37 | MOCK_METHOD2(bind, 38 | void(const std::vector& ipAddresses, 39 | uint16_t port)); 40 | MOCK_METHOD1(bind, 41 | void(uint16_t port)); 42 | MOCK_METHOD1(listen, 43 | void(int backlog)); 44 | MOCK_METHOD0(startAccepting, 45 | void()); 46 | MOCK_METHOD3(addAcceptCallback, 47 | void(AcceptCallback *callback, 48 | EventBase *eventBase, 49 | uint32_t maxAtOnce)); 50 | }; 51 | 52 | }} 53 | -------------------------------------------------------------------------------- /folly/Unicode.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | namespace folly { 20 | 21 | ////////////////////////////////////////////////////////////////////// 22 | 23 | fbstring codePointToUtf8(char32_t cp) { 24 | fbstring result; 25 | 26 | // Based on description from http://en.wikipedia.org/wiki/UTF-8. 27 | 28 | if (cp <= 0x7f) { 29 | result.resize(1); 30 | result[0] = static_cast(cp); 31 | } else if (cp <= 0x7FF) { 32 | result.resize(2); 33 | result[1] = static_cast(0x80 | (0x3f & cp)); 34 | result[0] = static_cast(0xC0 | (cp >> 6)); 35 | } else if (cp <= 0xFFFF) { 36 | result.resize(3); 37 | result[2] = static_cast(0x80 | (0x3f & cp)); 38 | result[1] = (0x80 | static_cast((0x3f & (cp >> 6)))); 39 | result[0] = (0xE0 | static_cast(cp >> 12)); 40 | } else if (cp <= 0x10FFFF) { 41 | result.resize(4); 42 | result[3] = static_cast(0x80 | (0x3f & cp)); 43 | result[2] = static_cast(0x80 | (0x3f & (cp >> 6))); 44 | result[1] = static_cast(0x80 | (0x3f & (cp >> 12))); 45 | result[0] = static_cast(0xF0 | (cp >> 18)); 46 | } 47 | 48 | return result; 49 | } 50 | 51 | ////////////////////////////////////////////////////////////////////// 52 | 53 | } 54 | -------------------------------------------------------------------------------- /folly/experimental/exception_tracer/ExceptionTracerBenchmark.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | 21 | #include 22 | #include 23 | 24 | #include 25 | #include 26 | 27 | void recurse(int level) { 28 | if (level == 0) { 29 | throw std::runtime_error(""); 30 | } 31 | recurse(level - 1); 32 | folly::doNotOptimizeAway(0); // prevent tail recursion 33 | } 34 | 35 | void loop(int iters) { 36 | for (int i = 0; i < iters * 100; ++i) { 37 | try { 38 | recurse(100); 39 | } catch (const std::exception& e) { 40 | folly::exception_tracer::getCurrentExceptions(); 41 | } 42 | } 43 | } 44 | 45 | BENCHMARK(ExceptionTracer, iters) { 46 | std::vector threads; 47 | constexpr size_t kNumThreads = 10; 48 | threads.resize(10); 49 | for (auto& t : threads) { 50 | t = std::thread([iters] () { loop(iters); }); 51 | } 52 | for (auto& t : threads) { 53 | t.join(); 54 | } 55 | } 56 | 57 | int main(int argc, char* argv[]) { 58 | gflags::ParseCommandLineFlags(&argc, &argv, true); 59 | google::InitGoogleLogging(argv[0]); 60 | folly::runBenchmarks(); 61 | return 0; 62 | } 63 | -------------------------------------------------------------------------------- /folly/experimental/exception_tracer/ExceptionTracer.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | // 18 | // Exception tracer library. 19 | 20 | #ifndef FOLLY_EXPERIMENTAL_EXCEPTION_TRACER_EXCEPTIONTRACER_H_ 21 | #define FOLLY_EXPERIMENTAL_EXCEPTION_TRACER_EXCEPTIONTRACER_H_ 22 | 23 | #include 24 | #include 25 | #include 26 | #include 27 | 28 | namespace folly { 29 | namespace exception_tracer { 30 | 31 | struct ExceptionInfo { 32 | const std::type_info* type; 33 | // The values in frames are IP (instruction pointer) addresses. 34 | // They are only filled if the low-level exception tracer library is 35 | // linked in or LD_PRELOADed. 36 | std::vector frames; // front() is top of stack 37 | }; 38 | 39 | std::ostream& operator<<(std::ostream& out, const ExceptionInfo& info); 40 | 41 | /** 42 | * Get current exceptions being handled. front() is the most recent exception. 43 | * There should be at most one unless rethrowing. 44 | */ 45 | std::vector getCurrentExceptions(); 46 | 47 | /** 48 | * Install the terminate / unexpected handlers to dump exceptions. 49 | */ 50 | void installHandlers(); 51 | 52 | } // namespace exception_tracer 53 | } // namespace folly 54 | 55 | #endif /* FOLLY_EXPERIMENTAL_EXCEPTION_TRACER_EXCEPTIONTRACER_H_ */ 56 | -------------------------------------------------------------------------------- /folly/wangle/acceptor/TransportInfo.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) 2015, Facebook, Inc. 3 | * All rights reserved. 4 | * 5 | * This source code is licensed under the BSD-style license found in the 6 | * LICENSE file in the root directory of this source tree. An additional grant 7 | * of patent rights can be found in the PATENTS file in the same directory. 8 | * 9 | */ 10 | #include 11 | 12 | #include 13 | #include 14 | #include 15 | 16 | using std::chrono::microseconds; 17 | using std::map; 18 | using std::string; 19 | 20 | namespace folly { 21 | 22 | bool TransportInfo::initWithSocket(const AsyncSocket* sock) { 23 | #if defined(__linux__) || defined(__FreeBSD__) 24 | if (!TransportInfo::readTcpInfo(&tcpinfo, sock)) { 25 | tcpinfoErrno = errno; 26 | return false; 27 | } 28 | rtt = microseconds(tcpinfo.tcpi_rtt); 29 | validTcpinfo = true; 30 | #else 31 | tcpinfoErrno = EINVAL; 32 | rtt = microseconds(-1); 33 | #endif 34 | return true; 35 | } 36 | 37 | int64_t TransportInfo::readRTT(const AsyncSocket* sock) { 38 | #if defined(__linux__) || defined(__FreeBSD__) 39 | struct tcp_info tcpinfo; 40 | if (!TransportInfo::readTcpInfo(&tcpinfo, sock)) { 41 | return -1; 42 | } 43 | return tcpinfo.tcpi_rtt; 44 | #else 45 | return -1; 46 | #endif 47 | } 48 | 49 | #if defined(__linux__) || defined(__FreeBSD__) 50 | bool TransportInfo::readTcpInfo(struct tcp_info* tcpinfo, 51 | const AsyncSocket* sock) { 52 | socklen_t len = sizeof(struct tcp_info); 53 | if (!sock) { 54 | return false; 55 | } 56 | if (getsockopt(sock->getFd(), IPPROTO_TCP, 57 | TCP_INFO, (void*) tcpinfo, &len) < 0) { 58 | VLOG(4) << "Error calling getsockopt(): " << strerror(errno); 59 | return false; 60 | } 61 | return true; 62 | } 63 | #endif 64 | 65 | } // folly 66 | -------------------------------------------------------------------------------- /folly/wangle/concurrent/GlobalExecutor.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | #include 22 | #include 23 | 24 | namespace folly { namespace wangle { 25 | 26 | // Retrieve the global Executor. If there is none, a default InlineExecutor 27 | // will be constructed and returned. This is named CPUExecutor to distinguish 28 | // it from IOExecutor below and to hint that it's intended for CPU-bound tasks. 29 | std::shared_ptr getCPUExecutor(); 30 | 31 | // Set an Executor to be the global Executor which will be returned by 32 | // subsequent calls to getCPUExecutor(). Takes a non-owning (weak) reference. 33 | void setCPUExecutor(std::shared_ptr executor); 34 | 35 | // Retrieve the global IOExecutor. If there is none, a default 36 | // IOThreadPoolExecutor will be constructed and returned. 37 | // 38 | // IOExecutors differ from Executors in that they drive and provide access to 39 | // one or more EventBases. 40 | std::shared_ptr getIOExecutor(); 41 | 42 | // Set an IOExecutor to be the global IOExecutor which will be returned by 43 | // subsequent calls to getIOExecutor(). Takes a non-owning (weak) reference. 44 | void setIOExecutor(std::shared_ptr executor); 45 | 46 | }} 47 | -------------------------------------------------------------------------------- /folly/experimental/exception_tracer/ExceptionAbi.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | 18 | #ifndef FOLLY_EXPERIMENTAL_EXCEPTION_TRACER_EXCEPTIONABI_H_ 19 | #define FOLLY_EXPERIMENTAL_EXCEPTION_TRACER_EXCEPTIONABI_H_ 20 | 21 | // A clone of the relevant parts of unwind-cxx.h from libstdc++ 22 | // The layout of these structures is defined by the ABI. 23 | 24 | #include 25 | #include 26 | 27 | #include 28 | 29 | namespace __cxxabiv1 { 30 | 31 | struct __cxa_exception { 32 | std::type_info* exceptionType; 33 | void (*exceptionDestructor) (void*); 34 | std::unexpected_handler unexpectedHandler; 35 | std::terminate_handler terminateHandler; 36 | __cxa_exception* nextException; 37 | 38 | int handlerCount; 39 | int handlerSwitchValue; 40 | const char* actionRecord; 41 | const char* languageSpecificData; 42 | void* catchTemp; 43 | void* adjustedPtr; 44 | 45 | _Unwind_Exception unwindHeader; 46 | }; 47 | 48 | struct __cxa_eh_globals { 49 | __cxa_exception* caughtExceptions; 50 | unsigned int uncaughtExceptions; 51 | }; 52 | 53 | extern "C" { 54 | __cxa_eh_globals* __cxa_get_globals(void) noexcept; 55 | __cxa_eh_globals* __cxa_get_globals_fast(void) noexcept; 56 | } 57 | 58 | } // namespace __cxxabiv1 59 | 60 | #endif /* FOLLY_EXPERIMENTAL_EXCEPTION_TRACER_EXCEPTIONABI_H_ */ 61 | -------------------------------------------------------------------------------- /folly/test/SingletonVaultCTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include 19 | 20 | #include 21 | 22 | #include 23 | 24 | __thread long instance_counter_instances = 0; 25 | 26 | class InstanceCounter { 27 | public: 28 | InstanceCounter() { 29 | instance_counter_instances++; 30 | } 31 | 32 | ~InstanceCounter() { 33 | instance_counter_instances--; 34 | } 35 | }; 36 | 37 | TEST(SingletonVault, singletonReturnsSingletonInstance) { 38 | SingletonVault_t *c = SingletonVault_singleton(); 39 | auto *cpp = folly::SingletonVault::singleton(); 40 | EXPECT_EQ(c, cpp); 41 | } 42 | 43 | struct TestTag {}; 44 | template 45 | using SingletonTest = folly::Singleton ; 46 | 47 | TEST(SingletonVault, singletonsAreCreatedAndDestroyed) { 48 | auto vault = folly::SingletonVault::singleton(); 49 | SingletonTest counter_singleton; 50 | SingletonVault_registrationComplete((SingletonVault_t*) vault); 51 | InstanceCounter *counter = SingletonTest::get(); 52 | EXPECT_EQ(instance_counter_instances, 1); 53 | SingletonVault_destroyInstances((SingletonVault_t*) vault); 54 | EXPECT_EQ(instance_counter_instances, 0); 55 | } 56 | -------------------------------------------------------------------------------- /folly/SafeAssert.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_SAFEASSERT_H_ 18 | #define FOLLY_SAFEASSERT_H_ 19 | 20 | #include 21 | #include 22 | 23 | /** 24 | * Verify that the expression is true. If not, prints an error message 25 | * (containing msg) to stderr and abort()s. Just like CHECK(), but only 26 | * logs to stderr and only does async-signal-safe calls. 27 | */ 28 | #define FOLLY_SAFE_CHECK(expr, msg) \ 29 | ((expr) ? static_cast(0) : \ 30 | ::folly::detail::assertionFailure( \ 31 | FB_STRINGIZE(expr), (msg), __FILE__, __LINE__, __PRETTY_FUNCTION__)) 32 | 33 | /** 34 | * In debug mode, verify that the expression is true. Otherwise, do nothing 35 | * (do not even evaluate expr). Just like assert() or DCHECK(), but only 36 | * logs to stderr and only does async-signal-safe calls. 37 | */ 38 | #ifdef NDEBUG 39 | #define FOLLY_SAFE_DCHECK(expr, msg) (static_cast(0)) 40 | #else 41 | #define FOLLY_SAFE_DCHECK FOLLY_SAFE_CHECK 42 | #endif 43 | 44 | namespace folly { namespace detail { 45 | 46 | FOLLY_NORETURN void assertionFailure(const char* expr, const char* msg, 47 | const char* file, unsigned int line, 48 | const char* function); 49 | 50 | }} // namespace folly 51 | 52 | #endif /* FOLLY_SAFEASSERT_H_ */ 53 | -------------------------------------------------------------------------------- /folly/futures/OpaqueCallbackShunt.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | 21 | namespace folly { 22 | 23 | /// These classes help you wrap an existing C style callback function 24 | /// into a Future. 25 | /// 26 | /// void legacy_send_async(..., void (*cb)(void*), void*); 27 | /// 28 | /// Future wrappedSendAsync(T&& obj) { 29 | /// auto handle = new OpaqueCallbackShunt(obj); 30 | /// auto future = handle->promise_.getFuture(); 31 | /// legacy_send_async(..., OpaqueCallbackShunt::callback, handle) 32 | /// return future; 33 | /// } 34 | /// 35 | /// If the legacy function doesn't conform to void (*cb)(void*), use a lambda: 36 | /// 37 | /// auto cb = [](t1*, t2*, void* arg) { 38 | /// OpaqueCallbackShunt::callback(arg); 39 | /// }; 40 | /// legacy_send_async(..., cb, handle); 41 | 42 | template 43 | class OpaqueCallbackShunt { 44 | public: 45 | explicit OpaqueCallbackShunt(T&& obj) 46 | : obj_(std::move(obj)) { } 47 | static void callback(void* arg) { 48 | std::unique_ptr> handle( 49 | static_cast*>(arg)); 50 | handle->promise_.setValue(std::move(handle->obj_)); 51 | } 52 | folly::Promise promise_; 53 | private: 54 | T obj_; 55 | }; 56 | 57 | } // folly 58 | -------------------------------------------------------------------------------- /folly/wangle/acceptor/ManagedConnection.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | 21 | namespace folly { namespace wangle { 22 | 23 | ManagedConnection::ManagedConnection() 24 | : connectionManager_(nullptr) { 25 | } 26 | 27 | ManagedConnection::~ManagedConnection() { 28 | if (connectionManager_) { 29 | connectionManager_->removeConnection(this); 30 | } 31 | } 32 | 33 | void 34 | ManagedConnection::resetTimeout() { 35 | if (connectionManager_) { 36 | resetTimeoutTo(connectionManager_->getDefaultTimeout()); 37 | } 38 | } 39 | 40 | void 41 | ManagedConnection::resetTimeoutTo(std::chrono::milliseconds timeout) { 42 | if (connectionManager_) { 43 | connectionManager_->scheduleTimeout(this, timeout); 44 | } 45 | } 46 | 47 | void 48 | ManagedConnection::scheduleTimeout( 49 | folly::HHWheelTimer::Callback* callback, 50 | std::chrono::milliseconds timeout) { 51 | if (connectionManager_) { 52 | connectionManager_->scheduleTimeout(callback, timeout); 53 | } 54 | } 55 | 56 | ////////////////////// Globals ///////////////////// 57 | 58 | std::ostream& 59 | operator<<(std::ostream& os, const ManagedConnection& conn) { 60 | conn.describe(os); 61 | return os; 62 | } 63 | 64 | }} // folly::wangle 65 | -------------------------------------------------------------------------------- /folly/wangle/codec/ByteToMessageCodec.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | 20 | namespace folly { namespace wangle { 21 | 22 | /** 23 | * A Handler which decodes bytes in a stream-like fashion from 24 | * IOBufQueue to a Message type. 25 | * 26 | * Frame detection 27 | * 28 | * Generally frame detection should be handled earlier in the pipeline 29 | * by adding a DelimiterBasedFrameDecoder, FixedLengthFrameDecoder, 30 | * LengthFieldBasedFrameDecoder, LineBasedFrameDecoder. 31 | * 32 | * If a custom frame decoder is required, then one needs to be careful 33 | * when implementing one with {@link ByteToMessageDecoder}. Ensure 34 | * there are enough bytes in the buffer for a complete frame by 35 | * checking {@link ByteBuf#readableBytes()}. If there are not enough 36 | * bytes for a complete frame, return without modify the reader index 37 | * to allow more bytes to arrive. 38 | * 39 | * To check for complete frames without modify the reader index, use 40 | * IOBufQueue.front(), without split() or pop_front(). 41 | */ 42 | class ByteToMessageCodec 43 | : public InboundBytesToBytesHandler { 44 | public: 45 | 46 | virtual std::unique_ptr decode( 47 | Context* ctx, IOBufQueue& buf, size_t&) = 0; 48 | 49 | void read(Context* ctx, IOBufQueue& q); 50 | }; 51 | 52 | }} 53 | -------------------------------------------------------------------------------- /folly/test/EndianTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | 21 | using namespace folly; 22 | 23 | TEST(Endian, Basic) { 24 | uint8_t v8 = 0x12; 25 | uint8_t v8s = 0x12; 26 | uint16_t v16 = 0x1234; 27 | uint16_t v16s = 0x3412; 28 | uint32_t v32 = 0x12345678; 29 | uint32_t v32s = 0x78563412; 30 | uint64_t v64 = 0x123456789abcdef0ULL; 31 | uint64_t v64s = 0xf0debc9a78563412ULL; 32 | 33 | #if __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__ 34 | 35 | #define GEN1(sz) \ 36 | EXPECT_EQ(v##sz, Endian::little(v##sz)); \ 37 | EXPECT_EQ(v##sz, Endian::little##sz(v##sz)); \ 38 | EXPECT_EQ(v##sz##s, Endian::big(v##sz)); \ 39 | EXPECT_EQ(v##sz##s, Endian::big##sz(v##sz)); 40 | 41 | #elif __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__ 42 | 43 | #define GEN1(sz) \ 44 | EXPECT_EQ(v##sz##s, Endian::little(v##sz)); \ 45 | EXPECT_EQ(v##sz##s, Endian::little##sz(v##sz)); \ 46 | EXPECT_EQ(v##sz, Endian::big(v##sz)); \ 47 | EXPECT_EQ(v##sz, Endian::big##sz(v##sz)); 48 | 49 | #else 50 | # error Your machine uses a weird endianness! 51 | #endif /* __BYTE_ORDER__ */ 52 | 53 | #define GEN(sz) \ 54 | EXPECT_EQ(v##sz##s, Endian::swap(v##sz)); \ 55 | EXPECT_EQ(v##sz##s, Endian::swap##sz(v##sz)); \ 56 | GEN1(sz); 57 | 58 | GEN(8); 59 | GEN(16) 60 | GEN(32) 61 | GEN(64) 62 | 63 | #undef GEN 64 | #undef GEN1 65 | } 66 | -------------------------------------------------------------------------------- /folly/experimental/JSONSchemaTester.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #include 17 | #include 18 | #include 19 | #include 20 | 21 | /** 22 | * A binary that supports testing against the official tests from: 23 | * https://github.com/json-schema/JSON-Schema-Test-Suite 24 | * 25 | * Use it like: 26 | * ./jsonschema_tester /path/to/test.json 27 | */ 28 | 29 | int main(int argc, char** argv) { 30 | if (argc < 2) { 31 | printf("Usage: %s [testfile2]...\n", argv[0]); 32 | return -1; 33 | } 34 | for (int i = 1; i < argc; ++i) { 35 | printf("FILE: %s\n", argv[i]); 36 | std::ifstream fin(argv[i]); 37 | std::stringstream buffer; 38 | buffer << fin.rdbuf(); 39 | const folly::dynamic d = folly::parseJson(buffer.str()); 40 | for (const auto& item : d) { 41 | printf("TEST: %s\n", item["description"].c_str()); 42 | auto v = folly::jsonschema::makeValidator(item["schema"]); 43 | for (const auto& t : item["tests"]) { 44 | printf("\t%s... ", t["description"].c_str()); 45 | auto ew = v->try_validate(t["data"]); 46 | bool had_error = !static_cast(ew); 47 | if (had_error == t["valid"].asBool()) { 48 | printf("passed\n"); 49 | } else { 50 | printf("FAILED\n"); 51 | } 52 | } 53 | } 54 | } 55 | } 56 | -------------------------------------------------------------------------------- /folly/wangle/rx/Subscription.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include // must come first 20 | #include 21 | 22 | namespace folly { namespace wangle { 23 | 24 | template 25 | class Subscription { 26 | public: 27 | Subscription() {} 28 | 29 | Subscription(const Subscription&) = delete; 30 | 31 | Subscription(Subscription&& other) noexcept { 32 | *this = std::move(other); 33 | } 34 | 35 | Subscription& operator=(Subscription&& other) noexcept { 36 | unsubscribe(); 37 | unsubscriber_ = std::move(other.unsubscriber_); 38 | id_ = other.id_; 39 | other.unsubscriber_ = nullptr; 40 | other.id_ = 0; 41 | return *this; 42 | } 43 | 44 | ~Subscription() { 45 | unsubscribe(); 46 | } 47 | 48 | private: 49 | typedef typename Observable::Unsubscriber Unsubscriber; 50 | 51 | Subscription(std::shared_ptr unsubscriber, uint64_t id) 52 | : unsubscriber_(std::move(unsubscriber)), id_(id) { 53 | CHECK(id_ > 0); 54 | } 55 | 56 | void unsubscribe() { 57 | if (unsubscriber_ && id_ > 0) { 58 | unsubscriber_->unsubscribe(id_); 59 | id_ = 0; 60 | unsubscriber_ = nullptr; 61 | } 62 | } 63 | 64 | std::shared_ptr unsubscriber_; 65 | uint64_t id_{0}; 66 | 67 | friend class Observable; 68 | }; 69 | 70 | }} 71 | -------------------------------------------------------------------------------- /folly/experimental/symbolizer/SignalHandler.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_SYMBOLIZER_SIGNALHANDLER_H_ 18 | #define FOLLY_SYMBOLIZER_SIGNALHANDLER_H_ 19 | 20 | #include 21 | 22 | namespace folly { namespace symbolizer { 23 | 24 | /** 25 | * Install handler for fatal signals. The list of signals being handled is in 26 | * SignalHandler.cpp. 27 | * 28 | * The handler will dump signal and time information followed by a stack trace 29 | * to stderr, and then call the callbacks registered below. 30 | */ 31 | void installFatalSignalHandler(); 32 | 33 | /** 34 | * Add a callback to be run when receiving a fatal signal. They will also 35 | * be called by LOG(FATAL) and abort() (as those raise SIGABRT internally). 36 | * 37 | * These callbacks must be async-signal-safe, so don't even think of using 38 | * LOG(...) or printf or malloc / new or doing anything even remotely fun. 39 | * 40 | * All these fatal callback must be added before calling 41 | * installFatalSignalCallbacks(), below. 42 | */ 43 | typedef void (*SignalCallback)(void); 44 | void addFatalSignalCallback(SignalCallback callback); 45 | 46 | /** 47 | * Install the fatal signal callbacks; fatal signals will call these 48 | * callbacks in the order in which they were added. 49 | */ 50 | void installFatalSignalCallbacks(); 51 | 52 | 53 | }} // namespaces 54 | 55 | #endif /* FOLLY_SYMBOLIZER_SIGNALHANDLER_H_ */ 56 | -------------------------------------------------------------------------------- /folly/experimental/fibers/EventBaseLoopController.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | #include 20 | #include 21 | 22 | namespace folly { 23 | class EventBase; 24 | } 25 | 26 | namespace folly { namespace fibers { 27 | 28 | class FiberManager; 29 | 30 | class EventBaseLoopController : public LoopController { 31 | public: 32 | explicit EventBaseLoopController(); 33 | ~EventBaseLoopController(); 34 | 35 | /** 36 | * Attach EventBase after LoopController was created. 37 | */ 38 | void attachEventBase(folly::EventBase& eventBase); 39 | 40 | folly::EventBase* getEventBase() { 41 | return eventBase_; 42 | } 43 | 44 | private: 45 | class ControllerCallback; 46 | 47 | bool awaitingScheduling_{false}; 48 | folly::EventBase* eventBase_{nullptr}; 49 | std::unique_ptr callback_; 50 | FiberManager* fm_{nullptr}; 51 | std::atomic eventBaseAttached_{false}; 52 | 53 | /* LoopController interface */ 54 | 55 | void setFiberManager(FiberManager* fm) override; 56 | void schedule() override; 57 | void cancel() override; 58 | void runLoop(); 59 | void scheduleThreadSafe() override; 60 | void timedSchedule(std::function func, TimePoint time) override; 61 | 62 | friend class FiberManager; 63 | }; 64 | 65 | }} // folly::fibers 66 | 67 | #include "EventBaseLoopController-inl.h" 68 | -------------------------------------------------------------------------------- /folly/wangle/rx/README.md: -------------------------------------------------------------------------------- 1 | Rx is a pattern for "functional reactive programming" that started at 2 | Microsoft in C#, and has been reimplemented in various languages, notably 3 | RxJava for JVM languages. 4 | 5 | It is basically the plural of Futures (a la Wangle). 6 | 7 | ``` 8 | singular | plural 9 | +---------------------------------+----------------------------------- 10 | sync | Foo getData() | std::vector getData() 11 | async | wangle::Future getData() | wangle::Observable getData() 12 | ``` 13 | 14 | For more on Rx, I recommend these resources: 15 | 16 | Netflix blog post (RxJava): http://techblog.netflix.com/2013/02/rxjava-netflix-api.html 17 | Introduction to Rx eBook (C#): http://www.introtorx.com/content/v1.0.10621.0/01_WhyRx.html 18 | The RxJava wiki: https://github.com/Netflix/RxJava/wiki 19 | Netflix QCon presentation: http://www.infoq.com/presentations/netflix-functional-rx 20 | https://rx.codeplex.com/ 21 | 22 | There are open source C++ implementations, I haven't looked at them. They 23 | might be the best way to go rather than writing it NIH-style. I mostly did it 24 | as an exercise, to think through how closely we might want to integrate 25 | something like this with Wangle, and to get a feel for how it works in C++. 26 | 27 | I haven't even tried to support move-only data in this version. I'm on the 28 | fence about the usage of shared_ptr. Subject is underdeveloped. A whole rich 29 | set of operations is obviously missing. I haven't decided how to handle 30 | subscriptions (and therefore cancellation), but I'm pretty sure C#'s 31 | "Disposable" is thoroughly un-C++ (opposite of RAII). So for now subscribe 32 | returns nothing at all and you can't cancel anything ever. The whole thing is 33 | probably riddled with lifetime corner case bugs that will come out like a 34 | swarm of angry bees as soon as someone tries an infinite sequence, or tries to 35 | partially observe a long sequence. I'm pretty sure subscribeOn has a bug that 36 | I haven't tracked down yet. 37 | -------------------------------------------------------------------------------- /folly/experimental/io/FsUtil.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | namespace bsys = ::boost::system; 20 | 21 | namespace folly { 22 | namespace fs { 23 | 24 | namespace { 25 | bool skipPrefix(const path& pth, const path& prefix, path::const_iterator& it) { 26 | it = pth.begin(); 27 | for (auto& p : prefix) { 28 | if (it == pth.end()) { 29 | return false; 30 | } 31 | if (p == ".") { 32 | // Should only occur at the end, if prefix ends with a slash 33 | continue; 34 | } 35 | if (*it++ != p) { 36 | return false; 37 | } 38 | } 39 | return true; 40 | } 41 | } // namespace 42 | 43 | bool starts_with(const path& pth, const path& prefix) { 44 | path::const_iterator it; 45 | return skipPrefix(pth, prefix, it); 46 | } 47 | 48 | path remove_prefix(const path& pth, const path& prefix) { 49 | path::const_iterator it; 50 | if (!skipPrefix(pth, prefix, it)) { 51 | throw filesystem_error( 52 | "Path does not start with prefix", 53 | pth, prefix, 54 | bsys::errc::make_error_code(bsys::errc::invalid_argument)); 55 | } 56 | 57 | path p; 58 | for (; it != pth.end(); ++it) { 59 | p /= *it; 60 | } 61 | 62 | return p; 63 | } 64 | 65 | path canonical_parent(const path& pth, const path& base) { 66 | return canonical(pth.parent_path(), base) / pth.filename(); 67 | } 68 | 69 | } // namespace fs 70 | } // namespace folly 71 | -------------------------------------------------------------------------------- /folly/futures/test/Try.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | 22 | using namespace folly; 23 | 24 | // Make sure we can copy Trys for copyable types 25 | TEST(Try, copy) { 26 | Try t; 27 | auto t2 = t; 28 | } 29 | 30 | // But don't choke on move-only types 31 | TEST(Try, moveOnly) { 32 | Try> t; 33 | std::vector>> v; 34 | v.reserve(10); 35 | } 36 | 37 | TEST(Try, makeTryWith) { 38 | auto func = []() { 39 | return folly::make_unique(1); 40 | }; 41 | 42 | auto result = makeTryWith(func); 43 | EXPECT_TRUE(result.hasValue()); 44 | EXPECT_EQ(*result.value(), 1); 45 | } 46 | 47 | TEST(Try, makeTryWithThrow) { 48 | auto func = []() { 49 | throw std::runtime_error("Runtime"); 50 | return folly::make_unique(1); 51 | }; 52 | 53 | auto result = makeTryWith(func); 54 | EXPECT_TRUE(result.hasException()); 55 | } 56 | 57 | TEST(Try, makeTryWithVoid) { 58 | auto func = []() { 59 | return; 60 | }; 61 | 62 | auto result = makeTryWith(func); 63 | EXPECT_TRUE(result.hasValue()); 64 | } 65 | 66 | TEST(Try, makeTryWithVoidThrow) { 67 | auto func = []() { 68 | throw std::runtime_error("Runtime"); 69 | return; 70 | }; 71 | 72 | auto result = makeTryWith(func); 73 | EXPECT_TRUE(result.hasException()); 74 | } 75 | -------------------------------------------------------------------------------- /folly/test/MapUtilTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | #include 20 | #include 21 | 22 | using namespace folly; 23 | 24 | TEST(MapUtil, get_default) { 25 | std::map m; 26 | m[1] = 2; 27 | EXPECT_EQ(2, get_default(m, 1, 42)); 28 | EXPECT_EQ(42, get_default(m, 2, 42)); 29 | EXPECT_EQ(0, get_default(m, 3)); 30 | } 31 | 32 | TEST(MapUtil, get_or_throw) { 33 | std::map m; 34 | m[1] = 2; 35 | EXPECT_EQ(2, get_or_throw(m, 1)); 36 | EXPECT_THROW(get_or_throw(m, 2), std::out_of_range); 37 | } 38 | 39 | TEST(MapUtil, get_or_throw_specified) { 40 | std::map m; 41 | m[1] = 2; 42 | EXPECT_EQ(2, get_or_throw(m, 1)); 43 | EXPECT_THROW(get_or_throw(m, 2), std::runtime_error); 44 | } 45 | 46 | TEST(MapUtil, get_optional) { 47 | std::map m; 48 | m[1] = 2; 49 | EXPECT_TRUE(get_optional(m, 1).hasValue()); 50 | EXPECT_EQ(2, get_optional(m, 1).value()); 51 | EXPECT_FALSE(get_optional(m, 2).hasValue()); 52 | } 53 | 54 | TEST(MapUtil, get_ref_default) { 55 | std::map m; 56 | m[1] = 2; 57 | const int i = 42; 58 | EXPECT_EQ(2, get_ref_default(m, 1, i)); 59 | EXPECT_EQ(42, get_ref_default(m, 2, i)); 60 | } 61 | 62 | TEST(MapUtil, get_ptr) { 63 | std::map m; 64 | m[1] = 2; 65 | EXPECT_EQ(2, *get_ptr(m, 1)); 66 | EXPECT_TRUE(get_ptr(m, 2) == nullptr); 67 | *get_ptr(m, 1) = 4; 68 | EXPECT_EQ(4, m.at(1)); 69 | } 70 | -------------------------------------------------------------------------------- /folly/test/function_benchmark/test_functions.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | 19 | /* 20 | * These functions are defined in a separate file so that 21 | * gcc won't be able to inline them. 22 | */ 23 | 24 | 25 | class Exception : public std::exception { 26 | public: 27 | explicit Exception(const std::string& value) : value_(value) {} 28 | virtual ~Exception(void) noexcept {} 29 | 30 | virtual const char *what(void) const noexcept { 31 | return value_.c_str(); 32 | } 33 | 34 | private: 35 | std::string value_; 36 | }; 37 | 38 | void doNothing() { 39 | } 40 | 41 | void throwException() { 42 | throw Exception("this is a test"); 43 | } 44 | 45 | std::exception_ptr returnExceptionPtr() { 46 | Exception ex("this is a test"); 47 | return std::make_exception_ptr(ex); 48 | } 49 | 50 | void exceptionPtrReturnParam(std::exception_ptr* excReturn) { 51 | if (excReturn) { 52 | Exception ex("this is a test"); 53 | *excReturn = std::make_exception_ptr(ex); 54 | } 55 | } 56 | 57 | std::string returnString() { 58 | return "this is a test"; 59 | } 60 | 61 | std::string returnStringNoExcept() noexcept { 62 | return "this is a test"; 63 | } 64 | 65 | int returnCode(int value) { 66 | return value; 67 | } 68 | 69 | int returnCodeNoExcept(int value) noexcept { 70 | return value; 71 | } 72 | 73 | void TestClass::doNothing() { 74 | } 75 | 76 | VirtualClass::~VirtualClass() { 77 | } 78 | 79 | void VirtualClass::doNothing() { 80 | }; 81 | -------------------------------------------------------------------------------- /folly/Executor.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | #include 21 | #include 22 | 23 | namespace folly { 24 | 25 | typedef std::function Func; 26 | 27 | /// An Executor accepts units of work with add(), which should be 28 | /// threadsafe. 29 | class Executor { 30 | public: 31 | virtual ~Executor() = default; 32 | 33 | /// Enqueue a function to executed by this executor. This and all 34 | /// variants must be threadsafe. 35 | virtual void add(Func) = 0; 36 | 37 | /// Enqueue a function with a given priority, where 0 is the medium priority 38 | /// This is up to the implementation to enforce 39 | virtual void addWithPriority(Func, int8_t priority) { 40 | throw std::runtime_error( 41 | "addWithPriority() is not implemented for this Executor"); 42 | } 43 | 44 | virtual uint8_t getNumPriorities() const { 45 | return 1; 46 | } 47 | 48 | static const int8_t LO_PRI = SCHAR_MIN; 49 | static const int8_t MID_PRI = 0; 50 | static const int8_t HI_PRI = SCHAR_MAX; 51 | 52 | /// A convenience function for shared_ptr to legacy functors. 53 | /// 54 | /// Sometimes you have a functor that is move-only, and therefore can't be 55 | /// converted to a std::function (e.g. std::packaged_task). In that case, 56 | /// wrap it in a shared_ptr (or maybe folly::MoveWrapper) and use this. 57 | template 58 | void addPtr(P fn) { 59 | this->add([fn]() mutable { (*fn)(); }); 60 | } 61 | }; 62 | 63 | } // folly 64 | -------------------------------------------------------------------------------- /folly/wangle/codec/LengthFieldPrepender.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | #pragma once 17 | 18 | #include 19 | #include 20 | 21 | namespace folly { namespace wangle { 22 | 23 | /** 24 | * An encoder that prepends the length of the message. The length value is 25 | * prepended as a binary form. 26 | * 27 | * For example, LengthFieldPrepender(2)will encode the 28 | * following 12-bytes string: 29 | * 30 | * +----------------+ 31 | * | "HELLO, WORLD" | 32 | * +----------------+ 33 | * 34 | * into the following: 35 | * 36 | * +--------+----------------+ 37 | * + 0x000C | "HELLO, WORLD" | 38 | * +--------+----------------+ 39 | * 40 | * If you turned on the lengthIncludesLengthFieldLength flag in the 41 | * constructor, the encoded data would look like the following 42 | * (12 (original data) + 2 (prepended data) = 14 (0xE)): 43 | * 44 | * +--------+----------------+ 45 | * + 0x000E | "HELLO, WORLD" | 46 | * +--------+----------------+ 47 | * 48 | */ 49 | class LengthFieldPrepender 50 | : public OutboundBytesToBytesHandler { 51 | public: 52 | LengthFieldPrepender( 53 | int lengthFieldLength = 4, 54 | int lengthAdjustment = 0, 55 | bool lengthIncludesLengthField = false, 56 | bool networkByteOrder = true); 57 | 58 | Future write(Context* ctx, std::unique_ptr buf); 59 | 60 | private: 61 | int lengthFieldLength_; 62 | int lengthAdjustment_; 63 | bool lengthIncludesLengthField_; 64 | bool networkByteOrder_; 65 | }; 66 | 67 | }} // namespace 68 | -------------------------------------------------------------------------------- /folly/experimental/io/FsUtil.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef FOLLY_IO_FSUTIL_H_ 18 | #define FOLLY_IO_FSUTIL_H_ 19 | 20 | #include 21 | 22 | namespace folly { 23 | namespace fs { 24 | 25 | // Functions defined in this file are meant to extend the 26 | // boost::filesystem library; functions will be named according to boost's 27 | // naming conventions instead of ours. For convenience, import the 28 | // boost::filesystem namespace into folly::fs. 29 | using namespace ::boost::filesystem; 30 | 31 | /** 32 | * Check whether "path" starts with "prefix". 33 | * That is, if prefix has n path elements, then the first n elements of 34 | * path must be the same as prefix. 35 | * 36 | * There is a special case if prefix ends with a slash: 37 | * /foo/bar/ is not a prefix of /foo/bar, but both /foo/bar and /foo/bar/ 38 | * are prefixes of /foo/bar/baz. 39 | */ 40 | bool starts_with(const path& p, const path& prefix); 41 | 42 | /** 43 | * If "path" starts with "prefix", return "path" with "prefix" removed. 44 | * Otherwise, throw filesystem_error. 45 | */ 46 | path remove_prefix(const path& p, const path& prefix); 47 | 48 | /** 49 | * Canonicalize the parent path, leaving the filename (last component) 50 | * unchanged. You may use this before creating a file instead of 51 | * boost::filesystem::canonical, which requires that the entire path exists. 52 | */ 53 | path canonical_parent(const path& p, const path& basePath = current_path()); 54 | 55 | } // namespace fs 56 | } // namespace folly 57 | 58 | #endif /* FOLLY_IO_FSUTIL_H_ */ 59 | -------------------------------------------------------------------------------- /folly/futures/ScheduledExecutor.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #pragma once 18 | 19 | #include 20 | #include 21 | #include 22 | #include 23 | 24 | namespace folly { 25 | // An executor that supports timed scheduling. Like RxScheduler. 26 | class ScheduledExecutor : public virtual Executor { 27 | public: 28 | // Reality is that better than millisecond resolution is very hard to 29 | // achieve. However, we reserve the right to be incredible. 30 | typedef std::chrono::microseconds Duration; 31 | typedef std::chrono::steady_clock::time_point TimePoint; 32 | 33 | virtual ~ScheduledExecutor() = default; 34 | 35 | virtual void add(Func) override = 0; 36 | 37 | /// Alias for add() (for Rx consistency) 38 | void schedule(Func&& a) { add(std::move(a)); } 39 | 40 | /// Schedule a Func to be executed after dur time has elapsed 41 | /// Expect millisecond resolution at best. 42 | void schedule(Func&& a, Duration const& dur) { 43 | scheduleAt(std::move(a), now() + dur); 44 | } 45 | 46 | /// Schedule a Func to be executed at time t, or as soon afterward as 47 | /// possible. Expect millisecond resolution at best. Must be threadsafe. 48 | virtual void scheduleAt(Func&& a, TimePoint const& t) { 49 | throw std::logic_error("unimplemented"); 50 | } 51 | 52 | /// Get this executor's notion of time. Must be threadsafe. 53 | virtual TimePoint now() { 54 | return std::chrono::steady_clock::now(); 55 | } 56 | }; 57 | } 58 | -------------------------------------------------------------------------------- /folly/test/MergeTest.cpp: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #include 18 | #include 19 | #include 20 | #include 21 | 22 | TEST(MergeTest, NonOverlapping) { 23 | std::vector a = {0, 2, 4, 6}; 24 | std::vector b = {1, 3, 5, 7}; 25 | std::vector c; 26 | 27 | folly::merge(a.begin(), a.end(), 28 | b.begin(), b.end(), 29 | std::back_inserter(c)); 30 | EXPECT_EQ(8, c.size()); 31 | for (int i = 0; i < 8; ++i) { 32 | EXPECT_EQ(i, c[i]); 33 | } 34 | } 35 | 36 | TEST(MergeTest, OverlappingInSingleInputRange) { 37 | std::vector> a = {{0, 0}, {0, 1}}; 38 | std::vector> b = {{2, 2}, {3, 3}}; 39 | std::map c; 40 | 41 | folly::merge(a.begin(), a.end(), 42 | b.begin(), b.end(), 43 | std::inserter(c, c.begin())); 44 | EXPECT_EQ(3, c.size()); 45 | 46 | // First value is inserted, second is not 47 | EXPECT_EQ(c[0], 0); 48 | 49 | EXPECT_EQ(c[2], 2); 50 | EXPECT_EQ(c[3], 3); 51 | } 52 | 53 | TEST(MergeTest, OverlappingInDifferentInputRange) { 54 | std::vector> a = {{0, 0}, {1, 1}}; 55 | std::vector> b = {{0, 2}, {3, 3}}; 56 | std::map c; 57 | 58 | folly::merge(a.begin(), a.end(), 59 | b.begin(), b.end(), 60 | std::inserter(c, c.begin())); 61 | EXPECT_EQ(3, c.size()); 62 | 63 | // Value from a is inserted, value from b is not. 64 | EXPECT_EQ(c[0], 0); 65 | 66 | EXPECT_EQ(c[1], 1); 67 | EXPECT_EQ(c[3], 3); 68 | } 69 | -------------------------------------------------------------------------------- /folly/CPortability.h: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright 2015 Facebook, Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | #ifndef CPORTABILITY_H 18 | #define CPORTABILITY_H 19 | 20 | /* These definitions are in a separate file so that they 21 | * may be included from C- as well as C++-based projects. */ 22 | 23 | /* Define a convenience macro to test when address sanitizer is being used 24 | * across the different compilers (e.g. clang, gcc) */ 25 | #if defined(__clang__) 26 | # if __has_feature(address_sanitizer) 27 | # define FOLLY_SANITIZE_ADDRESS 1 28 | # endif 29 | #elif defined (__GNUC__) && \ 30 | (((__GNUC__ == 4) && (__GNUC_MINOR__ >= 8)) || (__GNUC__ >= 5)) && \ 31 | __SANITIZE_ADDRESS__ 32 | # define FOLLY_SANITIZE_ADDRESS 1 33 | #endif 34 | 35 | /* Define attribute wrapper for function attribute used to disable 36 | * address sanitizer instrumentation. Unfortunately, this attribute 37 | * has issues when inlining is used, so disable that as well. */ 38 | #ifdef FOLLY_SANITIZE_ADDRESS 39 | # if defined(__clang__) 40 | # if __has_attribute(__no_address_safety_analysis__) 41 | # define FOLLY_DISABLE_ADDRESS_SANITIZER \ 42 | __attribute__((__no_address_safety_analysis__, __noinline__)) 43 | # elif __has_attribute(__no_sanitize_address__) 44 | # define FOLLY_DISABLE_ADDRESS_SANITIZER \ 45 | __attribute__((__no_sanitize_address__, __noinline__)) 46 | # endif 47 | # elif defined(__GNUC__) 48 | # define FOLLY_DISABLE_ADDRESS_SANITIZER \ 49 | __attribute__((__no_address_safety_analysis__, __noinline__)) 50 | # endif 51 | #endif 52 | #ifndef FOLLY_DISABLE_ADDRESS_SANITIZER 53 | # define FOLLY_DISABLE_ADDRESS_SANITIZER 54 | #endif 55 | 56 | #endif 57 | --------------------------------------------------------------------------------