# AGENTS.md

This file provides guidance to AI agents (or developers) when working with code in this repository.

## Project Overview

**leveldb-rs-binding** is a comprehensive Rust interface for Google's LevelDB key-value storage library. It provides safe, idiomatic Rust APIs while maintaining full compatibility with the underlying C++ LevelDB implementation.

## Prerequisites

- Rust toolchain (stable)
- CMake (for building LevelDB/Snappy)
- C++ compiler (for building LevelDB/Snappy)
- Git (for managing submodules)

## Project Structure

```
.
├── Cargo.toml              # Main project configuration and dependencies
├── src/                    # Main source code
│   ├── lib.rs              # Library entry point and re-exports
│   ├── binding.rs          # FFI bindings to LevelDB C API
│   ├── deps/               # Build scripts for compiling dependencies
│   ├── extension/          # Rust extension modules (feature-gated)
│   └── database/           # Main database module with submodules
├── extension/              # C++ extensions for LevelDB
│   ├── include/            # C++ header files
│   ├── src/                # C++ source implementations
│   ├── tests/              # C++ source tests
│   └── CMakeLists.txt      # CMake build config for extensions
├── deps/                   # Git submodules for dependencies.
├── tests/                  # Integration tests
├── benchmarks/             # Benchmark framework ported from C++ implementation
├── example/                # Example usage of the library
├── AGENTS.md               # Introduction of the project to AI agents
└── README.md               # Project documentation
```

## Core Architecture

- **`src/binding.rs`**: Low-level FFI bindings to LevelDB C API.
- **`src/database/`**: High-level Rust API modules (kv, iterator, options, batch, snapshots, etc.)
- **`src/extension/`**: Rust extension modules providing safe wrappers for custom LevelDB functionality.
- **`extension/`**: C++ extensions that enhance LevelDB with custom features (logger, etc.).
- **`src/deps/build.rs`**: Build script that compiles third-party dependencies and extensions using CMake.
- **`tests/`**: Integration tests covering all functionality.
- **`benchmarks/`**: Performance benchmark suite.
- **`deps/`**: Git submodules for dependencies.

## Feature Flags

- `snappy`: Enables Snappy compression support (enabled by default)
- `zstd`: Enables Zstd compression support (enabled by default)
- `logger`: Enables custom logging functionality with Rust handlers
- `enable_lto`: Enables Link-Time Optimization for better runtime performance at the cost of longer compilation times

## Quick Reference

### Essential Commands

**Build Commands:**
- **Build project**: `cargo build`
- **Build release version**: `cargo build --release`
- **Build with LTO**: `cargo build --features enable_lto --release`
- **Build with extensions**: `cargo build --features logger` (or other extension features)
- **Clean build artifacts**: `cargo clean`
- **Check compilation**: `cargo check`

**Test Commands:**
- **Run all tests**: `cargo test`
- **Run tests with verbose output**: `cargo test --verbose`
- **Run tests with extensions**: `cargo test --features logger` (or other extension features)
- **List all available tests**: `cargo test -- --list`
- **Run specific test**: `cargo test --test tests test_name`

**Documentation Commands:**
- **Generate and open docs**: `cargo doc --no-deps --open`
- **Generate docs**: `cargo doc --no-deps`

**Git Submodule Commands:**
- **Initialize submodules**: `git submodule update --init --recursive`
- **Update submodules**: `git submodule update --remote --merge`

**Benchmark Commands:**
- **Run benchmarks**: `cargo run --release` (in benchmarks directory)

## Development Guidelines

### Adding New LevelDB API Bindings
When Google LevelDB adds new APIs:
1. Add FFI declarations to `src/binding.rs` following existing naming patterns
2. Create safe wrappers in appropriate `src/database/` modules
3. Implement proper error handling using `database::error::Error`
4. Add comprehensive tests covering success and error cases
5. Update documentation with API usage patterns

### Extension Development
The `extension/` directory houses all custom LevelDB extensions that require C++ implementation. This architecture allows adding functionality beyond the standard LevelDB API while maintaining safe Rust interfaces.

Create a `build` folder under `extension` to work with CMake of `extension`. This requires LevelDB lib installed, which should be found under folder `target`. Try to find it first, if not, just run `cargo build`.

Read @extension/README.md for more instructions.

#### Extension Architecture
- **C++ Layer** (`extension/`): Low-level implementations that integrate with LevelDB internals
- **Rust Layer** (`src/extension/`): Safe Rust wrappers and public APIs
- **Feature Gates**: Extensions are controlled by Cargo feature flags for conditional compilation

#### Adding New Extensions
1. **C++ Implementation**:
   - Add headers in `extension/include/`
   - Add implementations in `extension/src/`
   - Update `extension/CMakeLists.txt` with new build targets
   - Use `extern "C"` for functions called from Rust

2. **Rust Wrapper**:
   - Create module in `src/extension/`
   - Implement safe Rust API with proper error handling
   - Add `#[cfg(feature = "...")]` gates for conditional compilation
   - Export public APIs in `src/extension/mod.rs` and `src/lib.rs`

3. **FFI Bridge**:
   - Use `#[unsafe(no_mangle)]` for Rust functions called from C++
   - Implement proper pointer lifetime management
   - Follow opaque pointer pattern for complex objects

4. **Build Integration**:
   - Add build logic in `src/deps/extension.rs`
   - Update `src/deps/build.rs` to conditionally build extensions
   - Ensure proper linking order and dependencies

#### Example: Logger Extension
The logger extension demonstrates the standard pattern:
- C++: `extension/src/logger.cpp` implements LevelDB::Logger interface
- Rust: `src/extension/logger.rs` provides safe Logger wrapper
- FFI: Functions like `leveldb_rs_logline_process` bridge the two layers

### FFI Safety Requirements
- All C function calls must be wrapped in `unsafe` blocks with safety comments
- Validate all pointers before dereferencing
- Check return values and convert to appropriate Rust types
- Use `Option<NonNull<T>>` for nullable pointers
- Implement `Drop` for all types that allocate resources
- For extensions: Use `#[unsafe(no_mangle)]` for Rust functions exported to C++
- Maintain clear ownership boundaries between Rust and C++ code
- Document lifetime requirements for cross-language function calls

### Common Development Tasks
- **Project Structure Updates**: Update module declarations in `src/database/mod.rs` and ensure all public APIs are re-exported in `src/lib.rs`
- **Error Handling**: Use the unified `Error` type from `database/error.rs` and convert all C error codes to appropriate Rust error variants
- **Performance Considerations**: Performance for code in `src/` folder is top priority; performance for code in `tests/` folder is less important than simplicity

### Important Notes
- Dependencies are included as git submodules in `deps/`. Files under this folder cannot be changed permanently.
- Scripts under `src/deps` handle compilation of these third-party dependencies.
- Extension development requires C++17 compatible compiler and CMake for building C++ components.
- Extensions are conditionally compiled based on feature flags to avoid unnecessary dependencies.
- When working with extensions, pay special attention to memory safety across the Rust/C++ boundary.
