From 2a01ff5fb140eca5c6159982a75df5a9123f0e6d Mon Sep 17 00:00:00 2001
From: Lizonghang <870644199@qq.com>
Date: Wed, 23 Oct 2024 09:42:32 +0400
Subject: [PATCH] init
---
Makefile | 8 +
README.md | 480 +------
common/arg.cpp | 35 +
common/common.cpp | 65 +-
common/common.h | 8 +-
examples/main/main.cpp | 233 ++--
include/llama.h | 23 +-
include/zmq.hpp | 2796 ++++++++++++++++++++++++++++++++++++++++
include/zmq_addon.hpp | 848 ++++++++++++
src/llama.cpp | 1255 ++++++++++++------
10 files changed, 4725 insertions(+), 1026 deletions(-)
create mode 100644 include/zmq.hpp
create mode 100644 include/zmq_addon.hpp
diff --git a/Makefile b/Makefile
index 2793978c..4bd59eb5 100644
--- a/Makefile
+++ b/Makefile
@@ -262,6 +262,14 @@ MK_CFLAGS = -std=c11 -fPIC
MK_CXXFLAGS = -std=c++11 -fPIC
MK_NVCCFLAGS = -std=c++11
+ifeq ($(UNAME_S),Darwin)
+ MK_CPPFLAGS += -I/opt/homebrew/include
+ MK_LDFLAGS += -L/opt/homebrew/lib -lzmq
+else ifeq ($(UNAME_S),Linux)
+ MK_CPPFLAGS += -I/usr/local/include
+ MK_LDFLAGS += -L/usr/local/lib -lzmq
+endif
+
ifdef LLAMA_NO_CCACHE
GGML_NO_CCACHE := 1
DEPRECATE_WARNING := 1
diff --git a/README.md b/README.md
index 41e5e544..cbbd7d55 100644
--- a/README.md
+++ b/README.md
@@ -1,479 +1,3 @@
-# llama.cpp
+# prima.cpp
-
-
-[](https://opensource.org/licenses/MIT)
-[](https://github.com/ggerganov/llama.cpp/actions/workflows/server.yml)
-[](https://conan.io/center/llama-cpp)
-
-[Roadmap](https://github.com/users/ggerganov/projects/7) / [Project status](https://github.com/ggerganov/llama.cpp/discussions/3471) / [Manifesto](https://github.com/ggerganov/llama.cpp/discussions/205) / [ggml](https://github.com/ggerganov/ggml)
-
-Inference of Meta's [LLaMA](https://arxiv.org/abs/2302.13971) model (and others) in pure C/C++
-
-## Recent API changes
-
-- [Changelog for `libllama` API](https://github.com/ggerganov/llama.cpp/issues/9289)
-- [Changelog for `llama-server` REST API](https://github.com/ggerganov/llama.cpp/issues/9291)
-
-## Hot topics
-
-- **Hugging Face Inference Endpoints now support GGUF out of the box! https://github.com/ggerganov/llama.cpp/discussions/9669**
-- Hugging Face GGUF editor: [discussion](https://github.com/ggerganov/llama.cpp/discussions/9268) | [tool](https://huggingface.co/spaces/CISCai/gguf-editor)
-
-----
-
-## Description
-
-The main goal of `llama.cpp` is to enable LLM inference with minimal setup and state-of-the-art performance on a wide
-variety of hardware - locally and in the cloud.
-
-- Plain C/C++ implementation without any dependencies
-- Apple silicon is a first-class citizen - optimized via ARM NEON, Accelerate and Metal frameworks
-- AVX, AVX2 and AVX512 support for x86 architectures
-- 1.5-bit, 2-bit, 3-bit, 4-bit, 5-bit, 6-bit, and 8-bit integer quantization for faster inference and reduced memory use
-- Custom CUDA kernels for running LLMs on NVIDIA GPUs (support for AMD GPUs via HIP)
-- Vulkan and SYCL backend support
-- CPU+GPU hybrid inference to partially accelerate models larger than the total VRAM capacity
-
-Since its [inception](https://github.com/ggerganov/llama.cpp/issues/33#issuecomment-1465108022), the project has
-improved significantly thanks to many contributions. It is the main playground for developing new features for the
-[ggml](https://github.com/ggerganov/ggml) library.
-
-**Supported models:**
-
-Typically finetunes of the base models below are supported as well.
-
-- [X] LLaMA π¦
-- [x] LLaMA 2 π¦π¦
-- [x] LLaMA 3 π¦π¦π¦
-- [X] [Mistral 7B](https://huggingface.co/mistralai/Mistral-7B-v0.1)
-- [x] [Mixtral MoE](https://huggingface.co/models?search=mistral-ai/Mixtral)
-- [x] [DBRX](https://huggingface.co/databricks/dbrx-instruct)
-- [X] [Falcon](https://huggingface.co/models?search=tiiuae/falcon)
-- [X] [Chinese LLaMA / Alpaca](https://github.com/ymcui/Chinese-LLaMA-Alpaca) and [Chinese LLaMA-2 / Alpaca-2](https://github.com/ymcui/Chinese-LLaMA-Alpaca-2)
-- [X] [Vigogne (French)](https://github.com/bofenghuang/vigogne)
-- [X] [BERT](https://github.com/ggerganov/llama.cpp/pull/5423)
-- [X] [Koala](https://bair.berkeley.edu/blog/2023/04/03/koala/)
-- [X] [Baichuan 1 & 2](https://huggingface.co/models?search=baichuan-inc/Baichuan) + [derivations](https://huggingface.co/hiyouga/baichuan-7b-sft)
-- [X] [Aquila 1 & 2](https://huggingface.co/models?search=BAAI/Aquila)
-- [X] [Starcoder models](https://github.com/ggerganov/llama.cpp/pull/3187)
-- [X] [Refact](https://huggingface.co/smallcloudai/Refact-1_6B-fim)
-- [X] [MPT](https://github.com/ggerganov/llama.cpp/pull/3417)
-- [X] [Bloom](https://github.com/ggerganov/llama.cpp/pull/3553)
-- [x] [Yi models](https://huggingface.co/models?search=01-ai/Yi)
-- [X] [StableLM models](https://huggingface.co/stabilityai)
-- [x] [Deepseek models](https://huggingface.co/models?search=deepseek-ai/deepseek)
-- [x] [Qwen models](https://huggingface.co/models?search=Qwen/Qwen)
-- [x] [PLaMo-13B](https://github.com/ggerganov/llama.cpp/pull/3557)
-- [x] [Phi models](https://huggingface.co/models?search=microsoft/phi)
-- [x] [GPT-2](https://huggingface.co/gpt2)
-- [x] [Orion 14B](https://github.com/ggerganov/llama.cpp/pull/5118)
-- [x] [InternLM2](https://huggingface.co/models?search=internlm2)
-- [x] [CodeShell](https://github.com/WisdomShell/codeshell)
-- [x] [Gemma](https://ai.google.dev/gemma)
-- [x] [Mamba](https://github.com/state-spaces/mamba)
-- [x] [Grok-1](https://huggingface.co/keyfan/grok-1-hf)
-- [x] [Xverse](https://huggingface.co/models?search=xverse)
-- [x] [Command-R models](https://huggingface.co/models?search=CohereForAI/c4ai-command-r)
-- [x] [SEA-LION](https://huggingface.co/models?search=sea-lion)
-- [x] [GritLM-7B](https://huggingface.co/GritLM/GritLM-7B) + [GritLM-8x7B](https://huggingface.co/GritLM/GritLM-8x7B)
-- [x] [OLMo](https://allenai.org/olmo)
-- [x] [OLMoE](https://huggingface.co/allenai/OLMoE-1B-7B-0924)
-- [x] [Granite models](https://huggingface.co/collections/ibm-granite/granite-code-models-6624c5cec322e4c148c8b330)
-- [x] [GPT-NeoX](https://github.com/EleutherAI/gpt-neox) + [Pythia](https://github.com/EleutherAI/pythia)
-- [x] [Snowflake-Arctic MoE](https://huggingface.co/collections/Snowflake/arctic-66290090abe542894a5ac520)
-- [x] [Smaug](https://huggingface.co/models?search=Smaug)
-- [x] [Poro 34B](https://huggingface.co/LumiOpen/Poro-34B)
-- [x] [Bitnet b1.58 models](https://huggingface.co/1bitLLM)
-- [x] [Flan T5](https://huggingface.co/models?search=flan-t5)
-- [x] [Open Elm models](https://huggingface.co/collections/apple/openelm-instruct-models-6619ad295d7ae9f868b759ca)
-- [x] [ChatGLM3-6b](https://huggingface.co/THUDM/chatglm3-6b) + [ChatGLM4-9b](https://huggingface.co/THUDM/glm-4-9b)
-- [x] [SmolLM](https://huggingface.co/collections/HuggingFaceTB/smollm-6695016cad7167254ce15966)
-- [x] [EXAONE-3.0-7.8B-Instruct](https://huggingface.co/LGAI-EXAONE/EXAONE-3.0-7.8B-Instruct)
-- [x] [FalconMamba Models](https://huggingface.co/collections/tiiuae/falconmamba-7b-66b9a580324dd1598b0f6d4a)
-- [x] [Jais](https://huggingface.co/inceptionai/jais-13b-chat)
-- [x] [Bielik-11B-v2.3](https://huggingface.co/collections/speakleash/bielik-11b-v23-66ee813238d9b526a072408a)
-
-(instructions for supporting more models: [HOWTO-add-model.md](./docs/development/HOWTO-add-model.md))
-
-**Multimodal models:**
-
-- [x] [LLaVA 1.5 models](https://huggingface.co/collections/liuhaotian/llava-15-653aac15d994e992e2677a7e), [LLaVA 1.6 models](https://huggingface.co/collections/liuhaotian/llava-16-65b9e40155f60fd046a5ccf2)
-- [x] [BakLLaVA](https://huggingface.co/models?search=SkunkworksAI/Bakllava)
-- [x] [Obsidian](https://huggingface.co/NousResearch/Obsidian-3B-V0.5)
-- [x] [ShareGPT4V](https://huggingface.co/models?search=Lin-Chen/ShareGPT4V)
-- [x] [MobileVLM 1.7B/3B models](https://huggingface.co/models?search=mobileVLM)
-- [x] [Yi-VL](https://huggingface.co/models?search=Yi-VL)
-- [x] [Mini CPM](https://huggingface.co/models?search=MiniCPM)
-- [x] [Moondream](https://huggingface.co/vikhyatk/moondream2)
-- [x] [Bunny](https://github.com/BAAI-DCAI/Bunny)
-
-**Bindings:**
-
-- Python: [abetlen/llama-cpp-python](https://github.com/abetlen/llama-cpp-python)
-- Go: [go-skynet/go-llama.cpp](https://github.com/go-skynet/go-llama.cpp)
-- Node.js: [withcatai/node-llama-cpp](https://github.com/withcatai/node-llama-cpp)
-- JS/TS (llama.cpp server client): [lgrammel/modelfusion](https://modelfusion.dev/integration/model-provider/llamacpp)
-- JS/TS (Programmable Prompt Engine CLI): [offline-ai/cli](https://github.com/offline-ai/cli)
-- JavaScript/Wasm (works in browser): [tangledgroup/llama-cpp-wasm](https://github.com/tangledgroup/llama-cpp-wasm)
-- Typescript/Wasm (nicer API, available on npm): [ngxson/wllama](https://github.com/ngxson/wllama)
-- Ruby: [yoshoku/llama_cpp.rb](https://github.com/yoshoku/llama_cpp.rb)
-- Rust (more features): [edgenai/llama_cpp-rs](https://github.com/edgenai/llama_cpp-rs)
-- Rust (nicer API): [mdrokz/rust-llama.cpp](https://github.com/mdrokz/rust-llama.cpp)
-- Rust (more direct bindings): [utilityai/llama-cpp-rs](https://github.com/utilityai/llama-cpp-rs)
-- C#/.NET: [SciSharp/LLamaSharp](https://github.com/SciSharp/LLamaSharp)
-- Scala 3: [donderom/llm4s](https://github.com/donderom/llm4s)
-- Clojure: [phronmophobic/llama.clj](https://github.com/phronmophobic/llama.clj)
-- React Native: [mybigday/llama.rn](https://github.com/mybigday/llama.rn)
-- Java: [kherud/java-llama.cpp](https://github.com/kherud/java-llama.cpp)
-- Zig: [deins/llama.cpp.zig](https://github.com/Deins/llama.cpp.zig)
-- Flutter/Dart: [netdur/llama_cpp_dart](https://github.com/netdur/llama_cpp_dart)
-- PHP (API bindings and features built on top of llama.cpp): [distantmagic/resonance](https://github.com/distantmagic/resonance) [(more info)](https://github.com/ggerganov/llama.cpp/pull/6326)
-- Guile Scheme: [guile_llama_cpp](https://savannah.nongnu.org/projects/guile-llama-cpp)
-
-**UI:**
-
-Unless otherwise noted these projects are open-source with permissive licensing:
-
-- [MindWorkAI/AI-Studio](https://github.com/MindWorkAI/AI-Studio) (FSL-1.1-MIT)
-- [iohub/collama](https://github.com/iohub/coLLaMA)
-- [janhq/jan](https://github.com/janhq/jan) (AGPL)
-- [nat/openplayground](https://github.com/nat/openplayground)
-- [Faraday](https://faraday.dev/) (proprietary)
-- [LMStudio](https://lmstudio.ai/) (proprietary)
-- [Layla](https://play.google.com/store/apps/details?id=com.laylalite) (proprietary)
-- [ramalama](https://github.com/containers/ramalama) (MIT)
-- [LocalAI](https://github.com/mudler/LocalAI) (MIT)
-- [LostRuins/koboldcpp](https://github.com/LostRuins/koboldcpp) (AGPL)
-- [Mozilla-Ocho/llamafile](https://github.com/Mozilla-Ocho/llamafile)
-- [nomic-ai/gpt4all](https://github.com/nomic-ai/gpt4all)
-- [ollama/ollama](https://github.com/ollama/ollama)
-- [oobabooga/text-generation-webui](https://github.com/oobabooga/text-generation-webui) (AGPL)
-- [psugihara/FreeChat](https://github.com/psugihara/FreeChat)
-- [cztomsik/ava](https://github.com/cztomsik/ava) (MIT)
-- [ptsochantaris/emeltal](https://github.com/ptsochantaris/emeltal)
-- [pythops/tenere](https://github.com/pythops/tenere) (AGPL)
-- [RAGNA Desktop](https://ragna.app/) (proprietary)
-- [RecurseChat](https://recurse.chat/) (proprietary)
-- [semperai/amica](https://github.com/semperai/amica)
-- [withcatai/catai](https://github.com/withcatai/catai)
-- [Mobile-Artificial-Intelligence/maid](https://github.com/Mobile-Artificial-Intelligence/maid) (MIT)
-- [Msty](https://msty.app) (proprietary)
-- [LLMFarm](https://github.com/guinmoon/LLMFarm?tab=readme-ov-file) (MIT)
-- [KanTV](https://github.com/zhouwg/kantv?tab=readme-ov-file)(Apachev2.0 or later)
-- [Dot](https://github.com/alexpinel/Dot) (GPL)
-- [MindMac](https://mindmac.app) (proprietary)
-- [KodiBot](https://github.com/firatkiral/kodibot) (GPL)
-- [eva](https://github.com/ylsdamxssjxxdd/eva) (MIT)
-- [AI Sublime Text plugin](https://github.com/yaroslavyaroslav/OpenAI-sublime-text) (MIT)
-- [AIKit](https://github.com/sozercan/aikit) (MIT)
-- [LARS - The LLM & Advanced Referencing Solution](https://github.com/abgulati/LARS) (AGPL)
-- [LLMUnity](https://github.com/undreamai/LLMUnity) (MIT)
-- [Llama Assistant](https://github.com/vietanhdev/llama-assistant) (GPL)
-
-*(to have a project listed here, it should clearly state that it depends on `llama.cpp`)*
-
-**Tools:**
-
-- [akx/ggify](https://github.com/akx/ggify) β download PyTorch models from HuggingFace Hub and convert them to GGML
-- [akx/ollama-dl](https://github.com/akx/ollama-dl) β download models from the Ollama library to be used directly with llama.cpp
-- [crashr/gppm](https://github.com/crashr/gppm) β launch llama.cpp instances utilizing NVIDIA Tesla P40 or P100 GPUs with reduced idle power consumption
-- [gpustack/gguf-parser](https://github.com/gpustack/gguf-parser-go/tree/main/cmd/gguf-parser) - review/check the GGUF file and estimate the memory usage
-- [Styled Lines](https://marketplace.unity.com/packages/tools/generative-ai/styled-lines-llama-cpp-model-292902) (proprietary licensed, async wrapper of inference part for game development in Unity3d with prebuild Mobile and Web platform wrappers and a model example)
-
-**Infrastructure:**
-
-- [Paddler](https://github.com/distantmagic/paddler) - Stateful load balancer custom-tailored for llama.cpp
-- [GPUStack](https://github.com/gpustack/gpustack) - Manage GPU clusters for running LLMs
-
-**Games:**
-- [Lucy's Labyrinth](https://github.com/MorganRO8/Lucys_Labyrinth) - A simple maze game where agents controlled by an AI model will try to trick you.
-
-## Demo
-
-
-Typical run using LLaMA v2 13B on M2 Ultra
-
-```
-$ make -j && ./llama-cli -m models/llama-13b-v2/ggml-model-q4_0.gguf -p "Building a website can be done in 10 simple steps:\nStep 1:" -n 400 -e
-I llama.cpp build info:
-I UNAME_S: Darwin
-I UNAME_P: arm
-I UNAME_M: arm64
-I CFLAGS: -I. -O3 -std=c11 -fPIC -DNDEBUG -Wall -Wextra -Wpedantic -Wcast-qual -Wdouble-promotion -Wshadow -Wstrict-prototypes -Wpointer-arith -Wmissing-prototypes -pthread -DGGML_USE_K_QUANTS -DGGML_USE_ACCELERATE
-I CXXFLAGS: -I. -I./common -O3 -std=c++11 -fPIC -DNDEBUG -Wall -Wextra -Wpedantic -Wcast-qual -Wno-unused-function -Wno-multichar -pthread -DGGML_USE_K_QUANTS
-I LDFLAGS: -framework Accelerate
-I CC: Apple clang version 14.0.3 (clang-1403.0.22.14.1)
-I CXX: Apple clang version 14.0.3 (clang-1403.0.22.14.1)
-
-make: Nothing to be done for `default'.
-main: build = 1041 (cf658ad)
-main: seed = 1692823051
-llama_model_loader: loaded meta data with 16 key-value pairs and 363 tensors from models/llama-13b-v2/ggml-model-q4_0.gguf (version GGUF V1 (latest))
-llama_model_loader: - type f32: 81 tensors
-llama_model_loader: - type q4_0: 281 tensors
-llama_model_loader: - type q6_K: 1 tensors
-llm_load_print_meta: format = GGUF V1 (latest)
-llm_load_print_meta: arch = llama
-llm_load_print_meta: vocab type = SPM
-llm_load_print_meta: n_vocab = 32000
-llm_load_print_meta: n_merges = 0
-llm_load_print_meta: n_ctx_train = 4096
-llm_load_print_meta: n_ctx = 512
-llm_load_print_meta: n_embd = 5120
-llm_load_print_meta: n_head = 40
-llm_load_print_meta: n_head_kv = 40
-llm_load_print_meta: n_layer = 40
-llm_load_print_meta: n_rot = 128
-llm_load_print_meta: n_gqa = 1
-llm_load_print_meta: f_norm_eps = 1.0e-05
-llm_load_print_meta: f_norm_rms_eps = 1.0e-05
-llm_load_print_meta: n_ff = 13824
-llm_load_print_meta: freq_base = 10000.0
-llm_load_print_meta: freq_scale = 1
-llm_load_print_meta: model type = 13B
-llm_load_print_meta: model ftype = mostly Q4_0
-llm_load_print_meta: model size = 13.02 B
-llm_load_print_meta: general.name = LLaMA v2
-llm_load_print_meta: BOS token = 1 ''
-llm_load_print_meta: EOS token = 2 ''
-llm_load_print_meta: UNK token = 0 ''
-llm_load_print_meta: LF token = 13 '<0x0A>'
-llm_load_tensors: ggml ctx size = 0.11 MB
-llm_load_tensors: mem required = 7024.01 MB (+ 400.00 MB per state)
-...................................................................................................
-llama_new_context_with_model: kv self size = 400.00 MB
-llama_new_context_with_model: compute buffer total size = 75.41 MB
-
-system_info: n_threads = 16 / 24 | AVX = 0 | AVX2 = 0 | AVX512 = 0 | AVX512_VBMI = 0 | AVX512_VNNI = 0 | FMA = 0 | NEON = 1 | ARM_FMA = 1 | F16C = 0 | FP16_VA = 1 | WASM_SIMD = 0 | BLAS = 1 | SSE3 = 0 | VSX = 0 |
-sampling: repeat_last_n = 64, repeat_penalty = 1.100000, presence_penalty = 0.000000, frequency_penalty = 0.000000, top_k = 40, tfs_z = 1.000000, top_p = 0.950000, typical_p = 1.000000, temp = 0.800000, mirostat = 0, mirostat_lr = 0.100000, mirostat_ent = 5.000000
-generate: n_ctx = 512, n_batch = 512, n_predict = 400, n_keep = 0
-
-
- Building a website can be done in 10 simple steps:
-Step 1: Find the right website platform.
-Step 2: Choose your domain name and hosting plan.
-Step 3: Design your website layout.
-Step 4: Write your website content and add images.
-Step 5: Install security features to protect your site from hackers or spammers
-Step 6: Test your website on multiple browsers, mobile devices, operating systems etcβ¦
-Step 7: Test it again with people who are not related to you personally β friends or family members will work just fine!
-Step 8: Start marketing and promoting the website via social media channels or paid ads
-Step 9: Analyze how many visitors have come to your site so far, what type of people visit more often than others (e.g., men vs women) etcβ¦
-Step 10: Continue to improve upon all aspects mentioned above by following trends in web design and staying up-to-date on new technologies that can enhance user experience even further!
-How does a Website Work?
-A website works by having pages, which are made of HTML code. This code tells your computer how to display the content on each page you visit β whether itβs an image or text file (like PDFs). In order for someone elseβs browser not only be able but also want those same results when accessing any given URL; some additional steps need taken by way of programming scripts that will add functionality such as making links clickable!
-The most common type is called static HTML pages because they remain unchanged over time unless modified manually (either through editing files directly or using an interface such as WordPress). They are usually served up via HTTP protocols β this means anyone can access them without having any special privileges like being part of a group who is allowed into restricted areas online; however, there may still exist some limitations depending upon where one lives geographically speaking.
-How to
-llama_print_timings: load time = 576.45 ms
-llama_print_timings: sample time = 283.10 ms / 400 runs ( 0.71 ms per token, 1412.91 tokens per second)
-llama_print_timings: prompt eval time = 599.83 ms / 19 tokens ( 31.57 ms per token, 31.68 tokens per second)
-llama_print_timings: eval time = 24513.59 ms / 399 runs ( 61.44 ms per token, 16.28 tokens per second)
-llama_print_timings: total time = 25431.49 ms
-```
-
-
-
-
-Demo of running both LLaMA-7B and whisper.cpp on a single M1 Pro MacBook
-
-And here is another demo of running both LLaMA-7B and [whisper.cpp](https://github.com/ggerganov/whisper.cpp) on a single M1 Pro MacBook:
-
-https://user-images.githubusercontent.com/1991296/224442907-7693d4be-acaa-4e01-8b4f-add84093ffff.mp4
-
-
-
-## Usage
-
-Here are the end-to-end binary build and model conversion steps for most supported models.
-
-### Basic usage
-
-Firstly, you need to get the binary. There are different methods that you can follow:
-- Method 1: Clone this repository and build locally, see [how to build](./docs/build.md)
-- Method 2: If you are using MacOS or Linux, you can install llama.cpp via [brew, flox or nix](./docs/install.md)
-- Method 3: Use a Docker image, see [documentation for Docker](./docs/docker.md)
-- Method 4: Download pre-built binary from [releases](https://github.com/ggerganov/llama.cpp/releases)
-
-You can run a basic completion using this command:
-
-```bash
-llama-cli -m your_model.gguf -p "I believe the meaning of life is" -n 128
-
-# Output:
-# I believe the meaning of life is to find your own truth and to live in accordance with it. For me, this means being true to myself and following my passions, even if they don't align with societal expectations. I think that's what I love about yoga β it's not just a physical practice, but a spiritual one too. It's about connecting with yourself, listening to your inner voice, and honoring your own unique journey.
-```
-
-See [this page](./examples/main/README.md) for a full list of parameters.
-
-### Conversation mode
-
-If you want a more ChatGPT-like experience, you can run in conversation mode by passing `-cnv` as a parameter:
-
-```bash
-llama-cli -m your_model.gguf -p "You are a helpful assistant" -cnv
-
-# Output:
-# > hi, who are you?
-# Hi there! I'm your helpful assistant! I'm an AI-powered chatbot designed to assist and provide information to users like you. I'm here to help answer your questions, provide guidance, and offer support on a wide range of topics. I'm a friendly and knowledgeable AI, and I'm always happy to help with anything you need. What's on your mind, and how can I assist you today?
-#
-# > what is 1+1?
-# Easy peasy! The answer to 1+1 is... 2!
-```
-
-By default, the chat template will be taken from the input model. If you want to use another chat template, pass `--chat-template NAME` as a parameter. See the list of [supported templates](https://github.com/ggerganov/llama.cpp/wiki/Templates-supported-by-llama_chat_apply_template)
-
-```bash
-./llama-cli -m your_model.gguf -p "You are a helpful assistant" -cnv --chat-template chatml
-```
-
-You can also use your own template via in-prefix, in-suffix and reverse-prompt parameters:
-
-```bash
-./llama-cli -m your_model.gguf -p "You are a helpful assistant" -cnv --in-prefix 'User: ' --reverse-prompt 'User:'
-```
-
-### Web server
-
-[llama.cpp web server](./examples/server/README.md) is a lightweight [OpenAI API](https://github.com/openai/openai-openapi) compatible HTTP server that can be used to serve local models and easily connect them to existing clients.
-
-Example usage:
-
-```bash
-./llama-server -m your_model.gguf --port 8080
-
-# Basic web UI can be accessed via browser: http://localhost:8080
-# Chat completion endpoint: http://localhost:8080/v1/chat/completions
-```
-
-### Interactive mode
-
-> [!NOTE]
-> If you prefer basic usage, please consider using conversation mode instead of interactive mode
-
-In this mode, you can always interrupt generation by pressing Ctrl+C and entering one or more lines of text, which will be converted into tokens and appended to the current context. You can also specify a *reverse prompt* with the parameter `-r "reverse prompt string"`. This will result in user input being prompted whenever the exact tokens of the reverse prompt string are encountered in the generation. A typical use is to use a prompt that makes LLaMA emulate a chat between multiple users, say Alice and Bob, and pass `-r "Alice:"`.
-
-Here is an example of a few-shot interaction, invoked with the command
-
-```bash
-# default arguments using a 7B model
-./examples/chat.sh
-
-# advanced chat with a 13B model
-./examples/chat-13B.sh
-
-# custom arguments using a 13B model
-./llama-cli -m ./models/13B/ggml-model-q4_0.gguf -n 256 --repeat_penalty 1.0 --color -i -r "User:" -f prompts/chat-with-bob.txt
-```
-
-Note the use of `--color` to distinguish between user input and generated text. Other parameters are explained in more detail in the [README](examples/main/README.md) for the `llama-cli` example program.
-
-
-
-### Persistent Interaction
-
-The prompt, user inputs, and model generations can be saved and resumed across calls to `./llama-cli` by leveraging `--prompt-cache` and `--prompt-cache-all`. The `./examples/chat-persistent.sh` script demonstrates this with support for long-running, resumable chat sessions. To use this example, you must provide a file to cache the initial chat prompt and a directory to save the chat session, and may optionally provide the same variables as `chat-13B.sh`. The same prompt cache can be reused for new chat sessions. Note that both prompt cache and chat directory are tied to the initial prompt (`PROMPT_TEMPLATE`) and the model file.
-
-```bash
-# Start a new chat
-PROMPT_CACHE_FILE=chat.prompt.bin CHAT_SAVE_DIR=./chat/default ./examples/chat-persistent.sh
-
-# Resume that chat
-PROMPT_CACHE_FILE=chat.prompt.bin CHAT_SAVE_DIR=./chat/default ./examples/chat-persistent.sh
-
-# Start a different chat with the same prompt/model
-PROMPT_CACHE_FILE=chat.prompt.bin CHAT_SAVE_DIR=./chat/another ./examples/chat-persistent.sh
-
-# Different prompt cache for different prompt/model
-PROMPT_TEMPLATE=./prompts/chat-with-bob.txt PROMPT_CACHE_FILE=bob.prompt.bin \
- CHAT_SAVE_DIR=./chat/bob ./examples/chat-persistent.sh
-```
-
-### Constrained output with grammars
-
-`llama.cpp` supports grammars to constrain model output. For example, you can force the model to output JSON only:
-
-```bash
-./llama-cli -m ./models/13B/ggml-model-q4_0.gguf -n 256 --grammar-file grammars/json.gbnf -p 'Request: schedule a call at 8pm; Command:'
-```
-
-The `grammars/` folder contains a handful of sample grammars. To write your own, check out the [GBNF Guide](./grammars/README.md).
-
-For authoring more complex JSON grammars, you can also check out https://grammar.intrinsiclabs.ai/, a browser app that lets you write TypeScript interfaces which it compiles to GBNF grammars that you can save for local use. Note that the app is built and maintained by members of the community, please file any issues or FRs on [its repo](http://github.com/intrinsiclabsai/gbnfgen) and not this one.
-
-## Build
-
-Please refer to [Build llama.cpp locally](./docs/build.md)
-
-## Supported backends
-
-| Backend | Target devices |
-| --- | --- |
-| [Metal](./docs/build.md#metal-build) | Apple Silicon |
-| [BLAS](./docs/build.md#blas-build) | All |
-| [BLIS](./docs/backend/BLIS.md) | All |
-| [SYCL](./docs/backend/SYCL.md) | Intel and Nvidia GPU |
-| [MUSA](./docs/build.md#musa) | Moore Threads GPU |
-| [CUDA](./docs/build.md#cuda) | Nvidia GPU |
-| [hipBLAS](./docs/build.md#hipblas) | AMD GPU |
-| [Vulkan](./docs/build.md#vulkan) | GPU |
-| [CANN](./docs/build.md#cann) | Ascend NPU |
-
-## Tools
-
-### Prepare and Quantize
-
-> [!NOTE]
-> You can use the [GGUF-my-repo](https://huggingface.co/spaces/ggml-org/gguf-my-repo) space on Hugging Face to quantise your model weights without any setup too. It is synced from `llama.cpp` main every 6 hours.
-
-To obtain the official LLaMA 2 weights please see the Obtaining and using the Facebook LLaMA 2 model section. There is also a large selection of pre-quantized `gguf` models available on Hugging Face.
-
-Note: `convert.py` has been moved to `examples/convert_legacy_llama.py` and shouldn't be used for anything other than `Llama/Llama2/Mistral` models and their derivatives.
-It does not support LLaMA 3, you can use `convert_hf_to_gguf.py` with LLaMA 3 downloaded from Hugging Face.
-
-To learn more about quantizing model, [read this documentation](./examples/quantize/README.md)
-
-### Perplexity (measuring model quality)
-
-You can use the `perplexity` example to measure perplexity over a given prompt (lower perplexity is better).
-For more information, see [https://huggingface.co/docs/transformers/perplexity](https://huggingface.co/docs/transformers/perplexity).
-
-To learn more how to measure perplexity using llama.cpp, [read this documentation](./examples/perplexity/README.md)
-
-## Contributing
-
-- Contributors can open PRs
-- Collaborators can push to branches in the `llama.cpp` repo and merge PRs into the `master` branch
-- Collaborators will be invited based on contributions
-- Any help with managing issues, PRs and projects is very appreciated!
-- See [good first issues](https://github.com/ggerganov/llama.cpp/issues?q=is%3Aissue+is%3Aopen+label%3A%22good+first+issue%22) for tasks suitable for first contributions
-- Read the [CONTRIBUTING.md](CONTRIBUTING.md) for more information
-- Make sure to read this: [Inference at the edge](https://github.com/ggerganov/llama.cpp/discussions/205)
-- A bit of backstory for those who are interested: [Changelog podcast](https://changelog.com/podcast/532)
-
-## Other documentations
-
-- [main (cli)](./examples/main/README.md)
-- [server](./examples/server/README.md)
-- [jeopardy](./examples/jeopardy/README.md)
-- [GBNF grammars](./grammars/README.md)
-
-**Development documentations**
-
-- [How to build](./docs/build.md)
-- [Running on Docker](./docs/docker.md)
-- [Build on Android](./docs/android.md)
-- [Performance troubleshooting](./docs/development/token_generation_performance_tips.md)
-- [GGML tips & tricks](https://github.com/ggerganov/llama.cpp/wiki/GGML-Tips-&-Tricks)
-
-**Seminal papers and background on the models**
-
-If your issue is with model generation quality, then please at least scan the following links and papers to understand the limitations of LLaMA models. This is especially important when choosing an appropriate model size and appreciating both the significant and subtle differences between LLaMA models and ChatGPT:
-- LLaMA:
- - [Introducing LLaMA: A foundational, 65-billion-parameter large language model](https://ai.facebook.com/blog/large-language-model-llama-meta-ai/)
- - [LLaMA: Open and Efficient Foundation Language Models](https://arxiv.org/abs/2302.13971)
-- GPT-3
- - [Language Models are Few-Shot Learners](https://arxiv.org/abs/2005.14165)
-- GPT-3.5 / InstructGPT / ChatGPT:
- - [Aligning language models to follow instructions](https://openai.com/research/instruction-following)
- - [Training language models to follow instructions with human feedback](https://arxiv.org/abs/2203.02155)
+This is a distributed implementation of [llama.cpp](https://github.com/ggerganov/llama.cpp), coming soon.
\ No newline at end of file
diff --git a/common/arg.cpp b/common/arg.cpp
index 2a85ad84..0d3ddccf 100644
--- a/common/arg.cpp
+++ b/common/arg.cpp
@@ -661,6 +661,41 @@ gpt_params_context gpt_params_parser_init(gpt_params & params, llama_example ex,
params.n_ctx = value;
}
).set_env("LLAMA_ARG_CTX_SIZE"));
+ add_opt(llama_arg(
+ {"-w", "--world", "--world-size"}, "N",
+ format("number of devices to use (default: %d)", params.n_world),
+ [](gpt_params & params, int value) {
+ params.n_world = value;
+ }
+ ).set_env("LLAMA_ARG_N_WORLD"));
+ add_opt(llama_arg(
+ {"-r", "--rank", "--my-rank"}, "N",
+ format("my rank for distributed inference (default: %d)", params.rank),
+ [](gpt_params & params, int value) {
+ params.rank = value;
+ }
+ ).set_env("LLAMA_ARG_RANK"));
+ add_opt(llama_arg(
+ {"-lw", "--layer-window", "--n-layer-window"}, "N",
+ format("number of layers to process in each compute (default: %d)", params.n_layer_window),
+ [](gpt_params & params, int value) {
+ params.n_layer_window = value;
+ }
+ ).set_env("LLAMA_ARG_N_LAYER_WINDOW"));
+ add_opt(llama_arg(
+ {"-mip", "--master", "--master-ip"}, "IPAddress",
+ format("ip address of the master node (default: %s)", params.master_ip.c_str()),
+ [](gpt_params & params, const std::string & value) {
+ params.master_ip = value;
+ }
+ ).set_env("LLAMA_ARG_MASTER_IP"));
+ add_opt(llama_arg(
+ {"-nip", "--next", "--next-node", "--next-ip", "--next-node-ip"}, "IPAddress",
+ format("ip address of the next node (default: %s)", params.next_node_ip.c_str()),
+ [](gpt_params & params, const std::string & value) {
+ params.next_node_ip = value;
+ }
+ ).set_env("LLAMA_ARG_NEXT_NODE_IP"));
add_opt(llama_arg(
{"-n", "--predict", "--n-predict"}, "N",
format("number of tokens to predict (default: %d, -1 = infinity, -2 = until context filled)", params.n_predict),
diff --git a/common/common.cpp b/common/common.cpp
index 29df16c9..a4a68899 100644
--- a/common/common.cpp
+++ b/common/common.cpp
@@ -872,6 +872,8 @@ struct llama_init_result llama_init_from_gpt_params(gpt_params & params) {
return iparams;
}
+ llama_init_sockets(lctx, cparams.n_world, cparams.rank);
+
if (!params.control_vectors.empty()) {
if (params.control_vector_layer_start <= 0) params.control_vector_layer_start = 1;
if (params.control_vector_layer_end <= 0) params.control_vector_layer_end = llama_n_layer(model);
@@ -924,28 +926,34 @@ struct llama_init_result llama_init_from_gpt_params(gpt_params & params) {
if (params.warmup) {
LOG_WRN("%s: warming up the model with an empty run - please wait ... (--no-warmup to disable)\n", __func__);
+ const uint32_t my_rank = cparams.rank;
std::vector tmp;
- llama_token bos = llama_token_bos(model);
- llama_token eos = llama_token_eos(model);
- // some models (e.g. T5) don't have a BOS token
- if (bos != LLAMA_TOKEN_NULL) {
- tmp.push_back(bos);
- }
- if (eos != LLAMA_TOKEN_NULL) {
- tmp.push_back(eos);
- }
- if (tmp.empty()) {
- tmp.push_back(0);
- }
- if (llama_model_has_encoder(model)) {
- llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size(), 0, 0));
- llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
- if (decoder_start_token_id == -1) {
- decoder_start_token_id = bos;
+ if (my_rank == 0) {
+ llama_token bos = llama_token_bos(model);
+ llama_token eos = llama_token_eos(model);
+ // some models (e.g. T5) don't have a BOS token
+ if (bos != LLAMA_TOKEN_NULL) {
+ tmp.push_back(bos);
+ }
+ if (eos != LLAMA_TOKEN_NULL) {
+ tmp.push_back(eos);
+ }
+ if (tmp.empty()) {
+ tmp.push_back(0);
+ }
+
+ if (llama_model_has_encoder(model)) {
+ throw std::runtime_error("this model is currently not supported");
+
+ llama_encode(lctx, llama_batch_get_one(tmp.data(), tmp.size(), 0, 0));
+ llama_token decoder_start_token_id = llama_model_decoder_start_token(model);
+ if (decoder_start_token_id == -1) {
+ decoder_start_token_id = bos;
+ }
+ tmp.clear();
+ tmp.push_back(decoder_start_token_id);
}
- tmp.clear();
- tmp.push_back(decoder_start_token_id);
}
if (llama_model_has_decoder(model)) {
llama_decode(lctx, llama_batch_get_one(tmp.data(), std::min(tmp.size(), (size_t) params.n_batch), 0, 0));
@@ -976,6 +984,9 @@ struct llama_model_params llama_model_params_from_gpt_params(const gpt_params &
if (params.n_gpu_layers != -1) {
mparams.n_gpu_layers = params.n_gpu_layers;
}
+ mparams.n_world = params.n_world;
+ mparams.rank = params.rank;
+ mparams.n_layer_window = params.n_layer_window;
mparams.rpc_servers = params.rpc_servers.c_str();
mparams.main_gpu = params.main_gpu;
mparams.split_mode = params.split_mode;
@@ -1025,6 +1036,22 @@ static ggml_type kv_cache_type_from_str(const std::string & s) {
struct llama_context_params llama_context_params_from_gpt_params(const gpt_params & params) {
auto cparams = llama_context_default_params();
+ cparams.n_world = params.n_world;
+ cparams.rank = params.rank;
+ cparams.n_layer_window = params.n_layer_window;
+
+ if (cparams.master_ip != nullptr) {
+ delete[] cparams.master_ip;
+ }
+ cparams.master_ip = new char[params.master_ip.length() + 1];
+ std::strcpy(cparams.master_ip, params.master_ip.c_str());
+
+ if (cparams.next_node_ip != nullptr) {
+ delete[] cparams.next_node_ip;
+ }
+ cparams.next_node_ip = new char[params.next_node_ip.length() + 1];
+ std::strcpy(cparams.next_node_ip, params.next_node_ip.c_str());
+
cparams.n_ctx = params.n_ctx;
cparams.n_seq_max = params.n_parallel;
cparams.n_batch = params.n_batch;
diff --git a/common/common.h b/common/common.h
index 8b84cf9a..21540dac 100644
--- a/common/common.h
+++ b/common/common.h
@@ -142,6 +142,11 @@ struct gpt_sampler_params {
};
struct gpt_params {
+ int32_t n_world = 1; // number of devices to use
+ int32_t rank = 0; // my rank for distributed inference
+ int32_t n_layer_window = 32; // number of layers to process in each compute
+ std::string master_ip = "localhost"; // ip address of the master node
+ std::string next_node_ip = "localhost"; // ip address of my next node
int32_t n_predict = -1; // new tokens to predict
int32_t n_ctx = 0; // context size
int32_t n_batch = 2048; // logical batch size for prompt processing (must be >=32 to use BLAS)
@@ -229,8 +234,7 @@ struct gpt_params {
bool multiple_choice = false; // compute TruthfulQA score over random tasks from datafile supplied in prompt
size_t multiple_choice_tasks = 0; // number of tasks to use when computing the TruthfulQA score. If 0, all tasks will be computed
- bool kl_divergence = false; // compute KL divergence
-
+ bool kl_divergence = false; // compute KL divergence
bool usage = false; // print usage
bool use_color = false; // use color to distinguish generations and inputs
bool special = false; // enable special token output
diff --git a/examples/main/main.cpp b/examples/main/main.cpp
index 6bbb1e13..d85a7bb0 100644
--- a/examples/main/main.cpp
+++ b/examples/main/main.cpp
@@ -14,6 +14,7 @@
#include
#include
#include
+#include
#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__))
#include
@@ -141,6 +142,9 @@ int main(int argc, char ** argv) {
if (!gpt_params_parse(argc, argv, params, LLAMA_EXAMPLE_MAIN, print_usage)) {
return 1;
}
+ const uint32_t n_world = params.n_world;
+ const uint32_t my_rank = params.rank;
+ GGML_ASSERT(!(n_world == 1 && my_rank > 0));
gpt_init();
@@ -151,22 +155,6 @@ int main(int argc, char ** argv) {
console::init(params.simple_io, params.use_color);
atexit([]() { console::cleanup(); });
- if (params.logits_all) {
- LOG_ERR("************\n");
- LOG_ERR("%s: please use the 'perplexity' tool for perplexity calculations\n", __func__);
- LOG_ERR("************\n\n");
-
- return 0;
- }
-
- if (params.embedding) {
- LOG_ERR("************\n");
- LOG_ERR("%s: please use the 'embedding' tool for embedding calculations\n", __func__);
- LOG_ERR("************\n\n");
-
- return 0;
- }
-
if (params.n_ctx != 0 && params.n_ctx < 8) {
LOG_WRN("%s: warning: minimum context size is 8, using minimum size.\n", __func__);
params.n_ctx = 8;
@@ -290,7 +278,7 @@ int main(int argc, char ** argv) {
std::vector embd_inp;
- {
+ if (my_rank == 0) {
auto prompt = (params.conversation && params.enable_chat_template && !params.prompt.empty())
? chat_add_and_format(model, chat_msgs, "system", params.prompt) // format the system prompt in conversation mode
: params.prompt;
@@ -304,23 +292,23 @@ int main(int argc, char ** argv) {
LOG_DBG("prompt: \"%s\"\n", prompt.c_str());
LOG_DBG("tokens: %s\n", string_from(ctx, embd_inp).c_str());
- }
- // Should not run without any tokens
- if (embd_inp.empty()) {
- if (add_bos) {
- embd_inp.push_back(llama_token_bos(model));
- LOG_WRN("embd_inp was considered empty and bos was added: %s\n", string_from(ctx, embd_inp).c_str());
- } else {
- LOG_ERR("input is empty\n");
- return -1;
+ // should not run without any tokens
+ if (embd_inp.empty()) {
+ if (add_bos) {
+ embd_inp.push_back(llama_token_bos(model));
+ LOG_WRN("embd_inp was considered empty and bos was added: %s\n", string_from(ctx, embd_inp).c_str());
+ } else {
+ LOG_ERR("input is empty\n");
+ return -1;
+ }
}
- }
- // Tokenize negative prompt
- if ((int) embd_inp.size() > n_ctx - 4) {
- LOG_ERR("%s: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
- return 1;
+ // tokenize negative prompt
+ if ((int) embd_inp.size() > n_ctx - 4) {
+ LOG_ERR("%s: prompt is too long (%d tokens, max %d)\n", __func__, (int) embd_inp.size(), n_ctx - 4);
+ return 1;
+ }
}
// debug message about similarity of saved session, if applicable
@@ -448,18 +436,18 @@ int main(int argc, char ** argv) {
}
}
- smpl = gpt_sampler_init(model, sparams);
- if (!smpl) {
- LOG_ERR("%s: failed to initialize sampling subsystem\n", __func__);
- return 1;
+ if (my_rank == 0) {
+ smpl = gpt_sampler_init(model, sparams);
+ if (!smpl) {
+ LOG_ERR("%s: failed to initialize sampling subsystem\n", __func__);
+ return 1;
+ }
+ LOG_INF("sampler seed: %u\n", gpt_sampler_get_seed(smpl));
+ LOG_INF("sampler params: \n%s\n", sparams.print().c_str());
+ LOG_INF("sampler chain: %s\n", gpt_sampler_print(smpl).c_str());
+ LOG_INF("generate: n_ctx = %d, n_batch = %d, n_predict = %d, n_keep = %d\n", n_ctx, params.n_batch, params.n_predict, params.n_keep);
}
- LOG_INF("sampler seed: %u\n", gpt_sampler_get_seed(smpl));
- LOG_INF("sampler params: \n%s\n", sparams.print().c_str());
- LOG_INF("sampler chain: %s\n", gpt_sampler_print(smpl).c_str());
-
- LOG_INF("generate: n_ctx = %d, n_batch = %d, n_predict = %d, n_keep = %d\n", n_ctx, params.n_batch, params.n_predict, params.n_keep);
-
// group-attention state
// number of grouped KV tokens so far (used only if params.grp_attn_n > 1)
int ga_i = 0;
@@ -487,9 +475,7 @@ int main(int argc, char ** argv) {
" - If you want to submit another line, end your input with '\\'.\n";
}
LOG_INF("== Running in interactive mode. ==\n");
-#if defined (__unix__) || (defined (__APPLE__) && defined (__MACH__)) || defined (_WIN32)
- LOG_INF( " - Press Ctrl+C to interject at any time.\n");
-#endif
+ LOG_INF( " - Enter quit or exit to quit chat.\n");
LOG_INF( "%s\n", control_message);
is_interacting = params.interactive_first;
@@ -525,6 +511,8 @@ int main(int argc, char ** argv) {
}
if (llama_model_has_encoder(model)) {
+ throw std::runtime_error("this model is currently not supported");
+
int enc_input_size = embd_inp.size();
llama_token * enc_input_buf = embd_inp.data();
@@ -542,9 +530,16 @@ int main(int argc, char ** argv) {
embd_inp.push_back(decoder_start_token_id);
}
+ char * stop_signal = nullptr;
+ std::thread signal_thread;
+
+ if (my_rank != 0) {
+ signal_thread = std::thread(llama_free_sockets, ctx, &stop_signal);
+ }
+
while ((n_remain != 0 && !is_antiprompt) || params.interactive) {
// predict
- if (!embd.empty()) {
+ if (!embd.empty() || my_rank != 0) {
// Note: (n_ctx - 4) here is to match the logic for commandline prompt handling via
// --prompt or --file which uses the same value.
int max_embd_size = n_ctx - 4;
@@ -640,25 +635,22 @@ int main(int argc, char ** argv) {
}
}
- for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
- int n_eval = (int) embd.size() - i;
- if (n_eval > params.n_batch) {
- n_eval = params.n_batch;
+ if (my_rank == 0) {
+ for (int i = 0; i < (int) embd.size(); i += params.n_batch) {
+ int n_eval = (int) embd.size() - i;
+ if (n_eval > params.n_batch) {
+ n_eval = params.n_batch;
+ }
+ if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval, n_past, 0)) != 0) {
+ LOG_ERR("%s : failed to eval\n", __func__);
+ return 1;
+ }
+ n_past += n_eval;
}
-
- LOG_DBG("eval: %s\n", string_from(ctx, embd).c_str());
-
- if (llama_decode(ctx, llama_batch_get_one(&embd[i], n_eval, n_past, 0))) {
- LOG_ERR("%s : failed to eval\n", __func__);
- return 1;
- }
-
- n_past += n_eval;
-
- LOG_DBG("n_past = %d\n", n_past);
- // Display total tokens alongside total time
- if (params.n_print > 0 && n_past % params.n_print == 0) {
- LOG_DBG("\n\033[31mTokens consumed so far = %d / %d \033[0m\n", n_past, n_ctx);
+ } else {
+ llama_decode(ctx, llama_batch_get_one(embd.data(), 0, 0, 0));
+ if (stop_signal != nullptr && std::strcmp(stop_signal, "STOP") == 0) {
+ break;
}
}
@@ -670,70 +662,70 @@ int main(int argc, char ** argv) {
embd.clear();
- if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
- // optionally save the session on first sample (for faster prompt loading next time)
- if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
- need_to_save_session = false;
- llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
+ if (my_rank == 0) {
+ if ((int) embd_inp.size() <= n_consumed && !is_interacting) {
+ // optionally save the session on first sample (for faster prompt loading next time)
+ if (!path_session.empty() && need_to_save_session && !params.prompt_cache_ro) {
+ need_to_save_session = false;
+ llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
+ LOG_DBG("saved session to %s\n", path_session.c_str());
+ }
- LOG_DBG("saved session to %s\n", path_session.c_str());
- }
+ const llama_token id = gpt_sampler_sample(smpl, ctx, -1);
- const llama_token id = gpt_sampler_sample(smpl, ctx, -1);
+ gpt_sampler_accept(smpl, id, /* accept_grammar= */ true);
- gpt_sampler_accept(smpl, id, /* accept_grammar= */ true);
+ embd.push_back(id);
- // LOG_DBG("last: %s\n", string_from(ctx, smpl->prev.to_vector()).c_str());
+ // echo this to console
+ input_echo = true;
- embd.push_back(id);
+ // decrement remaining sampling budget
+ --n_remain;
- // echo this to console
- input_echo = true;
+ LOG_DBG("n_remain: %d\n", n_remain);
+ } else {
+ // some user input remains from prompt or interaction, forward it to processing
+ while ((int) embd_inp.size() > n_consumed) {
+ embd.push_back(embd_inp[n_consumed]);
- // decrement remaining sampling budget
- --n_remain;
+ // push the prompt in the sampling context in order to apply repetition penalties later
+ // for the prompt, we don't apply grammar rules
+ gpt_sampler_accept(smpl, embd_inp[n_consumed], /* accept_grammar= */ false);
- LOG_DBG("n_remain: %d\n", n_remain);
- } else {
- // some user input remains from prompt or interaction, forward it to processing
- LOG_DBG("embd_inp.size(): %d, n_consumed: %d\n", (int) embd_inp.size(), n_consumed);
- while ((int) embd_inp.size() > n_consumed) {
- embd.push_back(embd_inp[n_consumed]);
-
- // push the prompt in the sampling context in order to apply repetition penalties later
- // for the prompt, we don't apply grammar rules
- gpt_sampler_accept(smpl, embd_inp[n_consumed], /* accept_grammar= */ false);
-
- ++n_consumed;
- if ((int) embd.size() >= params.n_batch) {
- break;
+ ++n_consumed;
+ if ((int) embd.size() >= params.n_batch) {
+ break;
+ }
}
}
}
// display text
- if (input_echo && display) {
- for (auto id : embd) {
- const std::string token_str = llama_token_to_piece(ctx, id, params.special);
+ if (my_rank == 0) {
+ if (input_echo && display) {
+ for (auto id : embd) {
+ const std::string token_str = llama_token_to_piece(ctx, id, params.special);
- // Console/Stream Output
- LOG("%s", token_str.c_str());
+ // Console/Stream Output
+ LOG("%s", token_str.c_str());
- // Record Displayed Tokens To Log
- // Note: Generated tokens are created one by one hence this check
- if (embd.size() > 1) {
- // Incoming Requested Tokens
- input_tokens.push_back(id);
- } else {
- // Outgoing Generated Tokens
- output_tokens.push_back(id);
- output_ss << token_str;
+ // Record Displayed Tokens To Log
+ // Note: Generated tokens are created one by one hence this check
+ if (embd.size() > 1) {
+ // Incoming Requested Tokens
+ input_tokens.push_back(id);
+ } else {
+ // Outgoing Generated Tokens
+ output_tokens.push_back(id);
+ output_ss << token_str;
+ }
}
}
}
// reset color to default if there is no pending user input
- if (input_echo && (int) embd_inp.size() == n_consumed) {
+ if (my_rank == 0 && input_echo && (int) embd_inp.size() == n_consumed) {
console::set_display(console::reset);
display = true;
}
@@ -782,7 +774,7 @@ int main(int argc, char ** argv) {
}
// deal with end of generation tokens in interactive mode
- if (llama_token_is_eog(model, gpt_sampler_last(smpl))) {
+ if (my_rank == 0 && llama_token_is_eog(model, gpt_sampler_last(smpl))) {
LOG_DBG("found an EOG token\n");
if (params.interactive) {
@@ -840,6 +832,10 @@ int main(int argc, char ** argv) {
console::set_display(console::reset);
display = true;
+ if (buffer == "quit\n" || buffer == "exit\n") {
+ break;
+ }
+
// Add tokens to embd only if the input buffer is non-empty
// Entering a empty line lets the user pass control back
if (buffer.length() > 1) {
@@ -924,19 +920,20 @@ int main(int argc, char ** argv) {
llama_state_save_file(ctx, path_session.c_str(), session_tokens.data(), session_tokens.size());
}
- LOG("\n\n");
- gpt_perf_print(ctx, smpl);
- write_logfile(ctx, params, model, input_tokens, output_ss.str(), output_tokens);
-
- gpt_sampler_free(smpl);
-
+ if (my_rank == 0) {
+ LOG("\n\n");
+ gpt_perf_print(ctx, smpl);
+ write_logfile(ctx, params, model, input_tokens, output_ss.str(), output_tokens);
+ gpt_sampler_free(smpl);
+ llama_free_sockets(ctx, &stop_signal);
+ }
+ if (my_rank != 0 && signal_thread.joinable()) {
+ signal_thread.join();
+ }
llama_free(ctx);
llama_free_model(model);
-
llama_backend_free();
-
ggml_threadpool_free(threadpool);
ggml_threadpool_free(threadpool_batch);
-
return 0;
-}
+}
\ No newline at end of file
diff --git a/include/llama.h b/include/llama.h
index 7cae1bbe..b0965123 100644
--- a/include/llama.h
+++ b/include/llama.h
@@ -276,6 +276,9 @@ extern "C" {
};
struct llama_model_params {
+ uint32_t n_world; // number of nodes
+ uint32_t rank; // my node rank
+ uint32_t n_layer_window; // number of layers to kept each time
int32_t n_gpu_layers; // number of layers to store in VRAM
enum llama_split_mode split_mode; // how to split the model across multiple GPUs
@@ -312,12 +315,17 @@ extern "C" {
// NOTE: changing the default values of parameters marked as [EXPERIMENTAL] may cause crashes or incorrect results in certain configurations
// https://github.com/ggerganov/llama.cpp/pull/7544
struct llama_context_params {
- uint32_t n_ctx; // text context, 0 = from model
- uint32_t n_batch; // logical maximum batch size that can be submitted to llama_decode
- uint32_t n_ubatch; // physical maximum batch size
- uint32_t n_seq_max; // max number of sequences (i.e. distinct states for recurrent models)
- int32_t n_threads; // number of threads to use for generation
- int32_t n_threads_batch; // number of threads to use for batch processing
+ uint32_t n_world; // world size
+ uint32_t rank; // my rank
+ uint32_t n_layer_window; // number of layers to process in each compute
+ char * master_ip; // ip address of the master node
+ char * next_node_ip; // ip address of the next node
+ uint32_t n_ctx; // text context, 0 = from model
+ uint32_t n_batch; // logical maximum batch size that can be submitted to llama_decode
+ uint32_t n_ubatch; // physical maximum batch size
+ uint32_t n_seq_max; // max number of sequences (i.e. distinct states for recurrent models)
+ int32_t n_threads; // number of threads to use for generation
+ int32_t n_threads_batch; // number of threads to use for batch processing
enum llama_rope_scaling_type rope_scaling_type; // RoPE scaling type, from `enum llama_rope_scaling_type`
enum llama_pooling_type pooling_type; // whether to pool (sum) embedding results by sequence id
@@ -418,6 +426,9 @@ extern "C" {
LLAMA_API void llama_free_model(struct llama_model * model);
+ LLAMA_API void llama_init_sockets(struct llama_context * ctx, uint32_t n_world, uint32_t my_rank);
+ LLAMA_API void llama_free_sockets(struct llama_context * ctx, char ** msg);
+
// TODO: rename to llama_init_from_model
LLAMA_API struct llama_context * llama_new_context_with_model(
struct llama_model * model,
diff --git a/include/zmq.hpp b/include/zmq.hpp
new file mode 100644
index 00000000..a434eb61
--- /dev/null
+++ b/include/zmq.hpp
@@ -0,0 +1,2796 @@
+/*
+ Copyright (c) 2016-2017 ZeroMQ community
+ Copyright (c) 2009-2011 250bpm s.r.o.
+ Copyright (c) 2011 Botond Ballo
+ Copyright (c) 2007-2009 iMatix Corporation
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to
+ deal in the Software without restriction, including without limitation the
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ sell copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ IN THE SOFTWARE.
+*/
+
+#ifndef __ZMQ_HPP_INCLUDED__
+#define __ZMQ_HPP_INCLUDED__
+
+#ifdef _WIN32
+#ifndef NOMINMAX
+#define NOMINMAX
+#endif
+#endif
+
+// included here for _HAS_CXX* macros
+#include
+
+#if defined(_MSVC_LANG)
+#define CPPZMQ_LANG _MSVC_LANG
+#else
+#define CPPZMQ_LANG __cplusplus
+#endif
+// overwrite if specific language macros indicate higher version
+#if defined(_HAS_CXX14) && _HAS_CXX14 && CPPZMQ_LANG < 201402L
+#undef CPPZMQ_LANG
+#define CPPZMQ_LANG 201402L
+#endif
+#if defined(_HAS_CXX17) && _HAS_CXX17 && CPPZMQ_LANG < 201703L
+#undef CPPZMQ_LANG
+#define CPPZMQ_LANG 201703L
+#endif
+
+// macros defined if has a specific standard or greater
+#if CPPZMQ_LANG >= 201103L || (defined(_MSC_VER) && _MSC_VER >= 1900)
+#define ZMQ_CPP11
+#endif
+#if CPPZMQ_LANG >= 201402L
+#define ZMQ_CPP14
+#endif
+#if CPPZMQ_LANG >= 201703L
+#define ZMQ_CPP17
+#endif
+
+#if defined(ZMQ_CPP14) && !defined(_MSC_VER)
+#define ZMQ_DEPRECATED(msg) [[deprecated(msg)]]
+#elif defined(_MSC_VER)
+#define ZMQ_DEPRECATED(msg) __declspec(deprecated(msg))
+#elif defined(__GNUC__)
+#define ZMQ_DEPRECATED(msg) __attribute__((deprecated(msg)))
+#else
+#define ZMQ_DEPRECATED(msg)
+#endif
+
+#if defined(ZMQ_CPP17)
+#define ZMQ_NODISCARD [[nodiscard]]
+#else
+#define ZMQ_NODISCARD
+#endif
+
+#if defined(ZMQ_CPP11)
+#define ZMQ_NOTHROW noexcept
+#define ZMQ_EXPLICIT explicit
+#define ZMQ_OVERRIDE override
+#define ZMQ_NULLPTR nullptr
+#define ZMQ_CONSTEXPR_FN constexpr
+#define ZMQ_CONSTEXPR_VAR constexpr
+#define ZMQ_CPP11_DEPRECATED(msg) ZMQ_DEPRECATED(msg)
+#else
+#define ZMQ_NOTHROW throw()
+#define ZMQ_EXPLICIT
+#define ZMQ_OVERRIDE
+#define ZMQ_NULLPTR 0
+#define ZMQ_CONSTEXPR_FN
+#define ZMQ_CONSTEXPR_VAR const
+#define ZMQ_CPP11_DEPRECATED(msg)
+#endif
+#if defined(ZMQ_CPP14) && (!defined(_MSC_VER) || _MSC_VER > 1900) && (!defined(__GNUC__) || __GNUC__ > 5 || (__GNUC__ == 5 && __GNUC_MINOR__ > 3))
+#define ZMQ_EXTENDED_CONSTEXPR
+#endif
+#if defined(ZMQ_CPP17)
+#define ZMQ_INLINE_VAR inline
+#define ZMQ_CONSTEXPR_IF constexpr
+#else
+#define ZMQ_INLINE_VAR
+#define ZMQ_CONSTEXPR_IF
+#endif
+
+#include
+#include
+
+#include
+#include
+#include
+#include
+#include
+#include
+#include
+#ifdef ZMQ_CPP11
+#include
+#include
+#include
+#include
+#endif
+
+#if defined(__has_include) && defined(ZMQ_CPP17)
+#define CPPZMQ_HAS_INCLUDE_CPP17(X) __has_include(X)
+#else
+#define CPPZMQ_HAS_INCLUDE_CPP17(X) 0
+#endif
+
+#if CPPZMQ_HAS_INCLUDE_CPP17() && !defined(CPPZMQ_HAS_OPTIONAL)
+#define CPPZMQ_HAS_OPTIONAL 1
+#endif
+#ifndef CPPZMQ_HAS_OPTIONAL
+#define CPPZMQ_HAS_OPTIONAL 0
+#elif CPPZMQ_HAS_OPTIONAL
+#include
+#endif
+
+#if CPPZMQ_HAS_INCLUDE_CPP17() && !defined(CPPZMQ_HAS_STRING_VIEW)
+#define CPPZMQ_HAS_STRING_VIEW 1
+#endif
+#ifndef CPPZMQ_HAS_STRING_VIEW
+#define CPPZMQ_HAS_STRING_VIEW 0
+#elif CPPZMQ_HAS_STRING_VIEW
+#include
+#endif
+
+/* Version macros for compile-time API version detection */
+#define CPPZMQ_VERSION_MAJOR 4
+#define CPPZMQ_VERSION_MINOR 10
+#define CPPZMQ_VERSION_PATCH 0
+
+#define CPPZMQ_VERSION \
+ ZMQ_MAKE_VERSION(CPPZMQ_VERSION_MAJOR, CPPZMQ_VERSION_MINOR, \
+ CPPZMQ_VERSION_PATCH)
+
+// Detect whether the compiler supports C++11 rvalue references.
+#if (defined(__GNUC__) && (__GNUC__ > 4 || (__GNUC__ == 4 && __GNUC_MINOR__ > 2)) \
+ && defined(__GXX_EXPERIMENTAL_CXX0X__))
+#define ZMQ_HAS_RVALUE_REFS
+#define ZMQ_DELETED_FUNCTION = delete
+#elif defined(__clang__)
+#if __has_feature(cxx_rvalue_references)
+#define ZMQ_HAS_RVALUE_REFS
+#endif
+
+#if __has_feature(cxx_deleted_functions)
+#define ZMQ_DELETED_FUNCTION = delete
+#else
+#define ZMQ_DELETED_FUNCTION
+#endif
+#elif defined(_MSC_VER) && (_MSC_VER >= 1900)
+#define ZMQ_HAS_RVALUE_REFS
+#define ZMQ_DELETED_FUNCTION = delete
+#elif defined(_MSC_VER) && (_MSC_VER >= 1600)
+#define ZMQ_HAS_RVALUE_REFS
+#define ZMQ_DELETED_FUNCTION
+#else
+#define ZMQ_DELETED_FUNCTION
+#endif
+
+#if defined(ZMQ_CPP11) && !defined(__llvm__) && !defined(__INTEL_COMPILER) \
+ && defined(__GNUC__) && __GNUC__ < 5
+#define ZMQ_CPP11_PARTIAL
+#elif defined(__GLIBCXX__) && __GLIBCXX__ < 20160805
+//the date here is the last date of gcc 4.9.4, which
+// effectively means libstdc++ from gcc 5.5 and higher won't trigger this branch
+#define ZMQ_CPP11_PARTIAL
+#endif
+
+#ifdef ZMQ_CPP11
+#ifdef ZMQ_CPP11_PARTIAL
+#define ZMQ_IS_TRIVIALLY_COPYABLE(T) __has_trivial_copy(T)
+#else
+#include
+#define ZMQ_IS_TRIVIALLY_COPYABLE(T) std::is_trivially_copyable::value
+#endif
+#endif
+
+#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3, 3, 0)
+#define ZMQ_NEW_MONITOR_EVENT_LAYOUT
+#endif
+
+#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 1, 0)
+#define ZMQ_HAS_PROXY_STEERABLE
+/* Socket event data */
+typedef struct
+{
+ uint16_t event; // id of the event as bitfield
+ int32_t value; // value is either error code, fd or reconnect interval
+} zmq_event_t;
+#endif
+
+// Avoid using deprecated message receive function when possible
+#if ZMQ_VERSION < ZMQ_MAKE_VERSION(3, 2, 0)
+#define zmq_msg_recv(msg, socket, flags) zmq_recvmsg(socket, msg, flags)
+#endif
+
+
+// In order to prevent unused variable warnings when building in non-debug
+// mode use this macro to make assertions.
+#ifndef NDEBUG
+#define ZMQ_ASSERT(expression) assert(expression)
+#else
+#define ZMQ_ASSERT(expression) (void) (expression)
+#endif
+
+namespace zmq
+{
+#ifdef ZMQ_CPP11
+namespace detail
+{
+namespace ranges
+{
+using std::begin;
+using std::end;
+template auto begin(T &&r) -> decltype(begin(std::forward(r)))
+{
+ return begin(std::forward(r));
+}
+template auto end(T &&r) -> decltype(end(std::forward(r)))
+{
+ return end(std::forward(r));
+}
+} // namespace ranges
+
+template using void_t = void;
+
+template
+using iter_value_t = typename std::iterator_traits::value_type;
+
+template
+using range_iter_t = decltype(
+ ranges::begin(std::declval::type &>()));
+
+template using range_value_t = iter_value_t>;
+
+template struct is_range : std::false_type
+{
+};
+
+template
+struct is_range<
+ T,
+ void_t::type &>())
+ == ranges::end(std::declval::type &>()))>>
+ : std::true_type
+{
+};
+
+} // namespace detail
+#endif
+
+typedef zmq_free_fn free_fn;
+typedef zmq_pollitem_t pollitem_t;
+
+// duplicate definition from libzmq 4.3.3
+#if defined _WIN32
+#if defined _WIN64
+typedef unsigned __int64 fd_t;
+#else
+typedef unsigned int fd_t;
+#endif
+#else
+typedef int fd_t;
+#endif
+
+class error_t : public std::exception
+{
+ public:
+ error_t() ZMQ_NOTHROW : errnum(zmq_errno()) {}
+ explicit error_t(int err) ZMQ_NOTHROW : errnum(err) {}
+ virtual const char *what() const ZMQ_NOTHROW ZMQ_OVERRIDE
+ {
+ return zmq_strerror(errnum);
+ }
+ int num() const ZMQ_NOTHROW { return errnum; }
+
+ private:
+ int errnum;
+};
+
+namespace detail {
+inline int poll(zmq_pollitem_t *items_, size_t nitems_, long timeout_)
+{
+ int rc = zmq_poll(items_, static_cast(nitems_), timeout_);
+ if (rc < 0)
+ throw error_t();
+ return rc;
+}
+}
+
+#ifdef ZMQ_CPP11
+ZMQ_DEPRECATED("from 4.8.0, use poll taking std::chrono::duration instead of long")
+inline int poll(zmq_pollitem_t *items_, size_t nitems_, long timeout_)
+#else
+inline int poll(zmq_pollitem_t *items_, size_t nitems_, long timeout_ = -1)
+#endif
+{
+ return detail::poll(items_, nitems_, timeout_);
+}
+
+ZMQ_DEPRECATED("from 4.3.1, use poll taking non-const items")
+inline int poll(zmq_pollitem_t const *items_, size_t nitems_, long timeout_ = -1)
+{
+ return detail::poll(const_cast(items_), nitems_, timeout_);
+}
+
+#ifdef ZMQ_CPP11
+ZMQ_DEPRECATED("from 4.3.1, use poll taking non-const items")
+inline int
+poll(zmq_pollitem_t const *items, size_t nitems, std::chrono::milliseconds timeout)
+{
+ return detail::poll(const_cast(items), nitems,
+ static_cast(timeout.count()));
+}
+
+ZMQ_DEPRECATED("from 4.3.1, use poll taking non-const items")
+inline int poll(std::vector const &items,
+ std::chrono::milliseconds timeout)
+{
+ return detail::poll(const_cast(items.data()), items.size(),
+ static_cast(timeout.count()));
+}
+
+ZMQ_DEPRECATED("from 4.3.1, use poll taking non-const items")
+inline int poll(std::vector const &items, long timeout_ = -1)
+{
+ return detail::poll(const_cast(items.data()), items.size(), timeout_);
+}
+
+inline int
+poll(zmq_pollitem_t *items, size_t nitems, std::chrono::milliseconds timeout = std::chrono::milliseconds{-1})
+{
+ return detail::poll(items, nitems, static_cast(timeout.count()));
+}
+
+inline int poll(std::vector &items,
+ std::chrono::milliseconds timeout = std::chrono::milliseconds{-1})
+{
+ return detail::poll(items.data(), items.size(), static_cast(timeout.count()));
+}
+
+ZMQ_DEPRECATED("from 4.3.1, use poll taking std::chrono::duration instead of long")
+inline int poll(std::vector &items, long timeout_)
+{
+ return detail::poll(items.data(), items.size(), timeout_);
+}
+
+template
+inline int poll(std::array &items,
+ std::chrono::milliseconds timeout = std::chrono::milliseconds{-1})
+{
+ return detail::poll(items.data(), items.size(), static_cast(timeout.count()));
+}
+#endif
+
+
+inline void version(int *major_, int *minor_, int *patch_)
+{
+ zmq_version(major_, minor_, patch_);
+}
+
+#ifdef ZMQ_CPP11
+inline std::tuple version()
+{
+ std::tuple v;
+ zmq_version(&std::get<0>(v), &std::get<1>(v), &std::get<2>(v));
+ return v;
+}
+
+#if !defined(ZMQ_CPP11_PARTIAL)
+namespace detail
+{
+template struct is_char_type
+{
+ // true if character type for string literals in C++11
+ static constexpr bool value =
+ std::is_same::value || std::is_same::value
+ || std::is_same::value || std::is_same::value;
+};
+}
+#endif
+
+#endif
+
+class message_t
+{
+ public:
+ message_t() ZMQ_NOTHROW
+ {
+ int rc = zmq_msg_init(&msg);
+ ZMQ_ASSERT(rc == 0);
+ }
+
+ explicit message_t(size_t size_)
+ {
+ int rc = zmq_msg_init_size(&msg, size_);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ template message_t(ForwardIter first, ForwardIter last)
+ {
+ typedef typename std::iterator_traits::value_type value_t;
+
+ assert(std::distance(first, last) >= 0);
+ size_t const size_ =
+ static_cast(std::distance(first, last)) * sizeof(value_t);
+ int const rc = zmq_msg_init_size(&msg, size_);
+ if (rc != 0)
+ throw error_t();
+ std::copy(first, last, data());
+ }
+
+ message_t(const void *data_, size_t size_)
+ {
+ int rc = zmq_msg_init_size(&msg, size_);
+ if (rc != 0)
+ throw error_t();
+ if (size_) {
+ // this constructor allows (nullptr, 0),
+ // memcpy with a null pointer is UB
+ memcpy(data(), data_, size_);
+ }
+ }
+
+ message_t(void *data_, size_t size_, free_fn *ffn_, void *hint_ = ZMQ_NULLPTR)
+ {
+ int rc = zmq_msg_init_data(&msg, data_, size_, ffn_, hint_);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ // overload set of string-like types and generic containers
+#if defined(ZMQ_CPP11) && !defined(ZMQ_CPP11_PARTIAL)
+ // NOTE this constructor will include the null terminator
+ // when called with a string literal.
+ // An overload taking const char* can not be added because
+ // it would be preferred over this function and break compatiblity.
+ template<
+ class Char,
+ size_t N,
+ typename = typename std::enable_if::value>::type>
+ ZMQ_DEPRECATED("from 4.7.0, use constructors taking iterators, (pointer, size) "
+ "or strings instead")
+ explicit message_t(const Char (&data)[N]) :
+ message_t(detail::ranges::begin(data), detail::ranges::end(data))
+ {
+ }
+
+ template::value
+ && ZMQ_IS_TRIVIALLY_COPYABLE(detail::range_value_t)
+ && !detail::is_char_type>::value
+ && !std::is_same::value>::type>
+ explicit message_t(const Range &rng) :
+ message_t(detail::ranges::begin(rng), detail::ranges::end(rng))
+ {
+ }
+
+ explicit message_t(const std::string &str) : message_t(str.data(), str.size()) {}
+
+#if CPPZMQ_HAS_STRING_VIEW
+ explicit message_t(std::string_view str) : message_t(str.data(), str.size()) {}
+#endif
+
+#endif
+
+#ifdef ZMQ_HAS_RVALUE_REFS
+ message_t(message_t &&rhs) ZMQ_NOTHROW : msg(rhs.msg)
+ {
+ int rc = zmq_msg_init(&rhs.msg);
+ ZMQ_ASSERT(rc == 0);
+ }
+
+ message_t &operator=(message_t &&rhs) ZMQ_NOTHROW
+ {
+ std::swap(msg, rhs.msg);
+ return *this;
+ }
+#endif
+
+ ~message_t() ZMQ_NOTHROW
+ {
+ int rc = zmq_msg_close(&msg);
+ ZMQ_ASSERT(rc == 0);
+ }
+
+ void rebuild()
+ {
+ int rc = zmq_msg_close(&msg);
+ if (rc != 0)
+ throw error_t();
+ rc = zmq_msg_init(&msg);
+ ZMQ_ASSERT(rc == 0);
+ }
+
+ void rebuild(size_t size_)
+ {
+ int rc = zmq_msg_close(&msg);
+ if (rc != 0)
+ throw error_t();
+ rc = zmq_msg_init_size(&msg, size_);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ void rebuild(const void *data_, size_t size_)
+ {
+ int rc = zmq_msg_close(&msg);
+ if (rc != 0)
+ throw error_t();
+ rc = zmq_msg_init_size(&msg, size_);
+ if (rc != 0)
+ throw error_t();
+ memcpy(data(), data_, size_);
+ }
+
+ void rebuild(const std::string &str)
+ {
+ rebuild(str.data(), str.size());
+ }
+
+ void rebuild(void *data_, size_t size_, free_fn *ffn_, void *hint_ = ZMQ_NULLPTR)
+ {
+ int rc = zmq_msg_close(&msg);
+ if (rc != 0)
+ throw error_t();
+ rc = zmq_msg_init_data(&msg, data_, size_, ffn_, hint_);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ ZMQ_DEPRECATED("from 4.3.1, use move taking non-const reference instead")
+ void move(message_t const *msg_)
+ {
+ int rc = zmq_msg_move(&msg, const_cast(msg_->handle()));
+ if (rc != 0)
+ throw error_t();
+ }
+
+ void move(message_t &msg_)
+ {
+ int rc = zmq_msg_move(&msg, msg_.handle());
+ if (rc != 0)
+ throw error_t();
+ }
+
+ ZMQ_DEPRECATED("from 4.3.1, use copy taking non-const reference instead")
+ void copy(message_t const *msg_)
+ {
+ int rc = zmq_msg_copy(&msg, const_cast(msg_->handle()));
+ if (rc != 0)
+ throw error_t();
+ }
+
+ void copy(message_t &msg_)
+ {
+ int rc = zmq_msg_copy(&msg, msg_.handle());
+ if (rc != 0)
+ throw error_t();
+ }
+
+ bool more() const ZMQ_NOTHROW
+ {
+ int rc = zmq_msg_more(const_cast(&msg));
+ return rc != 0;
+ }
+
+ void *data() ZMQ_NOTHROW { return zmq_msg_data(&msg); }
+
+ const void *data() const ZMQ_NOTHROW
+ {
+ return zmq_msg_data(const_cast(&msg));
+ }
+
+ size_t size() const ZMQ_NOTHROW
+ {
+ return zmq_msg_size(const_cast(&msg));
+ }
+
+ ZMQ_NODISCARD bool empty() const ZMQ_NOTHROW { return size() == 0u; }
+
+ template T *data() ZMQ_NOTHROW { return static_cast(data()); }
+
+ template T const *data() const ZMQ_NOTHROW
+ {
+ return static_cast(data());
+ }
+
+ ZMQ_DEPRECATED("from 4.3.0, use operator== instead")
+ bool equal(const message_t *other) const ZMQ_NOTHROW { return *this == *other; }
+
+ bool operator==(const message_t &other) const ZMQ_NOTHROW
+ {
+ const size_t my_size = size();
+ return my_size == other.size() && 0 == memcmp(data(), other.data(), my_size);
+ }
+
+ bool operator!=(const message_t &other) const ZMQ_NOTHROW
+ {
+ return !(*this == other);
+ }
+
+#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3, 2, 0)
+ int get(int property_)
+ {
+ int value = zmq_msg_get(&msg, property_);
+ if (value == -1)
+ throw error_t();
+ return value;
+ }
+#endif
+
+#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 1, 0)
+ const char *gets(const char *property_)
+ {
+ const char *value = zmq_msg_gets(&msg, property_);
+ if (value == ZMQ_NULLPTR)
+ throw error_t();
+ return value;
+ }
+#endif
+
+#if defined(ZMQ_BUILD_DRAFT_API) && ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 0)
+ uint32_t routing_id() const
+ {
+ return zmq_msg_routing_id(const_cast(&msg));
+ }
+
+ void set_routing_id(uint32_t routing_id)
+ {
+ int rc = zmq_msg_set_routing_id(&msg, routing_id);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ const char *group() const
+ {
+ return zmq_msg_group(const_cast(&msg));
+ }
+
+ void set_group(const char *group)
+ {
+ int rc = zmq_msg_set_group(&msg, group);
+ if (rc != 0)
+ throw error_t();
+ }
+#endif
+
+ // interpret message content as a string
+ std::string to_string() const
+ {
+ return std::string(static_cast(data()), size());
+ }
+#if CPPZMQ_HAS_STRING_VIEW
+ // interpret message content as a string
+ std::string_view to_string_view() const noexcept
+ {
+ return std::string_view(static_cast(data()), size());
+ }
+#endif
+
+ /** Dump content to string for debugging.
+ * Ascii chars are readable, the rest is printed as hex.
+ * Probably ridiculously slow.
+ * Use to_string() or to_string_view() for
+ * interpreting the message as a string.
+ */
+ std::string str() const
+ {
+ // Partly mutuated from the same method in zmq::multipart_t
+ std::stringstream os;
+
+ const unsigned char *msg_data = this->data();
+ unsigned char byte;
+ size_t size = this->size();
+ int is_ascii[2] = {0, 0};
+
+ os << "zmq::message_t [size " << std::dec << std::setw(3)
+ << std::setfill('0') << size << "] (";
+ // Totally arbitrary
+ if (size >= 1000) {
+ os << "... too big to print)";
+ } else {
+ while (size--) {
+ byte = *msg_data++;
+
+ is_ascii[1] = (byte >= 32 && byte < 127);
+ if (is_ascii[1] != is_ascii[0])
+ os << " "; // Separate text/non text
+
+ if (is_ascii[1]) {
+ os << byte;
+ } else {
+ os << std::hex << std::uppercase << std::setw(2)
+ << std::setfill('0') << static_cast(byte);
+ }
+ is_ascii[0] = is_ascii[1];
+ }
+ os << ")";
+ }
+ return os.str();
+ }
+
+ void swap(message_t &other) ZMQ_NOTHROW
+ {
+ // this assumes zmq::msg_t from libzmq is trivially relocatable
+ std::swap(msg, other.msg);
+ }
+
+ ZMQ_NODISCARD zmq_msg_t *handle() ZMQ_NOTHROW { return &msg; }
+ ZMQ_NODISCARD const zmq_msg_t *handle() const ZMQ_NOTHROW { return &msg; }
+
+ private:
+ // The underlying message
+ zmq_msg_t msg;
+
+ // Disable implicit message copying, so that users won't use shared
+ // messages (less efficient) without being aware of the fact.
+ message_t(const message_t &) ZMQ_DELETED_FUNCTION;
+ void operator=(const message_t &) ZMQ_DELETED_FUNCTION;
+};
+
+inline void swap(message_t &a, message_t &b) ZMQ_NOTHROW
+{
+ a.swap(b);
+}
+
+#ifdef ZMQ_CPP11
+enum class ctxopt
+{
+#ifdef ZMQ_BLOCKY
+ blocky = ZMQ_BLOCKY,
+#endif
+#ifdef ZMQ_IO_THREADS
+ io_threads = ZMQ_IO_THREADS,
+#endif
+#ifdef ZMQ_THREAD_SCHED_POLICY
+ thread_sched_policy = ZMQ_THREAD_SCHED_POLICY,
+#endif
+#ifdef ZMQ_THREAD_PRIORITY
+ thread_priority = ZMQ_THREAD_PRIORITY,
+#endif
+#ifdef ZMQ_THREAD_AFFINITY_CPU_ADD
+ thread_affinity_cpu_add = ZMQ_THREAD_AFFINITY_CPU_ADD,
+#endif
+#ifdef ZMQ_THREAD_AFFINITY_CPU_REMOVE
+ thread_affinity_cpu_remove = ZMQ_THREAD_AFFINITY_CPU_REMOVE,
+#endif
+#ifdef ZMQ_THREAD_NAME_PREFIX
+ thread_name_prefix = ZMQ_THREAD_NAME_PREFIX,
+#endif
+#ifdef ZMQ_MAX_MSGSZ
+ max_msgsz = ZMQ_MAX_MSGSZ,
+#endif
+#ifdef ZMQ_ZERO_COPY_RECV
+ zero_copy_recv = ZMQ_ZERO_COPY_RECV,
+#endif
+#ifdef ZMQ_MAX_SOCKETS
+ max_sockets = ZMQ_MAX_SOCKETS,
+#endif
+#ifdef ZMQ_SOCKET_LIMIT
+ socket_limit = ZMQ_SOCKET_LIMIT,
+#endif
+#ifdef ZMQ_IPV6
+ ipv6 = ZMQ_IPV6,
+#endif
+#ifdef ZMQ_MSG_T_SIZE
+ msg_t_size = ZMQ_MSG_T_SIZE
+#endif
+};
+#endif
+
+class context_t
+{
+ public:
+ context_t()
+ {
+ ptr = zmq_ctx_new();
+ if (ptr == ZMQ_NULLPTR)
+ throw error_t();
+ }
+
+
+ explicit context_t(int io_threads_, int max_sockets_ = ZMQ_MAX_SOCKETS_DFLT)
+ {
+ ptr = zmq_ctx_new();
+ if (ptr == ZMQ_NULLPTR)
+ throw error_t();
+
+ int rc = zmq_ctx_set(ptr, ZMQ_IO_THREADS, io_threads_);
+ ZMQ_ASSERT(rc == 0);
+
+ rc = zmq_ctx_set(ptr, ZMQ_MAX_SOCKETS, max_sockets_);
+ ZMQ_ASSERT(rc == 0);
+ }
+
+#ifdef ZMQ_HAS_RVALUE_REFS
+ context_t(context_t &&rhs) ZMQ_NOTHROW : ptr(rhs.ptr) { rhs.ptr = ZMQ_NULLPTR; }
+ context_t &operator=(context_t &&rhs) ZMQ_NOTHROW
+ {
+ close();
+ std::swap(ptr, rhs.ptr);
+ return *this;
+ }
+#endif
+
+ ~context_t() ZMQ_NOTHROW { close(); }
+
+ ZMQ_CPP11_DEPRECATED("from 4.7.0, use set taking zmq::ctxopt instead")
+ int setctxopt(int option_, int optval_)
+ {
+ int rc = zmq_ctx_set(ptr, option_, optval_);
+ ZMQ_ASSERT(rc == 0);
+ return rc;
+ }
+
+ ZMQ_CPP11_DEPRECATED("from 4.7.0, use get taking zmq::ctxopt instead")
+ int getctxopt(int option_) { return zmq_ctx_get(ptr, option_); }
+
+#ifdef ZMQ_CPP11
+ void set(ctxopt option, int optval)
+ {
+ int rc = zmq_ctx_set(ptr, static_cast(option), optval);
+ if (rc == -1)
+ throw error_t();
+ }
+
+ ZMQ_NODISCARD int get(ctxopt option)
+ {
+ int rc = zmq_ctx_get(ptr, static_cast(option));
+ // some options have a default value of -1
+ // which is unfortunate, and may result in errors
+ // that don't make sense
+ if (rc == -1)
+ throw error_t();
+ return rc;
+ }
+#endif
+
+ // Terminates context (see also shutdown()).
+ void close() ZMQ_NOTHROW
+ {
+ if (ptr == ZMQ_NULLPTR)
+ return;
+
+ int rc;
+ do {
+ rc = zmq_ctx_term(ptr);
+ } while (rc == -1 && errno == EINTR);
+
+ ZMQ_ASSERT(rc == 0);
+ ptr = ZMQ_NULLPTR;
+ }
+
+ // Shutdown context in preparation for termination (close()).
+ // Causes all blocking socket operations and any further
+ // socket operations to return with ETERM.
+ void shutdown() ZMQ_NOTHROW
+ {
+ if (ptr == ZMQ_NULLPTR)
+ return;
+ int rc = zmq_ctx_shutdown(ptr);
+ ZMQ_ASSERT(rc == 0);
+ }
+
+ // Be careful with this, it's probably only useful for
+ // using the C api together with an existing C++ api.
+ // Normally you should never need to use this.
+ ZMQ_EXPLICIT operator void *() ZMQ_NOTHROW { return ptr; }
+
+ ZMQ_EXPLICIT operator void const *() const ZMQ_NOTHROW { return ptr; }
+
+ ZMQ_NODISCARD void *handle() ZMQ_NOTHROW { return ptr; }
+
+ ZMQ_DEPRECATED("from 4.7.0, use handle() != nullptr instead")
+ operator bool() const ZMQ_NOTHROW { return ptr != ZMQ_NULLPTR; }
+
+ void swap(context_t &other) ZMQ_NOTHROW { std::swap(ptr, other.ptr); }
+
+ private:
+ void *ptr;
+
+ context_t(const context_t &) ZMQ_DELETED_FUNCTION;
+ void operator=(const context_t &) ZMQ_DELETED_FUNCTION;
+};
+
+inline void swap(context_t &a, context_t &b) ZMQ_NOTHROW
+{
+ a.swap(b);
+}
+
+#ifdef ZMQ_CPP11
+
+struct recv_buffer_size
+{
+ size_t size; // number of bytes written to buffer
+ size_t untruncated_size; // untruncated message size in bytes
+
+ ZMQ_NODISCARD bool truncated() const noexcept
+ {
+ return size != untruncated_size;
+ }
+};
+
+#if CPPZMQ_HAS_OPTIONAL
+
+using send_result_t = std::optional;
+using recv_result_t = std::optional;
+using recv_buffer_result_t = std::optional;
+
+#else
+
+namespace detail
+{
+// A C++11 type emulating the most basic
+// operations of std::optional for trivial types
+template class trivial_optional
+{
+ public:
+ static_assert(std::is_trivial::value, "T must be trivial");
+ using value_type = T;
+
+ trivial_optional() = default;
+ trivial_optional(T value) noexcept : _value(value), _has_value(true) {}
+
+ const T *operator->() const noexcept
+ {
+ assert(_has_value);
+ return &_value;
+ }
+ T *operator->() noexcept
+ {
+ assert(_has_value);
+ return &_value;
+ }
+
+ const T &operator*() const noexcept
+ {
+ assert(_has_value);
+ return _value;
+ }
+ T &operator*() noexcept
+ {
+ assert(_has_value);
+ return _value;
+ }
+
+ T &value()
+ {
+ if (!_has_value)
+ throw std::exception();
+ return _value;
+ }
+ const T &value() const
+ {
+ if (!_has_value)
+ throw std::exception();
+ return _value;
+ }
+
+ explicit operator bool() const noexcept { return _has_value; }
+ bool has_value() const noexcept { return _has_value; }
+
+ private:
+ T _value{};
+ bool _has_value{false};
+};
+} // namespace detail
+
+using send_result_t = detail::trivial_optional;
+using recv_result_t = detail::trivial_optional;
+using recv_buffer_result_t = detail::trivial_optional;
+
+#endif
+
+namespace detail
+{
+template constexpr T enum_bit_or(T a, T b) noexcept
+{
+ static_assert(std::is_enum::value, "must be enum");
+ using U = typename std::underlying_type::type;
+ return static_cast(static_cast(a) | static_cast(b));
+}
+template constexpr T enum_bit_and(T a, T b) noexcept
+{
+ static_assert(std::is_enum::value, "must be enum");
+ using U = typename std::underlying_type::type;
+ return static_cast(static_cast(a) & static_cast(b));
+}
+template constexpr T enum_bit_xor(T a, T b) noexcept
+{
+ static_assert(std::is_enum::value, "must be enum");
+ using U = typename std::underlying_type::type;
+ return static_cast(static_cast(a) ^ static_cast(b));
+}
+template constexpr T enum_bit_not(T a) noexcept
+{
+ static_assert(std::is_enum::value, "must be enum");
+ using U = typename std::underlying_type::type;
+ return static_cast(~static_cast(a));
+}
+} // namespace detail
+
+// partially satisfies named requirement BitmaskType
+enum class send_flags : int
+{
+ none = 0,
+ dontwait = ZMQ_DONTWAIT,
+ sndmore = ZMQ_SNDMORE
+};
+
+constexpr send_flags operator|(send_flags a, send_flags b) noexcept
+{
+ return detail::enum_bit_or(a, b);
+}
+constexpr send_flags operator&(send_flags a, send_flags b) noexcept
+{
+ return detail::enum_bit_and(a, b);
+}
+constexpr send_flags operator^(send_flags a, send_flags b) noexcept
+{
+ return detail::enum_bit_xor(a, b);
+}
+constexpr send_flags operator~(send_flags a) noexcept
+{
+ return detail::enum_bit_not(a);
+}
+
+// partially satisfies named requirement BitmaskType
+enum class recv_flags : int
+{
+ none = 0,
+ dontwait = ZMQ_DONTWAIT
+};
+
+constexpr recv_flags operator|(recv_flags a, recv_flags b) noexcept
+{
+ return detail::enum_bit_or(a, b);
+}
+constexpr recv_flags operator&(recv_flags a, recv_flags b) noexcept
+{
+ return detail::enum_bit_and(a, b);
+}
+constexpr recv_flags operator^(recv_flags a, recv_flags b) noexcept
+{
+ return detail::enum_bit_xor(a, b);
+}
+constexpr recv_flags operator~(recv_flags a) noexcept
+{
+ return detail::enum_bit_not(a);
+}
+
+
+// mutable_buffer, const_buffer and buffer are based on
+// the Networking TS specification, draft:
+// http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/n4771.pdf
+
+class mutable_buffer
+{
+ public:
+ constexpr mutable_buffer() noexcept : _data(nullptr), _size(0) {}
+ constexpr mutable_buffer(void *p, size_t n) noexcept : _data(p), _size(n)
+ {
+#ifdef ZMQ_EXTENDED_CONSTEXPR
+ assert(p != nullptr || n == 0);
+#endif
+ }
+
+ constexpr void *data() const noexcept { return _data; }
+ constexpr size_t size() const noexcept { return _size; }
+ mutable_buffer &operator+=(size_t n) noexcept
+ {
+ // (std::min) is a workaround for when a min macro is defined
+ const auto shift = (std::min)(n, _size);
+ _data = static_cast(_data) + shift;
+ _size -= shift;
+ return *this;
+ }
+
+ private:
+ void *_data;
+ size_t _size;
+};
+
+inline mutable_buffer operator+(const mutable_buffer &mb, size_t n) noexcept
+{
+ return mutable_buffer(static_cast(mb.data()) + (std::min)(n, mb.size()),
+ mb.size() - (std::min)(n, mb.size()));
+}
+inline mutable_buffer operator+(size_t n, const mutable_buffer &mb) noexcept
+{
+ return mb + n;
+}
+
+class const_buffer
+{
+ public:
+ constexpr const_buffer() noexcept : _data(nullptr), _size(0) {}
+ constexpr const_buffer(const void *p, size_t n) noexcept : _data(p), _size(n)
+ {
+#ifdef ZMQ_EXTENDED_CONSTEXPR
+ assert(p != nullptr || n == 0);
+#endif
+ }
+ constexpr const_buffer(const mutable_buffer &mb) noexcept :
+ _data(mb.data()), _size(mb.size())
+ {
+ }
+
+ constexpr const void *data() const noexcept { return _data; }
+ constexpr size_t size() const noexcept { return _size; }
+ const_buffer &operator+=(size_t n) noexcept
+ {
+ const auto shift = (std::min)(n, _size);
+ _data = static_cast(_data) + shift;
+ _size -= shift;
+ return *this;
+ }
+
+ private:
+ const void *_data;
+ size_t _size;
+};
+
+inline const_buffer operator+(const const_buffer &cb, size_t n) noexcept
+{
+ return const_buffer(static_cast(cb.data())
+ + (std::min)(n, cb.size()),
+ cb.size() - (std::min)(n, cb.size()));
+}
+inline const_buffer operator+(size_t n, const const_buffer &cb) noexcept
+{
+ return cb + n;
+}
+
+// buffer creation
+
+constexpr mutable_buffer buffer(void *p, size_t n) noexcept
+{
+ return mutable_buffer(p, n);
+}
+constexpr const_buffer buffer(const void *p, size_t n) noexcept
+{
+ return const_buffer(p, n);
+}
+constexpr mutable_buffer buffer(const mutable_buffer &mb) noexcept
+{
+ return mb;
+}
+inline mutable_buffer buffer(const mutable_buffer &mb, size_t n) noexcept
+{
+ return mutable_buffer(mb.data(), (std::min)(mb.size(), n));
+}
+constexpr const_buffer buffer(const const_buffer &cb) noexcept
+{
+ return cb;
+}
+inline const_buffer buffer(const const_buffer &cb, size_t n) noexcept
+{
+ return const_buffer(cb.data(), (std::min)(cb.size(), n));
+}
+
+namespace detail
+{
+template struct is_buffer
+{
+ static constexpr bool value =
+ std::is_same::value || std::is_same::value;
+};
+
+template struct is_pod_like
+{
+ // NOTE: The networking draft N4771 section 16.11 requires
+ // T in the buffer functions below to be
+ // trivially copyable OR standard layout.
+ // Here we decide to be conservative and require both.
+ static constexpr bool value =
+ ZMQ_IS_TRIVIALLY_COPYABLE(T) && std::is_standard_layout::value;
+};
+
+template constexpr auto seq_size(const C &c) noexcept -> decltype(c.size())
+{
+ return c.size();
+}
+template
+constexpr size_t seq_size(const T (&/*array*/)[N]) noexcept
+{
+ return N;
+}
+
+template
+auto buffer_contiguous_sequence(Seq &&seq) noexcept
+ -> decltype(buffer(std::addressof(*std::begin(seq)), size_t{}))
+{
+ using T = typename std::remove_cv<
+ typename std::remove_reference::type>::type;
+ static_assert(detail::is_pod_like::value, "T must be POD");
+
+ const auto size = seq_size(seq);
+ return buffer(size != 0u ? std::addressof(*std::begin(seq)) : nullptr,
+ size * sizeof(T));
+}
+template
+auto buffer_contiguous_sequence(Seq &&seq, size_t n_bytes) noexcept
+ -> decltype(buffer_contiguous_sequence(seq))
+{
+ using T = typename std::remove_cv<
+ typename std::remove_reference::type>::type;
+ static_assert(detail::is_pod_like::value, "T must be POD");
+
+ const auto size = seq_size(seq);
+ return buffer(size != 0u ? std::addressof(*std::begin(seq)) : nullptr,
+ (std::min)(size * sizeof(T), n_bytes));
+}
+
+} // namespace detail
+
+// C array
+template mutable_buffer buffer(T (&data)[N]) noexcept
+{
+ return detail::buffer_contiguous_sequence(data);
+}
+template
+mutable_buffer buffer(T (&data)[N], size_t n_bytes) noexcept
+{
+ return detail::buffer_contiguous_sequence(data, n_bytes);
+}
+template const_buffer buffer(const T (&data)[N]) noexcept
+{
+ return detail::buffer_contiguous_sequence(data);
+}
+template
+const_buffer buffer(const T (&data)[N], size_t n_bytes) noexcept
+{
+ return detail::buffer_contiguous_sequence(data, n_bytes);
+}
+// std::array
+template mutable_buffer buffer(std::array &data) noexcept
+{
+ return detail::buffer_contiguous_sequence(data);
+}
+template
+mutable_buffer buffer(std::array &data, size_t n_bytes) noexcept
+{
+ return detail::buffer_contiguous_sequence(data, n_bytes);
+}
+template
+const_buffer buffer(std::array &data) noexcept
+{
+ return detail::buffer_contiguous_sequence(data);
+}
+template
+const_buffer buffer(std::array &data, size_t n_bytes) noexcept
+{
+ return detail::buffer_contiguous_sequence(data, n_bytes);
+}
+template
+const_buffer buffer(const std::array &data) noexcept
+{
+ return detail::buffer_contiguous_sequence(data);
+}
+template
+const_buffer buffer(const std::array &data, size_t n_bytes) noexcept
+{
+ return detail::buffer_contiguous_sequence(data, n_bytes);
+}
+// std::vector
+template
+mutable_buffer buffer(std::vector &data) noexcept
+{
+ return detail::buffer_contiguous_sequence(data);
+}
+template
+mutable_buffer buffer(std::vector &data, size_t n_bytes) noexcept
+{
+ return detail::buffer_contiguous_sequence(data, n_bytes);
+}
+template
+const_buffer buffer(const std::vector &data) noexcept
+{
+ return detail::buffer_contiguous_sequence(data);
+}
+template
+const_buffer buffer(const std::vector &data, size_t n_bytes) noexcept
+{
+ return detail::buffer_contiguous_sequence(data, n_bytes);
+}
+// std::basic_string
+template
+mutable_buffer buffer(std::basic_string &data) noexcept
+{
+ return detail::buffer_contiguous_sequence(data);
+}
+template
+mutable_buffer buffer(std::basic_string &data,
+ size_t n_bytes) noexcept
+{
+ return detail::buffer_contiguous_sequence(data, n_bytes);
+}
+template
+const_buffer buffer(const std::basic_string &data) noexcept
+{
+ return detail::buffer_contiguous_sequence(data);
+}
+template
+const_buffer buffer(const std::basic_string &data,
+ size_t n_bytes) noexcept
+{
+ return detail::buffer_contiguous_sequence(data, n_bytes);
+}
+
+#if CPPZMQ_HAS_STRING_VIEW
+// std::basic_string_view
+template
+const_buffer buffer(std::basic_string_view data) noexcept
+{
+ return detail::buffer_contiguous_sequence(data);
+}
+template
+const_buffer buffer(std::basic_string_view data, size_t n_bytes) noexcept
+{
+ return detail::buffer_contiguous_sequence(data, n_bytes);
+}
+#endif
+
+// Buffer for a string literal (null terminated)
+// where the buffer size excludes the terminating character.
+// Equivalent to zmq::buffer(std::string_view("...")).
+template
+constexpr const_buffer str_buffer(const Char (&data)[N]) noexcept
+{
+ static_assert(detail::is_pod_like::value, "Char must be POD");
+#ifdef ZMQ_EXTENDED_CONSTEXPR
+ assert(data[N - 1] == Char{0});
+#endif
+ return const_buffer(static_cast(data), (N - 1) * sizeof(Char));
+}
+
+namespace literals
+{
+constexpr const_buffer operator"" _zbuf(const char *str, size_t len) noexcept
+{
+ return const_buffer(str, len * sizeof(char));
+}
+constexpr const_buffer operator"" _zbuf(const wchar_t *str, size_t len) noexcept
+{
+ return const_buffer(str, len * sizeof(wchar_t));
+}
+constexpr const_buffer operator"" _zbuf(const char16_t *str, size_t len) noexcept
+{
+ return const_buffer(str, len * sizeof(char16_t));
+}
+constexpr const_buffer operator"" _zbuf(const char32_t *str, size_t len) noexcept
+{
+ return const_buffer(str, len * sizeof(char32_t));
+}
+}
+
+#ifdef ZMQ_CPP11
+enum class socket_type : int
+{
+ req = ZMQ_REQ,
+ rep = ZMQ_REP,
+ dealer = ZMQ_DEALER,
+ router = ZMQ_ROUTER,
+ pub = ZMQ_PUB,
+ sub = ZMQ_SUB,
+ xpub = ZMQ_XPUB,
+ xsub = ZMQ_XSUB,
+ push = ZMQ_PUSH,
+ pull = ZMQ_PULL,
+#if defined(ZMQ_BUILD_DRAFT_API) && ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 0)
+ server = ZMQ_SERVER,
+ client = ZMQ_CLIENT,
+ radio = ZMQ_RADIO,
+ dish = ZMQ_DISH,
+ gather = ZMQ_GATHER,
+ scatter = ZMQ_SCATTER,
+ dgram = ZMQ_DGRAM,
+#endif
+#if defined(ZMQ_BUILD_DRAFT_API) && ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 3, 3)
+ peer = ZMQ_PEER,
+ channel = ZMQ_CHANNEL,
+#endif
+#if ZMQ_VERSION_MAJOR >= 4
+ stream = ZMQ_STREAM,
+#endif
+ pair = ZMQ_PAIR
+};
+#endif
+
+namespace sockopt
+{
+// There are two types of options,
+// integral type with known compiler time size (int, bool, int64_t, uint64_t)
+// and arrays with dynamic size (strings, binary data).
+
+// BoolUnit: if true accepts values of type bool (but passed as T into libzmq)
+template struct integral_option
+{
+};
+
+// NullTerm:
+// 0: binary data
+// 1: null-terminated string (`getsockopt` size includes null)
+// 2: binary (size 32) or Z85 encoder string of size 41 (null included)
+template struct array_option
+{
+};
+
+#define ZMQ_DEFINE_INTEGRAL_OPT(OPT, NAME, TYPE) \
+ using NAME##_t = integral_option; \
+ ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME {}
+#define ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(OPT, NAME, TYPE) \
+ using NAME##_t = integral_option; \
+ ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME {}
+#define ZMQ_DEFINE_ARRAY_OPT(OPT, NAME) \
+ using NAME##_t = array_option; \
+ ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME {}
+#define ZMQ_DEFINE_ARRAY_OPT_BINARY(OPT, NAME) \
+ using NAME##_t = array_option; \
+ ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME {}
+#define ZMQ_DEFINE_ARRAY_OPT_BIN_OR_Z85(OPT, NAME) \
+ using NAME##_t = array_option; \
+ ZMQ_INLINE_VAR ZMQ_CONSTEXPR_VAR NAME##_t NAME {}
+
+// deprecated, use zmq::fd_t
+using cppzmq_fd_t = ::zmq::fd_t;
+
+#ifdef ZMQ_AFFINITY
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_AFFINITY, affinity, uint64_t);
+#endif
+#ifdef ZMQ_BACKLOG
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_BACKLOG, backlog, int);
+#endif
+#ifdef ZMQ_BINDTODEVICE
+ZMQ_DEFINE_ARRAY_OPT_BINARY(ZMQ_BINDTODEVICE, bindtodevice);
+#endif
+#ifdef ZMQ_CONFLATE
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_CONFLATE, conflate, int);
+#endif
+#ifdef ZMQ_CONNECT_ROUTING_ID
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_CONNECT_ROUTING_ID, connect_routing_id);
+#endif
+#ifdef ZMQ_CONNECT_TIMEOUT
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_CONNECT_TIMEOUT, connect_timeout, int);
+#endif
+#ifdef ZMQ_CURVE_PUBLICKEY
+ZMQ_DEFINE_ARRAY_OPT_BIN_OR_Z85(ZMQ_CURVE_PUBLICKEY, curve_publickey);
+#endif
+#ifdef ZMQ_CURVE_SECRETKEY
+ZMQ_DEFINE_ARRAY_OPT_BIN_OR_Z85(ZMQ_CURVE_SECRETKEY, curve_secretkey);
+#endif
+#ifdef ZMQ_CURVE_SERVER
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_CURVE_SERVER, curve_server, int);
+#endif
+#ifdef ZMQ_CURVE_SERVERKEY
+ZMQ_DEFINE_ARRAY_OPT_BIN_OR_Z85(ZMQ_CURVE_SERVERKEY, curve_serverkey);
+#endif
+#ifdef ZMQ_DISCONNECT_MSG
+ZMQ_DEFINE_ARRAY_OPT_BINARY(ZMQ_DISCONNECT_MSG, disconnect_msg);
+#endif
+#ifdef ZMQ_EVENTS
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_EVENTS, events, int);
+#endif
+#ifdef ZMQ_FD
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_FD, fd, ::zmq::fd_t);
+#endif
+#ifdef ZMQ_GSSAPI_PLAINTEXT
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_GSSAPI_PLAINTEXT, gssapi_plaintext, int);
+#endif
+#ifdef ZMQ_GSSAPI_SERVER
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_GSSAPI_SERVER, gssapi_server, int);
+#endif
+#ifdef ZMQ_GSSAPI_SERVICE_PRINCIPAL
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_GSSAPI_SERVICE_PRINCIPAL, gssapi_service_principal);
+#endif
+#ifdef ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_GSSAPI_SERVICE_PRINCIPAL_NAMETYPE,
+ gssapi_service_principal_nametype,
+ int);
+#endif
+#ifdef ZMQ_GSSAPI_PRINCIPAL
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_GSSAPI_PRINCIPAL, gssapi_principal);
+#endif
+#ifdef ZMQ_GSSAPI_PRINCIPAL_NAMETYPE
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_GSSAPI_PRINCIPAL_NAMETYPE,
+ gssapi_principal_nametype,
+ int);
+#endif
+#ifdef ZMQ_HANDSHAKE_IVL
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_HANDSHAKE_IVL, handshake_ivl, int);
+#endif
+#ifdef ZMQ_HEARTBEAT_IVL
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_HEARTBEAT_IVL, heartbeat_ivl, int);
+#endif
+#ifdef ZMQ_HEARTBEAT_TIMEOUT
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_HEARTBEAT_TIMEOUT, heartbeat_timeout, int);
+#endif
+#ifdef ZMQ_HEARTBEAT_TTL
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_HEARTBEAT_TTL, heartbeat_ttl, int);
+#endif
+#ifdef ZMQ_HELLO_MSG
+ZMQ_DEFINE_ARRAY_OPT_BINARY(ZMQ_HELLO_MSG, hello_msg);
+#endif
+#ifdef ZMQ_IMMEDIATE
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_IMMEDIATE, immediate, int);
+#endif
+#ifdef ZMQ_INVERT_MATCHING
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_INVERT_MATCHING, invert_matching, int);
+#endif
+#ifdef ZMQ_IPV6
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_IPV6, ipv6, int);
+#endif
+#ifdef ZMQ_LAST_ENDPOINT
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_LAST_ENDPOINT, last_endpoint);
+#endif
+#ifdef ZMQ_LINGER
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_LINGER, linger, int);
+#endif
+#ifdef ZMQ_MAXMSGSIZE
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_MAXMSGSIZE, maxmsgsize, int64_t);
+#endif
+#ifdef ZMQ_MECHANISM
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_MECHANISM, mechanism, int);
+#endif
+#ifdef ZMQ_METADATA
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_METADATA, metadata);
+#endif
+#ifdef ZMQ_MULTICAST_HOPS
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_MULTICAST_HOPS, multicast_hops, int);
+#endif
+#ifdef ZMQ_MULTICAST_LOOP
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_MULTICAST_LOOP, multicast_loop, int);
+#endif
+#ifdef ZMQ_MULTICAST_MAXTPDU
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_MULTICAST_MAXTPDU, multicast_maxtpdu, int);
+#endif
+#ifdef ZMQ_ONLY_FIRST_SUBSCRIBE
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_ONLY_FIRST_SUBSCRIBE, only_first_subscribe, int);
+#endif
+#ifdef ZMQ_PLAIN_SERVER
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_PLAIN_SERVER, plain_server, int);
+#endif
+#ifdef ZMQ_PLAIN_PASSWORD
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_PLAIN_PASSWORD, plain_password);
+#endif
+#ifdef ZMQ_PLAIN_USERNAME
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_PLAIN_USERNAME, plain_username);
+#endif
+#ifdef ZMQ_PRIORITY
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_PRIORITY, priority, int);
+#endif
+#ifdef ZMQ_USE_FD
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_USE_FD, use_fd, int);
+#endif
+#ifdef ZMQ_PROBE_ROUTER
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_PROBE_ROUTER, probe_router, int);
+#endif
+#ifdef ZMQ_RATE
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_RATE, rate, int);
+#endif
+#ifdef ZMQ_RCVBUF
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_RCVBUF, rcvbuf, int);
+#endif
+#ifdef ZMQ_RCVHWM
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_RCVHWM, rcvhwm, int);
+#endif
+#ifdef ZMQ_RCVMORE
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_RCVMORE, rcvmore, int);
+#endif
+#ifdef ZMQ_RCVTIMEO
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_RCVTIMEO, rcvtimeo, int);
+#endif
+#ifdef ZMQ_RECONNECT_IVL
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_RECONNECT_IVL, reconnect_ivl, int);
+#endif
+#ifdef ZMQ_RECONNECT_IVL_MAX
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_RECONNECT_IVL_MAX, reconnect_ivl_max, int);
+#endif
+#ifdef ZMQ_RECONNECT_STOP
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_RECONNECT_STOP, reconnect_stop, int);
+#endif
+#ifdef ZMQ_RECOVERY_IVL
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_RECOVERY_IVL, recovery_ivl, int);
+#endif
+#ifdef ZMQ_REQ_CORRELATE
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_REQ_CORRELATE, req_correlate, int);
+#endif
+#ifdef ZMQ_REQ_RELAXED
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_REQ_RELAXED, req_relaxed, int);
+#endif
+#ifdef ZMQ_ROUTER_HANDOVER
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_ROUTER_HANDOVER, router_handover, int);
+#endif
+#ifdef ZMQ_ROUTER_MANDATORY
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_ROUTER_MANDATORY, router_mandatory, int);
+#endif
+#ifdef ZMQ_ROUTER_NOTIFY
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_ROUTER_NOTIFY, router_notify, int);
+#endif
+#ifdef ZMQ_ROUTER_RAW
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_ROUTER_RAW, router_raw, int);
+#endif
+#ifdef ZMQ_ROUTING_ID
+ZMQ_DEFINE_ARRAY_OPT_BINARY(ZMQ_ROUTING_ID, routing_id);
+#endif
+#ifdef ZMQ_SNDBUF
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_SNDBUF, sndbuf, int);
+#endif
+#ifdef ZMQ_SNDHWM
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_SNDHWM, sndhwm, int);
+#endif
+#ifdef ZMQ_SNDTIMEO
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_SNDTIMEO, sndtimeo, int);
+#endif
+#ifdef ZMQ_SOCKS_PASSWORD
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_SOCKS_PASSWORD, socks_password);
+#endif
+#ifdef ZMQ_SOCKS_PROXY
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_SOCKS_PROXY, socks_proxy);
+#endif
+#ifdef ZMQ_SOCKS_USERNAME
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_SOCKS_USERNAME, socks_username);
+#endif
+#ifdef ZMQ_STREAM_NOTIFY
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_STREAM_NOTIFY, stream_notify, int);
+#endif
+#ifdef ZMQ_SUBSCRIBE
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_SUBSCRIBE, subscribe);
+#endif
+#ifdef ZMQ_TCP_KEEPALIVE
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_TCP_KEEPALIVE, tcp_keepalive, int);
+#endif
+#ifdef ZMQ_TCP_KEEPALIVE_CNT
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_TCP_KEEPALIVE_CNT, tcp_keepalive_cnt, int);
+#endif
+#ifdef ZMQ_TCP_KEEPALIVE_IDLE
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_TCP_KEEPALIVE_IDLE, tcp_keepalive_idle, int);
+#endif
+#ifdef ZMQ_TCP_KEEPALIVE_INTVL
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_TCP_KEEPALIVE_INTVL, tcp_keepalive_intvl, int);
+#endif
+#ifdef ZMQ_TCP_MAXRT
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_TCP_MAXRT, tcp_maxrt, int);
+#endif
+#ifdef ZMQ_THREAD_SAFE
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_THREAD_SAFE, thread_safe, int);
+#endif
+#ifdef ZMQ_TOS
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_TOS, tos, int);
+#endif
+#ifdef ZMQ_TYPE
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_TYPE, type, int);
+#ifdef ZMQ_CPP11
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_TYPE, socket_type, socket_type);
+#endif // ZMQ_CPP11
+#endif // ZMQ_TYPE
+#ifdef ZMQ_UNSUBSCRIBE
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_UNSUBSCRIBE, unsubscribe);
+#endif
+#ifdef ZMQ_VMCI_BUFFER_SIZE
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_VMCI_BUFFER_SIZE, vmci_buffer_size, uint64_t);
+#endif
+#ifdef ZMQ_VMCI_BUFFER_MIN_SIZE
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_VMCI_BUFFER_MIN_SIZE, vmci_buffer_min_size, uint64_t);
+#endif
+#ifdef ZMQ_VMCI_BUFFER_MAX_SIZE
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_VMCI_BUFFER_MAX_SIZE, vmci_buffer_max_size, uint64_t);
+#endif
+#ifdef ZMQ_VMCI_CONNECT_TIMEOUT
+ZMQ_DEFINE_INTEGRAL_OPT(ZMQ_VMCI_CONNECT_TIMEOUT, vmci_connect_timeout, int);
+#endif
+#ifdef ZMQ_XPUB_VERBOSE
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_XPUB_VERBOSE, xpub_verbose, int);
+#endif
+#ifdef ZMQ_XPUB_VERBOSER
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_XPUB_VERBOSER, xpub_verboser, int);
+#endif
+#ifdef ZMQ_XPUB_MANUAL
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_XPUB_MANUAL, xpub_manual, int);
+#endif
+#ifdef ZMQ_XPUB_MANUAL_LAST_VALUE
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_XPUB_MANUAL_LAST_VALUE, xpub_manual_last_value, int);
+#endif
+#ifdef ZMQ_XPUB_NODROP
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_XPUB_NODROP, xpub_nodrop, int);
+#endif
+#ifdef ZMQ_XPUB_WELCOME_MSG
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_XPUB_WELCOME_MSG, xpub_welcome_msg);
+#endif
+#ifdef ZMQ_ZAP_ENFORCE_DOMAIN
+ZMQ_DEFINE_INTEGRAL_BOOL_UNIT_OPT(ZMQ_ZAP_ENFORCE_DOMAIN, zap_enforce_domain, int);
+#endif
+#ifdef ZMQ_ZAP_DOMAIN
+ZMQ_DEFINE_ARRAY_OPT(ZMQ_ZAP_DOMAIN, zap_domain);
+#endif
+
+} // namespace sockopt
+#endif // ZMQ_CPP11
+
+
+namespace detail
+{
+class socket_base
+{
+ public:
+ socket_base() ZMQ_NOTHROW : _handle(ZMQ_NULLPTR) {}
+ ZMQ_EXPLICIT socket_base(void *handle) ZMQ_NOTHROW : _handle(handle) {}
+
+ template
+ ZMQ_CPP11_DEPRECATED("from 4.7.0, use `set` taking option from zmq::sockopt")
+ void setsockopt(int option_, T const &optval)
+ {
+ setsockopt(option_, &optval, sizeof(T));
+ }
+
+ ZMQ_CPP11_DEPRECATED("from 4.7.0, use `set` taking option from zmq::sockopt")
+ void setsockopt(int option_, const void *optval_, size_t optvallen_)
+ {
+ int rc = zmq_setsockopt(_handle, option_, optval_, optvallen_);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ ZMQ_CPP11_DEPRECATED("from 4.7.0, use `get` taking option from zmq::sockopt")
+ void getsockopt(int option_, void *optval_, size_t *optvallen_) const
+ {
+ int rc = zmq_getsockopt(_handle, option_, optval_, optvallen_);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ template
+ ZMQ_CPP11_DEPRECATED("from 4.7.0, use `get` taking option from zmq::sockopt")
+ T getsockopt(int option_) const
+ {
+ T optval;
+ size_t optlen = sizeof(T);
+ getsockopt(option_, &optval, &optlen);
+ return optval;
+ }
+
+#ifdef ZMQ_CPP11
+ // Set integral socket option, e.g.
+ // `socket.set(zmq::sockopt::linger, 0)`
+ template
+ void set(sockopt::integral_option, const T &val)
+ {
+ static_assert(std::is_integral::value, "T must be integral");
+ set_option(Opt, &val, sizeof val);
+ }
+
+ // Set integral socket option from boolean, e.g.
+ // `socket.set(zmq::sockopt::immediate, false)`
+ template
+ void set(sockopt::integral_option, bool val)
+ {
+ static_assert(std::is_integral::value, "T must be integral");
+ T rep_val = val;
+ set_option(Opt, &rep_val, sizeof rep_val);
+ }
+
+ // Set array socket option, e.g.
+ // `socket.set(zmq::sockopt::plain_username, "foo123")`
+ template
+ void set(sockopt::array_option, const char *buf)
+ {
+ set_option(Opt, buf, std::strlen(buf));
+ }
+
+ // Set array socket option, e.g.
+ // `socket.set(zmq::sockopt::routing_id, zmq::buffer(id))`
+ template
+ void set(sockopt::array_option, const_buffer buf)
+ {
+ set_option(Opt, buf.data(), buf.size());
+ }
+
+ // Set array socket option, e.g.
+ // `socket.set(zmq::sockopt::routing_id, id_str)`
+ template
+ void set(sockopt::array_option, const std::string &buf)
+ {
+ set_option(Opt, buf.data(), buf.size());
+ }
+
+#if CPPZMQ_HAS_STRING_VIEW
+ // Set array socket option, e.g.
+ // `socket.set(zmq::sockopt::routing_id, id_str)`
+ template
+ void set(sockopt::array_option, std::string_view buf)
+ {
+ set_option(Opt, buf.data(), buf.size());
+ }
+#endif
+
+ // Get scalar socket option, e.g.
+ // `auto opt = socket.get(zmq::sockopt::linger)`
+ template
+ ZMQ_NODISCARD T get(sockopt::integral_option) const
+ {
+ static_assert(std::is_scalar::value, "T must be scalar");
+ T val;
+ size_t size = sizeof val;
+ get_option(Opt, &val, &size);
+ assert(size == sizeof val);
+ return val;
+ }
+
+ // Get array socket option, writes to buf, returns option size in bytes, e.g.
+ // `size_t optsize = socket.get(zmq::sockopt::routing_id, zmq::buffer(id))`
+ template
+ ZMQ_NODISCARD size_t get(sockopt::array_option,
+ mutable_buffer buf) const
+ {
+ size_t size = buf.size();
+ get_option(Opt, buf.data(), &size);
+ return size;
+ }
+
+ // Get array socket option as string (initializes the string buffer size to init_size) e.g.
+ // `auto s = socket.get(zmq::sockopt::routing_id)`
+ // Note: removes the null character from null-terminated string options,
+ // i.e. the string size excludes the null character.
+ template
+ ZMQ_NODISCARD std::string get(sockopt::array_option,
+ size_t init_size = 1024) const
+ {
+ if ZMQ_CONSTEXPR_IF (NullTerm == 2) {
+ if (init_size == 1024) {
+ init_size = 41; // get as Z85 string
+ }
+ }
+ std::string str(init_size, '\0');
+ size_t size = get(sockopt::array_option{}, buffer(str));
+ if ZMQ_CONSTEXPR_IF (NullTerm == 1) {
+ if (size > 0) {
+ assert(str[size - 1] == '\0');
+ --size;
+ }
+ } else if ZMQ_CONSTEXPR_IF (NullTerm == 2) {
+ assert(size == 32 || size == 41);
+ if (size == 41) {
+ assert(str[size - 1] == '\0');
+ --size;
+ }
+ }
+ str.resize(size);
+ return str;
+ }
+#endif
+
+ void bind(std::string const &addr) { bind(addr.c_str()); }
+
+ void bind(const char *addr_)
+ {
+ int rc = zmq_bind(_handle, addr_);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ void unbind(std::string const &addr) { unbind(addr.c_str()); }
+
+ void unbind(const char *addr_)
+ {
+ int rc = zmq_unbind(_handle, addr_);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ void connect(std::string const &addr) { connect(addr.c_str()); }
+
+ void connect(const char *addr_)
+ {
+ int rc = zmq_connect(_handle, addr_);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ void disconnect(std::string const &addr) { disconnect(addr.c_str()); }
+
+ void disconnect(const char *addr_)
+ {
+ int rc = zmq_disconnect(_handle, addr_);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ ZMQ_DEPRECATED("from 4.7.1, use handle() != nullptr or operator bool")
+ bool connected() const ZMQ_NOTHROW { return (_handle != ZMQ_NULLPTR); }
+
+ ZMQ_CPP11_DEPRECATED("from 4.3.1, use send taking a const_buffer and send_flags")
+ size_t send(const void *buf_, size_t len_, int flags_ = 0)
+ {
+ int nbytes = zmq_send(_handle, buf_, len_, flags_);
+ if (nbytes >= 0)
+ return static_cast(nbytes);
+ if (zmq_errno() == EAGAIN)
+ return 0;
+ throw error_t();
+ }
+
+ ZMQ_CPP11_DEPRECATED("from 4.3.1, use send taking message_t and send_flags")
+ bool send(message_t &msg_,
+ int flags_ = 0) // default until removed
+ {
+ int nbytes = zmq_msg_send(msg_.handle(), _handle, flags_);
+ if (nbytes >= 0)
+ return true;
+ if (zmq_errno() == EAGAIN)
+ return false;
+ throw error_t();
+ }
+
+ template
+ ZMQ_CPP11_DEPRECATED(
+ "from 4.4.1, use send taking message_t or buffer (for contiguous "
+ "ranges), and send_flags")
+ bool send(T first, T last, int flags_ = 0)
+ {
+ zmq::message_t msg(first, last);
+ int nbytes = zmq_msg_send(msg.handle(), _handle, flags_);
+ if (nbytes >= 0)
+ return true;
+ if (zmq_errno() == EAGAIN)
+ return false;
+ throw error_t();
+ }
+
+#ifdef ZMQ_HAS_RVALUE_REFS
+ ZMQ_CPP11_DEPRECATED("from 4.3.1, use send taking message_t and send_flags")
+ bool send(message_t &&msg_,
+ int flags_ = 0) // default until removed
+ {
+#ifdef ZMQ_CPP11
+ return send(msg_, static_cast(flags_)).has_value();
+#else
+ return send(msg_, flags_);
+#endif
+ }
+#endif
+
+#ifdef ZMQ_CPP11
+ send_result_t send(const_buffer buf, send_flags flags = send_flags::none)
+ {
+ const int nbytes =
+ zmq_send(_handle, buf.data(), buf.size(), static_cast(flags));
+ if (nbytes >= 0)
+ return static_cast(nbytes);
+ if (zmq_errno() == EAGAIN)
+ return {};
+ throw error_t();
+ }
+
+ send_result_t send(message_t &msg, send_flags flags)
+ {
+ int nbytes = zmq_msg_send(msg.handle(), _handle, static_cast(flags));
+ if (nbytes >= 0)
+ return static_cast(nbytes);
+ if (zmq_errno() == EAGAIN)
+ return {};
+ throw error_t();
+ }
+
+ send_result_t send(message_t &&msg, send_flags flags)
+ {
+ return send(msg, flags);
+ }
+#endif
+
+ ZMQ_CPP11_DEPRECATED(
+ "from 4.3.1, use recv taking a mutable_buffer and recv_flags")
+ size_t recv(void *buf_, size_t len_, int flags_ = 0)
+ {
+ int nbytes = zmq_recv(_handle, buf_, len_, flags_);
+ if (nbytes >= 0)
+ return static_cast(nbytes);
+ if (zmq_errno() == EAGAIN)
+ return 0;
+ throw error_t();
+ }
+
+ ZMQ_CPP11_DEPRECATED(
+ "from 4.3.1, use recv taking a reference to message_t and recv_flags")
+ bool recv(message_t *msg_, int flags_ = 0)
+ {
+ int nbytes = zmq_msg_recv(msg_->handle(), _handle, flags_);
+ if (nbytes >= 0)
+ return true;
+ if (zmq_errno() == EAGAIN)
+ return false;
+ throw error_t();
+ }
+
+#ifdef ZMQ_CPP11
+ ZMQ_NODISCARD
+ recv_buffer_result_t recv(mutable_buffer buf,
+ recv_flags flags = recv_flags::none)
+ {
+ const int nbytes =
+ zmq_recv(_handle, buf.data(), buf.size(), static_cast(flags));
+ if (nbytes >= 0) {
+ return recv_buffer_size{
+ (std::min)(static_cast(nbytes), buf.size()),
+ static_cast(nbytes)};
+ }
+ if (zmq_errno() == EAGAIN)
+ return {};
+ throw error_t();
+ }
+
+ ZMQ_NODISCARD
+ recv_result_t recv(message_t &msg, recv_flags flags = recv_flags::none)
+ {
+ const int nbytes =
+ zmq_msg_recv(msg.handle(), _handle, static_cast(flags));
+ if (nbytes >= 0) {
+ assert(msg.size() == static_cast(nbytes));
+ return static_cast(nbytes);
+ }
+ if (zmq_errno() == EAGAIN)
+ return {};
+ throw error_t();
+ }
+#endif
+
+#if defined(ZMQ_BUILD_DRAFT_API) && ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 0)
+ void join(const char *group)
+ {
+ int rc = zmq_join(_handle, group);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ void leave(const char *group)
+ {
+ int rc = zmq_leave(_handle, group);
+ if (rc != 0)
+ throw error_t();
+ }
+#endif
+
+ ZMQ_NODISCARD void *handle() ZMQ_NOTHROW { return _handle; }
+ ZMQ_NODISCARD const void *handle() const ZMQ_NOTHROW { return _handle; }
+
+ ZMQ_EXPLICIT operator bool() const ZMQ_NOTHROW { return _handle != ZMQ_NULLPTR; }
+ // note: non-const operator bool can be removed once
+ // operator void* is removed from socket_t
+ ZMQ_EXPLICIT operator bool() ZMQ_NOTHROW { return _handle != ZMQ_NULLPTR; }
+
+ protected:
+ void *_handle;
+
+ private:
+ void set_option(int option_, const void *optval_, size_t optvallen_)
+ {
+ int rc = zmq_setsockopt(_handle, option_, optval_, optvallen_);
+ if (rc != 0)
+ throw error_t();
+ }
+
+ void get_option(int option_, void *optval_, size_t *optvallen_) const
+ {
+ int rc = zmq_getsockopt(_handle, option_, optval_, optvallen_);
+ if (rc != 0)
+ throw error_t();
+ }
+};
+} // namespace detail
+
+struct from_handle_t
+{
+ struct _private
+ {
+ }; // disabling use other than with from_handle
+ ZMQ_CONSTEXPR_FN ZMQ_EXPLICIT from_handle_t(_private /*p*/) ZMQ_NOTHROW {}
+};
+
+ZMQ_CONSTEXPR_VAR from_handle_t from_handle =
+ from_handle_t(from_handle_t::_private());
+
+// A non-owning nullable reference to a socket.
+// The reference is invalidated on socket close or destruction.
+class socket_ref : public detail::socket_base
+{
+ public:
+ socket_ref() ZMQ_NOTHROW : detail::socket_base() {}
+#ifdef ZMQ_CPP11
+ socket_ref(std::nullptr_t) ZMQ_NOTHROW : detail::socket_base() {}
+#endif
+ socket_ref(from_handle_t /*fh*/, void *handle) ZMQ_NOTHROW
+ : detail::socket_base(handle)
+ {
+ }
+};
+
+#ifdef ZMQ_CPP11
+inline bool operator==(socket_ref sr, std::nullptr_t /*p*/) ZMQ_NOTHROW
+{
+ return sr.handle() == nullptr;
+}
+inline bool operator==(std::nullptr_t /*p*/, socket_ref sr) ZMQ_NOTHROW
+{
+ return sr.handle() == nullptr;
+}
+inline bool operator!=(socket_ref sr, std::nullptr_t /*p*/) ZMQ_NOTHROW
+{
+ return !(sr == nullptr);
+}
+inline bool operator!=(std::nullptr_t /*p*/, socket_ref sr) ZMQ_NOTHROW
+{
+ return !(sr == nullptr);
+}
+#endif
+
+inline bool operator==(const detail::socket_base& a, const detail::socket_base& b) ZMQ_NOTHROW
+{
+ return std::equal_to()(a.handle(), b.handle());
+}
+inline bool operator!=(const detail::socket_base& a, const detail::socket_base& b) ZMQ_NOTHROW
+{
+ return !(a == b);
+}
+inline bool operator<(const detail::socket_base& a, const detail::socket_base& b) ZMQ_NOTHROW
+{
+ return std::less()(a.handle(), b.handle());
+}
+inline bool operator>(const detail::socket_base& a, const detail::socket_base& b) ZMQ_NOTHROW
+{
+ return b < a;
+}
+inline bool operator<=(const detail::socket_base& a, const detail::socket_base& b) ZMQ_NOTHROW
+{
+ return !(a > b);
+}
+inline bool operator>=(const detail::socket_base& a, const detail::socket_base& b) ZMQ_NOTHROW
+{
+ return !(a < b);
+}
+
+} // namespace zmq
+
+#ifdef ZMQ_CPP11
+namespace std
+{
+template<> struct hash
+{
+ size_t operator()(zmq::socket_ref sr) const ZMQ_NOTHROW
+ {
+ return hash()(sr.handle());
+ }
+};
+} // namespace std
+#endif
+
+namespace zmq
+{
+class socket_t : public detail::socket_base
+{
+ friend class monitor_t;
+
+ public:
+ socket_t() ZMQ_NOTHROW : detail::socket_base(ZMQ_NULLPTR), ctxptr(ZMQ_NULLPTR) {}
+
+ socket_t(context_t &context_, int type_) :
+ detail::socket_base(zmq_socket(context_.handle(), type_)),
+ ctxptr(context_.handle())
+ {
+ if (_handle == ZMQ_NULLPTR)
+ throw error_t();
+ }
+
+#ifdef ZMQ_CPP11
+ socket_t(context_t &context_, socket_type type_) :
+ socket_t(context_, static_cast(type_))
+ {
+ }
+#endif
+
+#ifdef ZMQ_HAS_RVALUE_REFS
+ socket_t(socket_t &&rhs) ZMQ_NOTHROW : detail::socket_base(rhs._handle),
+ ctxptr(rhs.ctxptr)
+ {
+ rhs._handle = ZMQ_NULLPTR;
+ rhs.ctxptr = ZMQ_NULLPTR;
+ }
+ socket_t &operator=(socket_t &&rhs) ZMQ_NOTHROW
+ {
+ close();
+ std::swap(_handle, rhs._handle);
+ std::swap(ctxptr, rhs.ctxptr);
+ return *this;
+ }
+#endif
+
+ ~socket_t() ZMQ_NOTHROW { close(); }
+
+ operator void *() ZMQ_NOTHROW { return _handle; }
+
+ operator void const *() const ZMQ_NOTHROW { return _handle; }
+
+ void close() ZMQ_NOTHROW
+ {
+ if (_handle == ZMQ_NULLPTR)
+ // already closed
+ return;
+ int rc = zmq_close(_handle);
+ ZMQ_ASSERT(rc == 0);
+ _handle = ZMQ_NULLPTR;
+ ctxptr = ZMQ_NULLPTR;
+ }
+
+ void swap(socket_t &other) ZMQ_NOTHROW
+ {
+ std::swap(_handle, other._handle);
+ std::swap(ctxptr, other.ctxptr);
+ }
+
+ operator socket_ref() ZMQ_NOTHROW { return socket_ref(from_handle, _handle); }
+
+ private:
+ void *ctxptr;
+
+ socket_t(const socket_t &) ZMQ_DELETED_FUNCTION;
+ void operator=(const socket_t &) ZMQ_DELETED_FUNCTION;
+
+ // used by monitor_t
+ socket_t(void *context_, int type_) :
+ detail::socket_base(zmq_socket(context_, type_)), ctxptr(context_)
+ {
+ if (_handle == ZMQ_NULLPTR)
+ throw error_t();
+ if (ctxptr == ZMQ_NULLPTR)
+ throw error_t();
+ }
+};
+
+inline void swap(socket_t &a, socket_t &b) ZMQ_NOTHROW
+{
+ a.swap(b);
+}
+
+ZMQ_DEPRECATED("from 4.3.1, use proxy taking socket_t objects")
+inline void proxy(void *frontend, void *backend, void *capture)
+{
+ int rc = zmq_proxy(frontend, backend, capture);
+ if (rc != 0)
+ throw error_t();
+}
+
+inline void
+proxy(socket_ref frontend, socket_ref backend, socket_ref capture = socket_ref())
+{
+ int rc = zmq_proxy(frontend.handle(), backend.handle(), capture.handle());
+ if (rc != 0)
+ throw error_t();
+}
+
+#ifdef ZMQ_HAS_PROXY_STEERABLE
+ZMQ_DEPRECATED("from 4.3.1, use proxy_steerable taking socket_t objects")
+inline void
+proxy_steerable(void *frontend, void *backend, void *capture, void *control)
+{
+ int rc = zmq_proxy_steerable(frontend, backend, capture, control);
+ if (rc != 0)
+ throw error_t();
+}
+
+inline void proxy_steerable(socket_ref frontend,
+ socket_ref backend,
+ socket_ref capture,
+ socket_ref control)
+{
+ int rc = zmq_proxy_steerable(frontend.handle(), backend.handle(),
+ capture.handle(), control.handle());
+ if (rc != 0)
+ throw error_t();
+}
+#endif
+
+class monitor_t
+{
+ public:
+ monitor_t() : _socket(), _monitor_socket() {}
+
+ virtual ~monitor_t() { close(); }
+
+#ifdef ZMQ_HAS_RVALUE_REFS
+ monitor_t(monitor_t &&rhs) ZMQ_NOTHROW : _socket(), _monitor_socket()
+ {
+ std::swap(_socket, rhs._socket);
+ std::swap(_monitor_socket, rhs._monitor_socket);
+ }
+
+ monitor_t &operator=(monitor_t &&rhs) ZMQ_NOTHROW
+ {
+ close();
+ _socket = socket_ref();
+ std::swap(_socket, rhs._socket);
+ std::swap(_monitor_socket, rhs._monitor_socket);
+ return *this;
+ }
+#endif
+
+
+ void
+ monitor(socket_t &socket, std::string const &addr, int events = ZMQ_EVENT_ALL)
+ {
+ monitor(socket, addr.c_str(), events);
+ }
+
+ void monitor(socket_t &socket, const char *addr_, int events = ZMQ_EVENT_ALL)
+ {
+ init(socket, addr_, events);
+ while (true) {
+ check_event(-1);
+ }
+ }
+
+ void init(socket_t &socket, std::string const &addr, int events = ZMQ_EVENT_ALL)
+ {
+ init(socket, addr.c_str(), events);
+ }
+
+ void init(socket_t &socket, const char *addr_, int events = ZMQ_EVENT_ALL)
+ {
+ int rc = zmq_socket_monitor(socket.handle(), addr_, events);
+ if (rc != 0)
+ throw error_t();
+
+ _socket = socket;
+ _monitor_socket = socket_t(socket.ctxptr, ZMQ_PAIR);
+ _monitor_socket.connect(addr_);
+
+ on_monitor_started();
+ }
+
+ bool check_event(int timeout = 0)
+ {
+ assert(_monitor_socket);
+
+ zmq::pollitem_t items[] = {
+ {_monitor_socket.handle(), 0, ZMQ_POLLIN, 0},
+ };
+
+ #ifdef ZMQ_CPP11
+ zmq::poll(&items[0], 1, std::chrono::milliseconds(timeout));
+ #else
+ zmq::poll(&items[0], 1, timeout);
+ #endif
+
+ return process_event(items[0].revents);
+ }
+
+#ifdef ZMQ_EVENT_MONITOR_STOPPED
+ void abort()
+ {
+ if (_socket)
+ zmq_socket_monitor(_socket.handle(), ZMQ_NULLPTR, 0);
+
+ _socket = socket_ref();
+ }
+
+ virtual void on_monitor_stopped() {}
+#endif
+ virtual void on_monitor_started() {}
+ virtual void on_event_connected(const zmq_event_t &event_, const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_connect_delayed(const zmq_event_t &event_,
+ const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_connect_retried(const zmq_event_t &event_,
+ const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_listening(const zmq_event_t &event_, const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_bind_failed(const zmq_event_t &event_, const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_accepted(const zmq_event_t &event_, const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_accept_failed(const zmq_event_t &event_, const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_closed(const zmq_event_t &event_, const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_close_failed(const zmq_event_t &event_, const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_disconnected(const zmq_event_t &event_, const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 3)
+ virtual void on_event_handshake_failed_no_detail(const zmq_event_t &event_,
+ const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_handshake_failed_protocol(const zmq_event_t &event_,
+ const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_handshake_failed_auth(const zmq_event_t &event_,
+ const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_handshake_succeeded(const zmq_event_t &event_,
+ const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+#elif ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 1)
+ virtual void on_event_handshake_failed(const zmq_event_t &event_,
+ const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+ virtual void on_event_handshake_succeed(const zmq_event_t &event_,
+ const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+#endif
+ virtual void on_event_unknown(const zmq_event_t &event_, const char *addr_)
+ {
+ (void) event_;
+ (void) addr_;
+ }
+
+ protected:
+ bool process_event(short events)
+ {
+ zmq::message_t eventMsg;
+
+ if (events & ZMQ_POLLIN) {
+ int rc = zmq_msg_recv(eventMsg.handle(), _monitor_socket.handle(), 0);
+ if (rc == -1 && zmq_errno() == ETERM)
+ return false;
+ assert(rc != -1);
+
+ } else {
+ return false;
+ }
+
+#if ZMQ_VERSION_MAJOR >= 4
+ const char *data = static_cast(eventMsg.data());
+ zmq_event_t msgEvent;
+ memcpy(&msgEvent.event, data, sizeof(uint16_t));
+ data += sizeof(uint16_t);
+ memcpy(&msgEvent.value, data, sizeof(int32_t));
+ zmq_event_t *event = &msgEvent;
+#else
+ zmq_event_t *event = static_cast(eventMsg.data());
+#endif
+
+#ifdef ZMQ_NEW_MONITOR_EVENT_LAYOUT
+ zmq::message_t addrMsg;
+ int rc = zmq_msg_recv(addrMsg.handle(), _monitor_socket.handle(), 0);
+ if (rc == -1 && zmq_errno() == ETERM) {
+ return false;
+ }
+
+ assert(rc != -1);
+ std::string address = addrMsg.to_string();
+#else
+ // Bit of a hack, but all events in the zmq_event_t union have the same layout so this will work for all event types.
+ std::string address = event->data.connected.addr;
+#endif
+
+#ifdef ZMQ_EVENT_MONITOR_STOPPED
+ if (event->event == ZMQ_EVENT_MONITOR_STOPPED) {
+ on_monitor_stopped();
+ return false;
+ }
+
+#endif
+
+ switch (event->event) {
+ case ZMQ_EVENT_CONNECTED:
+ on_event_connected(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_CONNECT_DELAYED:
+ on_event_connect_delayed(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_CONNECT_RETRIED:
+ on_event_connect_retried(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_LISTENING:
+ on_event_listening(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_BIND_FAILED:
+ on_event_bind_failed(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_ACCEPTED:
+ on_event_accepted(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_ACCEPT_FAILED:
+ on_event_accept_failed(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_CLOSED:
+ on_event_closed(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_CLOSE_FAILED:
+ on_event_close_failed(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_DISCONNECTED:
+ on_event_disconnected(*event, address.c_str());
+ break;
+#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 3, 0) || (defined(ZMQ_BUILD_DRAFT_API) && ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 3))
+ case ZMQ_EVENT_HANDSHAKE_FAILED_NO_DETAIL:
+ on_event_handshake_failed_no_detail(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_HANDSHAKE_FAILED_PROTOCOL:
+ on_event_handshake_failed_protocol(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_HANDSHAKE_FAILED_AUTH:
+ on_event_handshake_failed_auth(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_HANDSHAKE_SUCCEEDED:
+ on_event_handshake_succeeded(*event, address.c_str());
+ break;
+#elif defined(ZMQ_BUILD_DRAFT_API) && ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 1)
+ case ZMQ_EVENT_HANDSHAKE_FAILED:
+ on_event_handshake_failed(*event, address.c_str());
+ break;
+ case ZMQ_EVENT_HANDSHAKE_SUCCEED:
+ on_event_handshake_succeed(*event, address.c_str());
+ break;
+#endif
+ default:
+ on_event_unknown(*event, address.c_str());
+ break;
+ }
+
+ return true;
+ }
+
+ socket_ref monitor_socket() {return _monitor_socket;}
+
+ private:
+ monitor_t(const monitor_t &) ZMQ_DELETED_FUNCTION;
+ void operator=(const monitor_t &) ZMQ_DELETED_FUNCTION;
+
+ socket_ref _socket;
+ socket_t _monitor_socket;
+
+ void close() ZMQ_NOTHROW
+ {
+ if (_socket)
+ zmq_socket_monitor(_socket.handle(), ZMQ_NULLPTR, 0);
+ _monitor_socket.close();
+ }
+};
+
+#if defined(ZMQ_BUILD_DRAFT_API) && defined(ZMQ_CPP11) && defined(ZMQ_HAVE_POLLER)
+
+// polling events
+enum class event_flags : short
+{
+ none = 0,
+ pollin = ZMQ_POLLIN,
+ pollout = ZMQ_POLLOUT,
+ pollerr = ZMQ_POLLERR,
+ pollpri = ZMQ_POLLPRI
+};
+
+constexpr event_flags operator|(event_flags a, event_flags b) noexcept
+{
+ return detail::enum_bit_or(a, b);
+}
+constexpr event_flags operator&(event_flags a, event_flags b) noexcept
+{
+ return detail::enum_bit_and(a, b);
+}
+constexpr event_flags operator^(event_flags a, event_flags b) noexcept
+{
+ return detail::enum_bit_xor(a, b);
+}
+constexpr event_flags operator~(event_flags a) noexcept
+{
+ return detail::enum_bit_not(a);
+}
+
+struct no_user_data;
+
+// layout compatible with zmq_poller_event_t
+template struct poller_event
+{
+ socket_ref socket;
+ ::zmq::fd_t fd;
+ T *user_data;
+ event_flags events;
+};
+
+template class poller_t
+{
+ public:
+ using event_type = poller_event;
+
+ poller_t() : poller_ptr(zmq_poller_new())
+ {
+ if (!poller_ptr)
+ throw error_t();
+ }
+
+ template<
+ typename Dummy = void,
+ typename =
+ typename std::enable_if::value, Dummy>::type>
+ void add(zmq::socket_ref socket, event_flags events, T *user_data)
+ {
+ add_impl(socket, events, user_data);
+ }
+
+ void add(zmq::socket_ref socket, event_flags events)
+ {
+ add_impl(socket, events, nullptr);
+ }
+
+ template<
+ typename Dummy = void,
+ typename =
+ typename std::enable_if::value, Dummy>::type>
+ void add(fd_t fd, event_flags events, T *user_data)
+ {
+ add_impl(fd, events, user_data);
+ }
+
+ void add(fd_t fd, event_flags events) { add_impl(fd, events, nullptr); }
+
+ void remove(zmq::socket_ref socket)
+ {
+ if (0 != zmq_poller_remove(poller_ptr.get(), socket.handle())) {
+ throw error_t();
+ }
+ }
+
+ void remove(fd_t fd)
+ {
+ if (0 != zmq_poller_remove_fd(poller_ptr.get(), fd)) {
+ throw error_t();
+ }
+ }
+
+ void modify(zmq::socket_ref socket, event_flags events)
+ {
+ if (0
+ != zmq_poller_modify(poller_ptr.get(), socket.handle(),
+ static_cast(events))) {
+ throw error_t();
+ }
+ }
+
+ void modify(fd_t fd, event_flags events)
+ {
+ if (0
+ != zmq_poller_modify_fd(poller_ptr.get(), fd,
+ static_cast(events))) {
+ throw error_t();
+ }
+ }
+
+ template
+ size_t wait_all(Sequence &poller_events,
+ const std::chrono::milliseconds timeout)
+ {
+ static_assert(std::is_same::value,
+ "Sequence::value_type must be of poller_t::event_type");
+ int rc = zmq_poller_wait_all(
+ poller_ptr.get(),
+ reinterpret_cast(poller_events.data()),
+ static_cast(poller_events.size()),
+ static_cast(timeout.count()));
+ if (rc > 0)
+ return static_cast(rc);
+
+#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 2, 3)
+ if (zmq_errno() == EAGAIN)
+#else
+ if (zmq_errno() == ETIMEDOUT)
+#endif
+ return 0;
+
+ throw error_t();
+ }
+
+#if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4, 3, 3)
+ size_t size() const noexcept
+ {
+ int rc = zmq_poller_size(const_cast(poller_ptr.get()));
+ ZMQ_ASSERT(rc >= 0);
+ return static_cast(std::max(rc, 0));
+ }
+#endif
+
+ private:
+ struct destroy_poller_t
+ {
+ void operator()(void *ptr) noexcept
+ {
+ int rc = zmq_poller_destroy(&ptr);
+ ZMQ_ASSERT(rc == 0);
+ }
+ };
+
+ std::unique_ptr poller_ptr;
+
+ void add_impl(zmq::socket_ref socket, event_flags events, T *user_data)
+ {
+ if (0
+ != zmq_poller_add(poller_ptr.get(), socket.handle(), user_data,
+ static_cast(events))) {
+ throw error_t();
+ }
+ }
+
+ void add_impl(fd_t fd, event_flags events, T *user_data)
+ {
+ if (0
+ != zmq_poller_add_fd(poller_ptr.get(), fd, user_data,
+ static_cast(events))) {
+ throw error_t();
+ }
+ }
+};
+#endif // defined(ZMQ_BUILD_DRAFT_API) && defined(ZMQ_CPP11) && defined(ZMQ_HAVE_POLLER)
+
+inline std::ostream &operator<<(std::ostream &os, const message_t &msg)
+{
+ return os << msg.str();
+}
+
+} // namespace zmq
+
+#endif // __ZMQ_HPP_INCLUDED__
\ No newline at end of file
diff --git a/include/zmq_addon.hpp b/include/zmq_addon.hpp
new file mode 100644
index 00000000..291c2b93
--- /dev/null
+++ b/include/zmq_addon.hpp
@@ -0,0 +1,848 @@
+/*
+ Copyright (c) 2016-2017 ZeroMQ community
+ Copyright (c) 2016 VOCA AS / Harald NΓΈkland
+
+ Permission is hereby granted, free of charge, to any person obtaining a copy
+ of this software and associated documentation files (the "Software"), to
+ deal in the Software without restriction, including without limitation the
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
+ sell copies of the Software, and to permit persons to whom the Software is
+ furnished to do so, subject to the following conditions:
+
+ The above copyright notice and this permission notice shall be included in
+ all copies or substantial portions of the Software.
+
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
+ FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
+ IN THE SOFTWARE.
+*/
+
+#ifndef __ZMQ_ADDON_HPP_INCLUDED__
+#define __ZMQ_ADDON_HPP_INCLUDED__
+
+#include "zmq.hpp"
+
+#include
+#include
+#include
+#include
+#ifdef ZMQ_CPP11
+#include
+#include
+#include