Please check the build logs for more information.
See Builds for ideas on how to fix a failed build, or Metadata for how to configure docs.rs builds.
If you believe this is docs.rs' fault, open an issue.
NOTICE! THIS IS THE FULL GUIDE WE HAVE ADDED POWERFUL FEATURES , PLEASE REPORT ISSUES AT https://github.com/3Rr0RHACK3R/frd-pu/issues , WE RECOMMEND IT! NOTE! WE HAVE MADE THIS FOR WINDOWS , WE DONT KNOW ABOUT TOHER OS'S , RELEASING FOR LINUX SOON!
FRD-PU: The Fast RAM Data-Processing Unit A professional-grade, high-performance, and zero-dependency library built from the ground up for extreme efficiency. This crate is designed to handle massive computational tasks and data streams with minimal resource consumption. It is ideal for creating hyper-fast applications without a monstrous hardware footprint.
Our core philosophy is simple: Do more with less. We achieve this through a unique blend of optimized algorithms and zero-copy data streaming, all built on a foundation that relies only on the Rust standard library. This empowers you to create dominant, high-performance applications that make bloated, resource-hogging software a thing of the past.
Core Features Absolute 0 Dependencies: We rely only on the Rust standard library, ensuring a tiny footprint and lightning-fast compilation.
Memory-First Design: The library's core is built to avoid unnecessary memory allocations, allowing you to process massive datasets with minimal memory impact.
Optimized Engines: We provide specialized APIs for different types of computation, ensuring the right tool for the job.
Modules & API Documentation This crate is composed of several powerful modules, each designed for a specific purpose.
bloom_filter A memory-efficient, probabilistic data structure for checking if an element is a member of a set. It is ideal for scenarios where memory is a constraint and a small rate of false positives is acceptable.
BloomFilter::new(capacity, false_positive_probability): Creates a new filter with a specified expected number of items and a desired false-positive rate.
BloomFilter::insert(&self, item): Inserts a hashable item into the filter.
BloomFilter::check(&self, item): Checks if an item may be in the set. Returns false if it is definitely not, and true if it is probably in the set.
btree A zero-dependency Binary Search Tree (BST) data structure. A BST is an efficient way to store and retrieve sorted data, providing logarithmic time complexity for search, insertion, and deletion operations on average.
BinarySearchTree::insert(&mut self, key, value): Inserts a key-value pair into the tree. Returns an error if the key already exists.
BinarySearchTree::search(&self, key): Searches for a key in the tree and returns a reference to its value, if found.
cache A high-performance, memory-aware, Least Recently Used (LRU) cache. This cache uses a combination of a hash map for fast lookups and a linked list for efficient access-order tracking, providing O(1) average time complexity for most operations. The cache's memory usage is managed by a max_size in bytes.
LruCache::new(max_size): Creates a new cache with a maximum size in bytes.
LruCache::insert(&mut self, key, value): Inserts a key-value pair into the cache. Returns an error if the item exceeds the cache's maximum size.
LruCache::get(&mut self, key): Retrieves a value by key, marking it as the most recently used.
LruCache::remove(&mut self, key): Removes a key-value pair from the cache.
concurrent A thread-safe list that allows for safe concurrent access from multiple threads. It wraps a standard Vec in a Mutex to provide exclusive access and uses Arc for shared ownership between threads.
ConcurrentList::new(): Creates a new, empty, thread-safe list.
ConcurrentList::push(&self, item): Appends an item to the end of the list.
ConcurrentList::pop(&self): Removes and returns the last item in the list.
ConcurrentList::get(&self, index): Returns a reference to the item at the specified index.
cpu_task A professional wrapper for a single-threaded CPU task and its input. This module provides a clean and encapsulated way to define and execute a sequential computational task, ensuring robust error handling.
new_cpu_task(input, task): Creates a new single-threaded task with a defined input and a closure for the work to be done.
CpuTask::execute(): Executes the defined CPU task and returns the result or an error.
data_stream An efficient API for handling large files and network streams in a chunked manner. This module abstracts over different data sources, allowing for low-memory processing of vast datasets.
new_file_stream(path, chunk_size): A convenience function to create a data stream from a file path.
new_network_stream(stream, chunk_size): A convenience function to create a data stream from a network stream.
DataStream::for_each_chunk(&mut self, processor): Reads the stream in chunks and processes each chunk with a provided closure.
hasher A zero-dependency, high-performance hashing engine. This module provides functions for hashing byte slices, files, and data streams using a fast, non-cryptographic DefaultHasher.
hash_bytes(data): Hashes a byte slice into a 64-bit integer.
hash_file(path): Hashes the contents of a file.
hash_stream(reader): Hashes data from any type that implements the Read trait.
parallel A powerful module for executing data-parallel tasks across multiple CPU cores. It chunks input data and processes each chunk on a separate thread, ensuring thread safety and graceful panic handling.
execute_parallel(input, workers, task): Executes a data-parallel task, distributing the work across a specified number of threads.
quicksort An insanely fast, zero-dependency, in-place sorting algorithm. This implementation of QuickSort sorts a mutable slice in place and is generic over any type that can be compared.
quicksort(slice): Sorts a mutable slice of data in place using the QuickSort algorithm.
trie A memory-efficient, zero-dependency Trie (Prefix Tree) data structure. A Trie is ideal for efficient retrieval of keys from a dataset of strings, making it perfect for applications like autocompletion and spell-checking.
Trie::insert(&mut self, word): Inserts a word into the Trie.
Trie::search(&self, word): Checks if a complete word exists in the Trie.
Trie::starts_with(&self, prefix): Checks if a prefix exists in the Trie.
Getting Started To use this crate in your project, add it to your Cargo.toml.
[dependencies] frd-pu = { path = "/path/to/your/frd-pu" }
Contributing We welcome contributions from the community. Please read the CONTRIBUTING.md for guidelines on how to submit pull requests, report bugs, and propose new features.
License This project is licensed under the MIT License.
---------------------------- Bloomfilter and other features ---------------------------------------------------------------
BloomFilter The BloomFilter module introduces a space-efficient, probabilistic data structure used to test whether an element is a member of a set. It offers a significant memory advantage over traditional hash sets but comes with the trade-off of a small chance of false positives. It guarantees no false negatives.
Key Features Memory Efficiency: Drastically reduces memory footprint for set membership tests.
Fast Operations: Provides extremely fast add and check operations.
Zero Dependencies: Relies only on the Rust standard library.
Example Usage The following example demonstrates how to create a Bloom filter and perform basic operations.
use frd_pu::bloom_filter::{BloomFilter, BloomFilterError};
fn main() -> Result<(), BloomFilterError> { // Create a new Bloom filter with a capacity of 1000 items and a 1% false positive probability. let mut filter = BloomFilter::new(1000, 0.01)?;
// Add items to the filter.
filter.add(&"professional");
filter.add(&"project");
filter.add(&"efficiency");
// Check for membership.
assert_eq!(filter.check(&"project"), true);
assert_eq!(filter.check(&"quality"), false); // May be true in rare cases due to false positives.
Ok(())
}
BinarySearchTree The BinarySearchTree module provides a professional-grade, in-memory data structure for storing and retrieving key-value pairs. It is designed for operations that require fast lookups, insertions, and deletions, maintaining a sorted structure for efficient searching.
Key Features Logarithmic Complexity: Provides O( logn) average time complexity for core operations.
Zero Dependencies: Implemented with only the Rust standard library.
Generic: Supports any key-value pair that implements the Ord trait for comparison.
Example Usage This example shows how to insert and search for elements within the Binary Search Tree.
use frd_pu::btree::{BinarySearchTree, BinarySearchTreeError};
fn main() -> Result<(), BinarySearchTreeError> { // Create a new Binary Search Tree. let mut bst = BinarySearchTree::new();
// Insert key-value pairs.
bst.insert(5, "Task B")?;
bst.insert(3, "Task A")?;
bst.insert(8, "Task C")?;
// Search for a value.
assert_eq!(bst.search(&3), Some(&"Task A"));
assert_eq!(bst.search(&10), None);
Ok(())
}
----------------------------- memory_pool and Compression modules ---------------------------------------------------------
FRD-PU Memory Pool and Compression Documentation
The Fast RAM Data-Processing Unit
Source Code: https://github.com/3Rr0RHACK3R/frd-pu
Table of Contents
- Introduction
- Memory Pool Module
- Compression Module
- Integration Guide
- Performance Best Practices
- Advanced Usage Patterns
- Error Handling
- Complete Examples
Introduction
The FRD-PU library provides two powerful modules designed for extreme performance and minimal resource consumption: the Memory Pool module for zero-allocation memory management and the Compression module for high-speed LZ77-style data compression. Both modules follow the core philosophy of "Do more with less" by eliminating external dependencies and optimizing for speed and memory efficiency.
Core Benefits
The Memory Pool module eliminates runtime allocation overhead by pre-allocating memory blocks, making it perfect for high-frequency operations, real-time systems, and applications requiring predictable memory patterns. The Compression module provides fast LZ77-style compression with configurable parameters, enabling efficient data storage and transmission without external dependencies.
Zero Dependencies Philosophy
Both modules rely exclusively on the Rust standard library, ensuring minimal compile times, small binary sizes, and maximum compatibility. This approach eliminates version conflicts, reduces attack surface, and provides predictable behavior across different environments.
Memory Pool Module
The Memory Pool module provides high-performance, zero-allocation memory management through pre-allocated pools. This eliminates malloc/free overhead and provides predictable memory usage patterns essential for real-time applications.
Core Concepts
Memory pools work by allocating large blocks of memory upfront and dividing them into fixed-size chunks. When your application needs memory, it receives a pre-allocated chunk instantly. When finished, the memory returns to the pool for reuse, avoiding expensive system calls.
Basic Usage
use ;
// Create a pool with 1024-byte blocks, 100 blocks total
let pool = new?;
// Allocate memory from the pool
let mut memory = pool.allocate?;
// Use the memory
let data = b"Hello, high-performance world!";
memory.write_bytes?;
// Memory automatically returns to pool when dropped
Pre-configured Pool Types
The module provides several pre-configured pools optimized for common use cases:
use ;
// Small allocations: 64 bytes, 1000 blocks
let small_pool = create_small_pool?;
// Medium allocations: 1KB, 500 blocks
let medium_pool = create_medium_pool?;
// Large allocations: 64KB, 100 blocks
let large_pool = create_large_pool?;
PooledMemory Operations
The PooledMemory type provides safe access to pool-allocated memory with automatic cleanup:
let pool = new?;
let mut memory = pool.allocate?;
// Zero out the memory block
memory.zero;
// Write data safely
let input_data = b"Critical real-time data processing";
memory.write_bytes?;
// Read data back
let output_data = memory.read_bytes?;
assert_eq!;
// Get direct access to memory
let raw_slice = memory.as_mut_slice;
raw_slice = 0xFF;
// Get memory size
println!;
Pool Statistics and Monitoring
Monitor pool usage and performance with built-in statistics:
let pool = new?;
// Allocate some memory
let _mem1 = pool.allocate?;
let _mem2 = pool.allocate?;
let _mem3 = pool.allocate?;
// Check pool statistics
let stats = pool.stats;
println!;
println!;
println!;
println!;
println!;
// Check availability before allocating
if pool.has_available
// Reset statistics while keeping memory allocated
pool.reset_stats;
Object Pool for Complex Types
For reusing complex objects, use the ObjectPool:
use HashMap;
// Create a pool for HashMap objects
let pool = new;
// Get an object from the pool
let mut map_obj = pool.get;
map_obj.insert;
map_obj.insert;
// Object is automatically reset and returned to pool when dropped
drop;
// Next allocation gets a clean object
let clean_map = pool.get;
assert_eq!;
Pool Manager for Multiple Sizes
The PoolManager automatically selects the best pool for each allocation size:
let manager = new?;
// Allocate different sizes - manager picks the best pool
let small_mem = manager.allocate?; // Uses 32-byte pool
let medium_mem = manager.allocate?; // Uses 2KB pool
let large_mem = manager.allocate?; // Uses 32KB pool
// Check availability for specific size
if manager.has_available
// Get statistics for all pools
let all_stats = manager.total_stats;
for in all_stats.iter.enumerate
Memory Pool Error Types
The module defines specific error types for different failure conditions:
use MemoryPoolError;
match pool.allocate
Thread Safety
All pool types are thread-safe and can be shared across threads:
use Arc;
use thread;
let pool = new;
let mut handles = vec!;
for i in 0..4
for handle in handles
println!;
Compression Module
The Compression module provides high-performance LZ77-style compression with zero external dependencies. It features configurable sliding window compression optimized for both speed and compression ratio.
Core Concepts
The compression engine uses LZ77 algorithm with a sliding window approach. It identifies repeated sequences in the data and replaces them with references to previous occurrences, achieving excellent compression ratios on repetitive data while maintaining fast compression and decompression speeds.
Basic Compression
use ;
// Compress binary data
let original_data = b"Hello, World! Hello, World! This is a test of compression.";
let compressed = compress_data?;
let decompressed = decompress_data?;
assert_eq!;
println!;
println!;
Text Compression Convenience Functions
For text data, use the specialized text compression functions:
use ;
let text = "This is a long text document with repeated phrases. \
This is a long text document with repeated phrases. \
Compression works well on repetitive content.";
let compressed = compress_text?;
let decompressed_text = decompress_to_text?;
assert_eq!;
Advanced Compression Engine
For fine-grained control, use the CompressionEngine directly:
use CompressionEngine;
// Create engine with default settings (32KB window)
let engine = new;
// Create engine with custom window size
let custom_engine = with_window_size?;
let data = b"Repeated data patterns compress very well when using LZ77 compression algorithms.";
let compressed = engine.compress?;
let decompressed = engine.decompress?;
assert_eq!;
Compression Statistics
Analyze compression performance with detailed statistics:
use ;
let data = b"This is sample data with repeated patterns. \
This is sample data with repeated patterns. \
This is sample data with repeated patterns.";
// Get detailed compression statistics
let stats = get_compression_stats?;
println!;
// Estimate compression ratio before compressing
let engine = new;
let estimated_ratio = engine.estimate_compression_ratio?;
println!;
Compression Error Handling
The module provides specific error types for different compression failures:
use CompressionError;
match compress_data
Window Size Configuration
Adjust the sliding window size to optimize for your specific use case:
// Small window for limited memory environments
let small_engine = with_window_size?;
// Large window for better compression on large datasets
let large_engine = with_window_size?;
let test_data = generate_test_data; // Your data generation function
// Compare compression ratios
let small_compressed = small_engine.compress?;
let large_compressed = large_engine.compress?;
println!;
println!;
Streaming Compression for Large Files
For processing large files or data streams, combine compression with the data_stream module:
use ;
let engine = new;
// Read file in chunks and compress
let mut file_stream = new_file_stream?;
let mut compressed_chunks = Vec new;
while let Some = file_stream.read_chunk?
// Later, decompress all chunks
let mut decompressed_data = Vec new;
for compressed_chunk in compressed_chunks
Integration Guide
Adding to Your Project
Add FRD-PU to your Cargo.toml:
[]
= { = "https://github.com/3Rr0RHACK3R/frd-pu" }
Selective Module Import
Import only the modules you need:
// For memory pool functionality only
use ;
// For compression functionality only
use ;
// For both modules
use ;
Integration with Existing Code
Replace standard allocations with pool allocations:
// Before: Standard allocation
let mut buffer = vec!;
process_data;
// After: Pool allocation
let pool = create_medium_pool?;
let mut memory = pool.allocate?;
let buffer = memory.as_mut_slice;
process_data;
Replace standard compression libraries:
// Before: External compression library
// extern crate some_compression_lib;
// let compressed = some_compression_lib::compress(data)?;
// After: FRD-PU compression
let compressed = compress_data?;
Configuration Patterns
Create application-specific pool configurations:
Performance Best Practices
Memory Pool Optimization
Choose appropriate pool sizes based on your allocation patterns:
// Analyze your allocation patterns first
let = analyze_allocations;
// Size pools appropriately
let optimal_block_size = & !63; // Round up to 64-byte boundary
let pool = new?;
Pre-allocate pools during application startup:
Compression Optimization
Choose window sizes based on your data characteristics:
// Small window for low memory usage and faster compression
let fast_engine = with_window_size?;
// Large window for better compression ratio on large files
let efficient_engine = with_window_size?;
// Benchmark different window sizes
let test_data = load_representative_data;
let mut results = Vec new;
for window_size in
// Choose optimal window size based on results
Combined Optimization Strategies
Combine memory pools with compression for maximum performance:
Advanced Usage Patterns
Real-time Data Processing Pipeline
Build high-performance pipelines combining both modules:
use mpsc;
use thread;
use Arc;
Custom Pool Implementations
Extend the memory pool system for specialized use cases:
Adaptive Compression
Implement adaptive compression that chooses parameters based on data characteristics:
Memory-Mapped File Processing
Combine memory pools with memory-mapped files for processing large datasets:
use File;
use ;
Error Handling
Comprehensive Error Management
Both modules provide detailed error types for different failure conditions:
use ;
Graceful Degradation Patterns
Implement systems that degrade gracefully under resource pressure:
Resource Monitoring and Recovery
Implement monitoring systems to track resource usage and trigger recovery:
use ;
use Arc;
Complete Examples
High-Performance Web Server Buffer Pool
Complete example of using memory pools in a web server context:
use Arc;
use thread;
use Duration;
// Helper struct for HTTP request representation
// Usage example
Data Processing Pipeline with Compression
Complete example of a data processing pipeline using both modules:
use mpsc;
use thread;
use Instant;
// Helper trait for cloning pools (simplified for example)
// Usage example
Real-Time Game Engine Memory Management
Complete example for game engine-style memory management:
use HashMap;
use ;
// Game entity structure
// Memory statistics structure
// Game system that uses the memory manager
// Usage example
This comprehensive documentation provides a complete guide to using the FRD-PU Memory Pool and Compression modules. The examples demonstrate real-world usage patterns for high-performance applications, from web servers to game engines. The zero-dependency philosophy ensures maximum compatibility and minimal overhead, while the detailed error handling patterns provide robust applications that can gracefully handle resource pressure and failure conditions.
The memory pool module excels in scenarios requiring predictable memory allocation patterns, while the compression module provides efficient data storage and transmission without external dependencies. Together, they form a powerful foundation for building high-performance applications that truly embody the "Do more with less" philosophy.
We Would Love You contributing on Our github here
https://github.com/3Rr0RHACK3R/frd-pu
Join Us On Our Journey to Make a Great Library!
-------------------------- buffer pool module -----------------------------
Buffer Pool Module
Overview
The Buffer Pool module provides a high-performance, zero-dependency buffer pool implementation designed for extreme efficiency in data processing and streaming applications. This module eliminates constant allocation and deallocation cycles by recycling buffers, making it essential for high-throughput I/O operations and memory-sensitive applications.
The buffer pool system maintains multiple pools for different buffer sizes and automatically manages memory lifecycle, providing significant performance improvements for applications that frequently allocate and deallocate byte buffers.
Core Philosophy
Built on the same "do more with less" philosophy as the rest of FRD-PU, the Buffer Pool module achieves maximum efficiency through:
- Zero-allocation buffer reuse that eliminates garbage collection pressure
- Thread-safe operations that scale across multiple cores
- Automatic memory management with configurable pool sizes
- Fast O(1) buffer acquisition and release operations
- Memory-efficient pool shrinking when buffers are no longer needed
Key Features
Zero-Allocation Reuse: Buffers are recycled instead of being constantly allocated and deallocated, eliminating the performance overhead of memory management in tight loops.
Multiple Pool Sizes: The system maintains separate pools for different buffer sizes, ensuring optimal memory utilization and preventing fragmentation.
Thread-Safe Operations: All buffer pool operations are thread-safe using efficient locking mechanisms, making them suitable for concurrent applications.
Automatic Growth and Shrinking: Pools can grow automatically when under pressure and shrink when buffers are no longer needed, balancing performance with memory efficiency.
Global Convenience Pools: Pre-configured pools for common buffer sizes (1KB, 64KB, 1MB) provide instant access without manual pool management.
Comprehensive Statistics: Built-in monitoring capabilities track buffer usage, allocation patterns, and performance metrics for production optimization.
Architecture
The buffer pool system consists of three main components:
BufferPool: The main pool structure that manages collections of buffers for different sizes. Each pool maintains its own statistics and configuration.
PooledBuffer: A smart buffer wrapper that automatically returns buffers to their originating pool when dropped. This ensures automatic memory management without manual intervention.
Global Pools: Thread-safe singleton pools for common buffer sizes, providing convenient access without explicit pool creation.
Basic Usage
Creating Custom Pools
use BufferPool;
// Create a pool with default settings (64 buffers per size)
let pool = new;
// Create a pool with custom maximum buffers per size
let large_pool = with_max_buffers;
// Get a buffer from the pool
let mut buffer = pool.get_buffer?;
// Use the buffer for I/O operations
buffer.as_mut_slice = 42;
let data = buffer.as_slice;
// Buffer automatically returns to pool when dropped
Using Global Convenience Pools
use ;
// Get pre-sized buffers from global pools
let small = get_small_buffer?; // 1KB buffer
let medium = get_medium_buffer?; // 64KB buffer
let large = get_large_buffer?; // 1MB buffer
// Get automatically sized buffer
let buffer = get_buffer?; // Uses appropriate pool
Buffer Operations
// Get a buffer and perform operations
let mut buffer = pool.get_buffer?;
// Access as mutable slice
let slice = buffer.as_mut_slice;
slice = 100;
// Resize buffer contents
buffer.resize;
// Clear buffer contents
buffer.clear;
// Check buffer properties
println!;
println!;
println!;
Advanced Usage
Pool Statistics and Monitoring
// Get detailed pool statistics
let stats = pool.stats?;
println!;
println!;
println!;
println!;
println!;
println!;
// Monitor global pools
let = get_global_stats?;
Memory Management
// Clear all buffers from pool (forces deallocation)
pool.clear?;
// Shrink pool to remove excess buffers
pool.shrink?;
// Clear all global pools
clear_global_pools?;
Integration with Existing Code
The buffer pool integrates seamlessly with standard Rust I/O operations:
use File;
use Read;
// Use pooled buffer for file I/O
let mut buffer = get_medium_buffer?;
let mut file = open?;
// Read directly into pooled buffer
let bytes_read = file.read?;
buffer.resize;
// Process the data
process_data;
// Buffer automatically returns to pool when dropped
Performance Considerations
Buffer Size Selection: Choose buffer sizes that match your I/O patterns. Larger buffers reduce system call overhead but consume more memory.
Pool Size Configuration: Set maximum pool sizes based on expected concurrency. Higher limits provide better performance under load but consume more memory.
Buffer Reuse Patterns: Buffers work best when allocation and deallocation happen in similar patterns. Highly variable buffer sizes may reduce reuse effectiveness.
Thread Safety Overhead: While pools are thread-safe, high contention scenarios may benefit from thread-local pools or buffer pre-allocation strategies.
Error Handling
The buffer pool system uses comprehensive error handling for robust operation:
use ;
match pool.get_buffer
Integration with Other Modules
The buffer pool module is designed to work seamlessly with other FRD-PU components:
Data Stream Module: Use pooled buffers for efficient file and network streaming operations.
Memory Pool Module: Combine with memory pools for comprehensive memory management strategies.
Compression Module: Reuse compression and decompression buffers to eliminate allocation overhead.
Cache Module: Use pooled buffers for cached data storage and retrieval operations.
Concurrent Module: Leverage thread-safe pools in multi-threaded data processing pipelines.
Thread Safety
All buffer pool operations are fully thread-safe and can be used concurrently across multiple threads without additional synchronization. The implementation uses efficient locking mechanisms that minimize contention while ensuring data integrity.
Global pools are implemented as thread-safe singletons and can be accessed from any thread without explicit synchronization. This makes them ideal for use in multi-threaded applications and async runtimes.
Memory Efficiency
The buffer pool system is designed for optimal memory efficiency:
Buffers are only allocated when needed and reused whenever possible. Pool sizes can be configured to balance memory usage with performance requirements. Automatic shrinking prevents memory leaks in long-running applications.
The system tracks comprehensive statistics to help optimize memory usage patterns in production environments. Buffer capacity is preserved during reuse to minimize allocation overhead while ensuring buffers meet size requirements.
Production Considerations
When deploying buffer pools in production environments, consider these factors:
Monitoring: Use the built-in statistics to monitor buffer usage patterns, allocation rates, and pool efficiency.
Configuration: Tune pool sizes based on actual usage patterns and available memory. Start with conservative settings and increase based on monitoring data.
Error Handling: Implement proper error handling for all buffer pool operations, particularly in high-availability systems.
Memory Pressure: Monitor system memory usage and implement pool shrinking strategies during low-usage periods.
Performance Testing: Benchmark buffer pool performance under expected load patterns to validate configuration settings.
The buffer pool module represents a critical component for building high-performance, memory-efficient applications that can scale to handle massive data processing workloads while maintaining minimal resource consumption.
Download the Library to see the new features
----------------- universal processor ---------------------
Universal Processor Module Documentation
Overview
The Universal Processor is a revolutionary adaptive processing engine that maintains the same efficiency whether processing 1 byte or 1 terabyte of data. Unlike traditional processing systems that require different algorithms for different data sizes, the Universal Processor implements "fractal processing" - a single algorithm that scales fractally and self-optimizes based on data patterns it discovers in real-time.
Core Philosophy
The Universal Processor embodies the FRD-PU principle of "Do more with less" by providing:
- Pattern Recognition: Automatically detects data patterns and optimizes strategy
- Adaptive Scaling: Seamlessly switches between processing modes based on data size
- Memory Pressure Adaptation: Automatically adapts to available system resources
- CPU Architecture Detection: Leverages SIMD, multiple cores, or optimizes for single-threaded
- Predictive Resource Allocation: Pre-allocates resources based on pattern analysis
- Zero-Copy Transformations: Processes data in-place whenever possible
Quick Start Guide
Basic Usage
use ;
// Method 1: Using convenience function (recommended for beginners)
let mut data = vec!;
process_adaptive?;
// data is now [2, 4, 6, 8, 10]
// Method 2: Using processor instance
let processor = new;
let mut data = vec!;
processor.execute?;
Pattern-Specific Processing
use ;
// For data transformation operations
let transform_proc = create_transform_processor;
let mut numbers = vec!;
transform_proc.execute?;
// For aggregation operations (sum, count, average)
let agg_proc = create_aggregate_processor;
// Processing logic automatically optimized for aggregation patterns
Core Components
UniversalProcessor
The main processing engine that adapts to any computational task.
Creation Methods:
// Default processor with real-time optimization
let processor = new;
// Customized processor
let processor = new
.with_pattern
.with_scaling
.with_optimization;
Key Methods:
execute: Process mutable data with automatic optimization
processor.execute?;
execute_custom: Process immutable data with custom return type
let result = processor.execute_custom?;
execute_batch: Process multiple data batches efficiently
let mut batch1 = vec!;
let mut batch2 = vec!;
let batches = vec!;
processor.execute_batch?;
analyze_pattern: Analyze data characteristics for optimization
let data_bytes = vec!;
let pattern = processor.analyze_pattern?;
println!;
println!;
ProcessingPattern
Defines the type of operation being performed for optimal strategy selection.
Variants:
- Transform: Sequential transformation of data elements
- Aggregate: Operations like sum, count, average, min, max
- Filter: Filtering operations that remove or modify elements
- Sort: Sorting and ordering operations
- Search: Search and lookup operations
- Compress: Compression and decompression operations
- Mathematical: Mathematical computations and algorithms
- Custom(u64): User-defined pattern with custom identifier
Usage:
let processor = new
.with_pattern;
// Processor now optimizes for mathematical operations
let mut values = vec!;
processor.execute?;
ScalingBehavior
Controls how the processor scales with data size.
Variants:
- Linear: Performance scales linearly with data size
- Fractal: Maintains efficiency curves at all scales (recommended)
- Adaptive: Chooses best strategy based on data characteristics
- Batch: Optimized for batch processing of similar-sized chunks
Usage:
// For maximum efficiency at any scale
let processor = new
.with_scaling;
// For automatic strategy selection
let processor = new
.with_scaling;
OptimizationMode
Defines performance optimization priorities.
Variants:
- Latency: Minimize response time for individual operations
- Throughput: Maximize total data processing rate
- Memory: Minimize memory usage during processing
- RealTime: Balance all factors for real-time applications
- Custom: Specify custom weight priorities
Usage:
// Optimize for maximum throughput
let processor = new
.with_optimization;
// Custom optimization weights (latency: 30%, throughput: 50%, memory: 20%)
let processor = new
.with_optimization;
Advanced Usage
Pattern Analysis and Caching
The Universal Processor automatically analyzes data patterns and caches optimization strategies:
let processor = new;
// First analysis discovers pattern and caches optimization
let data1 = vec!; // Low entropy, high repetition
let pattern = processor.analyze_pattern?;
println!;
println!;
println!;
// Similar data will reuse cached optimization strategy
let data2 = vec!;
processor.analyze_pattern?; // Uses cached pattern
Monitoring Performance
Track processing statistics for performance optimization:
let processor = new;
// Perform multiple operations
processor.execute?;
processor.execute?;
// Check performance statistics
let stats = processor.stats?;
println!;
println!;
println!;
println!;
// Clear statistics for fresh monitoring
processor.clear_stats?;
Dynamic Context Adaptation
The processor adapts to changing system conditions:
let mut processor = new;
// Check current system context
let context = processor.context;
println!;
println!;
println!;
// Update context if system conditions change
processor.update_context;
Batch Processing for Multiple Datasets
Efficiently process multiple related datasets:
let processor = new
.with_scaling;
// Prepare multiple data batches
let mut dataset1 = vec!;
let mut dataset2 = vec!;
let mut dataset3 = vec!;
let mut batches = vec!;
// Process all batches with shared optimization
processor.execute_batch?;
Convenience Functions
Specialized Processors
Pre-configured processors for common use cases:
Transform Processor: Optimized for data transformation
use create_transform_processor;
let processor = create_transform_processor;
let mut data = vec!;
processor.execute?;
// Better approach for string transformation
let data = vec!;
let result = processor.execute_custom?;
Aggregate Processor: Optimized for aggregation operations
use create_aggregate_processor;
let processor = create_aggregate_processor;
let data = vec!;
let sum = processor.execute_custom?;
let average = processor.execute_custom?;
Filter Processor: Optimized for filtering operations
use create_filter_processor;
let processor = create_filter_processor;
let mut data = vec!;
// Mark even numbers for removal (set to 0)
processor.execute?;
// Filter out zeros
data.retain;
// data is now [1, 3, 5, 7, 9]
Math Processor: Optimized for mathematical operations
use create_math_processor;
let processor = create_math_processor;
let mut data = vec!;
// Calculate square roots
processor.execute?;
// data is now [1.0, 2.0, 3.0, 4.0, 5.0]
// Complex mathematical operation
let mut complex_data = vec!;
processor.execute?;
Global Processing Functions
process_adaptive: Automatic pattern detection and optimization
use process_adaptive;
let mut data = vec!;
process_adaptive?;
// Automatically chooses best processing strategy
process_fractal: Maximum efficiency fractal processing
use process_fractal;
let mut large_data: = .collect;
process_fractal?;
// Maintains efficiency even for very large datasets
Performance Optimization Patterns
Small Data (< 1KB)
For small datasets, the processor automatically uses sequential processing:
let processor = new
.with_optimization;
let mut small_data = vec!;
processor.execute?;
// Uses optimized sequential processing
Medium Data (1KB - 1MB)
Medium datasets benefit from parallel processing:
let processor = new
.with_optimization;
let mut medium_data: = .collect;
processor.execute?;
// Automatically uses parallel processing
Large Data (> 1MB)
Large datasets use fractal processing for maximum efficiency:
let processor = new
.with_scaling
.with_optimization;
let mut large_data: = .map.collect;
processor.execute?;
// Uses fractal processing to maintain efficiency
Memory-Constrained Environments
For limited memory situations:
let processor = new
.with_optimization
.with_scaling;
// Process in streaming chunks to minimize memory usage
let mut huge_data: = .collect;
processor.execute?;
// Automatically uses streaming processing
Error Handling
The Universal Processor uses comprehensive error handling:
use ;
let processor = new;
match processor.execute
Real-World Examples
Image Processing
use create_transform_processor;
// Simulate RGB pixel data
let processor = create_transform_processor;
let mut image_data = vec!;
// Apply brightness adjustment
processor.execute?;
// Automatically uses optimal processing strategy for image size
Financial Data Analysis
use create_aggregate_processor;
let processor = create_aggregate_processor;
let stock_data = vec!;
// Calculate moving average
let moving_avg = processor.execute_custom?;
Scientific Computing
use create_math_processor;
let processor = create_math_processor;
// Simulate 3D coordinates
let mut points = vec!;
// Normalize all vectors
processor.execute?;
// Uses fractal processing for maximum efficiency
Text Processing
use create_filter_processor;
let processor = create_filter_processor;
let text_data = vec!;
// Filter and transform words
let filtered_words = processor.execute_custom?;
// Result: ["QUICK", "BROWN", "JUMPS", "OVER", "LAZY"]
IoT Sensor Data
use process_adaptive;
let mut sensor_data = vec!;
// Apply calibration corrections
process_adaptive?;
Performance Tips
Choosing the Right Pattern
- Use
ProcessingPattern::Transform
for element-by-element modifications - Use
ProcessingPattern::Aggregate
for reductions and summations - Use
ProcessingPattern::Filter
for conditional processing - Use
ProcessingPattern::Mathematical
for complex calculations
Optimization Mode Selection
OptimizationMode::Latency
for real-time applicationsOptimizationMode::Throughput
for batch processingOptimizationMode::Memory
for resource-constrained environmentsOptimizationMode::RealTime
for balanced performance
Scaling Behavior Guidelines
ScalingBehavior::Fractal
for maximum efficiency across all data sizesScalingBehavior::Adaptive
when data size varies significantlyScalingBehavior::Linear
for predictable, uniform processingScalingBehavior::Batch
for processing multiple similar datasets
Memory Management
- The processor automatically manages memory allocation
- Pattern analysis caches optimization strategies to reduce overhead
- Use
clear_stats()
periodically to prevent memory growth in long-running applications - Consider
OptimizationMode::Memory
for large datasets in constrained environments
Integration with FRD-PU Ecosystem
The Universal Processor integrates seamlessly with other FRD-PU modules:
use ;
// Combined processing pipeline
let processor = create_transform_processor;
let mut cache = new;
let mut bloom_filter = new?;
let mut data = vec!;
// Process data
processor.execute?;
// Cache results
for &value in &data
// Check membership
for &value in &data
// Compress processed data
let data_bytes: = data.iter
.flat_map
.collect;
let compressed = compress_data?;
Repository
For the complete source code, examples, and contribution guidelines, visit the FRD-PU repository: https://github.com/3Rr0RHACK3R/frd-pu
The Universal Processor module represents the pinnacle of adaptive processing technology, providing unmatched efficiency and scalability while maintaining the FRD-PU philosophy of zero dependencies and minimal resource consumption.
------------------- TCP Server Module ----------------------
tcp_server Module DocumentationOverviewThe tcp_server module provides a production-ready, high-performance, and cross-platform TCP server. It is built with the core FRD-PU philosophy of zero dependencies and maximum efficiency.Key Features:Cross-Platform: Works seamlessly on Windows, Linux, and macOS.Non-blocking Architecture: Uses a non-blocking, single-threaded event loop to handle massive concurrency without the overhead of managing multiple threads for connections.Advanced Connection Management: Supports TCP keep-alive and provides hooks for graceful connection shutdown.Built-in DoS Protection: Includes a configurable rate limiter for each connection.Comprehensive Statistics: Offers detailed, real-time metrics for monitoring server health and performance.Full IPv4 & IPv6 Support.Quick StartThe easiest way to get started is by using one of the convenience functions. This example creates a simple echo server that listens on 127.0.0.1:8080.use frd_pu::tcp_server::{new_echo_server, TcpServerError};
fn main() -> Result<(), TcpServerError> { let mut server = new_echo_server("127.0.0.1:8080")?; println!("Echo server listening on 127.0.0.1:8080"); // This is a blocking call that runs the server's event loop. server.serve() } ConnectionHandler TraitTo implement custom logic, you must create a struct that implements the ConnectionHandler trait. This trait is the core of your server's application logic.pub trait ConnectionHandler: Send + Sync + 'static { // Required method to process incoming data. fn handle_data(&self, data: &[u8], addr: SocketAddr) -> Option<Vec>;
// Optional lifecycle hooks.
fn on_connect(&self, addr: SocketAddr) {}
fn on_disconnect(&self, addr: SocketAddr) {}
fn on_server_start(&self) {}
fn on_server_shutdown(&self) {}
// Health check for monitoring.
fn health_check(&self) -> bool { true }
} Example: Custom HandlerHere is an example of a simple handler that processes text-based commands.use frd_pu::tcp_server::{ConnectionHandler, new_tcp_server, TcpServerError}; use std::net::SocketAddr;
// 1. Define your handler struct. struct CommandHandler;
// 2. Implement the ConnectionHandler trait. impl ConnectionHandler for CommandHandler { fn handle_data(&self, data: &[u8], _addr: SocketAddr) -> Option<Vec> { let command = String::from_utf8_lossy(data).trim().to_lowercase();
let response = match command.as_str() {
"ping" => "pong",
"time" => "It's time to code!",
_ => "Unknown command",
};
// Return the response to be sent to the client.
// The response must be converted to bytes.
Some(response.as_bytes().to_vec())
}
fn on_connect(&self, addr: SocketAddr) {
println!("New client connected: {}", addr);
}
fn on_disconnect(&self, addr: SocketAddr) {
println!("Client disconnected: {}", addr);
}
}
fn main() -> Result<(), TcpServerError> { // 3. Create a server with an instance of your handler. let handler = CommandHandler; let mut server = new_tcp_server("127.0.0.1:9001", handler)?; println!("Command server listening on 127.0.0.1:9001"); server.serve() } Server ConfigurationThe server can be extensively customized using the ServerConfig struct. You can create a server with a custom configuration using the new_tcp_server_with_config function.ServerConfig Struct#[derive(Debug, Clone)] pub struct ServerConfig { pub max_connections: usize, // Default: 10,000 pub buffer_size: usize, // Default: 64 KB pub timeout: Duration, // Default: 300 seconds (5 minutes) pub rate_limit: usize, // Default: 1000 requests/sec pub rate_limit_window: Duration, // Default: 1 second pub max_request_size: usize, // Default: 1 MB pub enable_keepalive: bool, // Default: true pub enable_nodelay: bool, // Default: true pub socket_buffer_size: usize, // Default: 256 KB // ... other fields }
// To get a default configuration: let config = ServerConfig::default(); Example: Custom Configurationuse frd_pu::tcp_server::{new_tcp_server_with_config, ServerConfig, EchoHandler, TcpServerError}; use std::time::Duration;
fn main() -> Result<(), TcpServerError> { let config = ServerConfig { max_connections: 100, timeout: Duration::from_secs(60), rate_limit: 10, // 10 requests per second ..ServerConfig::default() };
let mut server = new_tcp_server_with_config("127.0.0.1:8080", EchoHandler, config)?;
server.serve()
} Monitoring and StatisticsThe server keeps detailed statistics about its operation. You can retrieve these stats at any time without impacting performance.ConnectionStatsSnapshot StructThe get_stats() method returns a ConnectionStatsSnapshot, which contains a copy of the server's current metrics.#[derive(Debug, Clone)] pub struct ConnectionStatsSnapshot { pub total_connections: usize, pub active_connections: usize, pub bytes_received: u64, pub bytes_sent: u64, pub messages_processed: u64, pub errors_count: usize, pub rate_limited_count: usize, pub timeout_count: usize, pub uptime_seconds: u64, } Example: Printing StatsYou can use the built-in print_stats() method or retrieve the snapshot for custom logging.// In a separate thread, you could monitor the server. // let server_arc = Arc::new(server); // Server would need to be wrapped in Arc/Mutex
// Periodically... // server_arc.lock().unwrap().print_stats();
// Or get the data for custom logging: // let stats = server_arc.lock().unwrap().get_stats(); // println!("Active connections: {}", stats.active_connections); Error HandlingThe tcp_server module uses a comprehensive TcpServerError enum to report issues. All public functions that can fail will return a Result<T, TcpServerError>.TcpServerError Enum#[derive(Debug)] pub enum TcpServerError { IoError(io::Error), BindError { addr: String, source: io::Error }, ServerShutdown, ConnectionError { addr: SocketAddr, source: io::Error }, BufferOverflow { size: usize, max: usize }, RateLimitExceeded { addr: SocketAddr, limit: usize }, TimeoutError { addr: SocketAddr, timeout: Duration }, ConfigurationError(String), SocketOptionError { description: String, source: io::Error }, // ... other variants } Advanced GuideGraceful ShutdownFor production applications, you need a way to shut down the server gracefully. The serve() method is blocking, so it should be run in a separate thread. You can then use the stop() method to signal the server to shut down.use frd_pu::tcp_server::{new_echo_server, TcpServer, EchoHandler}; use std::sync::Arc; use std::thread; use std::time::Duration;
fn main() { // The server needs to be mutable to call serve(), so we wrap it for thread safety. let server = Arc::new(new_echo_server("127.0.0.1:8080").unwrap()); let server_clone = server.clone();
// Run the server in its own thread.
let server_handle = thread::spawn(move || {
// We need a mutable reference to the server inside the thread.
// This is a bit tricky. A better approach is to not wrap the server in an Arc
// until after it's moved into the thread.
// For this example, we'll assume a more complex setup with channels.
// A simplified, conceptual example:
// let mut s = Arc::try_unwrap(server_clone).expect("Failed to get server");
// s.serve().unwrap();
println!("Server thread would run here.");
});
// In your main thread, you can wait for a shutdown signal (e.g., Ctrl-C).
println!("Server is running. Press Ctrl-C to stop.");
// In a real app, you'd use a crate like `ctrlc` to handle this.
thread::sleep(Duration::from_secs(10)); // Simulate running for 10 seconds.
// Signal the server to stop.
println!("Shutting down server...");
server.stop();
// Wait for the server thread to finish.
// server_handle.join().unwrap();
println!("Server shut down gracefully.");
} Note: The above example is conceptual. A robust implementation would use channels or a library like tokio for managing the server lifecycle.Sharing State in a HandlerSince the ConnectionHandler is shared across all potential connections, any state it holds must be thread-safe. Use Arc and Mutex (or RwLock) for this.use std::sync::{Arc, Mutex}; use std::collections::HashMap;
struct AppState { user_sessions: HashMap<SocketAddr, String>, }
// Your handler now holds a reference to the shared state. struct StatefulHandler { state: Arc<Mutex>, }
impl ConnectionHandler for StatefulHandler { fn on_connect(&self, addr: SocketAddr) { let mut state = self.state.lock().unwrap(); state.user_sessions.insert(addr, "new_user".to_string()); println!("Total sessions: {}", state.user_sessions.len()); }
fn on_disconnect(&self, addr: SocketAddr) {
let mut state = self.state.lock().unwrap();
state.user_sessions.remove(&addr);
println!("Total sessions: {}", state.user_sessions.len());
}
// handle_data would also lock the state to read/write session data.
fn handle_data(&self, data: &[u8], addr: SocketAddr) -> Option<Vec<u8>> {
let state = self.state.lock().unwrap();
if let Some(user) = state.user_sessions.get(&addr) {
// Process data for the user...
}
Some(b"OK".to_vec())
}
}
// In main(): let state = Arc::new(Mutex::new(AppState { user_sessions: HashMap::new() })); let handler = StatefulHandler { state: state.clone() }; // let mut server = new_tcp_server("...", handler)?; Protocol Design: Message FramingTCP is a stream-based protocol, not a message-based one. This means data can arrive in arbitrary chunks. If you send "HELLO" and "WORLD" from a client, the server might receive "HE", "LLOWOR", and "LD" in three separate handle_data calls.To handle this, you must implement message framing. A common technique is to prefix each message with its length.Example: Length-Prefixed FramingClient:Message: HELLO (5 bytes)Prefix: 5 as a 4-byte integer (e.g., [0, 0, 0, 5])Send: [0, 0, 0, 5, H, E, L, L, O]Server (handle_data):Maintain a buffer for each connection.Append incoming data to the connection's buffer.Check if the buffer contains at least 4 bytes (for the length prefix).If yes, read the length L.Check if the buffer contains at least 4 + L bytes.If yes, you have a complete message. Process the L bytes, and remove 4 + L bytes from the buffer.Repeat until the buffer doesn't contain a full message.This logic would be managed inside your ConnectionHandler, likely using a HashMap to store buffers for each SocketAddr.