~dancek/twinwiki

d0fb34fc6b41e84f0482e025f3d30d98a123f99d — Antti Keränen 4 years ago 899d6c3
Cleanup edit function

Use boxed iterators instead of Vecs. This should also reduce a few
memory allocations.
1 files changed, 9 insertions(+), 8 deletions(-)

M src/sed/edit.rs
M src/sed/edit.rs => src/sed/edit.rs +9 -8
@@ 20,7 20,7 @@ use super::parser::parse_substitute;
use super::types::{Address, Command, Substitute};

use itertools::Itertools;
use std::iter::repeat;
use std::iter::{empty, once, repeat};

fn regex_replace<'a, I>(lines: I, arg: &str) -> Result<String, String>
where


@@ 59,14 59,14 @@ pub fn edit(text: &str, cmd: Command) -> Result<String, String> {
    let repeating_arg = repeat(arg.as_ref()).take(count);

    let tmp;
    let edited = match command {
        'a' => editing_range.interleave_shortest(repeating_arg).collect(),
        'c' => vec![arg.as_ref()],
        'd' => vec![],
        'i' => repeating_arg.interleave_shortest(editing_range).collect(),
    let edited: Box<dyn Iterator<Item = &str>> = match command {
        'a' => Box::new(editing_range.interleave_shortest(repeating_arg)),
        'c' => Box::new(once(arg.as_ref())),
        'd' => Box::new(empty()),
        'i' => Box::new(repeating_arg.interleave_shortest(editing_range)),
        's' => {
            tmp = regex_replace(editing_range, &arg)?;
            vec![tmp.as_ref()]
            Box::new(once(tmp.as_ref()))
        }
        _ => return Err(format!("Sed command `{}` not implemented!", command)),
    };


@@ 76,5 76,6 @@ pub fn edit(text: &str, cmd: Command) -> Result<String, String> {
        .take(start)
        .chain(edited)
        .chain(text.split('\n').skip(start + count))
        .join("\n"))
        .intersperse("\n")
        .collect())
}