-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBitmap.cs
More file actions
80 lines (63 loc) · 2.28 KB
/
Copy pathBitmap.cs
File metadata and controls
80 lines (63 loc) · 2.28 KB
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
using System;
using System.IO;
namespace NewProject
{
public class FileSystemBitmap
{
private readonly byte[] bitmap;
private readonly int totalBlocks;
public FileSystemBitmap(long totalBlocks)
{
this.totalBlocks = (int)totalBlocks;
int sizeInBytes = (int)Math.Ceiling(this.totalBlocks / 8.0);
bitmap = new byte[sizeInBytes];
}
public void LoadBitmap(FileStream fs, int blockSize)
{
fs.Seek(1L * blockSize, SeekOrigin.Begin);
fs.Read(bitmap, 0, bitmap.Length);
}
public bool IsOccupied(int blockIndex)
{
// извън диска -> третираме като "заето" (невалидно)
if (blockIndex < 0 || blockIndex >= totalBlocks) return true;
int byteIndex = blockIndex / 8;
int bitOffset = blockIndex % 8;
return (bitmap[byteIndex] & (1 << bitOffset)) != 0;
}
public void OccupyBlock(int blockIndex)
{
if (blockIndex < 0 || blockIndex >= totalBlocks) return;
int byteIndex = blockIndex / 8;
int bitOffset = blockIndex % 8;
bitmap[byteIndex] |= (byte)(1 << bitOffset);
}
public void FreeBlock(int blockIndex)
{
if (blockIndex < 0 || blockIndex >= totalBlocks) return;
int byteIndex = blockIndex / 8;
int bitOffset = blockIndex % 8;
bitmap[byteIndex] &= (byte)~(1 << bitOffset);
}
public void WriteBitmap(FileStream fs, int blockSize)
{
fs.Seek(1L * blockSize, SeekOrigin.Begin);
// изчистваме целия блок 1 (както ти беше)
byte[] empty = new byte[blockSize];
fs.Write(empty, 0, empty.Length);
fs.Seek(1L * blockSize, SeekOrigin.Begin);
fs.Write(bitmap, 0, bitmap.Length);
fs.Flush();
}
public int FindFirstFreeBlock()
{
// ТЪРСИМ САМО в [0..totalBlocks-1]
for (int block = 0; block < totalBlocks; block++)
{
if (!IsOccupied(block))
return block;
}
return -1;
}
}
}