Skip to main content

rustledger_core/
lib.rs

1//! Core types for rustledger
2//!
3//! This crate provides the fundamental types used throughout the rustledger project:
4//!
5//! - [`Amount`] - A decimal number with a currency
6//! - [`Cost`] - Acquisition cost of a position (lot)
7//! - [`CostSpec`] - Specification for matching or creating costs
8//! - [`Position`] - Units held at a cost
9//! - [`Inventory`] - A collection of positions with booking support
10//! - [`BookingMethod`] - How to match lots when reducing positions
11//! - [`Directive`] - All directive types (Transaction, Balance, Open, etc.)
12//!
13//! # Example
14//!
15//! ```
16//! use rustledger_core::{Amount, Cost, Position, Inventory, BookingMethod};
17//! use rust_decimal_macros::dec;
18//!
19//! // Create an inventory
20//! let mut inv = Inventory::new();
21//!
22//! // Add a stock position with cost
23//! let cost = Cost::new(dec!(150.00), "USD")
24//!     .with_date(rustledger_core::naive_date(2024, 1, 15).unwrap());
25//! inv.add(Position::with_cost(Amount::new(dec!(10), "AAPL"), cost));
26//!
27//! // Check holdings
28//! assert_eq!(inv.units("AAPL"), dec!(10));
29//!
30//! // Sell some shares using FIFO
31//! let result = inv.reduce(
32//!     &Amount::new(dec!(-5), "AAPL"),
33//!     None,
34//!     BookingMethod::Fifo,
35//! ).unwrap();
36//!
37//! assert_eq!(inv.units("AAPL"), dec!(5));
38//! assert_eq!(result.cost_basis.unwrap().number, dec!(750.00)); // 5 * 150
39//! ```
40
41#![forbid(unsafe_code)]
42#![warn(missing_docs)]
43
44pub mod amount;
45pub mod calendar;
46pub mod cost;
47pub mod decimal;
48pub mod directive;
49pub mod display_context;
50pub mod extract;
51pub mod format;
52pub mod identifiers;
53pub mod implicit_prices;
54pub mod intern;
55pub mod inventory;
56pub mod meta_json;
57pub mod position;
58pub mod shift_spans_impls;
59pub mod span;
60pub mod synthetic;
61pub mod visit;
62
63// Kani formal verification proofs (only compiled with Kani)
64#[cfg(kani)]
65mod kani_proofs;
66
67pub use amount::{Amount, AmountParseError, AmountParseErrorReason, IncompleteAmount};
68pub use calendar::{CalendarPeriod, quarter_index0};
69pub use cost::{BookedCost, BookedCostInvariantError, Cost, CostNumber, CostSpec};
70pub use decimal::{
71    add_python_scale, checked_add_python_scale, checked_div_python_scale, checked_sub_python_scale,
72    negate_python, round_dp_python, sub_python_scale,
73};
74pub use directive::{
75    Balance, Close, Commodity, Custom, Directive, DirectivePriority, Document, Event, MetaValue,
76    Metadata, Note, Open, Pad, Posting, Price, PriceAnnotation, PriceKind, Query, Transaction,
77    booking_sort_key, meta_value_as_bool, parse_bool_word, parse_precision_meta, sort_directives,
78};
79pub use display_context::{DEFAULT_CURRENCY, DisplayContext, OutputSurface, Precision};
80pub use extract::{
81    DEFAULT_CURRENCIES, extract_accounts, extract_accounts_iter, extract_currencies,
82    extract_currencies_iter, extract_links, extract_links_iter, extract_payees,
83    extract_payees_iter, extract_tags, extract_tags_iter,
84};
85pub use format::{
86    Alignment, FormatConfig, FormatLine, format_directive_lines, format_directives,
87    format_posting_line, posting_format_line, render_lines, resolve_alignment,
88};
89pub use identifiers::{
90    ACCOUNT_TYPES, Account, AccountTypeKind, AccountTypes, Currency, Link, Tag, account_type,
91    is_default_account_root, is_subaccount_or_equal,
92};
93pub use implicit_prices::extract_per_unit_price;
94pub use intern::{InternedStr, StringInterner};
95pub use inventory::{
96    AccountedBookingError, BookingError, BookingMethod, BookingResult, Inventory, OverflowError,
97    ReductionScope, sum_account_and_subaccounts,
98};
99pub use meta_json::{json_to_meta_value, meta_value_to_json, meta_value_type_tag};
100pub use position::Position;
101pub use span::{SYNTHESIZED_FILE_ID, ShiftSpans, Span, Spanned};
102pub use visit::{visit_accounts, visit_currencies};
103
104// Re-export commonly used external types
105/// Calendar date without timezone. Alias for `jiff::civil::Date`.
106pub type NaiveDate = jiff::civil::Date;
107pub use rust_decimal::Decimal;
108
109/// Construct a [`NaiveDate`] from `(year, month, day)` with i32/u32 arguments.
110///
111/// Wraps [`jiff::civil::date`] which takes `(i16, i8, i8)`.
112/// Returns `None` if the date is invalid.
113#[must_use]
114pub fn naive_date(year: i32, month: u32, day: u32) -> Option<NaiveDate> {
115    let y = i16::try_from(year).ok()?;
116    let m = i8::try_from(month).ok()?;
117    let d = i8::try_from(day).ok()?;
118    NaiveDate::new(y, m, d).ok()
119}
120
121// Re-export rkyv wrappers when feature is enabled
122#[cfg(feature = "rkyv")]
123pub use intern::{AsDecimal, AsInternedStr, AsNaiveDate};