Skip to main content

FormatTasks

Trait FormatTasks 

Source
pub trait FormatTasks {
    // Required methods
    fn format(&mut self) -> String;
    fn divide(&mut self, parts: usize) -> Vec<Vec<Task>>;
}
Expand description

Trait providing formatting and manipulation operations for task collections.

This trait extends Vec with specialized methods for formatting tasks for display and dividing task collections for parallel processing or load balancing. It provides a clean interface for common task collection operations.

ยงDesign Philosophy

The trait follows Rustโ€™s iterator philosophy by providing chainable, efficient operations on task collections. Methods are designed to be:

  • Composable: Can be chained together for complex operations
  • Efficient: Minimize allocations and copying where possible
  • Flexible: Support various output formats and processing patterns
  • Predictable: Consistent behavior across different input sizes

ยงMethod Categories

ยงFormatting Methods

  • format(): Convert tasks to human-readable string representation

ยงPartitioning Methods

  • divide(): Split tasks into balanced groups for parallel processing

ยงPerformance Characteristics

  • Memory Usage: Methods minimize unnecessary allocations
  • Time Complexity: Most operations are O(n) where n is task count
  • Parallelization: Partitioning methods support concurrent processing

ยงExamples

use kasl::libs::task::{Task, FormatTasks};

let mut tasks = vec![
    Task::new("Task 1", "Description 1", Some(50)),
    Task::new("Task 2", "Description 2", Some(75)),
    Task::new("Task 3", "Description 3", Some(100)),
];

// Format for display
let formatted = tasks.format();
println!("{}", formatted);

// Divide for parallel processing
let groups = tasks.divide(2);
for (i, group) in groups.iter().enumerate() {
    println!("Group {}: {} tasks", i, group.len());
}

Required Methodsยง

Source

fn format(&mut self) -> String

Formats the task collection into a human-readable string representation.

This method converts a collection of tasks into a structured string format suitable for console output, logging, or simple text-based displays. The format includes key task information in a consistent, scannable layout.

ยงOutput Format

The method produces a multi-line string with each task formatted as:

{name} ({completeness}%)
ยงField Handling
  • ID: Shows database ID or โ€œNewโ€ for unsaved tasks
  • Name: Task title, truncated if excessively long
  • Completeness: Percentage or โ€œUnknownโ€ if not set
  • Comment: Description, truncated if excessively long
ยงUse Cases
  • Debug Output: Quick task collection visualization
  • Log Messages: Structured logging of task operations
  • Simple Reports: Basic text-based task summaries
  • CLI Output: Command-line interface task displays
ยงReturns

A formatted string representation of all tasks in the collection.

ยงExamples
use kasl::libs::task::{Task, FormatTasks};

let mut tasks = vec![
    Task::new("Review PR", "Code review for auth changes", Some(25)),
    Task::new("Write tests", "Unit tests for API endpoints", Some(75)),
];

let output = tasks.format();
// Output:
// Review PR (25%)
// Write tests (75%)
Source

fn divide(&mut self, parts: usize) -> Vec<Vec<Task>>

Divides the task collection into the specified number of balanced groups.

This method partitions tasks into multiple groups of approximately equal size, which is useful for parallel processing, load balancing, or organizing large task collections into manageable chunks.

ยงPartitioning Algorithm

The method uses a round-robin distribution strategy:

  1. Base Size Calculation: Determines minimum tasks per group
  2. Remainder Distribution: Distributes extra tasks evenly
  3. Sequential Assignment: Assigns tasks to groups in order
  4. Balance Optimization: Ensures groups differ by at most 1 task
ยงEdge Case Handling
ยงEmpty Collection
  • Returns vector of empty groups
  • Number of groups equals requested parts
ยงSingle Task
  • Duplicates the task across all groups
  • Useful for broadcast scenarios
ยงFewer Tasks Than Parts
  • Creates groups with 0-1 tasks each
  • Distributes tasks round-robin style
ยงMore Tasks Than Parts
  • Creates balanced groups with similar sizes
  • Groups differ by at most 1 task
ยงUse Cases
ยงParallel Processing
let task_groups = tasks.divide(cpu_count);
for group in task_groups {
    spawn_worker_thread(group);
}
ยงLoad Balancing
let worker_assignments = tasks.divide(worker_count);
for (worker_id, assignment) in worker_assignments.iter().enumerate() {
    assign_tasks_to_worker(worker_id, assignment);
}
ยงUI Organization
let columns = tasks.divide(3); // Three-column layout
for (col_index, column_tasks) in columns.iter().enumerate() {
    render_task_column(col_index, column_tasks);
}
ยงArguments
  • parts - Number of groups to create (must be > 0)
ยงReturns

A vector containing the requested number of task groups. Each group is a Vec containing a portion of the original task collection.

ยงExamples
use kasl::libs::task::{Task, FormatTasks};

let mut tasks = vec![
    Task::new("Task 1", "", None),
    Task::new("Task 2", "", None),
    Task::new("Task 3", "", None),
    Task::new("Task 4", "", None),
    Task::new("Task 5", "", None),
];

// Divide into 3 groups
let groups = tasks.divide(3);
// groups[0]: [Task 1, Task 4] (2 tasks)
// groups[1]: [Task 2, Task 5] (2 tasks)  
// groups[2]: [Task 3]         (1 task)

// Verify balanced distribution
assert_eq!(groups.len(), 3);
assert_eq!(groups[0].len(), 2);
assert_eq!(groups[1].len(), 2);
assert_eq!(groups[2].len(), 1);

Dyn Compatibilityยง

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementations on Foreign Typesยง

Sourceยง

impl FormatTasks for Vec<Task>

Implementation of FormatTasks trait for Vec.

This implementation provides concrete formatting and partitioning logic for task collections. It handles various edge cases and provides efficient algorithms for common task manipulation scenarios.

Sourceยง

fn divide(&mut self, parts: usize) -> Vec<Vec<Task>>

Divides the task collection into balanced groups using round-robin distribution.

This implementation uses an optimized algorithm that ensures balanced distribution while handling edge cases gracefully. The algorithm minimizes memory allocations and provides predictable results.

ยงAlgorithm Details
  1. Input Validation: Handle zero parts and empty collections
  2. Special Cases: Optimize for single task and small collections
  3. Size Calculation: Compute base size and remainder distribution
  4. Group Assignment: Distribute tasks using calculated sizes
ยงPerformance Characteristics
  • Time Complexity: O(n) where n is the number of tasks
  • Space Complexity: O(n) for the output groups
  • Memory Efficiency: Minimal allocations during processing

The implementation is optimized for common use cases while maintaining correctness for edge cases.

Sourceยง

fn format(&mut self) -> String

Formats the task collection into a structured string representation.

This implementation creates a multi-line string with each task formatted consistently. It handles missing fields gracefully and provides readable output suitable for debugging and simple displays.

ยงFormat Structure

Each task is formatted on a separate line with pipe-separated fields:

{name} ({completeness}%)
ยงField Processing
  • Name: Used as-is from task struct
  • Completeness: Shows percentage or โ€œUnknownโ€ for None values

The method handles all field types gracefully and provides consistent output regardless of which optional fields are present.

Implementorsยง