strs_tools 0.49.1

Tools to manipulate strings.
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
//! ANSI-aware truncation utilities
//!
//! Provides utilities for truncating text while preserving ANSI formatting.

extern crate alloc;

use alloc::string::{ String, ToString };
use super::{ Segment, parse_segments };
use super::strip::strip;

/// Configuration options for ANSI-aware truncation.
///
/// # Examples
///
/// ```rust
/// # #[ cfg( feature = "ansi" ) ]
/// # {
/// use strs_tools::ansi::TruncateOptions;
///
/// let opts = TruncateOptions::new( 10 )
///   .with_suffix( "..." )
///   .with_reset( true );
/// # }
/// ```
#[ derive( Debug, Clone, PartialEq, Eq ) ]
pub struct TruncateOptions
{
  /// Maximum visible width (excluding ANSI codes)
  pub max_width : usize,
  /// Suffix to append when truncated (e.g., "...", "…")
  pub suffix : Option< String >,
  /// Whether to append reset code after truncation
  pub append_reset : bool,
}

impl TruncateOptions
{
  /// Create new truncation options with specified max width.
  ///
  /// # Arguments
  ///
  /// * `max_width` - Maximum visible character width
  ///
  /// # Panics
  ///
  /// Panics if `max_width` is 0 (Architectural Principle: Panic on Invalid Configuration).
  pub fn new( max_width : usize ) -> Self
  {
    assert!( max_width != 0, "TruncateOptions: max_width must be greater than 0" );

    Self
    {
      max_width,
      suffix : None,
      append_reset : false,
    }
  }

  /// Set the suffix to append when truncated.
  ///
  /// # Arguments
  ///
  /// * `suffix` - String to append (e.g., "...", "…")
  pub fn with_suffix( mut self, suffix : impl Into< String > ) -> Self
  {
    self.suffix = Some( suffix.into() );
    self
  }

  /// Set whether to append ANSI reset code after truncation.
  ///
  /// # Arguments
  ///
  /// * `reset` - If true, append `\x1b[0m` after truncation
  pub fn with_reset( mut self, reset : bool ) -> Self
  {
    self.append_reset = reset;
    self
  }
}

impl Default for TruncateOptions
{
  fn default() -> Self
  {
    Self
    {
      max_width : 80,
      suffix : None,
      append_reset : false,
    }
  }
}

/// Truncate text to max width while preserving ANSI codes (char-based, Tier 1).
///
/// # Arguments
///
/// * `text` - Input text potentially containing ANSI escape sequences
/// * `options` - Truncation configuration
///
/// # Returns
///
/// Truncated string with ANSI codes preserved.
///
/// # Examples
///
/// ```rust
/// # #[ cfg( feature = "ansi" ) ]
/// # {
/// use strs_tools::ansi::{ truncate, TruncateOptions };
///
/// let opts = TruncateOptions::new( 5 );
/// assert_eq!( truncate( "hello world", &opts ), "hello" );
///
/// // With suffix
/// let opts = TruncateOptions::new( 8 ).with_suffix( "..." );
/// assert_eq!( truncate( "hello world", &opts ), "hello..." );
///
/// // ANSI codes preserved
/// let opts = TruncateOptions::new( 3 ).with_reset( true );
/// assert_eq!( truncate( "\x1b[31mhello\x1b[0m", &opts ), "\x1b[31mhel\x1b[0m" );
/// # }
/// ```
///
/// # Performance
///
/// - Time complexity: O(n)
/// - Benchmark: ~10µs/KB on modern hardware
pub fn truncate( text : &str, options : &TruncateOptions ) -> String
{
  truncate_internal( text, options, &CharCounter )
}

/// Truncate text to max width while preserving ANSI codes (grapheme-based, Tier 2).
///
/// Uses Unicode grapheme clusters for accurate truncation of
/// CJK characters, emoji, and combining marks.
///
/// # Arguments
///
/// * `text` - Input text potentially containing ANSI escape sequences
/// * `options` - Truncation configuration
///
/// # Returns
///
/// Truncated string with ANSI codes preserved.
///
/// # Examples
///
/// ```rust
/// # #[ cfg( all( feature = "ansi_unicode" ) ) ]
/// # {
/// use strs_tools::ansi::{ truncate_unicode, TruncateOptions };
///
/// let opts = TruncateOptions::new( 3 );
///
/// // Grapheme-aware: emoji with modifier counts as 1
/// assert_eq!( truncate_unicode( "👋🏽ab", &opts ), "👋🏽ab" );
/// # }
/// ```
#[ cfg( feature = "ansi_unicode" ) ]
pub fn truncate_unicode( text : &str, options : &TruncateOptions ) -> String
{
  truncate_internal( text, options, &GraphemeCounter )
}

/// Truncate ANSI text only if it exceeds maximum width.
///
/// Unlike `truncate()` which unconditionally reserves space for the suffix,
/// this function first checks if truncation is needed by comparing
/// `visual_len(text)` with `max_width`. Only truncates when text genuinely
/// exceeds the limit.
///
/// # Bug Fix
///
/// This function prevents incorrect truncation of text that fits exactly
/// within the width limit. For example, "hello" (5 visible chars) with
/// `max_width=5` returns "hello" unchanged, not "hell→".
///
/// # Arguments
///
/// * `text` - Input text potentially containing ANSI escape sequences
/// * `max_width` - Maximum visible character width
/// * `options` - Truncation configuration (suffix, reset behavior)
///
/// # Returns
///
/// Original text if it fits, truncated text if it exceeds max_width.
///
/// # Examples
///
/// ```rust
/// # #[ cfg( feature = "ansi" ) ]
/// # {
/// use strs_tools::ansi::{ truncate_if_needed, TruncateOptions };
///
/// let opts = TruncateOptions::new( 5 ).with_suffix( "→" );
///
/// // Fits exactly - no truncation
/// assert_eq!( truncate_if_needed( "hello", 5, &opts ), "hello" );
///
/// // Exceeds limit - truncated
/// let result = truncate_if_needed( "hello world", 5, &opts );
/// assert!( result.contains( "→" ) );
///
/// // ANSI codes don't count toward width
/// let ansi_text = "\x1b[31mhello\x1b[0m";
/// assert!( truncate_if_needed( ansi_text, 5, &opts ).contains( "hello" ) );
/// # }
/// ```
///
/// # Performance
///
/// - Time complexity: O(n)
/// - Only performs truncation when necessary
/// - Single width calculation per call
pub fn truncate_if_needed( text : &str, max_width : usize, options : &TruncateOptions ) -> String
{
  truncate_if_needed_internal( text, max_width, options, &CharCounter )
}

/// Unicode-aware version of `truncate_if_needed()`.
///
/// Uses grapheme clusters for accurate width calculation of CJK characters,
/// emoji, and combining marks.
#[ cfg( feature = "ansi_unicode" ) ]
pub fn truncate_if_needed_unicode( text : &str, max_width : usize, options : &TruncateOptions ) -> String
{
  truncate_if_needed_internal( text, max_width, options, &GraphemeCounter )
}

fn truncate_if_needed_internal< C : VisibleCounter >(
  text : &str,
  max_width : usize,
  options : &TruncateOptions,
  counter : &C
) -> String
{
  // Fix(bug-width-truncation): Check boundary before truncating
  //
  // Root cause: truncate() reserves space for suffix within max_width,
  // so calling it unconditionally truncates text that fits exactly.
  //
  // Pitfall: Always validate width boundary before calling truncate().
  // Don't assume truncate() handles this internally.

  let visible_width = counter.count( &strip( text ) );

  if visible_width > max_width
  {
    truncate_internal( text, options, counter )
  }
  else
  {
    text.to_string()
  }
}

/// Truncate each line in a text block to maximum width.
///
/// Applies `truncate_if_needed()` to each line independently, tracking
/// whether any line required truncation. Returns both the processed text
/// and a boolean flag indicating if truncation occurred.
///
/// # Arguments
///
/// * `text` - Multi-line text potentially containing ANSI escape sequences
/// * `max_width` - Maximum visible character width per line
/// * `options` - Truncation configuration
///
/// # Returns
///
/// Tuple of (processed_text, any_line_truncated).
///
/// # Examples
///
/// ```rust
/// # #[ cfg( feature = "ansi" ) ]
/// # {
/// use strs_tools::ansi::{ truncate_lines, TruncateOptions };
///
/// let text = "short\nthis is a very long line\nmedium";
/// let opts = TruncateOptions::new( 10 ).with_suffix( "→" );
///
/// let ( result, truncated ) = truncate_lines( text, 10, &opts );
/// assert!( truncated ); // Long line was truncated
///
/// let lines : Vec< &str > = result.lines().collect();
/// assert!( lines[ 0 ].contains( "short" ) );
/// assert!( lines[ 1 ].contains( "→" ) ); // Truncation indicator
/// # }
/// ```
///
/// # Performance
///
/// - Time complexity: O(n × m) where n is text length, m is average line count
/// - Single-pass processing
/// - Minimal allocations (one String per line)
pub fn truncate_lines( text : &str, max_width : usize, options : &TruncateOptions ) -> ( String, bool )
{
  truncate_lines_internal( text, max_width, options, &CharCounter )
}

/// Unicode-aware version of `truncate_lines()`.
#[ cfg( feature = "ansi_unicode" ) ]
pub fn truncate_lines_unicode( text : &str, max_width : usize, options : &TruncateOptions ) -> ( String, bool )
{
  truncate_lines_internal( text, max_width, options, &GraphemeCounter )
}

fn truncate_lines_internal< C : VisibleCounter >(
  text : &str,
  max_width : usize,
  options : &TruncateOptions,
  counter : &C
) -> ( String, bool )
{
  let mut any_truncated = false;

  let lines : alloc::vec::Vec< String > = text
    .lines()
    .map( | line |
    {
      let visible_width = counter.count( &strip( line ) );

      if visible_width > max_width
      {
        any_truncated = true;
        truncate_internal( line, options, counter )
      }
      else
      {
        line.to_string()
      }
    } )
    .collect();

  ( lines.join( "\n" ), any_truncated )
}

// ==================== Internal Implementation ====================

/// Trait for counting visible units (chars or graphemes).
trait VisibleCounter
{
  /// Count visible units in text.
  fn count( &self, text : &str ) -> usize;

  /// Take first N visible units from text.
  fn take_first< 'a >( &self, text : &'a str, n : usize ) -> &'a str;
}

/// Char-based counter (Tier 1).
struct CharCounter;

impl VisibleCounter for CharCounter
{
  fn count( &self, text : &str ) -> usize
  {
    text.chars().count()
  }

  fn take_first< 'a >( &self, text : &'a str, n : usize ) -> &'a str
  {
    let end = text
      .char_indices()
      .nth( n )
      .map_or( text.len(), | ( idx, _ ) | idx );
    &text[ ..end ]
  }
}

/// Grapheme-based counter (Tier 2).
#[ cfg( feature = "ansi_unicode" ) ]
struct GraphemeCounter;

#[ cfg( feature = "ansi_unicode" ) ]
impl VisibleCounter for GraphemeCounter
{
  fn count( &self, text : &str ) -> usize
  {
    use unicode_segmentation::UnicodeSegmentation;
    text.graphemes( true ).count()
  }

  fn take_first< 'a >( &self, text : &'a str, n : usize ) -> &'a str
  {
    use unicode_segmentation::UnicodeSegmentation;

    let mut end = 0;
    for ( idx, grapheme ) in text.grapheme_indices( true ).take( n )
    {
      end = idx + grapheme.len();
    }
    &text[ ..end ]
  }
}

/// Internal truncation implementation using generic counter.
fn truncate_internal< C : VisibleCounter >(
  text : &str,
  options : &TruncateOptions,
  counter : &C,
) -> String
{
  let segments = parse_segments( text );

  // Calculate suffix length
  let suffix_len = options.suffix.as_ref().map_or( 0, | s | counter.count( s ) );

  // If suffix is longer than max_width, we can't use it
  let ( effective_max, use_suffix ) = if suffix_len >= options.max_width
  {
    ( options.max_width, false )
  }
  else
  {
    ( options.max_width - suffix_len, true )
  };

  let mut result = String::new();
  let mut visible_count = 0;
  let mut truncated = false;

  for segment in segments
  {
    match segment
    {
      Segment::Ansi( code ) =>
      {
        // Always include ANSI codes
        result.push_str( code );
      }
      Segment::Text( text_content ) =>
      {
        let text_len = counter.count( text_content );

        if visible_count + text_len <= effective_max
        {
          // Fits entirely
          result.push_str( text_content );
          visible_count += text_len;
        }
        else if visible_count < effective_max
        {
          // Partial fit - truncate
          let remaining = effective_max - visible_count;
          let truncated_text = counter.take_first( text_content, remaining );
          result.push_str( truncated_text );
          truncated = true;
          break;
        }
        else
        {
          // No more room
          truncated = true;
          break;
        }
      }
    }
  }

  // Append suffix if truncated, suffix configured, and suffix fits
  if truncated && use_suffix
  {
    if let Some( ref suffix ) = options.suffix
    {
      result.push_str( suffix );
    }
  }

  // Append reset if configured
  if options.append_reset
  {
    result.push_str( "\x1b[0m" );
  }

  result
}