Skip to main content

samp/
lib.rs

1//! Rust toolkit for developing SA-MP plugins and native Open Multiplayer components.
2//!
3//! # Workspace structure
4//!
5//! - `samp` — main crate; re-exports SDK + codegen and exposes the API the plugin uses.
6//! - `samp-codegen` — proc macros (`#[native]`, `initialize_plugin!`,
7//!   `#[derive(SampPlugin)]`) that generate FFI entry points and argument parsing.
8//! - `samp-sdk` — low-level bindings for the AMX VM (SA-MP) and for the component
9//!   ABI (Open Multiplayer).
10//!
11//! # Minimal `Cargo.toml` setup
12//!
13//! ```toml
14//! [lib]
15//! crate-type = ["cdylib"]
16//!
17//! [dependencies]
18//! samp = { git = "https://github.com/NullSablex/rust-samp" }
19//! ```
20//!
21//! # Plugin example
22//!
23//! ```rust,ignore
24//! use samp::prelude::*;
25//! use samp::{native, initialize_plugin, SampPlugin};
26//!
27//! #[derive(SampPlugin, Default)]
28//! struct MyPlugin;
29//!
30//! impl MyPlugin {
31//!     #[native(name = "Greet")]
32//!     fn greet(&mut self, _amx: &Amx, name: &AmxString) -> AmxResult<bool> {
33//!         if name.starts_with("Admin") {
34//!             println!("[VIP] Welcome, {}!", &**name);
35//!         } else {
36//!             println!("Hello, {}!", &**name);
37//!         }
38//!         Ok(true)
39//!     }
40//! }
41//!
42//! // Short form — default constructor via Default::default().
43//! initialize_plugin!(
44//!     type: MyPlugin,
45//!     natives: [MyPlugin::greet],
46//! );
47//!
48//! // Full form when there is setup in the constructor (logger, tick, etc):
49//! // initialize_plugin!(
50//! //     natives: [MyPlugin::greet],
51//! //     {
52//! //         samp::plugin::enable_tick();
53//! //         return MyPlugin;
54//! //     }
55//! // );
56//! ```
57
58pub mod amx;
59pub mod events;
60#[doc(hidden)]
61pub mod interlayer;
62pub mod logger;
63#[cfg(not(feature = "samp-only"))]
64pub(crate) mod macros;
65pub mod plugin;
66pub(crate) mod runtime;
67
68pub use samp_codegen::{event, initialize_plugin, native};
69
70/// Version of the `rust-samp` (`samp`) crate the plugin was compiled
71/// against. Useful for diagnostic natives that report the SDK build
72/// back to the gamemode (e.g. `MyPlugin_GetSdkVersion()`), bug reports
73/// and runtime dashboards.
74#[must_use]
75pub fn version() -> &'static str {
76    env!("CARGO_PKG_VERSION")
77}
78
79// Re-export so the generated macro does not leak the `log` dep into the user's Cargo.toml.
80#[doc(hidden)]
81pub use log;
82
83/// Derive macro that generates an empty `impl SampPlugin for T {}` for structs
84/// that do not need to customize any trait method. For structs with logic in
85/// `on_load`/`on_tick`/etc, declare `impl SampPlugin for T { ... }`
86/// manually instead of using the derive.
87pub use samp_codegen::SampPlugin;
88pub use samp_sdk::exec_public;
89pub use samp_sdk::{args, cell, consts, error, exports, raw};
90
91#[cfg(feature = "debug")]
92pub use samp_sdk::debug;
93
94#[cfg(feature = "encoding")]
95pub use samp_sdk::encoding;
96
97#[cfg(not(feature = "samp-only"))]
98pub use samp_sdk::omp;
99
100pub mod prelude {
101    //! Most commonly used imports in plugins.
102    pub use crate::amx::{Amx, AmxExt};
103    pub use crate::cell::{AmxCell, AmxString, Buffer, CellConvert, Ref, UnsizedBuffer};
104    pub use crate::error::AmxResult;
105    pub use crate::events::EventReturn;
106    pub use crate::plugin::SampPlugin;
107}
108
109/// Installs the SDK logger with defaults derived from the caller's
110/// `Cargo.toml`. Writes to `logs/{CARGO_PKG_NAME}.log` with size-based
111/// rotation (50 MB × 5 archives) and forwards every line to the server's
112/// own log prefixed with `[CARGO_PKG_NAME]`.
113///
114/// Returns `Result<(), samp::logger::InstallError>` — the most common
115/// failures are "already installed" (a second call in the same process)
116/// and "I/O" (the log directory could not be created).
117///
118/// # Example
119/// ```rust,ignore
120/// fn on_load(&mut self) {
121///     let _ = samp::enable_logger!();
122///     log::info!("ready");
123/// }
124/// ```
125#[macro_export]
126macro_rules! enable_logger {
127    () => {
128        $crate::enable_logger_with!($crate::logger::LoggerConfig::new(env!("CARGO_PKG_NAME")))
129    };
130}
131
132/// Installs the SDK logger with an explicit [`LoggerConfig`].
133///
134/// The macro still seeds the banner metadata from the caller's
135/// `CARGO_PKG_*` values before delegating to [`logger::install`], so the
136/// startup banner reports the user's plugin even when every other field
137/// is overridden.
138///
139/// [`LoggerConfig`]: crate::logger::LoggerConfig
140/// [`logger::install`]: crate::logger::install
141#[macro_export]
142macro_rules! enable_logger_with {
143    ($cfg:expr) => {{
144        $crate::logger::__set_banner_metadata($crate::logger::BannerMetadata::new(
145            env!("CARGO_PKG_NAME"),
146            env!("CARGO_PKG_VERSION"),
147            env!("CARGO_PKG_AUTHORS"),
148            env!("CARGO_PKG_REPOSITORY"),
149        ));
150        $crate::logger::install($cfg)
151    }};
152}
153
154#[cfg(test)]
155mod tests {
156    #[test]
157    fn version_matches_cargo_pkg_version() {
158        assert_eq!(super::version(), env!("CARGO_PKG_VERSION"));
159        assert!(!super::version().is_empty());
160    }
161}