Ultimate C++ Libraries

License: MIT C++20 Thread Safe Memory Safe Build Status Buy Me a Coffee

Support the Project: If you find these libraries useful, consider buying me a coffee to support continued development! โ˜•

A comprehensive collection of production-ready C++ libraries designed for modern software development. This repository contains two powerful libraries that work together to provide safe, efficient, and maintainable C++ code.

๐Ÿ“š Libraries

๐Ÿ›ก๏ธ SafeString - Ultimate String Library

A comprehensive, memory-safe, and thread-safe string library that eliminates entire classes of string-related bugs while providing rich functionality.

โšก SmartError - Modern Error Handling

A modern error handling library that provides type-safe error management, context preservation, and seamless integration with SafeString.

๐Ÿš€ Quick Start

Installation

# Clone the repository
git clone https://github.com/your-org/ultimate-cpp-libraries.git
cd ultimate-cpp-libraries

# Build and install
mkdir build && cd build
cmake .. -DCMAKE_BUILD_TYPE=Release
cmake --build . --parallel
sudo cmake --install .

Basic Usage

#include <safestring/safestring.hpp>
#include <smarterror/error.hpp>

using namespace safestring;
using namespace smarterror;

int main() {
    // SafeString - Memory-safe string operations
    auto str = "Hello World"_s;
    auto upper = str.toUpperCase();
    auto parts = str.split(" "_s);
    
    // SmartError - Type-safe error handling
    auto result = divide_numbers(10, 2);
    if (!result.is_success()) {
        std::cerr << "Error: " << result.error().message() << std::endl;
        return 1;
    }
    
    std::cout << "Result: " << result.value() << std::endl;
    return 0;
}

๐Ÿ“‹ Table of Contents


๐Ÿ›ก๏ธ SafeString Library

Overview

SafeString is a comprehensive C++ string library that combines the best features from modern programming languages while maintaining C++'s performance. It eliminates entire classes of string-related bugs through memory safety, thread safety, and type safety.

Key Features

  • ๐Ÿ›ก๏ธ Memory Safe: No buffer overflows, automatic memory management, RAII
  • ๐Ÿงต Thread Safe: All operations are thread-safe with shared mutexes
  • ๐Ÿ” Type Safe: Compile-time and runtime type checking for all operations
  • โšก High Performance: Copy-on-write, string interning, SIMD optimizations
  • ๐ŸŒ Unicode Ready: Full internationalization support with ICU-compatible API
  • ๐Ÿ”ง Rich API: 200+ methods covering all string operations you'll ever need
  • ๐ŸŽฏ Modern C++: Leverages C++20 features, concepts, and best practices
  • ๐Ÿ“ฆ Zero Dependencies: Header-only library with optional feature dependencies

Basic Usage

#include <safestring/safestring.hpp>

// JavaScript-like string operations
auto str = "Hello World"_s;
auto lower = str.toLowerCase();
auto parts = str.split(" "_s);
auto result = str.replace("World"_s, "C++"_s);

// Type-safe sprintf
auto formatted = sprintf("User %s has %d messages"_s, "John"_s, 42);

// Functional programming
auto processed = "Hello123World!"_s
    .filter_chars([](char c) { return std::isalpha(c); })
    .map_chars([](char c) { return std::toupper(c); })
    .reduce([](SafeString acc, char c) { return acc + c; }, ""_s);

// Thread-safe operations
std::vector<std::thread> threads;
SafeString shared_string = "Thread Safe"_s;

for (int i = 0; i < 10; ++i) {
    threads.emplace_back([&shared_string]() {
        auto result = shared_string.toUpperCase(); // Completely safe
    });
}

Advanced Features

// Validation and sanitization
auto email = "user@example.com"_s;
if (email.isEmail()) {
    auto sanitized = email.sanitizeHtml();
    // Process safely
}

// Encoding and decoding
auto encoded = "Hello World"_s.base64Encode();
auto decoded = encoded.base64Decode();

// Regular expressions
auto text = "Phone: 123-456-7890, Email: user@example.com"_s;
auto phone_match = text.match("\\d{3}-\\d{3}-\\d{4}");
if (phone_match.success()) {
    std::cout << "Phone: " << phone_match[0] << std::endl;
}

// Internationalization
auto localized = "Hello"_s.translate("es"); // "Hola"
auto normalized = "cafรฉ"_s.normalize(UnicodeNormalization::NFC);

โšก SmartError Library

Overview

SmartError is a modern error handling library that provides type-safe error management, context preservation, and seamless integration with SafeString. It eliminates the need for exception handling while providing rich error information and debugging capabilities.

Key Features

  • ๐Ÿ”’ Type Safe: Compile-time error checking with Result types
  • ๐Ÿ“ Rich Context: Automatic source location, stack traces, and metadata
  • ๐Ÿ”— Error Chaining: Propagate errors with full context preservation
  • ๐ŸŽจ Multiple Formats: String, JSON, and custom error serialization
  • ๐Ÿงต Thread Safe: Thread-safe error context and collection
  • ๐Ÿ”ง Macros: Convenient macros for common error patterns
  • ๐Ÿ“Š Error Scopes: Collect and manage multiple errors
  • ๐Ÿ”„ Integration: Seamless integration with SafeString validation

Basic Usage

#include <smarterror/error.hpp>
#include <smarterror/result.hpp>

// Basic error creation
Error error(ErrorCode::NOT_FOUND, "Resource not found");
std::cout << error.to_string() << std::endl;

// Type-safe Result class
Result<int> divide_numbers(int a, int b) {
    if (b == 0) {
        return Result<int>::failure(
            SMARTERROR_CREATE(ErrorCode::INVALID_ARGUMENT, "Division by zero")
        );
    }
    return Result<int>::success(a / b);
}

// Using SMARTERROR_TRY macro
auto process_data = []() -> Result<int> {
    auto result1 = divide_numbers(20, 4);
    SMARTERROR_TRY(result1);
    
    auto result2 = divide_numbers(result1.value(), 2);
    SMARTERROR_TRY(result2);
    
    return Result<int>::success(result2.value());
};

Advanced Features

// Error with context and metadata
ErrorContext context;
context.set("user_id", "12345");
context.set("operation", "database_query");

Error error(ErrorCode::DATABASE_ERROR, "Connection failed");
error.set_context(context);
error.set_severity(ErrorSeverity::CRITICAL);
error.add_metadata("connection_string", "postgresql://localhost:5432/db");
error.add_metadata("retry_count", "3");

// Error chaining
Error original(ErrorCode::FILE_NOT_FOUND, "Config file not found");
Error propagated = SMARTERROR_PROPAGATE(original);

// Error scopes for collecting multiple errors
ErrorScope scope;
scope.add_error(SMARTERROR_VALIDATION_ERROR("username", "Too short"));
scope.add_error(SMARTERROR_VALIDATION_ERROR("email", "Invalid format"));

if (!scope.is_empty()) {
    auto errors = scope.errors();
    for (const auto& err : errors) {
        std::cerr << err.message() << std::endl;
    }
}

// Integration with SafeString validation
Result<SafeString> validate_email(const SafeString& email) {
    if (!email.isEmail()) {
        return Result<SafeString>::failure(
            SMARTERROR_VALIDATION_ERROR("email", "Invalid email format")
        );
    }
    return Result<SafeString>::success(email);
}

๐Ÿ“ฆ Installation

Method 1: Header-Only (Recommended)

// Simply include the headers
#include <safestring/safestring.hpp>
#include <smarterror/error.hpp>

Method 2: CMake Integration

find_package(UltimateCppLibraries REQUIRED)
target_link_libraries(your_target 
    UltimateCpp::safestring
    UltimateCpp::smarterror
)

Method 3: FetchContent

include(FetchContent)
FetchContent_Declare(
    UltimateCppLibraries
    GIT_REPOSITORY https://github.com/your-org/ultimate-cpp-libraries.git
    GIT_TAG v1.0.0
)
FetchContent_MakeAvailable(UltimateCppLibraries)
target_link_libraries(your_target 
    UltimateCpp::safestring
    UltimateCpp::smarterror
)

Method 4: Package Managers

# vcpkg
vcpkg install ultimate-cpp-libraries

# Conan
conan install ultimate-cpp-libraries/1.0.0@

๐ŸŽฏ Usage Examples

Web Development

#include <safestring/safestring.hpp>
#include <smarterror/error.hpp>

class WebServer {
public:
    Result<void> handle_request(const SafeString& request) {
        // Parse and validate request
        auto parsed = parse_request(request);
        SMARTERROR_TRY(parsed);
        
        // Validate user input
        auto email = parsed.value().get("email");
        auto email_result = validate_email(email);
        SMARTERROR_TRY_VOID(email_result);
        
        // Process request safely
        auto response = process_request(parsed.value());
        return response;
    }
    
private:
    Result<Request> parse_request(const SafeString& request) {
        if (request.empty()) {
            return Result<Request>::failure(
                SMARTERROR_CREATE(ErrorCode::INVALID_ARGUMENT, "Empty request")
            );
        }
        
        // Parse JSON, validate, etc.
        return Result<Request>::success(Request{});
    }
};

Data Processing

#include <safestring/safestring.hpp>
#include <smarterror/error.hpp>

class DataProcessor {
public:
    Result<std::vector<SafeString>> process_csv(const SafeString& csv_data) {
        ErrorContext context;
        context.set("file_size", std::to_string(csv_data.length()));
        context.set("operation", "csv_processing");
        
        // Validate input
        if (!csv_data.contains(",")) {
            auto error = SMARTERROR_CREATE(ErrorCode::VALIDATION_ERROR, "Invalid CSV format");
            error.set_context(context);
            return Result<std::vector<SafeString>>::failure(error);
        }
        
        // Process data safely
        auto lines = csv_data.split("\n"_s);
        std::vector<SafeString> processed;
        
        for (const auto& line : lines) {
            auto trimmed = line.trim();
            if (!trimmed.empty()) {
                processed.push_back(trimmed);
            }
        }
        
        return Result<std::vector<SafeString>>::success(processed);
    }
};

โšก Performance

Both libraries are designed for high performance:

SafeString Performance

  • Copy-on-write: Efficient memory sharing
  • String interning: Automatic deduplication
  • SIMD optimizations: Vectorized operations
  • Zero-copy views: Efficient string slicing
  • Memory pooling: Reduced allocation overhead

SmartError Performance

  • Zero-cost abstractions: No runtime overhead for success paths
  • Efficient error propagation: Minimal copying
  • Lazy evaluation: Context and metadata only when needed
  • Thread-local storage: Fast context access

Benchmarks

// SafeString vs std::string performance
SafeString safe_str = "Hello World"_s;
std::string std_str = "Hello World";

// SafeString operations are typically 1.2x-1.5x faster
auto safe_result = safe_str.toUpperCase() + "!"_s;
auto std_result = std_str;
std::transform(std_result.begin(), std_result.end(), std_result.begin(), ::toupper);
std_result += "!";

๐Ÿงต Thread Safety

SafeString Thread Safety

  • All operations are thread-safe by default
  • Shared mutex protection for concurrent access
  • Atomic operations where possible
  • Lock-free string views for read-only operations

SmartError Thread Safety

  • Thread-safe error contexts with atomic operations
  • Thread-local error scopes for isolation
  • Concurrent error collection with proper synchronization
  • Lock-free error propagation in most cases
// Thread-safe usage example
std::vector<std::thread> threads;
SafeString shared_string = "Thread Safe"_s;
ErrorScope global_scope;

for (int i = 0; i < 10; ++i) {
    threads.emplace_back([&shared_string, &global_scope, i]() {
        // Safe concurrent access
        auto result = shared_string.toUpperCase();
        
        // Thread-safe error collection
        if (i % 3 == 0) {
            global_scope.add_error(
                SMARTERROR_CREATE(ErrorCode::TIMEOUT, "Operation timed out")
            );
        }
    });
}

for (auto& thread : threads) {
    thread.join();
}

๐Ÿ›ก๏ธ Memory Safety

SafeString Memory Safety

  • Automatic bounds checking on all operations
  • RAII resource management with no memory leaks
  • Exception safety guarantees
  • Buffer overflow protection on all string operations

SmartError Memory Safety

  • No dynamic allocations in error paths
  • RAII error scopes with automatic cleanup
  • Exception-safe error propagation
  • Memory-efficient error storage
// Memory-safe operations
SafeString str = "Hello World"_s;

// Safe substring (no buffer overflow possible)
auto sub = str.substr(0, 1000); // Returns "Hello World" safely

// Safe element access
try {
    char c = str.at(100); // Throws std::out_of_range
} catch (const std::out_of_range& e) {
    // Handle safely
}

// Memory-safe error handling
auto result = risky_operation();
if (!result.is_success()) {
    // Error handling without exceptions
    handle_error(result.error());
}

๐Ÿ”ง Building

Requirements

  • C++20 compatible compiler (GCC 10+, Clang 11+, MSVC 2019+)
  • CMake 3.16+
  • Optional: ICU library for full Unicode support

Build Instructions

# Clone the repository
git clone https://github.com/your-org/ultimate-cpp-libraries.git
cd ultimate-cpp-libraries

# Create build directory
mkdir build && cd build

# Configure with CMake
cmake .. -DCMAKE_BUILD_TYPE=Release

# Build
cmake --build . --parallel

# Run tests
ctest --parallel

# Install
sudo cmake --install .

CMake Options

# SafeString options
option(SAFESTRING_BUILD_TESTS "Build SafeString tests" ON)
option(SAFESTRING_BUILD_EXAMPLES "Build SafeString examples" ON)
option(SAFESTRING_ENABLE_ICU "Enable ICU support" OFF)
option(SAFESTRING_ENABLE_SIMD "Enable SIMD optimizations" ON)
option(SAFESTRING_HEADER_ONLY "Header-only mode" ON)

# SmartError options
option(SMARTERROR_BUILD_TESTS "Build SmartError tests" ON)
option(SMARTERROR_BUILD_EXAMPLES "Build SmartError examples" ON)
option(SMARTERROR_ENABLE_STACK_TRACE "Enable stack trace support" ON)
option(SMARTERROR_ENABLE_COLOR "Enable colored output" ON)
option(SMARTERROR_ENABLE_JSON "Enable JSON error format" ON)
option(SMARTERROR_THREAD_SAFE "Enable thread safety" ON)

๐Ÿ“š API Reference

SafeString API

SmartError API


๐Ÿค Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

# Clone and setup
git clone https://github.com/your-org/ultimate-cpp-libraries.git
cd ultimate-cpp-libraries

# Install dependencies
sudo apt install cmake build-essential libicu-dev

# Build with all features
mkdir build && cd build
cmake .. \
    -DCMAKE_BUILD_TYPE=Debug \
    -DSAFESTRING_BUILD_TESTS=ON \
    -DSAFESTRING_BUILD_EXAMPLES=ON \
    -DSAFESTRING_ENABLE_ICU=ON \
    -DSMARTERROR_BUILD_TESTS=ON \
    -DSMARTERROR_BUILD_EXAMPLES=ON

# Build and test
cmake --build . --parallel
ctest --parallel

๐Ÿ“„ License

This project is licensed under the MIT License - see the LICENSE file for details.


๐Ÿ™ Acknowledgments

  • Inspired by modern programming languages like Rust, Swift, and Kotlin
  • Built with modern C++20 features and best practices
  • Thanks to the C++ community for feedback and contributions

๐Ÿ“ž Support


Made with โค๏ธ for the C++ community