Skip to content

Instantly share code, notes, and snippets.

@erickt
Created December 13, 2015 00:51
Show Gist options
  • Save erickt/720028faa36e0218ecbc to your computer and use it in GitHub Desktop.
Save erickt/720028faa36e0218ecbc to your computer and use it in GitHub Desktop.
#![feature(prelude_import)]
#![no_std]
#![feature(plugin)]
#![plugin(stateful)]
#[prelude_import]
use std::prelude::v1::*;
#[macro_use]
extern crate std as std;
fn yield_() -> ::std::boxed::Box<::std::iter::Iterator<Item = usize>> {
struct Wrapper<S, F> {
state: S,
next: F,
}
impl<S, T, F> Wrapper<S, F> where F: Fn(S) -> (Option<T>, S)
{
fn new(initial_state: S, next: F) -> Self {
Wrapper {
state: initial_state,
next: next,
}
}
}
impl<S, T, F> Iterator for Wrapper<S, F>
where S: Default,
F: Fn(S) -> (Option<T>, S)
{
type
Item
=
T;
fn next(&mut self) -> Option<Self::Item> {
let old_state = ::std::mem::replace(&mut self.state, S::default());
let (value, next_state) = (self.next)(old_state);
self.state = next_state;
value
}
}
enum State<T0, T1, T2, T3, T4, T5> {
State0,
State2,
State3(T0),
State4(T1, T2),
State5(T3, T4, T5),
State1,
}
impl<T0, T1, T2, T3, T4, T5> Default for State<T0, T1, T2, T3, T4, T5> {
fn default() -> Self {
State::State1
}
}
Box::new(Wrapper::new(State::State0, |mut state| {
loop {
match state {
State::State0 => {
state = State::State2;
continue;
}
State::State2 => {
let x = 0;
return (::std::option::Option::Some(x), State::State3(x));
}
State::State3(x) => {
let y = 1;
return (::std::option::Option::Some(x + y), State::State4(x, y));
}
State::State4(x, y) => {
let z = 2;
return (::std::option::Option::Some(x + y + z),
State::State5(x, y, z));
}
State::State5(x, y, z) => {
state = State::State1;
continue;
}
State::State1 => {
return (::std::option::Option::None, State::State1);
}
}
}
}))
}
fn main() {
for value in yield_() {
::std::io::_print(::std::fmt::Arguments::new_v1({
static __STATIC_FMTSTR:
&'static [&'static str]
=
&["yield_: ",
"\n"];
__STATIC_FMTSTR
},
&match (&value,) {
(__arg0,) =>
[::std::fmt::ArgumentV1::new(__arg0,
::std::fmt::Debug::fmt)],
}));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment