Metadata-Version: 2.4
Name: koruspy
Version: 0.6.1
Summary: Uma biblioteca inspirada em Rust e Kotlin para lidar com Option, println colorido e utilitários.
Author-email: Leonardo <leoGitKotDev@gmail.com>
Requires-Python: >=3.10
Description-Content-Type: text/markdown

# Documentação do Módulo Option - koruspy v0.6.0

## 🇧🇷 Versão em Português

### Visão Geral

O módulo **Option** da koruspy é uma estrutura de programação funcional projetada para eliminar o uso de `None` e fornecer segurança de tipos em operações que podem ou não retornar um valor. Inspirado em linguagens como Rust e Scala, o Option traz robustez para aplicações Python mobile de alta performance.

### Arquitetura

O módulo é composto por três classes principais:

#### 1. `Some(value)`
Representa um valor presente e válido.

```python
from koruspy import Some

resultado = Some(42)
println(resultado)  # Saída: Some(42) [em verde]
```

#### 2. `nothing` (singleton de `_NoneOption`)
Representa a ausência de valor de forma segura e tipada. É um singleton global para uso direto.

```python
from koruspy import nothing

resultado = nothing
println(resultado)  # Saída: nothing [em cinza]
```

#### 3. `AsyncOption(future)`
Encapsula operações assíncronas que retornam Option.

```python
from koruspy import AsyncOption
import asyncio

async def buscar_dados():
    await asyncio.sleep(1)
    return Some(100)

resultado = AsyncOption(buscar_dados())
println(resultado)  # Saída: AsyncOption(...) [em roxo]
```

---

### 🚀 Performance com Cython (v0.6.0)

#### Motor de Saída `println`

A versão 0.6.0 introduz o **println**, um sistema de saída otimizado implementado em **Cython** que acessa diretamente a `libc` do C e utiliza `fflush(stdout)` para garantir máxima eficiência.

#### Comparação de Performance

| Método | Tempo (10.000 iterações) | Ganho |
|--------|--------------------------|-------|
| `print()` Python nativo | 0.017s | - |
| `println()` Cython | 0.006s | **3x mais rápido** |

**Ambiente de teste:** Dispositivo mobile Android (ARM64), Python 3.11

```python
# Exemplo de benchmark
from koruspy import println, Some
import time

start = time.perf_counter()
for i in range(10000):
    println(Some(i))
end = time.perf_counter()

print(f"Tempo total: {end - start:.3f}s")
```

---

### 📦 Instalação e Compilação

#### Pré-requisitos
- Python 3.8+
- Cython
- Compilador C (GCC/Clang no Linux/Mac, MSVC no Windows)

#### Instalação via PyPI

```bash
pip install koruspy
```

#### Compilação Local (Opcional - para máxima performance)

Para ativar o motor de alta performance com Cython, execute o script de build incluído no pacote:

```bash
# Após instalar o koruspy
python build_println.py
```

O script automaticamente:
1. Executa `setup.py build_ext --inplace`
2. Move o binário `.so` (Linux/Mac) ou `.pyd` (Windows) para `printlnUtils/`
3. Configura o módulo para uso

#### Verificando a Instalação

```python
from koruspy import println, Some

println(Some("Compilação bem-sucedida!"))
# Se aparecer em verde, o Cython está ativo
```

---

### ♿ Acessibilidade Visual

#### Sistema de Cores ANSI

O koruspy implementa um esquema de cores otimizado para reduzir fadiga visual em telas pequenas, especialmente útil para desenvolvedores com astigmatismo:

| Tipo | Cor | Código ANSI | Propósito |
|------|-----|-------------|-----------|
| `Some` | **Verde** | `\033[32m` | Indica sucesso/valor presente |
| `nothing` | **Cinza** | `\033[90m` | Indica ausência de valor |
| `AsyncOption` | **Roxo** | `\033[35m` | Indica operação assíncrona |

#### Benefícios
- **Contraste suave:** Evita cores primárias fortes que causam cansaço
- **Distinção clara:** Facilita identificação rápida do estado
- **SmartIDE friendly:** Otimizado para editores mobile com telas 5-7"

---

### 🎯 Exemplos Práticos

#### Exemplo 1: Validação de Entrada

```python
from koruspy import Some, nothing, println

def dividir(a: int, b: int):
    if b == 0:
        return nothing
    return Some(a / b)

resultado = dividir(10, 2)
println(resultado)  # Some(5.0) [verde]

resultado_erro = dividir(10, 0)
println(resultado_erro)  # nothing [cinza]
```

#### Exemplo 2: Pipeline Assíncrono

```python
from koruspy import AsyncOption, Some, println
import asyncio

async def buscar_usuario(id: int):
    await asyncio.sleep(0.5)
    if id > 0:
        return Some({"nome": "Alice", "id": id})
    return nothing

async def main():
    opcao = AsyncOption(buscar_usuario(1))
    resultado = await opcao.value
    println(resultado)  # Some({'nome': 'Alice', 'id': 1})

asyncio.run(main())
```

#### Exemplo 3: Encadeamento Seguro

```python
from koruspy import Some, nothing

def processar_dados(option):
    return option.map(lambda x: x * 2).filter(lambda x: x > 10)

println(processar_dados(Some(10)))  # Some(20)
println(processar_dados(nothing))   # nothing
```

---

### 📚 Comparação com `None` do Python

| Aspecto | `None` Python | koruspy `Option` |
|---------|---------------|------------------|
| **Segurança de tipos** | ❌ Pode causar `AttributeError` | ✅ Type-safe, evita erros em runtime |
| **Composição** | ❌ Requer verificações manuais | ✅ `map()`, `filter()`, `flatMap()` |
| **Visibilidade** | ❌ Sem distinção visual | ✅ Cores ANSI para debugging rápido |
| **Performance** | ⚡ Nativa | ⚡⚡⚡ 3x mais rápida com Cython |
| **Async-friendly** | ❌ Requer wrappers manuais | ✅ `AsyncOption` nativo |

---

### 🔧 Troubleshooting

#### Problema: "Cores não aparecem no terminal"

**Solução:** Verifique se seu terminal suporta ANSI. No Windows, use Windows Terminal ou ative o suporte:

```python
import os
os.system('color')  # Ativa ANSI no Windows
```

#### Problema: "println não está mais rápido"

**Solução:** Verifique se a extensão Cython foi compilada:

```bash
ls printlnUtils/*.so  # Linux/Mac
dir printlnUtils\*.pyd  # Windows
```

Se não existir, recompile com `python build_println.py`.

---

### 🤝 Contribuindo

O koruspy é um projeto desenvolvido com foco em acessibilidade mobile! Se você tem sugestões, melhorias ou encontrou bugs, entre em contato com o desenvolvedor.

**Desenvolvido para celular, por desenvolvedores mobile.**

---

### 📄 Sobre o Projeto

koruspy é uma biblioteca focada em performance e acessibilidade para desenvolvimento Python mobile, parte do ecossistema SmartIDE.

---

## 🇺🇸 English Version

### Overview

The **Option** module in koruspy is a functional programming structure designed to eliminate the use of `None` and provide type safety for operations that may or may not return a value. Inspired by languages like Rust and Scala, Option brings robustness to high-performance mobile Python applications.

### Architecture

The module consists of three main classes:

#### 1. `Some(value)`
Represents a present and valid value.

```python
from koruspy import Some

result = Some(42)
println(result)  # Output: Some(42) [in green]
```

#### 2. `nothing` (singleton of `_NoneOption`)
Represents the absence of a value in a safe and typed manner. It's a global singleton for direct use.

```python
from koruspy import nothing

result = nothing
println(result)  # Output: nothing [in gray]
```

#### 3. `AsyncOption(future)`
Encapsulates asynchronous operations that return Option.

```python
from koruspy import AsyncOption
import asyncio

async def fetch_data():
    await asyncio.sleep(1)
    return Some(100)

result = AsyncOption(fetch_data())
println(result)  # Output: AsyncOption(...) [in purple]
```

---

### 🚀 Performance with Cython (v0.6.0)

#### `println` Output Engine

Version 0.6.0 introduces **println**, an optimized output system implemented in **Cython** that directly accesses C's `libc` and uses `fflush(stdout)` to ensure maximum efficiency.

#### Performance Comparison

| Method | Time (10,000 iterations) | Gain |
|--------|--------------------------|------|
| Python native `print()` | 0.017s | - |
| Cython `println()` | 0.006s | **3x faster** |

**Test environment:** Android mobile device (ARM64), Python 3.11

```python
# Benchmark example
from koruspy import println, Some
import time

start = time.perf_counter()
for i in range(10000):
    println(Some(i))
end = time.perf_counter()

print(f"Total time: {end - start:.3f}s")
```

---

### 📦 Installation and Compilation

#### Prerequisites
- Python 3.8+
- Cython
- C Compiler (GCC/Clang on Linux/Mac, MSVC on Windows)

#### Installation via PyPI

```bash
pip install koruspy
```

#### Local Compilation (Optional - for maximum performance)

To activate the high-performance engine with Cython, run the build script included in the package:

```bash
# After installing koruspy
python build_println.py
```

The script automatically:
1. Executes `setup.py build_ext --inplace`
2. Moves the `.so` (Linux/Mac) or `.pyd` (Windows) binary to `printlnUtils/`
3. Configures the module for use

#### Verifying Installation

```python
from koruspy import println, Some

println(Some("Compilation successful!"))
# If it appears in green, Cython is active
```

---

### ♿ Visual Accessibility

#### ANSI Color System

koruspy implements an optimized color scheme to reduce visual fatigue on small screens, especially useful for developers with astigmatism:

| Type | Color | ANSI Code | Purpose |
|------|-------|-----------|---------|
| `Some` | **Green** | `\033[32m` | Indicates success/value present |
| `nothing` | **Gray** | `\033[90m` | Indicates absence of value |
| `AsyncOption` | **Purple** | `\033[35m` | Indicates asynchronous operation |

#### Benefits
- **Soft contrast:** Avoids strong primary colors that cause fatigue
- **Clear distinction:** Facilitates quick state identification
- **SmartIDE friendly:** Optimized for mobile editors with 5-7" screens

---

### 🎯 Practical Examples

#### Example 1: Input Validation

```python
from koruspy import Some, nothing, println

def divide(a: int, b: int):
    if b == 0:
        return nothing
    return Some(a / b)

result = divide(10, 2)
println(result)  # Some(5.0) [green]

error_result = divide(10, 0)
println(error_result)  # nothing [gray]
```

#### Example 2: Asynchronous Pipeline

```python
from koruspy import AsyncOption, Some, println
import asyncio

async def fetch_user(id: int):
    await asyncio.sleep(0.5)
    if id > 0:
        return Some({"name": "Alice", "id": id})
    return nothing

async def main():
    option = AsyncOption(fetch_user(1))
    result = await option.value
    println(result)  # Some({'name': 'Alice', 'id': 1})

asyncio.run(main())
```

#### Example 3: Safe Chaining

```python
from koruspy import Some, nothing

def process_data(option):
    return option.map(lambda x: x * 2).filter(lambda x: x > 10)

println(process_data(Some(10)))  # Some(20)
println(process_data(nothing))   # nothing
```

---

### 📚 Comparison with Python's `None`

| Aspect | Python `None` | koruspy `Option` |
|--------|---------------|------------------|
| **Type safety** | ❌ Can cause `AttributeError` | ✅ Type-safe, prevents runtime errors |
| **Composition** | ❌ Requires manual checks | ✅ `map()`, `filter()`, `flatMap()` |
| **Visibility** | ❌ No visual distinction | ✅ ANSI colors for quick debugging |
| **Performance** | ⚡ Native | ⚡⚡⚡ 3x faster with Cython |
| **Async-friendly** | ❌ Requires manual wrappers | ✅ Native `AsyncOption` |

---

### 🔧 Troubleshooting

#### Issue: "Colors don't appear in terminal"

**Solution:** Check if your terminal supports ANSI. On Windows, use Windows Terminal or enable support:

```python
import os
os.system('color')  # Enables ANSI on Windows
```

#### Issue: "println is not faster"

**Solution:** Verify that the Cython extension was compiled:

```bash
ls printlnUtils/*.so  # Linux/Mac
dir printlnUtils\*.pyd  # Windows
```

If it doesn't exist, recompile with `python build_println.py`.

---

### 🤝 Contributing

koruspy is a project developed with a focus on mobile accessibility! If you have suggestions, improvements, or found bugs, please contact the developer.

**Built for mobile, by mobile developers.**

---

### 📄 About the Project

koruspy is a library focused on performance and accessibility for mobile Python development.
