ansi-align 0.2.2

Text alignment library with ANSI escape sequence and Unicode support
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
//! # ansi-align
//!
//! [![Crates.io](https://img.shields.io/crates/v/ansi-align.svg)](https://crates.io/crates/ansi-align)
//! [![Documentation](https://docs.rs/ansi-align/badge.svg)](https://docs.rs/ansi-align)
//! [![License](https://img.shields.io/crates/l/ansi-align.svg)](https://github.com/sabry-awad97/ansi-align#license)
//!
//! A high-performance Rust library for aligning text with comprehensive support for ANSI escape sequences,
//! Unicode characters, and customizable formatting options.
//!
//! This crate provides robust text alignment capabilities that correctly handle:
//! - ANSI escape sequences (colors, formatting codes)
//! - Unicode characters with varying display widths (including CJK characters)
//! - Custom line separators and padding characters
//! - Performance-optimized algorithms for large text processing
//!
//! ## πŸš€ Features
//!
//! - **🎨 ANSI-aware alignment**: Correctly handles text containing ANSI escape sequences
//! - **🌍 Unicode support**: Properly calculates display width for all Unicode characters
//! - **⚑ High performance**: Single-pass processing with optimized memory usage
//! - **πŸ”§ Highly customizable**: Configure alignment, separators, and padding
//! - **πŸ›‘οΈ Type-safe**: Uses a [`Width`] type to prevent display width confusion
//! - **πŸ“¦ Zero-copy optimizations**: Left alignment is implemented as a no-op
//!
//! ## πŸ“– Quick Start
//!
//! Add this to your `Cargo.toml`:
//!
//! ```toml
//! [dependencies]
//! ansi-align = "0.1.0"
//! ```
//!
//! ### Basic Usage
//!
//! ```rust
//! use ansi_align::{ansi_align, center, left, right};
//!
//! // Basic alignment (defaults to center)
//! let text = "hello\nworld";
//! let centered = ansi_align(text);
//! println!("{}", centered);
//! // Output:
//! //  hello
//! // world
//!
//! // Specific alignment functions
//! let left_aligned = left("short\nlonger line");
//! let centered = center("short\nlonger line");
//! let right_aligned = right("short\nlonger line");
//! ```
//!
//! ### ANSI Color Support
//!
//! ```rust
//! use ansi_align::center;
//!
//! // Colors and formatting are preserved but don't affect alignment
//! let colored_text = "\x1b[31mRed\x1b[0m\n\x1b[32mGreen Text\x1b[0m";
//! let aligned = center(colored_text);
//! println!("{}", aligned);
//! // ANSI codes are preserved in output but ignored for width calculation
//! ```
//!
//! ### Unicode Character Support
//!
//! ```rust
//! use ansi_align::right;
//!
//! // Correctly handles wide Unicode characters (CJK, emojis, etc.)
//! let unicode_text = "叀\n叀叀叀\nHello δΈ–η•Œ";
//! let aligned = right(unicode_text);
//! println!("{}", aligned);
//! // Properly accounts for double-width characters
//! ```
//!
//! ## πŸ”§ Advanced Usage
//!
//! ### Custom Options
//!
//! ```rust
//! use ansi_align::{ansi_align_with_options, Alignment, AlignOptions};
//!
//! // Custom separator and padding
//! let data = "Name|Age|City";
//! let options = AlignOptions::new(Alignment::Center)
//!     .with_split("|")
//!     .with_pad('_');
//!
//! let result = ansi_align_with_options(data, &options);
//! println!("{}", result);
//! // Output: __Name|Age|City
//! ```
//!
//! ### Builder Pattern
//!
//! ```rust
//! use ansi_align::{ansi_align_with_options, Alignment, AlignOptions};
//!
//! let options = AlignOptions::new(Alignment::Right)
//!     .with_split("<->")
//!     .with_pad('.');
//!
//! let text = "short<->very long line";
//! let result = ansi_align_with_options(text, &options);
//! ```
//!
//! ## πŸ“Š Performance Characteristics
//!
//! - **Left alignment**: O(1) - implemented as a no-op for maximum performance
//! - **Center/Right alignment**: O(n) - single pass through input text
//! - **Memory usage**: Minimal allocations with pre-calculated capacity
//! - **Large text handling**: Optimized padding creation for different sizes
//!
//! ## 🎯 Use Cases
//!
//! - **CLI applications**: Align help text, tables, and menus
//! - **Terminal UIs**: Create visually appealing layouts
//! - **Log formatting**: Align log entries and structured output
//! - **Code generation**: Format generated code with proper indentation
//! - **Documentation**: Align text blocks in generated docs
//!
//! ## πŸ—οΈ Architecture
//!
//! The library is built around three core concepts:
//!
//! 1. **[`Alignment`]** - Defines the alignment direction (Left, Center, Right)
//! 2. **[`AlignOptions`]** - Configuration for alignment behavior
//! 3. **[`Width`]** - Type-safe wrapper for display width calculations
//!
//! The main entry point is [`ansi_align_with_options`], which provides full customization,
//! while convenience functions like [`left`], [`center`], and [`right`] offer simplified APIs.
//!
//! ## πŸ” Examples
//!
//! ### Menu Alignment
//!
//! ```rust
//! use ansi_align::center;
//!
//! let menu = "🏠 Home\nπŸ“‹ About\nπŸ“ž Contact\nβš™οΈ Settings";
//! let aligned_menu = center(menu);
//! println!("{}", aligned_menu);
//! ```
//!
//! ### Table-like Data
//!
//! ```rust
//! use ansi_align::{ansi_align_with_options, Alignment, AlignOptions};
//!
//! let data = "ID|Name|Status";
//! let options = AlignOptions::new(Alignment::Center).with_split("|");
//! let result = ansi_align_with_options(data, &options);
//! ```
//!
//! ### Code Block Alignment
//!
//! ```rust
//! use ansi_align::right;
//!
//! let code = "if condition:\n    execute()\nelse:\n    handle_error()";
//! let aligned = right(code);
//! println!("{}", aligned);
//! ```

#![deny(missing_docs)]
#![warn(clippy::all)]
#![warn(clippy::pedantic)]
#![warn(clippy::nursery)]

use std::fmt;
use std::ops::{Add, Div, Mul, Sub};
use string_width::string_width;

/// Specifies the alignment direction for text.
///
/// This enum defines the three fundamental alignment options available in the library.
/// Each variant represents a different strategy for positioning text within the available width.
///
/// # Alignment Behavior
///
/// - **[`Left`](Alignment::Left)**: Text is positioned at the leftmost edge (no padding on left)
/// - **[`Center`](Alignment::Center)**: Text is centered with equal padding on both sides
/// - **[`Right`](Alignment::Right)**: Text is positioned at the rightmost edge (padding on left)
///
/// # Performance Notes
///
/// - `Left` alignment is optimized as a no-op operation
/// - `Center` and `Right` alignments require width calculation and padding
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust
/// use ansi_align::{Alignment, AlignOptions, ansi_align_with_options};
///
/// let text = "hello\nworld";
///
/// // Center alignment - distributes padding evenly
/// let opts = AlignOptions::new(Alignment::Center);
/// let result = ansi_align_with_options(text, &opts);
/// // Result: " hello\nworld" (hello gets 1 space padding)
///
/// // Right alignment - adds all padding to the left
/// let opts = AlignOptions::new(Alignment::Right);
/// let result = ansi_align_with_options(text, &opts);
/// // Result: " hello\n world" (both lines right-aligned)
///
/// // Left alignment - no changes to input
/// let opts = AlignOptions::new(Alignment::Left);
/// let result = ansi_align_with_options(text, &opts);
/// // Result: "hello\nworld" (unchanged)
/// ```
///
/// ## With Custom Padding
///
/// ```rust
/// use ansi_align::{Alignment, AlignOptions, ansi_align_with_options};
///
/// let text = "short\nlonger";
/// let opts = AlignOptions::new(Alignment::Right).with_pad('.');
/// let result = ansi_align_with_options(text, &opts);
/// // Result: ".short\nlonger"
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Alignment {
    /// Align text to the left (no padding added to the left side)
    Left,
    /// Align text to the center (padding distributed evenly on both sides)
    Center,
    /// Align text to the right (padding added to the left side)
    Right,
}

/// A type-safe wrapper for display width values.
///
/// This type represents the visual width of text as it would appear on a terminal or console,
/// correctly accounting for:
/// - ANSI escape sequences (which have zero display width)
/// - Unicode characters with varying display widths
/// - Multi-byte characters that occupy single or double terminal columns
///
/// The `Width` type prevents common bugs by distinguishing between:
/// - **Byte length**: The number of bytes in a string (`str.len()`)
/// - **Character count**: The number of Unicode scalar values (`str.chars().count()`)
/// - **Display width**: The number of terminal columns occupied when rendered
///
/// # Why Display Width Matters
///
/// Consider these examples:
/// - `"hello"` has 5 bytes, 5 characters, and 5 display width
/// - `"叀叀叀"` has 9 bytes, 3 characters, and 6 display width (CJK characters are wide)
/// - `"\x1b[31mred\x1b[0m"` has 11 bytes, 7 characters, and 3 display width (ANSI codes are invisible)
///
/// # Examples
///
/// ## Basic Usage
///
/// ```rust
/// use ansi_align::Width;
///
/// let width = Width::new(42);
/// assert_eq!(width.get(), 42);
///
/// // Convert from usize
/// let width: Width = 24.into();
/// assert_eq!(width.get(), 24);
/// ```
///
/// ## Comparison and Ordering
///
/// ```rust
/// use ansi_align::Width;
///
/// let small = Width::new(10);
/// let large = Width::new(20);
///
/// assert!(small < large);
/// assert_eq!(Width::new(15), Width::new(15));
///
/// // Can be used in collections
/// let mut widths = vec![Width::new(30), Width::new(10), Width::new(20)];
/// widths.sort();
/// assert_eq!(widths, vec![Width::new(10), Width::new(20), Width::new(30)]);
/// ```
///
/// ## Integration with String Width Calculation
///
/// ```rust
/// use ansi_align::Width;
/// // Note: This example shows the concept, actual width calculation
/// // is done internally by the library
///
/// let display_width = Width::new(5); // Represents 5 terminal columns
/// let padding_needed = 10 - display_width.get(); // 5 columns of padding
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
pub struct Width(usize);

impl Width {
    /// Creates a new `Width` value from a `usize`.
    ///
    /// # Arguments
    ///
    /// * `value` - The display width value
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansi_align::Width;
    ///
    /// let width = Width::new(10);
    /// assert_eq!(width.get(), 10);
    /// ```
    #[must_use]
    pub const fn new(value: usize) -> Self {
        Self(value)
    }

    /// Returns the underlying `usize` value.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansi_align::Width;
    ///
    /// let width = Width::new(42);
    /// assert_eq!(width.get(), 42);
    /// ```
    #[must_use]
    pub const fn get(self) -> usize {
        self.0
    }

    /// Performs saturating subtraction, returning 0 if the result would be negative.
    ///
    /// # Arguments
    ///
    /// * `other` - The `Width` value to subtract
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansi_align::Width;
    ///
    /// let w1 = Width::new(10);
    /// let w2 = Width::new(15);
    /// assert_eq!(w1.saturating_sub(w2).get(), 0); // 10 - 15 = 0 (saturated)
    ///
    /// let w3 = Width::new(20);
    /// assert_eq!(w3.saturating_sub(w1).get(), 10); // 20 - 10 = 10
    /// ```
    #[must_use]
    pub const fn saturating_sub(self, other: Self) -> Self {
        Self(self.0.saturating_sub(other.0))
    }

    /// Returns `true` if the width is zero.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansi_align::Width;
    ///
    /// assert!(Width::new(0).is_zero());
    /// assert!(!Width::new(5).is_zero());
    /// ```
    #[must_use]
    pub const fn is_zero(self) -> bool {
        self.0 == 0
    }
}

impl From<usize> for Width {
    fn from(value: usize) -> Self {
        Self(value)
    }
}

// Arithmetic operations for Width
impl Add for Width {
    type Output = Self;

    /// Adds two `Width` values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansi_align::Width;
    ///
    /// let w1 = Width::new(10);
    /// let w2 = Width::new(5);
    /// assert_eq!((w1 + w2).get(), 15);
    /// ```
    fn add(self, rhs: Self) -> Self::Output {
        Self(self.0 + rhs.0)
    }
}

impl Sub for Width {
    type Output = Self;

    /// Subtracts one `Width` value from another.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansi_align::Width;
    ///
    /// let w1 = Width::new(10);
    /// let w2 = Width::new(5);
    /// assert_eq!((w1 - w2).get(), 5);
    /// ```
    fn sub(self, rhs: Self) -> Self::Output {
        Self(self.0 - rhs.0)
    }
}

impl Mul for Width {
    type Output = Self;

    /// Multiplies two `Width` values.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansi_align::Width;
    ///
    /// let w1 = Width::new(10);
    /// let w2 = Width::new(5);
    /// assert_eq!((w1 * w2).get(), 50);
    /// ```
    fn mul(self, rhs: Self) -> Self::Output {
        Self(self.0 * rhs.0)
    }
}

impl Div for Width {
    type Output = Self;

    /// Divides one `Width` value by another.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansi_align::Width;
    ///
    /// let w1 = Width::new(10);
    /// let w2 = Width::new(5);
    /// assert_eq!((w1 / w2).get(), 2);
    /// ```
    fn div(self, rhs: Self) -> Self::Output {
        Self(self.0 / rhs.0)
    }
}

// Display implementation for Width
impl fmt::Display for Width {
    /// Formats the `Width` value for display.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansi_align::Width;
    ///
    /// let width = Width::new(42);
    /// assert_eq!(format!("{}", width), "42");
    /// ```
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}", self.0)
    }
}

/// Configuration options for text alignment operations.
///
/// This struct provides comprehensive control over text alignment behavior through a fluent
/// builder API. It allows customization of alignment direction, line separators, and padding
/// characters to handle diverse text formatting requirements.
///
/// # Fields
///
/// - **`align`**: The alignment direction ([`Alignment`])
/// - **`split`**: String used to separate lines (default: `"\n"`)
/// - **`pad`**: Character used for padding (default: `' '`)
///
/// # Design Philosophy
///
/// The options struct follows the builder pattern, allowing for method chaining and
/// readable configuration. All methods return `Self`, enabling fluent composition:
///
/// ```rust
/// use ansi_align::{AlignOptions, Alignment};
///
/// let opts = AlignOptions::new(Alignment::Center)
///     .with_split("|")
///     .with_pad('_');
/// ```
///
/// # Common Use Cases
///
/// ## Standard Text Alignment
///
/// ```rust
/// use ansi_align::{AlignOptions, Alignment, ansi_align_with_options};
///
/// let text = "Line 1\nLonger Line 2\nShort";
/// let opts = AlignOptions::new(Alignment::Center);
/// let result = ansi_align_with_options(text, &opts);
/// ```
///
/// ## Custom Line Separators
///
/// ```rust
/// use ansi_align::{AlignOptions, Alignment, ansi_align_with_options};
///
/// // Pipe-separated data
/// let data = "Name|Age|Location";
/// let opts = AlignOptions::new(Alignment::Center).with_split("|");
/// let result = ansi_align_with_options(data, &opts);
///
/// // Multi-character separators
/// let data = "Part1<->Part2<->Part3";
/// let opts = AlignOptions::new(Alignment::Right).with_split("<->");
/// let result = ansi_align_with_options(data, &opts);
/// ```
///
/// ## Custom Padding Characters
///
/// ```rust
/// use ansi_align::{AlignOptions, Alignment, ansi_align_with_options};
///
/// // Dot padding for visual emphasis
/// let text = "Title\nSubtitle";
/// let opts = AlignOptions::new(Alignment::Right).with_pad('.');
/// let result = ansi_align_with_options(text, &opts);
/// // Result: "..Title\nSubtitle"
///
/// // Zero padding for numeric alignment
/// let numbers = "1\n42\n123";
/// let opts = AlignOptions::new(Alignment::Right).with_pad('0');
/// let result = ansi_align_with_options(numbers, &opts);
/// // Result: "001\n042\n123"
/// ```
///
/// ## Complex Configurations
///
/// ```rust
/// use ansi_align::{AlignOptions, Alignment, ansi_align_with_options};
///
/// // Table-like data with custom formatting
/// let table_row = "ID|Name|Status";
/// let opts = AlignOptions::new(Alignment::Center)
///     .with_split("|")
///     .with_pad('_');
/// let result = ansi_align_with_options(table_row, &opts);
/// ```
///
/// # Performance Considerations
///
/// - Options are designed to be lightweight and cheap to clone
/// - The builder pattern methods are `const fn` where possible for compile-time optimization
/// - String splitting is performed only once during alignment processing
#[derive(Debug, Clone)]
pub struct AlignOptions {
    /// The alignment type (left, center, right)
    pub align: Alignment,
    /// The string to split lines on (default: "\n")
    pub split: String,
    /// The padding character to use (default: " ")
    pub pad: char,
}

impl Default for AlignOptions {
    fn default() -> Self {
        Self {
            align: Alignment::Center,
            split: "\n".to_string(),
            pad: ' ',
        }
    }
}

impl AlignOptions {
    /// Creates new alignment options with the specified alignment direction.
    ///
    /// Uses default values for split string (`"\n"`) and padding character (`' '`).
    ///
    /// # Arguments
    ///
    /// * `align` - The alignment direction to use
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansi_align::{AlignOptions, Alignment};
    ///
    /// let opts = AlignOptions::new(Alignment::Center);
    /// ```
    #[must_use]
    pub fn new(align: Alignment) -> Self {
        Self {
            align,
            ..Default::default()
        }
    }

    /// Sets the string used to split lines using the builder pattern.
    ///
    /// By default, lines are split on `"\n"`, but you can specify any string
    /// as a line separator.
    ///
    /// # Arguments
    ///
    /// * `split` - The string to use as a line separator
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansi_align::{AlignOptions, Alignment};
    ///
    /// let opts = AlignOptions::new(Alignment::Center)
    ///     .with_split("|")
    ///     .with_split("<->"); // Multi-character separators work too
    /// ```
    #[must_use]
    pub fn with_split<S: Into<String>>(mut self, split: S) -> Self {
        self.split = split.into();
        self
    }

    /// Sets the character used for padding using the builder pattern.
    ///
    /// By default, spaces (`' '`) are used for padding, but you can specify
    /// any character.
    ///
    /// # Arguments
    ///
    /// * `pad` - The character to use for padding
    ///
    /// # Examples
    ///
    /// ```rust
    /// use ansi_align::{AlignOptions, Alignment};
    ///
    /// let opts = AlignOptions::new(Alignment::Right)
    ///     .with_pad('.');
    /// ```
    #[must_use]
    pub const fn with_pad(mut self, pad: char) -> Self {
        self.pad = pad;
        self
    }
}

/// Efficiently create padding string for alignment
fn create_padding(pad_char: char, count: usize) -> String {
    match count {
        0 => String::new(),
        1 => pad_char.to_string(),
        // Use repeat for small counts (more efficient)
        2..=16 => pad_char.to_string().repeat(count),
        // Use with_capacity + push for larger counts to avoid reallocations
        _ => {
            let mut padding = String::with_capacity(count * pad_char.len_utf8());
            for _ in 0..count {
                padding.push(pad_char);
            }
            padding
        }
    }
}

/// Align text with center alignment (default behavior)
#[must_use]
pub fn ansi_align(text: &str) -> String {
    ansi_align_with_options(text, &AlignOptions::default())
}

/// Calculate display widths for lines
fn calculate_line_widths<'a>(text: &'a str, split: &str) -> Vec<(&'a str, Width)> {
    text.split(split)
        .map(|line| (line, Width::from(string_width(line))))
        .collect()
}

/// Find the maximum width among lines
fn find_max_width(line_data: &[(&str, Width)]) -> Width {
    line_data
        .iter()
        .map(|(_, width)| *width)
        .max()
        .unwrap_or(Width::new(0))
}

/// Apply alignment to a single line
fn align_line(
    line: &str,
    line_width: Width,
    max_width: Width,
    alignment: Alignment,
    pad_char: char,
) -> String {
    let padding_needed = match alignment {
        Alignment::Left => 0,
        Alignment::Center => (max_width.get() - line_width.get()) / 2,
        Alignment::Right => max_width.get() - line_width.get(),
    };

    if padding_needed == 0 {
        line.to_string()
    } else {
        let mut result = create_padding(pad_char, padding_needed);
        result.push_str(line);
        result
    }
}

/// Aligns text with comprehensive support for ANSI escape sequences and Unicode characters.
///
/// This is the core alignment function that provides full customization through [`AlignOptions`].
/// It correctly handles complex text containing ANSI escape sequences, Unicode characters,
/// and custom formatting requirements while maintaining optimal performance.
///
/// # Algorithm Overview
///
/// 1. **Input validation**: Handle empty strings and edge cases
/// 2. **Left alignment optimization**: Return input unchanged for left alignment
/// 3. **Width calculation**: Single-pass analysis to determine display widths
/// 4. **Alignment processing**: Apply padding based on alignment strategy
/// 5. **Output reconstruction**: Join aligned lines with original separator
///
/// # Supported Text Features
///
/// - **ANSI escape sequences**: Colors, formatting, cursor control
/// - **Unicode characters**: Including CJK, emojis, and combining characters
/// - **Mixed content**: Text with both ANSI codes and Unicode
/// - **Custom separators**: Any string can be used as a line delimiter
/// - **Flexible padding**: Any character for padding alignment gaps
///
/// # Examples
///
/// ```
/// use ansi_align::{ansi_align, ansi_align_with_options, Alignment, AlignOptions};
///
/// // Basic center alignment
/// let result = ansi_align("hello\nworld");
///
/// // Right alignment with custom padding
/// let opts = AlignOptions::new(Alignment::Right).with_pad('.');
/// let result = ansi_align_with_options("hi\nhello", &opts);
///
/// // Works with ANSI escape sequences
/// let colored = "\x1b[31mred\x1b[0m\n\x1b[32mgreen\x1b[0m";
/// let result = ansi_align_with_options(colored, &AlignOptions::new(Alignment::Center));
/// ```
///
/// # Performance
///
/// This function makes a single pass through the input text for optimal performance.
/// For left alignment, it returns the input unchanged as an optimization.
#[must_use]
pub fn ansi_align_with_options(text: &str, opts: &AlignOptions) -> String {
    if text.is_empty() || opts.align == Alignment::Left {
        return text.to_string();
    }

    let line_data = calculate_line_widths(text, &opts.split);
    let max_width = find_max_width(&line_data);

    let aligned_lines: Vec<String> = line_data
        .into_iter()
        .map(|(line, width)| align_line(line, width, max_width, opts.align, opts.pad))
        .collect();

    aligned_lines.join(&opts.split)
}

/// Align text to the left (no-op, returns original text)
#[must_use]
pub fn left(text: &str) -> String {
    ansi_align_with_options(text, &AlignOptions::new(Alignment::Left))
}

/// Align text to the center
#[must_use]
pub fn center(text: &str) -> String {
    ansi_align_with_options(text, &AlignOptions::new(Alignment::Center))
}

/// Align text to the right
#[must_use]
pub fn right(text: &str) -> String {
    ansi_align_with_options(text, &AlignOptions::new(Alignment::Right))
}

#[cfg(test)]
mod tests {
    use super::*;

    // Basic alignment tests
    #[test]
    fn test_left_alignment() {
        let text = "hello\nworld";
        let result = left(text);
        assert_eq!(result, text); // Left alignment should be no-op
    }

    #[test]
    fn test_center_alignment() {
        let text = "hi\nhello";
        let result = center(text);
        let lines: Vec<&str> = result.split('\n').collect();
        assert_eq!(lines[0], " hi"); // 1 space padding for "hi"
        assert_eq!(lines[1], "hello"); // No padding for "hello"
    }

    #[test]
    fn test_right_alignment() {
        let text = "hi\nhello";
        let result = right(text);
        let lines: Vec<&str> = result.split('\n').collect();
        assert_eq!(lines[0], "   hi"); // 3 spaces padding for "hi"
        assert_eq!(lines[1], "hello"); // No padding for "hello"
    }

    // Unicode and ANSI tests
    #[test]
    fn test_unicode_characters() {
        let text = "叀\n叀叀叀";
        let result = center(text);
        let lines: Vec<&str> = result.split('\n').collect();
        assert_eq!(lines[0], "  叀"); // 2 spaces padding (CJK char is width 2)
        assert_eq!(lines[1], "叀叀叀"); // No padding
    }

    #[test]
    fn test_ansi_escape_sequences() {
        let text = "hello\n\u{001B}[1mworld\u{001B}[0m";
        let result = center(text);
        let lines: Vec<&str> = result.split('\n').collect();
        assert_eq!(lines[0], "hello");
        assert_eq!(lines[1], "\u{001B}[1mworld\u{001B}[0m"); // ANSI codes preserved
    }

    #[test]
    fn test_complex_ansi_sequences() {
        // Test with multiple ANSI codes and colors
        let text = "\x1b[31m\x1b[1mred\x1b[0m\n\x1b[32mgreen text\x1b[0m";
        let result = right(text);
        let lines: Vec<&str> = result.split('\n').collect();
        // "red" has display width 3, "green text" has width 10
        assert_eq!(lines[0], "       \x1b[31m\x1b[1mred\x1b[0m"); // 7 spaces padding
        assert_eq!(lines[1], "\x1b[32mgreen text\x1b[0m"); // No padding
    }

    // Edge cases
    #[test]
    fn test_empty_string() {
        assert_eq!(ansi_align_with_options("", &AlignOptions::default()), "");
        assert_eq!(left(""), "");
        assert_eq!(center(""), "");
        assert_eq!(right(""), "");
    }

    #[test]
    fn test_single_line() {
        let text = "hello";
        assert_eq!(left(text), "hello");
        assert_eq!(center(text), "hello");
        assert_eq!(right(text), "hello");
    }

    #[test]
    fn test_single_character() {
        let text = "a\nb";
        let result = center(text);
        assert_eq!(result, "a\nb"); // Both lines same width, no padding needed
    }

    #[test]
    fn test_whitespace_only() {
        let text = "   \n ";
        let result = center(text);
        let lines: Vec<&str> = result.split('\n').collect();
        assert_eq!(lines[0], "   "); // 3 spaces, no padding needed
        assert_eq!(lines[1], "  "); // 1 space + 1 padding space
    }

    // Custom options tests
    #[test]
    fn test_custom_split_and_pad() {
        let text = "a|bb";
        let opts = AlignOptions::new(Alignment::Right)
            .with_split("|")
            .with_pad('.');
        let result = ansi_align_with_options(text, &opts);
        assert_eq!(result, ".a|bb");
    }

    #[test]
    fn test_custom_split_multichar() {
        let text = "short<->very long line";
        let opts = AlignOptions::new(Alignment::Center).with_split("<->");
        let result = ansi_align_with_options(text, &opts);
        assert_eq!(result, "    short<->very long line");
    }

    #[test]
    fn test_different_padding_chars() {
        let text = "hi\nhello";

        // Test dot padding
        let opts = AlignOptions::new(Alignment::Right).with_pad('.');
        let result = ansi_align_with_options(text, &opts);
        assert_eq!(result, "...hi\nhello");

        // Test underscore padding
        let opts = AlignOptions::new(Alignment::Center).with_pad('_');
        let result = ansi_align_with_options(text, &opts);
        assert_eq!(result, "_hi\nhello");

        // Test zero padding
        let opts = AlignOptions::new(Alignment::Right).with_pad('0');
        let result = ansi_align_with_options(text, &opts);
        assert_eq!(result, "000hi\nhello");
    }

    // Performance and memory optimization tests
    #[test]
    fn test_large_padding() {
        let text = format!("a\n{}", "b".repeat(100));
        let result = right(&text);
        let lines: Vec<&str> = result.split('\n').collect();
        assert_eq!(lines[0].len(), 100); // 99 spaces + "a"
        assert!(lines[0].starts_with(&" ".repeat(99)));
        assert!(lines[0].ends_with('a'));
        assert_eq!(lines[1], "b".repeat(100));
    }

    #[test]
    fn test_no_padding_optimization() {
        // Test that lines requiring no padding are handled efficiently
        let text = "same\nsame\nsame";
        let result = center(text);
        assert_eq!(result, text); // Should be unchanged
    }

    // Width type tests
    #[test]
    fn test_width_type() {
        let width = Width::new(42);
        assert_eq!(width.get(), 42);

        let width_from_usize: Width = 24.into();
        assert_eq!(width_from_usize.get(), 24);

        // Test ordering
        assert!(Width::new(10) < Width::new(20));
        assert_eq!(Width::new(15), Width::new(15));
    }

    // Width type tests
    #[test]
    fn test_width_arithmetic() {
        let w1 = Width::new(10);
        let w2 = Width::new(5);

        // Test addition
        assert_eq!((w1 + w2).get(), 15);

        // Test subtraction
        assert_eq!((w1 - w2).get(), 5);

        // Test multiplication
        assert_eq!((w1 * w2).get(), 50);

        // Test division
        assert_eq!((w1 / w2).get(), 2);

        // Test saturating subtraction
        assert_eq!(w2.saturating_sub(w1).get(), 0); // 5 - 10 = 0 (saturated)
        assert_eq!(w1.saturating_sub(w2).get(), 5); // 10 - 5 = 5

        // Test is_zero
        assert!(Width::new(0).is_zero());
        assert!(!w1.is_zero());
    }

    #[test]
    fn test_width_display() {
        let width = Width::new(42);
        assert_eq!(format!("{width}"), "42");
        assert_eq!(format!("{}", Width::new(0)), "0");
        assert_eq!(format!("{}", Width::new(999)), "999");
    }

    // Comprehensive alignment scenarios
    #[test]
    fn test_mixed_width_lines() {
        let text = "a\nbb\nccc\ndddd\neeeee";

        // Center alignment
        let result = center(text);
        let lines: Vec<&str> = result.split('\n').collect();

        // The longest line is "eeeee" with 5 chars
        // So padding for center should be: (5-1)/2=2, (5-2)/2=1, (5-3)/2=1, (5-4)/2=0, (5-5)/2=0
        assert_eq!(lines[0], "  a"); // 2 spaces + "a"
        assert_eq!(lines[1], " bb"); // 1 space + "bb"
        assert_eq!(lines[2], " ccc"); // 1 space + "ccc" (corrected)
        assert_eq!(lines[3], "dddd"); // no padding (corrected)
        assert_eq!(lines[4], "eeeee"); // no padding

        // Right alignment
        let result = right(text);
        let lines: Vec<&str> = result.split('\n').collect();
        assert_eq!(lines[0], "    a"); // 4 spaces + "a"
        assert_eq!(lines[1], "   bb"); // 3 spaces + "bb"
        assert_eq!(lines[2], "  ccc"); // 2 spaces + "ccc"
        assert_eq!(lines[3], " dddd"); // 1 space + "dddd"
        assert_eq!(lines[4], "eeeee"); // no padding
    }

    #[test]
    fn test_center_odd_padding() {
        // Test center alignment with odd padding amounts
        let text = "a\nbbbb";
        let result = center(text);
        let lines: Vec<&str> = result.split('\n').collect();
        assert_eq!(lines[0], " a"); // (4-1)/2 = 1 space
        assert_eq!(lines[1], "bbbb"); // no padding
    }

    #[test]
    fn test_multiline_with_empty_lines() {
        let text = "hello\n\nworld";
        let result = center(text);
        let lines: Vec<&str> = result.split('\n').collect();
        assert_eq!(lines[0], "hello");
        assert_eq!(lines[1], "  "); // 2 spaces for empty line (center of 5-char width)
        assert_eq!(lines[2], "world");
    }

    // Regression tests for performance improvements
    #[test]
    fn test_no_unnecessary_allocations() {
        // This test ensures we don't regress on the performance improvements
        let text = "line1\nline2\nline3";
        let result = left(text);
        // Left alignment should return original string (no allocations for processing)
        assert_eq!(result, text);
    }

    #[test]
    fn test_padding_efficiency() {
        // Test the efficient padding creation for different sizes
        let text = format!("a\n{}", "b".repeat(20));

        // Small padding (should use repeat)
        let opts = AlignOptions::new(Alignment::Right);
        let result = ansi_align_with_options("a\nbb", &opts);
        assert_eq!(result, " a\nbb");

        // Large padding (should use with_capacity)
        let result = ansi_align_with_options(&text, &opts);
        let lines: Vec<&str> = result.split('\n').collect();
        assert_eq!(lines[0].len(), 20); // 19 spaces + "a"
        assert!(lines[0].ends_with('a'));
    }

    #[test]
    fn test_create_padding_unicode() {
        // Test padding with Unicode characters
        let text = "a\nbb";
        let opts = AlignOptions::new(Alignment::Right).with_pad('β€’');
        let result = ansi_align_with_options(text, &opts);
        assert_eq!(result, "β€’a\nbb");

        // Test with multi-byte Unicode character
        let opts = AlignOptions::new(Alignment::Right).with_pad('🎯');
        let result = ansi_align_with_options(text, &opts);
        assert_eq!(result, "🎯a\nbb");
    }

    // Integration tests
    #[test]
    fn test_real_world_scenario() {
        // Simulate aligning a simple table or menu
        let menu = "Home\nAbout Us\nContact\nServices";
        let result = center(menu);
        let lines: Vec<&str> = result.split('\n').collect();

        // "About Us" and "Services" are both 8 chars (longest)
        assert_eq!(lines[0], "  Home"); // 2 spaces (8-4)/2 = 2
        assert_eq!(lines[1], "About Us"); // no padding (8 chars)
        assert_eq!(lines[2], "Contact"); // no padding - "Contact" is 7 chars, (8-7)/2 = 0
        assert_eq!(lines[3], "Services"); // no padding (8 chars)
    }

    #[test]
    fn test_code_alignment() {
        // Test aligning code-like content
        let code = "if x:\n    return y\nelse:\n    return z";
        let result = right(code);
        let lines: Vec<&str> = result.split('\n').collect();

        // "    return y" and "    return z" are longest at 12 chars
        assert_eq!(lines[0], "       if x:"); // 7 spaces + "if x:" (12-5=7)
        assert_eq!(lines[1], "    return y"); // no padding (12 chars)
        assert_eq!(lines[2], "       else:"); // 7 spaces + "else:" (12-5=7)
        assert_eq!(lines[3], "    return z"); // no padding (12 chars)
    }
}