### gets usage example Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Example of retrieving the 'Peer-Address' property from a message and handling the result. ```rust let addr = msg.gets("Peer-Address"); match addr { Some(a) => println!("peer: {}", a), None => println!("no Peer-Address property (or non-UTF8)"), } ``` -------------------------------- ### Weather proxy example using zmq::proxy Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/proxy.md Example from examples/zguide/wuproxy/main.rs. Creates XSUB and XPUB sockets, connects frontend, binds backend, and calls zmq::proxy. ```rust let context = zmq::Context::new(); let frontend = context.socket(zmq::XSUB).unwrap(); let backend = context.socket(zmq::XPUB).unwrap(); frontend.connect("tcp://192.168.55.210:5556").expect("failed connecting frontend"); backend.bind("tcp://10.1.1.0:8100").expect("failed binding backend"); zmq::proxy(&frontend, &backend).expect("failed proxying"); ``` -------------------------------- ### socket basic example Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/context.md Creates a REQ socket, connects to a local endpoint, and sends a message. This is the canonical hello-world client from examples/zguide/helloworld_client/main.rs. ```rust let context = zmq::Context::new(); let requester = context.socket(zmq::REQ).unwrap(); requester.connect("tcp://localhost:5555").unwrap(); requester.send("Hello", 0).unwrap(); ``` -------------------------------- ### z85_encode example with CurveKeyPair Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/utility-functions.md Example of encoding a 32-byte public key from a CurveKeyPair to Z85 text using z85_encode. The public key is obtained from a new CurveKeyPair instance, and the encoded string is printed. ```rust let pair = zmq::CurveKeyPair::new().unwrap(); let encoded = zmq::z85_encode(&pair.public_key).unwrap(); println!("public key (z85): {}", encoded); ``` -------------------------------- ### Send example using From conversions Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Shows sending messages using &str, byte slices, Vec, and Message itself via the From conversions. ```rust let socket = ctx.socket(zmq::PUSH).unwrap(); socket.send("hello world!", 0).unwrap(); // &str socket.send(b"raw bytes", 0).unwrap(); // &[u8] let data: Vec = vec![1, 2, 3]; socket.send(data, 0).unwrap(); // Vec, zero-copy move let msg = zmq::Message::from(b"abc"); // From<&[u8]> socket.send(msg, 0).unwrap(); // Message itself ``` -------------------------------- ### CURVE-encrypted REQ/REP sockets example Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/utility-functions.md Example from tests/curve.rs showing how to generate key pairs and configure a REP server and REQ client for CURVE encryption. The server sets its secret key and enables curve server; the client sets the server's public key and its own key pair. ```rust let server_pair = zmq::CurveKeyPair::new().unwrap(); let client_pair = zmq::CurveKeyPair::new().unwrap(); let ctx = zmq::Context::new(); let mut server = ctx.socket(zmq::REP).unwrap(); server.set_curve_server(true).unwrap(); server.set_curve_secretkey(&server_pair.secret_key).unwrap(); let mut client = ctx.socket(zmq::REQ).unwrap(); client.set_curve_serverkey(&server_pair.public_key).unwrap(); client.set_curve_publickey(&client_pair.public_key).unwrap(); client.set_curve_secretkey(&client_pair.secret_key).unwrap(); ``` -------------------------------- ### Multipart send example with SNDMORE Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/socket.md Example of sending a multipart message. The first frame uses SNDMORE to indicate more frames follow, and the last frame uses 0 flags. ```rust socket.send("12345678ABCDEFGH12345678abcdefgh".as_bytes(), zmq::SNDMORE).unwrap(); socket.send("12345678ABCDEFGH12345678abcdefgh".as_bytes(), 0).unwrap(); ``` -------------------------------- ### proxy Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/proxy.md Starts a simple proxy that connects a frontend socket to a backend socket. Blocks until the context is terminated. ```APIDOC ## proxy ### Description Starts a simple proxy that connects a frontend socket to a backend socket. Blocks until the context is terminated. ### Function Signature ```rust pub fn proxy(frontend: &Socket, backend: &Socket) -> Result<()> ``` ### Parameters - `frontend` (&Socket) - Required - Frontend socket (e.g., XSUB for a weather proxy, ROUTER for an async server) - `backend` (&Socket) - Required - Backend socket (e.g., XPUB, DEALER) ### Returns - `Result<()>` - Blocks until the context is terminated, then returns `Err(Error::ETERM)`. ### Example ```rust let context = zmq::Context::new(); let frontend = context.socket(zmq::XSUB).unwrap(); let backend = context.socket(zmq::XPUB).unwrap(); frontend.connect("tcp://192.168.55.210:5556").expect("failed connecting frontend"); backend.bind("tcp://10.1.1.0:8100").expect("failed binding backend"); zmq::proxy(&frontend, &backend).expect("failed proxying"); ``` ``` -------------------------------- ### Example: destroying a Context after dropping sockets Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/context.md Shows the recommended usage of `destroy()`. Sockets must be dropped before calling `destroy()` to avoid blocking or deadlock if the socket lives in the calling thread. The example creates a context, opens a `PAIR` socket, drops it, then destroys the context. ```rust let mut ctx = zmq::Context::new(); let s = ctx.socket(zmq::PAIR).unwrap(); // sockets must be dropped before destroy to avoid blocking (and a deadlock // if the socket lives in the calling thread) drop(s); ctx.destroy().unwrap(); ``` -------------------------------- ### Get 0MQ version with zmq::version() Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/utility-functions.md Retrieves the current ZeroMQ version as a tuple of (major, minor, patch). Use this to check the linked library version at runtime. The example prints the version components. ```rust let (major, minor, patch) = zmq::version(); println!("Current 0MQ version is {}.{}.{}", major, minor, patch); ``` -------------------------------- ### Creating a context and socket Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/context.md Example usage of Context::new() to create a context and then a socket with zmq::REQ. The socket call returns a Result, unwrapped here. ```rust let ctx = zmq::Context::new(); let socket = ctx.socket(zmq::REQ).unwrap(); ``` -------------------------------- ### get_io_threads example Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/context.md Creates a new context and retrieves the current IO thread count, printing it. The default is 1 (ZMQ_IO_THREADS_DFLT). ```rust let ctx = zmq::Context::new(); let threads = ctx.get_io_threads().unwrap(); println!("io threads: {}", threads); // default is 1 (ZMQ_IO_THREADS_DFLT) ``` -------------------------------- ### z85_decode round-trip example Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/utility-functions.md Example of a round-trip: decoding a Z85-encoded string to bytes and then encoding it back, asserting that the result matches the original string. This pattern is taken from tests/z85.rs. ```rust let test_str = "/AB8cGJ*-$lEbr2=TW$Q?i7:/ Result<()> ``` ### Parameters - `frontend` (&mut Socket) - Required - Frontend socket - `backend` (&mut Socket) - Required - Backend socket - `capture` (&mut Socket) - Required - Capture socket for all proxied messages - `control` (&mut Socket) - Required - Control socket (`PAUSE` / `RESUME` / `TERMINATE`) ### Returns - `Result<()>` - Combines the capture behavior of `proxy_with_capture` with the steering of `proxy_steerable`. ``` -------------------------------- ### proxy_steerable Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/proxy.md Starts a steerable proxy that accepts control commands (PAUSE, RESUME, TERMINATE) on a control socket. Blocks until context termination or a TERMINATE command. ```APIDOC ## proxy_steerable ### Description Starts a steerable proxy that accepts control commands (PAUSE, RESUME, TERMINATE) on a control socket. Blocks until context termination or a TERMINATE command. ### Function Signature ```rust pub fn proxy_steerable( frontend: &mut Socket, backend: &mut Socket, control: &mut Socket, ) -> Result<()> ``` ### Parameters - `frontend` (&mut Socket) - Required - Frontend socket - `backend` (&mut Socket) - Required - Backend socket - `control` (&mut Socket) - Required - Control socket receiving `PAUSE`, `RESUME`, `TERMINATE` commands ### Returns - `Result<()>` - Blocks until context termination or a `TERMINATE` command. ### Behavior - If `PAUSE` is received on the control socket, the proxy suspends its activities. - `RESUME` resumes the proxy. - `TERMINATE` terminates smoothly. - At start, the proxy runs normally as if `proxy` was used. ``` -------------------------------- ### Example: reading monitor events Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/socket.md Creates a DEALER socket and a PAIR monitor socket, binds the monitor to an inproc endpoint, enables monitoring with SocketEvent::ALL, then receives and decodes a monitor event using SocketEvent::from_raw. ```rust let ctx = zmq::Context::new(); let mut server = ctx.socket(zmq::DEALER).unwrap(); let mut monitor = ctx.socket(zmq::PAIR).unwrap(); monitor.bind("inproc://mon").unwrap(); server.monitor("inproc://mon", zmq::SocketEvent::ALL.to_raw()).unwrap(); let msg = monitor.recv_msg(0).unwrap(); let event = u16::from_ne_bytes([msg[0], msg[1]]); println!("event: {}", zmq::SocketEvent::from_raw(event)); ``` -------------------------------- ### socket error handling example Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/context.md Attempts to create a PUB socket and handles the Result by dropping the socket on success or printing an error message on failure. ```rust let ctx = zmq::Context::new(); let socket = ctx.socket(zmq::PUB); match socket { Ok(s) => drop(s), Err(e) => println!("failed to create socket: {}", e), } ``` -------------------------------- ### Basic usage: create context, REQ socket, connect, and send Source: https://github.com/erickt/rust-zmq/blob/master/README.md Shows a minimal `zmq` example: create a context, open a REQ socket, connect to a TCP endpoint, and send a message. The API follows the C API closely and is not idiomatic Rust. ```rust fn main() { let ctx = zmq::Context::new(); let socket = ctx.socket(zmq::REQ).unwrap(); socket.connect("tcp://127.0.0.1:1234").unwrap(); socket.send("hello world!", 0).unwrap(); } ``` -------------------------------- ### proxy_with_capture Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/proxy.md Starts a proxy that captures all messages sent on the frontend and backend sockets to a capture socket. Blocks until the context is terminated. ```APIDOC ## proxy_with_capture ### Description Starts a proxy that captures all messages sent on the frontend and backend sockets to a capture socket. Blocks until the context is terminated. ### Function Signature ```rust pub fn proxy_with_capture( frontend: &mut Socket, backend: &mut Socket, capture: &mut Socket, ) -> Result<()> ``` ### Parameters - `frontend` (&mut Socket) - Required - Frontend socket - `backend` (&mut Socket) - Required - Backend socket - `capture` (&mut Socket) - Required - Capture socket; receives all messages sent on the frontend and backend sockets ### Returns - `Result<()>` - Blocks until context termination, then returns `Err(Error::ETERM)`. ``` -------------------------------- ### Example: typical receive loop reusing a zmq::Message Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Shows a receive loop that reuses a single Message object. Sends 'Hello' and receives a reply, printing the message content via as_str().unwrap(). ```rust let mut msg = zmq::Message::new(); for request_nbr in 0..10 { requester.send("Hello", 0).unwrap(); requester.recv(&mut msg, 0).unwrap(); println!("Received World {}: {}", msg.as_str().unwrap(), request_nbr); } ``` -------------------------------- ### Multi-socket polling loop with poll Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/polling.md Full example from `examples/zguide/mspoller/main.rs` showing how to monitor a PULL socket and a SUB socket simultaneously using `zmq::poll`. It creates a context, connects sockets, subscribes to a topic, and processes incoming messages in a loop. ```rust let context = zmq::Context::new(); let receiver = context.socket(zmq::PULL).unwrap(); receiver.connect("tcp://localhost:5557").unwrap(); let subscriber = context.socket(zmq::SUB).unwrap(); subscriber.connect("tcp://localhost:5556").unwrap(); subscriber.set_subscribe(b"10001").unwrap(); let mut msg = zmq::Message::new(); loop { let mut items = [ receiver.as_poll_item(zmq::POLLIN), subscriber.as_poll_item(zmq::POLLIN), ]; zmq::poll(&mut items, -1).unwrap(); if items[0].is_readable() && receiver.recv(&mut msg, 0).is_ok() { // process task } if items[1].is_readable() && subscriber.recv(&mut msg, 0).is_ok() { // process weather update } } ``` -------------------------------- ### Set and get ZMQ_IO_THREADS context option Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/configuration.md Configures the context thread pool size at runtime. The default is ZMQ_IO_THREADS_DFLT = 1. Invalid values (e.g., -1) fail with an Error (EINVAL). ```rust let ctx = zmq::Context::new(); ctx.set_io_threads(4).unwrap(); assert_eq!(ctx.get_io_threads().unwrap(), 4); ``` -------------------------------- ### poll (free function) Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/polling.md Documentation for the `poll` free function in the rust-zmq library, including its signature, parameters, return value, and usage examples. ```APIDOC ## `poll` (free function) ### Description Polls multiple ZMQ sockets for events. This function monitors the handles provided in `items` and signals which ones have events ready. ### Signature ```rust pub fn poll(items: &mut [PollItem], timeout: i64) -> Result ``` ### Parameters - **items** (`&mut [PollItem]`) - Required - One item per handle to monitor; `events` inputs are monitored and results are signaled in each item's `revents`. - **timeout** (`i64`) - Required - Timeout in milliseconds; may be `0`; `-1` blocks indefinitely. ### Returns - **Result** - On success, the number of poll items that have events signaled; `Err(Error)` (e.g. `EINTR`) on failure. Wraps `zmq_poll`. ### Example (multi-socket loop) ```rust let context = zmq::Context::new(); let receiver = context.socket(zmq::PULL).unwrap(); receiver.connect("tcp://localhost:5557").unwrap(); let subscriber = context.socket(zmq::SUB).unwrap(); subscriber.connect("tcp://localhost:5556").unwrap(); subscriber.set_subscribe(b"10001").unwrap(); let mut msg = zmq::Message::new(); loop { let mut items = [ receiver.as_poll_item(zmq::POLLIN), subscriber.as_poll_item(zmq::POLLIN), ]; zmq::poll(&mut items, -1).unwrap(); if items[0].is_readable() && receiver.recv(&mut msg, 0).is_ok() { // process task } if items[1].is_readable() && subscriber.recv(&mut msg, 0).is_ok() { // process weather update } } ``` ### Example (error handling with EINTR retry) ```rust let mut items = [socket.as_poll_item(zmq::POLLIN)]; loop { match zmq::poll(&mut items, 0) { Ok(n) => { println!("{} items ready", n); break; } Err(zmq::Error::EINTR) => continue, Err(e) => panic!("poll failed: {}", e), } } ``` ``` -------------------------------- ### z85_decode error handling Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/utility-functions.md Example of handling errors from z85_decode when the input length is not a multiple of 5. It matches on the result, expecting a BadLength error and panicking otherwise. ```rust match zmq::z85_decode("/AB8") { Err(zmq::DecodeError::BadLength) => println!("length not a multiple of 5"), _ => panic!("expected bad length error"), } ``` -------------------------------- ### Check capability and generate keypair with zmq::has() Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/utility-functions.md Checks if the linked 0MQ library supports a given capability (e.g., "curve") using `zmq::has`. If supported, generates a CURVE keypair with `CurveKeyPair::new()` and prints a confirmation. `has` returns `Option`; unwrap to get the boolean. ```rust if zmq::has("curve").unwrap() { let keys = zmq::CurveKeyPair::new().unwrap(); println!("curve supported, generated a keypair"); } ``` -------------------------------- ### Catching EncodeError with match Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/errors.md Shows how to catch EncodeError from z85_encode. The example calls z85_encode with a byte slice of length 3, which triggers BadLength. The match arms handle Ok, BadLength, and other errors. ```rust match zmq::z85_encode(b"\x01\x01\x01") { Ok(s) => println!("{}", s), Err(zmq::EncodeError::BadLength) => (), Err(e) => (), } ``` -------------------------------- ### gets method signature Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Returns a message metadata property value if present and UTF-8, otherwise None. Ambiguity between missing and non-UTF-8 values is a known bug. ```rust pub fn gets<'a>(&'a mut self, property: &str) -> Option<&'a str> ``` -------------------------------- ### z85_encode error handling Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/utility-functions.md Example of handling errors from z85_encode when the input length is not a multiple of 4. It matches on the result, printing a specific message for BadLength errors and a generic message for other errors. ```rust match zmq::z85_encode(b"\x01\x01\x01") { Ok(s) => println!("{}", s), Err(zmq::EncodeError::BadLength) => println!("length not a multiple of 4"), Err(e) => println!("encode failed: {}", e), } ``` -------------------------------- ### Polling for incoming messages with poll Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/socket.md Example pattern from examples/zguide/asyncsrv/main.rs. Polls the client socket for POLLIN with a 10ms timeout, then receives a multipart message if an event is signaled. Uses expect() to handle polling and receiving failures. ```rust if client.poll(zmq::POLLIN, 10).expect("client failed polling") > 0 { let msg = client.recv_multipart(0).expect("client failed receiving response"); // ... process msg } ``` -------------------------------- ### Catching DecodeError with match Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/errors.md Shows how to catch DecodeError from z85_decode. The example calls z85_decode with a string containing an embedded NUL byte, triggering NulError. The match arms handle NulError, BadLength, and Ok. ```rust match zmq::z85_decode("/AB\x008") { Err(zmq::DecodeError::NulError(_)) => println!("embedded NUL byte"), Err(zmq::DecodeError::BadLength) => println!("length not a multiple of 5"), Ok(bytes) => (), } ``` -------------------------------- ### Handling nested results from recv_string Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/socket.md Example of matching on both the outer socket error and the inner decode result from recv_string, printing the string or the original bytes on non-UTF8. ```rust let outer = socket.recv_string(0); match outer { Err(e) => println!("socket error: {}", e), Ok(decoded) => match decoded { Ok(s) => println!("got: {}", s), Err(bytes) => println!("non-UTF8 payload: {:?}", bytes), }, } ``` -------------------------------- ### new Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/context.md Creates a new reference-counted context handle wrapping a fresh C context created via zmq_ctx_new. This is the primary way to obtain a Context instance. ```APIDOC ## new ### Description Creates a new reference-counted context handle wrapping a fresh C context created via `zmq_ctx_new`. This is the primary way to obtain a `Context` instance. ### Method N/A (Rust function) ### Endpoint N/A ### Parameters No parameters. ### Returns - **Context** - A new reference-counted context handle. ### Example ```rust let ctx = zmq::Context::new(); let socket = ctx.socket(zmq::REQ).unwrap(); ``` ### Source `src/lib.rs:427` ``` -------------------------------- ### gets Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Retrieves a message metadata property by name. Returns None if the property is missing or not valid UTF-8. ```APIDOC ## gets ### Description Retrieves a message metadata property by name. Returns None if the property is missing or not valid UTF-8. ### Method N/A (Rust method) ### Signature ```rust pub fn gets<'a>(&'a mut self, property: &str) -> Option<&'a str> ``` ### Parameters #### Parameters - `property` (`&str`) - Required - The message metadata property name (e.g. `"Peer-Address"`, `"Socket-Type"`). ### Returns - `Option<&'a str>` - The property value if present and valid UTF-8; `None` if the property is missing or not valid UTF-8. Note: The source documents a known ambiguity where a missing property and a non-UTF-8 value cannot be distinguished. ### Example ```rust let addr = msg.gets("Peer-Address"); match addr { Some(a) => println!("peer: {}", a), None => println!("no Peer-Address property (or non-UTF8)"), } ``` ### Source `src/message.rs:147` ``` -------------------------------- ### new Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Creates a new empty Message. This constructor initializes a zero-copy message buffer. ```APIDOC ## new ### Description Creates a new empty `Message`. ### Method Constructor ### Parameters None ### Returns - `Message` - An empty message. ### Panics Panics on allocation failure. ### Source `src/message.rs:58` ### Example ```rust let msg = zmq::Message::new(); ``` ``` -------------------------------- ### Constructing and inspecting PollItems Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/polling.md Shows how to create a PollItem from a socket and a raw fd, poll them, and inspect the results. ```rust let receiver = ctx.socket(zmq::PULL).unwrap(); let mut items = [ receiver.as_poll_item(zmq::POLLIN), zmq::PollItem::from_fd(some_raw_fd, zmq::POLLIN | zmq::POLLOUT), ]; zmq::poll(&mut items, -1).unwrap(); for item in items { if item.is_readable() { /* ... */ } if item.has_socket(&receiver) { println!("receiver signaled"); } } ``` -------------------------------- ### From conversions (Into) Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Lists the From implementations that allow converting various types into a Message, enabling direct use with Socket::send. ```APIDOC ## From conversions (Into) ### Description `Message` implements `From` for several types, allowing them to be used directly with `Socket::send` (via the blanket `Sendable` impl) and with `Message::from(...)`. ### Conversions | Source type | Behavior | Source line | |-------------|----------|-------------| | `From<&'a [u8]>` | copies the byte slice into the message | `src/message.rs:207` | | `From>` | moves the vector in **without copying** (via `into_boxed_slice()`) | `src/message.rs:218` | | `From>` | moves a boxed slice in without copying; empty input yields an empty message; the memory is given to the message and freed via the `drop_msg_data_box` callback when the message closes (`zmq_msg_init_data`) | `src/message.rs:225` | | `From<&str>` | copies the UTF-8 bytes | `src/message.rs:247` | | `From<&String>` | copies the UTF-8 bytes | `src/message.rs:254` | | `From<&'a T> where T: Into + Clone` | clones then converts | `src/message.rs:261` | ### Example ```rust let socket = ctx.socket(zmq::PUSH).unwrap(); socket.send("hello world!", 0).unwrap(); // &str socket.send(b"raw bytes", 0).unwrap(); // &[u8] let data: Vec = vec![1, 2, 3]; socket.send(data, 0).unwrap(); // Vec, zero-copy move let msg = zmq::Message::from(b"abc"); // From<&[u8]> socket.send(msg, 0).unwrap(); // Message itself ``` ``` -------------------------------- ### from_raw Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/socket.md Creates a Socket from a raw socket pointer obtained from into_raw, assuming ownership of the pointer. The pointer must come from into_raw; ownership is transferred, so other pointers to the same socket may only be used until the returned socket is dropped. ```APIDOC ## from_raw ### Description Creates a Socket from a raw socket pointer obtained from into_raw, assuming ownership of the pointer. The pointer must come from into_raw; ownership is transferred, so other pointers to the same socket may only be used until the returned socket is dropped. ### Method from_raw ### Signature pub unsafe fn from_raw(sock: *mut c_void) -> Socket ### Parameters - `sock` (*mut c_void) - Required - a raw socket pointer obtained from `into_raw` ### Returns - Socket - a Socket that assumes ownership of the pointer (closes it on drop) and references no context. ### Safety - The pointer must come from `into_raw`; ownership is transferred, so other pointers to the same socket may only be used until the returned socket is dropped. ### Source src/lib.rs:626 ``` -------------------------------- ### monitor Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/socket.md Sets up a monitor on the socket, sending events to a PAIR socket at the given endpoint. Monitoring only works over `inproc://`. Passing `0` as `events` disables monitoring. ```APIDOC ## `monitor` ### Description Sets up a monitor on the socket, sending events to a PAIR socket at the given endpoint. Monitoring only works over `inproc://`. Passing `0` as `events` disables monitoring. ### Method `monitor` ### Signature `pub fn monitor(&self, monitor_endpoint: &str, events: i32) -> Result<()>` ### Parameters - **monitor_endpoint** (`&str`) - Required - PAIR socket endpoint that receives monitor events; monitoring only works over `inproc://` - **events** (`i32`) - Required - bitmask of `SocketEvent` values, or `0` ### Returns `Result<()>`; wrapping `zmq_socket_monitor`. ### Behavior Monitor events are delivered as two-part messages on a PAIR socket connected to `monitor_endpoint`; the event code is the first two bytes (little-endian) of the first frame — convert with `SocketEvent::from_raw`. ### Example ```rust let ctx = zmq::Context::new(); let mut server = ctx.socket(zmq::DEALER).unwrap(); let mut monitor = ctx.socket(zmq::PAIR).unwrap(); monitor.bind("inproc://mon").unwrap(); server.monitor("inproc://mon", zmq::SocketEvent::ALL.to_raw()).unwrap(); let msg = monitor.recv_msg(0).unwrap(); let event = u16::from_ne_bytes([msg[0], msg[1]]); println!("event: {}", zmq::SocketEvent::from_raw(event)); ``` ### Source `src/lib.rs:672` ``` -------------------------------- ### Convert zmq::Error to std::io::Error Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/errors.md Use the From trait to convert a zmq::Error into a std::io::Error. The example asserts that EAGAIN maps to ErrorKind::WouldBlock. ```rust let io_err: std::io::Error = zmq::Error::EAGAIN.into(); assert_eq!(io_err.kind(), std::io::ErrorKind::WouldBlock); ``` -------------------------------- ### Default impl Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/context.md Provides a default implementation for Context that creates a new context, equivalent to calling Context::new(). ```APIDOC ## `Default` impl ### Description Returns a new context; equivalent to `Context::new()`. Used in tests as `Context::default()`. ### Method ```rust impl Default for Context { fn default() -> Self { Context::new() } } ``` ### Returns - **`Self`** - A new `Context` instance. ``` -------------------------------- ### Non-blocking poll with EINTR retry Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/polling.md Error handling example showing a non-blocking poll with a timeout of 0. It retries on `EINTR`, prints the number of ready items on success, and panics on other errors. ```rust let mut items = [socket.as_poll_item(zmq::POLLIN)]; loop { match zmq::poll(&mut items, 0) { Ok(n) => { println!("{} items ready", n); break; } Err(zmq::Error::EINTR) => continue, Err(e) => panic!("poll failed: {}", e), } } ``` -------------------------------- ### monitor method signature Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/socket.md Sets up a monitor on the socket. Monitoring only works over inproc:// endpoints. Passing 0 as events disables monitoring. Monitor events are delivered as two-part messages on a PAIR socket; the event code is the first two bytes (little-endian) of the first frame. ```rust pub fn monitor(&self, monitor_endpoint: &str, events: i32) -> Result<()> ``` -------------------------------- ### with_capacity Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Deprecated constructor that delegates to with_size. Use with_size instead. ```APIDOC ## with_capacity ### Description Deprecated constructor that delegates to `with_size`. ### Method Constructor (deprecated) ### Parameters - `len` (`usize`) - Required - Number of bytes to allocate. ### Returns - `Message` - A `Message` with `len` bytes of zeroed memory. ### Deprecation Deprecated since 0.9.1. Use `with_size` instead. ### Source `src/message.rs:111` ### Example ```rust let msg = zmq::Message::with_capacity(1024); ``` ``` -------------------------------- ### Regenerate C bindings with bindgen Source: https://github.com/erickt/rust-zmq/blob/master/HACKING.md Run this command to regenerate the auto-generated part of the C bindings in zmq-sys/src/ffi.rs from the zmq.h header file. It uses bindgen with specific whitelist options to include only ZMQ-related functions, types, and variables. ```sh bindgen \ --with-derive-default \ --whitelist-function "^zmq_.*" \ --whitelist-type "^zmq_.*" \ --whitelist-var "^ZMQ_.*" ~/src/zeromq-4.1.6/include/zmq.h > zmq-sys/src/ffi.rs ``` -------------------------------- ### has Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/utility-functions.md Checks whether the linked ZeroMQ library supports a given capability, such as "curve" or "ipv6". Returns an Option where Some(true) indicates support and Some(false) indicates lack of support. ```APIDOC ## has ### Description Checks whether the linked ZeroMQ library has a specific capability (e.g., "curve", "ipv6"). Returns `Some(true)` if supported, `Some(false)` otherwise. ### Method Function call ### Endpoint `zmq::has(capability: &str)` ### Parameters #### Path Parameters - **capability** (`&str`) - Required - The capability name as understood by `zmq_has` (e.g., "curve", "ipv6"). ### Request Example ```rust if zmq::has("curve").unwrap() { // capability is supported } ``` ### Response #### Success Response - Returns `Option`: `Some(true)` if the capability is supported, `Some(false)` otherwise. For ZeroMQ >= 0.9.0, always returns `Some` variant. #### Response Example ```rust let supported = zmq::has("curve").unwrap(); // true or false ``` ``` -------------------------------- ### socket Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/context.md Creates a new socket associated with this context. ```APIDOC ## `socket` ### Description Creates a new socket of the specified type, holding an `Arc` reference to this context. ### Method `pub fn socket(&self, socket_type: SocketType) -> Result` ### Parameters #### Parameters - `socket_type` (`SocketType`) - Required - One of `PAIR, PUB, SUB, REQ, REP, DEALER, ROUTER, PULL, PUSH, XPUB, XSUB, STREAM`. ### Returns - `Result` - A new socket on success; `Err(Error)` if the C call fails (e.g., `EMFILE` when too many sockets are open). ### Example ```rust let context = zmq::Context::new(); let requester = context.socket(zmq::REQ).unwrap(); requester.connect("tcp://localhost:5555").unwrap(); requester.send("Hello", 0).unwrap(); ``` ### Error Handling Example ```rust let ctx = zmq::Context::new(); let socket = ctx.socket(zmq::PUB); match socket { Ok(s) => drop(s), Err(e) => println!("failed to create socket: {}", e), } ``` ``` -------------------------------- ### zmq::Message::with_size() constructor Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Creates a Message with space for len bytes initialized to 0. ```rust pub fn with_size(len: usize) -> Message ``` -------------------------------- ### as_str method signature Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Returns the message content as a string slice if valid UTF-8, otherwise None. ```rust pub fn as_str(&self) -> Option<&str> ``` -------------------------------- ### connect method signature Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/socket.md Connects the socket to the given endpoint. Note that zmq_connect succeeds even when the peer is not yet reachable because the connection is asynchronous. ```rust pub fn connect(&self, endpoint: &str) -> Result<()> ``` -------------------------------- ### SUB subscription and heartbeat timeouts Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/socket.md Configures a SUB socket with a subscription filter and heartbeat intervals, then checks for readable events using get_events(). ```rust let sub = ctx.socket(zmq::SUB).unwrap(); sub.set_subscribe(b"10001").unwrap(); sub.set_heartbeat_ivl(1000).unwrap(); sub.set_heartbeat_ttl(3000).unwrap(); let events = sub.get_events().unwrap(); if events.contains(zmq::POLLIN) { println!("socket readable"); } ``` -------------------------------- ### CurveKeyPair::new Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/utility-functions.md Creates a new CurveKeyPair by generating a CURVE key pair. Returns a Result containing the key pair or an error if generation fails. ```APIDOC ## `CurveKeyPair::new` ### Description Creates a new `CurveKeyPair` by generating a CURVE key pair. Internally calls `zmq_curve_keypair` and decodes the keys into binary form. ### Method `new` ### Signature ```rust pub fn new() -> Result ``` ### Parameters None ### Returns - **Result** - A new key pair. `Err(Error)` is returned if key generation fails (e.g., unsupported platform or no `curve` capability). ### Example ```rust let server_pair = zmq::CurveKeyPair::new().unwrap(); let client_pair = zmq::CurveKeyPair::new().unwrap(); ``` ``` -------------------------------- ### zmq::Message::new() constructor Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Creates an empty Message via zmq_msg_init. Panics on allocation failure (behavior changed in 0.9.0). ```rust pub fn new() -> Message ``` -------------------------------- ### zmq-sys Cargo.toml system dependency declaration Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/configuration.md Declares the link to the system libzmq and its minimum version (4.1). The build-dependencies include system-deps and zeromq-src for vendored builds. ```toml links = "zmq" [build-dependencies] system-deps = "6" zeromq-src = "0.3" [package.metadata.system-deps] libzmq = "4.1" ``` -------------------------------- ### zmq-sys build script configure function Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/configuration.md Build script for zmq-sys that rebuilds on changes and links against libsodium to enable ZMQ_CURVE. It uses zeromq-src to build libzmq from source when vendored. ```rust pub fn configure() { println!("cargo:rerun-if-changed=build/main.rs"); println!("cargo:rerun-if-env-changed=PROFILE"); // Note that by default `libzmq` builds without `libsodium` by instead // relying on `tweetnacl`. However since this `tweetnacl` [has never been // audited nor is ready for production](https://github.com/zeromq/libzmq/issues/3006), // we link against `libsodium` to enable `ZMQ_CURVE`. zeromq_src::Build::new() .with_libsodium(None) .build(); } ``` -------------------------------- ### z85_encode Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/utility-functions.md Encodes a binary key into Z85 text. The input length must be a multiple of 4, otherwise an EncodeError::BadLength is returned. ```APIDOC ## z85_encode ### Description Encodes a binary key into Z85 text. The input length must be a multiple of 4, otherwise an EncodeError::BadLength is returned. ### Method N/A (Rust function) ### Endpoint N/A (Rust function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **data** (`&[u8]`) - Required - binary key; length **must** be a multiple of 4 ### Request Example ```rust let pair = zmq::CurveKeyPair::new().unwrap(); let encoded = zmq::z85_encode(&pair.public_key).unwrap(); println!("public key (z85): {}", encoded); ``` ### Response #### Success Response (200) - **Ok(String)** - Z85-encoded text #### Response Example ```rust let encoded = zmq::z85_encode(&pair.public_key).unwrap(); ``` ### Error Handling - **Err(EncodeError::BadLength)** - when `data.len() % 4 != 0` ```rust match zmq::z85_encode(b"\x01\x01\x01") { Ok(s) => println!("{}", s), Err(zmq::EncodeError::BadLength) => println!("length not a multiple of 4"), Err(e) => println!("encode failed: {}", e), } ``` ``` -------------------------------- ### zmq::Message::with_capacity() deprecated constructor Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Deprecated since 0.9.1; delegates to with_size. Use with_size instead because the name does not match its semantics. ```rust #[deprecated( since = "0.9.1", note = "This method has a name which does not match its semantics. Use `with_size` instead" )] pub fn with_capacity(len: usize) -> Message { Self::with_size(len) } ``` -------------------------------- ### with_size Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/message.md Creates a Message with space for len bytes initialized to zero. ```APIDOC ## with_size ### Description Creates a `Message` with space for `len` bytes initialized to `0`. ### Method Constructor ### Parameters - `len` (`usize`) - Required - Number of bytes to allocate. ### Returns - `Message` - A `Message` with `len` bytes of zeroed memory. ### Source `src/message.rs:98` ### Example ```rust let msg = zmq::Message::with_size(1024); ``` ``` -------------------------------- ### Error::from_raw Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/errors.md Creates an Error from a raw C errno number. Panics on unknown codes. ```APIDOC ## Error::from_raw ### Description Creates an Error from a raw C errno number. Maps POSIX errno codes, native ZMQ codes, and platform-fallback codes. Panics on unknown codes. ### Method `pub fn from_raw(raw: i32) -> Error` ### Parameters - **raw** (i32) - Required - The raw C errno number. ### Returns - **Error** - The corresponding Error variant. ### Panics Panics if the raw code is unknown. ### Source `src/lib.rs:238` ``` -------------------------------- ### send_str deprecated method Source: https://github.com/erickt/rust-zmq/blob/master/_autodocs/api-reference/socket.md Deprecated since 0.9.0; use send instead. Simply delegates to send. ```rust #[deprecated(since = "0.9.0", note = "Use `send` instead")] pub fn send_str(&self, data: &str, flags: i32) -> Result<()> { self.send(data, flags) } ```