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
use itertools::Itertools;
use std::cmp;
use unicode_width::*;

/// Represents pane.  lines are the content of the pane and width is the width with which you want
/// to display the content.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Pane<'a> {
    pub lines: &'a [&'a str],
    pub width: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct WrappedPane {
    lines: Vec<WrappedLine>,
    width: usize,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct WrappedLine {
    wrapped_lines_in_line: Vec<String>,
    width: usize,
}

impl WrappedLine {
    fn new(width: usize) -> WrappedLine {
        WrappedLine {
            wrapped_lines_in_line: Vec::new(),
            width,
        }
    }
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct LineWise {
    lines_in_panes_in_line: Vec<WrappedLine>,
}

#[derive(Debug, Clone, PartialEq, Eq)]
struct MergedLine(WrappedLine);

fn map_collect<T: IntoIterator, U, F: FnMut(T::Item) -> U>(iter: T, f: F) -> Vec<U> {
    iter.into_iter().map(f).collect()
}

/// Returns the merged string.
pub fn splitv(panes: &[Pane], delims: &[&str]) -> Vec<String> {
    assert_eq!(
        panes.len(),
        delims.len() + 1,
        "The number of delimiters is incorrect."
    );

    let wrapped_panes = map_collect(panes, wrap_pane);
    let linewise = transpose(wrapped_panes);
    let merged_lines = map_collect(linewise, |lw| merge(lw, &delims));

    merged_lines
        .into_iter()
        .flat_map(|MergedLine(wl)| wl.wrapped_lines_in_line.into_iter())
        .collect()
}

fn wrap_pane(pane: &Pane) -> WrappedPane {
    let width = pane.width;
    let lines = pane.lines.iter().map(|line| wrap_at(line, width)).collect();
    WrappedPane { lines, width }
}

fn wrap_at(original: &str, width: usize) -> WrappedLine {
    let mut wrapped_lines_in_line = Vec::new();
    let mut current = String::new();
    let mut current_width = 0;

    for ch in original.chars() {
        let ch_width = ch.width().unwrap_or(0);
        if current_width + ch_width > width {
            wrapped_lines_in_line.push(current);
            current = ch.to_string();
            current_width = ch_width;
        } else {
            current.push(ch);
            current_width += ch_width;
        }
    }

    if !current.is_empty() {
        wrapped_lines_in_line.push(current);
    }

    WrappedLine {
        wrapped_lines_in_line,
        width,
    }
}

fn transpose(wrapped: Vec<WrappedPane>) -> Vec<LineWise> {
    let max_lines = wrapped
        .iter()
        .fold(0, |max, w| cmp::max(max, w.lines.len()));

    let mut linewises = Vec::new();
    for line_no in 0..max_lines {
        let extract_line = |w: &WrappedPane| {
            w.lines
                .get(line_no)
                .cloned()
                .unwrap_or_else(|| WrappedLine::new(w.width))
        };

        let lines_in_panes_in_line = map_collect(&wrapped, extract_line);
        linewises.push(LineWise {
            lines_in_panes_in_line,
        });
    }

    linewises
}

fn merge(
    LineWise {
        lines_in_panes_in_line,
    }: LineWise,
    delims: &[&str],
) -> MergedLine {
    let max_lines = lines_in_panes_in_line.iter().fold(0, |max, pane| {
        cmp::max(max, pane.wrapped_lines_in_line.len())
    });

    let wrapped_lines_in_line = map_collect(0..max_lines, |i| {
        let extract_line = |wl: &WrappedLine| {
            wl.wrapped_lines_in_line
                .get(i)
                .cloned()
                .map(|line| {
                    let width = line.width();
                    line + &" ".repeat(wl.width - width)
                })
                .unwrap_or_else(|| " ".repeat(wl.width))
        };

        lines_in_panes_in_line
            .iter()
            .map(extract_line)
            .interleave(delims.iter().map(|x| x.to_string()))
            .join("")
    });

    let width = lines_in_panes_in_line
        .iter()
        .map(|wl| wl.width)
        .chain(delims.iter().map(|delim| delim.width()))
        .sum();

    MergedLine(WrappedLine {
        wrapped_lines_in_line,
        width,
    })
}

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

    #[allow(non_snake_case)]
    fn S(s: &str) -> String {
        s.into()
    }

    #[test]
    fn wrap() {
        assert_eq!(
            wrap_at("abcdefghijklmnopqrstuvwxyz", 5),
            WrappedLine {
                wrapped_lines_in_line: vec![
                    S("abcde"),
                    S("fghij"),
                    S("klmno"),
                    S("pqrst"),
                    S("uvwxy"),
                    S("z")
                ],
                width: 5
            }
        );

        assert_eq!(
            wrap_at("あいうえおかきくけこ", 5),
            WrappedLine {
                wrapped_lines_in_line: vec![
                    S("あい"),
                    S("うえ"),
                    S("おか"),
                    S("きく"),
                    S("けこ")
                ],
                width: 5
            }
        );
    }

    #[test]
    fn display() {
        let lines = Pane {
            lines: &vec!["1", "2", "3", "4"],
            width: 3,
        };
        let pane1 = Pane { lines: &vec!["Lorem ipsum dolor sit amet, consectetur adipiscing elit,", "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."], width: 30};
        let pane2 = Pane { lines: &vec!["Lorem ipsum dolor sit amet, consectetur adipiscing elit,", "sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.", "Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur.", "とりあえずここに自然に日本語がまぎれてきてもたぶんいい感じに切ってくれるはずだよね"], width: 40};

        println!(
            "{}",
            splitv(&vec![lines, pane1, pane2], &vec![" | ", " | "]).join("\n")
        );
    }
}