From 2bf495b127a40fd576a017aabb62898fb83e0a1e Mon Sep 17 00:00:00 2001 From: Jeff Baskin Date: Tue, 12 Nov 2024 10:26:21 -0500 Subject: [PATCH] Added a table field. --- src/data/id.rs | 11 +++++++++- src/data/mod.rs | 55 ++++++++++++++++++++++++++++++++++++++++++---- src/data/record.rs | 26 +++++++++++++++++++--- 3 files changed, 84 insertions(+), 8 deletions(-) diff --git a/src/data/id.rs b/src/data/id.rs index d98c3a0..160dfea 100644 --- a/src/data/id.rs +++ b/src/data/id.rs @@ -19,6 +19,10 @@ impl FieldRecord for ID { fn new_field() -> Field { Field::ID(ID::new()) } + + fn get_type() -> String { + "id".to_string() + } } impl fmt::Display for ID { @@ -40,10 +44,15 @@ mod fielddata { let id_string = id.to_string(); assert!(!ids.contains(&id_string), "'{}' repeated", id_string); ids.push(id_string); - }, + } } } } + + #[test] + fn get_type() { + assert_eq!(ID::get_type(), "id"); + } } #[cfg(test)] diff --git a/src/data/mod.rs b/src/data/mod.rs index 6a8279d..aa91b1d 100644 --- a/src/data/mod.rs +++ b/src/data/mod.rs @@ -1,11 +1,40 @@ -pub mod id; -pub mod record; +mod id; +mod record; -struct Table; +use crate::data::record::Record; +use std::collections::HashMap; + +struct FieldDef; + +impl FieldDef { + fn new() -> Self { + Self {} + } +} + +struct Table { + fields: HashMap, +} impl Table { fn new() -> Self { - Self {} + Self { + fields: HashMap::new(), + } + } + + fn len(&self) -> usize { + self.fields.len() + } + + fn add_field(&mut self, name: &str, field_type: &str) -> Result<(), String> { + match self.fields.get(name) { + Some(_) => Err("duplicate field name".to_string()), + None => { + self.fields.insert(name.to_string(), FieldDef::new()); + Ok(()) + }, + } } } @@ -16,5 +45,23 @@ mod table { #[test] fn new_table() { let tbl = Table::new(); + assert_eq!(tbl.len(), 0); + } + + #[test] + fn add_field() { + let mut tbl = Table::new(); + tbl.add_field("one", "id"); + assert_eq!(tbl.len(), 1); + } + + #[test] + fn error_on_duplicate_name() { + let mut tbl = Table::new(); + tbl.add_field("one", "id"); + match tbl.add_field("one", "id") { + Ok(_) => unreachable!(" Should not duplicates."), + Err(_) => {}, + } } } diff --git a/src/data/record.rs b/src/data/record.rs index 7a3ab1f..d1d2de0 100644 --- a/src/data/record.rs +++ b/src/data/record.rs @@ -6,11 +6,18 @@ pub enum Field { ID(ID), } -pub trait FieldRecord { - fn new_field() -> Field; +impl Field { + fn new(field_type: &str) -> Field { + ID::new_field() + } } -struct Record { +pub trait FieldRecord { + fn new_field() -> Field; + fn get_type() -> String; +} + +pub struct Record { data: HashMap, } @@ -39,6 +46,19 @@ impl fmt::Display for Field { } } +#[cfg(test)] +mod fields { + use super::*; + + #[test] + fn creaAte_new_id() { + match Field::new("id") { + Field::ID(_) => {} + _ => unreachable!("Fould should be an ID type."), + } + } +} + #[cfg(test)] mod records { use super::*;