1 /* Copyright (C) 2004 - 2009  Versant Inc.  http://www.db4o.com */
2 
3 using Sharpen;
4 
5 namespace Db4objects.Db4o.Foundation
6 {
7 	/// <exclude></exclude>
8 	public sealed class BitMap4
9 	{
10 		private readonly byte[] _bits;
11 
BitMap4(int numBits)12 		public BitMap4(int numBits)
13 		{
14 			_bits = new byte[ByteCount(numBits)];
15 		}
16 
17 		/// <summary>"readFrom  buffer" constructor</summary>
BitMap4(byte[] buffer, int pos, int numBits)18 		public BitMap4(byte[] buffer, int pos, int numBits) : this(numBits)
19 		{
20 			System.Array.Copy(buffer, pos, _bits, 0, _bits.Length);
21 		}
22 
BitMap4(byte singleByte)23 		public BitMap4(byte singleByte)
24 		{
25 			_bits = new byte[] { singleByte };
26 		}
27 
IsTrue(int bit)28 		public bool IsTrue(int bit)
29 		{
30 			return (((_bits[ArrayOffset(bit)]) >> (ByteOffset(bit) & 0x1f)) & 1) != 0;
31 		}
32 
IsFalse(int bit)33 		public bool IsFalse(int bit)
34 		{
35 			return !IsTrue(bit);
36 		}
37 
MarshalledLength()38 		public int MarshalledLength()
39 		{
40 			return _bits.Length;
41 		}
42 
SetFalse(int bit)43 		public void SetFalse(int bit)
44 		{
45 			_bits[ArrayOffset(bit)] &= (byte)~BitMask(bit);
46 		}
47 
Set(int bit, bool val)48 		public void Set(int bit, bool val)
49 		{
50 			if (val)
51 			{
52 				SetTrue(bit);
53 			}
54 			else
55 			{
56 				SetFalse(bit);
57 			}
58 		}
59 
SetTrue(int bit)60 		public void SetTrue(int bit)
61 		{
62 			_bits[ArrayOffset(bit)] |= BitMask(bit);
63 		}
64 
WriteTo(byte[] bytes, int pos)65 		public void WriteTo(byte[] bytes, int pos)
66 		{
67 			System.Array.Copy(_bits, 0, bytes, pos, _bits.Length);
68 		}
69 
ByteOffset(int bit)70 		private byte ByteOffset(int bit)
71 		{
72 			return (byte)(bit % 8);
73 		}
74 
ArrayOffset(int bit)75 		private int ArrayOffset(int bit)
76 		{
77 			return bit / 8;
78 		}
79 
BitMask(int bit)80 		private byte BitMask(int bit)
81 		{
82 			return (byte)(1 << ByteOffset(bit));
83 		}
84 
ByteCount(int numBits)85 		private int ByteCount(int numBits)
86 		{
87 			return (numBits + 7) / 8;
88 		}
89 
GetByte(int index)90 		public byte GetByte(int index)
91 		{
92 			return _bits[index];
93 		}
94 
Bytes()95 		public byte[] Bytes()
96 		{
97 			return _bits;
98 		}
99 	}
100 }
101