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
|
//-----------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//-----------------------------------------------------------------------------
namespace System.Runtime.Serialization
{
using System;
using System.Reflection;
#if !NO_DYNAMIC_CODEGEN
using System.Reflection.Emit;
#endif
using System.Security;
[Fx.Tag.SecurityNote(Miscellaneous = "RequiresReview (Critical) - works on CodeGenerator objects, which require Critical access.")]
class BitFlagsGenerator
{
#if !NO_DYNAMIC_CODEGEN
int bitCount;
CodeGenerator ilg;
LocalBuilder[] locals;
public BitFlagsGenerator(int bitCount, CodeGenerator ilg, string localName)
{
this.ilg = ilg;
this.bitCount = bitCount;
int localCount = (bitCount + 7) / 8;
locals = new LocalBuilder[localCount];
for (int i = 0; i < locals.Length; i++)
{
locals[i] = ilg.DeclareLocal(typeof(byte), localName + i, (byte) 0);
}
}
#endif
public static bool IsBitSet(byte[] bytes, int bitIndex)
{
int byteIndex = GetByteIndex(bitIndex);
byte bitValue = GetBitValue(bitIndex);
return (bytes[byteIndex] & bitValue) == bitValue;
}
public static void SetBit(byte[] bytes, int bitIndex)
{
int byteIndex = GetByteIndex(bitIndex);
byte bitValue = GetBitValue(bitIndex);
bytes[byteIndex] |= bitValue;
}
#if !NO_DYNAMIC_CODEGEN
public int GetBitCount()
{
return bitCount;
}
public LocalBuilder GetLocal(int i)
{
return locals[i];
}
public int GetLocalCount()
{
return locals.Length;
}
public void Load(int bitIndex)
{
LocalBuilder local = locals[GetByteIndex(bitIndex)];
byte bitValue = GetBitValue(bitIndex);
ilg.Load(local);
ilg.Load(bitValue);
ilg.And();
ilg.Load(bitValue);
ilg.Ceq();
}
public void LoadArray()
{
LocalBuilder localArray = ilg.DeclareLocal(Globals.TypeOfByteArray, "localArray");
ilg.NewArray(typeof(byte), locals.Length);
ilg.Store(localArray);
for (int i = 0; i < locals.Length; i++)
{
ilg.StoreArrayElement(localArray, i, locals[i]);
}
ilg.Load(localArray);
}
public void Store(int bitIndex, bool value)
{
LocalBuilder local = locals[GetByteIndex(bitIndex)];
byte bitValue = GetBitValue(bitIndex);
if (value)
{
ilg.Load(local);
ilg.Load(bitValue);
ilg.Or();
ilg.Stloc(local);
}
else
{
ilg.Load(local);
ilg.Load(bitValue);
ilg.Not();
ilg.And();
ilg.Stloc(local);
}
}
#endif
static byte GetBitValue(int bitIndex)
{
return (byte)(1 << (bitIndex & 7));
}
static int GetByteIndex(int bitIndex)
{
return bitIndex >> 3;
}
}
}
|