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
use nu_engine::CallExt;
use nu_protocol::ast::Call;
use nu_protocol::engine::{Command, EngineState, Stack};
use nu_protocol::{
Category, Example, IntoInterruptiblePipelineData, PipelineData, Signature, Span, Spanned,
SyntaxShape, Value,
};
#[derive(Clone)]
pub struct Group;
impl Command for Group {
fn name(&self) -> &str {
"group"
}
fn signature(&self) -> Signature {
Signature::build("group")
.required("group_size", SyntaxShape::Int, "the size of each group")
.category(Category::Filters)
}
fn usage(&self) -> &str {
"Groups input into groups of `group_size`."
}
fn examples(&self) -> Vec<Example> {
let stream_test_1 = vec![
Value::List {
vals: vec![
Value::Int {
val: 1,
span: Span::test_data(),
},
Value::Int {
val: 2,
span: Span::test_data(),
},
],
span: Span::test_data(),
},
Value::List {
vals: vec![
Value::Int {
val: 3,
span: Span::test_data(),
},
Value::Int {
val: 4,
span: Span::test_data(),
},
],
span: Span::test_data(),
},
];
vec![Example {
example: "echo [1 2 3 4] | group 2",
description: "Group the a list by pairs",
result: Some(Value::List {
vals: stream_test_1,
span: Span::test_data(),
}),
}]
}
fn run(
&self,
engine_state: &EngineState,
stack: &mut Stack,
call: &Call,
input: PipelineData,
) -> Result<nu_protocol::PipelineData, nu_protocol::ShellError> {
let group_size: Spanned<usize> = call.req(engine_state, stack, 0)?;
let ctrlc = engine_state.ctrlc.clone();
let metadata = input.metadata();
let each_group_iterator = EachGroupIterator {
group_size: group_size.item,
input: Box::new(input.into_iter()),
span: call.head,
};
Ok(each_group_iterator
.into_pipeline_data(ctrlc)
.set_metadata(metadata))
}
}
struct EachGroupIterator {
group_size: usize,
input: Box<dyn Iterator<Item = Value> + Send>,
span: Span,
}
impl Iterator for EachGroupIterator {
type Item = Value;
fn next(&mut self) -> Option<Self::Item> {
let mut group = vec![];
let mut current_count = 0;
loop {
let item = self.input.next();
match item {
Some(v) => {
group.push(v);
current_count += 1;
if current_count >= self.group_size {
break;
}
}
None => break,
}
}
if group.is_empty() {
return None;
}
Some(Value::List {
vals: group,
span: self.span,
})
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_examples() {
use crate::test_examples;
test_examples(Group {})
}
}