11extern crate unicode_width;
22use unicode_width:: UnicodeWidthStr ;
33
4- // Function to pad a string to a specified width with spaces
54fn pad_string ( input : & str , width : usize ) -> String {
65 let length = UnicodeWidthStr :: width ( input) ;
76 if length >= width {
@@ -12,47 +11,39 @@ fn pad_string(input: &str, width: usize) -> String {
1211 }
1312}
1413
15- // Define a function to create a Markdown table from a vector of rows with formatting for Discord.
1614pub fn create_discord_markdown_table ( rows : Vec < Vec < String > > ) -> String {
1715 let mut result = String :: new ( ) ;
1816
1917 if rows. is_empty ( ) {
2018 return result;
2119 }
2220
23- // Determine the number of columns from the first row
2421 let columns = rows[ 0 ] . len ( ) ;
2522
26- // Find the maximum width for each column
2723 let mut max_widths = vec ! [ 0 ; columns] ;
2824 for row in & rows {
2925 for ( index, cell) in row. iter ( ) . enumerate ( ) {
3026 max_widths[ index] =
3127 std:: cmp:: max ( max_widths[ index] , UnicodeWidthStr :: width ( cell. as_str ( ) ) + 2 ) ;
32- // Adjust for proper Unicode width
3328 }
3429 }
3530
36- // Create the header separator
3731 let header_separator: Vec < String > = max_widths. iter ( ) . map ( |& width| "-" . repeat ( width) ) . collect ( ) ;
3832
39- // Process each row, padding each cell to the max width of its column
4033 for ( i, row) in rows. iter ( ) . enumerate ( ) {
4134 let padded_row: Vec < String > = row
4235 . iter ( )
4336 . enumerate ( )
4437 . map ( |( index, cell) | pad_string ( cell, max_widths[ index] ) )
4538 . collect ( ) ;
4639
47- // Add row to the result
4840 result. push_str ( & format ! ( "|{}|\n " , padded_row. join( "|" ) ) ) ;
4941
50- // Add the header separator after the first row (header)
5142 if i == 0 {
5243 result. push_str ( & format ! ( "|{}|\n " , header_separator. join( "|" ) ) ) ;
5344 }
5445 }
5546
56- // Encapsulate in a monospace code block for Discord
47+ // Wrap in a fenced code block so Discord renders it monospaced.
5748 format ! ( "```\n {result}\n ```" )
5849}
0 commit comments