Compare commits

...

4 Commits

Author SHA1 Message Date
Rhinemann c730e0d1bd Rusty implementation. 2023-06-26 00:24:45 +03:00
Rhinemann e80304f84d Delete 'main.py' 2023-06-26 00:15:11 +03:00
Rhinemann 65750694e4 Delete 'bitutilities.py' 2023-06-26 00:15:07 +03:00
Rhinemann 0dc2bd3950 Delete 'README.md' 2023-06-26 00:15:01 +03:00
6 changed files with 161 additions and 71 deletions

16
Cargo.toml Normal file
View File

@ -0,0 +1,16 @@
[package]
name = "rust_tests"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[profile.release]
opt-level = 'z' # Optimize for size
lto = true # Enable link-time optimization
codegen-units = 1 # Reduce number of codegen units to increase optimizations
panic = 'abort' # Abort on panic
strip = true # Strip symbols from binary*
[dependencies]
text_io = "0.1.12"

View File

@ -1,3 +0,0 @@
# binaryCalculatorPrototype
This is a Python language prototype for a binary calculator to be used in Computer Arithmetics lab works for first-year students studying Computer Engineering at KPI.

View File

@ -1,46 +0,0 @@
from collections import deque
class BasicRegister:
"""The BasicRegister represents a hardware register capable of manipulating multiple bits at a time.
:param deque[bool] memory: The bits stored inside the register.
"""
def __init__(self, memory: list[bool]):
"""Constructor method"""
self.memory: deque[bool] = deque(memory)
def __str__(self) -> str:
return f"Memory: {[int(value) for value in self.memory]}"
def reverse(self):
self.memory = deque([not value for value in self.memory])
def left_shift(self, digit_to_fill: bool = False, steps_shifted: int = 1) -> deque[bool]:
self.memory.extend([digit_to_fill] * steps_shifted)
shifted_radices: deque[bool] = deque([self.memory.popleft() for _i in range(steps_shifted)])
return shifted_radices
def right_shift(self, digit_to_fill: bool = False, steps_shifted: int = 1) -> deque[bool]:
self.memory.extendleft([digit_to_fill] * steps_shifted)
shifted_radices: deque[bool] = deque([self.memory.pop() for _i in range(steps_shifted)])
return shifted_radices
def get_memory(variable_name: str) -> list[bool]:
"""
Reads user input to be used as a memory array.
:param str variable_name: The name to be displayed in the input line.
:return: A list of boolean values read from user.
:rtype: list[bool]
"""
while True:
input_chars: list[str] = list(input(f"Enter {variable_name}: "))
if all(character in ["0", "1"] for character in input_chars):
return [True if character == "1" else False for character in input_chars]
else:
print(f"[ERROR] The {variable_name} may contain only 1-s and 0-s!")

22
main.py
View File

@ -1,22 +0,0 @@
from bitutilities import *
import timeit
if __name__ == '__main__':
reg: BasicRegister = BasicRegister(get_memory("memory"))
# print(type(reg))
print("\nRegister:")
print(reg)
print("\nReversed:")
reg.reverse()
print(reg)
print("\nShifted left:")
print([int(value) for value in reg.left_shift()])
print(reg)
print("\nShifted right:")
print([int(value) for value in reg.right_shift()])
print(reg)

101
src/bit_utilities.rs Normal file
View File

@ -0,0 +1,101 @@
use std::fmt;
use std::fmt::Formatter;
fn capitalise(s: &str) -> String {
let mut c = s.chars();
match c.next() {
None => String::new(),
Some(f) => f.to_uppercase().collect::<String>() + c.as_str(),
}
}
/// A basic register capable of storing binary data.
#[derive(Debug)]
pub struct BasicRegister {
/// A [Vec] that stores the binary data of the register.
memory: Vec<bool>,
}
impl BasicRegister {
pub fn l_shift(&mut self) {
let mut res: Vec<bool> = vec![false; self.memory.len()];
res[..(self.memory.len() - 1)]
.copy_from_slice(&self.memory[1..((self.memory.len() - 1) + 1)]);
self.memory = res;
}
pub fn r_shift(&mut self) {
let mut res: Vec<bool> = vec![false; self.memory.len()];
for i in (1..self.memory.len()).rev() {
res[i] = self.memory[i - 1];
}
self.memory = res;
}
pub fn reverse(&mut self) {
self.memory = self.memory.iter().map(|val| !val).collect();
}
pub fn new(memory: Vec<bool>) -> Self {
Self { memory }
}
}
impl Default for BasicRegister {
fn default() -> Self {
Self {
memory: vec![false],
}
}
}
impl fmt::Display for BasicRegister {
fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result {
write!(f, "Memory: [")?;
for (count, v) in self.memory.iter().enumerate() {
if count != 0 {
write!(f, ", ")?;
}
write!(f, "{}", *v as u8)?;
}
write!(f, "]")
}
}
fn read_vec(variable_name: &str) -> Vec<char> {
loop {
print!("Enter {variable_name}: ");
let input: String = text_io::read!("{}\n");
match input.chars().all(|c| c == '1' || c == '0') {
true => return input.chars().collect(),
false => eprintln!(
"[ERROR] {} may contain only 1-s and 0-s with no whitespaces!",
capitalise(variable_name)
),
}
}
}
pub fn char_to_bool_vector(char_vector: Vec<char>) -> Vec<bool> {
let mut bool_vector: Vec<bool> = Vec::new();
for value in char_vector.iter() {
match value {
'0' => bool_vector.push(false),
'1' => bool_vector.push(true),
_ => (),
}
}
bool_vector
}
pub fn get_memory(variable_name: &str) -> Vec<bool> {
char_to_bool_vector(read_vec(variable_name))
}

44
src/main.rs Normal file
View File

@ -0,0 +1,44 @@
#[allow(dead_code)]
mod bit_utilities;
use bit_utilities::*;
// use text_io::read;
fn main() {
let mut reg = BasicRegister::new(get_memory("your number"));
// let mut reg: BasicRegister = Default::default();
println!("\nRegister:");
println!("{}", reg);
println!("\nShifted right:");
reg.r_shift();
println!("{}", reg);
println!("\nShifted left:");
reg.l_shift();
println!("{}", reg);
println!("\nReversed:");
reg.reverse();
println!("{}", reg);
// println!("{}", true);
// println!("{}", true);
// let a: i8 = read!();
// println!("{} {0:b}", a);
// println!("{} {0:b}", a >> 1);
// println!("{} {0:b}", a << 1);
// println!("{} {0:b}", !a);
// println!("{}", '3'.to_digit(2).unwrap());
// let f_text = format!("{a:b}").chars().collect::<Vec<char>>();
// println!("{:?}", f_text);
// println!("{:?}", char_to_bool_vector(f_text.clone()));
// let b: BasicRegister = BasicRegister::new(char_to_bool_vector(f_text));
// b.print_register();
// println!("{:?}", get_memory(format!("{a:b}")));
// println!("{:?}", a.split(" ").collect::<Vec<&str>>());
// a = text_io::read!("{}\n");
// println!("{a}")
}