www.pudn.com > sudoku.rar > FastBitArray.cs


//-------------------------------------------------------------------------- 
//  
//  Copyright (c) Microsoft Corporation.  All rights reserved.  
//  
//  File: FastBitArray.cs 
// 
//  Description: A simple bit bucket class. 
//  
//-------------------------------------------------------------------------- 
 
using System; 
using System.Collections; 
using System.Security.Permissions; 
 
namespace Microsoft.Sudoku.Collections 
{ 
	/// A simple bit bucket. 
	[Serializable]  
	internal sealed class FastBitArray  
	{ 
		/// Maximum length of the array == sizeof(Int32)*8 
		const int MAX_LENGTH = 32; 
		/// The bits. 
		private uint _bits; 
		/// The length, less than or equal to MAX_LENGTH. 
		private int _length; 
		/// The number of set bits in the array. 
		private int _countSet; 
 
		/// Initializes the array. 
		/// The length of the array, which must be less than or equal to MAX_LENGTH 
		public FastBitArray(int length) : this(length, false) {} 
 
		/// Initializes the array. 
		/// The length of the array, which must be less than or equal to MAX_LENGTH 
		/// The initial value of each element in the array. 
		public FastBitArray(int length, bool defaultValue)  
		{ 
			_length = length; 
			SetAll(defaultValue); 
		} 
 
		/// Gets or sets the value at the specified index. 
		public bool this[int index]  
		{ 
			get { return Get(index); } 
			set { Set(index,value); } 
		} 
     
		/// Gets the value at the specified index. 
		/// The index at which to retrieve the value. 
		/// The value at the specified index. 
		public bool Get(int index)  
		{ 
			return (_bits & (1u << index)) != 0; 
		} 
     
		/// Sets the value at the specified index. 
		/// The index at which to set the value. 
		/// The value to set. 
		public void Set(int index, bool value)  
		{ 
			bool curVal = Get(index); 
			if (value && !curVal)  
			{ 
				_bits |= (1u << index); 
				_countSet++; 
			} 
			else if (!value && curVal) 
			{ 
				_bits &= ~(1u << index); 
				_countSet--; 
			} 
		} 
     
		/// Sets all elements in the array to the specified value. 
		/// The value to set. 
		public void SetAll(bool value)  
		{ 
			if (value) 
			{ 
				_bits = 0xFFFFFFFF; 
				_countSet = _length; 
			} 
			else 
			{ 
				_bits = 0; 
				_countSet = 0; 
			} 
		} 
     
		/// Gets the length of the array. 
		public int Length { get { return _length; } } 
 
		/// Gets the number of bits set in the array. 
		public int CountSet { get { return _countSet; } } 
 
		/// Gets an array of the values set in the bit array. 
		/// An array of the values set. 
		public int [] GetSetBits() 
		{ 
			int count = this.CountSet; 
			int [] bits = new int[count]; 
			int pos = 0; 
			for(int i=0; i