From 9020618a0ed55f8219a6d01a71aa8fe7340f71ee Mon Sep 17 00:00:00 2001 From: Tobie Morgan Hitchcock Date: Mon, 30 May 2022 16:05:05 +0100 Subject: [PATCH] Add IntoIterator trait to SQL Model type --- lib/src/sql/model.rs | 48 ++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/lib/src/sql/model.rs b/lib/src/sql/model.rs index 932ab241..b648b0bc 100644 --- a/lib/src/sql/model.rs +++ b/lib/src/sql/model.rs @@ -1,18 +1,66 @@ use crate::sql::common::take_u64; use crate::sql::error::IResult; use crate::sql::escape::escape_ident; +use crate::sql::id::Id; use crate::sql::ident::ident_raw; +use crate::sql::thing::Thing; use nom::branch::alt; use nom::character::complete::char; use serde::{Deserialize, Serialize}; use std::fmt; +pub struct IntoIter { + model: Model, + index: u64, +} + +impl Iterator for IntoIter { + type Item = Thing; + fn next(&mut self) -> Option { + match &self.model { + Model::Count(tb, c) => { + if self.index < *c { + self.index += 1; + Some(Thing { + tb: tb.to_string(), + id: Id::rand(), + }) + } else { + None + } + } + Model::Range(tb, b, e) => { + if self.index + b <= *e { + self.index += 1; + Some(Thing { + tb: tb.to_string(), + id: Id::from(self.index), + }) + } else { + None + } + } + } + } +} + #[derive(Clone, Debug, Eq, PartialEq, PartialOrd, Serialize, Deserialize)] pub enum Model { Count(String, u64), Range(String, u64, u64), } +impl IntoIterator for Model { + type Item = Thing; + type IntoIter = IntoIter; + fn into_iter(self) -> Self::IntoIter { + IntoIter { + model: self, + index: 0, + } + } +} + impl fmt::Display for Model { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { match self {