pub fn size<S: AsRef<str>>(src: S) -> [usize; 2]Expand description
Returns the size of the text in src as a [ width, height ] array.
This function calculates the dimensions of the input text, where the width is defined as the length of the longest line, and the height is the total number of lines. It handles various edge cases, including empty strings and strings with trailing newlines, to ensure accurate dimension calculation.
§Arguments
src- A string slice or any type that can be referenced as a string. This allows for flexibility in passing different string-like types.
§Returns
A [usize; 2] array representing the dimensions of the text:
width: The length of the longest line in the text.height: The total number of lines in the text.
§Nuances
- Empty Strings: If the input string is empty, the function returns
[0, 1]because there is one line with a width of zero. - Trailing Newlines: If the input string ends with a newline character, it is treated as having an additional empty line at the end.
- Empty Lines: Empty lines within the text are counted as lines with a width of zero.
§Examples
let text = "Hello\nWorld\nThis is a test";
let dimensions = format_tools::string::size( text );
assert_eq!( dimensions, [ 14, 3 ] );In this example, the function returns [ 14, 3 ] because the longest line ( “This is a test” )
has 14 characters, and there are 3 lines in total.
let text = "";
let dimensions = format_tools::string::size( text );
assert_eq!( dimensions, [ 0, 1 ] );Here, the function returns [0, 1] because the input is an empty string, which is considered
as a single line with zero width.
let text = "Line 1\n\nLine 3\n";
let dimensions = format_tools::string::size( text );
assert_eq!( dimensions, [ 6, 4 ] );In this example, the function returns [ 6, 4 ] because the longest line ( “Line 1” or “Line 3” )
has 6 characters, there are 4 lines in total, including the empty line and the trailing newline.