├── .clang-format ├── BUILD ├── third_party ├── syslibs │ ├── BUILD │ ├── README.md │ ├── zlib.BUILD │ ├── snappy.BUILD │ ├── double-conversion.BUILD │ ├── openssl.BUILD │ └── libevent.BUILD ├── fmtlib │ ├── BUILD │ └── fmtlib.BUILD ├── snappy │ ├── BUILD │ └── snappy.BUILD ├── zlib │ ├── BUILD │ └── zlib.BUILD ├── libevent │ ├── BUILD │ ├── README.md │ └── libevent.BUILD └── folly │ ├── BUILD │ ├── p00_double_conversion_include_fix.patch │ ├── CMakeLists.txt.patch │ ├── folly-config.h.sample │ ├── folly-config.without.gflags.h.sample │ └── folly-config.h.cmake ├── tools └── bazelrc ├── .bazelrc ├── test ├── random_test.cc ├── cpu_id_test.cc ├── BUILD ├── random_bm.cc ├── chrono_test.cc ├── fingerprint_test.cc ├── checksum_test.cc └── small_vector_test.cc ├── bazel ├── generate_config_in.sh ├── strip_config_h.sh ├── BUILD ├── README.md ├── folly_deps.bzl └── folly.bzl ├── .gitignore ├── .editorconfig ├── WORKSPACE ├── README.md └── LICENSE /.clang-format: -------------------------------------------------------------------------------- 1 | BasedOnStyle: Google 2 | -------------------------------------------------------------------------------- /BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | -------------------------------------------------------------------------------- /third_party/syslibs/BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | -------------------------------------------------------------------------------- /tools/bazelrc: -------------------------------------------------------------------------------- 1 | build --cxxopt="-std=c++1z" 2 | build --host_cxxopt="-std=c++1z" 3 | -------------------------------------------------------------------------------- /.bazelrc: -------------------------------------------------------------------------------- 1 | try-import %workspace%/tools/bazelrc 2 | try-import %workspace%/user.bazelrc 3 | -------------------------------------------------------------------------------- /third_party/fmtlib/BUILD: -------------------------------------------------------------------------------- 1 | package( 2 | default_visibility = ["//visibility:public"], 3 | ) 4 | -------------------------------------------------------------------------------- /third_party/snappy/BUILD: -------------------------------------------------------------------------------- 1 | package( 2 | default_visibility = ["//visibility:public"], 3 | ) 4 | 5 | exports_files([ 6 | "snappy.BUILD", 7 | ]) 8 | -------------------------------------------------------------------------------- /third_party/zlib/BUILD: -------------------------------------------------------------------------------- 1 | package( 2 | default_visibility = ["//visibility:public"], 3 | ) 4 | 5 | exports_files([ 6 | "zlib.BUILD", 7 | ]) 8 | -------------------------------------------------------------------------------- /third_party/libevent/BUILD: -------------------------------------------------------------------------------- 1 | package( 2 | default_visibility = ["//visibility:public"], 3 | ) 4 | 5 | exports_files([ 6 | "libevent.BUILD", 7 | ]) 8 | -------------------------------------------------------------------------------- /third_party/syslibs/README.md: -------------------------------------------------------------------------------- 1 | # Bazel Build Rules for OpenSSL 2 | 3 | Copied from [TensorFlow](https://github.com/tensorflow/tensorflow/blob/master/third_party/systemlibs/boringssl.BUILD) 4 | 5 | 6 | -------------------------------------------------------------------------------- /third_party/folly/BUILD: -------------------------------------------------------------------------------- 1 | package( 2 | default_visibility = ["//visibility:public"], 3 | ) 4 | 5 | exports_files([ 6 | "folly-config.h", 7 | "p00_double_conversion_include_fix.patch", 8 | ]) 9 | -------------------------------------------------------------------------------- /third_party/syslibs/zlib.BUILD: -------------------------------------------------------------------------------- 1 | load("@rules_cc//cc:defs.bzl", "cc_library") 2 | 3 | licenses(["notice"]) 4 | 5 | cc_library( 6 | name = "zlib", 7 | linkopts = ["-lz"], 8 | visibility = ["//visibility:public"], 9 | ) 10 | -------------------------------------------------------------------------------- /third_party/syslibs/snappy.BUILD: -------------------------------------------------------------------------------- 1 | load("@rules_cc//cc:defs.bzl", "cc_library") 2 | 3 | licenses(["notice"]) 4 | 5 | cc_library( 6 | name = "snappy", 7 | linkopts = ["-lsnappy"], 8 | visibility = ["//visibility:public"], 9 | ) 10 | -------------------------------------------------------------------------------- /test/random_test.cc: -------------------------------------------------------------------------------- 1 | #include "folly/Random.h" 2 | 3 | #include "gtest/gtest.h" 4 | 5 | TEST(RandomTest, TestFollyRand32) { 6 | uint32_t kMaxNum = 5; 7 | uint32_t val = folly::Random::secureRand32(kMaxNum); 8 | EXPECT_GT(kMaxNum, val); 9 | } 10 | -------------------------------------------------------------------------------- /third_party/syslibs/double-conversion.BUILD: -------------------------------------------------------------------------------- 1 | load("@rules_cc//cc:defs.bzl", "cc_library") 2 | 3 | licenses(["notice"]) 4 | 5 | cc_library( 6 | name = "double-conversion", 7 | linkopts = ["-ldouble-conversion"], 8 | visibility = ["//visibility:public"], 9 | ) 10 | -------------------------------------------------------------------------------- /bazel/generate_config_in.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | while read -r line; do 3 | if [[ "${line}" =~ ^#cmakedefine ]]; then 4 | read -r -a elems <<< "${line}" 5 | printf "#cmakedefine %-40s %-42s\n" "${elems[1]}" "@${elems[1]}@" 6 | else 7 | echo "${line}" 8 | fi 9 | done 10 | -------------------------------------------------------------------------------- /third_party/libevent/README.md: -------------------------------------------------------------------------------- 1 | # Bazel Build Rules for libevent 2 | 3 | Tailored from https://github.com/tensorflow/serving.git:third_party/libevent/BUILD 4 | 5 | ## References: 6 | - https://github.com/3rdparty/bazel-rules-libevent/blob/main/BUILD.bazel 7 | - https://github.com/alibaba/sentinel-cpp/blob/master/bazel/third_party_repositories.bzl 8 | 9 | -------------------------------------------------------------------------------- /bazel/strip_config_h.sh: -------------------------------------------------------------------------------- 1 | #! /bin/bash 2 | while read -r line; do 3 | if [[ "${line}" =~ ^#cmakedefine ]]; then 4 | read -r -a elems <<< "${line}" 5 | val="${elems[2]}" 6 | if [[ "${val}" == "0" || "${val}" =~ ^@ ]]; then 7 | printf "//#undef %-40s\n" "${elems[1]}" 8 | else 9 | printf "#define %-40s %-20s\n" "${elems[1]}" "${val}" 10 | fi 11 | else 12 | echo "${line}" 13 | fi 14 | done 15 | -------------------------------------------------------------------------------- /third_party/fmtlib/fmtlib.BUILD: -------------------------------------------------------------------------------- 1 | load("@rules_cc//cc:defs.bzl", "cc_library") 2 | 3 | # NOTE(jiaming): Adapted from 4 | # https://github.com/pytorch/pytorch/blob/v1.9.0/third_party/fmt.BUILD 5 | 6 | licenses(["notice"]) # Apache 2 7 | 8 | cc_library( 9 | name = "fmt", 10 | hdrs = glob(["include/fmt/*.h",]), 11 | defines = ["FMT_HEADER_ONLY=1"], 12 | includes = ["include"], 13 | visibility = ["//visibility:public"], 14 | ) 15 | 16 | -------------------------------------------------------------------------------- /third_party/syslibs/openssl.BUILD: -------------------------------------------------------------------------------- 1 | licenses(["notice"]) 2 | 3 | filegroup( 4 | name = "LICENSE", 5 | visibility = ["//visibility:public"], 6 | ) 7 | 8 | cc_library( 9 | name = "crypto", 10 | linkopts = ["-lcrypto"], 11 | visibility = ["//visibility:public"], 12 | ) 13 | 14 | cc_library( 15 | name = "ssl", 16 | linkopts = ["-lssl"], 17 | visibility = ["//visibility:public"], 18 | deps = [ 19 | ":crypto", 20 | ], 21 | ) 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Bazel artifacts 2 | bazel-* 3 | user.bazelrc 4 | 5 | # Prerequisites 6 | *.d 7 | 8 | # Compiled Object files 9 | *.slo 10 | *.lo 11 | *.o 12 | *.obj 13 | 14 | # Precompiled Headers 15 | *.gch 16 | *.pch 17 | 18 | # Compiled Dynamic libraries 19 | *.so 20 | *.dylib 21 | *.dll 22 | 23 | # Fortran module files 24 | *.mod 25 | *.smod 26 | 27 | # Compiled Static libraries 28 | *.lai 29 | *.la 30 | *.a 31 | *.lib 32 | 33 | # Executables 34 | *.exe 35 | *.out 36 | *.app 37 | -------------------------------------------------------------------------------- /third_party/syslibs/libevent.BUILD: -------------------------------------------------------------------------------- 1 | load("@rules_cc//cc:defs.bzl", "cc_library") 2 | 3 | licenses(["notice"]) 4 | 5 | cc_library( 6 | name = "libevent", 7 | linkopts = [ 8 | "-levent", 9 | ], 10 | visibility = ["//visibility:public"], 11 | ) 12 | 13 | cc_library( 14 | name = "libevent_openssl", 15 | linkopts = [ 16 | "-levent_openssl", 17 | ], 18 | visibility = ["//visibility:public"], 19 | deps = [ 20 | "@openssl//:crypto", 21 | ], 22 | ) 23 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | # like -i=2 7 | indent_style = space 8 | indent_size = 2 9 | insert_final_newline = true 10 | trim_trailing_whitespace = true 11 | 12 | [*.{sh,bash,bashrc}] 13 | shell_variant = bash # like -ln=bash 14 | binary_next_line = true # like -bn 15 | switch_case_indent = true # like -ci 16 | space_redirects = true # like -sr 17 | 18 | # in case third party libraries need a Makefile. 19 | [Makefile] 20 | indent_style = tab 21 | -------------------------------------------------------------------------------- /bazel/BUILD: -------------------------------------------------------------------------------- 1 | package( 2 | default_visibility = ["//visibility:public"], 3 | ) 4 | 5 | exports_files([ 6 | "generate_config_in.sh", 7 | "strip_config_h.sh", 8 | ]) 9 | 10 | config_setting( 11 | name = "linux_aarch64", 12 | constraint_values = [ 13 | "@bazel_tools//platforms:linux", 14 | "@bazel_tools//platforms:aarch64", 15 | ], 16 | ) 17 | 18 | config_setting( 19 | name = "linux_x86_64", 20 | constraint_values = [ 21 | "@bazel_tools//platforms:linux", 22 | "@bazel_tools//platforms:x86_64", 23 | ], 24 | ) 25 | -------------------------------------------------------------------------------- /WORKSPACE: -------------------------------------------------------------------------------- 1 | workspace(name = "com_github_storypku_rules_folly") 2 | 3 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") 4 | load("//bazel:folly_deps.bzl", "folly_deps") 5 | 6 | folly_deps(with_gflags = 1) 7 | 8 | load("@com_github_nelhage_rules_boost//:boost/boost.bzl", "boost_deps") 9 | 10 | boost_deps() 11 | 12 | http_archive( 13 | name = "com_google_googletest", 14 | sha256 = "b4870bf121ff7795ba20d20bcdd8627b8e088f2d1dab299a031c1034eddc93d5", 15 | strip_prefix = "googletest-release-1.11.0", 16 | urls = [ 17 | "https://github.com/google/googletest/archive/release-1.11.0.tar.gz", 18 | ], 19 | ) 20 | -------------------------------------------------------------------------------- /third_party/folly/p00_double_conversion_include_fix.patch: -------------------------------------------------------------------------------- 1 | diff --git a/folly/Conv.h b/folly/Conv.h 2 | index 0157a6c..ce7a259 100644 3 | --- a/folly/Conv.h 4 | +++ b/folly/Conv.h 5 | @@ -111,7 +111,7 @@ 6 | #include 7 | #include 8 | 9 | -#include // V8 JavaScript implementation 10 | +#include "double-conversion/double-conversion.h" // V8 JavaScript implementation 11 | 12 | #include 13 | #include 14 | diff --git a/folly/Format.cpp b/folly/Format.cpp 15 | index b85dacf..ec1b515 100644 16 | --- a/folly/Format.cpp 17 | +++ b/folly/Format.cpp 18 | @@ -22,7 +22,7 @@ 19 | #include 20 | #include 21 | 22 | -#include 23 | +#include "double-conversion/double-conversion.h" 24 | 25 | namespace folly { 26 | namespace detail { 27 | -------------------------------------------------------------------------------- /test/cpu_id_test.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Facebook, Inc. and its affiliates. 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 "folly/CpuId.h" 18 | #include "gtest/gtest.h" 19 | 20 | using namespace folly; 21 | 22 | TEST(CpuId, Simple) { 23 | CpuId id; 24 | // All x64 CPUs should support MMX 25 | EXPECT_EQ(kIsArchAmd64, id.mmx()); 26 | } 27 | -------------------------------------------------------------------------------- /third_party/folly/CMakeLists.txt.patch: -------------------------------------------------------------------------------- 1 | diff --git a/CMakeLists.txt b/CMakeLists.txt 2 | index f4d6b7d..a42a058 100644 3 | --- a/CMakeLists.txt 4 | +++ b/CMakeLists.txt 5 | @@ -65,6 +65,14 @@ option(BUILD_SHARED_LIBS 6 | a stable ABI." 7 | OFF 8 | ) 9 | + 10 | +set(CMAKE_VERBOSE_MAKEFILE ON) 11 | + 12 | +if (BUILD_SHARED_LIBS) 13 | + set(CMAKE_POSITION_INDEPENDENT_CODE ON) 14 | + # add_compile_options(-fPIC) 15 | +endif(BUILD_SHARED_LIBS) 16 | + 17 | # Mark BUILD_SHARED_LIBS as an "advanced" option, since enabling it 18 | # is generally discouraged. 19 | mark_as_advanced(BUILD_SHARED_LIBS) 20 | @@ -282,6 +270,19 @@ else() 21 | ${FOLLY_DIR}/experimental/crypto/LtHash.h 22 | ) 23 | endif() 24 | + 25 | +message(STATUS "=================HEADERS Start ==================") 26 | +foreach(my_hdr IN LISTS hfiles) 27 | + message(STATUS "${my_hdr}") 28 | +endforeach() 29 | +message(STATUS "==============HEADERS End=================") 30 | + 31 | +message(STATUS "=================SRCS Start ==================") 32 | +foreach(my_src IN LISTS files) 33 | + message(STATUS "${my_src}") 34 | +endforeach() 35 | +message(STATUS "==============SRCS End=================") 36 | + 37 | if (NOT ${LIBGFLAGS_FOUND}) 38 | list(REMOVE_ITEM files 39 | ${FOLLY_DIR}/experimental/NestedCommandLineApp.cpp 40 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # `rules_folly` -- Bazel Build Rules for Folly 2 | 3 | ## Pre-requisites 4 | 5 | On Ubuntu, 6 | 7 | ```bash 8 | sudo apt-get update \ 9 | && sudo apt-get -y install --no-install-recommends \ 10 | autoconf \ 11 | automake \ 12 | libtool \ 13 | libssl-dev 14 | ``` 15 | 16 | ## How To Use 17 | 18 | 1. In your `WORKSPACE` file, add the following: 19 | 20 | ``` 21 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") 22 | 23 | http_archive( 24 | name = "com_github_storypku_rules_folly", 25 | sha256 = "16441df2d454a6d7ef4da38d4e5fada9913d1f9a3b2015b9fe792081082d2a65", 26 | strip_prefix = "rules_folly-0.2.0", 27 | urls = [ 28 | "https://github.com/storypku/rules_folly/archive/v0.2.0.tar.gz", 29 | ], 30 | ) 31 | 32 | load("@com_github_storypku_rules_folly//bazel:folly_deps.bzl", "folly_deps") 33 | folly_deps() 34 | 35 | load("@com_github_nelhage_rules_boost//:boost/boost.bzl", "boost_deps") 36 | boost_deps() 37 | ``` 38 | 39 | If you would like to use Folly without gflags, you should change the line 40 | `folly_deps()` to: 41 | 42 | ``` 43 | folly_deps(with_gflags = 0) 44 | ``` 45 | 46 | 2. Then you can add Folly in the `deps` section of target rule in the `BUILD` file: 47 | 48 | ``` 49 | deps = [ 50 | # ... 51 | "@folly//:folly", 52 | # ... 53 | ], 54 | ``` 55 | 56 | ## ROADMAP 57 | 1. (Done) Make it work for recent versions of Folly 58 | 2. (Done) Make rules_folly configurable, e.g., whether openssl/boringssl should be used, 59 | if glog was with gflags support, etc. 60 | -------------------------------------------------------------------------------- /test/BUILD: -------------------------------------------------------------------------------- 1 | load("@rules_cc//cc:defs.bzl", "cc_test") 2 | 3 | package( 4 | default_visibility = ["//visibility:public"], 5 | ) 6 | 7 | cc_test( 8 | name = "chrono_test", 9 | size = "small", 10 | srcs = ["chrono_test.cc"], 11 | deps = [ 12 | "@com_google_googletest//:gtest_main", 13 | "@folly", 14 | ], 15 | ) 16 | 17 | cc_test( 18 | name = "cpu_id_test", 19 | size = "small", 20 | srcs = ["cpu_id_test.cc"], 21 | deps = [ 22 | "@com_google_googletest//:gtest_main", 23 | "@folly", 24 | ], 25 | ) 26 | 27 | cc_test( 28 | name = "fingerprint_test", 29 | size = "small", 30 | srcs = ["fingerprint_test.cc"], 31 | deps = [ 32 | "@com_github_google_glog//:glog", 33 | "@com_google_googletest//:gtest_main", 34 | "@folly", 35 | ], 36 | ) 37 | 38 | cc_test( 39 | name = "checksum_test", 40 | size = "small", 41 | srcs = ["checksum_test.cc"], 42 | deps = [ 43 | "@boost//:crc", 44 | "@com_github_google_glog//:glog", 45 | "@com_google_googletest//:gtest_main", 46 | "@folly", 47 | ], 48 | ) 49 | 50 | cc_test( 51 | name = "random_test", 52 | size = "small", 53 | srcs = ["random_test.cc"], 54 | deps = [ 55 | "@com_google_googletest//:gtest_main", 56 | "@folly", 57 | ], 58 | ) 59 | 60 | # Enable this if enable_testing is True 61 | # cc_test( 62 | # name = "small_vector_test", 63 | # size = "small", 64 | # srcs = ["small_vector_test.cc"], 65 | # deps = [ 66 | # "@com_google_googletest//:gtest_main", 67 | # "@folly//:folly_test_support", 68 | # ], 69 | # ) 70 | cc_test( 71 | name = "random_bm", 72 | size = "small", 73 | srcs = ["random_bm.cc"], 74 | deps = [ 75 | "@folly//:follybenchmark", 76 | ], 77 | ) 78 | -------------------------------------------------------------------------------- /third_party/zlib/zlib.BUILD: -------------------------------------------------------------------------------- 1 | # Copied from https://github.com/protocolbuffers/protobuf/blob/3.17.x/third_party/zlib.BUILD 2 | load("@rules_cc//cc:defs.bzl", "cc_library") 3 | 4 | licenses(["notice"]) # BSD/MIT-like license (for zlib) 5 | 6 | _ZLIB_HEADERS = [ 7 | "crc32.h", 8 | "deflate.h", 9 | "gzguts.h", 10 | "inffast.h", 11 | "inffixed.h", 12 | "inflate.h", 13 | "inftrees.h", 14 | "trees.h", 15 | "zconf.h", 16 | "zlib.h", 17 | "zutil.h", 18 | ] 19 | 20 | _ZLIB_PREFIXED_HEADERS = ["zlib/include/" + hdr for hdr in _ZLIB_HEADERS] 21 | 22 | # In order to limit the damage from the `includes` propagation 23 | # via `:zlib`, copy the public headers to a subdirectory and 24 | # expose those. 25 | genrule( 26 | name = "copy_public_headers", 27 | srcs = _ZLIB_HEADERS, 28 | outs = _ZLIB_PREFIXED_HEADERS, 29 | cmd = "cp $(SRCS) $(@D)/zlib/include/", 30 | ) 31 | 32 | cc_library( 33 | name = "zlib", 34 | srcs = [ 35 | "adler32.c", 36 | "compress.c", 37 | "crc32.c", 38 | "deflate.c", 39 | "gzclose.c", 40 | "gzlib.c", 41 | "gzread.c", 42 | "gzwrite.c", 43 | "infback.c", 44 | "inffast.c", 45 | "inflate.c", 46 | "inftrees.c", 47 | "trees.c", 48 | "uncompr.c", 49 | "zutil.c", 50 | # Include the un-prefixed headers in srcs to work 51 | # around the fact that zlib isn't consistent in its 52 | # choice of <> or "" delimiter when including itself. 53 | ] + _ZLIB_HEADERS, 54 | hdrs = _ZLIB_PREFIXED_HEADERS, 55 | copts = select({ 56 | "@bazel_tools//src/conditions:windows": [], 57 | "//conditions:default": [ 58 | "-Wno-unused-variable", 59 | "-Wno-implicit-function-declaration", 60 | ], 61 | }), 62 | includes = ["zlib/include/"], 63 | visibility = ["//visibility:public"], 64 | ) 65 | -------------------------------------------------------------------------------- /test/random_bm.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Facebook, Inc. and its affiliates. 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 | // NOTE(storypku): Adapted from 17 | // https://github.com/facebook/folly/blob/v2021.09.06.00/folly/test/RandomBenchmark.cpp 18 | 19 | #include 20 | #include 21 | 22 | #include "folly/Benchmark.h" 23 | #include "folly/Random.h" 24 | #include "folly/container/Foreach.h" 25 | #include "glog/logging.h" 26 | 27 | #if FOLLY_HAVE_EXTRANDOM_SFMT19937 28 | #include 29 | #endif 30 | 31 | using namespace folly; 32 | 33 | BENCHMARK(minstdrand, n) { 34 | BenchmarkSuspender braces; 35 | std::random_device rd; 36 | std::minstd_rand rng(rd()); 37 | 38 | braces.dismiss(); 39 | 40 | FOR_EACH_RANGE(i, 0, n) { doNotOptimizeAway(rng()); } 41 | } 42 | 43 | BENCHMARK(mt19937, n) { 44 | BenchmarkSuspender braces; 45 | std::random_device rd; 46 | std::mt19937 rng(rd()); 47 | 48 | braces.dismiss(); 49 | 50 | FOR_EACH_RANGE(i, 0, n) { doNotOptimizeAway(rng()); } 51 | } 52 | 53 | #if FOLLY_HAVE_EXTRANDOM_SFMT19937 54 | BENCHMARK(sfmt19937, n) { 55 | BenchmarkSuspender braces; 56 | std::random_device rd; 57 | __gnu_cxx::sfmt19937 rng(rd()); 58 | 59 | braces.dismiss(); 60 | 61 | FOR_EACH_RANGE(i, 0, n) { doNotOptimizeAway(rng()); } 62 | } 63 | #endif 64 | 65 | BENCHMARK(threadprng, n) { 66 | BenchmarkSuspender braces; 67 | ThreadLocalPRNG tprng; 68 | tprng(); 69 | 70 | braces.dismiss(); 71 | 72 | FOR_EACH_RANGE(i, 0, n) { doNotOptimizeAway(tprng()); } 73 | } 74 | 75 | BENCHMARK(RandomDouble) { doNotOptimizeAway(Random::randDouble01()); } 76 | BENCHMARK(Random32) { doNotOptimizeAway(Random::rand32()); } 77 | BENCHMARK(Random32Num) { doNotOptimizeAway(Random::rand32(100)); } 78 | BENCHMARK(Random64) { doNotOptimizeAway(Random::rand64()); } 79 | BENCHMARK(Random64Num) { doNotOptimizeAway(Random::rand64(100ull << 32)); } 80 | BENCHMARK(Random64OneIn) { doNotOptimizeAway(Random::oneIn(100)); } 81 | 82 | int main(int argc, char** argv) { 83 | folly::runBenchmarks(); 84 | return 0; 85 | } 86 | -------------------------------------------------------------------------------- /bazel/README.md: -------------------------------------------------------------------------------- 1 | # Optional Packages 2 | 3 | ## Disabled Dependencies 4 | 5 | - LIBZ zlib1g-dev Enabled 6 | - BZip2 libbz2-dev Disabled 7 | - LibLZMA liblzma-dev Disabled 8 | - LZ4 liblz4-dev Disabled 9 | - ZSTD libzstd-dev Disabled 10 | - LIBDWARF libdwarf-dev Disabled 11 | - LIBUNWIND libunwind-dev Disabled 12 | - LIBIBERTY libiberty-dev Disabled 13 | - LIBAIO libaio-dev Disabled 14 | - LIBURING N/A Disabled 15 | - LIBSODIUM libsodium-dev Disabled 16 | 17 | ## Steps 18 | 19 | 1. Manage Folly tarball as git repository 20 | 2. Added the following section in `CMakeLists.txt` 21 | 22 | ``` 23 | set(CMAKE_VERBOSE_MAKEFILE ON) 24 | 25 | if (BUILD_SHARED_LIBS) 26 | # set(CMAKE_POSITION_INDEPENDENT_CODE ON) 27 | add_compile_options("-fPIC") 28 | endif (BUILD_SHARED_LIBS) 29 | ``` 30 | 31 | 3. Run the following: 32 | ``` 33 | sudo apt autoremove \ 34 | libiberty-dev \ 35 | libbz2-dev \ 36 | liblz4-dev \ 37 | liblzma-dev \ 38 | libzstd-dev \ 39 | libjemalloc-dev \ 40 | libunwind-dev 41 | libdwarf-dev \ 42 | libsodium-dev \ 43 | libaio-dev 44 | cd build 45 | cmake .. -DBUILD_SHARED_LIBS=ON -Wno-dev 46 | ``` 47 | 48 | Output: 49 | 50 | ``` 51 | -- Found gflags from package config /usr/lib/x86_64-linux-gnu/cmake/gflags/gflags-config.cmake 52 | -- Found libevent: /usr/lib/x86_64-linux-gnu/libevent.so 53 | -- Could NOT find BZip2 (missing: BZIP2_LIBRARIES BZIP2_INCLUDE_DIR) 54 | -- Could NOT find LibLZMA (missing: LIBLZMA_LIBRARY LIBLZMA_INCLUDE_DIR LIBLZMA_HAS_AUTO_DECODER LIBLZMA_HAS_EASY_ENCODER LIBLZMA_HAS_LZMA_PRESET) 55 | -- Could NOT find LZ4 (missing: LZ4_LIBRARY LZ4_INCLUDE_DIR) 56 | -- Could NOT find ZSTD (missing: ZSTD_LIBRARY ZSTD_INCLUDE_DIR) 57 | -- Could NOT find LIBDWARF (missing: LIBDWARF_LIBRARY LIBDWARF_INCLUDE_DIR) 58 | -- Could NOT find LIBIBERTY (missing: LIBIBERTY_LIBRARY LIBIBERTY_INCLUDE_DIR) 59 | -- Could NOT find LIBAIO (missing: LIBAIO_LIBRARY LIBAIO_INCLUDE_DIR) 60 | -- Could NOT find LIBURING (missing: LIBURING_LIBRARY LIBURING_INCLUDE_DIR) 61 | -- Could NOT find LIBSODIUM (missing: LIBSODIUM_LIBRARY LIBSODIUM_INCLUDE_DIR) 62 | -- Could NOT find LIBUNWIND (missing: LIBUNWIND_LIBRARY LIBUNWIND_INCLUDE_DIR) 63 | -- Setting FOLLY_USE_SYMBOLIZER: ON 64 | -- Setting FOLLY_HAVE_ELF: 1 65 | -- Setting FOLLY_HAVE_DWARF: FALSE 66 | -- compiler has flag pclmul, setting compile flag for /work/github/folly-2021.08.23.00/folly/hash/detail/ChecksumDetail.cpp;/work/github/folly-2021.08.23.00/folly/hash/detail/Crc32CombineDetail.cpp;/work/github/folly-2021.08.23.00/folly/hash/detail/Crc32cDetail.cpp 67 | -- Configuring done 68 | -- Generating done 69 | -- Build files have been written to: /work/github/folly-2021.08.23.00/build 70 | ``` 71 | -------------------------------------------------------------------------------- /third_party/folly/folly-config.h.sample: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Facebook, Inc. and its affiliates. 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 | #if !defined(FOLLY_MOBILE) 20 | #if defined(__ANDROID__) || \ 21 | (defined(__APPLE__) && \ 22 | (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE)) 23 | #define FOLLY_MOBILE 1 24 | #else 25 | #define FOLLY_MOBILE 0 26 | #endif 27 | #endif // FOLLY_MOBILE 28 | 29 | #define FOLLY_HAVE_PTHREAD 1 30 | #define FOLLY_HAVE_PTHREAD_ATFORK 1 31 | 32 | #define FOLLY_HAVE_LIBGFLAGS 1 33 | /* #undef FOLLY_UNUSUAL_GFLAGS_NAMESPACE */ 34 | #define FOLLY_GFLAGS_NAMESPACE gflags 35 | 36 | #define FOLLY_HAVE_LIBGLOG 1 37 | 38 | /* #undef FOLLY_USE_JEMALLOC */ 39 | #define FOLLY_USE_LIBSTDCPP 1 40 | 41 | #if __has_include() 42 | #include 43 | #endif 44 | 45 | #define FOLLY_HAVE_ACCEPT4 1 46 | #define FOLLY_HAVE_GETRANDOM 1 47 | #define FOLLY_HAVE_PREADV 1 48 | #define FOLLY_HAVE_PWRITEV 1 49 | #define FOLLY_HAVE_CLOCK_GETTIME 1 50 | #define FOLLY_HAVE_PIPE2 1 51 | #define FOLLY_HAVE_SENDMMSG 1 52 | #define FOLLY_HAVE_RECVMMSG 1 53 | #define FOLLY_HAVE_OPENSSL_ASN1_TIME_DIFF 1 54 | 55 | #define FOLLY_HAVE_IFUNC 1 56 | #define FOLLY_HAVE_STD__IS_TRIVIALLY_COPYABLE 1 57 | #define FOLLY_HAVE_UNALIGNED_ACCESS 1 58 | #define FOLLY_HAVE_VLA 1 59 | #define FOLLY_HAVE_WEAK_SYMBOLS 1 60 | #define FOLLY_HAVE_LINUX_VDSO 1 61 | #define FOLLY_HAVE_MALLOC_USABLE_SIZE 1 62 | /* #undef FOLLY_HAVE_INT128_T */ 63 | #define FOLLY_HAVE_WCHAR_SUPPORT 1 64 | #define FOLLY_HAVE_EXTRANDOM_SFMT19937 1 65 | /* #undef FOLLY_USE_LIBCPP */ 66 | #define HAVE_VSNPRINTF_ERRORS 1 67 | 68 | /* #undef FOLLY_HAVE_LIBUNWIND */ 69 | /* #undef FOLLY_HAVE_DWARF */ 70 | #define FOLLY_HAVE_ELF 1 71 | #define FOLLY_HAVE_SWAPCONTEXT 1 72 | #define FOLLY_HAVE_BACKTRACE 1 73 | #define FOLLY_USE_SYMBOLIZER 1 74 | #define FOLLY_DEMANGLE_MAX_SYMBOL_SIZE 1024 75 | 76 | #define FOLLY_HAVE_SHADOW_LOCAL_WARNINGS 1 77 | 78 | /* #undef FOLLY_HAVE_LIBLZ4 */ 79 | /* #undef FOLLY_HAVE_LIBLZMA */ 80 | #define FOLLY_HAVE_LIBSNAPPY 1 81 | #define FOLLY_HAVE_LIBZ 1 82 | /* #undef FOLLY_HAVE_LIBZSTD */ 83 | /* #undef FOLLY_HAVE_LIBBZ2 */ 84 | 85 | #define FOLLY_LIBRARY_SANITIZE_ADDRESS 0 86 | 87 | #define FOLLY_SUPPORT_SHARED_LIBRARY 1 88 | 89 | #define FOLLY_HAVE_LIBRT 0 90 | -------------------------------------------------------------------------------- /third_party/folly/folly-config.without.gflags.h.sample: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Facebook, Inc. and its affiliates. 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 | #if !defined(FOLLY_MOBILE) 20 | #if defined(__ANDROID__) || \ 21 | (defined(__APPLE__) && \ 22 | (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE)) 23 | #define FOLLY_MOBILE 1 24 | #else 25 | #define FOLLY_MOBILE 0 26 | #endif 27 | #endif // FOLLY_MOBILE 28 | 29 | #define FOLLY_HAVE_PTHREAD 1 30 | #define FOLLY_HAVE_PTHREAD_ATFORK 1 31 | 32 | /* #undef FOLLY_HAVE_LIBGFLAGS */ 33 | /* #undef FOLLY_UNUSUAL_GFLAGS_NAMESPACE */ 34 | /* #undef FOLLY_GFLAGS_NAMESPACE */ 35 | 36 | #define FOLLY_HAVE_LIBGLOG 1 37 | 38 | /* #undef FOLLY_USE_JEMALLOC */ 39 | #define FOLLY_USE_LIBSTDCPP 1 40 | 41 | #if __has_include() 42 | #include 43 | #endif 44 | 45 | #define FOLLY_HAVE_ACCEPT4 1 46 | #define FOLLY_HAVE_GETRANDOM 1 47 | #define FOLLY_HAVE_PREADV 1 48 | #define FOLLY_HAVE_PWRITEV 1 49 | #define FOLLY_HAVE_CLOCK_GETTIME 1 50 | #define FOLLY_HAVE_PIPE2 1 51 | #define FOLLY_HAVE_SENDMMSG 1 52 | #define FOLLY_HAVE_RECVMMSG 1 53 | #define FOLLY_HAVE_OPENSSL_ASN1_TIME_DIFF 1 54 | 55 | #define FOLLY_HAVE_IFUNC 1 56 | #define FOLLY_HAVE_STD__IS_TRIVIALLY_COPYABLE 1 57 | #define FOLLY_HAVE_UNALIGNED_ACCESS 1 58 | #define FOLLY_HAVE_VLA 1 59 | #define FOLLY_HAVE_WEAK_SYMBOLS 1 60 | #define FOLLY_HAVE_LINUX_VDSO 1 61 | #define FOLLY_HAVE_MALLOC_USABLE_SIZE 1 62 | /* #undef FOLLY_HAVE_INT128_T */ 63 | #define FOLLY_HAVE_WCHAR_SUPPORT 1 64 | #define FOLLY_HAVE_EXTRANDOM_SFMT19937 1 65 | /* #undef FOLLY_USE_LIBCPP */ 66 | #define HAVE_VSNPRINTF_ERRORS 1 67 | 68 | #define FOLLY_HAVE_LIBUNWIND 1 69 | /* #undef FOLLY_HAVE_DWARF */ 70 | #define FOLLY_HAVE_ELF 1 71 | #define FOLLY_HAVE_SWAPCONTEXT 1 72 | #define FOLLY_HAVE_BACKTRACE 1 73 | #define FOLLY_USE_SYMBOLIZER 1 74 | #define FOLLY_DEMANGLE_MAX_SYMBOL_SIZE 1024 75 | 76 | #define FOLLY_HAVE_SHADOW_LOCAL_WARNINGS 1 77 | 78 | /* #undef FOLLY_HAVE_LIBLZ4 */ 79 | #define FOLLY_HAVE_LIBLZMA 1 80 | /* #undef FOLLY_HAVE_LIBSNAPPY */ 81 | #define FOLLY_HAVE_LIBZ 1 82 | /* #undef FOLLY_HAVE_LIBZSTD */ 83 | /* #undef FOLLY_HAVE_LIBBZ2 */ 84 | 85 | #define FOLLY_LIBRARY_SANITIZE_ADDRESS 0 86 | 87 | #define FOLLY_SUPPORT_SHARED_LIBRARY 1 88 | 89 | #define FOLLY_HAVE_LIBRT 0 90 | -------------------------------------------------------------------------------- /third_party/libevent/libevent.BUILD: -------------------------------------------------------------------------------- 1 | # libevent (libevent.org) library. 2 | # from https://github.com/libevent/libevent 3 | package( 4 | default_visibility = ["//visibility:public"], 5 | ) 6 | 7 | licenses(["notice"]) # BSD 8 | 9 | exports_files(["LICENSE"]) 10 | 11 | include_files = [ 12 | "libevent/include/evdns.h", 13 | "libevent/include/event.h", 14 | "libevent/include/evhttp.h", 15 | "libevent/include/evrpc.h", 16 | "libevent/include/evutil.h", 17 | "libevent/include/event2/buffer.h", 18 | "libevent/include/event2/bufferevent_struct.h", 19 | "libevent/include/event2/event.h", 20 | "libevent/include/event2/http_struct.h", 21 | "libevent/include/event2/rpc_struct.h", 22 | "libevent/include/event2/buffer_compat.h", 23 | "libevent/include/event2/dns.h", 24 | "libevent/include/event2/event_compat.h", 25 | "libevent/include/event2/keyvalq_struct.h", 26 | "libevent/include/event2/tag.h", 27 | "libevent/include/event2/bufferevent.h", 28 | "libevent/include/event2/dns_compat.h", 29 | "libevent/include/event2/event_struct.h", 30 | "libevent/include/event2/listener.h", 31 | "libevent/include/event2/tag_compat.h", 32 | "libevent/include/event2/bufferevent_compat.h", 33 | "libevent/include/event2/dns_struct.h", 34 | "libevent/include/event2/http.h", 35 | "libevent/include/event2/rpc.h", 36 | "libevent/include/event2/thread.h", 37 | "libevent/include/event2/event-config.h", 38 | "libevent/include/event2/http_compat.h", 39 | "libevent/include/event2/rpc_compat.h", 40 | "libevent/include/event2/util.h", 41 | "libevent/include/event2/visibility.h", 42 | ] 43 | 44 | lib_files = [ 45 | "libevent/lib/libevent.a", 46 | "libevent/lib/libevent_core.a", 47 | "libevent/lib/libevent_extra.a", 48 | "libevent/lib/libevent_pthreads.a", 49 | ] 50 | 51 | genrule( 52 | name = "libevent-srcs", 53 | srcs = glob(["**/*"]), 54 | outs = include_files + lib_files, 55 | cmd = "\n".join([ 56 | "export INSTALL_DIR=$$(pwd)/$(@D)/libevent", 57 | "export TMP_DIR=$$(mktemp -d -t libevent.XXXXXX)", 58 | "mkdir -p $$TMP_DIR", 59 | "cp -R $$(pwd)/external/com_github_libevent_libevent/* $$TMP_DIR", 60 | "cd $$TMP_DIR", 61 | "./autogen.sh >/dev/null", 62 | "./configure --prefix=$$INSTALL_DIR CFLAGS=-fPIC CXXFLAGS=-fPIC --enable-shared=no --disable-openssl >/dev/null", 63 | "make -j$$(nproc) install >/dev/null", 64 | "rm -rf $$TMP_DIR", 65 | ]), 66 | ) 67 | 68 | cc_library( 69 | name = "libevent", 70 | srcs = [ 71 | "libevent/lib/libevent.a", 72 | "libevent/lib/libevent_pthreads.a", 73 | ], 74 | hdrs = include_files, 75 | includes = ["libevent/include"], 76 | linkopts = ["-lpthread"], 77 | linkstatic = 1, 78 | ) 79 | 80 | filegroup( 81 | name = "libevent-files", 82 | srcs = include_files + lib_files, 83 | ) 84 | -------------------------------------------------------------------------------- /third_party/folly/folly-config.h.cmake: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Facebook, Inc. and its affiliates. 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 | #if !defined(FOLLY_MOBILE) 20 | #if defined(__ANDROID__) || \ 21 | (defined(__APPLE__) && \ 22 | (TARGET_IPHONE_SIMULATOR || TARGET_OS_SIMULATOR || TARGET_OS_IPHONE)) 23 | #define FOLLY_MOBILE 1 24 | #else 25 | #define FOLLY_MOBILE 0 26 | #endif 27 | #endif // FOLLY_MOBILE 28 | 29 | #cmakedefine FOLLY_HAVE_PTHREAD 1 30 | #cmakedefine FOLLY_HAVE_PTHREAD_ATFORK 1 31 | 32 | #cmakedefine FOLLY_HAVE_LIBGFLAGS 1 33 | #cmakedefine FOLLY_UNUSUAL_GFLAGS_NAMESPACE 1 34 | #cmakedefine FOLLY_GFLAGS_NAMESPACE @FOLLY_GFLAGS_NAMESPACE@ 35 | 36 | #cmakedefine FOLLY_HAVE_LIBGLOG 1 37 | 38 | #cmakedefine FOLLY_USE_JEMALLOC 1 39 | #cmakedefine FOLLY_USE_LIBSTDCPP 1 40 | 41 | #if __has_include() 42 | #include 43 | #endif 44 | 45 | #cmakedefine FOLLY_HAVE_ACCEPT4 1 46 | #cmakedefine01 FOLLY_HAVE_GETRANDOM 47 | #cmakedefine FOLLY_HAVE_PREADV 1 48 | #cmakedefine FOLLY_HAVE_PWRITEV 1 49 | #cmakedefine FOLLY_HAVE_CLOCK_GETTIME 1 50 | #cmakedefine FOLLY_HAVE_PIPE2 1 51 | #cmakedefine FOLLY_HAVE_SENDMMSG 1 52 | #cmakedefine FOLLY_HAVE_RECVMMSG 1 53 | #cmakedefine FOLLY_HAVE_OPENSSL_ASN1_TIME_DIFF 1 54 | 55 | #cmakedefine FOLLY_HAVE_IFUNC 1 56 | #cmakedefine FOLLY_HAVE_STD__IS_TRIVIALLY_COPYABLE 1 57 | #cmakedefine FOLLY_HAVE_UNALIGNED_ACCESS 1 58 | #cmakedefine FOLLY_HAVE_VLA 1 59 | #cmakedefine FOLLY_HAVE_WEAK_SYMBOLS 1 60 | #cmakedefine FOLLY_HAVE_LINUX_VDSO 1 61 | #cmakedefine FOLLY_HAVE_MALLOC_USABLE_SIZE 1 62 | #cmakedefine FOLLY_HAVE_INT128_T 1 63 | #cmakedefine FOLLY_HAVE_WCHAR_SUPPORT 1 64 | #cmakedefine FOLLY_HAVE_EXTRANDOM_SFMT19937 1 65 | #cmakedefine FOLLY_USE_LIBCPP 1 66 | #cmakedefine HAVE_VSNPRINTF_ERRORS 1 67 | 68 | #cmakedefine FOLLY_HAVE_LIBUNWIND 1 69 | #cmakedefine FOLLY_HAVE_DWARF 1 70 | #cmakedefine FOLLY_HAVE_ELF 1 71 | #cmakedefine FOLLY_HAVE_SWAPCONTEXT 1 72 | #cmakedefine FOLLY_HAVE_BACKTRACE 1 73 | #cmakedefine FOLLY_USE_SYMBOLIZER 1 74 | #define FOLLY_DEMANGLE_MAX_SYMBOL_SIZE 1024 75 | 76 | #cmakedefine FOLLY_HAVE_SHADOW_LOCAL_WARNINGS 1 77 | 78 | #cmakedefine FOLLY_HAVE_LIBLZ4 1 79 | #cmakedefine FOLLY_HAVE_LIBLZMA 1 80 | #cmakedefine FOLLY_HAVE_LIBSNAPPY 1 81 | #cmakedefine FOLLY_HAVE_LIBZ 1 82 | #cmakedefine FOLLY_HAVE_LIBZSTD 1 83 | #cmakedefine FOLLY_HAVE_LIBBZ2 1 84 | 85 | #cmakedefine01 FOLLY_LIBRARY_SANITIZE_ADDRESS 86 | 87 | #cmakedefine FOLLY_SUPPORT_SHARED_LIBRARY 1 88 | 89 | #cmakedefine01 FOLLY_HAVE_LIBRT 90 | -------------------------------------------------------------------------------- /test/chrono_test.cc: -------------------------------------------------------------------------------- 1 | // Tailored from 2 | // https://github.com/facebook/folly/blob/master/folly/test/ChronoTest.cpp 3 | /* 4 | * Copyright (c) Facebook, Inc. and its affiliates. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * 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, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | #include 20 | 21 | #include "gtest/gtest.h" 22 | 23 | using namespace std::chrono; 24 | using namespace folly::chrono; 25 | 26 | namespace { 27 | 28 | class ChronoTest : public testing::Test {}; 29 | } // namespace 30 | 31 | TEST_F(ChronoTest, abs_duration) { 32 | EXPECT_EQ(seconds(7), abs(seconds(7))); 33 | EXPECT_EQ(seconds(7), abs(seconds(-7))); 34 | } 35 | 36 | TEST_F(ChronoTest, ceil_duration) { 37 | EXPECT_EQ(seconds(7), ceil(seconds(7))); 38 | EXPECT_EQ(seconds(7), ceil(milliseconds(7000))); 39 | EXPECT_EQ(seconds(7), ceil(milliseconds(6200))); 40 | } 41 | 42 | TEST_F(ChronoTest, ceil_time_point) { 43 | auto const point = steady_clock::time_point{}; 44 | EXPECT_EQ(point + seconds(7), ceil(point + seconds(7))); 45 | EXPECT_EQ(point + seconds(7), ceil(point + milliseconds(7000))); 46 | EXPECT_EQ(point + seconds(7), ceil(point + milliseconds(6200))); 47 | } 48 | 49 | TEST_F(ChronoTest, floor_duration) { 50 | EXPECT_EQ(seconds(7), floor(seconds(7))); 51 | EXPECT_EQ(seconds(7), floor(milliseconds(7000))); 52 | EXPECT_EQ(seconds(7), floor(milliseconds(7800))); 53 | } 54 | 55 | TEST_F(ChronoTest, floor_time_point) { 56 | auto const point = steady_clock::time_point{}; 57 | EXPECT_EQ(point + seconds(7), floor(point + seconds(7))); 58 | EXPECT_EQ(point + seconds(7), floor(point + milliseconds(7000))); 59 | EXPECT_EQ(point + seconds(7), floor(point + milliseconds(7800))); 60 | } 61 | 62 | TEST_F(ChronoTest, round_duration) { 63 | EXPECT_EQ(seconds(7), round(seconds(7))); 64 | EXPECT_EQ(seconds(6), round(milliseconds(6200))); 65 | EXPECT_EQ(seconds(6), round(milliseconds(6500))); 66 | EXPECT_EQ(seconds(7), round(milliseconds(6800))); 67 | EXPECT_EQ(seconds(7), round(milliseconds(7000))); 68 | EXPECT_EQ(seconds(7), round(milliseconds(7200))); 69 | EXPECT_EQ(seconds(8), round(milliseconds(7500))); 70 | EXPECT_EQ(seconds(8), round(milliseconds(7800))); 71 | } 72 | 73 | TEST_F(ChronoTest, round_time_point) { 74 | auto const point = steady_clock::time_point{}; 75 | EXPECT_EQ(point + seconds(7), round(point + seconds(7))); 76 | EXPECT_EQ(point + seconds(6), round(point + milliseconds(6200))); 77 | EXPECT_EQ(point + seconds(6), round(point + milliseconds(6500))); 78 | EXPECT_EQ(point + seconds(7), round(point + milliseconds(6800))); 79 | EXPECT_EQ(point + seconds(7), round(point + milliseconds(7000))); 80 | EXPECT_EQ(point + seconds(7), round(point + milliseconds(7200))); 81 | EXPECT_EQ(point + seconds(8), round(point + milliseconds(7500))); 82 | EXPECT_EQ(point + seconds(8), round(point + milliseconds(7800))); 83 | } 84 | -------------------------------------------------------------------------------- /third_party/snappy/snappy.BUILD: -------------------------------------------------------------------------------- 1 | package(default_visibility = ["//visibility:public"]) 2 | 3 | licenses(["notice"]) # BSD 3-Clause 4 | 5 | exports_files(["COPYING"]) 6 | 7 | cc_library( 8 | name = "snappy", 9 | srcs = [ 10 | "config.h", 11 | "snappy.cc", 12 | "snappy-internal.h", 13 | "snappy-sinksource.cc", 14 | "snappy-stubs-internal.cc", 15 | "snappy-stubs-internal.h", 16 | ], 17 | hdrs = [ 18 | "snappy.h", 19 | "snappy-sinksource.h", 20 | "snappy-stubs-public.h", 21 | ], 22 | copts = [ 23 | "-DHAVE_CONFIG_H", 24 | "-fno-exceptions", 25 | "-Wno-sign-compare", 26 | "-Wno-shift-negative-value", 27 | # Note(jiaming): disabled, as on aarch64 (Jetson AGX Xvier) 28 | # cc1plus: warning: command line option '-Wno-implicit-function-declaration' is valid for C/ObjC but not for C++ 29 | # "-Wno-implicit-function-declaration", 30 | ], 31 | defines = ["HAVE_SYS_UIO_H"], 32 | includes = ["."], 33 | ) 34 | 35 | genrule( 36 | name = "config_h", 37 | outs = ["config.h"], 38 | cmd = "\n".join([ 39 | "cat <<'EOF' >$@", 40 | "#define HAVE_STDDEF_H 1", 41 | "#define HAVE_STDINT_H 1", 42 | "", 43 | "#ifdef __has_builtin", 44 | "# if !defined(HAVE_BUILTIN_EXPECT) && __has_builtin(__builtin_expect)", 45 | "# define HAVE_BUILTIN_EXPECT 1", 46 | "# endif", 47 | "# if !defined(HAVE_BUILTIN_CTZ) && __has_builtin(__builtin_ctzll)", 48 | "# define HAVE_BUILTIN_CTZ 1", 49 | "# endif", 50 | "#elif defined(__GNUC__) && (__GNUC__ > 3 || __GNUC__ == 3 && __GNUC_MINOR__ >= 4)", 51 | "# ifndef HAVE_BUILTIN_EXPECT", 52 | "# define HAVE_BUILTIN_EXPECT 1", 53 | "# endif", 54 | "# ifndef HAVE_BUILTIN_CTZ", 55 | "# define HAVE_BUILTIN_CTZ 1", 56 | "# endif", 57 | "#endif", 58 | "", 59 | "#ifdef __has_include", 60 | "# if !defined(HAVE_BYTESWAP_H) && __has_include()", 61 | "# define HAVE_BYTESWAP_H 1", 62 | "# endif", 63 | "# if !defined(HAVE_UNISTD_H) && __has_include()", 64 | "# define HAVE_UNISTD_H 1", 65 | "# endif", 66 | "# if !defined(HAVE_SYS_ENDIAN_H) && __has_include()", 67 | "# define HAVE_SYS_ENDIAN_H 1", 68 | "# endif", 69 | "# if !defined(HAVE_SYS_MMAN_H) && __has_include()", 70 | "# define HAVE_SYS_MMAN_H 1", 71 | "# endif", 72 | "# if !defined(HAVE_SYS_UIO_H) && __has_include()", 73 | "# define HAVE_SYS_UIO_H 1", 74 | "# endif", 75 | "#endif", 76 | "", 77 | "#ifndef SNAPPY_IS_BIG_ENDIAN", 78 | "# ifdef __s390x__", 79 | "# define SNAPPY_IS_BIG_ENDIAN 1", 80 | "# elif defined(__BYTE_ORDER__) && defined(__ORDER_BIG_ENDIAN__) && __BYTE_ORDER__ == __ORDER_BIG_ENDIAN__", 81 | "# define SNAPPY_IS_BIG_ENDIAN 1", 82 | "# endif", 83 | "#endif", 84 | "EOF", 85 | ]), 86 | ) 87 | 88 | genrule( 89 | name = "snappy_stubs_public_h", 90 | srcs = ["snappy-stubs-public.h.in"], 91 | outs = ["snappy-stubs-public.h"], 92 | # NOTE(jiaming): Change patch-level no. accordingly. 93 | cmd = ("sed " + 94 | "-e 's/$${\\(.*\\)_01}/\\1/g' " + 95 | "-e 's/$${SNAPPY_MAJOR}/1/g' " + 96 | "-e 's/$${SNAPPY_MINOR}/1/g' " + 97 | "-e 's/$${SNAPPY_PATCHLEVEL}/9/g' " + 98 | "$< >$@"), 99 | ) 100 | -------------------------------------------------------------------------------- /test/fingerprint_test.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Facebook, Inc. and its affiliates. 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 "folly/Fingerprint.h" 18 | 19 | #include "folly/detail/SlowFingerprint.h" 20 | #include "glog/logging.h" 21 | #include "gtest/gtest.h" 22 | 23 | using namespace folly; 24 | using namespace folly::detail; 25 | 26 | TEST(Fingerprint, BroderOptimization) { 27 | // Test that the Broder optimization produces the same result as 28 | // the default (slow) implementation that processes one bit at a time. 29 | uint64_t val_a = 0xfaceb00cdeadbeefUL; 30 | uint64_t val_b = 0x1234567890abcdefUL; 31 | 32 | uint64_t slow[2]; 33 | uint64_t fast[2]; 34 | 35 | SlowFingerprint<64>().update64(val_a).update64(val_b).write(slow); 36 | Fingerprint<64>().update64(val_a).update64(val_b).write(fast); 37 | EXPECT_EQ(slow[0], fast[0]); 38 | 39 | SlowFingerprint<96>().update64(val_a).update64(val_b).write(slow); 40 | Fingerprint<96>().update64(val_a).update64(val_b).write(fast); 41 | EXPECT_EQ(slow[0], fast[0]); 42 | EXPECT_EQ(slow[1], fast[1]); 43 | 44 | SlowFingerprint<128>().update64(val_a).update64(val_b).write(slow); 45 | Fingerprint<128>().update64(val_a).update64(val_b).write(fast); 46 | EXPECT_EQ(slow[0], fast[0]); 47 | EXPECT_EQ(slow[1], fast[1]); 48 | } 49 | 50 | TEST(Fingerprint, MultiByteUpdate) { 51 | // Test that the multi-byte update functions (update32, update64, 52 | // update(StringPiece)) produce the same result as calling update8 53 | // repeatedly. 54 | uint64_t val_a = 0xfaceb00cdeadbeefUL; 55 | uint64_t val_b = 0x1234567890abcdefUL; 56 | uint8_t bytes[16]; 57 | for (int i = 0; i < 8; i++) { 58 | bytes[i] = (val_a >> (8 * (7 - i))) & 0xff; 59 | } 60 | for (int i = 0; i < 8; i++) { 61 | bytes[i + 8] = (val_b >> (8 * (7 - i))) & 0xff; 62 | } 63 | StringPiece sp((const char*)bytes, 16); 64 | 65 | uint64_t u8[2]; // updating 8 bits at a time 66 | uint64_t u32[2]; // updating 32 bits at a time 67 | uint64_t u64[2]; // updating 64 bits at a time 68 | uint64_t usp[2]; // update(StringPiece) 69 | uint64_t uconv[2]; // convenience function (fingerprint*(StringPiece)) 70 | 71 | { 72 | Fingerprint<64> fp; 73 | for (int i = 0; i < 16; i++) { 74 | fp.update8(bytes[i]); 75 | } 76 | fp.write(u8); 77 | } 78 | Fingerprint<64>() 79 | .update32(val_a >> 32) 80 | .update32(val_a & 0xffffffff) 81 | .update32(val_b >> 32) 82 | .update32(val_b & 0xffffffff) 83 | .write(u32); 84 | Fingerprint<64>().update64(val_a).update64(val_b).write(u64); 85 | Fingerprint<64>().update(sp).write(usp); 86 | uconv[0] = fingerprint64(sp); 87 | 88 | EXPECT_EQ(u8[0], u32[0]); 89 | EXPECT_EQ(u8[0], u64[0]); 90 | EXPECT_EQ(u8[0], usp[0]); 91 | EXPECT_EQ(u8[0], uconv[0]); 92 | 93 | { 94 | Fingerprint<96> fp; 95 | for (int i = 0; i < 16; i++) { 96 | fp.update8(bytes[i]); 97 | } 98 | fp.write(u8); 99 | } 100 | Fingerprint<96>() 101 | .update32(val_a >> 32) 102 | .update32(val_a & 0xffffffff) 103 | .update32(val_b >> 32) 104 | .update32(val_b & 0xffffffff) 105 | .write(u32); 106 | Fingerprint<96>().update64(val_a).update64(val_b).write(u64); 107 | Fingerprint<96>().update(sp).write(usp); 108 | uint32_t uconv_lsb; 109 | fingerprint96(sp, &(uconv[0]), &uconv_lsb); 110 | uconv[1] = (uint64_t)uconv_lsb << 32; 111 | 112 | EXPECT_EQ(u8[0], u32[0]); 113 | EXPECT_EQ(u8[1], u32[1]); 114 | EXPECT_EQ(u8[0], u64[0]); 115 | EXPECT_EQ(u8[1], u64[1]); 116 | EXPECT_EQ(u8[0], usp[0]); 117 | EXPECT_EQ(u8[1], usp[1]); 118 | EXPECT_EQ(u8[0], uconv[0]); 119 | EXPECT_EQ(u8[1], uconv[1]); 120 | 121 | { 122 | Fingerprint<128> fp; 123 | for (int i = 0; i < 16; i++) { 124 | fp.update8(bytes[i]); 125 | } 126 | fp.write(u8); 127 | } 128 | Fingerprint<128>() 129 | .update32(val_a >> 32) 130 | .update32(val_a & 0xffffffff) 131 | .update32(val_b >> 32) 132 | .update32(val_b & 0xffffffff) 133 | .write(u32); 134 | Fingerprint<128>().update64(val_a).update64(val_b).write(u64); 135 | Fingerprint<128>().update(sp).write(usp); 136 | fingerprint128(sp, &(uconv[0]), &(uconv[1])); 137 | 138 | EXPECT_EQ(u8[0], u32[0]); 139 | EXPECT_EQ(u8[1], u32[1]); 140 | EXPECT_EQ(u8[0], u64[0]); 141 | EXPECT_EQ(u8[1], u64[1]); 142 | EXPECT_EQ(u8[0], usp[0]); 143 | EXPECT_EQ(u8[1], usp[1]); 144 | EXPECT_EQ(u8[0], uconv[0]); 145 | EXPECT_EQ(u8[1], uconv[1]); 146 | } 147 | 148 | TEST(Fingerprint, Alignment) { 149 | // Test that update() gives the same result regardless of string alignment 150 | const char test_str[] = "hello world 12345"; 151 | int len = sizeof(test_str) - 1; 152 | std::unique_ptr str(new char[len + 8]); 153 | uint64_t ref_fp; 154 | SlowFingerprint<64>().update(StringPiece(test_str, len)).write(&ref_fp); 155 | for (int i = 0; i < 8; i++) { 156 | char* p = str.get(); 157 | char* q; 158 | // Fill the string as !!hello?????? 159 | for (int j = 0; j < i; j++) { 160 | *p++ = '!'; 161 | } 162 | q = p; 163 | for (int j = 0; j < len; j++) { 164 | *p++ = test_str[j]; 165 | } 166 | for (int j = i; j < 8; j++) { 167 | *p++ = '?'; 168 | } 169 | 170 | uint64_t fp; 171 | Fingerprint<64>().update(StringPiece(q, len)).write(&fp); 172 | EXPECT_EQ(ref_fp, fp); 173 | } 174 | } 175 | 176 | int main(int argc, char* argv[]) { 177 | testing::InitGoogleTest(&argc, argv); 178 | return RUN_ALL_TESTS(); 179 | } 180 | -------------------------------------------------------------------------------- /bazel/folly_deps.bzl: -------------------------------------------------------------------------------- 1 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive") 2 | load("@bazel_tools//tools/build_defs/repo:utils.bzl", "maybe") 3 | 4 | def folly_deps(with_gflags = 1, with_syslibs = 0): 5 | if with_gflags: 6 | maybe( 7 | http_archive, 8 | name = "com_github_gflags_gflags", 9 | sha256 = "34af2f15cf7367513b352bdcd2493ab14ce43692d2dcd9dfc499492966c64dcf", 10 | strip_prefix = "gflags-2.2.2", 11 | urls = [ 12 | "https://github.com/gflags/gflags/archive/v2.2.2.tar.gz", 13 | ], 14 | ) 15 | 16 | maybe( 17 | http_archive, 18 | name = "com_github_google_glog", 19 | strip_prefix = "glog-0.5.0", 20 | build_file_content = """ 21 | load(":bazel/glog.bzl", "glog_library") 22 | glog_library(with_gflags = {}) 23 | """.format(with_gflags), 24 | sha256 = "eede71f28371bf39aa69b45de23b329d37214016e2055269b3b5e7cfd40b59f5", 25 | urls = [ 26 | "https://github.com/google/glog/archive/v0.5.0.tar.gz", 27 | ], 28 | ) 29 | 30 | if with_syslibs: 31 | maybe( 32 | native.new_local_repository, 33 | name = "double-conversion", 34 | path = "/usr/include", 35 | build_file = "@com_github_storypku_rules_folly//third_party/syslibs:double-conversion.BUILD", 36 | ) 37 | else: 38 | maybe( 39 | http_archive, 40 | name = "double-conversion", 41 | strip_prefix = "double-conversion-3.1.5", 42 | sha256 = "a63ecb93182134ba4293fd5f22d6e08ca417caafa244afaa751cbfddf6415b13", 43 | urls = ["https://github.com/google/double-conversion/archive/v3.1.5.tar.gz"], 44 | ) 45 | 46 | if with_syslibs: 47 | maybe( 48 | native.new_local_repository, 49 | name = "zlib", 50 | path = "/usr/include", 51 | build_file = "@com_github_storypku_rules_folly//third_party/syslibs:zlib.BUILD", 52 | ) 53 | else: 54 | maybe( 55 | http_archive, 56 | name = "zlib", 57 | sha256 = "629380c90a77b964d896ed37163f5c3a34f6e6d897311f1df2a7016355c45eff", 58 | strip_prefix = "zlib-1.2.11", 59 | build_file = "@com_github_storypku_rules_folly//third_party/zlib:zlib.BUILD", 60 | urls = ["https://github.com/madler/zlib/archive/v1.2.11.tar.gz"], 61 | ) 62 | 63 | if with_syslibs: 64 | maybe( 65 | native.new_local_repository, 66 | name = "com_github_google_snappy", 67 | path = "/usr/include", 68 | build_file = "@com_github_storypku_rules_folly//third_party/syslibs:snappy.BUILD", 69 | ) 70 | else: 71 | maybe( 72 | http_archive, 73 | name = "com_github_google_snappy", 74 | build_file = "@com_github_storypku_rules_folly//third_party/snappy:snappy.BUILD", 75 | strip_prefix = "snappy-1.1.9", 76 | sha256 = "75c1fbb3d618dd3a0483bff0e26d0a92b495bbe5059c8b4f1c962b478b6e06e7", 77 | urls = [ 78 | "https://github.com/google/snappy/archive/1.1.9.tar.gz", 79 | ], 80 | ) 81 | 82 | # ===== libevent (libevent.org) dependency ===== 83 | if with_syslibs: 84 | maybe( 85 | native.new_local_repository, 86 | name = "com_github_libevent_libevent", 87 | path = "/usr/include", 88 | build_file = "@com_github_storypku_rules_folly//third_party/syslibs:libevent.BUILD", 89 | ) 90 | else: 91 | maybe( 92 | http_archive, 93 | name = "com_github_libevent_libevent", 94 | sha256 = "316ddb401745ac5d222d7c529ef1eada12f58f6376a66c1118eee803cb70f83d", 95 | urls = ["https://github.com/libevent/libevent/archive/release-2.1.8-stable.tar.gz"], 96 | strip_prefix = "libevent-release-2.1.8-stable", 97 | build_file = "@com_github_storypku_rules_folly//third_party/libevent:libevent.BUILD", 98 | ) 99 | 100 | maybe( 101 | http_archive, 102 | name = "com_github_fmtlib_fmt", 103 | urls = ["https://github.com/fmtlib/fmt/archive/8.0.1.tar.gz"], 104 | sha256 = "b06ca3130158c625848f3fb7418f235155a4d389b2abc3a6245fb01cb0eb1e01", 105 | strip_prefix = "fmt-8.0.1", 106 | build_file = "@com_github_storypku_rules_folly//third_party/fmtlib:fmtlib.BUILD", 107 | ) 108 | 109 | # Note(jiaming): 110 | # Here we choose the latest (as of 08.04.2021) version of rules_boost as 111 | # AArch64 support was only complete in recent versions. We had to resolve 112 | # all build errors caused by API changes since Boost 1.69+ and refactored 113 | # HttpProxy implementation as it was dependent on Boost.Beast. 114 | # PS: Use of git_repository is discouraged. Ref: 115 | # https://docs.bazel.build/versions/main/external.html#repository-rules 116 | rules_boost_commit = "fb9f3c9a6011f966200027843d894923ebc9cd0b" 117 | maybe( 118 | http_archive, 119 | name = "com_github_nelhage_rules_boost", 120 | sha256 = "046f774b185436d506efeef8be6979f2c22f1971bfebd0979bafa28088bf28d0", 121 | strip_prefix = "rules_boost-{}".format(rules_boost_commit), 122 | urls = [ 123 | "https://github.com/nelhage/rules_boost/archive/{}.tar.gz".format(rules_boost_commit), 124 | ], 125 | ) 126 | 127 | maybe( 128 | native.new_local_repository, 129 | name = "openssl", 130 | path = "/usr/include", 131 | build_file = "@com_github_storypku_rules_folly//third_party/syslibs:openssl.BUILD", 132 | ) 133 | 134 | gtest_version = "1.11.0" 135 | maybe( 136 | http_archive, 137 | name = "com_google_googletest", 138 | sha256 = "b4870bf121ff7795ba20d20bcdd8627b8e088f2d1dab299a031c1034eddc93d5", 139 | strip_prefix = "googletest-release-{}".format(gtest_version), 140 | urls = [ 141 | "https://github.com/google/googletest/archive/refs/tags/release-{}.tar.gz".format(gtest_version), 142 | ], 143 | ) 144 | 145 | # NOTE(storypku): The following failed with error: 146 | # external/folly/folly/ssl/OpenSSLVersionFinder.h:29:26: 147 | # error: 'OPENSSL_VERSION' was not declared in this scope 148 | # 29 | return OpenSSL_version(OPENSSL_VERSION); 149 | # maybe( 150 | # http_archive, 151 | # name = "openssl", 152 | # sha256 = "17f5e63875d592ac8f596a6c3d579978a7bf943247c1f8cbc8051935ea42b3e5", 153 | # strip_prefix = "boringssl-b3d98af9c80643b0a36d495693cc0e669181c0af", 154 | # urls = ["https://github.com/google/boringssl/archive/b3d98af9c80643b0a36d495693cc0e669181c0af.tar.gz"], 155 | # ) 156 | # TODO(storypku): Ref: https://github.com/google/glog/blob/master/bazel/glog.bzl 157 | folly_version = "2021.09.06.00" 158 | http_archive( 159 | name = "folly", 160 | # build_file = "@com_github_storypku_rules_folly//third_party/folly:folly.BUILD", 161 | build_file_content = """ 162 | load("@com_github_storypku_rules_folly//bazel:folly.bzl", "folly_library") 163 | package(default_visibility = ["//visibility:public"]) 164 | folly_library(with_gflags = {}) 165 | """.format(with_gflags), 166 | strip_prefix = "folly-{}".format(folly_version), 167 | sha256 = "8fb0a5392cbf6da1233c59933fff880dd77bbe61e0e2d578347ff436c776eda5", 168 | urls = [ 169 | "https://github.com/facebook/folly/archive/v{}.tar.gz".format(folly_version), 170 | ], 171 | patch_args = ["-p1"], 172 | patches = [ 173 | "@com_github_storypku_rules_folly//third_party/folly:p00_double_conversion_include_fix.patch", 174 | ], 175 | ) 176 | -------------------------------------------------------------------------------- /test/checksum_test.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Facebook, Inc. and its affiliates. 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 "folly/hash/Checksum.h" 18 | 19 | #include "boost/crc.hpp" 20 | #include "folly/Random.h" 21 | #include "folly/hash/Hash.h" 22 | #include "folly/hash/detail/ChecksumDetail.h" 23 | #include "folly/portability/GFlags.h" 24 | #include "glog/logging.h" 25 | #include "gtest/gtest.h" 26 | 27 | namespace { 28 | const unsigned int BUFFER_SIZE = 512 * 1024 * sizeof(uint64_t); 29 | uint8_t buffer[BUFFER_SIZE]; 30 | 31 | struct ExpectedResult { 32 | size_t offset; 33 | size_t length; 34 | uint32_t crc32c; 35 | }; 36 | 37 | ExpectedResult expectedResults[] = { 38 | // Zero-byte input 39 | {0, 0, ~0U}, 40 | // Small aligned inputs to test special cases in SIMD implementations 41 | {8, 1, 1543413366}, 42 | {8, 2, 523493126}, 43 | {8, 3, 1560427360}, 44 | {8, 4, 3422504776}, 45 | {8, 5, 447841138}, 46 | {8, 6, 3910050499}, 47 | {8, 7, 3346241981}, 48 | // Small unaligned inputs 49 | {9, 1, 3855826643}, 50 | {10, 2, 560880875}, 51 | {11, 3, 1479707779}, 52 | {12, 4, 2237687071}, 53 | {13, 5, 4063855784}, 54 | {14, 6, 2553454047}, 55 | {15, 7, 1349220140}, 56 | // Larger inputs to test leftover chunks at the end of aligned blocks 57 | {8, 8, 627613930}, 58 | {8, 9, 2105929409}, 59 | {8, 10, 2447068514}, 60 | {8, 11, 863807079}, 61 | {8, 12, 292050879}, 62 | {8, 13, 1411837737}, 63 | {8, 14, 2614515001}, 64 | {8, 15, 3579076296}, 65 | {8, 16, 2897079161}, 66 | {8, 17, 675168386}, 67 | // Much larger inputs 68 | {0, BUFFER_SIZE, 2096790750}, 69 | {1, BUFFER_SIZE / 2, 3854797577}, 70 | }; 71 | 72 | void testCRC32C( 73 | std::function impl) { 74 | for (auto expected : expectedResults) { 75 | uint32_t result = impl(buffer + expected.offset, expected.length, ~0U); 76 | EXPECT_EQ(expected.crc32c, result); 77 | } 78 | } 79 | 80 | void testCRC32CContinuation( 81 | std::function impl) { 82 | for (auto expected : expectedResults) { 83 | size_t partialLength = expected.length / 2; 84 | uint32_t partialChecksum = 85 | impl(buffer + expected.offset, partialLength, ~0U); 86 | uint32_t result = impl(buffer + expected.offset + partialLength, 87 | expected.length - partialLength, partialChecksum); 88 | EXPECT_EQ(expected.crc32c, result); 89 | } 90 | } 91 | 92 | void testMatchesBoost32Type() { 93 | for (auto expected : expectedResults) { 94 | boost::crc_32_type result; 95 | result.process_bytes(buffer + expected.offset, expected.length); 96 | const uint32_t boostResult = result.checksum(); 97 | const uint32_t follyResult = 98 | folly::crc32_type(buffer + expected.offset, expected.length); 99 | EXPECT_EQ(follyResult, boostResult); 100 | } 101 | } 102 | 103 | } // namespace 104 | 105 | TEST(Checksum, crc32c_software) { testCRC32C(folly::detail::crc32c_sw); } 106 | 107 | TEST(Checksum, crc32c_continuation_software) { 108 | testCRC32CContinuation(folly::detail::crc32c_sw); 109 | } 110 | 111 | TEST(Checksum, crc32c_hardware) { 112 | if (folly::detail::crc32c_hw_supported()) { 113 | testCRC32C(folly::detail::crc32c_hw); 114 | } else { 115 | LOG(WARNING) << "skipping hardware-accelerated CRC-32C tests" 116 | << " (not supported on this CPU)"; 117 | } 118 | } 119 | 120 | TEST(Checksum, crc32c_hardware_eq) { 121 | if (folly::detail::crc32c_hw_supported()) { 122 | for (int i = 0; i < 1000; i++) { 123 | auto sw = folly::detail::crc32c_sw(buffer, i, 0); 124 | auto hw = folly::detail::crc32c_hw(buffer, i, 0); 125 | EXPECT_EQ(sw, hw); 126 | } 127 | } else { 128 | LOG(WARNING) << "skipping hardware-accelerated CRC-32C tests" 129 | << " (not supported on this CPU)"; 130 | } 131 | } 132 | 133 | TEST(Checksum, crc32c_continuation_hardware) { 134 | if (folly::detail::crc32c_hw_supported()) { 135 | testCRC32CContinuation(folly::detail::crc32c_hw); 136 | } else { 137 | LOG(WARNING) << "skipping hardware-accelerated CRC-32C tests" 138 | << " (not supported on this CPU)"; 139 | } 140 | } 141 | 142 | TEST(Checksum, crc32c_autodetect) { testCRC32C(folly::crc32c); } 143 | 144 | TEST(Checksum, crc32c_continuation_autodetect) { 145 | testCRC32CContinuation(folly::crc32c); 146 | } 147 | 148 | TEST(Checksum, crc32) { 149 | if (folly::detail::crc32c_hw_supported()) { 150 | // Just check that sw and hw match 151 | for (auto expected : expectedResults) { 152 | uint32_t sw_res = 153 | folly::detail::crc32_sw(buffer + expected.offset, expected.length, 0); 154 | uint32_t hw_res = 155 | folly::detail::crc32_hw(buffer + expected.offset, expected.length, 0); 156 | EXPECT_EQ(sw_res, hw_res); 157 | } 158 | } else { 159 | LOG(WARNING) << "skipping hardware-accelerated CRC-32 tests" 160 | << " (not supported on this CPU)"; 161 | } 162 | } 163 | 164 | TEST(Checksum, crc32_continuation) { 165 | if (folly::detail::crc32c_hw_supported()) { 166 | // Just check that sw and hw match 167 | for (auto expected : expectedResults) { 168 | auto halflen = expected.length / 2; 169 | uint32_t sw_res = 170 | folly::detail::crc32_sw(buffer + expected.offset, halflen, 0); 171 | sw_res = folly::detail::crc32_sw(buffer + expected.offset + halflen, 172 | halflen, sw_res); 173 | uint32_t hw_res = 174 | folly::detail::crc32_hw(buffer + expected.offset, halflen, 0); 175 | hw_res = folly::detail::crc32_hw(buffer + expected.offset + halflen, 176 | halflen, hw_res); 177 | EXPECT_EQ(sw_res, hw_res); 178 | uint32_t sw_res2 = 179 | folly::detail::crc32_sw(buffer + expected.offset, halflen * 2, 0); 180 | EXPECT_EQ(sw_res, sw_res2); 181 | uint32_t hw_res2 = 182 | folly::detail::crc32_hw(buffer + expected.offset, halflen * 2, 0); 183 | EXPECT_EQ(hw_res, hw_res2); 184 | } 185 | } else { 186 | LOG(WARNING) << "skipping hardware-accelerated CRC-32 tests" 187 | << " (not supported on this CPU)"; 188 | } 189 | } 190 | 191 | TEST(Checksum, crc32_type) { 192 | // Test that crc32_type matches boost::crc_32_type 193 | testMatchesBoost32Type(); 194 | } 195 | 196 | TEST(Checksum, crc32_combine) { 197 | for (size_t totlen = 1024; totlen < BUFFER_SIZE; totlen += BUFFER_SIZE / 8) { 198 | auto mid = folly::Random::rand64(0, totlen); 199 | auto crc1 = folly::crc32(&buffer[0], mid, 0); 200 | auto crc2 = folly::crc32(&buffer[mid], totlen - mid, 0); 201 | auto crcfull = folly::crc32(&buffer[0], totlen, 0); 202 | auto combined = folly::crc32_combine(crc1, crc2, totlen - mid); 203 | EXPECT_EQ(combined, crcfull); 204 | } 205 | } 206 | 207 | TEST(Checksum, crc32c_combine) { 208 | for (size_t totlen = 1024; totlen < BUFFER_SIZE; totlen += BUFFER_SIZE / 8) { 209 | auto mid = folly::Random::rand64(0, totlen); 210 | auto crc1 = folly::crc32c(&buffer[0], mid, 0); 211 | auto crc2 = folly::crc32c(&buffer[mid], totlen - mid, 0); 212 | auto crcfull = folly::crc32c(&buffer[0], totlen, 0); 213 | auto combined = folly::crc32c_combine(crc1, crc2, totlen - mid); 214 | EXPECT_EQ(combined, crcfull); 215 | } 216 | } 217 | 218 | int main(int argc, char** argv) { 219 | testing::InitGoogleTest(&argc, argv); 220 | google::InitGoogleLogging(argv[0]); 221 | 222 | // Populate a buffer with a deterministic pattern 223 | // on which to compute checksums 224 | const uint8_t* src = buffer; 225 | uint64_t* dst = (uint64_t*)buffer; 226 | const uint64_t* end = (const uint64_t*)(buffer + BUFFER_SIZE); 227 | *dst++ = 0; 228 | while (dst < end) { 229 | *dst++ = folly::hash::fnv64_buf((const char*)src, sizeof(uint64_t)); 230 | src += sizeof(uint64_t); 231 | } 232 | 233 | return RUN_ALL_TESTS(); 234 | } 235 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /bazel/folly.bzl: -------------------------------------------------------------------------------- 1 | # Implement a macro folly_library() that the BUILD file can load. 2 | load("@rules_cc//cc:defs.bzl", "cc_library") 3 | 4 | # Ref: https://github.com/google/glog/blob/v0.5.0/bazel/glog.bzl 5 | def _expand_template_impl(ctx): 6 | ctx.actions.expand_template( 7 | template = ctx.file.template, 8 | output = ctx.outputs.out, 9 | substitutions = ctx.attr.substitutions, 10 | ) 11 | 12 | expand_template = rule( 13 | implementation = _expand_template_impl, 14 | attrs = { 15 | "template": attr.label(mandatory = True, allow_single_file = True), 16 | "substitutions": attr.string_dict(mandatory = True), 17 | "out": attr.output(mandatory = True), 18 | }, 19 | ) 20 | 21 | def _dict_union(x, y): 22 | z = {} 23 | z.update(x) 24 | z.update(y) 25 | return z 26 | 27 | def folly_library( 28 | with_gflags = 1, 29 | with_jemalloc = 0, 30 | with_bz2 = 0, 31 | with_lzma = 0, 32 | with_lz4 = 0, 33 | with_zstd = 0, 34 | with_unwind = 0, 35 | with_dwarf = 0, 36 | with_libaio = 0, 37 | with_liburing = 0, 38 | enable_testing = 0): 39 | # Exclude tests, benchmarks, and other standalone utility executables from the 40 | # library sources. Test sources are listed separately below. 41 | common_excludes = [ 42 | "folly/build/**", 43 | "folly/logging/example/**", 44 | "folly/tools/**", 45 | ] 46 | 47 | hdrs = native.glob(["folly/**/*.h"], exclude = common_excludes + [ 48 | "folly/test/**/*.h", 49 | "folly/**/test/**/*.h", 50 | "folly/python/fibers.h", 51 | "folly/python/GILAwareManualExecutor.h", 52 | ]) 53 | srcs = native.glob(["folly/**/*.cpp"], exclude = common_excludes + [ 54 | "folly/Benchmark.cpp", 55 | "folly/test/**/*.cpp", 56 | "folly/**/test/**/*.cpp", 57 | "folly/**/*Test.cpp", 58 | "folly/experimental/JSONSchemaTester.cpp", 59 | "folly/experimental/io/HugePageUtil.cpp", 60 | "folly/python/error.cpp", 61 | "folly/python/executor.cpp", 62 | "folly/python/fibers.cpp", 63 | "folly/python/GILAwareManualExecutor.cpp", 64 | "folly/cybld/folly/executor.cpp", 65 | "folly/experimental/symbolizer/Addr2Line.cpp", 66 | ]) 67 | 68 | # Explicitly include utility library code from inside 69 | # test subdirs 70 | hdrs = hdrs + [ 71 | "folly/container/test/F14TestUtil.h", 72 | "folly/container/test/TrackingTypes.h", 73 | "folly/io/async/test/AsyncSSLSocketTest.h", 74 | "folly/io/async/test/AsyncSocketTest.h", 75 | "folly/io/async/test/AsyncSocketTest2.h", 76 | "folly/io/async/test/BlockingSocket.h", 77 | "folly/io/async/test/MockAsyncSocket.h", 78 | "folly/io/async/test/MockAsyncServerSocket.h", 79 | "folly/io/async/test/MockAsyncSSLSocket.h", 80 | "folly/io/async/test/MockAsyncTransport.h", 81 | "folly/io/async/test/MockAsyncUDPSocket.h", 82 | "folly/io/async/test/MockTimeoutManager.h", 83 | "folly/io/async/test/ScopedBoundPort.h", 84 | "folly/io/async/test/SocketPair.h", 85 | "folly/io/async/test/TestSSLServer.h", 86 | "folly/io/async/test/TimeUtil.h", 87 | "folly/io/async/test/UndelayedDestruction.h", 88 | "folly/io/async/test/Util.h", 89 | "folly/synchronization/test/Semaphore.h", 90 | "folly/test/DeterministicSchedule.h", 91 | "folly/test/JsonTestUtil.h", 92 | "folly/test/TestUtils.h", 93 | ] 94 | 95 | srcs = srcs + [ 96 | "folly/io/async/test/ScopedBoundPort.cpp", 97 | "folly/io/async/test/SocketPair.cpp", 98 | "folly/io/async/test/TimeUtil.cpp", 99 | ] 100 | 101 | # Exclude specific sources if we do not have third-party libraries 102 | # required to build them 103 | common_excludes = [] 104 | 105 | # NOTE(storypku): hardcode with_libsodium set to False for now 106 | # Ref: https://github.com/facebook/folly/blob/v2021.09.06.00/CMakeLists.txt#L270 107 | hdrs_excludes = [ 108 | "folly/experimental/crypto/Blake2xb.h", 109 | "folly/experimental/crypto/detail/LtHashInternal.h", 110 | "folly/experimental/crypto/LtHash-inl.h", 111 | "folly/experimental/crypto/LtHash.h", 112 | ] 113 | 114 | srcs_excludes = [ 115 | "folly/experimental/crypto/Blake2xb.cpp", 116 | "folly/experimental/crypto/detail/MathOperation_AVX2.cpp", 117 | "folly/experimental/crypto/detail/MathOperation_Simple.cpp", 118 | "folly/experimental/crypto/detail/MathOperation_SSE2.cpp", 119 | "folly/experimental/crypto/LtHash.cpp", 120 | ] 121 | 122 | if with_libaio == 0: 123 | hdrs_excludes = hdrs_excludes + [ 124 | "folly/experimental/io/AsyncIO.h", 125 | ] 126 | srcs_excludes = srcs_excludes + [ 127 | "folly/experimental/io/AsyncIO.cpp", 128 | ] 129 | 130 | if with_liburing == 0: 131 | hdrs_excludes = hdrs_excludes + [ 132 | "folly/experimental/io/IoUring.h", 133 | "folly/experimental/io/IoUringBackend.h", 134 | ] 135 | srcs_excludes = srcs_excludes + [ 136 | "folly/experimental/io/IoUring.cpp", 137 | "folly/experimental/io/IoUringBackend.cpp", 138 | ] 139 | if with_libaio == 0 and with_liburing == 0: 140 | hdrs_excludes = hdrs_excludes + [ 141 | "folly/experimental/io/AsyncBase.h", 142 | "folly/experimental/io/PollIoBackend.h", 143 | "folly/experimental/io/SimpleAsyncIO.h", 144 | ] 145 | srcs_excludes = srcs_excludes + [ 146 | "folly/experimental/io/AsyncBase.cpp", 147 | "folly/experimental/io/PollIoBackend.cpp", 148 | "folly/experimental/io/SimpleAsyncIO.cpp", 149 | ] 150 | 151 | # NOTE(storypku): 152 | # Compare header and source files with that of CMake 153 | # my_hdrs = native.glob(hdrs, exclude = common_excludes + hdrs_excludes) 154 | # print("=== # of headers: {} ===".format(len(my_hdrs))) 155 | # print("===== HEADERS END =====") 156 | # my_srcs = native.glob(srcs, exclude = common_excludes + srcs_excludes) 157 | # print("=== # of srcs: {} ===".format(len(my_srcs))) 158 | # for my_src in my_srcs: 159 | # print(my_src) 160 | # print("===== SRCS END =====") 161 | if with_gflags == 0: 162 | hdrs_excludes = hdrs_excludes + [ 163 | "folly/experimental/NestedCommandLineApp.h", 164 | "folly/experimental/ProgramOptions.h", 165 | ] 166 | srcs_excludes = srcs_excludes + [ 167 | "folly/experimental/NestedCommandLineApp.cpp", 168 | "folly/experimental/ProgramOptions.cpp", 169 | ] 170 | 171 | # TODO(jiaming) 172 | common_defs = { 173 | "@FOLLY_HAVE_PTHREAD@": "1", 174 | "@FOLLY_HAVE_PTHREAD_ATFORK@": "1", 175 | "@FOLLY_HAVE_ACCEPT4@": "1", 176 | "@FOLLY_HAVE_GETRANDOM@": "1", 177 | "@FOLLY_HAVE_PREADV@": "1", 178 | "@FOLLY_HAVE_PWRITEV@": "1", 179 | "@FOLLY_HAVE_CLOCK_GETTIME@": "1", 180 | "@FOLLY_HAVE_PIPE2@": "1", 181 | "@FOLLY_HAVE_SENDMMSG@": "1", 182 | "@FOLLY_HAVE_RECVMMSG@": "1", 183 | "@FOLLY_HAVE_OPENSSL_ASN1_TIME_DIFF@": "1", 184 | "@FOLLY_HAVE_IFUNC@": "1", 185 | "@FOLLY_HAVE_STD__IS_TRIVIALLY_COPYABLE@": "1", 186 | "@FOLLY_HAVE_UNALIGNED_ACCESS@": "1", 187 | "@FOLLY_HAVE_VLA@": "1", 188 | "@FOLLY_HAVE_WEAK_SYMBOLS@": "1", 189 | "@FOLLY_HAVE_LINUX_VDSO@": "1", 190 | "@FOLLY_HAVE_MALLOC_USABLE_SIZE@": "1", 191 | "@FOLLY_HAVE_INT128_T@": "0", 192 | "@FOLLY_HAVE_WCHAR_SUPPORT@": "1", 193 | "@define FOLLY_HAVE_EXTRANDOM_SFMT19937@": "1", 194 | "@HAVE_VSNPRINTF_ERRORS@": "1", 195 | "@FOLLY_HAVE_SHADOW_LOCAL_WARNINGS@": "1", 196 | "@FOLLY_SUPPORT_SHARED_LIBRARY@": "1", 197 | "@FOLLY_DEMANGLE_MAX_SYMBOL_SIZE": "1024", 198 | } 199 | 200 | # Note(storypku): 201 | total_defs = _dict_union(common_defs, { 202 | "@FOLLY_USE_LIBSTDCPP@": "1", 203 | "@FOLLY_USE_LIBCPP@": "0", 204 | "@FOLLY_HAVE_LIBGFLAGS@": str(with_gflags), 205 | "@FOLLY_UNUSUAL_GFLAGS_NAMESPACE@": "0", 206 | "@FOLLY_GFLAGS_NAMESPACE@": "gflags", 207 | "@FOLLY_HAVE_LIBGLOG@": "1", 208 | "@FOLLY_HAVE_LIBLZ4@": str(with_lz4), 209 | "@FOLLY_HAVE_LIBLZMA@": str(with_lzma), 210 | "@FOLLY_HAVE_LIBSNAPPY@": "0", 211 | "@FOLLY_HAVE_LIBZ@": "1", 212 | "@FOLLY_HAVE_LIBZSTD@": str(with_zstd), 213 | "@FOLLY_HAVE_LIBBZ2@": str(with_bz2), 214 | "@FOLLY_USE_JEMALLOC@": str(with_jemalloc), 215 | "@FOLLY_HAVE_LIBUNWIND@": str(with_unwind), 216 | "@FOLLY_HAVE_DWARF@": str(with_dwarf), 217 | "@FOLLY_HAVE_ELF@": "1", 218 | "@FOLLY_HAVE_SWAPCONTEXT@": "1", 219 | "@FOLLY_HAVE_BACKTRACE@": "1", 220 | "@FOLLY_USE_SYMBOLIZER@": "1", 221 | "@FOLLY_LIBRARY_SANITIZE_ADDRESS@": "0", 222 | "@FOLLY_HAVE_LIBRT@": "0", 223 | }) 224 | 225 | native.genrule( 226 | name = "folly_config_in_h", 227 | srcs = [ 228 | "CMake/folly-config.h.cmake", 229 | ], 230 | outs = [ 231 | "folly/folly-config.h.in", 232 | ], 233 | cmd = "$(location @com_github_storypku_rules_folly//bazel:generate_config_in.sh) < $< > $@", 234 | tools = ["@com_github_storypku_rules_folly//bazel:generate_config_in.sh"], 235 | ) 236 | 237 | expand_template( 238 | name = "folly_config_h_unstripped", 239 | template = "folly/folly-config.h.in", 240 | out = "folly/folly-config.h.unstripped", 241 | substitutions = total_defs, 242 | ) 243 | 244 | native.genrule( 245 | name = "folly_config_h", 246 | srcs = [ 247 | "folly/folly-config.h.unstripped", 248 | ], 249 | outs = [ 250 | "folly/folly-config.h", 251 | ], 252 | cmd = "$(location @com_github_storypku_rules_folly//bazel:strip_config_h.sh) < $< > $@", 253 | tools = ["@com_github_storypku_rules_folly//bazel:strip_config_h.sh"], 254 | ) 255 | 256 | common_copts = [ 257 | "-std=gnu++1z", 258 | "-fPIC", 259 | "-finput-charset=UTF-8", 260 | "-fsigned-char", 261 | "-fopenmp", 262 | "-faligned-new", 263 | "-Wall", 264 | "-Wno-deprecated", 265 | "-Wno-deprecated-declarations", 266 | "-Wno-sign-compare", 267 | "-Wno-unused", 268 | "-Wunused-label", 269 | "-Wunused-result", 270 | "-Wshadow-compatible-local", 271 | "-Wno-noexcept-type", 272 | ] 273 | 274 | # CHECK_CXX_COMPILER_FLAG(-mpclmul COMPILER_HAS_M_PCLMUL) 275 | cc_library( 276 | name = "folly", 277 | hdrs = ["folly_config_h"] + 278 | native.glob(hdrs, exclude = common_excludes + hdrs_excludes), 279 | srcs = native.glob(srcs, exclude = common_excludes + srcs_excludes), 280 | copts = common_copts + select({ 281 | "@com_github_storypku_rules_folly//bazel:linux_x86_64": ["-mpclmul"], 282 | "//conditions:default": [], 283 | }), 284 | includes = ["."], 285 | linkopts = [ 286 | "-pthread", 287 | "-ldl", 288 | "-lstdc++fs", 289 | ], 290 | # if (FOLLY_STDLIB_LIBSTDCXX AND NOT FOLLY_STDLIB_LIBSTDCXX_GE_9) 291 | # list (APPEND CMAKE_REQUIRED_LIBRARIES stdc++fs) 292 | # list (APPEND FOLLY_LINK_LIBRARIES stdc++fs) 293 | # endif() 294 | # if (FOLLY_STDLIB_LIBCXX AND NOT FOLLY_STDLIB_LIBCXX_GE_9) 295 | # list (APPEND CMAKE_REQUIRED_LIBRARIES c++fs) 296 | # list (APPEND FOLLY_LINK_LIBRARIES c++fs) 297 | # endif () 298 | # Ref: https://docs.bazel.build/versions/main/be/c-cpp.html#cc_library.linkstatic 299 | # linkstatic = True, 300 | visibility = ["//visibility:public"], 301 | deps = [ 302 | "@boost//:algorithm", 303 | "@boost//:config", 304 | "@boost//:container", 305 | "@boost//:context", 306 | "@boost//:conversion", 307 | "@boost//:crc", 308 | "@boost//:filesystem", 309 | "@boost//:intrusive", 310 | "@boost//:iterator", 311 | "@boost//:multi_index", 312 | "@boost//:operators", 313 | "@boost//:program_options", 314 | "@boost//:regex", 315 | "@boost//:type_traits", 316 | "@boost//:utility", 317 | "@boost//:variant", 318 | "@com_github_google_glog//:glog", 319 | "@com_github_google_snappy//:snappy", 320 | "@com_github_libevent_libevent//:libevent", 321 | "@com_github_fmtlib_fmt//:fmt", 322 | "@double-conversion//:double-conversion", 323 | "@openssl//:ssl", 324 | ] + ([ 325 | "@com_github_gflags_gflags//:gflags", 326 | ] if with_gflags else []), 327 | ) 328 | 329 | cc_library( 330 | name = "follybenchmark", 331 | srcs = ["folly/Benchmark.cpp"], 332 | deps = [ 333 | ":folly", 334 | ], 335 | copts = common_copts, 336 | ) 337 | 338 | if enable_testing: 339 | cc_library( 340 | name = "folly_test_support", 341 | srcs = [ 342 | "folly/test/common/TestMain.cpp", 343 | "folly/test/FBVectorTestUtil.cpp", 344 | "folly/test/DeterministicSchedule.cpp", 345 | "folly/test/SingletonTestStructs.cpp", 346 | "folly/test/SocketAddressTestHelper.cpp", 347 | "folly/experimental/test/CodingTestUtils.cpp", 348 | "folly/futures/test/TestExecutor.cpp", 349 | "folly/io/async/test/ScopedBoundPort.cpp", 350 | "folly/io/async/test/SocketPair.cpp", 351 | "folly/logging/test/ConfigHelpers.cpp", 352 | "folly/logging/test/TestLogHandler.cpp", 353 | "folly/io/async/test/SSLUtil.cpp", 354 | "folly/io/async/test/TestSSLServer.cpp", 355 | "folly/io/async/test/TimeUtil.cpp", 356 | ], 357 | hdrs = [ 358 | "folly/test/FBVectorTestUtil.h", 359 | "folly/test/DeterministicSchedule.h", 360 | "folly/test/SingletonTestStructs.h", 361 | "folly/test/SocketAddressTestHelper.h", 362 | "folly/container/test/F14TestUtil.h", 363 | "folly/container/test/TrackingTypes.h", 364 | "folly/experimental/test/CodingTestUtils.h", 365 | "folly/futures/test/TestExecutor.h", 366 | "folly/io/async/test/BlockingSocket.h", 367 | "folly/io/async/test/MockAsyncServerSocket.h", 368 | "folly/io/async/test/MockAsyncSocket.h", 369 | "folly/io/async/test/MockAsyncSSLSocket.h", 370 | "folly/io/async/test/MockAsyncTransport.h", 371 | "folly/io/async/test/MockAsyncUDPSocket.h", 372 | "folly/io/async/test/MockTimeoutManager.h", 373 | "folly/io/async/test/ScopedBoundPort.h", 374 | "folly/io/async/test/SocketPair.h", 375 | "folly/io/async/test/SSLUtil.h", 376 | "folly/io/async/test/TestSSLServer.h", 377 | "folly/io/async/test/TimeUtil.h", 378 | "folly/io/async/test/UndelayedDestruction.h", 379 | "folly/io/async/test/Util.h", 380 | "folly/logging/test/ConfigHelpers.h", 381 | "folly/logging/test/TestLogHandler.h", 382 | ], 383 | deps = [ 384 | ":follybenchmark", 385 | "@com_github_google_glog//:glog", 386 | "@com_google_googletest//:gtest", 387 | ], 388 | ) 389 | -------------------------------------------------------------------------------- /test/small_vector_test.cc: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (c) Facebook, Inc. and its affiliates. 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 | // NOTE(storypku): Adapted from 17 | // https://github.com/facebook/folly/blob/v2021.09.06.00/folly/test/small_vector_test.cpp 18 | #include "folly/small_vector.h" 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | #include 26 | #include 27 | #include 28 | 29 | #include "boost/algorithm/string.hpp" 30 | #include "fmt/format.h" 31 | #include "folly/Conv.h" 32 | #include "folly/Traits.h" 33 | #include "folly/portability/GTest.h" 34 | #include "folly/sorted_vector_types.h" 35 | 36 | using folly::small_vector; 37 | using namespace folly::small_vector_policy; 38 | 39 | #if FOLLY_X64 || FOLLY_PPC64 40 | 41 | static_assert(sizeof(small_vector) == 16, 42 | "Object size is not what we expect for small_vector"); 43 | static_assert(sizeof(small_vector) == 16, 44 | "Object size is not what we expect for " 45 | "small_vector"); 46 | static_assert(sizeof(small_vector) == 47 | 10 * sizeof(int) + sizeof(std::size_t), 48 | "Object size is not what we expect for small_vector"); 49 | 50 | static_assert(sizeof(small_vector) == 8 + 4, 51 | "small_vector is wrong size"); 52 | 53 | // Extra 2 bytes needed for alignment. 54 | static_assert(sizeof(small_vector) == 8 + 2 + 2, 55 | "small_vector is wrong size"); 56 | static_assert(alignof(small_vector) >= 4, 57 | "small_vector not aligned correctly"); 58 | 59 | // Extra 3 bytes needed for alignment. 60 | static_assert(sizeof(small_vector) == 8 + 1 + 3, 61 | "small_vector is wrong size"); 62 | static_assert(alignof(small_vector) >= 4, 63 | "small_vector not aligned correctly"); 64 | 65 | static_assert(sizeof(small_vector) == 10, 66 | "Sizeof unexpectedly large"); 67 | 68 | #endif 69 | 70 | static_assert(!folly::is_trivially_copyable>::value, 71 | "std::unique_ptr<> is trivially copyable"); 72 | 73 | static_assert(alignof(small_vector::type, 4>) == 74 | 32, 75 | "small_vector not aligned correctly"); 76 | 77 | namespace { 78 | 79 | template 80 | using small_sorted_vector_map = 81 | folly::sorted_vector_map, 82 | std::allocator>, void, 83 | folly::small_vector, N>>; 84 | 85 | template 86 | using noheap_sorted_vector_map = folly::sorted_vector_map< 87 | Key, Value, std::less, std::allocator>, void, 88 | folly::small_vector, N, 89 | folly::small_vector_policy::NoHeap>>; 90 | 91 | template 92 | using small_sorted_vector_set = 93 | folly::sorted_vector_set, std::allocator, void, 94 | folly::small_vector>; 95 | 96 | template 97 | using noheap_sorted_vector_set = folly::sorted_vector_set< 98 | T, std::less, std::allocator, void, 99 | folly::small_vector>; 100 | 101 | struct NontrivialType { 102 | static int ctored; 103 | explicit NontrivialType() : a(0) {} 104 | 105 | /* implicit */ NontrivialType(int a_) : a(a_) { ++ctored; } 106 | 107 | NontrivialType(NontrivialType const& /* s */) { ++ctored; } 108 | 109 | NontrivialType& operator=(NontrivialType const& o) { 110 | a = o.a; 111 | return *this; 112 | } 113 | 114 | int32_t a; 115 | }; 116 | static_assert(!folly::is_trivially_copyable::value, 117 | "NontrivialType is trivially copyable"); 118 | 119 | int NontrivialType::ctored = 0; 120 | 121 | struct TestException {}; 122 | 123 | int throwCounter = 1; 124 | void MaybeThrow() { 125 | if (!--throwCounter) { 126 | throw TestException(); 127 | } 128 | } 129 | 130 | const int kMagic = 0xdeadbeef; 131 | struct Thrower { 132 | static int alive; 133 | 134 | Thrower() : magic(kMagic) { 135 | EXPECT_EQ(magic, kMagic); 136 | MaybeThrow(); 137 | ++alive; 138 | } 139 | Thrower(Thrower const& other) : magic(other.magic) { 140 | EXPECT_EQ(magic, kMagic); 141 | MaybeThrow(); 142 | ++alive; 143 | } 144 | ~Thrower() noexcept { 145 | EXPECT_EQ(magic, kMagic); 146 | magic = 0; 147 | --alive; 148 | } 149 | 150 | Thrower& operator=(Thrower const& /* other */) { 151 | EXPECT_EQ(magic, kMagic); 152 | MaybeThrow(); 153 | return *this; 154 | } 155 | 156 | // This is just to try to make sure we don't get our member 157 | // functions called on uninitialized memory. 158 | int magic; 159 | }; 160 | 161 | int Thrower::alive = 0; 162 | 163 | // Type that counts how many exist and doesn't support copy 164 | // construction. 165 | struct NoncopyableCounter { 166 | static int alive; 167 | NoncopyableCounter() { ++alive; } 168 | ~NoncopyableCounter() { --alive; } 169 | NoncopyableCounter(NoncopyableCounter&&) noexcept { ++alive; } 170 | NoncopyableCounter(NoncopyableCounter const&) = delete; 171 | NoncopyableCounter& operator=(NoncopyableCounter const&) const = delete; 172 | NoncopyableCounter& operator=(NoncopyableCounter&&) { return *this; } 173 | }; 174 | int NoncopyableCounter::alive = 0; 175 | 176 | static_assert(!folly::is_trivially_copyable::value, 177 | "NoncopyableCounter is trivially copyable"); 178 | 179 | // Check that throws don't break the basic guarantee for some cases. 180 | // Uses the method for testing exception safety described at 181 | // http://www.boost.org/community/exception_safety.html, to force all 182 | // throwing code paths to occur. 183 | struct TestBasicGuarantee { 184 | folly::small_vector vec; 185 | int const prepopulate; 186 | 187 | explicit TestBasicGuarantee(int prepopulate_) : prepopulate(prepopulate_) { 188 | throwCounter = 1000; 189 | for (int i = 0; i < prepopulate; ++i) { 190 | vec.emplace_back(); 191 | } 192 | } 193 | 194 | ~TestBasicGuarantee() { throwCounter = 1000; } 195 | 196 | template 197 | void operator()(int insertCount, Operation const& op) { 198 | bool done = false; 199 | 200 | std::unique_ptr> workingVec; 201 | for (int counter = 1; !done; ++counter) { 202 | throwCounter = 1000; 203 | workingVec = std::make_unique>(vec); 204 | throwCounter = counter; 205 | EXPECT_EQ(Thrower::alive, prepopulate * 2); 206 | try { 207 | op(*workingVec); 208 | done = true; 209 | } catch (...) { 210 | // Note that the size of the vector can change if we were 211 | // inserting somewhere other than the end (it's a basic only 212 | // guarantee). All we're testing here is that we have the 213 | // right amount of uninitialized vs initialized memory. 214 | EXPECT_EQ(Thrower::alive, workingVec->size() + vec.size()); 215 | continue; 216 | } 217 | 218 | // If things succeeded. 219 | EXPECT_EQ(workingVec->size(), prepopulate + insertCount); 220 | EXPECT_EQ(Thrower::alive, prepopulate * 2 + insertCount); 221 | } 222 | } 223 | }; 224 | 225 | } // namespace 226 | 227 | TEST(small_vector, BasicGuarantee) { 228 | for (int prepop = 1; prepop < 30; ++prepop) { 229 | (TestBasicGuarantee(prepop))( // parens or a mildly vexing parse :( 230 | 1, [&](folly::small_vector& v) { v.emplace_back(); }); 231 | 232 | EXPECT_EQ(Thrower::alive, 0); 233 | 234 | (TestBasicGuarantee(prepop))(1, [&](folly::small_vector& v) { 235 | v.insert(v.begin(), Thrower()); 236 | }); 237 | 238 | EXPECT_EQ(Thrower::alive, 0); 239 | 240 | (TestBasicGuarantee(prepop))(1, [&](folly::small_vector& v) { 241 | v.insert(v.begin() + 1, Thrower()); 242 | }); 243 | 244 | EXPECT_EQ(Thrower::alive, 0); 245 | } 246 | 247 | TestBasicGuarantee(4)(3, [&](folly::small_vector& v) { 248 | std::vector b; 249 | b.emplace_back(); 250 | b.emplace_back(); 251 | b.emplace_back(); 252 | 253 | /* 254 | * Apparently if you do the following initializer_list instead 255 | * of the above push_back's, and one of the Throwers throws, 256 | * g++4.6 doesn't destruct the previous ones. Heh. 257 | */ 258 | // b = { Thrower(), Thrower(), Thrower() }; 259 | v.insert(v.begin() + 1, b.begin(), b.end()); 260 | }); 261 | 262 | TestBasicGuarantee(2)(6, [&](folly::small_vector& v) { 263 | std::vector b; 264 | for (int i = 0; i < 6; ++i) { 265 | b.emplace_back(); 266 | } 267 | 268 | v.insert(v.begin() + 1, b.begin(), b.end()); 269 | }); 270 | 271 | EXPECT_EQ(Thrower::alive, 0); 272 | try { 273 | throwCounter = 4; 274 | folly::small_vector p(14, Thrower()); 275 | } catch (...) { 276 | } 277 | EXPECT_EQ(Thrower::alive, 0); 278 | } 279 | 280 | // Run this with. 281 | // MALLOC_CONF=prof_leak:true 282 | // LD_PRELOAD=${JEMALLOC_PATH}/lib/libjemalloc.so.2 283 | // LD_PRELOAD="$LD_PRELOAD:"${UNWIND_PATH}/lib/libunwind.so.7 284 | TEST(small_vector, leak_test) { 285 | for (int j = 0; j < 1000; ++j) { 286 | folly::small_vector someVec(300); 287 | for (int i = 0; i < 10000; ++i) { 288 | someVec.push_back(12); 289 | } 290 | } 291 | } 292 | 293 | TEST(small_vector, InsertTrivial) { 294 | folly::small_vector someVec(3, 3); 295 | someVec.insert(someVec.begin(), 12, 12); 296 | EXPECT_EQ(someVec.size(), 15); 297 | for (size_t i = 0; i < someVec.size(); ++i) { 298 | if (i < 12) { 299 | EXPECT_EQ(someVec[i], 12); 300 | } else { 301 | EXPECT_EQ(someVec[i], 3); 302 | } 303 | } 304 | 305 | // Make sure we insert a larger range so we can test placement new 306 | // and move inserts 307 | auto oldSize = someVec.size(); 308 | someVec.insert(someVec.begin() + 1, 30, 30); 309 | EXPECT_EQ(someVec.size(), oldSize + 30); 310 | EXPECT_EQ(someVec[0], 12); 311 | EXPECT_EQ(someVec[1], 30); 312 | EXPECT_EQ(someVec[31], 12); 313 | } 314 | 315 | TEST(small_vector, InsertNontrivial) { 316 | folly::small_vector v1(6, "asd"), v2(7, "wat"); 317 | v1.insert(v1.begin() + 1, v2.begin(), v2.end()); 318 | EXPECT_TRUE(v1.size() == 6 + 7); 319 | EXPECT_EQ(v1.front(), "asd"); 320 | EXPECT_EQ(v1[1], "wat"); 321 | 322 | // Insert without default constructor 323 | class TestClass { 324 | public: 325 | // explicit TestClass() = default; 326 | explicit TestClass(std::string s_) : s(s_) {} 327 | std::string s; 328 | }; 329 | folly::small_vector v3(5, TestClass("asd")); 330 | folly::small_vector v4(10, TestClass("wat")); 331 | v3.insert(v3.begin() + 1, v4.begin(), v4.end()); 332 | EXPECT_TRUE(v3.size() == 5 + 10); 333 | EXPECT_EQ(v3[0].s, "asd"); 334 | EXPECT_EQ(v3[1].s, "wat"); 335 | EXPECT_EQ(v3[10].s, "wat"); 336 | EXPECT_EQ(v3[11].s, "asd"); 337 | } 338 | 339 | TEST(small_vecctor, InsertFromBidirectionalList) { 340 | folly::small_vector v(6, "asd"); 341 | std::list l(6, "wat"); 342 | v.insert(v.end(), l.begin(), l.end()); 343 | EXPECT_EQ(v[0], "asd"); 344 | EXPECT_EQ(v[5], "asd"); 345 | EXPECT_EQ(v[6], "wat"); 346 | EXPECT_EQ(v[11], "wat"); 347 | } 348 | 349 | TEST(small_vector, Swap) { 350 | folly::small_vector somethingVec, emptyVec; 351 | somethingVec.push_back(1); 352 | somethingVec.push_back(2); 353 | somethingVec.push_back(3); 354 | somethingVec.push_back(4); 355 | 356 | // Swapping intern'd with intern'd. 357 | auto vec = somethingVec; 358 | EXPECT_TRUE(vec == somethingVec); 359 | EXPECT_FALSE(vec == emptyVec); 360 | EXPECT_FALSE(somethingVec == emptyVec); 361 | 362 | // Swapping a heap vector with an intern vector. 363 | folly::small_vector junkVec; 364 | junkVec.assign(12, 12); 365 | EXPECT_EQ(junkVec.size(), 12); 366 | for (auto i : junkVec) { 367 | EXPECT_EQ(i, 12); 368 | } 369 | swap(junkVec, vec); 370 | EXPECT_TRUE(junkVec == somethingVec); 371 | EXPECT_EQ(vec.size(), 12); 372 | for (auto i : vec) { 373 | EXPECT_EQ(i, 12); 374 | } 375 | 376 | // Swapping two heap vectors. 377 | folly::small_vector moreJunk(15, 15); 378 | EXPECT_EQ(moreJunk.size(), 15); 379 | for (auto i : moreJunk) { 380 | EXPECT_EQ(i, 15); 381 | } 382 | swap(vec, moreJunk); 383 | EXPECT_EQ(moreJunk.size(), 12); 384 | for (auto i : moreJunk) { 385 | EXPECT_EQ(i, 12); 386 | } 387 | EXPECT_EQ(vec.size(), 15); 388 | for (auto i : vec) { 389 | EXPECT_EQ(i, 15); 390 | } 391 | 392 | // Making a vector heap, then smaller than another non-heap vector, 393 | // then swapping. 394 | folly::small_vector shrinker, other(4, 10); 395 | shrinker = {0, 1, 2, 3, 4, 5, 6, 7, 8}; 396 | shrinker.erase(shrinker.begin() + 2, shrinker.end()); 397 | EXPECT_LT(shrinker.size(), other.size()); 398 | swap(shrinker, other); 399 | EXPECT_EQ(shrinker.size(), 4); 400 | EXPECT_TRUE(boost::all(shrinker, boost::is_any_of(std::vector{10}))); 401 | EXPECT_TRUE((other == small_vector{0, 1})); 402 | } 403 | 404 | TEST(small_vector, Emplace) { 405 | NontrivialType::ctored = 0; 406 | 407 | folly::small_vector vec; 408 | vec.reserve(1024); 409 | { 410 | auto& emplaced = vec.emplace_back(12); 411 | EXPECT_EQ(NontrivialType::ctored, 1); 412 | EXPECT_EQ(vec.front().a, 12); 413 | EXPECT_TRUE(std::addressof(emplaced) == std::addressof(vec.back())); 414 | } 415 | { 416 | auto& emplaced = vec.emplace_back(13); 417 | EXPECT_EQ(vec.front().a, 12); 418 | EXPECT_EQ(vec.back().a, 13); 419 | EXPECT_EQ(NontrivialType::ctored, 2); 420 | EXPECT_TRUE(std::addressof(emplaced) == std::addressof(vec.back())); 421 | } 422 | 423 | NontrivialType::ctored = 0; 424 | for (int i = 0; i < 120; ++i) { 425 | auto& emplaced = vec.emplace_back(i); 426 | EXPECT_TRUE(std::addressof(emplaced) == std::addressof(vec.back())); 427 | } 428 | EXPECT_EQ(NontrivialType::ctored, 120); 429 | EXPECT_EQ(vec[0].a, 12); 430 | EXPECT_EQ(vec[1].a, 13); 431 | EXPECT_EQ(vec.back().a, 119); 432 | 433 | // We implement emplace() with a temporary (see the implementation 434 | // for a comment about why), so this should make 2 ctor calls. 435 | NontrivialType::ctored = 0; 436 | vec.emplace(vec.begin(), 12); 437 | EXPECT_EQ(NontrivialType::ctored, 2); 438 | } 439 | 440 | TEST(small_vector, Erase) { 441 | folly::small_vector notherVec = {1, 2, 3, 4, 5}; 442 | EXPECT_EQ(notherVec.front(), 1); 443 | EXPECT_EQ(notherVec.size(), 5); 444 | notherVec.erase(notherVec.begin()); 445 | EXPECT_EQ(notherVec.front(), 2); 446 | EXPECT_EQ(notherVec.size(), 4); 447 | EXPECT_EQ(notherVec[2], 4); 448 | EXPECT_EQ(notherVec[3], 5); 449 | notherVec.erase(notherVec.begin() + 2); 450 | EXPECT_EQ(notherVec.size(), 3); 451 | EXPECT_EQ(notherVec[2], 5); 452 | 453 | folly::small_vector vec2 = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; 454 | vec2.erase(vec2.begin() + 1, vec2.end() - 1); 455 | folly::small_vector expected = {1, 10}; 456 | EXPECT_TRUE(vec2 == expected); 457 | 458 | folly::small_vector v(102, "ASD"); 459 | v.resize(1024, "D"); 460 | EXPECT_EQ(v.size(), 1024); 461 | EXPECT_EQ(v.back(), "D"); 462 | EXPECT_EQ(v.front(), "ASD"); 463 | v.resize(1); 464 | EXPECT_EQ(v.front(), "ASD"); 465 | EXPECT_EQ(v.size(), 1); 466 | v.resize(0); 467 | EXPECT_TRUE(v.empty()); 468 | } 469 | 470 | TEST(small_vector, GrowShrinkGrow) { 471 | folly::small_vector vec = {1, 2, 3, 4, 5}; 472 | std::generate_n(std::back_inserter(vec), 102, std::rand); 473 | 474 | auto capacity = vec.capacity(); 475 | 476 | auto oldSize = vec.size(); 477 | for (size_t i = 0; i < oldSize; ++i) { 478 | vec.erase(vec.begin() + (std::rand() % vec.size())); 479 | EXPECT_EQ(vec.capacity(), capacity); 480 | } 481 | EXPECT_TRUE(vec.empty()); 482 | 483 | EXPECT_EQ(vec.capacity(), capacity); 484 | std::generate_n(std::back_inserter(vec), 102, std::rand); 485 | EXPECT_EQ(vec.capacity(), capacity); 486 | 487 | std::generate_n(std::back_inserter(vec), 4096, std::rand); 488 | EXPECT_GT(vec.capacity(), capacity); 489 | 490 | vec.resize(10); 491 | vec.shrink_to_fit(); 492 | EXPECT_LT(vec.capacity(), capacity); 493 | vec.resize(4); 494 | vec.shrink_to_fit(); 495 | EXPECT_EQ(vec.capacity(), 7); // in situ size 496 | } 497 | 498 | TEST(small_vector, Iteration) { 499 | folly::small_vector vec = {"foo", "bar"}; 500 | vec.push_back("blah"); 501 | vec.push_back("blah2"); 502 | vec.push_back("blah3"); 503 | vec.erase(vec.begin() + 2); 504 | 505 | std::vector otherVec; 506 | for (auto& s : vec) { 507 | otherVec.push_back(s); 508 | } 509 | EXPECT_EQ(otherVec.size(), vec.size()); 510 | if (otherVec.size() == vec.size()) { 511 | EXPECT_TRUE(std::equal(otherVec.begin(), otherVec.end(), vec.begin())); 512 | } 513 | 514 | std::reverse(otherVec.begin(), otherVec.end()); 515 | auto oit = otherVec.begin(); 516 | auto rit = vec.crbegin(); 517 | for (; rit != vec.crend(); ++oit, ++rit) { 518 | EXPECT_EQ(*oit, *rit); 519 | } 520 | } 521 | 522 | TEST(small_vector, NonCopyableType) { 523 | folly::small_vector vec; 524 | 525 | for (int i = 0; i < 10; ++i) { 526 | vec.emplace(vec.begin(), 13); 527 | } 528 | EXPECT_EQ(vec.size(), 10); 529 | auto vec2 = std::move(vec); 530 | EXPECT_EQ(vec.size(), 0); 531 | EXPECT_EQ(vec2.size(), 10); 532 | vec2.clear(); 533 | 534 | folly::small_vector vec3; 535 | for (int i = 0; i < 10; ++i) { 536 | EXPECT_EQ(vec3.size(), i); 537 | EXPECT_EQ(NoncopyableCounter::alive, i); 538 | vec3.insert(vec3.begin(), NoncopyableCounter()); 539 | } 540 | EXPECT_EQ(vec3.size(), 10); 541 | EXPECT_EQ(NoncopyableCounter::alive, 10); 542 | 543 | vec3.insert(vec3.begin() + 3, NoncopyableCounter()); 544 | EXPECT_EQ(NoncopyableCounter::alive, 11); 545 | auto vec4 = std::move(vec3); 546 | EXPECT_EQ(NoncopyableCounter::alive, 11); 547 | vec4.resize(30); 548 | EXPECT_EQ(NoncopyableCounter::alive, 30); 549 | vec4.erase(vec4.begin(), vec4.end()); 550 | EXPECT_EQ(vec4.size(), 0); 551 | EXPECT_EQ(NoncopyableCounter::alive, 0); 552 | } 553 | 554 | TEST(small_vector, MoveConstructor) { 555 | folly::small_vector v1; 556 | v1.push_back("asd"); 557 | v1.push_back("bsd"); 558 | auto v2 = std::move(v1); 559 | EXPECT_EQ(v2.size(), 2); 560 | EXPECT_EQ(v2[0], "asd"); 561 | EXPECT_EQ(v2[1], "bsd"); 562 | 563 | v1 = std::move(v2); 564 | EXPECT_EQ(v1.size(), 2); 565 | EXPECT_EQ(v1[0], "asd"); 566 | EXPECT_EQ(v1[1], "bsd"); 567 | } 568 | 569 | TEST(small_vector, NoHeap) { 570 | typedef folly::small_vector 572 | Vector; 573 | 574 | Vector v; 575 | static_assert(v.max_size() == 10, "max_size is incorrect"); 576 | 577 | for (int i = 0; i < 10; ++i) { 578 | v.push_back(folly::to(i)); 579 | EXPECT_EQ(v.size(), i + 1); 580 | } 581 | 582 | bool caught = false; 583 | try { 584 | v.insert(v.begin(), "ha"); 585 | } catch (const std::length_error&) { 586 | caught = true; 587 | } 588 | EXPECT_TRUE(caught); 589 | 590 | // Check max_size works right with various policy combinations. 591 | folly::small_vector v4; 592 | EXPECT_EQ(v4.max_size(), (1ul << 30) - 1); 593 | 594 | /* 595 | * Test that even when we ask for a small number inlined it'll still 596 | * inline at least as much as it takes to store the value_type 597 | * pointer. 598 | */ 599 | folly::small_vector notsosmall; 600 | static_assert(notsosmall.max_size() == sizeof(char*), 601 | "max_size is incorrect"); 602 | caught = false; 603 | try { 604 | notsosmall.push_back(12); 605 | notsosmall.push_back(13); 606 | notsosmall.push_back(14); 607 | } catch (const std::length_error&) { 608 | caught = true; 609 | } 610 | EXPECT_FALSE(caught); 611 | } 612 | 613 | TEST(small_vector, MaxSize) { 614 | folly::small_vector vec; 615 | EXPECT_EQ(vec.max_size(), 63); 616 | folly::small_vector vec2; 617 | EXPECT_EQ(vec2.max_size(), (1 << 14) - 1); 618 | } 619 | 620 | TEST(small_vector, AllHeap) { 621 | // Use something bigger than the pointer so it can't get inlined. 622 | struct SomeObj { 623 | double a, b, c, d, e; 624 | int val; 625 | SomeObj(int val_) : val(val_) {} 626 | bool operator==(SomeObj const& o) const { return o.val == val; } 627 | }; 628 | 629 | folly::small_vector vec = {1}; 630 | EXPECT_EQ(vec.size(), 1); 631 | if (!vec.empty()) { 632 | EXPECT_TRUE(vec[0] == 1); 633 | } 634 | vec.insert(vec.begin(), {0, 1, 2, 3}); 635 | EXPECT_EQ(vec.size(), 5); 636 | EXPECT_TRUE((vec == folly::small_vector{0, 1, 2, 3, 1})); 637 | } 638 | 639 | TEST(small_vector, Basic) { 640 | typedef folly::small_vector Vector; 641 | 642 | Vector a; 643 | 644 | a.push_back(12); 645 | EXPECT_EQ(a.front(), 12); 646 | EXPECT_EQ(a.size(), 1); 647 | a.push_back(13); 648 | EXPECT_EQ(a.size(), 2); 649 | EXPECT_EQ(a.front(), 12); 650 | EXPECT_EQ(a.back(), 13); 651 | 652 | a.emplace(a.end(), 32); 653 | EXPECT_EQ(a.back(), 32); 654 | 655 | a.emplace(a.begin(), 12); 656 | EXPECT_EQ(a.front(), 12); 657 | EXPECT_EQ(a.back(), 32); 658 | a.erase(a.end() - 1); 659 | EXPECT_EQ(a.back(), 13); 660 | 661 | a.push_back(12); 662 | EXPECT_EQ(a.back(), 12); 663 | a.pop_back(); 664 | EXPECT_EQ(a.back(), 13); 665 | 666 | const int s = 12; 667 | a.push_back(s); // lvalue reference 668 | 669 | Vector b, c; 670 | b = a; 671 | EXPECT_TRUE(b == a); 672 | c = std::move(b); 673 | EXPECT_TRUE(c == a); 674 | EXPECT_TRUE(c != b && b != a); 675 | 676 | EXPECT_GT(c.size(), 0); 677 | c.resize(1); 678 | EXPECT_EQ(c.size(), 1); 679 | 680 | Vector intCtor(12); 681 | } 682 | 683 | TEST(small_vector, Capacity) { 684 | folly::small_vector vec; 685 | EXPECT_EQ(vec.size(), 0); 686 | EXPECT_EQ(vec.capacity(), 1); 687 | 688 | vec.push_back(0); 689 | EXPECT_EQ(vec.size(), 1); 690 | EXPECT_EQ(vec.capacity(), 1); 691 | 692 | vec.push_back(1); 693 | EXPECT_EQ(vec.size(), 2); 694 | EXPECT_GT(vec.capacity(), 1); 695 | 696 | folly::small_vector vec2; 697 | EXPECT_EQ(vec2.size(), 0); 698 | EXPECT_EQ(vec2.capacity(), 2); 699 | 700 | vec2.push_back(0); 701 | vec2.push_back(1); 702 | EXPECT_EQ(vec2.size(), 2); 703 | EXPECT_EQ(vec2.capacity(), 2); 704 | 705 | vec2.push_back(2); 706 | EXPECT_EQ(vec2.size(), 3); 707 | EXPECT_GT(vec2.capacity(), 2); 708 | 709 | // Test capacity heapifying logic 710 | folly::small_vector vec3; 711 | const size_t hc_size = 100000; 712 | for (size_t i = 0; i < hc_size; ++i) { 713 | auto v = (unsigned char)i; 714 | vec3.push_back(v); 715 | EXPECT_EQ(vec3[i], v); 716 | EXPECT_EQ(vec3.size(), i + 1); 717 | EXPECT_GT(vec3.capacity(), i); 718 | } 719 | for (auto i = hc_size; i > 0; --i) { 720 | auto v = (unsigned char)(i - 1); 721 | EXPECT_EQ(vec3.back(), v); 722 | vec3.pop_back(); 723 | EXPECT_EQ(vec3.size(), i - 1); 724 | } 725 | } 726 | 727 | TEST(small_vector, SelfPushBack) { 728 | for (int i = 1; i < 33; ++i) { 729 | folly::small_vector vec; 730 | for (int j = 0; j < i; ++j) { 731 | vec.push_back("abc"); 732 | } 733 | EXPECT_EQ(vec.size(), i); 734 | vec.push_back(std::move(vec[0])); 735 | EXPECT_EQ(vec.size(), i + 1); 736 | 737 | EXPECT_EQ(vec[i], "abc"); 738 | } 739 | } 740 | 741 | TEST(small_vector, SelfEmplaceBack) { 742 | for (int i = 1; i < 33; ++i) { 743 | folly::small_vector vec; 744 | for (int j = 0; j < i; ++j) { 745 | vec.emplace_back("abc"); 746 | } 747 | EXPECT_EQ(vec.size(), i); 748 | vec.emplace_back(std::move(vec[0])); 749 | EXPECT_EQ(vec.size(), i + 1); 750 | 751 | EXPECT_EQ(vec[i], "abc"); 752 | } 753 | } 754 | 755 | TEST(small_vector, SelfInsert) { 756 | // end insert 757 | for (int i = 1; i < 33; ++i) { 758 | folly::small_vector vec; 759 | for (int j = 0; j < i; ++j) { 760 | vec.push_back("abc"); 761 | } 762 | EXPECT_EQ(vec.size(), i); 763 | vec.insert(vec.end(), std::move(vec[0])); 764 | EXPECT_EQ(vec.size(), i + 1); 765 | 766 | EXPECT_EQ(vec[i], "abc"); 767 | EXPECT_EQ(vec[vec.size() - 1], "abc"); 768 | } 769 | 770 | // middle insert 771 | for (int i = 2; i < 33; ++i) { 772 | folly::small_vector vec; 773 | for (int j = 0; j < i; ++j) { 774 | vec.push_back("abc"); 775 | } 776 | EXPECT_EQ(vec.size(), i); 777 | vec.insert(vec.end() - 1, std::move(vec[0])); 778 | EXPECT_EQ(vec.size(), i + 1); 779 | 780 | EXPECT_EQ(vec[i - 1], "abc"); 781 | EXPECT_EQ(vec[i], "abc"); 782 | } 783 | 784 | // range insert 785 | for (int i = 2; i < 33; ++i) { 786 | folly::small_vector vec; 787 | // reserve 2 * i space so we don't grow and invalidate references. 788 | vec.reserve(2 * i); 789 | for (int j = 0; j < i; ++j) { 790 | vec.push_back("abc"); 791 | } 792 | EXPECT_EQ(vec.size(), i); 793 | vec.insert(vec.end() - 1, vec.begin(), vec.end() - 1); 794 | EXPECT_EQ(vec.size(), 2 * i - 1); 795 | 796 | for (auto const& val : vec) { 797 | EXPECT_EQ(val, "abc"); 798 | } 799 | } 800 | } 801 | 802 | struct CheckedInt { 803 | static const int DEFAULT_VALUE = (int)0xdeadbeef; 804 | CheckedInt() : value(DEFAULT_VALUE) {} 805 | explicit CheckedInt(int value_) : value(value_) {} 806 | CheckedInt(const CheckedInt& rhs, int) : value(rhs.value) {} 807 | CheckedInt(const CheckedInt& rhs) : value(rhs.value) {} 808 | CheckedInt(CheckedInt&& rhs) noexcept : value(rhs.value) { 809 | rhs.value = DEFAULT_VALUE; 810 | } 811 | CheckedInt& operator=(const CheckedInt& rhs) { 812 | value = rhs.value; 813 | return *this; 814 | } 815 | CheckedInt& operator=(CheckedInt&& rhs) noexcept { 816 | value = rhs.value; 817 | rhs.value = DEFAULT_VALUE; 818 | return *this; 819 | } 820 | ~CheckedInt() {} 821 | int value; 822 | }; 823 | 824 | TEST(small_vector, ForwardingEmplaceInsideVector) { 825 | folly::small_vector v; 826 | v.push_back(CheckedInt(1)); 827 | for (int i = 1; i < 20; ++i) { 828 | v.emplace_back(v[0], 42); 829 | ASSERT_EQ(1, v.back().value); 830 | } 831 | } 832 | 833 | TEST(small_vector, LVEmplaceInsideVector) { 834 | folly::small_vector v; 835 | v.push_back(CheckedInt(1)); 836 | for (int i = 1; i < 20; ++i) { 837 | v.emplace_back(v[0]); 838 | ASSERT_EQ(1, v.back().value); 839 | } 840 | } 841 | 842 | TEST(small_vector, CLVEmplaceInsideVector) { 843 | folly::small_vector v; 844 | const folly::small_vector& cv = v; 845 | v.push_back(CheckedInt(1)); 846 | for (int i = 1; i < 20; ++i) { 847 | v.emplace_back(cv[0]); 848 | ASSERT_EQ(1, v.back().value); 849 | } 850 | } 851 | 852 | TEST(small_vector, RVEmplaceInsideVector) { 853 | folly::small_vector v; 854 | v.push_back(CheckedInt(0)); 855 | for (int i = 1; i < 20; ++i) { 856 | v[0] = CheckedInt(1); 857 | v.emplace_back(std::move(v[0])); 858 | ASSERT_EQ(1, v.back().value); 859 | } 860 | } 861 | 862 | TEST(small_vector, LVPushValueInsideVector) { 863 | folly::small_vector v; 864 | v.push_back(CheckedInt(1)); 865 | for (int i = 1; i < 20; ++i) { 866 | v.push_back(v[0]); 867 | ASSERT_EQ(1, v.back().value); 868 | } 869 | } 870 | 871 | TEST(small_vector, RVPushValueInsideVector) { 872 | folly::small_vector v; 873 | v.push_back(CheckedInt(0)); 874 | for (int i = 1; i < 20; ++i) { 875 | v[0] = CheckedInt(1); 876 | v.push_back(v[0]); 877 | ASSERT_EQ(1, v.back().value); 878 | } 879 | } 880 | 881 | TEST(small_vector, EmplaceIterCtor) { 882 | std::vector v{new int(1), new int(2)}; 883 | std::vector> uv(v.begin(), v.end()); 884 | 885 | std::vector w{new int(1), new int(2)}; 886 | small_vector> uw(w.begin(), w.end()); 887 | } 888 | 889 | TEST(small_vector, InputIterator) { 890 | std::vector expected{125, 320, 512, 750, 333}; 891 | std::string values = "125 320 512 750 333"; 892 | std::istringstream is1(values); 893 | std::istringstream is2(values); 894 | 895 | std::vector stdV{std::istream_iterator(is1), 896 | std::istream_iterator()}; 897 | ASSERT_EQ(stdV.size(), expected.size()); 898 | for (size_t i = 0; i < expected.size(); i++) { 899 | ASSERT_EQ(stdV[i], expected[i]); 900 | } 901 | 902 | small_vector smallV{std::istream_iterator(is2), 903 | std::istream_iterator()}; 904 | ASSERT_EQ(smallV.size(), expected.size()); 905 | for (size_t i = 0; i < expected.size(); i++) { 906 | ASSERT_EQ(smallV[i], expected[i]); 907 | } 908 | } 909 | 910 | TEST(small_vector, NoCopyCtor) { 911 | struct Tester { 912 | Tester() = default; 913 | Tester(const Tester&) = delete; 914 | Tester(Tester&&) = default; 915 | 916 | int field = 42; 917 | }; 918 | 919 | small_vector test(10); 920 | ASSERT_EQ(test.size(), 10); 921 | for (const auto& element : test) { 922 | EXPECT_EQ(element.field, 42); 923 | } 924 | } 925 | 926 | TEST(small_vector, ZeroInitializable) { 927 | small_vector test(10); 928 | ASSERT_EQ(test.size(), 10); 929 | for (const auto& element : test) { 930 | EXPECT_EQ(element, 0); 931 | } 932 | } 933 | 934 | TEST(small_vector, InsertMoreThanGrowth) { 935 | small_vector test; 936 | test.insert(test.end(), 30, 0); 937 | for (auto element : test) { 938 | EXPECT_EQ(element, 0); 939 | } 940 | } 941 | 942 | TEST(small_vector, EmplaceBackExponentialGrowth) { 943 | small_vector> test; 944 | std::vector capacities; 945 | capacities.push_back(test.capacity()); 946 | for (int i = 0; i < 10000; ++i) { 947 | test.emplace_back(0, 0); 948 | if (test.capacity() != capacities.back()) { 949 | capacities.push_back(test.capacity()); 950 | } 951 | } 952 | EXPECT_LE(capacities.size(), 25); 953 | } 954 | 955 | TEST(small_vector, InsertExponentialGrowth) { 956 | small_vector> test; 957 | std::vector capacities; 958 | capacities.push_back(test.capacity()); 959 | for (int i = 0; i < 10000; ++i) { 960 | test.insert(test.begin(), std::make_pair(0, 0)); 961 | if (test.capacity() != capacities.back()) { 962 | capacities.push_back(test.capacity()); 963 | } 964 | } 965 | EXPECT_LE(capacities.size(), 25); 966 | } 967 | 968 | TEST(small_vector, InsertNExponentialGrowth) { 969 | small_vector test; 970 | std::vector capacities; 971 | capacities.push_back(test.capacity()); 972 | for (int i = 0; i < 10000; ++i) { 973 | test.insert(test.begin(), 100, 0); 974 | if (test.capacity() != capacities.back()) { 975 | capacities.push_back(test.capacity()); 976 | } 977 | } 978 | EXPECT_LE(capacities.size(), 25); 979 | } 980 | 981 | namespace { 982 | struct Counts { 983 | size_t copyCount{0}; 984 | size_t moveCount{0}; 985 | }; 986 | 987 | class Counter { 988 | Counts* counts; 989 | 990 | public: 991 | explicit Counter(Counts& counts_) : counts(&counts_) {} 992 | Counter(Counter const& other) noexcept : counts(other.counts) { 993 | ++counts->copyCount; 994 | } 995 | Counter(Counter&& other) noexcept : counts(other.counts) { 996 | ++counts->moveCount; 997 | } 998 | Counter& operator=(Counter const& rhs) noexcept { 999 | EXPECT_EQ(counts, rhs.counts); 1000 | ++counts->copyCount; 1001 | return *this; 1002 | } 1003 | Counter& operator=(Counter&& rhs) noexcept { 1004 | EXPECT_EQ(counts, rhs.counts); 1005 | ++counts->moveCount; 1006 | return *this; 1007 | } 1008 | }; 1009 | } // namespace 1010 | 1011 | TEST(small_vector, EmplaceBackEfficiency) { 1012 | small_vector test; 1013 | Counts counts; 1014 | for (size_t i = 1; i <= test.capacity(); ++i) { 1015 | test.emplace_back(counts); 1016 | EXPECT_EQ(0, counts.copyCount); 1017 | EXPECT_EQ(0, counts.moveCount); 1018 | } 1019 | EXPECT_EQ(test.size(), test.capacity()); 1020 | test.emplace_back(counts); 1021 | // Every element except the last has to be moved to the new position 1022 | EXPECT_EQ(0, counts.copyCount); 1023 | EXPECT_EQ(test.size() - 1, counts.moveCount); 1024 | EXPECT_LT(test.size(), test.capacity()); 1025 | } 1026 | 1027 | TEST(small_vector, RVPushBackEfficiency) { 1028 | small_vector test; 1029 | Counts counts; 1030 | for (size_t i = 1; i <= test.capacity(); ++i) { 1031 | test.push_back(Counter(counts)); 1032 | // 1 copy for each push_back() 1033 | EXPECT_EQ(0, counts.copyCount); 1034 | EXPECT_EQ(i, counts.moveCount); 1035 | } 1036 | EXPECT_EQ(test.size(), test.capacity()); 1037 | test.push_back(Counter(counts)); 1038 | // 1 move for each push_back() 1039 | // Every element except the last has to be moved to the new position 1040 | EXPECT_EQ(0, counts.copyCount); 1041 | EXPECT_EQ(test.size() + test.size() - 1, counts.moveCount); 1042 | EXPECT_LT(test.size(), test.capacity()); 1043 | } 1044 | 1045 | TEST(small_vector, CLVPushBackEfficiency) { 1046 | small_vector test; 1047 | Counts counts; 1048 | Counter const counter(counts); 1049 | for (size_t i = 1; i <= test.capacity(); ++i) { 1050 | test.push_back(counter); 1051 | // 1 copy for each push_back() 1052 | EXPECT_EQ(i, counts.copyCount); 1053 | EXPECT_EQ(0, counts.moveCount); 1054 | } 1055 | EXPECT_EQ(test.size(), test.capacity()); 1056 | test.push_back(counter); 1057 | // 1 copy for each push_back() 1058 | EXPECT_EQ(test.size(), counts.copyCount); 1059 | // Every element except the last has to be moved to the new position 1060 | EXPECT_EQ(test.size() - 1, counts.moveCount); 1061 | EXPECT_LT(test.size(), test.capacity()); 1062 | } 1063 | 1064 | TEST(small_vector, StorageForSortedVectorMap) { 1065 | small_sorted_vector_map test; 1066 | test.insert(std::make_pair(10, 10)); 1067 | EXPECT_EQ(test.size(), 1); 1068 | test.insert(std::make_pair(10, 10)); 1069 | EXPECT_EQ(test.size(), 1); 1070 | test.insert(std::make_pair(20, 10)); 1071 | EXPECT_EQ(test.size(), 2); 1072 | test.insert(std::make_pair(30, 10)); 1073 | EXPECT_EQ(test.size(), 3); 1074 | } 1075 | 1076 | TEST(small_vector, NoHeapStorageForSortedVectorMap) { 1077 | noheap_sorted_vector_map test; 1078 | test.insert(std::make_pair(10, 10)); 1079 | EXPECT_EQ(test.size(), 1); 1080 | test.insert(std::make_pair(10, 10)); 1081 | EXPECT_EQ(test.size(), 1); 1082 | test.insert(std::make_pair(20, 10)); 1083 | EXPECT_EQ(test.size(), 2); 1084 | EXPECT_THROW(test.insert(std::make_pair(30, 10)), std::length_error); 1085 | EXPECT_EQ(test.size(), 2); 1086 | } 1087 | 1088 | TEST(small_vector, StorageForSortedVectorSet) { 1089 | small_sorted_vector_set test; 1090 | test.insert(10); 1091 | EXPECT_EQ(test.size(), 1); 1092 | test.insert(10); 1093 | EXPECT_EQ(test.size(), 1); 1094 | test.insert(20); 1095 | EXPECT_EQ(test.size(), 2); 1096 | test.insert(30); 1097 | EXPECT_EQ(test.size(), 3); 1098 | } 1099 | 1100 | TEST(small_vector, NoHeapStorageForSortedVectorSet) { 1101 | noheap_sorted_vector_set test; 1102 | test.insert(10); 1103 | EXPECT_EQ(test.size(), 1); 1104 | test.insert(10); 1105 | EXPECT_EQ(test.size(), 1); 1106 | test.insert(20); 1107 | EXPECT_EQ(test.size(), 2); 1108 | EXPECT_THROW(test.insert(30), std::length_error); 1109 | EXPECT_EQ(test.size(), 2); 1110 | } 1111 | 1112 | TEST(small_vector, SelfMoveAssignmentForVectorOfPair) { 1113 | folly::small_vector, 2> test; 1114 | test.emplace_back(13, 2); 1115 | EXPECT_EQ(test.size(), 1); 1116 | EXPECT_EQ(test[0].first, 13); 1117 | test = static_cast(test); // suppress self-move warning 1118 | EXPECT_EQ(test.size(), 1); 1119 | EXPECT_EQ(test[0].first, 13); 1120 | } 1121 | 1122 | TEST(small_vector, SelfCopyAssignmentForVectorOfPair) { 1123 | folly::small_vector, 2> test; 1124 | test.emplace_back(13, 2); 1125 | EXPECT_EQ(test.size(), 1); 1126 | EXPECT_EQ(test[0].first, 13); 1127 | test = static_cast(test); // suppress self-assign warning 1128 | EXPECT_EQ(test.size(), 1); 1129 | EXPECT_EQ(test[0].first, 13); 1130 | } 1131 | 1132 | namespace { 1133 | struct NonAssignableType { 1134 | int const i_{}; 1135 | }; 1136 | } // namespace 1137 | 1138 | TEST(small_vector, PopBackNonAssignableType) { 1139 | small_vector v; 1140 | v.emplace_back(); 1141 | EXPECT_EQ(1, v.size()); 1142 | v.pop_back(); 1143 | EXPECT_EQ(0, v.size()); 1144 | } 1145 | 1146 | TEST(small_vector, erase) { 1147 | small_vector v(3); 1148 | std::iota(v.begin(), v.end(), 1); 1149 | v.push_back(2); 1150 | erase(v, 2); 1151 | ASSERT_EQ(2u, v.size()); 1152 | EXPECT_EQ(1u, v[0]); 1153 | EXPECT_EQ(3u, v[1]); 1154 | } 1155 | 1156 | TEST(small_vector, erase_if) { 1157 | small_vector v(6); 1158 | std::iota(v.begin(), v.end(), 1); 1159 | erase_if(v, [](const auto& x) { return x % 2 == 0; }); 1160 | ASSERT_EQ(3u, v.size()); 1161 | EXPECT_EQ(1u, v[0]); 1162 | EXPECT_EQ(3u, v[1]); 1163 | EXPECT_EQ(5u, v[2]); 1164 | } 1165 | 1166 | namespace { 1167 | 1168 | class NonTrivialInt { 1169 | public: 1170 | NonTrivialInt() {} 1171 | /* implicit */ NonTrivialInt(int value) 1172 | : value_(std::make_shared(value)) {} 1173 | 1174 | operator int() const { return *value_; } 1175 | 1176 | private: 1177 | std::shared_ptr value_; 1178 | }; 1179 | 1180 | // Move and copy constructor and assignment have several special cases depending 1181 | // on relative sizes, so test all combinations. 1182 | template 1183 | void testMoveAndCopy() { 1184 | const auto fill = [](auto& v, size_t n) { 1185 | v.resize(n); 1186 | std::iota(v.begin(), v.end(), 0); 1187 | }; 1188 | const auto verify = [](const auto& v, size_t n) { 1189 | ASSERT_EQ(v.size(), n); 1190 | for (size_t i = 0; i < n; ++i) { 1191 | EXPECT_EQ(v[i], i); 1192 | } 1193 | }; 1194 | 1195 | using Vec = small_vector; 1196 | SCOPED_TRACE(fmt::format("N = {}", N)); 1197 | 1198 | const size_t kMinCapacity = Vec{}.capacity(); 1199 | 1200 | for (size_t from = 0; from < 16; ++from) { 1201 | SCOPED_TRACE(fmt::format("from = {}", from)); 1202 | 1203 | { 1204 | SCOPED_TRACE("Move-construction"); 1205 | Vec a; 1206 | fill(a, from); 1207 | const auto aCapacity = a.capacity(); 1208 | Vec b = std::move(a); 1209 | verify(b, from); 1210 | EXPECT_EQ(b.capacity(), aCapacity); 1211 | verify(a, 0); 1212 | EXPECT_EQ(a.capacity(), kMinCapacity); 1213 | } 1214 | { 1215 | SCOPED_TRACE("Copy-construction"); 1216 | Vec a; 1217 | fill(a, from); 1218 | Vec b = a; 1219 | verify(b, from); 1220 | verify(a, from); 1221 | } 1222 | 1223 | for (size_t to = 0; to < 16; ++to) { 1224 | SCOPED_TRACE(fmt::format("to = {}", to)); 1225 | { 1226 | SCOPED_TRACE("Move-assignment"); 1227 | Vec a; 1228 | fill(a, from); 1229 | Vec b; 1230 | fill(b, to); 1231 | 1232 | const auto aCapacity = a.capacity(); 1233 | b = std::move(a); 1234 | verify(b, from); 1235 | EXPECT_EQ(b.capacity(), aCapacity); 1236 | verify(a, 0); 1237 | EXPECT_EQ(a.capacity(), kMinCapacity); 1238 | } 1239 | { 1240 | SCOPED_TRACE("Copy-assignment"); 1241 | Vec a; 1242 | fill(a, from); 1243 | Vec b; 1244 | fill(b, to); 1245 | 1246 | b = a; 1247 | verify(b, from); 1248 | verify(a, from); 1249 | } 1250 | { 1251 | SCOPED_TRACE("swap"); 1252 | Vec a; 1253 | fill(a, from); 1254 | Vec b; 1255 | fill(b, to); 1256 | 1257 | const auto aCapacity = a.capacity(); 1258 | const auto bCapacity = b.capacity(); 1259 | swap(a, b); 1260 | verify(b, from); 1261 | EXPECT_EQ(b.capacity(), aCapacity); 1262 | verify(a, to); 1263 | EXPECT_EQ(a.capacity(), bCapacity); 1264 | } 1265 | } 1266 | } 1267 | } 1268 | 1269 | } // namespace 1270 | 1271 | TEST(small_vector, MoveAndCopyTrivial) { 1272 | testMoveAndCopy(); 1273 | // Capacity does not fit inline. 1274 | testMoveAndCopy(); 1275 | // Capacity does fits inline. 1276 | testMoveAndCopy(); 1277 | } 1278 | 1279 | TEST(small_vector, MoveAndCopyNonTrivial) { 1280 | testMoveAndCopy(); 1281 | testMoveAndCopy(); 1282 | } 1283 | --------------------------------------------------------------------------------