4 Star 2 Fork 2

alibaba / yalantinglibs

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

yaLanTingLibs

A Collection of C++20 libraries, include struct_pack, struct_json, struct_xml, struct_yaml, struct_pb, easylog, coro_rpc, coro_http and async_simple

license language last commit

中文版

yaLanTingLibs is a collection of modern c++ util libraries, now it contains struct_pack, struct_json, struct_xml, struct_yaml, struct_pb, easylog, coro_rpc, coro_io, coro_http and async_simple, more and more cool libraries will be added into yaLanTingLibs in the future.

The target of yaLanTingLibs: provide very easy and high performance modern C++ libraries for developers, it can help to quickly build high performance applications.

OS (Compiler Version) Status
Ubuntu 22.04 (clang 14.0.0) ubuntu-clang
Ubuntu 22.04 (gcc 11.2.0) ubuntu-gcc
macOS Monterey 12 (AppleClang 14.0.0.14000029) macos-clang
Windows Server 2022 (MSVC 19.33.31630.0) win-msvc

Quick Start

compiler requirements

If your compiler don't support C++20, yalantinglibs will only compile the serialization libraries (struct_pack, struct_json, struct_xml, struct_yaml, easylog support C++17). Make sure you have such compilers:

  • g++9 above;
  • clang++6 above
  • msvc 14.20 above;

Otherwise, yalantinglibs will compile all the libraries. Make sure you have such compilers:

  • g++10 above;
  • clang++13 above
  • msvc 14.29 above;

You can also use cmake option -DENABLE_CPP_20=ON or -DENABLE_CPP_20=OFF to control it.

Install & Compile

Yalantinglibs is a head-only library. You can just copy ./include/ylt directory into your project. But we suggest you use cmake to install it.

Install

  1. clone repo
git clone https://github.com/alibaba/yalantinglibs.git
cd yalantinglibs
mkdir build
cd build
  1. build & test
  • We suggest you compile the example and test the code first:
cmake ..
cmake --build . --config debug # add -j, if you have enough memory to parallel compile
ctest . # run tests
  • Build in bazel:
bazel build ylt # Please make sure bazel in you bin path.
bazel build coro_http_example # Or replace in anyone you want to build and test.
# Actually you might take it in other project in prefix @com_alibaba_yalangtinglibs, like
bazel build @com_alibaba_yalangtinglibs://ylt

You can see the test/example/benchmark executable file in ./build/output/.

  • Or you can just skip build example/test/benchmark:
# You can use those option to skip build unit-test & benchmark & example: 
cmake .. -DBUILD_EXAMPLES=OFF -DBUILD_BENCHMARK=OFF -DBUILD_UNIT_TESTS=OFF
  1. install
cmake --install . # --prefix ./user_defined_install_path 
  1. start develop
  • Use Cmake:

After install ylt, copy then open the directory src/*/examples, then:

mkdir build
cd build
cmake ..
cmake --build .

Cmake FetchContent

You can also import ylt by cmake FetchContent

cmake_minimum_required(VERSION 3.15)
project(ylt_test)

include(FetchContent)

FetchContent_Declare(
    yalantinglibs
    GIT_REPOSITORY https://github.com/JYLeeLYJ/yalantinglibs.git
    GIT_TAG feat/fetch # optional ( default master / main )
    GIT_SHALLOW 1 # optional ( --depth=1 )
)

FetchContent_MakeAvailable(yalantinglibs)
add_executable(main main.cpp)

target_link_libraries(main yalantinglibs::yalantinglibs)
target_compile_features(main PRIVATE cxx_std_20)

Compile Manually:

  1. Add include/ directory to include path(skip it if you have install ylt into default include path).
  2. Add include/ylt/thirdparty to include path(skip it if you have install ylt by cmake).
  3. Add include/ylt/standalone to include path(skip it if you have install ylt by cmake).
  4. Enable c++20 standard by option -std=c++20(g++/clang++) or /std:c++20(msvc)
  5. If you use any header with coro_ prefix, add link option -pthread in linux, add option -fcoroutines when you use g++10.

More Details:

For more details, see the cmake file here and there.

Introduction

coro_rpc

Very easy-to-use, coroutine-based, high performance rpc framework with C++20, more than 0.4M QPS per thread in pipeline mode. coro_rpc is a header only library.

You can finish a rpc server and rpc client in 5 minutes!

English Introduction

[English API] (TODO)

Talk (Chinese) of coro_rpc on purecpp conference.

Video (Chinese) on purecpp conference, start from 04:55:08 of the video record.

quick example

1.define a rpc function as a local normal function.

// rpc_service.hpp
inline std::string_view echo(std::string_view str) { return str; }

2.register rpc function and start a server

#include "rpc_service.hpp"
#include <ylt/coro_rpc/coro_rpc_server.hpp>

int main() {
  coro_rpc_server server(/*thread_num =*/10, /*port =*/9000);
  server.register_handler<echo>(); // register function echo
  server.start(); // start the server & block
}

3.rpc client call rpc service

#include "rpc_service.hpp"
#include <ylt/coro_rpc/coro_rpc_client.hpp>

Lazy<void> test_client() {
  coro_rpc_client client;
  co_await client.connect("localhost", /*port =*/"9000"); // connect to the server

  auto r = co_await client.call<echo>("hello coro_rpc"); // call remote function echo
  std::cout << r.result.value() << "\n"; //will print "hello coro_rpc"
}

int main() {
  syncAwait(test_client());
}

More examples here.

struct_pack

Based on compile-time reflection, very easy to use, high performance serialization library, struct_pack is a header only library, it is used by coro_rpc now.

Only one line code to finish serialization and deserialization, 2-20x faster than protobuf.

quick example

struct person {
  int64_t id;
  std::string name;
  int age;
  double salary;
};

person person1{.id = 1, .name = "hello struct pack", .age = 20, .salary = 1024.42};

// one line code serialize
std::vector<char> buffer = struct_pack::serialize(person1);

// one line code deserialization
auto person2 = deserialize<person>(buffer);

struct_pack is very fast.

English Introduction

[English API] (TODO)

(Slides) A Faster Serialization Library Based on Compile-time Reflection and C++ 20 of struct_pack on CppCon2022

(Video) A Faster Serialization Library Based on Compile-time Reflection and C++ 20 on cppcon2022

(Slides)(Chinese) of struct_pack on purecpp conference.

(Video)(Chinese) on purecpp conference, start from 01:32:20 of the video record.

See more examples here.

struct_json

reflection-based json lib, very easy to do struct to json and json to struct.

quick example

#include "ylt/struct_json/json_reader.h"
#include "ylt/struct_json/json_writer.h"

struct person {
  std::string name;
  int age;
};
REFLECTION(person, name, age);

int main() {
  person p{.name = "tom", .age = 20};
  std::string str;
  struct_json::to_json(p, str); // {"name":"tom","age":20}

  person p1;
  struct_json::from_json(p1, str);
}

struct_xml

reflection-based xml lib, very easy to do struct to xml and xml to struct.

quick example

#include "ylt/struct_xml/xml_reader.h"
#include "ylt/struct_xml/xml_writer.h"

struct person {
  std::string name;
  int age;
};
REFLECTION(person, name, age);

void basic_usage() {
  std::string xml = R"(
<person>
    <name>tom</name>
    <age>20</age>
</person>
)";

  person p;
  bool r = struct_xml::from_xml(p, xml.data());
  assert(r);
  assert(p.name == "tom" && p.age == 20);

  std::string str;
  r = struct_xml::to_xml_pretty(p, str);
  assert(r);
  std::cout << str;
}

struct_yaml

reflection-based yaml lib, very easy to do struct to yaml and yaml to struct.

quick example

#include "ylt/struct_yaml/yaml_reader.h"
#include "ylt/struct_yaml/yaml_writer.h"

struct person {
  std::string name;
  int age;
};
REFLECTION(person, name, age);

void basic_usage() {
    // serialization the structure to the string
    person p = {"admin", 20};
    std::string ss;
    struct_yaml::to_yaml(ss, p);
    std::cout << ss << std::endl;
    
    std::string yaml = R"(
    name : tom
    age : 30
    )";
    
    // deserialization the structure from the string
    struct_yaml::from_yaml(p, yaml);
}

coro_http

coro_http is a C++20 coroutine http(https) library, include server and client, functions: get/post, websocket, multipart file upload, chunked and ranges download etc. more examples

get/post

#include "ylt/coro_http/coro_http_server.hpp"
#include "ylt/coro_http/coro_http_client.hpp"
using namespace coro_http;

async_simple::coro::Lazy<void> basic_usage() {
  coro_http_server server(1, 9001);
  server.set_http_handler<GET>(
      "/get", [](coro_http_request &req, coro_http_response &resp) {
        resp.set_status_and_content(status_type::ok, "ok");
      });

  server.set_http_handler<GET>(
      "/coro",
      [](coro_http_request &req,
         coro_http_response &resp) -> async_simple::coro::Lazy<void> {
        resp.set_status_and_content(status_type::ok, "ok");
        co_return;
      });
  server.aync_start(); // aync_start() don't block, sync_start() will block.
  std::this_thread::sleep_for(300ms);  // wait for server start

  coro_http_client client{};
  auto result = co_await client.async_get("http://127.0.0.1:9001/get");
  assert(result.status == 200);
  assert(result.resp_body == "ok");
  for (auto [key, val] : result.resp_headers) {
    std::cout << key << ": " << val << "\n";
  }
}

async_simple::coro::Lazy<void> get_post(coro_http_client &client) {
  std::string uri = "http://www.example.com";
  auto result = co_await client.async_get(uri);
  std::cout << result.status << "\n";
  
  result = co_await client.async_post(uri, "hello", req_content_type::string);
  std::cout << result.status << "\n";
}

int main() {
  coro_http_client client{};
  async_simple::coro::syncAwait(get_post(client));
}

websocket

async_simple::coro::Lazy<void> websocket(coro_http_client &client) {
  // connect to your websocket server.
  bool r = co_await client.async_connect("ws://example.com/ws");
  if (!r) {
    co_return;
  }

  co_await client.write_websocket("hello websocket");
  auto data = co_await client.read_websocket();
  CHECK(data.resp_body == "hello websocket");
  co_await client.write_websocket("test again");
  data = co_await client.read_websocket();
  CHECK(data.resp_body == "test again");
  co_await client.write_websocket("ws close");
  data = co_await client.read_websocket();
  CHECK(data.net_err == asio::error::eof);
  CHECK(data.resp_body == "ws close");
}

upload/download

async_simple::coro::Lazy<void> upload_files(coro_http_client &client) {
  std::string uri = "http://example.com";
  
  client.add_str_part("hello", "world");
  client.add_str_part("key", "value");
  client.add_file_part("test", "test.jpg");
  auto result = co_await client.async_upload(uri);
  std::cout << result.status << "\n";
  
  result = co_await client.async_upload(uri, "test", "test.jpg");
}

async_simple::coro::Lazy<void> download_files(coro_http_client &client) {
  // chunked download
  auto result = co_await client.async_download("http://example.com/test.jpg",
                                               "myfile.jpg");
  std::cout << result.status << "\n";
  
  // ranges download
  result = co_await client.async_download("http://example.com/test.txt",
                                               "myfile.txt", "1-10,11-16");
  std::cout << result.status << "\n";
}

async_simple

A C++ 20 coroutine library offering simple, light-weight and easy-to-use components to write asynchronous codes. See async_simple

Details

CMAKE OPTION

config option

These option maybe useful for your project. You can enable it in your project if you import ylt by cmake fetchContent or find_package.

option default value description
YLT_ENABLE_SSL OFF enable optional ssl support for rpc/http
YLT_ENABLE_PMR OFF enable pmr optimize
YLT_ENABLE_IO_URING OFF enable io_uring in linux
YLT_ENABLE_FILE_IO_URING OFF enable file io_uring as backend in linux
YLT_ENABLE_STRUCT_PACK_UNPORTABLE_TYPE OFF enable unportable type(like wstring, int128_t) for struct_pack
YLT_ENABLE_STRUCT_PACK_OPTIMIZE OFF optimize struct_pack by radical template unwinding(will cost more compile time)

installation option

In default, yalantinglibs will install thirdparty librarys and standalone sublibrarires in your install path independently.

If you don't want to install the thirdparty librarys(you need install it manually), you can turn off cmake option -DINSTALL_THIRDPARTY=OFF.

If you want to install the thirdparty dependently. (install thirdparty librarys and standalone sublibrarires in ylt/thirdparty and ylt/standalone ), you can use turn off cmake option -DINSTALL_INDEPENDENT_THIRDPARTY=OFF and -DINSTALL_INDEPENDENT_STANDALONE=OFF.

option default value
INSTALL_THIRDPARTY ON
INSTALL_STANDALONE ON
INSTALL_INDEPENDENT_THIRDPARTY ON
INSTALL_INDEPENDENT_STANDALONE ON

Those options only work in installation.

develop option

These CMake options is used for yalantinglibs developing/installing itself. They are not effected for your project, because ylt is a head-only.

option default value
BUILD_EXAMPLES ON
BUILD_BENCHMARK ON
BUILD_UNIT_TESTS ON
BUILD_*(BUILD_CORO_RPC, BUILD_STRUCT_PACK etc) ON
COVERAGE_TEST OFF
GENERATE_BENCHMARK_DATA ON
CORO_RPC_USE_OTHER_RPC ON

Thirdparty Dependency List

Here are the thirdparty libraries we used(Although async_simple is a part of ylt, it open source first, so we import it as a independence thirdparty library).

coro_io/coro_rpc/coro_http

Those dependency will by install by default. you can control it by cmake option.

easylog

No dependency.

struct_pack, struct_json, struct_xml, struct_yaml

No dependency.

struct_pb (optional)

In default, struct_pb wont be installed. You need install protobuf manually.

Standalone sublibraries

coro_http is implemented by a standalone sublibrary cinatra

struct_json、struct_xml、struct_yaml are implemented by a standalone sublibrary iguana

Benchmark

coro_rpc

options:

./benchmark_client # [threads = hardware counts] [client_pre_thread = 20] [pipeline_size = 1] [host = 127.0.0.1] [port = 9000] [test_data_path = ./test_data/echo_test] [test_seconds = 30] [warm_up_seconds = 5]

How to generate document

see Build Website

How to Contribute

  1. Create an issue in the issue template.
  2. Run tests and git-clang-format HEAD^ locally for the change.
  3. Create a PR, fill in the PR template.
  4. Choose one or more reviewers from contributors: (e.g., qicosmos, poor-circle, PikachuHyA).
  5. Get approved and merged.

Discussion group

DingTalk group id: 645010455

License

yaLanTingLibs is distributed under the Apache License (Version 2.0) This product contains various third-party components under other open-source licenses. See the NOTICE file for more information.

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

暂无描述 展开 收起
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/mirrors_alibaba/yalantinglibs.git
git@gitee.com:mirrors_alibaba/yalantinglibs.git
mirrors_alibaba
yalantinglibs
yalantinglibs
main

搜索帮助