arzmq 0.6.2

High-level bindings to the zeromq library
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
//! # 0MQ context
//!
//! The 0MQ [`Context`] keeps the list of sockets and manages the async I/O thread and internal
//! queries.
//!
//! Before using any 0MQ library functions you must create a 0MQ [`Context`].
//!
//! ## Multiple contexts
//! Multiple [`Context`] may coexist within a single application. Thus, an application can use 0MQ
//! directly and at the same time make use of any number of additional libraries or components
//! which themselves make use of 0MQ:
//!
//! ## Example
//! ```
//! # use arzmq::prelude::{ZmqResult, Context, SubscribeSocket};
//! #
//! # fn main() -> ZmqResult<()> {
//! #
//! let context = Context::new()?;
//! context.set_blocky(false)?;
//!
//! let socket = SubscribeSocket::from_context(&context)?;
//! #
//! # Ok(())
//! # }
//!
//! ```
//!
//! [`Context`]: Context

use alloc::sync::Arc;

#[cfg(feature = "builder")]
pub use builder::ContextBuilder;
use derive_more::{Debug as DebugDeriveMore, Display as DisplayDeriveMore};
use num_traits::PrimInt;

use crate::{ZmqResult, ffi::RawContext, zmq_sys_crate};

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
/// Options that can be set and/or retrieved on a 0MQ [`Context`]
pub enum ContextOption {
    /// Number of I/O threads on this context
    IoThreads,
    /// Maximum number of sockets on this context
    MaxSockets,
    /// Scheduling priority for I/O threads
    ThreadPriority,
    /// Scheduling policy for I/O threads
    ThreadSchedulingPolicy,
    /// Maximum message size
    MaxMessageSize,
    /// Add a CPI to list of affinity for I/O threads
    ThreadAffinityCPUAdd,
    /// Remove a CPI from list of affinity for I/O threads
    ThreadAffinityCPURemove,
    /// Name prefix for I/O threads
    ThreadNamePrefix,
    #[cfg(feature = "draft-api")]
    /// Specify message decoding strategy
    ZeroCopyReceiving,
    /// Enable IPv6 support
    IPv6,
    /// Fix blocky behavior
    Blocky,
    /// Get maximum number of sockets
    SocketLimit,
}

impl From<ContextOption> for i32 {
    fn from(value: ContextOption) -> Self {
        match value {
            ContextOption::Blocky => zmq_sys_crate::ZMQ_BLOCKY as i32,
            ContextOption::IoThreads => zmq_sys_crate::ZMQ_IO_THREADS as i32,
            ContextOption::SocketLimit => zmq_sys_crate::ZMQ_SOCKET_LIMIT as i32,
            ContextOption::ThreadSchedulingPolicy => zmq_sys_crate::ZMQ_THREAD_SCHED_POLICY as i32,
            ContextOption::ThreadPriority => zmq_sys_crate::ZMQ_THREAD_PRIORITY as i32,
            ContextOption::ThreadAffinityCPUAdd => {
                zmq_sys_crate::ZMQ_THREAD_AFFINITY_CPU_ADD as i32
            }
            ContextOption::ThreadAffinityCPURemove => {
                zmq_sys_crate::ZMQ_THREAD_AFFINITY_CPU_REMOVE as i32
            }
            ContextOption::ThreadNamePrefix => zmq_sys_crate::ZMQ_THREAD_NAME_PREFIX as i32,
            ContextOption::MaxMessageSize => zmq_sys_crate::ZMQ_MAX_MSGSZ as i32,
            ContextOption::MaxSockets => zmq_sys_crate::ZMQ_MAX_SOCKETS as i32,
            ContextOption::IPv6 => zmq_sys_crate::ZMQ_IPV6 as i32,
            #[cfg(feature = "draft-api")]
            ContextOption::ZeroCopyReceiving => zmq_sys_crate::ZMQ_ZERO_COPY_RECV as i32,
        }
    }
}

#[cfg(test)]
mod context_option_tests {
    use rstest::*;

    use super::ContextOption;
    use crate::zmq_sys_crate;

    #[rstest]
    #[case(ContextOption::Blocky, zmq_sys_crate::ZMQ_BLOCKY as i32)]
    #[case(ContextOption::IoThreads, zmq_sys_crate::ZMQ_IO_THREADS as i32)]
    #[case(ContextOption::SocketLimit, zmq_sys_crate::ZMQ_SOCKET_LIMIT as i32)]
    #[case(ContextOption::ThreadSchedulingPolicy, zmq_sys_crate::ZMQ_THREAD_SCHED_POLICY as i32)]
    #[case(ContextOption::ThreadPriority, zmq_sys_crate::ZMQ_THREAD_PRIORITY as i32)]
    #[case(ContextOption::ThreadAffinityCPUAdd, zmq_sys_crate::ZMQ_THREAD_AFFINITY_CPU_ADD as i32)]
    #[case(ContextOption::ThreadAffinityCPURemove, zmq_sys_crate::ZMQ_THREAD_AFFINITY_CPU_REMOVE as i32)]
    #[case(ContextOption::ThreadNamePrefix, zmq_sys_crate::ZMQ_THREAD_NAME_PREFIX as i32)]
    #[case(ContextOption::MaxMessageSize, zmq_sys_crate::ZMQ_MAX_MSGSZ as i32)]
    #[case(ContextOption::MaxSockets, zmq_sys_crate::ZMQ_MAX_SOCKETS as i32)]
    #[case(ContextOption::IPv6, zmq_sys_crate::ZMQ_IPV6 as i32)]
    #[cfg_attr(feature = "draft-api", case(ContextOption::ZeroCopyReceiving, zmq_sys_crate::ZMQ_ZERO_COPY_RECV as i32))]
    fn context_options_convert_to_i32(#[case] option: ContextOption, #[case] expected: i32) {
        assert_eq!(<ContextOption as Into<i32>>::into(option), expected);
    }
}

#[derive(DebugDeriveMore, DisplayDeriveMore)]
#[debug("ZmqContext {{ ... }}")]
#[display("ZmqContext")]
/// # 0MQ context
///
/// The 0MQ [`Context`] keeps the list of sockets and manages the async I/O thread and internal
/// queries.
pub struct Context {
    pub(crate) inner: Arc<RawContext>,
}

unsafe impl Send for Context {}
unsafe impl Sync for Context {}

impl Context {
    pub fn new() -> ZmqResult<Self> {
        let inner = RawContext::new()?;
        Ok(Self::from_raw_context(inner))
    }

    pub(crate) fn from_raw_context(raw_context: RawContext) -> Self {
        Self {
            inner: raw_context.into(),
        }
    }

    pub(crate) fn as_raw(&self) -> &RawContext {
        &self.inner
    }

    /// # set context options
    ///
    /// Sets a [`ContextOption`] option on the context. The bool version is mostly suitable for 0/1
    /// options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`ContextOption`]: ContextOption
    pub fn set_option_bool(&self, option: ContextOption, value: bool) -> ZmqResult<()> {
        self.inner.set_ctxopt_bool(option.into(), value)
    }

    /// # set context options
    ///
    /// Sets a [`ContextOption`] option on the context. The int version is mostly suitable for
    /// integer options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`ContextOption`]: ContextOption
    pub fn set_option_int<V>(&self, option: ContextOption, value: V) -> ZmqResult<()>
    where
        V: PrimInt + Into<i32>,
    {
        self.inner.set_ctxopt_int(option.into(), value)
    }

    /// # set context options
    ///
    /// Sets a [`ContextOption`] option on the context. The string version is mostly suitable for
    /// character-based options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`ContextOption`]: ContextOption
    #[cfg(feature = "draft-api")]
    pub fn set_option_string<V>(&self, option: ContextOption, value: V) -> ZmqResult<()>
    where
        V: AsRef<str>,
    {
        self.inner.set_ctxopt_string(option.into(), value.as_ref())
    }

    /// # get context options
    ///
    /// Retrieves a [`ContextOption`] option on the context. The bool version is mostly suitable
    /// for 0/1 options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`ContextOption`]: ContextOption
    pub fn get_option_bool(&self, option: ContextOption) -> ZmqResult<bool> {
        self.inner.get_ctxpt_bool(option.into())
    }

    /// # get context options
    ///
    /// Retrieves a [`ContextOption`] option on the context. The bool version is mostly suitable
    /// for integer options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`ContextOption`]: ContextOption
    pub fn get_option_int<V>(&self, option: ContextOption) -> ZmqResult<V>
    where
        V: PrimInt + From<i32>,
    {
        self.inner.get_ctxopt_int(option.into())
    }

    /// # get context options
    ///
    /// Retrieves a [`ContextOption`] option on the context. The bool version is mostly suitable
    /// for character options.
    ///
    /// For convenience, many options have their dedicated method.
    ///
    /// [`ContextOption`]: ContextOption
    #[cfg(feature = "draft-api")]
    pub fn get_option_string(&self, option: ContextOption) -> ZmqResult<String> {
        self.inner.get_ctxopt_string(option.into())
    }

    /// # Fix blocky behavior `ZMQ_BLOCKY`
    ///
    /// By default the context will block, forever, when dropped. The assumption behind this
    /// behavior is that abrupt termination will cause message loss. Most real applications use
    /// some form of handshaking to ensure applications receive termination messages, and then
    /// terminate the context with [`Linger`] set to zero on all sockets. This setting is an easier
    /// way to get the same result. When [`Blocky`] is set to `false`, all new sockets are given a
    /// linger timeout of zero.
    ///
    /// Default: `true` (old behavior)
    ///
    /// [`Linger`]: crate::socket::Socket::set_linger
    /// [`Blocky`]: ContextOption::Blocky
    pub fn set_blocky(&self, value: bool) -> ZmqResult<()> {
        self.set_option_bool(ContextOption::Blocky, value)
    }

    /// # Get blocky setting `ZMQ_BLOCKY`
    ///
    /// By default the context will block, forever, when dropped. The assumption behind this
    /// behavior is that abrupt termination will cause message loss. Most real applications use
    /// some form of handshaking to ensure applications receive termination messages, and then
    /// terminate the context with [`Linger`] set to zero on all sockets. This setting is an easier
    /// way to get the same result. When '[`Blocky`] is set to `false`, all new sockets are given a
    /// linger timeout of zero.
    ///
    /// Default: `true` (old behavior)
    ///
    /// [`Linger`]: crate::socket::Socket::set_linger
    /// [`Blocky`]: ContextOption::Blocky
    pub fn blocky(&self) -> ZmqResult<bool> {
        self.get_option_bool(ContextOption::Blocky)
    }

    /// # Set number of I/O threads `ZMQ_IO_THREADS`
    ///
    /// The [`IoThreads`] argument specifies the size of the 0MQ thread pool to handle I/O
    /// operations. If your application is using only the `inproc` transport for messaging you may
    /// set this to zero, otherwise set it to at least one. This option only applies before
    /// creating any sockets on the context.
    ///
    /// Default: `1`
    ///
    /// [`IoThreads`]: ContextOption::IoThreads
    pub fn set_io_threads(&self, value: i32) -> ZmqResult<()> {
        self.set_option_int(ContextOption::IoThreads, value)
    }

    /// # Retrieve the number of I/O threads `ZMQ_IO_THREADS`
    ///
    /// The [`IoThreads`] argument specifies the size of the 0MQ thread pool to handle I/O
    /// operations. This option only applies before creating any sockets on the context.
    ///
    /// Default: `1`
    ///
    /// [`IoThreads`]: ContextOption::IoThreads
    pub fn io_threads(&self) -> ZmqResult<i32> {
        self.get_option_int(ContextOption::IoThreads)
    }

    /// # Set maximum message size `ZMQ_MAX_MSGSZ`
    ///
    /// The [`MaxMessageSize`] argument sets the maximum allowed size of a message sent in the
    /// context. You can query the maximal allowed value with [`max_message_size()`].
    ///
    /// Default: [`i32::MAX`]
    ///
    /// [`MaxMessageSize`]: ContextOption::MaxMessageSize
    /// [`max_message_size()`]: #method.max_message_size
    /// [`i32::MAX`]: ::core::primitive::i32::MAX
    pub fn set_max_message_size(&self, value: i32) -> ZmqResult<()> {
        self.set_option_int(ContextOption::MaxMessageSize, value)
    }

    /// # Retrieve maximum message size `ZMQ_MAX_MSGSZ`
    ///
    /// [`max_message_size()`] returns the maximum size of a message allowed for this context.
    /// Default value is [`i32::MAX`].
    ///
    /// [`max_message_size()`]: #method.max_message_size
    /// [`i32::MAX`]: ::core::primitive::i32::MAX
    pub fn max_message_size(&self) -> ZmqResult<i32> {
        self.get_option_int(ContextOption::MaxMessageSize)
    }

    /// # Set maximum number of sockets `ZMQ_MAX_SOCKETS`
    ///
    /// The [`MaxSockets`] argument sets the maximum number of sockets allowed on the context. You
    /// can query the maximal allowed value with [`socket_limit()`] option.
    ///
    /// Default value: `1023`
    ///
    /// [`MaxSockets`]: ContextOption::MaxSockets
    /// [`socket_limit()`]: #method.socket_limit
    pub fn set_max_sockets(&self, value: i32) -> ZmqResult<()> {
        self.set_option_int(ContextOption::MaxSockets, value)
    }

    /// # Retrieve the maximum number of sockets `ZMQ_MAX_SOCKETS`
    ///
    /// Returns the maximum number of sockets allowed for this context.
    ///
    /// Default value: `1023`
    pub fn max_sockets(&self) -> ZmqResult<i32> {
        self.get_option_int(ContextOption::MaxSockets)
    }

    /// # Retreive the socket limit `ZMQ_SOCKET_LIMIT`
    ///
    /// Returns the largest number of sockets that [`set_max_sockets()`] will accept.
    ///
    /// [`set_max_sockets()`]: #method.set_max_sockets
    pub fn socket_limit(&self) -> ZmqResult<i32> {
        self.get_option_int(ContextOption::SocketLimit)
    }

    /// # Set IPv6 option `ZMQ_IPV6`
    ///
    /// The [`IPv6`] argument sets the IPv6 value for all sockets created in the context from this
    /// point onwards. A value of `true` means IPv6 is enabled, while `false` means the socket will
    /// use only IPv4. When IPv6 is enabled, a socket will connect to, or accept connections from,
    /// both IPv4 and IPv6 hosts.
    ///
    /// Default value: `false`
    ///
    /// [`IPv6`]: ContextOption::IPv6
    pub fn set_ipv6(&self, value: bool) -> ZmqResult<()> {
        self.set_option_bool(ContextOption::IPv6, value)
    }

    /// # Retrieve IPv6 option `ZMQ_IPV6`
    ///
    /// Returns the IPv6 option for the context.
    ///
    /// Default value: `false`
    pub fn ipv6(&self) -> ZmqResult<bool> {
        self.get_option_bool(ContextOption::IPv6)
    }

    /// # Specify message decoding strategy `ZMQ_ZERO_COPY_RECV`
    ///
    /// The [`ZeroCopyReceiving`] argument specifies whether the message decoder should use a zero
    /// copy strategy when receiving messages. The zero copy strategy can lead to increased memory
    /// usage in some cases. This option allows you to use the older copying strategy. You can
    /// query the value of this option with [`zero_copy_receiving()`].
    ///
    /// Default value: `true`
    ///
    /// [`ZeroCopyReceiving`]: ContextOption::ZeroCopyReceiving
    /// [`zero_copy_receiving()`]: #method.zero_copy_receiving
    #[cfg(feature = "draft-api")]
    pub fn set_zero_copy_receiving(&self, value: bool) -> ZmqResult<()> {
        self.set_option_bool(ContextOption::ZeroCopyReceiving, value)
    }

    /// # Get message decoding strategy `ZMQ_ZERO_COPY_RECV`
    ///
    /// The [`ZeroCopyReceiving`] argument return whether message decoder uses a zero copy strategy
    /// when receiving messages.
    ///
    /// Default value: `true`
    ///
    /// [`ZeroCopyReceiving`]: ContextOption::ZeroCopyReceiving
    #[cfg(feature = "draft-api")]
    pub fn zero_copy_receiving(&self) -> ZmqResult<bool> {
        self.get_option_bool(ContextOption::ZeroCopyReceiving)
    }

    /// # shutdown a 0MQ context
    ///
    /// The [`shutdown()`] function shall shutdown the 0MQ context.
    ///
    /// Context shutdown will cause any blocking operations currently in progress on sockets open
    /// within `context` to return immediately with an error code of [`ContextTerminated`]. Any
    /// further operations on sockets open within `context` shall fail with an error code of
    /// [`ContextTerminated`]. No further sockets can be created on a context for which
    /// [`shutdown()`] has been called, it will return `Err(`[`ContextTerminated`]`)`.
    ///
    /// [`shutdown()`]: #method.shutdown
    /// [`ContextTerminated`]: crate::ZmqError::ContextTerminated
    pub fn shutdown(&self) -> ZmqResult<()> {
        self.inner.shutdown()
    }
}

impl Clone for Context {
    fn clone(&self) -> Self {
        Self {
            inner: Arc::clone(&self.inner),
        }
    }
}

#[cfg(feature = "builder")]
mod builder {
    use derive_builder::Builder;
    use serde::{Deserialize, Serialize};

    use crate::{ZmqResult, context::Context};

    #[derive(Default, Clone, PartialEq, Eq, Hash, Serialize, Deserialize, Builder)]
    #[builder(
        pattern = "owned",
        name = "ContextBuilder",
        public,
        build_fn(skip, error = "ZmqError"),
        derive(PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)
    )]
    #[builder_struct_attr(doc = "Builder for [`Context`].\n\n")]
    #[allow(dead_code)]
    struct ContextConfig {
        #[builder(default = true)]
        /// Blocky behavior, see [`set_blocky()`].
        ///
        /// [`set_blocky()`]: Context::set_blocky
        blocky: bool,
        #[builder(setter(into), default = 1)]
        /// Number of I/O threads, see [`set_io_threads()`].
        ///
        /// [`set_io_threads()`]: Context::set_io_threads
        io_threads: i32,
        #[builder(setter(into), default = "i32::MAX")]
        /// Maximum message size, see [`set_max_message_size()`].
        ///
        /// [`set_max_message_size()`]: Context::set_max_message_size
        max_message_size: i32,
        #[cfg(feature = "draft-api")]
        #[builder(default = true)]
        /// Specify message decoding strategy, see [`set_zero_copy_receiving()`].
        ///
        /// [`set_zero_copy_receiving()`]: Context::set_zero_copy_receiving
        zero_copy_receiving: bool,
        #[builder(setter(into), default = 1023)]
        /// Maximum number of sockets, see [`set_max_sockets()`].
        ///
        /// [`set_max_sockets()`]: Context::set_max_sockets
        max_sockets: i32,
        #[builder(default = false)]
        /// IPv6 option, see [`set_ipv6()`].
        ///
        /// [`set_ipv6()`]: Context::set_ipv6
        ipv6: bool,
    }

    impl ContextBuilder {
        /// Applies this builder to the provided context
        pub fn apply(self, context: &Context) -> ZmqResult<()> {
            if let Some(blocky) = self.blocky {
                context.set_blocky(blocky)?;
            }

            if let Some(io_threads) = self.io_threads {
                context.set_io_threads(io_threads)?;
            }

            if let Some(max_msg_size) = self.max_message_size {
                context.set_max_message_size(max_msg_size)?;
            }

            if let Some(max_sockets) = self.max_sockets {
                context.set_max_sockets(max_sockets)?;
            }

            if let Some(ipv6) = self.ipv6 {
                context.set_ipv6(ipv6)?;
            }

            #[cfg(feature = "draft-api")]
            if let Some(zero_copy_receiving) = self.zero_copy_receiving {
                context.set_zero_copy_receiving(zero_copy_receiving)?;
            }

            Ok(())
        }

        /// Builds a new context and applies this builder to it.
        pub fn build(self) -> ZmqResult<Context> {
            let context = Context::new()?;

            self.apply(&context)?;

            Ok(context)
        }
    }

    #[cfg(test)]
    mod context_builder_tests {
        use super::ContextBuilder;
        use crate::prelude::ZmqResult;

        #[test]
        fn context_builder_with_default_settings() -> ZmqResult<()> {
            let context = ContextBuilder::default().build()?;

            assert!(context.blocky()?);
            assert_eq!(context.max_message_size()?, i32::MAX);
            assert!(!context.ipv6()?);
            assert_eq!(context.max_sockets()?, 1023);
            assert_eq!(context.io_threads()?, 1);

            Ok(())
        }

        #[test]
        fn context_builder_with_custom_settings() -> ZmqResult<()> {
            let context = ContextBuilder::default()
                .blocky(true)
                .max_message_size(42)
                .ipv6(true)
                .max_sockets(21)
                .io_threads(2)
                .build()?;

            assert!(context.blocky()?);
            assert_eq!(context.max_message_size()?, 42);
            assert!(context.ipv6()?);
            assert_eq!(context.max_sockets()?, 21);
            assert_eq!(context.io_threads()?, 2);

            Ok(())
        }

        #[cfg(feature = "draft-api")]
        #[test]
        fn context_builder_with_draft_api_settings() -> ZmqResult<()> {
            let context = ContextBuilder::default()
                .zero_copy_receiving(false)
                .build()?;

            assert!(!context.zero_copy_receiving()?);

            Ok(())
        }
    }
}

#[cfg(test)]
mod context_tests {
    use rstest::*;

    use super::Context;
    #[cfg(feature = "draft-api")]
    use crate::prelude::ContextOption;
    use crate::prelude::{ZmqError, ZmqResult};

    #[rstest]
    #[case(true)]
    #[case(false)]
    fn context_with_blocky_option(#[case] option_value: bool) -> ZmqResult<()> {
        let context = Context::new()?;

        context.set_blocky(option_value)?;

        assert_eq!(context.blocky()?, option_value);

        Ok(())
    }

    #[rstest]
    #[case(0)]
    #[case(1)]
    #[case(42)]
    #[case(i32::MAX)]
    fn context_with_io_threads(#[case] option_value: i32) -> ZmqResult<()> {
        let context = Context::new()?;

        context.set_io_threads(option_value)?;

        assert_eq!(context.io_threads()?, option_value);

        Ok(())
    }

    #[test]
    fn context_with_invalid_io_threads() -> ZmqResult<()> {
        let context = Context::new()?;

        let result = context.set_io_threads(-1);

        assert!(result.is_err_and(|err| err == ZmqError::InvalidArgument));

        Ok(())
    }

    #[rstest]
    #[case(0)]
    #[case(1)]
    #[case(42)]
    #[case(i32::MAX)]
    fn context_with_max_message_size(#[case] option_value: i32) -> ZmqResult<()> {
        let context = Context::new()?;

        context.set_max_message_size(option_value)?;

        assert_eq!(context.max_message_size()?, option_value);
        Ok(())
    }

    #[test]
    fn context_with_invalid_max_message_size() -> ZmqResult<()> {
        let context = Context::new()?;

        let result = context.set_max_message_size(-1);

        assert!(result.is_err_and(|err| err == ZmqError::InvalidArgument));

        Ok(())
    }

    #[rstest]
    #[case(1)]
    #[case(42)]
    #[case(i32::MAX)]
    fn context_with_max_sockets(#[case] option_value: i32) -> ZmqResult<()> {
        let context = Context::new()?;

        context.set_max_sockets(option_value)?;

        assert_eq!(context.max_sockets()?, option_value);

        Ok(())
    }

    #[rstest]
    #[case(0)]
    #[case(-1)]
    fn context_with_invalid_max_sockets(#[case] option_value: i32) -> ZmqResult<()> {
        let context = Context::new()?;

        let result = context.set_max_sockets(option_value);

        assert!(result.is_err_and(|err| err == ZmqError::InvalidArgument));

        Ok(())
    }

    #[test]
    fn context_socket_limit() -> ZmqResult<()> {
        let context = Context::new()?;

        assert_eq!(context.socket_limit()?, 65535);

        Ok(())
    }

    #[rstest]
    #[case(true)]
    #[case(false)]
    fn context_with_ipv6(#[case] option_value: bool) -> ZmqResult<()> {
        let context = Context::new()?;

        context.set_ipv6(option_value)?;

        assert_eq!(context.ipv6()?, option_value);

        Ok(())
    }

    #[cfg(feature = "draft-api")]
    #[rstest]
    #[case(true)]
    #[case(false)]
    fn context_with_zero_copy_receiving(#[case] option_value: bool) -> ZmqResult<()> {
        let context = Context::new()?;

        context.set_zero_copy_receiving(option_value)?;

        assert_eq!(context.zero_copy_receiving()?, option_value);

        Ok(())
    }

    #[cfg(feature = "draft-api")]
    #[test]
    fn context_with_threadname_prefix() -> ZmqResult<()> {
        let context = Context::new()?;

        context.set_option_string(ContextOption::ThreadNamePrefix, "asdf")?;

        assert_eq!(
            context.get_option_string(ContextOption::ThreadNamePrefix)?,
            "asdf"
        );

        Ok(())
    }
}