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
//! Atomic abstractions and thread-safe appendable list with lock-free iterators
//!
//! # Features
//!  - [`Atomic abstractions (Atomic, AtomicOption, FillOnceAtomicOption, FillOnceAtomicArc)`]
//!  - [`Thread-safe appendable list with a lock-free iterator (VoluntaryServitude - also called VS)`]
//!  - [`Serde serialization/deserialization ("serde-traits" feature)`]
//!  - [`Diesel Insertable implementation ("diesel-traits" or "diesel-sqlite" feature)`]
//!
//!    Implements `Insertable` for [`&VS`] and [`&Iter`]
//!
//!    Sqlite backend is not supported since it doesn't really support batch inserts and we can't
//!    implement the traits needed to mock it (orphan rules), use a transaction and insert them individually ([https://github.com/diesel-rs/diesel/issues/1177](https://github.com/diesel-rs/diesel/issues/1177))
//!  - [`par_extend, from_par_iter rayon implementation ("rayon-traits" feature)`]
//!  - [`Logging ("logs" feature)`]
//!
//!     You probably only need this if you are debugging this crate
//!
//! # Atomic abstractions
//!  - [`Atomic`] -> atomic `Box<T>`
//!  - [`AtomicOption`] -> atomic `Option<Box<T>>`
//!  - [`FillOnceAtomicOption`] -> atomic `Option<Box<T>>` that can give references (ideal for iterators)
//!  - [`FillOnceAtomicArc`] -> atomic `Option<Arc<T>>` with a limited API (like [`FillOnceAtomicOption`])
//!
//! With [`Atomic`] and [`AtomicOption`] it's not safe to get a reference, you must replace the value to access it.
//!
//! To safely get a reference to T you must use [`FillOnceAtomicOption`] and accept the API limitations (initially `None` but can be filled once).
//!
//! For a safe `AtomicArc` you must use some data-structure from `arc-swap`, `RwLock/Mutex` from `parking_lot` (or `std`, which is slower but the standard) or [`FillOnceAtomicArc`] and accept the limited API (2018).
//!
//! # Thread-safe appendable list that can create a lock-free iterator
//!  - [`VoluntaryServitude`] (also called [`VS`])
//!
//! # API of `VS` Iterator
//! - [`Iter`]
//!
//! # Logging
//!
//! *Setup logger according to `RUST_LOG` env var and `logs` feature*
//!
//! ## Enable the feature:
//!
//! **Cargo.toml**
//! ```toml
//! [dependencies]
//! voluntary_servitude = { version = "4", features = "logs" }
//! ```
//!
//! ## Set the `RUST_LOG` env var:
//!
//! ```bash
//! export RUST_LOG=voluntary_servitude=trace
//! export RUST_LOG=voluntary_servitude=debug
//! export RUST_LOG=voluntary_servitude=info
//! export RUST_LOG=voluntary_servitude=warn
//! export RUST_LOG=voluntary_servitude=error
//! ```
//!
//! ## Enable the logger using some setup (like env_logger)
//!
//! ```rust
//! extern crate env_logger;
//! env_logger::init();
//! // Call code to be logged
//! // ...
//! ```
//!
//! [`Atomic`]: ./atomics/struct.Atomic.html
//! [`AtomicOption`]: ./atomics/struct.AtomicOption.html
//! [`FillOnceAtomicOption`]: ./atomics/struct.FillOnceAtomicOption.html
//! [`FillOnceAtomicArc`]: ./atomics/struct.FillOnceAtomicArc.html
//! [`Atomic abstractions (Atomic, AtomicOption, FillOnceAtomicOption, FillOnceAtomicArc)`]: #atomic-abstractions
//! [`Thread-safe appendable list with a lock-free iterator (VoluntaryServitude - also called VS)`]: ./struct.VoluntaryServitude.html
//! [`Serde serialization/deserialization ("serde-traits" feature)`]: ./struct.VoluntaryServitude.html#impl-Serialize
//! [`Diesel Insertable implementation ("diesel-traits" or "diesel-sqlite" feature)`]: ./struct.VoluntaryServitude.html#impl-Insertable<Tab>
//! [`&VS`]: ./struct.VoluntaryServitude.html#impl-Insertable<Tab>
//! [`&Iter`]: ./struct.Iter.html#impl-Insertable<Tab>
//! [`par_extend, from_par_iter rayon implementation ("rayon-traits" feature)`]: ./struct.VoluntaryServitude.html#impl-FromParallelIterator<T>
//! [`VoluntaryServitude`]: ./struct.VoluntaryServitude.html
//! [`VS`]: ./type.VS.html
//! [`Iter`]: ./struct.Iter.html
//! [`Logging ("logs" feature)`]: #logging

#![deny(
    missing_docs,
    missing_debug_implementations,
    trivial_numeric_casts,
    unused_extern_crates,
    unused_import_braces,
    unused_qualifications,
    unused_results,
    bad_style,
    const_err,
    dead_code,
    improper_ctypes,
    legacy_directory_ownership,
    non_shorthand_field_patterns,
    no_mangle_generic_items,
    overflowing_literals,
    path_statements,
    patterns_in_fns_without_body,
    plugin_as_library,
    private_in_public,
    safe_extern_statics,
    unconditional_recursion,
    unions_with_drop_fields,
    unused_allocation,
    unused_comparisons,
    unused_parens,
    while_true
)]
#![doc(html_root_url = "https://docs.rs/voluntary_servitude/4.0.3/voluntary-servitude")]
#![cfg_attr(docs_rs_workaround, feature(doc_cfg))]

/// Alias for [`voluntary_servitude`] macro
///
/// [`voluntary_servitude`]: ./macro.voluntary_servitude.html
///
/// ```
/// # #[macro_use] extern crate voluntary_servitude;
/// # extern crate env_logger;
/// # env_logger::init();
/// use voluntary_servitude::VS;
/// let vs: VS<()> = vs![];
/// assert!(vs.is_empty());
///
/// let vs = vs![1, 2, 3];
/// assert_eq!(vs.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
///
/// let vs = vs![1; 3];
/// assert_eq!(vs.iter().collect::<Vec<_>>(), vec![&1; 3]);
/// # let _ = vs![1, 2, 3,];
/// ```
#[macro_export]
macro_rules! vs {
    () => (voluntary_servitude![]);
    ($elem: expr; $n: expr) => (voluntary_servitude![$elem; $n]);
    ($($x: expr),+) => (voluntary_servitude![$($x),+]);
    ($($x: expr,)+) => (voluntary_servitude![$($x,)+]);
}

/// Creates new [`VS`] with specified elements as in the `vec!` macro
///
/// [`VS`]: ./type.VS.html
///
/// ```
/// # #[macro_use] extern crate voluntary_servitude;
/// # extern crate env_logger;
/// # env_logger::init();
/// use voluntary_servitude::VS;
/// let vs: VS<()> = voluntary_servitude![];
/// assert!(vs.is_empty());
///
/// let vs = voluntary_servitude![1, 2, 3];
/// assert_eq!(vs.iter().collect::<Vec<_>>(), vec![&1, &2, &3]);
///
/// let vs = voluntary_servitude![1; 3];
/// assert_eq!(vs.iter().collect::<Vec<_>>(), vec![&1; 3]);
/// # let _ = voluntary_servitude![1, 2, 3,];
/// ```
#[macro_export]
macro_rules! voluntary_servitude {
    () => ($crate::VS::default());
    ($elem: expr; $n: expr) => {{
        let vs = $crate::VS::default();
        for _ in 0..$n {
            vs.append($elem);
        }
        vs
    }};
    ($($x: expr),+) => (voluntary_servitude![$($x,)+]);
    ($($x: expr,)+) => {{
        let vs = $crate::VS::default();
        $(vs.append($x);)+
        vs
    }};
}

// Diesel doesn't play well with 2018 edition macro imports
#[cfg(all(any(feature = "diesel-traits", feature = "diesel-sqlite"), test))]
#[macro_use]
extern crate diesel;

/// Remove logging macros when they are disabled (at compile time)
#[macro_use]
#[cfg(not(feature = "logs"))]
#[allow(unused)]
mod mock {
    macro_rules! trace(($($x:tt)*) => ());
    macro_rules! debug(($($x:tt)*) => ());
    macro_rules! info(($($x:tt)*) => ());
    macro_rules! warn(($($x:tt)*) => ());
    macro_rules! error(($($x:tt)*) => ());
}

pub mod atomics;
mod iterator;
mod node;
mod traits;
mod voluntary_servitude;

/// Simplify internal imports
#[allow(unused)]
mod prelude {
    pub(crate) use crate::atomics::{Atomic, AtomicOption, FillOnceAtomicOption};
    pub(crate) use crate::{IntoPtr, NotEmpty};
    pub(crate) use crate::{Iter, VoluntaryServitude, VS};
    #[cfg(feature = "logs")]
    pub use log::{debug, error, info, trace, warn};
}

use std::{error::Error, fmt, fmt::Debug, fmt::Display, fmt::Formatter};

/// Happens when you call `try_store` in a already filled [`AtomicOption`]/[`FillOnceAtomicOption`]/[`FillOnceAtomicArc`]
///
/// [`AtomicOption`]: ./atomics/struct.AtomicOption.html#method.try_store
/// [`FillOnceAtomicOption`]: ./atomics/struct.FillOnceAtomicOption.html#method.try_store
/// [`FillOnceAtomicArc`]: ./atomics/struct.FillOnceAtomicArc.html#method.try_store
#[derive(Copy, Clone, Eq, PartialEq, Ord, PartialOrd, Default)]
pub struct NotEmpty;

impl Debug for NotEmpty {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "NotEmpty")
    }
}

impl Display for NotEmpty {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(f, "not empty")
    }
}

impl Error for NotEmpty {}

pub use crate::iterator::Iter;
pub use crate::voluntary_servitude::{VoluntaryServitude, VS};

use std::ptr::null_mut;

/// Trait made to simplify conversion between smart pointers and raw pointers
pub(crate) trait IntoPtr<T> {
    /// Converts itself into a mutable pointer to it (leak or unwrap things)
    fn into_ptr(self) -> *mut T;
}

impl<T> IntoPtr<T> for T {
    #[inline]
    #[must_use]
    fn into_ptr(self) -> *mut Self {
        Box::into_raw(Box::new(self))
    }
}

impl<T> IntoPtr<T> for Option<T> {
    #[inline]
    #[must_use]
    fn into_ptr(self) -> *mut T {
        self.map(Box::new).into_ptr()
    }
}

impl<T> IntoPtr<T> for Box<T> {
    #[inline]
    #[must_use]
    fn into_ptr(self) -> *mut T {
        Self::into_raw(self)
    }
}

impl<T> IntoPtr<T> for Option<Box<T>> {
    #[inline]
    #[must_use]
    fn into_ptr(self) -> *mut T {
        self.map_or(null_mut(), Box::into_raw)
    }
}

#[cfg(all(feature = "logs", test))]
extern crate env_logger;

#[cfg(test)]
pub fn setup_logger() {
    use std::sync::Once;
    #[allow(unused)]
    static INITIALIZE: Once = Once::new();
    #[cfg(feature = "logs")]
    INITIALIZE.call_once(env_logger::init);
}