DEWQ/bit_utils/bitmap.rs
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 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320
/// A bitmap representation for storing and manipulating bit-level data
///
/// # Structure
///
/// The `BitMap` stores a 2D grid of bits as a vector of bytes, optimized for space efficiency
///
/// # Methods
///
/// Provides methods to:
/// - Create a new bitmap
/// - Set and get individual bits
/// - Invert bits
/// - Get bitmap size
/// - Save bitmap to a file
///
/// # Example
///
/// ```rust
/// let mut bitmap = BitMap::new(10);
/// bitmap.set(5, 7, 1);
/// assert_eq!(bitmap.get(5, 7), Bit::One);
/// ```
use super::bit::Bit;
use std::fmt::Display;
use std::fs::File;
use std::io::Write;
// Helper functions
fn get_byte_location(j: usize) -> (usize, usize) {
(j / 8, j % 8)
}
// bitmaps can only be square in size
pub struct BitMap {
/// Internal storage of bits using byte arrays
map: Vec<Vec<u8>>,
/// Size of the bitmap (width and height)
size: usize,
}
impl BitMap {
/// Creates a new bitmap with specified size
///
/// # Arguments
///
/// * `size` - The width and height of the bitmap (must be square)
///
/// # Returns
///
/// A new `BitMap` initialized with zeros
pub fn new(size: usize) -> Self {
Self {
map: vec![vec![0u8; (size / 8) + 1]; size],
size,
}
}
/// Sets a specific bit in the bitmap
///
/// # Arguments
///
/// * `i` - Row index
/// * `j` - Column index
/// * `bit` - Bit value to set (can be `Bit::One` or `Bit::Zero`)
pub fn set<B>(&mut self, i: usize, j: usize, bit: B)
where
B: Into<Bit>,
{
if i >= self.size || j >= self.size {
return;
}
let row = &mut self.map[i];
let (byte, byte_offset) = get_byte_location(j);
match bit.into() {
Bit::One => row[byte] |= 1 << byte_offset,
Bit::Zero => row[byte] &= !(1 << byte_offset),
}
}
/// Inverts the bit at the specified location
///
/// # Arguments
///
/// * `i` - Row index
/// * `j` - Column index
pub fn invert_bit(&mut self, i: usize, j: usize) {
let row = &mut self.map[i];
let (byte, byte_offset) = get_byte_location(j);
row[byte] ^= 1 << byte_offset;
}
/// Retrieves the bit value at a specific location
///
/// # Arguments
///
/// * `i` - Row index
/// * `j` - Column index
///
/// # Returns
///
/// The `Bit` value at the specified location
pub fn get(&self, i: usize, j: usize) -> Bit {
let row = &self.map[i];
let (byte, byte_offset) = get_byte_location(j);
(row[byte] & (1 << byte_offset)).into()
}
/// Returns the size of the bitmap
///
/// # Returns
///
/// The width/height of the bitmap
pub fn size(&self) -> usize {
self.size
}
/// Saves the bitmap to a file in BMP format
///
/// # Arguments
///
/// * `path` - File path to save the bitmap
///
/// # Remarks
///
/// Creates a 1bpp bitmap image with a black and white color palette
pub fn save_to_file<P>(&self, path: P)
where
P: AsRef<std::path::Path>,
{
if let Ok(mut file) = File::create(path) {
// Write the bmp header 14 bytes
// header field
_ = file.write(&[0x42, 0x4D]); // ASCII BM
// Size of the bmp file in bytes
let file_size = (62 + (self.size() * self.size())) as u32;
// let file_size = (62 + 100) as u32;
_ = file.write(&[
file_size as u8,
(file_size >> 8) as u8,
(file_size >> 16) as u8,
(file_size >> 24) as u8,
]);
// reserved bytes
_ = file.write(&[0, 0, 0, 0]);
// Offset of the pixel array
_ = file.write(&[62, 0, 0, 0]);
// BITMAPINFOHEADER --------
// Size of this header (40 bytes)
_ = file.write(&[40, 0, 0, 0]);
// Bitmap width in pixels
// _ = file.write(&[10, 0, 0, 0]);
// _ = file.write(&[10, 0, 0, 0]);
_ = file.write(&[
self.size() as u8,
(self.size() >> 8) as u8,
(self.size() >> 16) as u8,
(self.size() >> 24) as u8,
]);
// Bitmap height in pixels
_ = file.write(&[
self.size() as u8,
(self.size() >> 8) as u8,
(self.size() >> 16) as u8,
(self.size() >> 24) as u8,
]);
// Number of color planes (must be 1)
_ = file.write(&[1, 0]);
// Number of bits per pixel (1 in our case)
_ = file.write(&[1, 0]);
// Compression method being used (no compression)
_ = file.write(&[0, 0, 0, 0]);
// Image size (can be ignored)
_ = file.write(&[0, 0, 0, 0]);
// Horizontal resolution of the bitmap
_ = file.write(&[255, 255, 255, 255]);
// Vertical resolution of the bitmap
_ = file.write(&[255, 255, 255, 255]);
// Number of colors in the palette
_ = file.write(&[2, 0, 0, 0]);
// Number of important colors in the palette
_ = file.write(&[0, 0, 0, 0]);
// Color Palette
// White
_ = file.write(&[255, 255, 255, 0]);
// Black
_ = file.write(&[0, 0, 0, 0]);
// Write the bits to the bitmap
let mut bit_index = 0;
let mut current_byte = 0;
for i in (0..self.size()).rev() {
for j in 0..self.size() {
match self.get(i, j) {
Bit::Zero => {}
Bit::One => {
current_byte |= 1 << (31 - bit_index);
}
}
bit_index += 1;
if bit_index == 32 {
_ = file.write(&[
(current_byte >> 24) as u8,
(current_byte >> 16) as u8,
(current_byte >> 8) as u8,
current_byte as u8,
]);
current_byte = 0;
bit_index = 0;
}
}
if bit_index != 0 {
_ = file.write(&[
(current_byte >> 24) as u8,
(current_byte >> 16) as u8,
(current_byte >> 8) as u8,
current_byte as u8,
]);
}
current_byte = 0;
bit_index = 0;
}
}
}
}
/// Implements a text-based display of the bitmap
///
/// Renders the bitmap using block characters, where:
/// - `██` represents a black/set bit
/// - ` ` represents a white/unset bit
impl Display for BitMap {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
for _ in 0..=self.size + 2 {
write!(f, "██")?;
}
writeln!(f, "██")?;
for _ in 0..=self.size + 2 {
write!(f, "██")?;
}
writeln!(f, "██")?;
for i in 0..self.size {
write!(f, "██")?;
write!(f, "██")?;
for j in 0..self.size {
match self.get(i, j) {
Bit::Zero => {
write!(f, "██")?;
}
Bit::One => {
write!(f, " ")?;
}
}
}
write!(f, "██")?;
writeln!(f, "██")?;
}
for _ in 0..=self.size + 2 {
write!(f, "██")?;
}
writeln!(f, "██")?;
for _ in 0..=self.size + 2 {
write!(f, "██")?;
}
writeln!(f, "██")?;
Ok(())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_bitmap_basics() {
let mut bit_map = BitMap::new(10);
bit_map.set(5, 7, 1);
assert_eq!(bit_map.get(5, 7), Bit::One);
}
#[test]
fn test_bitmap_sizing() {
let bit_map = BitMap::new(10);
assert_eq!(bit_map.map.len(), 10);
assert_eq!(bit_map.map[0].len(), 2);
}
}