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
/******************************************************************************
Author: Joaquín Béjar García
Email: jb@taunais.com
Date: 25/12/25
******************************************************************************/
//! # Positive
//!
//! A type-safe wrapper for guaranteed positive decimal values in Rust.
//!
//! ## Overview
//!
//! `Positive` is a Rust library that provides a type-safe wrapper around `Decimal` values,
//! ensuring that the contained value is always positive. `Positive` values are non-negative
//! (>= 0). Its companion type, [`StrictlyPositive`], holds values that are strictly positive
//! (> 0), and the two can be used side by side in the same crate.
//! This is particularly useful in financial applications where negative values would be
//! invalid or meaningless, such as prices, quantities, volatilities, and other positive metrics.
//!
//! ## Features
//!
//! - **Type Safety**: Compile-time and runtime guarantees that values are positive
//! - **Strictly Positive Values**: [`StrictlyPositive`] (> 0) next to `Positive` (>= 0), always available
//! - **Non-Zero Mode (deprecated)**: the `non-zero` feature flag; use [`StrictlyPositive`] instead
//! - **Decimal Precision**: Built on [`rust_decimal`](https://crates.io/crates/rust_decimal) for accurate financial calculations
//! - **Rich API**: Comprehensive arithmetic operations, conversions, and mathematical utilities
//! - **Predefined Constants**: Common numeric values (0-10, multiples of 5/100/1000, PI, E, etc.)
//! - **Convenient Macros**: `pos!`, `pos_or_panic!`, `spos!`, `strict_pos!`, `strict_pos_or_panic!`
//! - **Prelude Module**: Simple imports with `use positive::prelude::*;`
//! - **Serde Support**: Lossless serialisation as exact decimal strings, for JSON and binary formats alike
//! - **Approx Support**: Approximate equality comparisons for floating-point tolerance
//! - **Checked Operations**: Safe arithmetic operations that return `Result` instead of panicking
//! - **Optional utoipa Integration**: OpenAPI schema generation support via feature flag
//!
//! ## Installation
//!
//! Add this to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! positive = "0.7"
//! ```
//!
//! Strictly positive values need no feature: use [`StrictlyPositive`]. The
//! `non-zero` feature is **deprecated** (see
//! [Deprecated: the `non-zero` feature](#deprecated-the-non-zero-feature)).
//!
//! To enable OpenAPI schema support:
//!
//! ```toml
//! [dependencies]
//! positive = { version = "0.7", features = ["utoipa"] }
//! ```
//!
//! ## Quick Start
//!
//! The recommended pattern is fallible construction and checked arithmetic,
//! propagating [`PositiveError`] with `?`. Nothing here can panic:
//!
//! ```rust
//! use positive::prelude::*;
//!
//! fn order_total() -> Result<Positive, PositiveError> {
//! let price = Positive::new(100.50)?;
//! let quantity = Positive::new(10.0)?;
//! let discount = Positive::new(5.0)?;
//!
//! let subtotal = price.checked_mul(&quantity)?;
//! let after_discount = subtotal.checked_sub(&discount)?;
//!
//! // Constants are ready-made and cannot fail
//! let tax_rate = FIVE.checked_div(&HUNDRED)?; // 5%
//! let tax = after_discount.checked_mul(&tax_rate)?;
//!
//! after_discount.checked_add(&tax)
//! }
//!
//! assert!(order_total().is_ok());
//! ```
//!
//! The operators (`+`, `-`, `*`, `/`) are available too and read more
//! naturally, at the cost of panicking on overflow or on a result that would
//! break the invariant. Every one of them has a `checked_` counterpart, listed
//! in its `# Panics` section, so the panicking form is always an opt-in:
//!
//! ```rust
//! use positive::prelude::*;
//!
//! # fn main() -> Result<(), PositiveError> {
//! let price = Positive::new(100.50)?;
//! let quantity = Positive::new(10.0)?;
//! let total = price * quantity; // panics on overflow
//! let total = price.checked_mul(&quantity)?; // returns Err instead
//! # Ok(())
//! # }
//! ```
//!
//! ### A note on the examples below
//!
//! The remaining examples use [`pos_or_panic!`] for brevity, so each one fits
//! in a line or two. That macro panics on invalid input and is intended for
//! tests, examples and constant literals — **not** for production paths that
//! handle external input. There, use [`Positive::new`], [`pos!`] or [`spos!`]
//! and handle the failure.
//!
//! ## API Overview
//!
//! ### Creation
//!
//! ```rust
//! use positive::{Positive, pos, pos_or_panic, spos};
//! use rust_decimal::Decimal;
//!
//! // From f64
//! let p = Positive::new(5.0).unwrap();
//!
//! // From Decimal
//! let p = Positive::new_decimal(Decimal::ONE).unwrap();
//!
//! // Using macros
//! let p = pos!(5.0); // Returns Result<Positive, PositiveError>
//! let p = pos_or_panic!(5.0); // Panics on invalid input
//! let p = spos!(5.0); // Returns Option<Positive>
//! ```
//!
//! ### Constants
//!
//! The library provides many predefined constants accessible via `Positive::CONSTANT`
//! or directly from the `constants` module:
//!
//! ```rust
//! use positive::Positive;
//! use positive::constants::*;
//!
//! // Integer constants (1-10)
//! let one = Positive::ONE; // 1
//! let two = Positive::TWO; // 2
//! let ten = Positive::TEN; // 10
//!
//! // Multiples of 5 (15-95)
//! let fifteen = FIFTEEN; // 15
//! let fifty = FIFTY; // 50
//!
//! // Multiples of 100 (100-900)
//! let hundred = Positive::HUNDRED; // 100
//! let five_hundred = FIVE_HUNDRED; // 500
//!
//! // Multiples of 1000 (1000-10000)
//! let thousand = Positive::THOUSAND; // 1000
//! let ten_thousand = TEN_THOUSAND; // 10000
//!
//! // Mathematical constants
//! let pi = Positive::PI; // π (3.14159...)
//! let e = Positive::E; // e (2.71828...)
//!
//! // Special values
//! let epsilon = EPSILON; // Small tolerance for comparisons
//! let max = Positive::MAX; // Largest representable value (Decimal::MAX)
//! ```
//!
//! ### Conversions
//!
//! ```rust
//! use positive::pos_or_panic;
//!
//! let p = pos_or_panic!(5.5);
//!
//! let f: f64 = p.to_f64(); // Infallible, lossy beyond ~15 digits
//! let d = p.to_dec(); // To Decimal, exact
//!
//! // Integer conversions are fallible and truncate toward zero
//! let i: Result<i64, _> = i64::try_from(p);
//! let u: Result<u64, _> = u64::try_from(p);
//! let n: Result<usize, _> = usize::try_from(p);
//! let maybe: Option<u64> = p.to_u64_checked();
//! ```
//!
//! ### Arithmetic Operations
//!
//! ```rust
//! use positive::pos_or_panic;
//!
//! let a = pos_or_panic!(10.0);
//! let b = pos_or_panic!(3.0);
//!
//! // Standard operations
//! let sum = a + b; // Addition
//! let diff = a - b; // Subtraction (panics if result < 0)
//! let prod = a * b; // Multiplication
//! let quot = a / b; // Division
//!
//! // Safe operations
//! let safe_diff = a.checked_sub(&b); // Returns Result
//! let safe_quot = a.checked_div(&b); // Returns Result (handles div by zero)
//! ```
//!
//! ### Mathematical Functions
//!
//! ```rust
//! use positive::pos_or_panic;
//!
//! let p = pos_or_panic!(16.0);
//!
//! let sqrt = p.sqrt(); // Square root
//! let ln = p.ln(); // Natural logarithm
//! let log10 = p.log10(); // Base-10 logarithm
//! let exp = p.exp(); // Exponential (e^x)
//! let pow = p.pow(pos_or_panic!(2.0)); // Power with Positive exponent
//! let powi = p.powi(2); // Integer power
//! let floor = p.floor(); // Floor
//! let ceil = p.ceiling(); // Ceiling
//! let round = p.round(); // Round to nearest integer
//! let round2 = p.round_to(2); // Round to 2 decimal places
//! ```
//!
//! ### Utility Methods
//!
//! ```rust
//! use positive::pos_or_panic;
//!
//! use rust_decimal_macros::dec;
//! let p = pos_or_panic!(5.0);
//!
//! let is_zero = p.is_zero(); // Check if zero
//! let is_mult = p.is_multiple_of_dec(dec!(2)); // Check if multiple of value
//! let clamped = p.clamp(pos_or_panic!(1.0), pos_or_panic!(10.0)); // Clamp between bounds
//! let min_val = p.min(pos_or_panic!(3.0)); // Minimum of two values
//! let max_val = p.max(pos_or_panic!(3.0)); // Maximum of two values
//! let formatted = p.format_fixed_places(2); // Format with fixed decimals
//! ```
//!
//! ## StrictlyPositive
//!
//! [`StrictlyPositive`] is a decimal that is always greater than zero. It is
//! always available, independent of any feature flag, so a single type can
//! hold a price that must never be zero next to a volume that may be:
//!
//! ```rust
//! use positive::prelude::*;
//! use rust_decimal_macros::dec;
//!
//! struct Instrument {
//! price: StrictlyPositive, // > 0
//! daily_volume: Positive, // >= 0
//! }
//!
//! # fn main() -> Result<(), PositiveError> {
//! let instrument = Instrument {
//! price: StrictlyPositive::new_decimal(dec!(101.25))?,
//! daily_volume: Positive::new_decimal(dec!(1500))?,
//! };
//!
//! // Zero and negative values are rejected with `OutOfBounds`, whose
//! // minimum is `StrictlyPositive::MIN` (1e-28).
//! assert!(StrictlyPositive::new_decimal(dec!(0)).is_err());
//! assert!(strict_pos!(0.0).is_err());
//!
//! // Results keep the strict type only where they are guaranteed > 0.
//! let with_fee: StrictlyPositive = instrument.price + Positive::ONE; // S + P -> S
//! let notional: Positive = instrument.price * instrument.daily_volume; // S * P -> P
//! let spread: Positive = with_fee - instrument.price; // S - S -> P
//! assert_eq!(spread, Positive::ONE);
//! assert!(notional > dec!(0));
//!
//! // `checked_sub` keeps the strict type and reports a non-positive result.
//! assert!(instrument.price.checked_sub(&instrument.price).is_err());
//! # Ok(())
//! # }
//! ```
//!
//! | Operation | Result |
//! |---|---|
//! | `S + S`, `S + P`, `P + S` | `S` |
//! | `S * S`, `S / S` | `S`; the `checked_*` form returns `Err` if `Decimal` rounding underflows to zero |
//! | `S * P`, `P * S`, `S / P`, `P / S` | `P` |
//! | `S - S` | `P` (the operator); `checked_sub` returns `Result<S, _>` |
//! | `ln`, `log10` | `Decimal`, with no zero edge case |
//!
//! Every operator that returns a `StrictlyPositive` has a `checked_*`
//! counterpart. There is no `std::iter::Sum` impl, because an empty sum is
//! zero; use [`StrictlyPositive::checked_sum`]. Serialisation uses the same
//! exact decimal string as `Positive`, and deserialising `0` fails under every
//! feature configuration.
//!
//! ## Deprecated: the `non-zero` feature
//!
//! The `non-zero` feature is deprecated and will be removed in a future minor
//! release. It changes what `Positive` means (from `>= 0` to `> 0`) instead of
//! adding a type, which makes it non-additive: Cargo unifies features across
//! the whole dependency graph, so if any crate in your build enables
//! `non-zero`, every `Positive` in the build becomes strictly positive,
//! including in crates that rely on zero being valid.
//!
//! To migrate, drop the feature and use [`StrictlyPositive`] wherever you need
//! `> 0`, keeping `Positive` where zero is valid:
//!
//! ```toml
//! # Before
//! positive = { version = "0.7", features = ["non-zero"] }
//! # After
//! positive = "0.7"
//! ```
//!
//! ```rust
//! use positive::{StrictlyPositive, strict_pos};
//!
//! // Before (with `non-zero`): let price = pos!(10.0)?; // Positive, > 0
//! // After:
//! let price: Result<StrictlyPositive, _> = strict_pos!(10.0);
//! assert!(price.is_ok());
//! ```
//!
//! `StrictlyPositive` mirrors the commonly used `Positive` API: constructors,
//! `checked_*` arithmetic, the rounding and power functions, conversions and
//! constants. Anything else is one `to_positive()` away.
//!
//! ## Error Handling
//!
//! The library provides `PositiveError` for comprehensive error handling:
//!
//! ```rust
//! use positive::{Positive, PositiveError};
//!
//! fn example() -> Result<Positive, PositiveError> {
//! let value = Positive::new(-5.0)?; // Returns Err(OutOfBounds)
//! Ok(value)
//! }
//! ```
//!
//! `PositiveError` has exactly five variants, and that set is stable across
//! minor versions. There is no catch-all, so callers can match exhaustively
//! without a wildcard arm:
//!
//! - `InvalidValue` - Input that is not a decimal at all (`NaN`, `±inf`, unparsable text)
//! - `ArithmeticError` - Overflow, division by zero, or a result breaking the invariant
//! - `ConversionError` - A valid value not representable in the destination type
//! - `OutOfBounds` - A well-formed decimal outside the permitted range
//! - `InvalidPrecision` - A decimal precision outside the range `Decimal` supports
//!
//! `OutOfBounds` carries exact `Decimal` values for the offending input and
//! both bounds, so no precision is lost in the diagnostic. For
//! [`StrictlyPositive`], and for `Positive` under the deprecated `non-zero`
//! feature, the reported minimum is `1e-28`, the smallest strictly positive
//! `Decimal`.
//!
//! Parsing follows the same contract — `FromStr` fails with a `PositiveError`
//! that preserves the offending input:
//!
//! ```rust
//! use positive::{Positive, PositiveError};
//! use std::str::FromStr;
//!
//! let err = Positive::from_str("not a number").unwrap_err();
//! assert!(matches!(err, PositiveError::InvalidValue { .. }));
//! ```
//!
//! ## Serialization
//!
//! `Positive` serialises as the **exact decimal string**, so every value the
//! type can hold round-trips without losing a digit:
//!
//! ```rust
//! use positive::{Positive, pos_or_panic};
//! use rust_decimal::Decimal;
//! use std::str::FromStr;
//!
//! let p = pos_or_panic!(42.5);
//! let json = serde_json::to_string(&p).unwrap(); // "\"42.5\""
//! let parsed: Positive = serde_json::from_str(&json).unwrap();
//! assert_eq!(parsed, p);
//!
//! // Full 28-digit precision survives the round trip
//! let exact = Decimal::from_str("0.1234567890123456789012345678").unwrap();
//! let value = Positive::new_decimal(exact).unwrap();
//! let json = serde_json::to_string(&value).unwrap();
//! let back: Positive = serde_json::from_str(&json).unwrap();
//! assert_eq!(back.to_dec(), exact);
//! ```
//!
//! ### Precision guarantees
//!
//! - **Representation**: a JSON string holding the exact decimal, e.g.
//! `"42.5"`, `"79228162514264337593543950335"`.
//! - **Lossless for every representable value**, including 28-digit fractions,
//! integers above `i64::MAX`, and `Positive::MAX`.
//! - **Validation on the way in**: the positivity invariant is enforced on
//! deserialisation, so the `non-zero` feature rejects zero there too.
//! - **Non-self-describing formats** (bincode, postcard) are supported: the
//! implementation asks for a string rather than relying on
//! `deserialize_any`, which such formats cannot provide.
//! - **Backward compatibility**: plain JSON numbers written by 0.5.x still
//! deserialise. They are lossy by construction — that precision was gone
//! before the bytes were written — so re-serialising upgrades them to the
//! exact form.
//!
//! A JSON *number* cannot carry this precision: nearly every consumer parses
//! one into an `f64`, which holds about 15 significant digits. That is why the
//! wire format is a string, and why `rust_decimal` itself uses one.
//!
//! ## Use Cases
//!
//! - **Financial Applications**: Prices, quantities, fees, rates
//! - **Scientific Computing**: Physical quantities that cannot be negative
//! - **Game Development**: Health points, distances, timers
//! - **Data Validation**: Ensuring input values meet positivity constraints
//!
//! ## Safety
//!
//! This crate contains no `unsafe` code, enforced at compile time by
//! `#![forbid(unsafe_code)]`. Earlier versions exposed a public
//! `Positive::new_unchecked`, an `unsafe fn` that performed no unsafe
//! operation: it moved a logical precondition onto the caller without making
//! a violation Rust undefined behaviour. It has been removed. Every public
//! path that yields a `Positive` validates the invariant.
//!
//! ## License
//!
//! This project is licensed under the MIT License.
//!
pub use ;
pub use ;
pub use StrictlyPositive;
/// Re-export rust_decimal for convenience.
pub use Decimal;